问:
OpenMP for nested for loops?
I am attempting to use OpenMP in my project that contains N agents in a simulation. Every agent has a position vector. Inside my program, I do something like the following:

```<code>for(int i=0;i<agents.size();i++){
 for(int j=0;j<agents.size();j++){
   if(i==j) continue;
   if(distance_between(i,j)<10){
     //do a lot of calculations for interaction between i and j,
     //and a bunch of changes to variables of the Agents stored in the list
   }
 }
}
</code>```

Am I able to simply prepend "#pragma omp parallel for" in front of the first loop to distribute the work? If I do it, my program runs much faster, but I am concerned that the calculations it is doing may not be accurate.

The order of these calculations does not matter, as long as every i,j pair is processed, and no variable outside of the variables defined inside the innermost loop, and the variables in my Agents class are ever changed (only read).

Not being a systems guy I have trouble understanding inner workings of OpenMP, and have become slightly suspicious of it. Thanks for any help with this!

答:
Make sure interactions i,j and j,i which affect the same data don't cause data races. You can do so carefully tuning the distribution of the work or by using omp critical or omp atomic constructs where necessary.

Apart from that, there is no problem at all on making your code run faster by just using omp parallel for constructs on the outer loop. Bear in mind that if the amount of processing units (cores, hwthreads, etc.) your processor has, or if you are using a ccNUMA machine, it might be a nice idea to do some additional things, as the scalability of your code will not be as good as it could.

The easiest improvement is to add collapse(2) to your omp for clause. This will tell OpenMP that you want to distribute iterations of both of those loops altogether.

```<code>#pragma omp parallel for collapse(2)
for(int i=0;i<agents.size();i++){
 for(int j=0;j<agents.size();j++){
   if(i==j) continue;
   if(distance_between(i,j)<10){
     //do a lot of calculations for interaction between i and j,
     //and a bunch of changes to variables of the Agents stored in the list
   }
  }
}
</code>```

Once you reach huge amounts of particles (or agents as you call them), it might be wise to sort all of them according to their position. This will cause your if condition inside the innermost loop to have a much more stable behavior, thus allowing a better prediction of the branches (see why is it faster to process a sorted array).

In addition, you can delete the branch completely if you divide the geometric space in bins. This is because you exactly know that non-adjacent buckets are too far for the condition to become successful.

This kind of problems is very well known and, as you might already know, they are called n-body problems. The bucket optimization version is called Barnes-Hut simulation, although you might find other approaches working much faster (although more difficult to parallelize, still are more efficient most of the time) such as the Fast Multipole Method, which consists more or less in reducing the number of computations by solving both interactions i,j and j,i in the same step.

Title: OpenMP for nested for loops?

Body:
I am attempting to use OpenMP in my project that contains N agents in a simulation. Every agent has a position vector. Inside my program, I do something like the following:

for(int i=0;i<agents.size();i++){
 for(int j=0;j<agents.size();j++){
   if(i==j) continue;
   if(distance_between(i,j)<10){
     //do a lot of calculations for interaction between i and j,
     //and a bunch of changes to variables of the Agents stored in the list
   }
 }
}

Am I able to simply prepend "#pragma omp parallel for" in front of the first loop to distribute the work? If I do it, my program runs much faster, but I am concerned that the calculations it is doing may not be accurate.

The order of these calculations does not matter, as long as every i,j pair is processed, and no variable outside of the variables defined inside the innermost loop, and the variables in my Agents class are ever changed (only read).

Not being a systems guy I have trouble understanding inner workings of OpenMP, and have become slightly suspicious of it. Thanks for any help with this!

Body:
Make sure interactions i,j and j,i which affect the same data don't cause data races. You can do so carefully tuning the distribution of the work or by using omp critical or omp atomic constructs where necessary.

Apart from that, there is no problem at all on making your code run faster by just using omp parallel for constructs on the outer loop. Bear in mind that if the amount of processing units (cores, hwthreads, etc.) your processor has, or if you are using a ccNUMA machine, it might be a nice idea to do some additional things, as the scalability of your code will not be as good as it could.

The easiest improvement is to add collapse(2) to your omp for clause. This will tell OpenMP that you want to distribute iterations of both of those loops altogether.

#pragma omp parallel for collapse(2)
for(int i=0;i<agents.size();i++){
 for(int j=0;j<agents.size();j++){
   if(i==j) continue;
   if(distance_between(i,j)<10){
     //do a lot of calculations for interaction between i and j,
     //and a bunch of changes to variables of the Agents stored in the list
   }
  }
}

Once you reach huge amounts of particles (or agents as you call them), it might be wise to sort all of them according to their position. This will cause your if condition inside the innermost loop to have a much more stable behavior, thus allowing a better prediction of the branches (see why is it faster to process a sorted array).

In addition, you can delete the branch completely if you divide the geometric space in bins. This is because you exactly know that non-adjacent buckets are too far for the condition to become successful.

This kind of problems is very well known and, as you might already know, they are called n-body problems. The bucket optimization version is called Barnes-Hut simulation, although you might find other approaches working much faster (although more difficult to parallelize, still are more efficient most of the time) such as the Fast Multipole Method, which consists more or less in reducing the number of computations by solving both interactions i,j and j,i in the same step.


来源: stackexchange

问:
How do I get the query builder to output its raw SQL query as a string?
Given the following code:

DB::table('users')->get();
```

I want to get the raw SQL query string that the database query builder above will generate. In this example, it would be SELECT * FROM users.

How do I do this?

答:
Here is the solution I use:

```<code>DB::listen(function ($sql, $bindings, $time) {
    $bound = preg_replace_callback("/\?/", function($matches) use ($bindings) {
        static $localBindings;
        if (!isset($localBindings)) {
            $localBindings = $bindings;
        }
        $val = array_shift($localBindings);

        switch (gettype($val)) {
            case "boolean":
                $val = ($val === TRUE) ? 1 : 0;  // mysql doesn't support BOOL data types, ints are widely used
                // $val = ($val === TRUE) ? "'t'" : "'f'";   // todo: use this line instead of the above for postgres and others
                break;

            case "NULL":
                $val = "NULL";
                break;

            case "string":
            case "object":
                $val = "'". addslashes($val). "'";   // correct escaping would depend on the RDBMS
                break;
        }
        return $val;
    }, $sql);
    array_map(function($x) {
        (new \Illuminate\Support\Debug\Dumper)->dump($x);
    }, [$sql, $bindings, $bound]);
});
</code>```

Please, read the comments in the code. I know, it is not perfect but for my everyday debugging it is OK. It tries to build the bound query with more-or-less reliability. However, don't trust it completely, the database engines escape the values differently which this short function does not implement. So, take the result carefully.

ContentLicense: CC BY-SA 4.0

Body:
Given the following code:

DB::table('users')->get();

I want to get the raw SQL query string that the database query builder above will generate. In this example, it would be SELECT * FROM users.

How do I do this?

Body:
Here is the solution I use:

DB::listen(function ($sql, $bindings, $time) {
    $bound = preg_replace_callback("/\?/", function($matches) use ($bindings) {
        static $localBindings;
        if (!isset($localBindings)) {
            $localBindings = $bindings;
        }
        $val = array_shift($localBindings);

        switch (gettype($val)) {
            case "boolean":
                $val = ($val === TRUE) ? 1 : 0;  // mysql doesn't support BOOL data types, ints are widely used
                // $val = ($val === TRUE) ? "'t'" : "'f'";   // todo: use this line instead of the above for postgres and others
                break;

            case "NULL":
                $val = "NULL";
                break;

            case "string":
            case "object":
                $val = "'". addslashes($val). "'";   // correct escaping would depend on the RDBMS
                break;
        }
        return $val;
    }, $sql);
    array_map(function($x) {
        (new \Illuminate\Support\Debug\Dumper)->dump($x);
    }, [$sql, $bindings, $bound]);
});

Please, read the comments in the code. I know, it is not perfect but for my everyday debugging it is OK. It tries to build the bound query with more-or-less reliability. However, don't trust it completely, the database engines escape the values differently which this short function does not implement. So, take the result carefully.

ContentLicense: CC BY-SA 3.0


问:
Does ClearCase fit our development process?
So, let me describe our current situation. We are a small team (6) of experienced Java developers, lost in a big IS team that is composed in majority with SAP and Siebel configurators.

While all the other teams were currently using VSS, mostly as a vaulting system, our team had switch for Subversion (after evaluating DVCS as well) as it best fits our agile methodology.

Now, everyone is asked to move to ClearCase, and all the migration effort is put on the VSS users as they are the biggest part of users.

As we are left on our own and don't know really ClearCase, we have some fear that it won't fit our current work process.

Here is currently how we are working on a daily basis:

SVN repository follows the /trunk, /branches, /tags structure.

Each developer has its own sandbox in the repository, for testing and prototyping purpose.

We intensively use branches for new feature development, and are used to merge them together to do some integration testing before promoting them back to the trunk.

Working in Java, we are used to do refactoring, and Eclipse is a great help for that. A lot of classes and packages renaming is done everyday.

Depending on how the projects evolved, some pieces may be reused, resulting in a split of a project in several project, the original remains integrated through the svn:external property.

We use keyword substitution for some elements as it's a extremely simple way to know for the tester what revision he's testing.

Our Subversion repository is linked to Hudson for running test suites and promote valid builds by tagging them.

All that I know about ClearCase for the moment is that we'll have to use it through CCRC (or via its eclipse plugin version), and that it is highly encouraged that we linked most of our projects to a ClearQuest project for issue tracking management.

Could you enlighten us about how well ClearCase will substitute our Subversion, what concepts have an exact match (I don't care about synonyms but really about concepts), and what kind of changes could you foreseen in the whole process.

Thanks.

答:
Here's the issue with ClearCase:

ClearCase was created back in the 1990s when your workstation on your desktop system might not even have had a disk drive -- let alone space. Plus, your desktop system was probably memory limited and slow.

ClearCase was a great answer. Views could live on a view server. VOBs live on a Vob server. Dedicated machines that are fast, fast, fast.

ClearCase had derived objects that could be winked in instead of having your slow machine attempt to compile the code. What a time saver that was!

And, ClearCase's VOB structure meant you could do things that few version control systems could do. For example, you could cd into a file if you appended @@ on the name. That allowed you to see all the branches, tags, and all versions of that file. You could simply run your standard Unix tools to search for differences, etc.

Then, the world changed:

Desktop systems got more powerful. You have the diskspace, the memory, and the raw processing power. Creating a checkout workspace on your local drive (and you certainly had one) meant you didn't have to depend upon the network which was getting slower as more and more network processes appeared. Wink in a derived object? Heck, my machine could build the sucker five times faster than ClearCase could locate an appropriate derived object.

Windows. ClearCase was designed with Unix in mind. Hooks could operate on the local system because everyone had Perl installed on their desktop, and you could easily make sure they all were at the same revision. Heck, you could have an NFS mounted /usr/local directory (I know, but networked local directories were common) with the right version of Perl or whatever installed, and your hooks would work. Windows didn't play so nicely. Hooks became a headache.

Windows again: ClearCase depended upon the Unix tools to work well. Windows didn't have them.

Agile Development: When ClearCase was developed, the development model was one of isolating developers from each other. You could work a lot faster if you didn't constantly have to worry about another developer making changes to your system. In ClearCase branching was easy. You could give everyone their own branch, and then they could merge back to the main branch when they're done. Merge back and forth! It's easy in ClearCase. Heck, UCM is built upon the very foundation. Unfortunately, the strategy demanded complete discipline. You had to keep reminding developers to merge their code, so other developers could see them. There was the inevitable merge crunch that occurred right before a release as dozens of developers all try to merge their changes back to the integration branch. Agile development removes the concept of developer isolation. You make small changes, and keep track with what others are doing. Thus, the concept of "Oprah Branching" (You get a branch! You get a branch! Everyone gets a branch!) is no longer used.

So, now you have a fast system with plenty of disk space and memory. You can have three or four separate checkouts at once. The dynamic view advantage simply didn't overcome its disadvantage of being dog slow and network intensive. Snapshot views help, but they remove all the ClearCase magic one once had. In other words, why use a system as big and as bulky as ClearCase like it was CVS when you could just simply use CVS in the first place?

Lastly ClearCase is hard. Back in the old days when developers were all system and network experts, learning the ins and outs of ClearCase could be expected. Making views was no harder than learning YACC syntax. However, developers aren't as system savvy as they once were. Why should they be? You don't need to know how memory works in order to program in Java or C#. Developers no longer want to learn about 100 different tools in order to do their job. ClearCase training can take a few days, and learning the ins and outs of ClearCase can take weeks. In ClearCase, I have to understand the view syntax to do simple things like modifying code on a branch. With CVS, it's just a single command.

ClearCase simply is too complex, slow, and expensive. And, much of it was the bet that Atria took when they built ClearCase: 1). Developers will be willing to learn it because they have to learn 100 other tools anyway. 2). Your desktop machine is slow and tiny compared to the network servers. Doing everything "in the cloud" is faster. 3). ClearCase centralization abilities is a great advantage for companies since one site can manage and support everything.

All three of those assumptions turn out to be false, and because of that, fewer and fewer companies are even considering ClearCase. Maybe back when Rational bought PureAtria, if Rational brought it into the 21st century to make it smaller and lighter and cheaper, it might still be a widely used tool. But, Rational was too busying making development more convoluted in order to integrate all the nifty tools they bought into a centralized development process. By the time IBM bought Rational, ClearCase was starting to bleed users.

ContentLicense: CC BY-SA 2.5


问:
Xamarin Form Notification with FireBase
Can any one tell me about xamarin form notification with firebase. I read out many blogs and tutorials, they are using xamarin.android. But i want to implement notification with xamarin form.
Can any one help me out of it or tell me the alternate.

Thanks

答: There are more then enough resources online available to help you with this. The Microsoft website has a tutorial that uses Notification Hubs (which is a feature of Azure). This connects to both FireBase for Android and APNS for iOS devices. Their tutorial to implement this can be found here: https://learn.microsoft.com/en-us/azure/app-service-mobile/app-service-mobile-xamarin-forms-get-started-push</p>

Title: Xamarin Form Notification with FireBase


问:
Is there a "nice" way to advance a pointer to a struct by one byte?
I have a pointer to a structure that I would like to move over an
address range, byte-by-byte. I have an approach that's working, but
it's ugly in my eyes. Unfortunately, the "nice" way doesn't work. Here's a minimum example:

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

typedef struct {
    uint32_t a;
    uint32_t b;
} s_t;

int main( int argc, char** argv )
{
    uint32_t address = 17;
    s_t* ps = (s_t*) address;

    // ugly
    uint8_t* gna = (uint8_t*) ps;
    ++gna;
    ps = (s_t*) gna;

    // nice
    ++((uint8_t*) ps);
}
</code>```

The compiler reports an error on the "nice" part:

```<code>% gcc test.c -o test.bin
test.c: In function 'main':
test.c:17:5: error: lvalue required as increment operand
     ++((uint8_t*) ps);
     ^
</code>```

I understand the error, but I thought casting to an uint8_t* would
create an lvalue. Obviously, I'm wrong.

Is there a way to make it better?

答:
As solution can be defining a char* pointer to point to the struct. Then by adding this pointer you could access to the bytes of the pointed structure.

```<code> s_t a;
 unsigned char *b = (unsigned char*)&a;
 unsigned char next_byte = *(++b);
</code>```

Then by adding b you can get the bytes of the a. The shortage of this solution is you might get error or warning in some compilers to pass the pointer to struct by a char pointer.

Body:
I have a pointer to a structure that I would like to move over an
address range, byte-by-byte. I have an approach that's working, but
it's ugly in my eyes. Unfortunately, the "nice" way doesn't work. Here's a minimum example:

#include <stdint.h>

typedef struct {
    uint32_t a;
    uint32_t b;
} s_t;

int main( int argc, char** argv )
{
    uint32_t address = 17;
    s_t* ps = (s_t*) address;

    // ugly
    uint8_t* gna = (uint8_t*) ps;
    ++gna;
    ps = (s_t*) gna;

    // nice
    ++((uint8_t*) ps);
}

The compiler reports an error on the "nice" part:

% gcc test.c -o test.bin
test.c: In function 'main':
test.c:17:5: error: lvalue required as increment operand
     ++((uint8_t*) ps);
     ^

I understand the error, but I thought casting to an uint8_t* would
create an lvalue. Obviously, I'm wrong.

Is there a way to make it better?

Body:
As solution can be defining a char* pointer to point to the struct. Then by adding this pointer you could access to the bytes of the pointed structure.

 s_t a;
 unsigned char *b = (unsigned char*)&a;
 unsigned char next_byte = *(++b);

Then by adding b you can get the bytes of the a. The shortage of this solution is you might get error or warning in some compilers to pass the pointer to struct by a char pointer.


问:
OSX: How do I convert a static library to a dynamic one?
Suppose I have a third party library called somelib.a on a Mac running Mountain Lion with Xcode 4.4 installed. I want to get a dynamic library out of it called somelib.dylib. An appropriate Linux command would be:

```<code>g++ -fpic -shared -Wl,-whole-archive somelib.a -Wl,-no-whole-archive -o somelib.so
</code>```

where -whole-archive and -no-whole-archive are passed to the linker.
When I do the equivalent for Mac:

```<code>g++ -fpic -shared -Wl,-whole-archive somelib.a -Wl,-no-whole-archive -o somelib.dylib
</code>```

ld fails with an error:

```<code>ld: unknown option: -whole-archive
</code>```

It seems that the ld on OSX is different from GNU ld. How do I have to modify above command so I will get the desired result?

Thank you in advance!

答:
Note: A link for the documentation of the OSX ld linker.

http://www.unix.com/man-page/osx/1/ld/

I know it is late to give an answer for this, but I do not have enough reputation to make a comment on @hanslovsky answer.
However, it helps me a lot to have the docs of the options too.
It helps what the options do exactly, and that other options the ld linker also has.
So I just wanted to share with others who finds linking an issue.

UPDATE:

After the comment from @GhostCat I have decided to expand my answer.

The docs for -all_load is:

-all_load

```<code>Loads all members of static archive libraries.
</code>```

So it loads for all static libraries that you note.
If you want something similar to --whole-archive and --no-whole-archive, then you need to use -force_load and -noall_load.

-force_load "path_to_archive"

Loads all members of the specified static archive library.  Note: -
     all_load forces all members of all archives to be loaded.

     This option allows you to target a specific archive.

-noall_load

This is the default.  This option is obsolete.

Then you can define which libraries to fully load with -force_load and then later turn it off again with -noall_load.

Body:
Suppose I have a third party library called somelib.a on a Mac running Mountain Lion with Xcode 4.4 installed. I want to get a dynamic library out of it called somelib.dylib. An appropriate Linux command would be:

g++ -fpic -shared -Wl,-whole-archive somelib.a -Wl,-no-whole-archive -o somelib.so

where -whole-archive and -no-whole-archive are passed to the linker.
When I do the equivalent for Mac:

g++ -fpic -shared -Wl,-whole-archive somelib.a -Wl,-no-whole-archive -o somelib.dylib

ld fails with an error:

ld: unknown option: -whole-archive

It seems that the ld on OSX is different from GNU ld. How do I have to modify above command so I will get the desired result?

Thank you in advance!

Body:
Note: A link for the documentation of the OSX ld linker.

http://www.unix.com/man-page/osx/1/ld/

I know it is late to give an answer for this, but I do not have enough reputation to make a comment on @hanslovsky answer.
However, it helps me a lot to have the docs of the options too.
It helps what the options do exactly, and that other options the ld linker also has.
So I just wanted to share with others who finds linking an issue.

UPDATE:

After the comment from @GhostCat I have decided to expand my answer.

The docs for -all_load is:

-all_load

Loads all members of static archive libraries.

So it loads for all static libraries that you note.
If you want something similar to --whole-archive and --no-whole-archive, then you need to use -force_load and -noall_load.

-force_load "path_to_archive"

Loads all members of the specified static archive library.  Note: -
     all_load forces all members of all archives to be loaded.

     This option allows you to target a specific archive.

-noall_load

This is the default.  This option is obsolete.

Then you can define which libraries to fully load with -force_load and then later turn it off again with -noall_load.


问:
Can a module be reloaded from a different location, from within the module?
I have an API A::B that's "use"d by others in their scripts like so:

```<code>use A::B;
my $out = A::B->new(dir => $dir);
...
</code>```

Now, I want a different version of A::B to be used depending on some parameter of the attribute $dir passed to the constructor.  The user of this module has no need to know this - all he has to do is

use A::B

in his code, and expect that the module is picked up from the right location.  Is it possible to do this?

答:
Messy:

```<code>BEGIN {
   my $version = '2.0';
   require "/home/$version/lib/A/B.pm";
}

my $obj = A::B->new();
</code>```

If it's an external entity controlling the choice, then simply adjust Perl's library search path.

```<code>version=2.0
PERL5LIB="/home/$version/lib" script
</code>```

```<code>use A::B qw( );

my $obj = A::B->new();
</code>```

If it's an internal choice, use submodules instead.

```<code>package A::B;

sub new {
   my ($class, $version) = @_;
   $version =~ s/\./_/g;
   $class .= "::V$version";
   require $class;
   return $class->new(@_);
}

1;
</code>```

```<code>use A::B qw( );

my $version = '2.0';
my $obj = A::B->new($version);
</code>```

Body:
I have an API A::B that's "use"d by others in their scripts like so:

use A::B;
my $out = A::B->new(dir => $dir);
...

Now, I want a different version of A::B to be used depending on some parameter of the attribute $dir passed to the constructor.  The user of this module has no need to know this - all he has to do is

use A::B

in his code, and expect that the module is picked up from the right location.  Is it possible to do this?

Body:
Messy:

BEGIN {
   my $version = '2.0';
   require "/home/$version/lib/A/B.pm";
}

my $obj = A::B->new();

If it's an external entity controlling the choice, then simply adjust Perl's library search path.

version=2.0
PERL5LIB="/home/$version/lib" script

use A::B qw( );

my $obj = A::B->new();

If it's an internal choice, use submodules instead.

package A::B;

sub new {
   my ($class, $version) = @_;
   $version =~ s/\./_/g;
   $class .= "::V$version";
   require $class;
   return $class->new(@_);
}

1;

use A::B qw( );

my $version = '2.0';
my $obj = A::B->new($version);


问:
CSS 3 : Image doesn't get 100% of div
I have a div in which I am displaying an image. The image is bigger than its contained div.

somehow I get space to top and bottom of the image.

.image_contain_div {
  height: 130px;
  padding: 5px;
  width: 180px;
  border: thin black solid;
  /* Firefox */
  display: -moz-box;
  -moz-box-orient: horizontal;
  -moz-box-pack: center;
  -moz-box-align: center;
  /* Safari and Chrome */
  display: -webkit-box;
  -webkit-box-orient: horizontal;
  -webkit-box-pack: center;
  -webkit-box-align: center;
  /* W3C */
  display: box;
  box-orient: horizontal;
  box-pack: center;
  box-align: center;
  /* IE10 -Doesn't work yet! */
  display: -ms-flexbox;
  -ms-flex-align: center;
  -ms-flex-pack: center;
  -ms-box-orient: horizontal;
}
.image_contain_div .image_div {
  background: #000;
  /* Firefox */
  display: -moz-box;
  -moz-box-orient: horizontal;
  -moz-box-pack: center;
  -moz-box-align: center;
  /* Safari and Chrome */
  display: -webkit-box;
  -webkit-box-orient: horizontal;
  -webkit-box-pack: center;
  -webkit-box-align: center;
  /* W3C */
  display: box;
  box-orient: horizontal;
  box-pack: center;
  box-align: center;
  /* IE10 -Doesn't work yet! */
  display: -ms-flexbox;
  -ms-flex-align: center;
  -ms-flex-pack: center;
  -ms-box-orient: horizontal;
  height: 100%;
  width: 100%;
  position: relative;
}
.image_contain_div .image_div .custom_website_default_image_div {
  /* Firefox */
  display: -moz-box;
  -moz-box-orient: horizontal;
  -moz-box-pack: center;
  -moz-box-align: center;
  /* Safari and Chrome */
  display: -webkit-box;
  -webkit-box-orient: horizontal;
  -webkit-box-pack: center;
  -webkit-box-align: center;
  /* W3C */
  display: box;
  box-orient: horizontal;
  box-pack: center;
  box-align: center;
  /* IE10 -Doesn't work yet! */
  display: -ms-flexbox;
  -ms-flex-align: center;
  -ms-flex-pack: center;
  -ms-box-orient: horizontal;
}
.image_contain_div .image_div .custom_website_default_image_div svg {
  width: 26px;
  height: 26px;
}
.image_contain_div .image_div img {
  max-width: 100%;
  max-height: 100%;
}
.image_contain_div .image_div .custom_website_image_overlay_div {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: none;
}
.image_contain_div .image_div .custom_website_image_overlay_div svg {
  width: 30px;
  height: 30px;
}
.image_contain_div .image_div:hover .custom_website_image_overlay_div {
  /* Firefox */
  display: -moz-box;
  -moz-box-orient: horizontal;
  -moz-box-pack: center;
  -moz-box-align: center;
  /* Safari and Chrome */
  display: -webkit-box;
  -webkit-box-orient: horizontal;
  -webkit-box-pack: center;
  -webkit-box-align: center;
  /* W3C */
  display: box;
  box-orient: horizontal;
  box-pack: center;
  box-align: center;
  /* IE10 -Doesn't work yet! */
  display: -ms-flexbox;
  -ms-flex-align: center;
  -ms-flex-pack: center;
  -ms-box-orient: horizontal;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="image_contain_div b">
    <div class="image_div ">

        <img src="https://d28hsb6vkzynsw.cloudfront.net/banner/2877/500/99041_banner_testfile.jpeg" alt="">

        <div class="custom_website_image_overlay_div">
            <span class="cursor_pointer">
                <svg  class="v-middle" style="enable-background:new 0 0 33.004 33.004;" viewBox="0 0 33.004 33.004"  x="0px" xmlns="http://www.w3.org/2000/svg" y="0px">
                    <path  d="M33.004,15.414H17.59V0h-2.176v15.414H0v2.176h15.414v15.414h2.176V17.59h15.414V15.414z" style="fill:#fff;"></path>
                </svg>
            </span>
        </div>

    </div>
</div></code>```

I want to cover the image to the black background div.

Note : If image is smaller than the div then it should be in the middle of the div.

Any help would be great.

Thank You.

答:
.image_contain_div {
  height: 130px;
  padding: 5px;
  width: 180px;
  border: thin black solid;
  /* Firefox */
  display: -moz-box;
  -moz-box-orient: horizontal;
  -moz-box-pack: center;
  -moz-box-align: center;
  /* Safari and Chrome */
  display: -webkit-box;
  -webkit-box-orient: horizontal;
  -webkit-box-pack: center;
  -webkit-box-align: center;
  /* W3C */
  display: box;
  box-orient: horizontal;
  box-pack: center;
  box-align: center;
  /* IE10 -Doesn't work yet! */
  display: -ms-flexbox;
  -ms-flex-align: center;
  -ms-flex-pack: center;
  -ms-box-orient: horizontal;
}
.image_contain_div .image_div {
  background: #000;
  /* Firefox */
  display: -moz-box;
  -moz-box-orient: horizontal;
  -moz-box-pack: center;
  -moz-box-align: center;
  /* Safari and Chrome */
  display: -webkit-box;
  -webkit-box-orient: horizontal;
  -webkit-box-pack: center;
  -webkit-box-align: center;
  /* W3C */
  display: box;
  box-orient: horizontal;
  box-pack: center;
  box-align: center;
  /* IE10 -Doesn't work yet! */
  display: -ms-flexbox;
  -ms-flex-align: center;
  -ms-flex-pack: center;
  -ms-box-orient: horizontal;
  height: 100%;
  width: 100%;
  position: relative;
}
.image_contain_div .image_div .custom_website_default_image_div {
  /* Firefox */
  display: -moz-box;
  -moz-box-orient: horizontal;
  -moz-box-pack: center;
  -moz-box-align: center;
  /* Safari and Chrome */
  display: -webkit-box;
  -webkit-box-orient: horizontal;
  -webkit-box-pack: center;
  -webkit-box-align: center;
  /* W3C */
  display: box;
  box-orient: horizontal;
  box-pack: center;
  box-align: center;
  /* IE10 -Doesn't work yet! */
  display: -ms-flexbox;
  -ms-flex-align: center;
  -ms-flex-pack: center;
  -ms-box-orient: horizontal;
}
.image_contain_div .image_div .custom_website_default_image_div svg {
  width: 26px;
  height: 26px;
}
.image_contain_div .image_div img {
  max-width: 100%;
  max-height: 100%;
  position: absolute;
  top: 0;
  z-index: 1;
  height: 100%;
  left: 0;
}
.image_contain_div .image_div .custom_website_image_overlay_div {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: none;
  z-index: 1;
}
.image_contain_div .image_div .custom_website_image_overlay_div svg {
  width: 30px;
  height: 30px;
}
.image_contain_div .image_div:hover .custom_website_image_overlay_div {
  /* Firefox */
  display: -moz-box;
  -moz-box-orient: horizontal;
  -moz-box-pack: center;
  -moz-box-align: center;
  /* Safari and Chrome */
  display: -webkit-box;
  -webkit-box-orient: horizontal;
  -webkit-box-pack: center;
  -webkit-box-align: center;
  /* W3C */
  display: box;
  box-orient: horizontal;
  box-pack: center;
  box-align: center;
  /* IE10 -Doesn't work yet! */
  display: -ms-flexbox;
  -ms-flex-align: center;
  -ms-flex-pack: center;
  -ms-box-orient: horizontal;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="image_contain_div b">
    <div class="image_div ">

        <img src="https://d28hsb6vkzynsw.cloudfront.net/banner/2877/500/99041_banner_testfile.jpeg" alt="">

        <div class="custom_website_image_overlay_div">
            <span class="cursor_pointer">
                <svg  class="v-middle" style="enable-background:new 0 0 33.004 33.004;" viewBox="0 0 33.004 33.004"  x="0px" xmlns="http://www.w3.org/2000/svg" y="0px">
                    <path  d="M33.004,15.414H17.59V0h-2.176v15.414H0v2.176h15.414v15.414h2.176V17.59h15.414V15.414z" style="fill:#fff;"></path>
                </svg>
            </span>
        </div>

    </div>
</div></code>```

Title: CSS 3 : Image doesn't get 100% of div

Body:
I have a div in which I am displaying an image. The image is bigger than its contained div.

somehow I get space to top and bottom of the image.

.image_contain_div {
  height: 130px;
  padding: 5px;
  width: 180px;
  border: thin black solid;
  /* Firefox */
  display: -moz-box;
  -moz-box-orient: horizontal;
  -moz-box-pack: center;
  -moz-box-align: center;
  /* Safari and Chrome */
  display: -webkit-box;
  -webkit-box-orient: horizontal;
  -webkit-box-pack: center;
  -webkit-box-align: center;
  /* W3C */
  display: box;
  box-orient: horizontal;
  box-pack: center;
  box-align: center;
  /* IE10 -Doesn't work yet! */
  display: -ms-flexbox;
  -ms-flex-align: center;
  -ms-flex-pack: center;
  -ms-box-orient: horizontal;
}
.image_contain_div .image_div {
  background: #000;
  /* Firefox */
  display: -moz-box;
  -moz-box-orient: horizontal;
  -moz-box-pack: center;
  -moz-box-align: center;
  /* Safari and Chrome */
  display: -webkit-box;
  -webkit-box-orient: horizontal;
  -webkit-box-pack: center;
  -webkit-box-align: center;
  /* W3C */
  display: box;
  box-orient: horizontal;
  box-pack: center;
  box-align: center;
  /* IE10 -Doesn't work yet! */
  display: -ms-flexbox;
  -ms-flex-align: center;
  -ms-flex-pack: center;
  -ms-box-orient: horizontal;
  height: 100%;
  width: 100%;
  position: relative;
}
.image_contain_div .image_div .custom_website_default_image_div {
  /* Firefox */
  display: -moz-box;
  -moz-box-orient: horizontal;
  -moz-box-pack: center;
  -moz-box-align: center;
  /* Safari and Chrome */
  display: -webkit-box;
  -webkit-box-orient: horizontal;
  -webkit-box-pack: center;
  -webkit-box-align: center;
  /* W3C */
  display: box;
  box-orient: horizontal;
  box-pack: center;
  box-align: center;
  /* IE10 -Doesn't work yet! */
  display: -ms-flexbox;
  -ms-flex-align: center;
  -ms-flex-pack: center;
  -ms-box-orient: horizontal;
}
.image_contain_div .image_div .custom_website_default_image_div svg {
  width: 26px;
  height: 26px;
}
.image_contain_div .image_div img {
  max-width: 100%;
  max-height: 100%;
}
.image_contain_div .image_div .custom_website_image_overlay_div {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: none;
}
.image_contain_div .image_div .custom_website_image_overlay_div svg {
  width: 30px;
  height: 30px;
}
.image_contain_div .image_div:hover .custom_website_image_overlay_div {
  /* Firefox */
  display: -moz-box;
  -moz-box-orient: horizontal;
  -moz-box-pack: center;
  -moz-box-align: center;
  /* Safari and Chrome */
  display: -webkit-box;
  -webkit-box-orient: horizontal;
  -webkit-box-pack: center;
  -webkit-box-align: center;
  /* W3C */
  display: box;
  box-orient: horizontal;
  box-pack: center;
  box-align: center;
  /* IE10 -Doesn't work yet! */
  display: -ms-flexbox;
  -ms-flex-align: center;
  -ms-flex-pack: center;
  -ms-box-orient: horizontal;
}

                <svg  class="v-middle" style="enable-background:new 0 0 33.004 33.004;" viewBox="0 0 33.004 33.004"  x="0px" xmlns="http://www.w3.org/2000/svg" y="0px">
                    <path  d="M33.004,15.414H17.59V0h-2.176v15.414H0v2.176h15.414v15.414h2.176V17.59h15.414V15.414z" style="fill:#fff;"></path>
                </svg>

I want to cover the image to the black background div.

Note : If image is smaller than the div then it should be in the middle of the div.

Any help would be great.

Thank You.

Body:
.image_contain_div {
  height: 130px;
  padding: 5px;
  width: 180px;
  border: thin black solid;
  /* Firefox */
  display: -moz-box;
  -moz-box-orient: horizontal;
  -moz-box-pack: center;
  -moz-box-align: center;
  /* Safari and Chrome */
  display: -webkit-box;
  -webkit-box-orient: horizontal;
  -webkit-box-pack: center;
  -webkit-box-align: center;
  /* W3C */
  display: box;
  box-orient: horizontal;
  box-pack: center;
  box-align: center;
  /* IE10 -Doesn't work yet! */
  display: -ms-flexbox;
  -ms-flex-align: center;
  -ms-flex-pack: center;
  -ms-box-orient: horizontal;
}
.image_contain_div .image_div {
  background: #000;
  /* Firefox */
  display: -moz-box;
  -moz-box-orient: horizontal;
  -moz-box-pack: center;
  -moz-box-align: center;
  /* Safari and Chrome */
  display: -webkit-box;
  -webkit-box-orient: horizontal;
  -webkit-box-pack: center;
  -webkit-box-align: center;
  /* W3C */
  display: box;
  box-orient: horizontal;
  box-pack: center;
  box-align: center;
  /* IE10 -Doesn't work yet! */
  display: -ms-flexbox;
  -ms-flex-align: center;
  -ms-flex-pack: center;
  -ms-box-orient: horizontal;
  height: 100%;
  width: 100%;
  position: relative;
}
.image_contain_div .image_div .custom_website_default_image_div {
  /* Firefox */
  display: -moz-box;
  -moz-box-orient: horizontal;
  -moz-box-pack: center;
  -moz-box-align: center;
  /* Safari and Chrome */
  display: -webkit-box;
  -webkit-box-orient: horizontal;
  -webkit-box-pack: center;
  -webkit-box-align: center;
  /* W3C */
  display: box;
  box-orient: horizontal;
  box-pack: center;
  box-align: center;
  /* IE10 -Doesn't work yet! */
  display: -ms-flexbox;
  -ms-flex-align: center;
  -ms-flex-pack: center;
  -ms-box-orient: horizontal;
}
.image_contain_div .image_div .custom_website_default_image_div svg {
  width: 26px;
  height: 26px;
}
.image_contain_div .image_div img {
  max-width: 100%;
  max-height: 100%;
  position: absolute;
  top: 0;
  z-index: 1;
  height: 100%;
  left: 0;
}
.image_contain_div .image_div .custom_website_image_overlay_div {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: none;
  z-index: 1;
}
.image_contain_div .image_div .custom_website_image_overlay_div svg {
  width: 30px;
  height: 30px;
}
.image_contain_div .image_div:hover .custom_website_image_overlay_div {
  /* Firefox */
  display: -moz-box;
  -moz-box-orient: horizontal;
  -moz-box-pack: center;
  -moz-box-align: center;
  /* Safari and Chrome */
  display: -webkit-box;
  -webkit-box-orient: horizontal;
  -webkit-box-pack: center;
  -webkit-box-align: center;
  /* W3C */
  display: box;
  box-orient: horizontal;
  box-pack: center;
  box-align: center;
  /* IE10 -Doesn't work yet! */
  display: -ms-flexbox;
  -ms-flex-align: center;
  -ms-flex-pack: center;
  -ms-box-orient: horizontal;
}

<div class="image_contain_div b">
    <div class="image_div ">

        <img src="https://d28hsb6vkzynsw.cloudfront.net/banner/2877/500/99041_banner_testfile.jpeg" alt="">

        <div class="custom_website_image_overlay_div">
            <span class="cursor_pointer">
                <svg  class="v-middle" style="enable-background:new 0 0 33.004 33.004;" viewBox="0 0 33.004 33.004"  x="0px" xmlns="http://www.w3.org/2000/svg" y="0px">
                    <path  d="M33.004,15.414H17.59V0h-2.176v15.414H0v2.176h15.414v15.414h2.176V17.59h15.414V15.414z" style="fill:#fff;"></path>
                </svg>
            </span>
        </div>

    </div>
</div>


问:
Visual Studio crashes consistently on web-related projects

I have a brand new VS2010 installed on a Win2008R2 machine.

I started getting this error when debugging a WCF service project:

"Attempted to read or write protected
  memory. This is often an indication
  that other memory is corrupt."

When I started developing a web site a week later, this became consistent - I can't debug it.
The stack dump reads:

at
  Microsoft.VisualStudio.WebHost.Host.ProcessRequest(Connection
  conn)    at
  Microsoft.VisualStudio.WebHost.Server.OnSocketAccept(Object
  acceptedSocket)    at
  System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object
  state)    at
  System.Threading.ExecutionContext.Run(ExecutionContext
  executionContext, ContextCallback
  callback, Object state, Boolean
  ignoreSyncCtx)    at
  System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
  at
  System.Threading.ThreadPoolWorkQueue.Dispatch()
  at
  System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()

I tried searching online, and some recommend turning off the "Suppress JIT Optimizations" in the Debugging options - this dos not seem to make a difference.

Clearly the problem is with the built in web server. But am I doing something wrong? Is there something I can do? Or is this a known bug?

Thanks for your time,

Guy

Update 12/31: Today I tried using CassiniDev as a replacement to the original VS2010 WebServer - exact same result. My suspicion is that there's some internal conflict between VS2010, Windows Server 2008R2 and maybe the fact that it's a 64 bit OS. I switched to using IIS as my debug server - and that seems to work, with some annoying side effects.

My conclusion: do not use a 64 bit server system as your dev machine. Develop on 32bit - deploy to 64bit.

Side conclusion: there are some scenarios Microsoft's QA doesn't test.

答:
The thing that gets my attention is Win2008R2 and Cassini.

I'm just guessing, but it makes me think that it could be a permission issue.

Is it possible that your Win2008R2 machine is locked down more than your average developer machine (the average developer machine being XP / Vista / Win7 etc).

Perhaps Cassini when launched under your user account on Win2008R2 does not have enough permission to do its thing. Perhaps it cannot open ports? But I wouldn't think a port issue would cause a crash. Or perhaps it doesn't have access to the temporary directories it needs?

Perhaps your user account is denied the permission to debug on the local security policy? But i'm not an admin, so i'm not certain on this.

Maybe try launching visual studio as an Administrator (just incase, to help you investigate the problem).

Or perhaps try starting your site without debugging to help see if it's some sort of permission issue with debugging processes.

I came across this, it's from some time ago talking about Windows 7 and Cassini. http://msmvps.com/blogs/rfennell/archive/2009/01/24/problem-hosting-wcf-using-cassini-on-windows-7.aspx But it may not of been fixed.


问:
Set Service Start Parameter using Topshelf
I have a service with multiple instances with different parameters for each instance, at the moment I'm setting these parameters manually (in another code to be exact) to Image Path of the service in Registry (e.g. HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\MyService$i00). so our service installation is done in two steps.

I'm really interested to merge these steps in Topshelf installation for example like

```<code>MyService.exe install -instance "i00" -config "C:\i00Config.json"
</code>```

First Try

I tried AddCommandLineDefinition from TopShelf but it seems it only works during installation and running through console not the service itself (will not add anything to service Image Path).

Second Try

I tried to see if its possible to do this with AfterInstall from Topshelf without any luck. here is a test code to see if it going to work or not (but unfortunately Topshelf overwrites the registry after AfterInstall call).

```<code>HostFactory.Run(x =>
        {
            x.UseNLog();
            x.Service<MyService>(sc =>
            {
                sc.ConstructUsing(hs => new MyService(hs));
                sc.WhenStarted((s, h) => s.Start(h));
                sc.WhenStopped((s, h) => s.Stop(h));
            });

            x.AfterInstall(s =>
            {
                using (var system = Registry.LocalMachine.OpenSubKey("SYSTEM"))
                using (var controlSet = system.OpenSubKey("CurrentControlSet"))
                using (var services = controlSet.OpenSubKey("services"))
                using (var service = services.OpenSubKey(string.IsNullOrEmpty(s.InstanceName)
                    ? s.ServiceName
                    : s.ServiceName + "$" + s.InstanceName, true))
                {

                    if (service == null)
                        return;

                    var imagePath = service.GetValue("ImagePath") as string;

                    if (string.IsNullOrEmpty(imagePath))
                        return;

                        var appendix = string.Format(" -{0} \"{1}\"", "config", "C:\i00config.json"); //only a test to see if it is possible at all or not
                        imagePath = imagePath + appendix;

                    service.SetValue("ImagePath", imagePath);
                }
            });

            x.SetServiceName("MyService");
            x.SetDisplayName("My Service");
            x.SetDescription("My Service Sample");
            x.StartAutomatically();
            x.RunAsLocalSystem();
            x.EnableServiceRecovery(r =>
            {
                r.OnCrashOnly();
                r.RestartService(1); //first
                r.RestartService(1); //second
                r.RestartService(1); //subsequents
                r.SetResetPeriod(0);
            });
        });
</code>```

I couldn't find any relevant information about how it can be done using TopShelf so the question is, is it possible to do this with TopShelf?

答:
The following work-around is nothing more than a registry update. The update operation expects the privileges the installer requires in order to write our extended arguments.

Basically, we're responding to the AfterInstall() event. As of Topshelf v4.0.3, calling the AppendImageArgs() work-around from within the event will cause your args to appear before the TS args. If the call is deferred, your args will appear after the TS args.

The work-around

```<code>private static void AppendImageArgs(string serviceName, IEnumerable<Tuple<string, object>> args)
{
  try
  {
    using (var service = Registry.LocalMachine.OpenSubKey($@"System\CurrentControlSet\Services\{serviceName}", true))
    {
      const string imagePath = "ImagePath";
      var value = service?.GetValue(imagePath) as string;
      if (value == null)
        return;
      foreach (var arg in args)
        if (arg.Item2 == null)
          value += $" -{arg.Item1}";
        else
          value += $" -{arg.Item1} \"{arg.Item2}\"";
      service.SetValue(imagePath, value);
    }
  }
  catch (Exception e)
  {
    Log.Error(e);
  }
}
</code>```

An example call

```<code>private static void AppendImageArgs(string serviceName)
{
  var args = new[]
  {
    new Tuple<string, object>("param1", "Hello"),
    new Tuple<string, object>("param2", 1),
    new Tuple<string, object>("Color", ConsoleColor.Cyan),
  };
  AppendImageArgs(serviceName, args);
}
</code>```

And the resulting args that would appear in the ImagePath:

```<code> -displayname "MyService Display Name" -servicename "MyServiceName" -param1 "Hello" -param2 "1" -Color "Cyan"
</code>```

Notice the args appeared after the TS args, -displayname & -servicename. In this example, the AppendImageArgs() call was invoked after TS finished its installation business.

Command line args can be specified normally using Topshelf methods such as AddCommandLineDefinition(). To force processing of the args, call ApplyCommandLine().

Body:
I have a service with multiple instances with different parameters for each instance, at the moment I'm setting these parameters manually (in another code to be exact) to Image Path of the service in Registry (e.g. HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\MyService$i00). so our service installation is done in two steps.

I'm really interested to merge these steps in Topshelf installation for example like

MyService.exe install -instance "i00" -config "C:\i00Config.json"

First Try

I tried AddCommandLineDefinition from TopShelf but it seems it only works during installation and running through console not the service itself (will not add anything to service Image Path).

Second Try

I tried to see if its possible to do this with AfterInstall from Topshelf without any luck. here is a test code to see if it going to work or not (but unfortunately Topshelf overwrites the registry after AfterInstall call).

HostFactory.Run(x =>
        {
            x.UseNLog();
            x.Service<MyService>(sc =>
            {
                sc.ConstructUsing(hs => new MyService(hs));
                sc.WhenStarted((s, h) => s.Start(h));
                sc.WhenStopped((s, h) => s.Stop(h));
            });

            x.AfterInstall(s =>
            {
                using (var system = Registry.LocalMachine.OpenSubKey("SYSTEM"))
                using (var controlSet = system.OpenSubKey("CurrentControlSet"))
                using (var services = controlSet.OpenSubKey("services"))
                using (var service = services.OpenSubKey(string.IsNullOrEmpty(s.InstanceName)
                    ? s.ServiceName
                    : s.ServiceName + "$" + s.InstanceName, true))
                {

                    if (service == null)
                        return;

                    var imagePath = service.GetValue("ImagePath") as string;

                    if (string.IsNullOrEmpty(imagePath))
                        return;

                        var appendix = string.Format(" -{0} \"{1}\"", "config", "C:\i00config.json"); //only a test to see if it is possible at all or not
                        imagePath = imagePath + appendix;

                    service.SetValue("ImagePath", imagePath);
                }
            });

            x.SetServiceName("MyService");
            x.SetDisplayName("My Service");
            x.SetDescription("My Service Sample");
            x.StartAutomatically();
            x.RunAsLocalSystem();
            x.EnableServiceRecovery(r =>
            {
                r.OnCrashOnly();
                r.RestartService(1); //first
                r.RestartService(1); //second
                r.RestartService(1); //subsequents
                r.SetResetPeriod(0);
            });
        });

I couldn't find any relevant information about how it can be done using TopShelf so the question is, is it possible to do this with TopShelf?

Body:
The following work-around is nothing more than a registry update. The update operation expects the privileges the installer requires in order to write our extended arguments.

Basically, we're responding to the AfterInstall() event. As of Topshelf v4.0.3, calling the AppendImageArgs() work-around from within the event will cause your args to appear before the TS args. If the call is deferred, your args will appear after the TS args.

The work-around

private static void AppendImageArgs(string serviceName, IEnumerable<Tuple<string, object>> args)
{
  try
  {
    using (var service = Registry.LocalMachine.OpenSubKey($@"System\CurrentControlSet\Services\{serviceName}", true))
    {
      const string imagePath = "ImagePath";
      var value = service?.GetValue(imagePath) as string;
      if (value == null)
        return;
      foreach (var arg in args)
        if (arg.Item2 == null)
          value += $" -{arg.Item1}";
        else
          value += $" -{arg.Item1} \"{arg.Item2}\"";
      service.SetValue(imagePath, value);
    }
  }
  catch (Exception e)
  {
    Log.Error(e);
  }
}

An example call

private static void AppendImageArgs(string serviceName)
{
  var args = new[]
  {
    new Tuple<string, object>("param1", "Hello"),
    new Tuple<string, object>("param2", 1),
    new Tuple<string, object>("Color", ConsoleColor.Cyan),
  };
  AppendImageArgs(serviceName, args);
}

And the resulting args that would appear in the ImagePath:

 -displayname "MyService Display Name" -servicename "MyServiceName" -param1 "Hello" -param2 "1" -Color "Cyan"

Notice the args appeared after the TS args, -displayname & -servicename. In this example, the AppendImageArgs() call was invoked after TS finished its installation business.

Command line args can be specified normally using Topshelf methods such as AddCommandLineDefinition(). To force processing of the args, call ApplyCommandLine().


问:
Generator expressions Python
I have a list of dictionaries like the following:

```<code>lst = [{'a': 5}, {'b': 6}, {'c': 7}, {'d': 8}]
</code>```

I wrote a generator expression like:

```<code>next((itm for itm in lst if itm['a']==5))
</code>```

Now the strange part is that though this works for the key value pair of 'a'
it throws an error for all other expressions the next time.
Expression:

```<code>next((itm for itm in lst if itm['b']==6))
</code>```

Error:

```<code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <genexpr>
KeyError: 'b'
</code>```

答:
Take a look at your generator expression separately:

```<code>(itm for itm in lst if itm['a']==5)
</code>```

This will collect all items in the list where itm['a'] == 5. So far so good.

When you call next() on it, you tell Python to generate the first item from that generator expression. But only the first.

So when you have the condition itm['a'] == 5, the generator will take the first element of the list, {'a': 5} and perform the check on it. The condition is true, so that item is generated by the generator expression and returned by next().

Now, when you change the condition to itm['b'] == 6, the generator will again take the first element of the list, {'a': 5}, and attempt to get the element with the key b. This will fail:

```<code>>>> itm = {'a': 5}
>>> itm['b']
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    itm['b']
KeyError: 'b'
</code>```

It does not even get the chance to look at the second element because it already fails while trying to look at the first element.

To solve this, you have to avoid using an expression that can raise a KeyError here. You could use dict.get() to attempt to retrieve the value without raising an exception:

```<code>>>> lst = [{'a': 5}, {'b': 6}, {'c': 7}, {'d': 8}]
>>> next((itm for itm in lst if itm.get('b') == 6))
{'b': 6}
</code>```

Title: Generator expressions Python

Body:
I have a list of dictionaries like the following:

lst = [{'a': 5}, {'b': 6}, {'c': 7}, {'d': 8}]

I wrote a generator expression like:

next((itm for itm in lst if itm['a']==5))

Now the strange part is that though this works for the key value pair of 'a'
it throws an error for all other expressions the next time.
Expression:

next((itm for itm in lst if itm['b']==6))

Error:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <genexpr>
KeyError: 'b'

Body:
Take a look at your generator expression separately:

(itm for itm in lst if itm['a']==5)

This will collect all items in the list where itm['a'] == 5. So far so good.

When you call next() on it, you tell Python to generate the first item from that generator expression. But only the first.

So when you have the condition itm['a'] == 5, the generator will take the first element of the list, {'a': 5} and perform the check on it. The condition is true, so that item is generated by the generator expression and returned by next().

Now, when you change the condition to itm['b'] == 6, the generator will again take the first element of the list, {'a': 5}, and attempt to get the element with the key b. This will fail:

>>> itm = {'a': 5}
>>> itm['b']
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    itm['b']
KeyError: 'b'

It does not even get the chance to look at the second element because it already fails while trying to look at the first element.

To solve this, you have to avoid using an expression that can raise a KeyError here. You could use dict.get() to attempt to retrieve the value without raising an exception:

>>> lst = [{'a': 5}, {'b': 6}, {'c': 7}, {'d': 8}]
>>> next((itm for itm in lst if itm.get('b') == 6))
{'b': 6}


问:
Access submodule files on server
I have used git sub module as follows:

```<code>git submodule add git:<repository>.git
</code>```

It works fine and I can see directory for the project inside my current directory.

Then I did:

```<code>git config --global status.submoduleSummary true
git commit -am "push"
git push origin master
</code>```

On git hub it shows something like this.

However when I try to access these sub module files on server it shows empty directory. How to solve this ?

答:
You add the repository as submodule, now you have to initialize it.

Use git submodule update --init --recursive to initialize and update the submodules recorded in the index.

Title: Access submodule files on server

Body:
I have used git sub module as follows:

git submodule add git:<repository>.git

It works fine and I can see directory for the project inside my current directory.

Then I did:

git config --global status.submoduleSummary true
git commit -am "push"
git push origin master

On git hub it shows something like this.

However when I try to access these sub module files on server it shows empty directory. How to solve this ?


问:
wso2 IS 520 user accountDisabled claim verify as 'admin'
Is there a way to verify a multi-tenant environment USER account is enabled or disabled using WS ?

```<code>getUserClaimValue
</code>```

IS the only one I could see !, unfortunately it asks for User credentials !

Cant we do it at admin level ?

Its not even storing into ldap-attributes. How can I get this verified as super-admin.

Claim URI :

http://wso2.org/claims/identity/accountDisabled

Worked out to get the claim as 'ref'.

How to get the value from this 'ref' direct using LDAP with JAVA ?

答:
Any claims which has the pattern http://wso2.org/claims/identity/XXXXX is considered as a special claim. Hence they are ignored by getUserClaimValue (and by setUserClaimValue when setting value).

You'll need to use either getUserClaimValues or getUserClaimValuesForClaims for the above purpose (And setUserClaimValues to set).

Update

Due to the tenant separation model it is not allowed to get claim details by other tenant admins (Even for super tenant admin). In case you really need that, one possible option would be to write a custom admin service extending the org.wso2.carbon.um.ws.service.UserStoreManagerService class (which reflects RemoteUserStoreManagerService) where it will start a tenant flow for the user's tenant, and call super class method to get the claim value.

Body:
Is there a way to verify a multi-tenant environment USER account is enabled or disabled using WS ?

getUserClaimValue

IS the only one I could see !, unfortunately it asks for User credentials !

Cant we do it at admin level ?

Its not even storing into ldap-attributes. How can I get this verified as super-admin.

Claim URI :

http://wso2.org/claims/identity/accountDisabled

Worked out to get the claim as 'ref'.

How to get the value from this 'ref' direct using LDAP with JAVA ?


问:
Query Join Condition
I Have two tables named account and assignedgroup. In account table there are two columns named ID and sourceaccount and In assignedgroup I have two columns named ID and assignedgroup.

I want to select ID by joining account and assignedgroup tables. I did something like this:

```<code>select a.ID
from account a
  left outer join assignedgroup b
   on a.sourceaccount = b.assignedgorup
</code>```

But I get Null as output the reason being that The values in sourceaccount are like this

sourceaccount:

```<code>sample
sample
</code>```

and whereas the values in assignedgroup are like this

assignedgroup:

```<code>sample-L1
sample-P-L1
</code>```

Can anyone help me on how to join these two tables?

I want to get all the ID's whenever there is a sample value in both sourceaccount and assignedgroup.

It is comparing sample with sample-L1 since those are not equal it is returning null but I want the ID even if it has values like that. I mean if somepart of the column values matches then also I want those values to be displayed

答: Clearly your database structure is flawed.  If you need the first part of the assigned group to join to the  source account, it should be stored that way in a separate column. YOu can do some manipulation to get the right values, but changing the datbase structure is the best fix as any data manipulation you do in a join is very expensive (and likely to introduce bugs).</p>

Title: Query Join Condition

Body:
I Have two tables named account and assignedgroup. In account table there are two columns named ID and sourceaccount and In assignedgroup I have two columns named ID and assignedgroup.

I want to select ID by joining account and assignedgroup tables. I did something like this:

select a.ID
from account a
  left outer join assignedgroup b
   on a.sourceaccount = b.assignedgorup

But I get Null as output the reason being that The values in sourceaccount are like this

sourceaccount:

sample
sample

and whereas the values in assignedgroup are like this

assignedgroup:

sample-L1
sample-P-L1

Can anyone help me on how to join these two tables?

I want to get all the ID's whenever there is a sample value in both sourceaccount and assignedgroup.

It is comparing sample with sample-L1 since those are not equal it is returning null but I want the ID even if it has values like that. I mean if somepart of the column values matches then also I want those values to be displayed


问:
Could not write to output file 'c:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\''\''\''\''' -- 'Access is denied. '
I have an asp.net project which is running well in visual studio 2013 development server and in IIS local host. But when I upload the project in online hosting, the error showing

CS0016: Could not write to output file 'c:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\8d0dec5c\beef09e6\App_Code.u8avtytx.dll' -- 'Access is denied. '

I tried many thing to resolve the issues like the below:
http://www.tugberkugurlu.com/archive/local-iis-7-0-cs0016--could-not-write-to-output-file-microsoft-net-framework-v4-0-30319-temporary-asp-net-files

and

https://forums.asp.net/t/1353803.aspx?CS0016%20Could%20not%20write%20to%20output%20file

and many more but no result.

答: You need to give permission to those folders where write actions are being performed (i.e Upload, File open and edit). Check all options from the permission tab from the server.</p>


问:
Javascript JSON.Stringify() what is undefined
I am using JSON.Stringify() in my javascript...

```<code>var jsonProp;
var json = { };
json.prop= { };
json.prop.Brand = $('.Brand' + val).val();
json.prop.Name = $('.Name' + val).val();
json.prop.Desc = $('.Desc' + val).val();
json.prop.Address = $('.Address' + val).val();
json.prop.Phone = $('.Phone' + val).val();
json.prop.Tag = $('.Tag' + val).val();
json.prop.City = $('.City' + val).val();
json.prop.Status = $('.Status' + val).val();
jsonProp = jsonProp + JSON.stringify(json);
</code>```

and the result is :

```<code>"undefined{"prop":{"Brand":"","Name":"apotik AA","Desc":"","Address":"Address","Phone":"","Tag":"","City":"BEKASI","Status":"0"}}
{"prop":{"Brand":"","Name":"apotik AAaaaa. Bina Farma","Desc":"","Address":"Jl. RA. Kartini, Margahayu-Bekasi Tim., Kota Bks, Jawa Barat 17113","Phone":"","Tag":"","City":"BEKASI","Status":"0"}}"
</code>```

why is "undefined" there? how can I set it? all I want to have is a JSONArray like this :

```<code>Prop{{"Brand":"value","Name":"value"},{"Brand":"value","Name":"value"}}
</code>```

Please help

答:
When you declare a variable without any unassigned value:

```<code>var jsonProp; // default value set to undefined by javascript.
</code>```

Without any assignment. What javascript does is, it assigns a default value to undefined. That is how it works.  So, when you concatenate it:

```<code>jsonProp = jsonProp + JSON.stringify(json);
//         undefined + "{prop:{}}"
</code>```

This happens.

Body:
I am using JSON.Stringify() in my javascript...

var jsonProp;
var json = { };
json.prop= { };
json.prop.Brand = $('.Brand' + val).val();
json.prop.Name = $('.Name' + val).val();
json.prop.Desc = $('.Desc' + val).val();
json.prop.Address = $('.Address' + val).val();
json.prop.Phone = $('.Phone' + val).val();
json.prop.Tag = $('.Tag' + val).val();
json.prop.City = $('.City' + val).val();
json.prop.Status = $('.Status' + val).val();
jsonProp = jsonProp + JSON.stringify(json);

and the result is :

"undefined{"prop":{"Brand":"","Name":"apotik AA","Desc":"","Address":"Address","Phone":"","Tag":"","City":"BEKASI","Status":"0"}}
{"prop":{"Brand":"","Name":"apotik AAaaaa. Bina Farma","Desc":"","Address":"Jl. RA. Kartini, Margahayu-Bekasi Tim., Kota Bks, Jawa Barat 17113","Phone":"","Tag":"","City":"BEKASI","Status":"0"}}"

why is "undefined" there? how can I set it? all I want to have is a JSONArray like this :

Prop{{"Brand":"value","Name":"value"},{"Brand":"value","Name":"value"}}

Please help

Body:
When you declare a variable without any unassigned value:

var jsonProp; // default value set to undefined by javascript.

Without any assignment. What javascript does is, it assigns a default value to undefined. That is how it works.  So, when you concatenate it:

jsonProp = jsonProp + JSON.stringify(json);
//         undefined + "{prop:{}}"

This happens.


问:
Pass arguments with page.evaluate
I'm using PhantomJS page.evaluate() to do some scraping. My problem is that the code I pass to the webkit page is sandboxed, and so has no access to the variables of my main phantom script. This makes it hard make the scraping code generic.

```<code>page.open(url, function() {
  var foo = 42;

  page.evaluate(function() {
    // this code has no access to foo
    console.log(foo);
  });
}
</code>```

How could I push arguments into the page?

答:
While you can pass arguments into evaluate(function, arg1, arg2, ...), this is often a little cumbersome. Especially in cases when passing in several variables, or worse, functions.

To get around this obstacle, one can use injectJs(filename) instead.

```<code>page.open(url, function() {
    if ( webpage.injectJs('my_extra_functionality.js') ) {
        page.evaluate( function() {
            // this code has access to foo and also myFunction();
            console.log(foo);
            console.log(myFunction());
        });
    }
    else {
        console.log("Failed to inject JS");
    }
}
</code>```

Where my_extra_functionality.js is a local file in the same directory:

```<code>var foo = 42;
var myFunction = function(){
    return "Hello world!";
}
</code>```

Title: Pass arguments with page.evaluate

Body:
I'm using PhantomJS page.evaluate() to do some scraping. My problem is that the code I pass to the webkit page is sandboxed, and so has no access to the variables of my main phantom script. This makes it hard make the scraping code generic.

page.open(url, function() {
  var foo = 42;

  page.evaluate(function() {
    // this code has no access to foo
    console.log(foo);
  });
}

How could I push arguments into the page?

Body:
While you can pass arguments into evaluate(function, arg1, arg2, ...), this is often a little cumbersome. Especially in cases when passing in several variables, or worse, functions.

To get around this obstacle, one can use injectJs(filename) instead.

page.open(url, function() {
    if ( webpage.injectJs('my_extra_functionality.js') ) {
        page.evaluate( function() {
            // this code has access to foo and also myFunction();
            console.log(foo);
            console.log(myFunction());
        });
    }
    else {
        console.log("Failed to inject JS");
    }
}

Where my_extra_functionality.js is a local file in the same directory:

var foo = 42;
var myFunction = function(){
    return "Hello world!";
}


问:
Business Intelligence: Live reports from MySQL
I wanted to create a (nearly) live dashboard from MySQL databases I tried PowerBI, SSRS and other similar tools but they were not as fast as I wanted. What I have in mind is the data to be updated every 1 minute or even less. Is it possible? and are there any free (or inexpensive) tools for this?

Edit: I want to build a wallboard to show some data on a big TV screen. I need it to be real-time. I tried SSRS autorefresh as well but it has a loading sign and very slow, plus PowerBI uses Azure which is very complex to configure and blocked for my country.

答:
This is a topic which has many more layers than to ask which tool is best for this case.

You have to consider

Velocity

Veracity

Variety

Kind

Use Case

of the data. Sure, this is usually only being recounted if talking about Big Data, but will give you a feeling about the size and complexity of data.

Loading

Is the data being loaded and you "just" use it? Or do you also need to load it realtime or near-realtime (for clarification read this answer here)?

Polling/Pushing

Do you want to poll data every x seconds or minutes? Or do you want to work event based? What are the requirements which will need you to show data this fast?

Use case

Do you want to show financial data? Do you need to show data about error and system logs of servers and applications? Do you want to generate insights as soon as a visitor of a webpage is making a request?

Conclusion

When thinking about those questions, keep in mind this should just be a hint to go into one direction or another. Depending on the data and the use case, you might use an ELK stack (for logs), Power BI (for financial data) or even some scripts (for billing).


问:
Action Mailer Not delivering Emails - MailCatcher and sendmail
I am using Rails 5. I have the following configurations in my config/environments/development.rb and config/environments/staging.rb.

config/environments/development.rb

```<code>config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = { address: "localhost", port: 1025 }
</code>```

When I call the method that sends email, I get the following output.

```<code>Rendering mailer/consolidated_s3_storage_report.html.erb
Rendered mailer/consolidated_s3_storage_report.html.erb (0.4ms)
Mailer#consolidated_s3_storage_report: processed outbound mail in 17668.1ms
 => #<Mail::Message:86763960, Multipart: true, Headers: <From: mcds@sheridan.com>, <To: mcds.support@sheridan.com>, <Subject: 2017 July - S3 Storage Report>, <Mime-Version: 1.0>, <Content-Type: multipart/mixed; boundary="--==_mimepart_595c962cc36fb_1be1b2198436941"; charset=UTF-8>>
</code>```

But email is not delivered to my gmail. The 'from' address is 'default from' from which all other emails are sent. Please clarify why my emails are not delivered.

答:
Following is the configuration for send mail to gmail:

config/environments/development.rb

```<code>config.action_mailer.default_url_options = { :host => 'localhost:3000' }
config.action_mailer.delivery_method = :smtp

config.action_mailer.smtp_settings = {
      :address => "smtp.gmail.com",
      :port => 587,
      :domain => "gmail.com",
      :user_name => "user@gmail.com", #your gmail id
      :password => "password", #your gmail password
      :authentication => "plain",
      :enable_starttls_auto => true
}
</code>```

Body:
I am using Rails 5. I have the following configurations in my config/environments/development.rb and config/environments/staging.rb.

config/environments/development.rb

config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = { address: "localhost", port: 1025 }

When I call the method that sends email, I get the following output.

Rendering mailer/consolidated_s3_storage_report.html.erb
Rendered mailer/consolidated_s3_storage_report.html.erb (0.4ms)
Mailer#consolidated_s3_storage_report: processed outbound mail in 17668.1ms
 => #<Mail::Message:86763960, Multipart: true, Headers: <From: mcds@sheridan.com>, <To: mcds.support@sheridan.com>, <Subject: 2017 July - S3 Storage Report>, <Mime-Version: 1.0>, <Content-Type: multipart/mixed; boundary="--==_mimepart_595c962cc36fb_1be1b2198436941"; charset=UTF-8>>

But email is not delivered to my gmail. The 'from' address is 'default from' from which all other emails are sent. Please clarify why my emails are not delivered.

Body:
Following is the configuration for send mail to gmail:

config/environments/development.rb

config.action_mailer.default_url_options = { :host => 'localhost:3000' }
config.action_mailer.delivery_method = :smtp

config.action_mailer.smtp_settings = {
      :address => "smtp.gmail.com",
      :port => 587,
      :domain => "gmail.com",
      :user_name => "user@gmail.com", #your gmail id
      :password => "password", #your gmail password
      :authentication => "plain",
      :enable_starttls_auto => true
}


问:
python module using boost python is empty?
I am trying to learn the boost python API to create my own python(3.6) module.  I am able to successfully compile the following c++ code and get the resulting pythonTest.dll that I am generating.

```<code>#define BOOST_ALL_DYN_LINK
#include <boost/python.hpp>
#include <string>

const std::string hello_world(void)
{
    return std::string("hello world!\n");
}

BOOST_PYTHON_MODULE(pythonTest)
{
    namespace python = boost::python;

    python::def("hello_world", hello_world);
}
</code>```

I then copy the pythonTest.dll to my module folder that looks like the following.  (I rename the pythonTest.dll to pythonTest.pyd)

```<code>pythonTest\
    __init__.py
    pythonTest.pyd
</code>```

When I execute python, it will import the module but it does not find my hello_world function:

```<code>Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import pythonTest
>>> pythonTest.hello_world()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
**AttributeError: module 'pythonTest' has no attribute 'hello_world'**

>>> help(pythonTest)
Help on package pythonTest:

NAME
    pythonTest

PACKAGE CONTENTS
    pythonTest

FILE
    <...>\pythontest\__init__.py

>>> dir(pythonTest)
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__','__name__', '__package__', '__path__', '__spec__']
>>>
</code>```

What am I missing?
Thanks.

EDIT:
This is the output from the visual studio build:

```<code>1>------ Rebuild All started: Project: pythonTest, Configuration: Release x64 ------
1>Build started 7/10/2017 2:49:53 PM.
1>InitializeBuildStatus:
1>  Creating "x64\Release\pythonTest.tlog\unsuccessfulbuild" because "AlwaysCreate" was specified.
1>ClCompile:
1>  pythonTest.cpp
1>G:\DataBackup\dev-vc13\3rdParty\boost_1_64_0\boost/python/detail/caller.hpp(55): warning C4244: 'return' : conversion from 'Py_ssize_t' to 'unsigned int', possible loss of data
1>Link:
1>     Creating library G:\DataBackup\dev-vc13\temp\pythonTest\x64\Release\pythonTest.lib and object G:\DataBackup\dev-vc13\temp\pythonTest\x64\Release\pythonTest.exp
1>  Generating code
1>  Finished generating code
1>  pythonTest.vcxproj -> G:\DataBackup\dev-vc13\temp\pythonTest\x64\Release\pythonTest.dll
1>PostBuildEvent:
1>          1 file(s) copied.
1>FinalizeBuildStatus:
1>  Deleting file "x64\Release\pythonTest.tlog\unsuccessfulbuild".
1>  Touching "x64\Release\pythonTest.tlog\pythonTest.lastbuildstate".
1>
1>Build succeeded.
1>
1>Time Elapsed 00:00:04.21
========== Rebuild All: 1 succeeded, 0 failed, 0 skipped ==========
</code>```

答:
try using the dir() function

```<code>>>> dir(pythonTest)
</code>```

that will show u the available methods and functions
of packages

Body:
I am trying to learn the boost python API to create my own python(3.6) module.  I am able to successfully compile the following c++ code and get the resulting pythonTest.dll that I am generating.

#define BOOST_ALL_DYN_LINK
#include <boost/python.hpp>
#include <string>

const std::string hello_world(void)
{
    return std::string("hello world!\n");
}

BOOST_PYTHON_MODULE(pythonTest)
{
    namespace python = boost::python;

    python::def("hello_world", hello_world);
}

I then copy the pythonTest.dll to my module folder that looks like the following.  (I rename the pythonTest.dll to pythonTest.pyd)

pythonTest\
    __init__.py
    pythonTest.pyd

When I execute python, it will import the module but it does not find my hello_world function:

Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import pythonTest
>>> pythonTest.hello_world()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
**AttributeError: module 'pythonTest' has no attribute 'hello_world'**

>>> help(pythonTest)
Help on package pythonTest:

NAME
    pythonTest

PACKAGE CONTENTS
    pythonTest

FILE
    <...>\pythontest\__init__.py

>>> dir(pythonTest)
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__','__name__', '__package__', '__path__', '__spec__']
>>>

What am I missing?
Thanks.

EDIT:
This is the output from the visual studio build:

1>------ Rebuild All started: Project: pythonTest, Configuration: Release x64 ------
1>Build started 7/10/2017 2:49:53 PM.
1>InitializeBuildStatus:
1>  Creating "x64\Release\pythonTest.tlog\unsuccessfulbuild" because "AlwaysCreate" was specified.
1>ClCompile:
1>  pythonTest.cpp
1>G:\DataBackup\dev-vc13\3rdParty\boost_1_64_0\boost/python/detail/caller.hpp(55): warning C4244: 'return' : conversion from 'Py_ssize_t' to 'unsigned int', possible loss of data
1>Link:
1>     Creating library G:\DataBackup\dev-vc13\temp\pythonTest\x64\Release\pythonTest.lib and object G:\DataBackup\dev-vc13\temp\pythonTest\x64\Release\pythonTest.exp
1>  Generating code
1>  Finished generating code
1>  pythonTest.vcxproj -> G:\DataBackup\dev-vc13\temp\pythonTest\x64\Release\pythonTest.dll
1>PostBuildEvent:
1>          1 file(s) copied.
1>FinalizeBuildStatus:
1>  Deleting file "x64\Release\pythonTest.tlog\unsuccessfulbuild".
1>  Touching "x64\Release\pythonTest.tlog\pythonTest.lastbuildstate".
1>
1>Build succeeded.
1>
1>Time Elapsed 00:00:04.21
========== Rebuild All: 1 succeeded, 0 failed, 0 skipped ==========

Body:
try using the dir() function

>>> dir(pythonTest)

that will show u the available methods and functions
of packages


问:
preventing double clicks on button with ajax call
I noticed my users sometimes click the buttons twice, maybe no one told them one click is enough.

What's the best way to prevent the double-click?
I basically hide the button and show a "loading" gif, but that apparently is not enough...

答:
Another example using a flag</p>

```<code><!DOCTYPE html>
<html>
    <head>
        <meta charset=utf-8 />
        <title>test dbl click</title>
    </head>
    <body>
        <button id="btn1">Click Away</button>
        <div id="out"></div>
        <script type="text/javascript">

            function addMessage( msg ){
                document.getElementById("out").innerHTML += (new Date().toTimeString()) + " : " + msg + "<br/><br/>";
            }

            function singleClick(){
                addMessage( "single");
            }

            function addDoubleClickProtection( element, fncToCall ){
                var isClicked = false;
                var timer = null;
                element.onclick = function(){
                    if(!isClicked){
                        isClicked = true;
                        timer = window.setTimeout( function(){ isClicked = false; }, 200);
                        return fncToCall();
                    }
                }
            }

            addDoubleClickProtection( document.getElementById("btn1"), singleClick );

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

Body:
Another example using a flag

<!DOCTYPE html>
<html>
    <head>
        <meta charset=utf-8 />
        <title>test dbl click</title>
    </head>
    <body>
        <button id="btn1">Click Away</button>
        <div id="out"></div>
        <script type="text/javascript">

            function addMessage( msg ){
                document.getElementById("out").innerHTML += (new Date().toTimeString()) + " : " + msg + "<br/><br/>";
            }

            function singleClick(){
                addMessage( "single");
            }

            function addDoubleClickProtection( element, fncToCall ){
                var isClicked = false;
                var timer = null;
                element.onclick = function(){
                    if(!isClicked){
                        isClicked = true;
                        timer = window.setTimeout( function(){ isClicked = false; }, 200);
                        return fncToCall();
                    }
                }
            }

            addDoubleClickProtection( document.getElementById("btn1"), singleClick );

        </script>
    </body>
</html>


问:
Action bar moving down while replacing with fragment
I am adding a fragment to activity, and then i am replacing that fragment with the second fragment.After replacing the second fragment action bar is slightly moving down like this

My Activity code

```<code>public class MyActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.meetinglist_activity);
    Fragment first_fragment = new FirstFragment();
    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    ft.add(R.id.content_frame, first_fragment).commit();
     }
</code>```

Replacing second fragment in the first fragment's button click

```<code>public class Firstfragment extends Fragment  {

FloatingActionButton new_fab;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View list_view=inflater.inflate(R.layout.meetingslist_fragment,container,false);
    new_fab=(FloatingActionButton)list_view.findViewById(R.id.meeting_new);
    new_fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Fragment second_fragment = new SecondFragment();
            FragmentTransaction ft =getActivity().getSupportFragmentManager().beginTransaction();
            ft.replace(R.id.content_frame, second_fragment).commit();
  }
</code>```

Activity layout

```<code> <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical" android:layout_width="match_parent"
 android:layout_height="match_parent">
 <FrameLayout
    android:id="@+id/content_frame"
    android:layout_width="match_parent"
    android:layout_height="match_parent"></FrameLayout>
   </LinearLayout>
</code>```

Fragment's Xml

```<code><!--First Layout-->
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">

<android.support.design.widget.FloatingActionButton
    android:id="@+id/meeting_new"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/fab_margin"
    android:src="@android:drawable/ic_dialog_email" />

    </android.support.design.widget.CoordinatorLayout>

 <!--Second Layout-->

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="Large Text"
    android:gravity="center"
    android:id="@+id/textView"
    android:layout_gravity="center_horizontal" />
    </LinearLayout>
</code>```

I am using  android.support.v4.app.Fragment;

I am using Android Studio version2.0 and latest API levels.

Can anybody help me? Thanks in advance.

答:
Just change this line

android:fitsSystemWindows="true"

to

android:fitsSystemWindows="false"

I'm sure your problem will be solved

Body:
I am adding a fragment to activity, and then i am replacing that fragment with the second fragment.After replacing the second fragment action bar is slightly moving down like this

My Activity code

public class MyActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.meetinglist_activity);
    Fragment first_fragment = new FirstFragment();
    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    ft.add(R.id.content_frame, first_fragment).commit();
     }

Replacing second fragment in the first fragment's button click

public class Firstfragment extends Fragment  {

FloatingActionButton new_fab;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View list_view=inflater.inflate(R.layout.meetingslist_fragment,container,false);
    new_fab=(FloatingActionButton)list_view.findViewById(R.id.meeting_new);
    new_fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Fragment second_fragment = new SecondFragment();
            FragmentTransaction ft =getActivity().getSupportFragmentManager().beginTransaction();
            ft.replace(R.id.content_frame, second_fragment).commit();
  }

Activity layout

 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical" android:layout_width="match_parent"
 android:layout_height="match_parent">
 <FrameLayout
    android:id="@+id/content_frame"
    android:layout_width="match_parent"
    android:layout_height="match_parent"></FrameLayout>
   </LinearLayout>

Fragment's Xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">

<android.support.design.widget.FloatingActionButton
    android:id="@+id/meeting_new"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/fab_margin"
    android:src="@android:drawable/ic_dialog_email" />

    </android.support.design.widget.CoordinatorLayout>

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="Large Text"
    android:gravity="center"
    android:id="@+id/textView"
    android:layout_gravity="center_horizontal" />
    </LinearLayout>

I am using  android.support.v4.app.Fragment;

I am using Android Studio version2.0 and latest API levels.

Can anybody help me? Thanks in advance.


问:
Using pointers and structs
Hello i'm not sure if I'm understand the following piece of code. I would glad if someone could read my explanations and correct me if I'm wrong.

 So first of all I'm declaring a struct with three arrays of char and an integer.

```<code>struct Employee
{
    char last[16];
    char first[11];
    char title[16];
    int salary;
};
</code>```

 After that I declare a function which takes three pointers to char and an integer value. This function uses malloc() and sizeof() to create a struct on the heap. Now this creations of the object on the heap is not really clear to me. When I use struct Employee* p = malloc(sizeof(struct Employee)), what happens there exactly?
 What happens when I use the function struct Employee* createEmployee (char* last, char* first, char* title, int salary) several times with different input. I know that I will get back a pointer p but isn't that the same pointer to the same struct on the heap. So do I rewrite the information on the heap, when I use the function several times? Or does it always create a new object in a different memory space?

```<code>struct Employee* createEmployee(char*, char*, char*, int);

struct Employee* createEmployee(char* last, char* first, char* title, int salary)
{
    struct Employee* p = malloc(sizeof(struct Employee));
    if (p != NULL)
    {
        strcpy(p->last, last);
        strcpy(p->first, first);
        strcpy(p->title, title);
        p->salary = salary;
    }
    return p;
}
</code>```

I would be glad if someone could explain it to me. Thank you very much.

答:
Your first question is a question about malloc. You might get better results searching for "How does malloc work?" The answer is different for different operating systems and C libraries.

The createEmployee function creates an all-new struct Employee every time it is called.

I also see that createEmployee is written in a very dangerous way. No checking is done to ensure that the strings fit into their destinations before calling strcpy. This is how buffer overflows are created.

Title: Using pointers and structs

Body:
Hello i'm not sure if I'm understand the following piece of code. I would glad if someone could read my explanations and correct me if I'm wrong.

 So first of all I'm declaring a struct with three arrays of char and an integer.

struct Employee
{
    char last[16];
    char first[11];
    char title[16];
    int salary;
};

 After that I declare a function which takes three pointers to char and an integer value. This function uses malloc() and sizeof() to create a struct on the heap. Now this creations of the object on the heap is not really clear to me. When I use struct Employee* p = malloc(sizeof(struct Employee)), what happens there exactly?
 What happens when I use the function struct Employee* createEmployee (char* last, char* first, char* title, int salary) several times with different input. I know that I will get back a pointer p but isn't that the same pointer to the same struct on the heap. So do I rewrite the information on the heap, when I use the function several times? Or does it always create a new object in a different memory space?

struct Employee* createEmployee(char*, char*, char*, int);

struct Employee* createEmployee(char* last, char* first, char* title, int salary)
{
    struct Employee* p = malloc(sizeof(struct Employee));
    if (p != NULL)
    {
        strcpy(p->last, last);
        strcpy(p->first, first);
        strcpy(p->title, title);
        p->salary = salary;
    }
    return p;
}

I would be glad if someone could explain it to me. Thank you very much.


问:
Regex replace any number of matches at the start of the line
I have text with this structure:

```<code>1.  Text1
2.  Text 2. It has a number with a dot.
3.  1.   Text31
</code>```

I want to get this text:

```<code># Text1
# Text 2. It has a number with a dot. (notice that this number did not get replaced)
## Text31
</code>```

I tried doing the following but it does not work

```<code>var pattern = @"^(\s*\d+\.\s*)+";
var replaced = Regex.Replace(str, pattern, "#", RegexOptions.Multiline);
</code>```

Basically, it should start matching at the start of every line and replace every matched group with # symbol. Currently, if more than one group is matched, everything is replaced by a single # symbol. Pattern I am using is probably incorrect, can anyone come up with a solution?

答:
Try

```<code>(?<![a-z].*)\s*\d+\.
</code>```

It looks for a sequence of digits \d+ followed by a dot \. preceded by any number of white space characters \s*. This, in turn, must not be preceded by a letter on the line, checked by a negative look-behind (?<![a-z].*) in the beginning of the regex.

Here at RegEx Storm.

Body:
I have text with this structure:

1.  Text1
2.  Text 2. It has a number with a dot.
3.  1.   Text31

I want to get this text:

# Text1
# Text 2. It has a number with a dot. (notice that this number did not get replaced)
## Text31

I tried doing the following but it does not work

var pattern = @"^(\s*\d+\.\s*)+";
var replaced = Regex.Replace(str, pattern, "#", RegexOptions.Multiline);

Basically, it should start matching at the start of every line and replace every matched group with # symbol. Currently, if more than one group is matched, everything is replaced by a single # symbol. Pattern I am using is probably incorrect, can anyone come up with a solution?

Body:
Try

(?<![a-z].*)\s*\d+\.

It looks for a sequence of digits \d+ followed by a dot \. preceded by any number of white space characters \s*. This, in turn, must not be preceded by a letter on the line, checked by a negative look-behind (?<![a-z].*) in the beginning of the regex.

Here at RegEx Storm.


问:
How to import a module in a subdirectory that imports another module in that same subdirectory?
In a module that I import, I'm trying to import another module, that is located in that same directory.

My files look something like this...

```<code>project
├── main.py
└── app
    └── foo.py
    └── bar.py
</code>```

main.py

```<code>import app.foo as Foo
</code>```

foo.py

```<code>import bar
</code>```

So now, when I run main.py, I get a

```<code>ModuleNotFoundError: No module named 'bar'
</code>```

There are so many similar questions, but none of them seem to be my exact situation.

How can I get this to work?

答:
Imports from .. or . should work:

```<code>from . import bar
</code>```

remember to add __init__.py (empty file) inside app directory.

Edit: it could be done only if using foo and bar as modules. E.g. you would not be able to run "python foo.py" or "python foo.bar". Outside of app directory, you could try the code with:

```<code>python -m app.foo
</code>```

(mind the lack of .py extension)

Body:
In a module that I import, I'm trying to import another module, that is located in that same directory.

My files look something like this...

project
├── main.py
└── app
    └── foo.py
    └── bar.py

main.py

import app.foo as Foo

foo.py

import bar

So now, when I run main.py, I get a

ModuleNotFoundError: No module named 'bar'

There are so many similar questions, but none of them seem to be my exact situation.

How can I get this to work?

Body:
Imports from .. or . should work:

from . import bar

remember to add __init__.py (empty file) inside app directory.

Edit: it could be done only if using foo and bar as modules. E.g. you would not be able to run "python foo.py" or "python foo.bar". Outside of app directory, you could try the code with:

python -m app.foo

(mind the lack of .py extension)