问:
How to remove an entity class in a Symfony2 project
When we initially designed our project, we had a couple of entities that to date are unused (and we don't plan to implement them in the near future). Ergo I want to remove them from my project. I would proceed like this (all steps manually performed):

Remove all relations from my currently used entities.

Delete the doctrime ORM file src/Resources/config/doctrine

Delete the class PHP file from src/Entity

Remove the table from the database

What I would like to know: Are there any routines (e.g. console commands) that may support this procedure? For example, if I run

```<code>php app/console doctrine:schema:update --dump-sql
</code>```

after having removed all relations and deleted the files, that I get the SQL statement that removes the according table(s)?

答:
Once you have removed the entities from your code, you can use the following console command to drop the tables:

```<code>php bin/console doctrine:schema:update --complete --dump-sql
</code>```

Note the use of the --complete option.

Here are the relevant parts from the doctrine:schema:update help text:

Options:

--complete        If defined, all assets of the database which are not relevant to the current metadata will be dropped.

    [...]

Help:

[...]

Finally, be aware that if the --complete option is passed, this task will drop all database assets (e.g. tables, etc) that are not described by the current metadata. In other words, without this option, this task leaves untouched any "extra" tables that exist in the database, but which aren't described by any metadata.

Hint: If you have a database with tables that should not be managed by the ORM, you can use a DBAL functionality to filter the tables and sequences down on a global level:

```<code>$config->setFilterSchemaAssetsExpression($regexp);
</code>```

Body:
When we initially designed our project, we had a couple of entities that to date are unused (and we don't plan to implement them in the near future). Ergo I want to remove them from my project. I would proceed like this (all steps manually performed):

Remove all relations from my currently used entities.

Delete the doctrime ORM file src/Resources/config/doctrine

Delete the class PHP file from src/Entity

Remove the table from the database

What I would like to know: Are there any routines (e.g. console commands) that may support this procedure? For example, if I run

php app/console doctrine:schema:update --dump-sql

after having removed all relations and deleted the files, that I get the SQL statement that removes the according table(s)?

Body:
Once you have removed the entities from your code, you can use the following console command to drop the tables:

php bin/console doctrine:schema:update --complete --dump-sql

Note the use of the --complete option.

Here are the relevant parts from the doctrine:schema:update help text:

Options:

--complete        If defined, all assets of the database which are not relevant to the current metadata will be dropped.

    [...]

Help:

[...]

Finally, be aware that if the --complete option is passed, this task will drop all database assets (e.g. tables, etc) that are not described by the current metadata. In other words, without this option, this task leaves untouched any "extra" tables that exist in the database, but which aren't described by any metadata.

Hint: If you have a database with tables that should not be managed by the ORM, you can use a DBAL functionality to filter the tables and sequences down on a global level:

$config->setFilterSchemaAssetsExpression($regexp);


来源: stackexchange

问:
Interesting Applications of Interfaces
Why are interfaces useful?

Actually, I have a [small] idea of why interfaces are useful/necessary but...

What are [interesting or realistic] applications of interfaces?

答:
An interface (or an abstract class) is a contract you pass with the compiler. This contract says :

-- Well, compiler, make sure that all the classes that will implement this will provide at least everything that is defined in this interface !

With this insurance, you can then write methods that manipulate objects of any class implementing this interface :

```<code> void myGenericMethod( IAnInterface genericObject )
</code>```

myGenericMethod method can use any member of the interface IAnInterface. It will never throw a runtime error (any missing member will have been caught by the compiler).

Utility : to give some common behavior to different objects. You may want for example to be able to call a method named GetID on any of your objects, being it a BankAccount, a ComputerCluster or an AirplaneTrip.

You will find a lot of useful interface usages in most design patterns. MSDN provides some hints about when you should use an interface here : http://msdn.microsoft.com/en-us/library/27db6csx.aspx

OwnerDisplayName: koldfyre

ContentLicense: CC BY-SA 2.5

Title: Interesting Applications of Interfaces

Body:
An interface (or an abstract class) is a contract you pass with the compiler. This contract says :

-- Well, compiler, make sure that all the classes that will implement this will provide at least everything that is defined in this interface !

With this insurance, you can then write methods that manipulate objects of any class implementing this interface :

 void myGenericMethod( IAnInterface genericObject )

myGenericMethod method can use any member of the interface IAnInterface. It will never throw a runtime error (any missing member will have been caught by the compiler).

Utility : to give some common behavior to different objects. You may want for example to be able to call a method named GetID on any of your objects, being it a BankAccount, a ComputerCluster or an AirplaneTrip.

You will find a lot of useful interface usages in most design patterns. MSDN provides some hints about when you should use an interface here : http://msdn.microsoft.com/en-us/library/27db6csx.aspx

OwnerDisplayName: Sylvain Rodrigue


问:
Netbeans open maven project with pom.yml
I'm trying to load a maven project in netbeans which contains pom.yml instead of pom.xml.

When I go to the directory where the application is present, Netbeans is not recognising it as a project/app. It is showing up as a regular directory. When I click on the directory, it is taking me right inside instead of opening it.

I checked in the plugins repo to see if there are any related plugins, but unfortunately, there aren't any.

Can anyone help me out please?

Thanks

答:
The pom.yml is used by the Polyglot for Maven extension. Netbeans has no support for it.

A working solution is to convert the pom.yml back to pom.xml.

with Maven 3.3.1+ run following command

```<code>mvn io.takari.polyglot:polyglot-translate-plugin:0.1.15:translate \
  -Dinput=pom.xml \
  -Doutput=pom.yml
</code>```

note: Newer versions of the polyglot-translate-plugin have a bug see issue #96. Which lead to the error

```<code>... A required class was missing while executing \
  io.takari.polyglot:polyglot-translate-plugin:0.1.16:translate: \
  org/codehaus/plexus/util/xml/XmlStreamReader
</code>```

ContentLicense: CC BY-SA 3.0

Body:
The pom.yml is used by the Polyglot for Maven extension. Netbeans has no support for it.

A working solution is to convert the pom.yml back to pom.xml.

with Maven 3.3.1+ run following command

mvn io.takari.polyglot:polyglot-translate-plugin:0.1.15:translate \
  -Dinput=pom.xml \
  -Doutput=pom.yml

note: Newer versions of the polyglot-translate-plugin have a bug see issue #96. Which lead to the error

... A required class was missing while executing \
  io.takari.polyglot:polyglot-translate-plugin:0.1.16:translate: \
  org/codehaus/plexus/util/xml/XmlStreamReader


问:
Getting the size of a groupby operation in Pandas
I've been performing a groupby operation on a dataframe I have that aggregates columns together based on the column 'Name':

```<code>Name | As | Bs | Cs   |  Note
Mark   3     4     7     Good
Luke   2     1     12    Well
Mark   5     6     8     Ok
John   1     18    3     Great
</code>```

So in this case, the rows with 'Mark' are aggregated together on columns A,B, and C using this code:

```<code>temp_df = temp_df.groupby(['Name'], as_index=False).agg({'As': np.sum, 'Bs': np.sum,'Cs': np.sum})
</code>```

A thing I need to add in is to do a count on the number of rows that have the same value in 'Name'. This would give me an output like:

```<code>Name | As | Bs | Cs   |  Note   | Count
Mark   8     10    15    Good      2
Luke   2     1     12    Well      1
John   1     18    3     Great     1
</code>```

How do I modify the above line of code to do what I need?

答:
Use first + size and then is necessary rename columns by dict:

```<code>temp_df = temp_df.groupby('Name', sort=False) \
                .agg({'As':np.sum,'Bs':np.sum,'Cs':np.sum,'Note':'first','Name':'size'}) \
                .rename(columns={'Name':'Count'}) \
                .reset_index() \
                .reindex_axis(temp_df.columns.tolist() + ['Count'], axis=1)
print (temp_df)
   Name  As  Bs  Cs   Note  Count
0  Mark   8  10  15   Good      2
1  Luke   2   1  12   Well      1
2  John   1  18   3  Great      1
</code>```

Dont use count, only size or len.

What is the difference between size and count in pandas?

Body:
I've been performing a groupby operation on a dataframe I have that aggregates columns together based on the column 'Name':

Name | As | Bs | Cs   |  Note
Mark   3     4     7     Good
Luke   2     1     12    Well
Mark   5     6     8     Ok
John   1     18    3     Great

So in this case, the rows with 'Mark' are aggregated together on columns A,B, and C using this code:

temp_df = temp_df.groupby(['Name'], as_index=False).agg({'As': np.sum, 'Bs': np.sum,'Cs': np.sum})

A thing I need to add in is to do a count on the number of rows that have the same value in 'Name'. This would give me an output like:

Name | As | Bs | Cs   |  Note   | Count
Mark   8     10    15    Good      2
Luke   2     1     12    Well      1
John   1     18    3     Great     1

How do I modify the above line of code to do what I need?

Body:
Use first + size and then is necessary rename columns by dict:

temp_df = temp_df.groupby('Name', sort=False) \
                .agg({'As':np.sum,'Bs':np.sum,'Cs':np.sum,'Note':'first','Name':'size'}) \
                .rename(columns={'Name':'Count'}) \
                .reset_index() \
                .reindex_axis(temp_df.columns.tolist() + ['Count'], axis=1)
print (temp_df)
   Name  As  Bs  Cs   Note  Count
0  Mark   8  10  15   Good      2
1  Luke   2   1  12   Well      1
2  John   1  18   3  Great      1

Dont use count, only size or len.

What is the difference between size and count in pandas?


问:
how to get previous value of textbox in jquery on change event

 $(".whitebox").on('change', function () {
       var previousAmt = $(this).data("old"); //  i want previous value
        var id = this.id;
        var slpitid = id.split("_");

        var checkboxid = "#chck_" + slpitid[0];
        if ($(checkboxid).is(':checked')) {
            var tipFlag = true;
        }
        else {
            var tipFlag = false;
        }

        if (tipFlag === true)
        {
            $("#amounttipchange").modal('show');
        }
        //alert(previousAmount);
    });```

i want to store previous value on change event how can i perform in jquery  i am not able to store value using $(this).data("old"); any help will be appreciated

答:
Try this:

```<code>$("#checkboxid").on('click',function(){
   $(this).data('old',$(this).val());
});
</code>```

And then use your change event.

Body:
 $(".whitebox").on('change', function () {
       var previousAmt = $(this).data("old"); //  i want previous value
        var id = this.id;
        var slpitid = id.split("_");

        var checkboxid = "#chck_" + slpitid[0];
        if ($(checkboxid).is(':checked')) {
            var tipFlag = true;
        }
        else {
            var tipFlag = false;
        }

        if (tipFlag === true)
        {
            $("#amounttipchange").modal('show');
        }
        //alert(previousAmount);
    });

i want to store previous value on change event how can i perform in jquery  i am not able to store value using $(this).data("old"); any help will be appreciated

Body:
Try this:

$("#checkboxid").on('click',function(){
   $(this).data('old',$(this).val());
});

And then use your change event.


问:
How can I make a dynamic width for elements based on the screen size?
Here is my code:

.container{
  border:1px solid;
  width: 70%;
}

.el {
  border: 1px solid red;
  display: inline-block;
  min-width: 250px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="el">one</div>
  <div class="el">two</div>
  <div class="el">three</div>
  <div class="el">four</div>
  <div class="el">five</div>
  <div class="el">six</div>
  <div class="el">seven</div>
  <div class="el">eight</div>
</div></code>```

Please run the code snippet above, click on Full page button and resize the page. I want to divide div.container to equal parts.

So if there are three elements (div.el) in a row, then the width of them should be 33%. If two elements in a row, then the width should be 50%.

How can I do that? Noted that I don't want to use any framework like Bootstrap.

答:
.container{
  border:1px solid;
  width: 70%;
  display: table;
  table-layout: fixed;
}

.el {
  border: 1px solid red;
  min-width: auto;
  display: table-cell;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="el">one</div>
  <div class="el">two</div>
  <div class="el">three</div>
  <div class="el">four</div>
  <div class="el">five</div>
  <div class="el">six</div>
  <div class="el">seven</div>
  <div class="el">eight</div>
</div></code>```

Body:
Here is my code:

.container{
  border:1px solid;
  width: 70%;
}

.el {
  border: 1px solid red;
  display: inline-block;
  min-width: 250px;
}

one

two

three

four

five

six

seven

eight

Please run the code snippet above, click on Full page button and resize the page. I want to divide div.container to equal parts.

So if there are three elements (div.el) in a row, then the width of them should be 33%. If two elements in a row, then the width should be 50%.

How can I do that? Noted that I don't want to use any framework like Bootstrap.

Body:
.container{
  border:1px solid;
  width: 70%;
  display: table;
  table-layout: fixed;
}

.el {
  border: 1px solid red;
  min-width: auto;
  display: table-cell;
}

<div class="container">
  <div class="el">one</div>
  <div class="el">two</div>
  <div class="el">three</div>
  <div class="el">four</div>
  <div class="el">five</div>
  <div class="el">six</div>
  <div class="el">seven</div>
  <div class="el">eight</div>
</div>


问:
Error starting up a network. Nodes in different VM - Failed connecting to orderer0.tec.com:7050 , error: context deadline exceeded
I'm starting up a network, which will have 3 peers and an orderer. I have 4 different Virtual Machines, one for each node.

I follow the Getting Started manual for Hyperledger Fabric. I execute all the steps without any problem. However, after executing the following command peer channel join -b channeldemo.block, I start getting some erros. It seems to me that the previous command is generated well, because I get the following logs:

```<code>2017-06-27 08:26:23.247 UTC [channelCmd] executeJoin -> INFO 00a Peer joined the channel!
2017-06-27 08:26:23.247 UTC [main] main -> INFO 00b Exiting.....
</code>```

But then, after that, I get the following logs in the peer:

```<code>peer0.proveedor.com    | 2017-06-27 08:26:29.241 UTC [deliveryClient] StartDeliverForChannel -> DEBU 2d8 This peer will pass blocks from orderer service to other peers for channel canaltraza
peer0.proveedor.com    | 2017-06-27 08:26:32.242 UTC [ConnProducer] NewConnection -> ERRO 2d9 Failed connecting to orderer0.tec.com:7050 , error: context deadline exceeded
peer0.proveedor.com    | 2017-06-27 08:26:32.242 UTC [deliveryClient] connect -> ERRO 2da Failed obtaining connection: Could not connect to any of the endpoints: [orderer0.tec.com:7050]
</code>```

However, if I start up the network in my localhost, I don't get any error log. After one Peer joins the channel, I get the following messages (there are messages from the peer and the orderer):

```<code>peer0.proveedor.com | 2017-06-29 11:17:16.027 UTC [deliveryClient] StartDeliverForChannel -> DEBU 2d8 This peer will pass blocks from orderer service to other peers for channel canaltraza
orderer0.tec.com | 2017-06-29 11:17:16.031 UTC [orderer/main] Deliver -> DEBU c22 Starting new Deliver handler
orderer0.tec.com | 2017-06-29 11:17:16.031 UTC [orderer/common/deliver] Handle -> DEBU c23 Starting new deliver loop
orderer0.tec.com | 2017-06-29 11:17:16.031 UTC [orderer/common/deliver] Handle -> DEBU c24 Attempting to read seek info message
orderer0.tec.com | 2017-06-29 11:17:16.032 UTC [policies] GetPolicy -> DEBU c25 Returning policy Readers for evaluation
orderer0.tec.com | 2017-06-29 11:17:16.032 UTC [cauthdsl] func1 -> DEBU c26 0xc42010d530 gate 1498735036032103426 evaluation starts
orderer0.tec.com | 2017-06-29 11:17:16.032 UTC [cauthdsl] func2 -> DEBU c27 0xc42010d530 signed by 0 principal evaluation starts (used [false])
orderer0.tec.com | 2017-06-29 11:17:16.032 UTC [cauthdsl] func2 -> DEBU c28 0xc42010d530 processing identity 0 with bytes of 0a0950726f766565646f7212f4052d2d2d2d2d424547494e202d2d2d2d2d0a4d49494345444343416265674177494241674952414c595177764d593852483533594d4a7970767977457777436759494b6f5a497a6a3045417749776254454c0a4d416b474131554542684d4356564d78457a415242674e5642416754436b4e6862476c6d62334a7561574578466a415542674e564241635444564e68626942470a636d467559326c7a59323878466a415542674e5642416f544458427962335a6c5a5752766369356a623230784754415842674e5642414d5445474e684c6e42790a62335a6c5a5752766369356a623230774868634e4d5463774e6a49354d4467304d7a41335768634e4d6a63774e6a49334d4467304d7a4133576a42594d5173770a435159445651514745774a56557a45544d4245474131554543424d4b5132467361575a76636d3570595445574d4251474131554542784d4e5532467549455a790a5957356a61584e6a627a45634d426f474131554541784d546347566c636a417563484a76646d566c5a4739794c6d4e766254425a4d424d4742797147534d34390a4167454743437147534d34394177454841304941424b5137324e78684f744648354b62666876744e3068624a484f714d6c56734c37695262794e75626a5264630a785039784554507153313169492b33724b46336f4e622b7679777756555058376335653877616f2b6a46366a5454424c4d41344741315564447745422f7751450a417749486744414d42674e5648524d4241663845416a41414d437347413155644977516b4d434b4149496631483567312b535164576369307753386b536136370a45305a4d4651516944776f426a466978786d48434d416f4743437147534d343942414d43413063414d4551434945497a7451796f476e512f6d74334c685561640a3563585172415a6b5978656b4777524f655947326e6a56694169417a6449472f4f2f4a4f57466e566c50727569567332734844724a676356496f70446a4d76360a64696f4e31773d3d0a2d2d2d2d2d454e44202d2d2d2d2d0a
orderer0.tec.com | 2017-06-29 11:17:16.032 UTC [msp/identity] newIdentity -> DEBU c29 Creating identity instance for ID &{Proveedor 0bf7d673709e14cef044e09025b8511a590e2c758697ae07f2eef5283757787d}
orderer0.tec.com | 2017-06-29 11:17:16.032 UTC [cauthdsl] func2 -> DEBU c2a 0xc42010d530 identity 0 does not satisfy principal: The identity is a member of a different MSP (expected Usuario, got Proveedor
orderer0.tec.com | 2017-06-29 11:17:16.032 UTC [cauthdsl] func2 -> DEBU c2b 0xc42010d530 principal evaluation fails
orderer0.tec.com | 2017-06-29 11:17:16.032 UTC [cauthdsl] func1 -> DEBU c2c 0xc42010d530 gate 1498735036032103426 evaluation fails
orderer0.tec.com | 2017-06-29 11:17:16.032 UTC [cauthdsl] func1 -> DEBU c2d 0xc42010d530 gate 1498735036032902403 evaluation starts
orderer0.tec.com | 2017-06-29 11:17:16.032 UTC [cauthdsl] func2 -> DEBU c2e 0xc42010d530 signed by 0 principal evaluation starts (used [false])
orderer0.tec.com | 2017-06-29 11:17:16.032 UTC [cauthdsl] func2 -> DEBU c2f 0xc42010d530 processing identity 0 with bytes of 0a0950726f766565646f7212f4052d2d2d2d2d424547494e202d2d2d2d2d0a4d49494345444343416265674177494241674952414c595177764d593852483533594d4a7970767977457777436759494b6f5a497a6a3045417749776254454c0a4d416b474131554542684d4356564d78457a415242674e5642416754436b4e6862476c6d62334a7561574578466a415542674e564241635444564e68626942470a636d467559326c7a59323878466a415542674e5642416f544458427962335a6c5a5752766369356a623230784754415842674e5642414d5445474e684c6e42790a62335a6c5a5752766369356a623230774868634e4d5463774e6a49354d4467304d7a41335768634e4d6a63774e6a49334d4467304d7a4133576a42594d5173770a435159445651514745774a56557a45544d4245474131554543424d4b5132467361575a76636d3570595445574d4251474131554542784d4e5532467549455a790a5957356a61584e6a627a45634d426f474131554541784d546347566c636a417563484a76646d566c5a4739794c6d4e766254425a4d424d4742797147534d34390a4167454743437147534d34394177454841304941424b5137324e78684f744648354b62666876744e3068624a484f714d6c56734c37695262794e75626a5264630a785039784554507153313169492b33724b46336f4e622b7679777756555058376335653877616f2b6a46366a5454424c4d41344741315564447745422f7751450a417749486744414d42674e5648524d4241663845416a41414d437347413155644977516b4d434b4149496631483567312b535164576369307753386b536136370a45305a4d4651516944776f426a466978786d48434d416f4743437147534d343942414d43413063414d4551434945497a7451796f476e512f6d74334c685561640a3563585172415a6b5978656b4777524f655947326e6a56694169417a6449472f4f2f4a4f57466e566c50727569567332734844724a676356496f70446a4d76360a64696f4e31773d3d0a2d2d2d2d2d454e44202d2d2d2d2d0a
orderer0.tec.com | 2017-06-29 11:17:16.033 UTC [msp/identity] newIdentity -> DEBU c30 Creating identity instance for ID &{Proveedor 0bf7d673709e14cef044e09025b8511a590e2c758697ae07f2eef5283757787d}
orderer0.tec.com | 2017-06-29 11:17:16.033 UTC [msp] SatisfiesPrincipal -> DEBU c31 Checking if identity satisfies MEMBER role for Proveedor
orderer0.tec.com | 2017-06-29 11:17:16.033 UTC [msp] Validate -> DEBU c32 MSP Proveedor validating identity
orderer0.tec.com | 2017-06-29 11:17:16.033 UTC [cauthdsl] func2 -> DEBU c33 0xc42010d530 principal matched by identity 0
orderer0.tec.com | 2017-06-29 11:17:16.034 UTC [msp/identity] Verify -> DEBU c34 Verify: digest = 00000000 b0 ac 91 ca 2f e9 0d 5e 0d 48 d0 dc 11 06 3b 53 |..../..^.H....;S| orderer0.tec.com | 00000010 a1 d7 f9 d6 2f fe 7d fb 19 2c 90 cb 0f 67 4a 7e |..../.}..,...gJ~|
orderer0.tec.com | 2017-06-29 11:17:16.034 UTC [msp/identity] Verify -> DEBU c35 Verify: sig = 00000000 30 45 02 21 00 99 07 ef f1 72 66 96 f6 bc 5f cf |0E.!.....rf..._.| orderer0.tec.com | 00000010 ca a7 4c fd 86 de a2 5c 9e 87 02 ec 35 be df 8d |..L........5...| orderer0.tec.com | 00000020 65 3f 8a 48 67 02 20 38 6b 1d aa 86 f6 53 9c 76 |e?.Hg. 8k....S.v| orderer0.tec.com | 00000030 c1 10 f7 81 5d 1f 65 9a fd 92 fb 35 84 e1 71 ba |....].e....5..q.| orderer0.tec.com | 00000040 7f ce 14 54 d7 0a a7 |...T...|
orderer0.tec.com | 2017-06-29 11:17:16.034 UTC [cauthdsl] func2 -> DEBU c36 0xc42010d530 principal evaluation succeeds for identity 0
orderer0.tec.com | 2017-06-29 11:17:16.034 UTC [cauthdsl] func1 -> DEBU c37 0xc42010d530 gate 1498735036032902403 evaluation succeeds
orderer0.tec.com | 2017-06-29 11:17:16.034 UTC [orderer/common/sigfilter] Apply -> DEBU c38 Forwarding validly signed message for policy &{%!s(*common.ImplicitMetaPolicy=&{Readers 0}) %!s(int=1) [%!s(*policies.implicitMetaPolicy=&{0xc4201dcde0 1 [0xc42010d2a8 0xc42010d370 0xc42010d408]}) %!s(*policies.implicitMetaPolicy=&{0xc4201dc3a0 1 [0xc42010d228]})]}
orderer0.tec.com | 2017-06-29 11:17:16.034 UTC [orderer/common/deliver] Handle -> DEBU c39 [channel: canaltraza] Received seekInfo (0xc42081b260) start: > stop: >
orderer0.tec.com | 2017-06-29 11:17:16.034 UTC [fsblkstorage] retrieveBlockByNumber -> DEBU c3a retrieveBlockByNumber() - blockNum = [1]
orderer0.tec.com | 2017-06-29 11:17:16.034 UTC [fsblkstorage] newBlockfileStream -> DEBU c3b newBlockfileStream(): filePath=[/var/hyperledger/production/orderer/chains/canaltraza/blockfile_000000], startOffset=[14553]
orderer0.tec.com | 2017-06-29 11:17:16.034 UTC [fsblkstorage] nextBlockBytesAndPlacementInfo -> DEBU c3c Remaining bytes=[16306], Going to peek [8] bytes
orderer0.tec.com | 2017-06-29 11:17:16.034 UTC [fsblkstorage] nextBlockBytesAndPlacementInfo -> DEBU c3d Returning blockbytes - length=[16304], placementInfo={fileNum=[0], startOffset=[14553], bytesOffset=[14555]}
orderer0.tec.com | 2017-06-29 11:17:16.034 UTC [orderer/common/deliver] Handle -> DEBU c3e [channel: canaltraza] Delivering block for (0xc42081b260)
peer0.proveedor.com | 2017-06-29 11:17:16.031 UTC [deliveryClient] RequestBlocks -> DEBU 2d9 Starting deliver with block [1] for channel canaltraza
peer0.proveedor.com | 2017-06-29 11:17:16.038 UTC [blocksProvider] DeliverBlocks -> DEBU 2da [canaltraza] Adding payload locally, buffer seqNum = [1], peers number [0] peer0.proveedor.com | 2017-06-29 11:17:16.038 UTC [blocksProvider] DeliverBlocks -> DEBU 2db [canaltraza] Gossiping block [1], peers number [0]
peer0.proveedor.com | 2017-06-29 11:17:16.038 UTC [committer] Commit -> DEBU 2dc Validating block
</code>```

答:
The error was an internal error of the Peer. The peer couldn't connect to the orderer. It was because of the default configuration of the Docker containers that you create.

When you create a docker container, you define its network. By default, the containers that you create are locaten inside the bridge network. This networks isolates the containers from other containers that are in other hosts.

I changed this configuration to Host, and I don't get the error. It goes well.

I commented the default network network: byfn

I added the property network_mode: host to each container

I define the - CORE_VM_DOCKER_HOSTCONFIG_NETWORKMODE=host

I should read more about docker networks, because there are other posibilities like overlay. I thin that this would be better. Also, I thin that it would be a good idea using docker-machien, but I haven't done it. There is more info about it here.

Body:
I'm starting up a network, which will have 3 peers and an orderer. I have 4 different Virtual Machines, one for each node.

I follow the Getting Started manual for Hyperledger Fabric. I execute all the steps without any problem. However, after executing the following command peer channel join -b channeldemo.block, I start getting some erros. It seems to me that the previous command is generated well, because I get the following logs:

2017-06-27 08:26:23.247 UTC [channelCmd] executeJoin -> INFO 00a Peer joined the channel!
2017-06-27 08:26:23.247 UTC [main] main -> INFO 00b Exiting.....

But then, after that, I get the following logs in the peer:

peer0.proveedor.com    | 2017-06-27 08:26:29.241 UTC [deliveryClient] StartDeliverForChannel -> DEBU 2d8 This peer will pass blocks from orderer service to other peers for channel canaltraza
peer0.proveedor.com    | 2017-06-27 08:26:32.242 UTC [ConnProducer] NewConnection -> ERRO 2d9 Failed connecting to orderer0.tec.com:7050 , error: context deadline exceeded
peer0.proveedor.com    | 2017-06-27 08:26:32.242 UTC [deliveryClient] connect -> ERRO 2da Failed obtaining connection: Could not connect to any of the endpoints: [orderer0.tec.com:7050]

However, if I start up the network in my localhost, I don't get any error log. After one Peer joins the channel, I get the following messages (there are messages from the peer and the orderer):

peer0.proveedor.com | 2017-06-29 11:17:16.027 UTC [deliveryClient] StartDeliverForChannel -> DEBU 2d8 This peer will pass blocks from orderer service to other peers for channel canaltraza
orderer0.tec.com | 2017-06-29 11:17:16.031 UTC [orderer/main] Deliver -> DEBU c22 Starting new Deliver handler
orderer0.tec.com | 2017-06-29 11:17:16.031 UTC [orderer/common/deliver] Handle -> DEBU c23 Starting new deliver loop
orderer0.tec.com | 2017-06-29 11:17:16.031 UTC [orderer/common/deliver] Handle -> DEBU c24 Attempting to read seek info message
orderer0.tec.com | 2017-06-29 11:17:16.032 UTC [policies] GetPolicy -> DEBU c25 Returning policy Readers for evaluation
orderer0.tec.com | 2017-06-29 11:17:16.032 UTC [cauthdsl] func1 -> DEBU c26 0xc42010d530 gate 1498735036032103426 evaluation starts
orderer0.tec.com | 2017-06-29 11:17:16.032 UTC [cauthdsl] func2 -> DEBU c27 0xc42010d530 signed by 0 principal evaluation starts (used [false])
orderer0.tec.com | 2017-06-29 11:17:16.032 UTC [cauthdsl] func2 -> DEBU c28 0xc42010d530 processing identity 0 with bytes of 0a0950726f766565646f7212f4052d2d2d2d2d424547494e202d2d2d2d2d0a4d49494345444343416265674177494241674952414c595177764d593852483533594d4a7970767977457777436759494b6f5a497a6a3045417749776254454c0a4d416b474131554542684d4356564d78457a415242674e5642416754436b4e6862476c6d62334a7561574578466a415542674e564241635444564e68626942470a636d467559326c7a59323878466a415542674e5642416f544458427962335a6c5a5752766369356a623230784754415842674e5642414d5445474e684c6e42790a62335a6c5a5752766369356a623230774868634e4d5463774e6a49354d4467304d7a41335768634e4d6a63774e6a49334d4467304d7a4133576a42594d5173770a435159445651514745774a56557a45544d4245474131554543424d4b5132467361575a76636d3570595445574d4251474131554542784d4e5532467549455a790a5957356a61584e6a627a45634d426f474131554541784d546347566c636a417563484a76646d566c5a4739794c6d4e766254425a4d424d4742797147534d34390a4167454743437147534d34394177454841304941424b5137324e78684f744648354b62666876744e3068624a484f714d6c56734c37695262794e75626a5264630a785039784554507153313169492b33724b46336f4e622b7679777756555058376335653877616f2b6a46366a5454424c4d41344741315564447745422f7751450a417749486744414d42674e5648524d4241663845416a41414d437347413155644977516b4d434b4149496631483567312b535164576369307753386b536136370a45305a4d4651516944776f426a466978786d48434d416f4743437147534d343942414d43413063414d4551434945497a7451796f476e512f6d74334c685561640a3563585172415a6b5978656b4777524f655947326e6a56694169417a6449472f4f2f4a4f57466e566c50727569567332734844724a676356496f70446a4d76360a64696f4e31773d3d0a2d2d2d2d2d454e44202d2d2d2d2d0a
orderer0.tec.com | 2017-06-29 11:17:16.032 UTC [msp/identity] newIdentity -> DEBU c29 Creating identity instance for ID &{Proveedor 0bf7d673709e14cef044e09025b8511a590e2c758697ae07f2eef5283757787d}
orderer0.tec.com | 2017-06-29 11:17:16.032 UTC [cauthdsl] func2 -> DEBU c2a 0xc42010d530 identity 0 does not satisfy principal: The identity is a member of a different MSP (expected Usuario, got Proveedor
orderer0.tec.com | 2017-06-29 11:17:16.032 UTC [cauthdsl] func2 -> DEBU c2b 0xc42010d530 principal evaluation fails
orderer0.tec.com | 2017-06-29 11:17:16.032 UTC [cauthdsl] func1 -> DEBU c2c 0xc42010d530 gate 1498735036032103426 evaluation fails
orderer0.tec.com | 2017-06-29 11:17:16.032 UTC [cauthdsl] func1 -> DEBU c2d 0xc42010d530 gate 1498735036032902403 evaluation starts
orderer0.tec.com | 2017-06-29 11:17:16.032 UTC [cauthdsl] func2 -> DEBU c2e 0xc42010d530 signed by 0 principal evaluation starts (used [false])
orderer0.tec.com | 2017-06-29 11:17:16.032 UTC [cauthdsl] func2 -> DEBU c2f 0xc42010d530 processing identity 0 with bytes of 0a0950726f766565646f7212f4052d2d2d2d2d424547494e202d2d2d2d2d0a4d49494345444343416265674177494241674952414c595177764d593852483533594d4a7970767977457777436759494b6f5a497a6a3045417749776254454c0a4d416b474131554542684d4356564d78457a415242674e5642416754436b4e6862476c6d62334a7561574578466a415542674e564241635444564e68626942470a636d467559326c7a59323878466a415542674e5642416f544458427962335a6c5a5752766369356a623230784754415842674e5642414d5445474e684c6e42790a62335a6c5a5752766369356a623230774868634e4d5463774e6a49354d4467304d7a41335768634e4d6a63774e6a49334d4467304d7a4133576a42594d5173770a435159445651514745774a56557a45544d4245474131554543424d4b5132467361575a76636d3570595445574d4251474131554542784d4e5532467549455a790a5957356a61584e6a627a45634d426f474131554541784d546347566c636a417563484a76646d566c5a4739794c6d4e766254425a4d424d4742797147534d34390a4167454743437147534d34394177454841304941424b5137324e78684f744648354b62666876744e3068624a484f714d6c56734c37695262794e75626a5264630a785039784554507153313169492b33724b46336f4e622b7679777756555058376335653877616f2b6a46366a5454424c4d41344741315564447745422f7751450a417749486744414d42674e5648524d4241663845416a41414d437347413155644977516b4d434b4149496631483567312b535164576369307753386b536136370a45305a4d4651516944776f426a466978786d48434d416f4743437147534d343942414d43413063414d4551434945497a7451796f476e512f6d74334c685561640a3563585172415a6b5978656b4777524f655947326e6a56694169417a6449472f4f2f4a4f57466e566c50727569567332734844724a676356496f70446a4d76360a64696f4e31773d3d0a2d2d2d2d2d454e44202d2d2d2d2d0a
orderer0.tec.com | 2017-06-29 11:17:16.033 UTC [msp/identity] newIdentity -> DEBU c30 Creating identity instance for ID &{Proveedor 0bf7d673709e14cef044e09025b8511a590e2c758697ae07f2eef5283757787d}
orderer0.tec.com | 2017-06-29 11:17:16.033 UTC [msp] SatisfiesPrincipal -> DEBU c31 Checking if identity satisfies MEMBER role for Proveedor
orderer0.tec.com | 2017-06-29 11:17:16.033 UTC [msp] Validate -> DEBU c32 MSP Proveedor validating identity
orderer0.tec.com | 2017-06-29 11:17:16.033 UTC [cauthdsl] func2 -> DEBU c33 0xc42010d530 principal matched by identity 0
orderer0.tec.com | 2017-06-29 11:17:16.034 UTC [msp/identity] Verify -> DEBU c34 Verify: digest = 00000000 b0 ac 91 ca 2f e9 0d 5e 0d 48 d0 dc 11 06 3b 53 |..../..^.H....;S| orderer0.tec.com | 00000010 a1 d7 f9 d6 2f fe 7d fb 19 2c 90 cb 0f 67 4a 7e |..../.}..,...gJ~|
orderer0.tec.com | 2017-06-29 11:17:16.034 UTC [msp/identity] Verify -> DEBU c35 Verify: sig = 00000000 30 45 02 21 00 99 07 ef f1 72 66 96 f6 bc 5f cf |0E.!.....rf..._.| orderer0.tec.com | 00000010 ca a7 4c fd 86 de a2 5c 9e 87 02 ec 35 be df 8d |..L........5...| orderer0.tec.com | 00000020 65 3f 8a 48 67 02 20 38 6b 1d aa 86 f6 53 9c 76 |e?.Hg. 8k....S.v| orderer0.tec.com | 00000030 c1 10 f7 81 5d 1f 65 9a fd 92 fb 35 84 e1 71 ba |....].e....5..q.| orderer0.tec.com | 00000040 7f ce 14 54 d7 0a a7 |...T...|
orderer0.tec.com | 2017-06-29 11:17:16.034 UTC [cauthdsl] func2 -> DEBU c36 0xc42010d530 principal evaluation succeeds for identity 0
orderer0.tec.com | 2017-06-29 11:17:16.034 UTC [cauthdsl] func1 -> DEBU c37 0xc42010d530 gate 1498735036032902403 evaluation succeeds
orderer0.tec.com | 2017-06-29 11:17:16.034 UTC [orderer/common/sigfilter] Apply -> DEBU c38 Forwarding validly signed message for policy &{%!s(*common.ImplicitMetaPolicy=&{Readers 0}) %!s(int=1) [%!s(*policies.implicitMetaPolicy=&{0xc4201dcde0 1 [0xc42010d2a8 0xc42010d370 0xc42010d408]}) %!s(*policies.implicitMetaPolicy=&{0xc4201dc3a0 1 [0xc42010d228]})]}
orderer0.tec.com | 2017-06-29 11:17:16.034 UTC [orderer/common/deliver] Handle -> DEBU c39 [channel: canaltraza] Received seekInfo (0xc42081b260) start: > stop: >
orderer0.tec.com | 2017-06-29 11:17:16.034 UTC [fsblkstorage] retrieveBlockByNumber -> DEBU c3a retrieveBlockByNumber() - blockNum = [1]
orderer0.tec.com | 2017-06-29 11:17:16.034 UTC [fsblkstorage] newBlockfileStream -> DEBU c3b newBlockfileStream(): filePath=[/var/hyperledger/production/orderer/chains/canaltraza/blockfile_000000], startOffset=[14553]
orderer0.tec.com | 2017-06-29 11:17:16.034 UTC [fsblkstorage] nextBlockBytesAndPlacementInfo -> DEBU c3c Remaining bytes=[16306], Going to peek [8] bytes
orderer0.tec.com | 2017-06-29 11:17:16.034 UTC [fsblkstorage] nextBlockBytesAndPlacementInfo -> DEBU c3d Returning blockbytes - length=[16304], placementInfo={fileNum=[0], startOffset=[14553], bytesOffset=[14555]}
orderer0.tec.com | 2017-06-29 11:17:16.034 UTC [orderer/common/deliver] Handle -> DEBU c3e [channel: canaltraza] Delivering block for (0xc42081b260)
peer0.proveedor.com | 2017-06-29 11:17:16.031 UTC [deliveryClient] RequestBlocks -> DEBU 2d9 Starting deliver with block [1] for channel canaltraza
peer0.proveedor.com | 2017-06-29 11:17:16.038 UTC [blocksProvider] DeliverBlocks -> DEBU 2da [canaltraza] Adding payload locally, buffer seqNum = [1], peers number [0] peer0.proveedor.com | 2017-06-29 11:17:16.038 UTC [blocksProvider] DeliverBlocks -> DEBU 2db [canaltraza] Gossiping block [1], peers number [0]
peer0.proveedor.com | 2017-06-29 11:17:16.038 UTC [committer] Commit -> DEBU 2dc Validating block


问:
how to retrieve exact text width for RenderText in Graphics32
I think my question is clear enough, but I explain more. Simply, when we are using AntiAlias on RenderText procedure, the value gotten within TextWidth function is not correct. What can I do to get the right text width?</p>

答:
You can also use the Windows API function GetTextExtentPoint32
Do some google to find example on Delphi</p>


问:
Pre-populate an object with fake data
Is there a way to pre-populate an object with fake data with Faker without specifying property rules explicitly. I found it is taking way too much time specifying rules for each property in order to populate an object with random data. How about a method that would automatically do that for me, based on property data type. It is so easy to achieve that with NBuilder, unfortunately not supporting .Net Core.

Here is the code I am using to populate CategoryViewModel:

```<code>var category = PopulateCategoryViewModelFaker().Generate();

    private Faker<CategoryViewModel> PopulateCategoryViewModelFaker()
    {
        var faker = new Faker<CategoryViewModel>();
        //faker.StrictMode(true);
        faker.RuleFor(x => x.DateCreated, f => DateTime.Now);
        faker.RuleFor(x => x.Description, f => f.Lorem.Sentence(2));
        faker.RuleFor(x => x.ParentCategory, f => null);
        faker.RuleFor(x => x.Status, f => null);
        faker.RuleFor(x => x.Title, f => f.Lorem.Sentence(2));
        faker.RuleFor(x => x.CategoryId, f => Guid.NewGuid());
        faker.RuleFor(x => x.CreatedByUser, f => null);
        faker.RuleFor(x => x.CrumbPath, f => null);
        faker.RuleFor(x => x.StatusId, _ctx.CategoryStatuses.First().StatusId);
        faker.RuleFor(x => x.CreatedByUserId, x => Guid.NewGuid());

        return faker;
    }
</code>```

I would be looking something like:

```<code>        var cat = new CategoryViewModel();
        cat  = new Faker<CategoryViewModel>().Generate();
</code>```

The above creates an object, however with no fake data.

答: After a little bit of digging, I have found an excellent library that is compatible with .Net Core, and can be used to generate random realistic test data in a very efficient way, without specifying explicitly rules for class properties. In case anyone would look for a substitution for NBuilder library that worked excellent in standard .Net, GenFu library might be an answer for you for your .Net Core Unit/Integration tests.</p>

Title: Pre-populate an object with fake data

Body:
Is there a way to pre-populate an object with fake data with Faker without specifying property rules explicitly. I found it is taking way too much time specifying rules for each property in order to populate an object with random data. How about a method that would automatically do that for me, based on property data type. It is so easy to achieve that with NBuilder, unfortunately not supporting .Net Core.

Here is the code I am using to populate CategoryViewModel:

var category = PopulateCategoryViewModelFaker().Generate();

    private Faker<CategoryViewModel> PopulateCategoryViewModelFaker()
    {
        var faker = new Faker<CategoryViewModel>();
        //faker.StrictMode(true);
        faker.RuleFor(x => x.DateCreated, f => DateTime.Now);
        faker.RuleFor(x => x.Description, f => f.Lorem.Sentence(2));
        faker.RuleFor(x => x.ParentCategory, f => null);
        faker.RuleFor(x => x.Status, f => null);
        faker.RuleFor(x => x.Title, f => f.Lorem.Sentence(2));
        faker.RuleFor(x => x.CategoryId, f => Guid.NewGuid());
        faker.RuleFor(x => x.CreatedByUser, f => null);
        faker.RuleFor(x => x.CrumbPath, f => null);
        faker.RuleFor(x => x.StatusId, _ctx.CategoryStatuses.First().StatusId);
        faker.RuleFor(x => x.CreatedByUserId, x => Guid.NewGuid());

        return faker;
    }

I would be looking something like:

        var cat = new CategoryViewModel();
        cat  = new Faker<CategoryViewModel>().Generate();

The above creates an object, however with no fake data.


问:
JavaFX Canvas: Draw a shape exclusively within another shape
I'm currently developing a game in Java, and I've been trying to figure out how to draw a shape (e.g. a circle) to the canvas, on top of a different shape (e.g. a square), but to only draw the parts of the circle which are intersecting the square, similar to a clipping mask between layers in Photoshop.

I've tried using GraphicsContext.clearRect() to clear the areas where the bottom shape is not, but that removes the background.

The code below produces this result:

However, this is the result I desire:

```<code>import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import javafx.scene.transform.Rotate;
import javafx.stage.Stage;

public class CircleWithinSquareTest extends Application {
    @Override
    public void start(Stage stage) throws Exception {
        int width = 200;
        int height = 200;
        Canvas canvas = new Canvas(width, height);
        GraphicsContext gc = canvas.getGraphicsContext2D();

        AnimationTimer timer = new AnimationTimer() {
            final int bgCellSize = 8;
            final int x = 100;
            final int y = 100;
            double angle = 0;

            @Override
            public void handle(long now) {
                /* Draw checkered background */
                gc.setFill(Color.WHITE);
                gc.fillRect(0, 0, width, height);
                gc.setFill(Color.LIGHTGRAY);
                boolean odd = false;
                for (int y = 0; y < height; y += bgCellSize) {
                    odd = !odd;
                    for (int x = odd ? 0 : bgCellSize; x < width; x += bgCellSize * 2) {
                        gc.fillRect(x, y, bgCellSize, bgCellSize);
                    }
                }
                /* Draw square */
                gc.setFill(Color.BLUE);
                gc.fillRect(x, y, 50, 50);
                /* Draw circle */
                gc.save();
                angle += 5;
                if (angle >= 360) {
                    angle = 0;
                }
                Rotate r = new Rotate(angle, x, y);
                gc.setTransform(r.getMxx(), r.getMyx(), r.getMxy(), r.getMyy(), r.getTx(), r.getTy());
                gc.setFill(Color.RED);
                gc.fillOval(x, y, 30, 30);
                gc.restore();
            }
        };
        timer.start();

        Group root = new Group(canvas);
        Scene scene = new Scene(root);

        stage.setScene(scene);
        stage.show();
    }
}
</code>```

答:
You can use clipping, add next code before setTransform:</p>

```<code>gc.beginPath();
gc.rect(x, y, 50, 50);
gc.closePath();
gc.clip();
</code>```

Body:
I'm currently developing a game in Java, and I've been trying to figure out how to draw a shape (e.g. a circle) to the canvas, on top of a different shape (e.g. a square), but to only draw the parts of the circle which are intersecting the square, similar to a clipping mask between layers in Photoshop.

I've tried using GraphicsContext.clearRect() to clear the areas where the bottom shape is not, but that removes the background.

The code below produces this result:

However, this is the result I desire:

import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import javafx.scene.transform.Rotate;
import javafx.stage.Stage;

public class CircleWithinSquareTest extends Application {
    @Override
    public void start(Stage stage) throws Exception {
        int width = 200;
        int height = 200;
        Canvas canvas = new Canvas(width, height);
        GraphicsContext gc = canvas.getGraphicsContext2D();

        AnimationTimer timer = new AnimationTimer() {
            final int bgCellSize = 8;
            final int x = 100;
            final int y = 100;
            double angle = 0;

            @Override
            public void handle(long now) {
                /* Draw checkered background */
                gc.setFill(Color.WHITE);
                gc.fillRect(0, 0, width, height);
                gc.setFill(Color.LIGHTGRAY);
                boolean odd = false;
                for (int y = 0; y < height; y += bgCellSize) {
                    odd = !odd;
                    for (int x = odd ? 0 : bgCellSize; x < width; x += bgCellSize * 2) {
                        gc.fillRect(x, y, bgCellSize, bgCellSize);
                    }
                }
                /* Draw square */
                gc.setFill(Color.BLUE);
                gc.fillRect(x, y, 50, 50);
                /* Draw circle */
                gc.save();
                angle += 5;
                if (angle >= 360) {
                    angle = 0;
                }
                Rotate r = new Rotate(angle, x, y);
                gc.setTransform(r.getMxx(), r.getMyx(), r.getMxy(), r.getMyy(), r.getTx(), r.getTy());
                gc.setFill(Color.RED);
                gc.fillOval(x, y, 30, 30);
                gc.restore();
            }
        };
        timer.start();

        Group root = new Group(canvas);
        Scene scene = new Scene(root);

        stage.setScene(scene);
        stage.show();
    }
}

Body:
You can use clipping, add next code before setTransform:

gc.beginPath();
gc.rect(x, y, 50, 50);
gc.closePath();
gc.clip();


答:
just do df.index = pd.RangeIndex(0, df.shape[0])

to overwrite your index directly, with reindex it's effectively keeping the existing index and returning you the rows that correspond to the passed in row values, as they don't exist it displays NaN

Example:

```<code>In[92]:
df = pd.DataFrame(np.random.randn(5,3), columns = list('abc'), index=[3,4,5,10,50])
df

Out[92]:
           a         b         c
3  -0.185420  0.230181  1.561401
4  -0.142055 -1.130427 -1.209588
5   2.590563  0.367157  1.878946
10  0.317735 -1.578927  0.555270
50  1.424068  0.667701  0.619741

In[93]:
df.index = pd.RangeIndex(0,df.shape[0])
df

Out[93]:
          a         b         c
0 -0.185420  0.230181  1.561401
1 -0.142055 -1.130427 -1.209588
2  2.590563  0.367157  1.878946
3  0.317735 -1.578927  0.555270
4  1.424068  0.667701  0.619741
</code>```

Here the RangeIndex is an optimised Index object for monotonic int indices, you could also do df.index = np.arange(0, df.shape[0]) but this creates a full range np array which gets converted into a RangeIndex anyway. With a RangeIndex it just needs to know the start, stop range and the step so it's memory efficient

Alternatively just call reset_index(drop=True):

```<code>In[94]:
df = df.reset_index(drop=True)
df

Out[94]:
          a         b         c
0 -0.185420  0.230181  1.561401
1 -0.142055 -1.130427 -1.209588
2  2.590563  0.367157  1.878946
3  0.317735 -1.578927  0.555270
4  1.424068  0.667701  0.619741
</code>```

This will essentially drop the current index and remake it with the index starting from 0

Title: How to del DataFrame useless rows, make the useful rows index from 0?

Body:
I get a DataFrame from an API, but the index is not from 0.
I want to index it from 0,so I tried .reindex().
But it just NA the items before, useful lines still lies from where it from...
How can I index the useful items from 0 in pandas DataFrame?

In [29]: a = ts.get_k_data('399300', index=True,start='2015-05-01', end='2015-05
    ...: -31')

In [30]: a
Out[30]:
          date     open    close     high      low       volume      code
78  2015-05-04  4757.64  4787.74  4795.92  4699.40  377843853.0  sz399300
79  2015-05-05  4785.19  4596.84  4785.19  4572.98  460419626.0  sz399300
80  2015-05-06  4626.23  4553.33  4700.91  4511.76  376073702.0  sz399300
81  2015-05-07  4520.82  4470.09  4546.34  4467.46  297759203.0  sz399300

In [31]: b = a.reindex(list(range(0,80)))

In [32]: b
Out[32]:
          date     open    close     high      low       volume      code
0          NaN      NaN      NaN      NaN      NaN          NaN       NaN
1          NaN      NaN      NaN      NaN      NaN          NaN       NaN
2          NaN      NaN      NaN      NaN      NaN          NaN       NaN
..         ...      ...      ...      ...      ...          ...       ...
76         NaN      NaN      NaN      NaN      NaN          NaN       NaN
77         NaN      NaN      NaN      NaN      NaN          NaN       NaN
78  2015-05-04  4757.64  4787.74  4795.92  4699.40  377843853.0  sz399300
79  2015-05-05  4785.19  4596.84  4785.19  4572.98  460419626.0  sz399300

[80 rows x 7 columns]

Body:
just do df.index = pd.RangeIndex(0, df.shape[0])

to overwrite your index directly, with reindex it's effectively keeping the existing index and returning you the rows that correspond to the passed in row values, as they don't exist it displays NaN

Example:

In[92]:
df = pd.DataFrame(np.random.randn(5,3), columns = list('abc'), index=[3,4,5,10,50])
df

Out[92]:
           a         b         c
3  -0.185420  0.230181  1.561401
4  -0.142055 -1.130427 -1.209588
5   2.590563  0.367157  1.878946
10  0.317735 -1.578927  0.555270
50  1.424068  0.667701  0.619741

In[93]:
df.index = pd.RangeIndex(0,df.shape[0])
df

Out[93]:
          a         b         c
0 -0.185420  0.230181  1.561401
1 -0.142055 -1.130427 -1.209588
2  2.590563  0.367157  1.878946
3  0.317735 -1.578927  0.555270
4  1.424068  0.667701  0.619741

Here the RangeIndex is an optimised Index object for monotonic int indices, you could also do df.index = np.arange(0, df.shape[0]) but this creates a full range np array which gets converted into a RangeIndex anyway. With a RangeIndex it just needs to know the start, stop range and the step so it's memory efficient

Alternatively just call reset_index(drop=True):

In[94]:
df = df.reset_index(drop=True)
df

Out[94]:
          a         b         c
0 -0.185420  0.230181  1.561401
1 -0.142055 -1.130427 -1.209588
2  2.590563  0.367157  1.878946
3  0.317735 -1.578927  0.555270
4  1.424068  0.667701  0.619741

This will essentially drop the current index and remake it with the index starting from 0


问:
Google Fonts, CSS, Latin Question
I'm trying to use this font on my web.

It's in Lithuanian language, but it's not the point, the point is, that on google fonts previewer I can see characters beautifully, but on my site some specific symbols gets some nasty look.

Maybe anyone knows how can I solve this, I say, issue?

P.S. Or recommend me some other standard very light font which I could use ...

答:
Those glyphs are not in the font. The standard fallback font of serif should be making it obvious; here’s what I see (using a pangram from Wikipedia):

If you download the font and look inside (using Font Book on Mac, or something like FontForge), you can see which glyphs are present or absent. To fix this, I would enter the characters you need into the previewer.

A quick selection of sans-serif fonts which contain the glyphs you need:

Museo Sans whose 500 weight may be used freely online.

Aller, which may require a license.

DejaVu Sans and Droid Sans, which many users will have installed.

Helvetica, Geneva, and FreeSans.

Trebuchet MS, Verdana, Calibri, Candara, and Arial, which almost all users will have installed.

Calibri appears to be a decent match for Lato, so you might use font-family: Calibri, sans-serif; (without embedding anything at all).

Title: Google Fonts, CSS, Latin Question


问:
Setting a new background image for UIButton programmatically in a ContainerViewController Class DEPENDING on which PARENT View it is In
```<code>    override func viewWillAppear(_ animated: Bool) {
    if (self.parent?.isKind(of: GuideViewController.self))!{

        relatedGuide1.setBackgroundImage(#imageLiteral(resourceName: "ab-logo-rebrand"), for: .normal)
    }
}
</code>```

I tried writing it in viewDidLoad as well. No cigar. It is strange because I am able to do this

```<code>@IBAction func relatedGuidePressed(_ sender: Any) {
    if (self.parent?.isKind(of: GuideViewController.self))!{
    show(guideViewController, sender: nil)

    }

}
</code>```

This top method basically shows a different view Controller depending on which parent it's in. For reference basically I have 7 view controllers all with the same layout but different data being displayed. So I figured a ContainerView would be the best way to go about it. Everything's been going swell but this is the last piece of the puzzle. Ideally I would js be able to do something more efficient than a bunch of conditional statements on a button but this is the best I've come up with so far.

Pour conclure: UIButton in a ContainerView. I want the UIButton to change (visually and functionally) depending on which ParentView it is in.

If anyone could help. Bless

答:
Hey guys so I found an answer. It has to do with the view hierarchy and which callback gets called when, which I'm not going to get into (mostly because I might be wrong in my explanation) BUT you do need to implement the code in the viewDidAppear NOT viewWillAppear method. Here it is as follows:

```<code>override func viewDidAppear(_ animated: Bool) {

    if (self.parent?.isKind(of: IDController.self))!{

    UpNextButton.backgroundColor = UIColor.init(hex: "536BA1")
    nextUpButtonImage.image = #imageLiteral(resourceName: "logo")

        //BUTTONS
        relatedGuideButton1.backgroundColor = UIColor.init(hex: "400080") //purple
        relatedGuideButton1.setImage(#imageLiteral(resourceName: "onenote-logo"), for: .normal)
        relatedGuideButton1.setTitle("TAKE NOTES", for: .normal) }
</code>```

If you need some functionality along with the button that's a bit more straightforward. Just use the same conditional and implement like any other IBAction. Like thus:

```<code> @IBAction func relatedGuideButton1Pressed(_ sender: Any) {

    if (self.parent?.isKind(of: IDController.self))!{

        show(notesController, sender: nil)
    }

    else if (self.parent?.isKind(of: DriveController.self))! ||
            (self.parent?.isKind(of: ShareController.self))! ||
            (self.parent?.isKind(of: NoteController.self))! ||
            (self.parent?.isKind(of: AppsController.self))! ||
            (self.parent?.isKind(of: SymbolsController.self))! ||
            (self.parent?.isKind(of: MonthController.self))! {

            show(guideViewController, sender: nil)

    }

}
</code>```

Cheers!

Body:
    override func viewWillAppear(_ animated: Bool) {
    if (self.parent?.isKind(of: GuideViewController.self))!{

        relatedGuide1.setBackgroundImage(#imageLiteral(resourceName: "ab-logo-rebrand"), for: .normal)
    }
}

I tried writing it in viewDidLoad as well. No cigar. It is strange because I am able to do this

@IBAction func relatedGuidePressed(_ sender: Any) {
    if (self.parent?.isKind(of: GuideViewController.self))!{
    show(guideViewController, sender: nil)

    }

}

This top method basically shows a different view Controller depending on which parent it's in. For reference basically I have 7 view controllers all with the same layout but different data being displayed. So I figured a ContainerView would be the best way to go about it. Everything's been going swell but this is the last piece of the puzzle. Ideally I would js be able to do something more efficient than a bunch of conditional statements on a button but this is the best I've come up with so far.

Pour conclure: UIButton in a ContainerView. I want the UIButton to change (visually and functionally) depending on which ParentView it is in.

If anyone could help. Bless

Body:
Hey guys so I found an answer. It has to do with the view hierarchy and which callback gets called when, which I'm not going to get into (mostly because I might be wrong in my explanation) BUT you do need to implement the code in the viewDidAppear NOT viewWillAppear method. Here it is as follows:

override func viewDidAppear(_ animated: Bool) {

    if (self.parent?.isKind(of: IDController.self))!{

    UpNextButton.backgroundColor = UIColor.init(hex: "536BA1")
    nextUpButtonImage.image = #imageLiteral(resourceName: "logo")

        //BUTTONS
        relatedGuideButton1.backgroundColor = UIColor.init(hex: "400080") //purple
        relatedGuideButton1.setImage(#imageLiteral(resourceName: "onenote-logo"), for: .normal)
        relatedGuideButton1.setTitle("TAKE NOTES", for: .normal) }

If you need some functionality along with the button that's a bit more straightforward. Just use the same conditional and implement like any other IBAction. Like thus:

 @IBAction func relatedGuideButton1Pressed(_ sender: Any) {

    if (self.parent?.isKind(of: IDController.self))!{

        show(notesController, sender: nil)
    }

    else if (self.parent?.isKind(of: DriveController.self))! ||
            (self.parent?.isKind(of: ShareController.self))! ||
            (self.parent?.isKind(of: NoteController.self))! ||
            (self.parent?.isKind(of: AppsController.self))! ||
            (self.parent?.isKind(of: SymbolsController.self))! ||
            (self.parent?.isKind(of: MonthController.self))! {

            show(guideViewController, sender: nil)

    }

}

Cheers!


问:
Robot framework not picking up keyword implementation
I'm trying to set up robot on top of an Eclipse Maven-Selenium-TestNG java project I created, but it doesn't seem to be picking up default keywords (I haven't even tried adding my own yet).

I started by creating a maven project and adding to pom.xml the dependencies for selenium 3.4, testNG 6.8 and robot 3.0.2, then also added robot plugin 1.4.7. Finally, updated the project so maven downloads all the needed stuff.

To test selenium (without robot) I created a textNG class in src>test>java, added a system property pointing to the chromedriver.exe file in my system and added a simple test that just opens the browser and navigates to google. It worked, so now I want to use robot on top of that.

This is my pom.xml file:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.demo.automation</groupId>
  <artifactId>automated_tests</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <dependencies>
    <dependency>
      <groupId>org.seleniumhq.selenium</groupId>
      <artifactId>selenium-java</artifactId>
      <version>3.4.0</version>
    </dependency>
    <dependency>
      <groupId>org.testng</groupId>
      <artifactId>testng</artifactId>
      <version>6.8</version>
      <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.robotframework</groupId>
        <artifactId>robotframework</artifactId>
        <version>3.0.2</version>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.robotframework</groupId>
        <artifactId>robotframework-maven-plugin</artifactId>
        <version>1.4.7</version>
        <executions>
          <execution>
            <goals>
              <goal>run</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>
</code>```

I created a file in src/test/robotframework/acceptance, with the following contents:

```<code>*** Settings ***
Test Set Up  Start Selenium Server
Test Tear Down  Stop Selenium Server

*** Test Cases ***
Visit google
  Open Browser  https://www.google.com  chrome
  Close Browser
</code>```

However, when I run as maven install, I get:

Setup failed: No keyword with name 'Start Selenium Server' found.

Also teardown failed: No keyword with name 'Stop Selenium Server'
  found.

So why is it that robot is not finding the keywords implementation? And how do I add implementations of my own keywords?

答:
The reason robot isn't finding the keywords is that you aren't importing the library that contains the keywords. Start Selenium Server is part of the deprecated SeleniumLibrary. In order to use the keywords you must import them with the Library setting:

```<code>*** Settings ***
Library  SeleniumLibrary
Test Set Up  Start Selenium Server
Test Tear Down  Stop Selenium Server
</code>```

Assuming that the folder where SeleniumLibrary is installed is in your PYTHONPATH, robot will import the library and make the keywords available to you.

Body:
I'm trying to set up robot on top of an Eclipse Maven-Selenium-TestNG java project I created, but it doesn't seem to be picking up default keywords (I haven't even tried adding my own yet).

I started by creating a maven project and adding to pom.xml the dependencies for selenium 3.4, testNG 6.8 and robot 3.0.2, then also added robot plugin 1.4.7. Finally, updated the project so maven downloads all the needed stuff.

To test selenium (without robot) I created a textNG class in src>test>java, added a system property pointing to the chromedriver.exe file in my system and added a simple test that just opens the browser and navigates to google. It worked, so now I want to use robot on top of that.

This is my pom.xml file:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.demo.automation</groupId>
  <artifactId>automated_tests</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <dependencies>
    <dependency>
      <groupId>org.seleniumhq.selenium</groupId>
      <artifactId>selenium-java</artifactId>
      <version>3.4.0</version>
    </dependency>
    <dependency>
      <groupId>org.testng</groupId>
      <artifactId>testng</artifactId>
      <version>6.8</version>
      <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.robotframework</groupId>
        <artifactId>robotframework</artifactId>
        <version>3.0.2</version>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.robotframework</groupId>
        <artifactId>robotframework-maven-plugin</artifactId>
        <version>1.4.7</version>
        <executions>
          <execution>
            <goals>
              <goal>run</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>

I created a file in src/test/robotframework/acceptance, with the following contents:

*** Settings ***
Test Set Up  Start Selenium Server
Test Tear Down  Stop Selenium Server

*** Test Cases ***
Visit google
  Open Browser  https://www.google.com  chrome
  Close Browser

However, when I run as maven install, I get:

Setup failed: No keyword with name 'Start Selenium Server' found.

Also teardown failed: No keyword with name 'Stop Selenium Server'
  found.

So why is it that robot is not finding the keywords implementation? And how do I add implementations of my own keywords?

Body:
The reason robot isn't finding the keywords is that you aren't importing the library that contains the keywords. Start Selenium Server is part of the deprecated SeleniumLibrary. In order to use the keywords you must import them with the Library setting:

*** Settings ***
Library  SeleniumLibrary
Test Set Up  Start Selenium Server
Test Tear Down  Stop Selenium Server

Assuming that the folder where SeleniumLibrary is installed is in your PYTHONPATH, robot will import the library and make the keywords available to you.


Title: transform a matrix inserting zero row

Body:
I have got a matrix, called crash.data. I would like to create a matrix which is exactly the same but with rows with zeros in between, as in the code below

> head(crash.data)
            [,1]       [,2]       [,3]
[1,]  0.14449657 -0.2289661 -0.9065017
[2,]  0.06079472 -0.1801571 -0.9796568
[3,] -0.04159815 -0.2442845 -0.9071650
[4,] -0.01820570 -0.1778194 -0.9765629
[5,] -0.06200437 -0.2801673 -0.9325789
[6,]  0.09424269 -0.2143995 -0.9233422
> graph<-matrix(0,ncol=3,nrow = 4000)
> for (i in seq(2,4000,2)){graph[i,]<-as.matrix(crash.data)[i/2,]}
> head(graph)
            [,1]       [,2]       [,3]
[1,]  0.00000000  0.0000000  0.0000000
[2,]  0.14449657 -0.2289661 -0.9065017
[3,]  0.00000000  0.0000000  0.0000000
[4,]  0.06079472 -0.1801571 -0.9796568
[5,]  0.00000000  0.0000000  0.0000000
[6,] -0.04159815 -0.2442845 -0.9071650

In order to do so, I am using a for cycle. Is there a nicer and faster way, ideally without using a for cycle?

Thanks

Body:
A fully Vectorized method would be, (Using @d.b's dataset)

m1 <- m1[rep(1:nrow(m1), each = 2),]
m1[c(TRUE, FALSE),] <- 0

m1
#            [,1]        [,2]       [,3]
# [1,]  0.0000000  0.00000000  0.0000000
# [2,]  1.3709584  1.51152200 -1.3888607
# [3,]  0.0000000  0.00000000  0.0000000
# [4,] -0.5646982 -0.09465904 -0.2787888
# [5,]  0.0000000  0.00000000  0.0000000
# [6,]  0.3631284  2.01842371 -0.1333213
# [7,]  0.0000000  0.00000000  0.0000000
# [8,]  0.6328626 -0.06271410  0.6359504
# [9,]  0.0000000  0.00000000  0.0000000
#[10,]  0.4042683  1.30486965 -0.2842529
#[11,]  0.0000000  0.00000000  0.0000000
#[12,] -0.1061245  2.28664539 -2.6564554


问:
ASP.NET MVC - ViewModel for Listing from 2 Models at Once
I have a scenario where a user will submit a form that contains information for 2 models (database tables): Users and Requests. The data will also need to be listed together joined by UserID, i.e. to list all Requests made by all users, or by a specific user. So I also need to output the data from both tables.

My solution was to create ViewModel called UserRequests which would contain both of these models, however I am stuck on the implementation. I am not sure if it should look like the following:

```<code>public class UserRequestModel {
    public User User1 { get; set; }
    public Request Request1 { get; set; }
</code>```

To summarize, what the Index() function in the Controller will do, is get a query of requests by all users and list all fields from both tables (joined). So I need to somehow get the data from that query into the ViewModel to output it and have no idea how to set up the ViewModel in order to do so. Any insight would be appreciated. Thanks!

答:
You can just use linq to join the two tables and then project the records to your target view model so something like:

```<code>  var res =
    from u in Users
    join r in Requests on u.UserId equals r.UserId
    select new UserRequestModel { User1 = u,  Request1 = r};
</code>```

Are you using an ORM (e.g. Entity Framework) to map the database tables?

Body:
I have a scenario where a user will submit a form that contains information for 2 models (database tables): Users and Requests. The data will also need to be listed together joined by UserID, i.e. to list all Requests made by all users, or by a specific user. So I also need to output the data from both tables.

My solution was to create ViewModel called UserRequests which would contain both of these models, however I am stuck on the implementation. I am not sure if it should look like the following:

public class UserRequestModel {
    public User User1 { get; set; }
    public Request Request1 { get; set; }

To summarize, what the Index() function in the Controller will do, is get a query of requests by all users and list all fields from both tables (joined). So I need to somehow get the data from that query into the ViewModel to output it and have no idea how to set up the ViewModel in order to do so. Any insight would be appreciated. Thanks!

Body:
You can just use linq to join the two tables and then project the records to your target view model so something like:

  var res =
    from u in Users
    join r in Requests on u.UserId equals r.UserId
    select new UserRequestModel { User1 = u,  Request1 = r};

Are you using an ORM (e.g. Entity Framework) to map the database tables?


问:
Confusion about repeating pattern in python Regex
I have confusion about repeating pattern in Python regular expression.
I read from the documentation that '*' means repeating zero to N times. Suppose I have a string abc123def. I want to find the position of the substring containing numeric characters, so I use the following code:

```<code>p = re.compile(r'[\d]*')
p.search('abc123def').span()
</code>```

And it outputs (0,0)
If I change the regex to [\d]+, it outputs (3,6).

Why the regex r'[\d]*' doesn't work?
Thanks.

答:
Another way to see what is happening is to use findall:

```<code>>>> re.findall(r'\d*', 'abc123def')
['', '', '', '123', '', '', '', '']
</code>```

vs

```<code>>>> re.findall(r'\d+', 'abc123def')
['123']
</code>```

Or visually with regex101

The * means 'zero or more' at the first opportunity. You have zero digits at the start of the string. A match! And that matches are every character in the string.

Use + if you want to match a substring.

Body:
I have confusion about repeating pattern in Python regular expression.
I read from the documentation that '*' means repeating zero to N times. Suppose I have a string abc123def. I want to find the position of the substring containing numeric characters, so I use the following code:

p = re.compile(r'[\d]*')
p.search('abc123def').span()

And it outputs (0,0)
If I change the regex to [\d]+, it outputs (3,6).

Why the regex r'[\d]*' doesn't work?
Thanks.

Body:
Another way to see what is happening is to use findall:

>>> re.findall(r'\d*', 'abc123def')
['', '', '', '123', '', '', '', '']

vs

>>> re.findall(r'\d+', 'abc123def')
['123']

Or visually with regex101

The * means 'zero or more' at the first opportunity. You have zero digits at the start of the string. A match! And that matches are every character in the string.

Use + if you want to match a substring.


问:
CSS reset and browsers dependencies
Can a CSS reset file eliminate the need for coding style rules for specific browsers?

For Example: -moz- in Firefox, -webkit- for Safari and Chrome, -o- for Opera, and -ms- for Internet Explorer.

答:
That's not what a CSS Reset stylesheet is for. A reset stylesheet is used to override existing or preset styles on a web page to their default values. This can be useful when you are using a popular framework or library that includes styling, and you wish to avoid the styling while still using the library.

It does not obviate the need for vendor-prefixes because it has no relation to what browser a visitor will use to visit your site. Any new styles you use that include vendor-prefixed properties will still need those vendor-prefixed properties.

By the way, Firefox and Microsoft Edge use some -webkit- prefixes, as well, for compatibility.

Title: CSS reset and browsers dependencies


答:
The ViewModel should designed to help you displaying data. I would suggest you to follow the rule 1 ViewModel per View.
You should design first clearly how you want to represent the data in the view. I'm not sure if your ViewModel is exactly what you want to represent. Do you want to show 1 request and all the users related? or you want 1 user and all the requests related? Or you want many requests with many users related?

Depending on your need, you should create the ViewModel. Imagine you want 1 user and many Requests, then I would have a List of Requests inside the user class.

Title: ASP.NET MVC - ViewModel for Listing from 2 Models at Once


问:
Javascript Audio object play/pause
I have theres function 1 is for playing music and the second is for set pause to the actual music, my pause function don't work. How can i do for set pause ?</p>

```<code>function play(id){
        var audio = new Audio('music/'+id+'.mp3');
        audio.play();
}

function pause(){
        audio.pause();
}
</code>```

答:
The audio variable isn't accessible in the Pause function. You need to pass it as a parameter or set it outside the function. This is just an example of how you can do it:</p>

```<code>var audio;

function createAudio(id) {
    audio = new Audio('music/'+id+'.mp3');
    play();
}

function play(){
    audio.play();
}

function pause(){
    audio.pause();
}
</code>```

Title: Javascript Audio object play/pause

Body:
I have theres function 1 is for playing music and the second is for set pause to the actual music, my pause function don't work. How can i do for set pause ?

function play(id){
        var audio = new Audio('music/'+id+'.mp3');
        audio.play();
}

function pause(){
        audio.pause();
}

Body:
The audio variable isn't accessible in the Pause function. You need to pass it as a parameter or set it outside the function. This is just an example of how you can do it:

var audio;

function createAudio(id) {
    audio = new Audio('music/'+id+'.mp3');
    play();
}

function play(){
    audio.play();
}

function pause(){
    audio.pause();
}


问:
How to bind a click event to the document so that it fires only when no object is clicked
I would like an event to fire whenever something other than a DOM element is clicked, and a separate event when an image is clicked.

Right now I have:

```<code>$( document ).click( function() { /*do whatev*/ } );
</code>```

and in another place:

```<code>$( "img" ).click( function( e ) {
  e.stopPropagation();
  /*do whatev*/
} );
</code>```

it does not work. both events are fired. any other ideas?

答: This should work, but just img isn't enough.  It could be triggering from the img container.  I think you'd need a selector like $('p,div,img,a,input,textarea,span,ul,ol,dl,li,dd,dt,table,tr,td') and any other tag you can think of to pull it off.  This might have performance issues.

Body:
I would like an event to fire whenever something other than a DOM element is clicked, and a separate event when an image is clicked.

Right now I have:

$( document ).click( function() { /*do whatev*/ } );

and in another place:

$( "img" ).click( function( e ) {
  e.stopPropagation();
  /*do whatev*/
} );

it does not work. both events are fired. any other ideas?


问:
Meteor Iron Router WaitOn Subscription
I am really struggling with waiting on a subscription to load for a specific route before returning the data to the template.  I can see on from the publish on the server that a document is found, but on the client there is no document.

If I do a find().count() on the publish, it shows 1 document found, which is correct, but when I do the count on the subscription, it shows 0 documents.

I have tried a number of different methods, like using subscriptions:function() instead of waitOn:function(), but nothing works.

Collections.js lib:

```<code>SinglePackage = new Mongo.Collection("SinglePackage");
SinglePackage.allow({
  insert: function(){
    return true;
  },
  update: function(){
    return true;
  },
  remove: function(){
    return true;
  }
});
</code>```

Publications.js server:

```<code>Meteor.publish("SinglePackage", function(pack_id) {
 return Packages.find({shortId: pack_id});
});
</code>```

Iron Router:

```<code>Router.route('/package/:id', {
  name: 'package.show',
  template: 'Package_page',
  layoutTemplate: 'Landing_layout',
  waitOn: function() {
    return Meteor.subscribe('SinglePackage', this.params.id);
  },
  data: function() {
    return SinglePackage.find();
  },
  action: function () {
    if (this.ready()) {
      this.render();
    } else {
      this.render('Loading');
    }
  }
});
</code>```

Am I doing something very wrong, or is this just a complicated thing to achieve?  One would think that waitOn would make the rest of the function wait until the subscription is ready.

Any help would be highly appreciated.

答:
It appears that the data function is running before the subscription is ready. Even if the data function did run after the subscription was ready, it wouldn't be a reactive data source rendering the pub/sub here pointless. Here's a great article on reactive data sources.

Referring to the example from the Iron Router Docs for subscriptions, you would do something like this:

```<code>Router.route('/package/:id', {
  subscriptions: function() {
    // returning a subscription handle or an array of subscription handles
    // adds them to the wait list.
    return Meteor.subscribe('SinglePackage', this.params.id);
  },

  action: function () {
    if (this.ready()) {
      this.render();
    } else {
      this.render('Loading');
    }
  }
});
</code>```

Then in your template.js:

```<code>Template.Package_page.helpers({
  singlePackage() {
  // This is now a reactive data source and will automatically update whenever SinglePackage changes in Mongo.
    return Package.find().fetch();
  }
});
</code>```

In your template.html you can now use singlePackage:

```<code><template name="Package_page">
  {#with singlePackage} <!-- Use #each if you're singlePackage is an array -->
    ID: {_id}
  {/with}
</template>
</code>```

Title: Meteor Iron Router WaitOn Subscription

Body:
I am really struggling with waiting on a subscription to load for a specific route before returning the data to the template.  I can see on from the publish on the server that a document is found, but on the client there is no document.

If I do a find().count() on the publish, it shows 1 document found, which is correct, but when I do the count on the subscription, it shows 0 documents.

I have tried a number of different methods, like using subscriptions:function() instead of waitOn:function(), but nothing works.

Collections.js lib:

SinglePackage = new Mongo.Collection("SinglePackage");
SinglePackage.allow({
  insert: function(){
    return true;
  },
  update: function(){
    return true;
  },
  remove: function(){
    return true;
  }
});

Publications.js server:

Meteor.publish("SinglePackage", function(pack_id) {
 return Packages.find({shortId: pack_id});
});

Iron Router:

Router.route('/package/:id', {
  name: 'package.show',
  template: 'Package_page',
  layoutTemplate: 'Landing_layout',
  waitOn: function() {
    return Meteor.subscribe('SinglePackage', this.params.id);
  },
  data: function() {
    return SinglePackage.find();
  },
  action: function () {
    if (this.ready()) {
      this.render();
    } else {
      this.render('Loading');
    }
  }
});

Am I doing something very wrong, or is this just a complicated thing to achieve?  One would think that waitOn would make the rest of the function wait until the subscription is ready.

Any help would be highly appreciated.

Body:
It appears that the data function is running before the subscription is ready. Even if the data function did run after the subscription was ready, it wouldn't be a reactive data source rendering the pub/sub here pointless. Here's a great article on reactive data sources.

Referring to the example from the Iron Router Docs for subscriptions, you would do something like this:

Router.route('/package/:id', {
  subscriptions: function() {
    // returning a subscription handle or an array of subscription handles
    // adds them to the wait list.
    return Meteor.subscribe('SinglePackage', this.params.id);
  },

  action: function () {
    if (this.ready()) {
      this.render();
    } else {
      this.render('Loading');
    }
  }
});

Then in your template.js:

Template.Package_page.helpers({
  singlePackage() {
  // This is now a reactive data source and will automatically update whenever SinglePackage changes in Mongo.
    return Package.find().fetch();
  }
});

In your template.html you can now use singlePackage:

<template name="Package_page">
  {#with singlePackage} <!-- Use #each if you're singlePackage is an array -->
    ID: {_id}
  {/with}
</template>


问:
Quick way to determine whether a list contains at least one item contained in an array
I have a List<String> a and a String[] b. I would like to return true if there is at least one member of the list inside the array. For that matter, it doesn't matter that I am dealing with a List<String> and an String[]. Both could be lists.

EDIT

Java 8 gives you a way to do it via streams, it seems. What about more basic ways?

Thanks

答:
One way without Java 8 streams:

```<code>public boolean containsAtLeastOne( List<String> a, String[] b ) {
    Set<String> aSet = new HashSet( a );
    for ( s : b ) {
       if ( aSet.contains( s ) ) {
           return true;
       }
    }
    return false;
}
</code>```

Another way:

```<code> public boolean containsAtLeastOne( List<String> a, String[] b ) {
    Set<String> aSet = new HashSet( a );
    List<String> bList = Arrays.asList(b);

    bList.retainAll( aSet );

    return 0 < bList.size();
 }
</code>```

Body:
One way without Java 8 streams:

public boolean containsAtLeastOne( List<String> a, String[] b ) {
    Set<String> aSet = new HashSet( a );
    for ( s : b ) {
       if ( aSet.contains( s ) ) {
           return true;
       }
    }
    return false;
}

Another way:

 public boolean containsAtLeastOne( List<String> a, String[] b ) {
    Set<String> aSet = new HashSet( a );
    List<String> bList = Arrays.asList(b);

    bList.retainAll( aSet );

    return 0 < bList.size();
 }

ContentLicense: CC BY-SA 4.0


问:
svn to git migration with long history is over 6Gb
I've been tasked with migrating our SVN to Git, while I've managed to do some projects there is one project that is giving me trouble.

Having converted this project, the Git repo is over 6Gb. Note I have removed all binaries for SVN before the migration.

This project has over 1000 tags and 100 branches, and within the .git folder the svn folder is @4.9Gb not sure what I can do. I don't want to lose history, but I can not see how to reduce this folder.

答:
over 1000 tags and 100 branches

Branching and tagging is cheap in SVN and in git and should not cause your repository to be 4-6GB. There have to be other data that's taking up the space. Or the project you work with is large by itself.

The problem is that you expect git repository to be (much) smaller that SVN repository. This is a common mistake. SVN and git repository with the same dataset will be about the same size and git repository can be even larger in certain cases.

SVN solves this problem by providing you with disposable working copies that are fast to checkout. However, as you must clone a whole repository with git, you will have to divide your single monorepo into multiple smaller repositories.


问:
config.xml on system not same as Jenkins UI
I have edited the config.xml file within the jobs directory on the Jenkins system:

```<code>$JENKINS_HOME/jobs/myjob/config.xml.
</code>```

I expect the changes to be reflected on the Jenkins UI when I go to configure on the job page: https://my-jenkins-system/job/myjob/configure

But this does not happen. It works the other way around, i.e if i edit in UI, I see the changes in config.xml.

Is the one displayed on UI a cached file? or Am I doing something wrong or is my understanding wrong?

答:
After modifying the data in config.xml you need to select the below option

Jenkins --> Manage Jenkins --> Reload Configuration from Disk

in your Jenkins to see the changes in UI.

Body:
I have edited the config.xml file within the jobs directory on the Jenkins system:

$JENKINS_HOME/jobs/myjob/config.xml.

I expect the changes to be reflected on the Jenkins UI when I go to configure on the job page: https://my-jenkins-system/job/myjob/configure

But this does not happen. It works the other way around, i.e if i edit in UI, I see the changes in config.xml.

Is the one displayed on UI a cached file? or Am I doing something wrong or is my understanding wrong?


问:
How to render an element conditionally in Vue.js?
I'm new to Vue.js, I just read the documentation on conditional rendering here (https://v2.vuejs.org/v2/guide/conditional.html) but somehow can't get it to work...

My code:

```<code><button onclick="showTemplate()">Teste</button>

<template v-if="app">

    <div id="app">
      {{ message }}
    </div>

</template>

function showTemplate(){
    var app = new Vue({
      el: '#app',
      data: {
        message: 'Hello Vue!'
      }
    })
}
</code>```

I want the template tag to render only after app has been instantiated.
I have also tried variations of this code without success.
Can someone help out?

答:
Use v-cloak. The intended use of v-cloak is to hide the Vue until it is instantiated.

function showTemplate() {
  var app = new Vue({
    el: '#app',
    data: {
      message: 'Hello Vue!'
    }
  })
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>[v-cloak] {
  display: none;
}</code>```

<button onclick="showTemplate()">Teste</button>

  {{ message }}

```
</div>
</div>
</p>
<p>Here is how you might hide your "loading" screen when data is retrieved. In this case, the button will serve as our loading screen.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var app = new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue!',
    loaded: false
  },
  methods: {
    getData() {
      setTimeout(() => this.loaded = true, 2000)
    }
  }
})</code>```

[v-cloak] {
  display: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.js"></script>

<div id="app" v-cloak>
  <button v-if="!loaded" @click="getData">Get Data</button>

  <div v-if="loaded">
    {{ message }}
  </div>
</div></code>```

Body:
I'm new to Vue.js, I just read the documentation on conditional rendering here (https://v2.vuejs.org/v2/guide/conditional.html) but somehow can't get it to work...

My code:

<button onclick="showTemplate()">Teste</button>

<template v-if="app">

      {{ message }}

</template>

function showTemplate(){
    var app = new Vue({
      el: '#app',
      data: {
        message: 'Hello Vue!'
      }
    })
}

I want the template tag to render only after app has been instantiated.
I have also tried variations of this code without success.
Can someone help out?

Body:
Use v-cloak. The intended use of v-cloak is to hide the Vue until it is instantiated.

function showTemplate() {
  var app = new Vue({
    el: '#app',
    data: {
      message: 'Hello Vue!'
    }
  })
}

[v-cloak] {
  display: none;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.js"></script>
<button onclick="showTemplate()">Teste</button>

<div id="app" v-cloak>
  {{ message }}
</div>

Here is how you might hide your "loading" screen when data is retrieved. In this case, the button will serve as our loading screen.

var app = new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue!',
    loaded: false
  },
  methods: {
    getData() {
      setTimeout(() => this.loaded = true, 2000)
    }
  }
})

[v-cloak] {
  display: none;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.js"></script>

<div id="app" v-cloak>
  <button v-if="!loaded" @click="getData">Get Data</button>

  <div v-if="loaded">
    {{ message }}
  </div>
</div>


问:
.Net - Accessing GPS Data from Plethora of Devices
Is anyone aware of any utility that can retrieve GPS data from other devices?  Such as handhelds, mobile phones, etc.

I'm building an website where we want users to be able to easily import various GPS coordinates that they may have collected - be it with a handheld gps by Garmin, Lowrance, etc or a mobile phone (android, iphone, xyz)  I know my Garmin came with software - but it was overkill - and requires the owner to read-up and figure it out.

I'm sure my Dad can plot points and markers on his GPS - but figuring out how to easily get that data out (exporting) to import may be overly-complicated.  So I'm looking to see if there's anyway to bridge that gap.

can anyone help shed some light as to how to attack this issue?  Is there any software available that's achieved something similar?

I'm developing in C# - and have seen that Garmin has a nice API - but other's don't - and not sure how exactly to interact with Phones.

答: Most GPS devices with an output (serial, USB, etc...) will output NMEA sentences (http://www.gpsinformation.org/dale/nmea.htm#nmea).`</p>


问:
How to send hashmap <Object,boolean> as a JSON to angular controller?
I am quite new to AngularJS. I am trying to send a hashmap over to angular controller through a REST service. I am using JSONContentEncapsulator for the same. I am not sure about the syntax.
JSONContentEncapsulator<HashMap> encapsulator = new JSONContentEncapsulator<HashMap>(sampleHashmap);
The problem is my Hashmap is sent over to controller with the object converted in the string format.
Also when I try printing the key value pair on the screen using ng-repeat, it's blank.
but when I print it in my controller using forEach I am able to see the values.
Could anyone please help as to how I should achieve this so that I can retrieve the object and corresponding boolean value on the screen?

EDIT1: The json values returned by REST service in my controller look like below:
{"EventValue(eventValueId=14, eventValueDescription=Deb Basic Neg Settle-intern plus   , valueClassId=ALTBASIC, resultType=CALC, creditdebitIndicator=DEBIT, sign=POSITIVE, custAccountType=INTERNAL_SETTLEMENT)":true,"EventValue(eventValueId=11, eventValueDescription=Cred Basic Neg Correction minus    , valueClassId=ALTBASIC, resultType=CORP, creditdebitIndicator=CREDIT, sign=NEGATIVE, custAccountType=NA)":true}
Where EvenValue is the object which is used as key and there is corresponding  boolean value with it.

答:
As I read online. It is not possible to send Map with Object as key in JSON format.
So instead I created two arraylists out of the map and sent those as a part of a single nested list.
It works fine.</p>


问:
Adding a node in the beginning of XML parent node
I wanted to add a xmlNode in a parent but at the top/beginning. Is there a variant of XMLNode.AppendChild() that i can use?

答:
I believe the question is asking how to add a node to the beginning of the XML file. I did that in the following manner:</p>

```<code>// This is the main xml document
XmlDocument document = new XmlDocument();

// This part is creation of RootNode, however you want
XmlNode RootNode = document.CreateElement("Comments");
document.AppendChild(RootNode);

//Adding first child node as usual
XmlNode CommentNode1 = document.CreateElement("UserComment");
RootNode.AppendChild(commentNode1);

//Now create a child node and add it to the beginning of the XML file
XmlNode CommentNode2 = document.CreateElement("UserComment");
RootNode.InsertBefore(commentNode2, RootNode.FirstChild);
</code>```

Body:
I believe the question is asking how to add a node to the beginning of the XML file. I did that in the following manner:

// This is the main xml document
XmlDocument document = new XmlDocument();

// This part is creation of RootNode, however you want
XmlNode RootNode = document.CreateElement("Comments");
document.AppendChild(RootNode);

//Adding first child node as usual
XmlNode CommentNode1 = document.CreateElement("UserComment");
RootNode.AppendChild(commentNode1);

//Now create a child node and add it to the beginning of the XML file
XmlNode CommentNode2 = document.CreateElement("UserComment");
RootNode.InsertBefore(commentNode2, RootNode.FirstChild);


问:
Is it possible to get the string inside the enclosing '<' and '>' of a tag using jquery or plain javascript?
If  my question isn't clear,I don't want the outerhtml which returns all the contents inside a node.I don't want those.For example:

  Hello!

    How are you?Hope you are doing well!

```
</div>
</div>
</p>

<p>Now,outerHTML of 'foo' will give the whole string representation of its DOM structure.I just want </p>

```div id="foo" class="something" style="width:80%; display:inline-block"
```

Is it possible to get this without using regex/string matching?

答:
You can get the outerHTML and then parse the part you want:

console.log(
    document.getElementById('foo').outerHTML.match(/<([^>]+)>/)[1]
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="foo" class="something" style="width:80%; display:inline-block">
  Hello!
  <div id="bar" class="something_else">
    How are you?Hope you are doing well!
  </div>
</div></code>```

Body:
If  my question isn't clear,I don't want the outerhtml which returns all the contents inside a node.I don't want those.For example:

  Hello!

    How are you?Hope you are doing well!

Now,outerHTML of 'foo' will give the whole string representation of its DOM structure.I just want

div id="foo" class="something" style="width:80%; display:inline-block"

Is it possible to get this without using regex/string matching?

Body:
You can get the outerHTML and then parse the part you want:

console.log(
    document.getElementById('foo').outerHTML.match(/<([^>]+)>/)[1]
);

<div id="foo" class="something" style="width:80%; display:inline-block">
  Hello!
  <div id="bar" class="something_else">
    How are you?Hope you are doing well!
  </div>
</div>


问:
Write random numbers to an array of objects
I'm currently working on a simulator, which should imitate a certain business logic.
I try to create an object of a class Suggestion by picking two random strings out of two string arrays. The method should return an array of Suggestion objects. The array length is also variable. For now the returned array should be printed out in the console.

This is my class Suggestion:

```<code> public class Suggestion
    {
        public Suggestion(string aktenName, string relevanz)
        {
            MAktenName = aktenName;
            MRelevanz = relevanz;
        }

        public string MAktenName { get; private set; }

        public string MRelevanz { get; private set; }
    }
</code>```

My other class including the "logic" and the main method looks like this:

```<code> private static void Main()
        {
            var test = GetSuggestions();

            for (var i = 0; i < test.Length; i++)
            {
                Console.WriteLine(test[i].MAktenName + "-" + test[i].MRelevanz + "%");
            }

            Console.ReadLine();
        }

        public static Suggestion[] GetSuggestions()
        {
            var random = new Random();
            var suggestionsCount = random.Next(1, 10);
            var suggestions = new Suggestion[suggestionsCount];

            string[] names =
            {
                "721/12", "345/93", "478/54", "876/39", "546/27", "481/56", "824/39", "897/51",
                "574/48"
            };
            string[] relevance =
            {
                "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"
            };

            for (var i = 0; i < suggestionsCount; i++)
            {

                var sugName = names[new Random().Next(0, names.Length)];
                var sugRelevance = relevance[new Random().Next(0, relevance.Length)];

                suggestions[i] = new Suggestion(sugName, sugRelevance);
            }
            return suggestions;
        }
</code>```

My problem is that it prints out a random combination of the string arrays sugName and sugRelevance and it prints a variable amount of these, but all the objects of the class Suggestions are the same.
Like my result is something like:

345/93-20%

345/93-20%

345/93-20%

345/93-20%

I reckon it is something with the new Random().Next(0, names.Length) but I am not sure.

答:
Instead of

```<code>var sugName = names[new Random().Next(0, names.Length)];
var sugRelevance = relevance[new Random().Next(0, relevance.Length)];
</code>```

Write:

```<code>var sugName = names[random.Next(0, names.Length)];
var sugRelevance = relevance[random.Next(0, relevance.Length)];
</code>```

Body:
I'm currently working on a simulator, which should imitate a certain business logic.
I try to create an object of a class Suggestion by picking two random strings out of two string arrays. The method should return an array of Suggestion objects. The array length is also variable. For now the returned array should be printed out in the console.

This is my class Suggestion:

 public class Suggestion
    {
        public Suggestion(string aktenName, string relevanz)
        {
            MAktenName = aktenName;
            MRelevanz = relevanz;
        }

        public string MAktenName { get; private set; }

        public string MRelevanz { get; private set; }
    }

My other class including the "logic" and the main method looks like this:

 private static void Main()
        {
            var test = GetSuggestions();

            for (var i = 0; i < test.Length; i++)
            {
                Console.WriteLine(test[i].MAktenName + "-" + test[i].MRelevanz + "%");
            }

            Console.ReadLine();
        }

        public static Suggestion[] GetSuggestions()
        {
            var random = new Random();
            var suggestionsCount = random.Next(1, 10);
            var suggestions = new Suggestion[suggestionsCount];

            string[] names =
            {
                "721/12", "345/93", "478/54", "876/39", "546/27", "481/56", "824/39", "897/51",
                "574/48"
            };
            string[] relevance =
            {
                "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"
            };

            for (var i = 0; i < suggestionsCount; i++)
            {

                var sugName = names[new Random().Next(0, names.Length)];
                var sugRelevance = relevance[new Random().Next(0, relevance.Length)];

                suggestions[i] = new Suggestion(sugName, sugRelevance);
            }
            return suggestions;
        }

My problem is that it prints out a random combination of the string arrays sugName and sugRelevance and it prints a variable amount of these, but all the objects of the class Suggestions are the same.
Like my result is something like:

345/93-20%

345/93-20%

345/93-20%

345/93-20%

I reckon it is something with the new Random().Next(0, names.Length) but I am not sure.

Body:
Instead of

var sugName = names[new Random().Next(0, names.Length)];
var sugRelevance = relevance[new Random().Next(0, relevance.Length)];

Write:

var sugName = names[random.Next(0, names.Length)];
var sugRelevance = relevance[random.Next(0, relevance.Length)];