问:
MVC KendoUI cascading dropdownlists, on multiple parents
I have three column in kendoui grid as "Delivery Location", "PickUp location" and "Available Shipping Options". When either of the location column changed("Delivery location" or "Pickup location"), the "Available shipping options" column should be changed accordingly.

I can achieve this using Cascade-from for two column(i.e. if one column changed, other would list the result based on the first column data) but don't know how to achieve same for two or more column.

How can i achieve cascading for two or more column?

Code:
JS Function:

```<code>    function filterShippingOptions() {
   return { pickUpLocationId: $("#PickUpLocationId").data("kendoDropDownList").value(),        deliveryLocationId: $("#deliveryLocationId").data("kendoDropDownList").value() };
}
</code>```

AvailableShippingOptions Editor:

```<code>@(Html.Kendo().DropDownListFor(m => m)
.DataValueField("ShippingOptionId")
.DataTextField("ShippingOptionName")
.OptionLabel("Select...")
.AutoBind(false)
.DataSource(dataSource =>
              {
                  dataSource.Read(read =>
                  {
                      read.Action("GetAvailableShippingOptions", "ProductionZone").Type(HttpVerbs.Post)
                          .Data("filterShippingOptions");
                  }).ServerFiltering(true);
              })
              //.CascadeFrom("RMSupplierLocationViewModel")
              .CascadeFrom("DeliveryLocationViewModel")
)
    @Html.ValidationMessageFor(m => m)
</code>```

答:
I have achieved this as follows:

View code:

```<code><script>
    function filterShippingOptions() {
        return { locationId: $("#LocationViewModel").data("kendoDropDownList").value(), deliveryLocationId: $("#Location2ViewModel").data("kendoDropDownList").value() };
    }

function onCascade(e) {
  $("#ShippingOptionViewModel").data("kendoDropDownList").dataSource.read();
}
</script>
</code>```

Editor code:

```<code>@model Comanex.Models.ShippingOptionsViewModel
@(Html.Kendo().DropDownListFor(m => m)
    .DataValueField("ShippingOptionId")
    .DataTextField("ShippingOptionName")
    .OptionLabel("Select")
    .AutoBind(false)
    .DataSource(dataSource =>
                  {
                      dataSource.Read(read =>
                      {
                          read.Action("GetAvailableShippingOptions", "Shipping").Type(HttpVerbs.Post)
                              .Data("filterShippingOptions");
                      }).ServerFiltering(true);
                  })
)
@Html.ValidationMessageFor(m => m)
</code>```

Controller Method:

```<code>public JsonResult GetAvailableShippingOptions(string PickUpLocationId, string DeliveryLocationId)
    {
   //Getting value from database
        return Json(ShippingOptionRepository.GetAvailableShippingOptions(PickUpLocationId, DeliveryLocationId), JsonRequestBehavior.AllowGet);
    }
</code>```

Both the Parent controls(Dropdownlists in my case) should have following:

```<code>.Events(evnt => evnt.Cascade("onCascade")) //Need to add this Event on Parent Drop Downs
</code>```

Body:
I have three column in kendoui grid as "Delivery Location", "PickUp location" and "Available Shipping Options". When either of the location column changed("Delivery location" or "Pickup location"), the "Available shipping options" column should be changed accordingly.

I can achieve this using Cascade-from for two column(i.e. if one column changed, other would list the result based on the first column data) but don't know how to achieve same for two or more column.

How can i achieve cascading for two or more column?

Code:
JS Function:

    function filterShippingOptions() {
   return { pickUpLocationId: $("#PickUpLocationId").data("kendoDropDownList").value(),        deliveryLocationId: $("#deliveryLocationId").data("kendoDropDownList").value() };
}

AvailableShippingOptions Editor:

@(Html.Kendo().DropDownListFor(m => m)
.DataValueField("ShippingOptionId")
.DataTextField("ShippingOptionName")
.OptionLabel("Select...")
.AutoBind(false)
.DataSource(dataSource =>
              {
                  dataSource.Read(read =>
                  {
                      read.Action("GetAvailableShippingOptions", "ProductionZone").Type(HttpVerbs.Post)
                          .Data("filterShippingOptions");
                  }).ServerFiltering(true);
              })
              //.CascadeFrom("RMSupplierLocationViewModel")
              .CascadeFrom("DeliveryLocationViewModel")
)
    @Html.ValidationMessageFor(m => m)

Body:
I have achieved this as follows:

View code:

<script>
    function filterShippingOptions() {
        return { locationId: $("#LocationViewModel").data("kendoDropDownList").value(), deliveryLocationId: $("#Location2ViewModel").data("kendoDropDownList").value() };
    }

function onCascade(e) {
  $("#ShippingOptionViewModel").data("kendoDropDownList").dataSource.read();
}
</script>

Editor code:

@model Comanex.Models.ShippingOptionsViewModel
@(Html.Kendo().DropDownListFor(m => m)
    .DataValueField("ShippingOptionId")
    .DataTextField("ShippingOptionName")
    .OptionLabel("Select")
    .AutoBind(false)
    .DataSource(dataSource =>
                  {
                      dataSource.Read(read =>
                      {
                          read.Action("GetAvailableShippingOptions", "Shipping").Type(HttpVerbs.Post)
                              .Data("filterShippingOptions");
                      }).ServerFiltering(true);
                  })
)
@Html.ValidationMessageFor(m => m)

Controller Method:

public JsonResult GetAvailableShippingOptions(string PickUpLocationId, string DeliveryLocationId)
    {
   //Getting value from database
        return Json(ShippingOptionRepository.GetAvailableShippingOptions(PickUpLocationId, DeliveryLocationId), JsonRequestBehavior.AllowGet);
    }

Both the Parent controls(Dropdownlists in my case) should have following:

.Events(evnt => evnt.Cascade("onCascade")) //Need to add this Event on Parent Drop Downs


来源: stackexchange

问:
Android Studio AVD error launching
I have a Nexus 6P API23 emulator downloaded on my Ubuntu 15.10 PC. When I try to launch it, it fails and a dialog box pops up and says:

(AVD config: Nexus 6P API 23 x86 -- Hardware-GLES 2.0 Graphics)

```<code>Cannot launch AVD in emulator.
Output:
libGL error: unable to load driver: nouveau_dri.so
libGL error: driver pointer missing
libGL error: failed to load driver: nouveau
libGL error: unable to load driver: swrast_dri.so
libGL error: failed to load driver: swrast
X Error of failed request:  GLXBadContext
  Major opcode of failed request:  155 (GLX)
  Minor opcode of failed request:  6 (X_GLXIsDirect)
  Serial number of failed request:  47
  Current serial number in output stream:  46
libGL error: unable to load driver: nouveau_dri.so
libGL error: driver pointer missing
libGL error: failed to load driver: nouveau
libGL error: unable to load driver: swrast_dri.so
libGL error: failed to load driver: swrast
X Error of failed request:  GLXBadContext
  Major opcode of failed request:  155 (GLX)
  Minor opcode of failed request:  6 (X_GLXIsDirect)
  Serial number of failed request:  47
  Current serial number in output stream:  46
libGL error: unable to load driver: nouveau_dri.so
libGL error: driver pointer missing
libGL error: failed to load driver: nouveau
libGL error: unable to load driver: swrast_dri.so
libGL error: failed to load driver: swrast
X Error of failed request:  BadValue (integer parameter out of range for operation)
  Major opcode of failed request:  155 (GLX)
  Minor opcode of failed request:  24 (X_GLXCreateNewContext)
  Value in failed request:  0x0
  Serial number of failed request:  33
  Current serial number in output stream:  34
QObject::~QObject: Timers cannot be stopped from another thread
</code>```

I have tried other AVDs and they don't work.

答:
My case: I work with Debian Jessie and Android Studio 2.2.3. My graphic card is an ATI Radeon HD 6850 by Sapphire.

The emulator says that there is a problem loading the graphic driver ("libGL error: unable to load driver: r600_dri.so"). As it is explained here, it seems that Google packaged with Android Studio an old version of one library (libstdc++.so.6), and the emulator fails when it tries to use the graphic card.

Solution? Very easy: to use the system libraries instead of the packaged in Android Studio. How? Adding "-use-system-libs" at the end of the command. So:

```<code>./emulator -avd EMULATOR_NAME -netspeed full -netdelay none -use-system-libs
</code>```

The definitive solution (if you don't want to use the terminal) is to set the ANDROID_EMULATOR_USE_SYSTEM_LIBS environment variable to 1 for your user/system. With this change, when you run the emulator within Android Studio, it will also load the system libraries instead of the packaged.

PS - The easiest way I found to set the environment variable, it's to modify the script that launch the Android Studio (studio.sh, in my case it is inside /opt/android-stuido/bin), and add at the begining this:

```<code>export ANDROID_EMULATOR_USE_SYSTEM_LIBS=1
</code>```

UPDATE December 2017: I had the same problem with Debian Stretch and Android Studio 3.0.1 (same graphic card). The same solution works for me.

ContentLicense: CC BY-SA 3.0

Title: Android Studio AVD error launching

Body:
I have a Nexus 6P API23 emulator downloaded on my Ubuntu 15.10 PC. When I try to launch it, it fails and a dialog box pops up and says:

(AVD config: Nexus 6P API 23 x86 -- Hardware-GLES 2.0 Graphics)

Cannot launch AVD in emulator.
Output:
libGL error: unable to load driver: nouveau_dri.so
libGL error: driver pointer missing
libGL error: failed to load driver: nouveau
libGL error: unable to load driver: swrast_dri.so
libGL error: failed to load driver: swrast
X Error of failed request:  GLXBadContext
  Major opcode of failed request:  155 (GLX)
  Minor opcode of failed request:  6 (X_GLXIsDirect)
  Serial number of failed request:  47
  Current serial number in output stream:  46
libGL error: unable to load driver: nouveau_dri.so
libGL error: driver pointer missing
libGL error: failed to load driver: nouveau
libGL error: unable to load driver: swrast_dri.so
libGL error: failed to load driver: swrast
X Error of failed request:  GLXBadContext
  Major opcode of failed request:  155 (GLX)
  Minor opcode of failed request:  6 (X_GLXIsDirect)
  Serial number of failed request:  47
  Current serial number in output stream:  46
libGL error: unable to load driver: nouveau_dri.so
libGL error: driver pointer missing
libGL error: failed to load driver: nouveau
libGL error: unable to load driver: swrast_dri.so
libGL error: failed to load driver: swrast
X Error of failed request:  BadValue (integer parameter out of range for operation)
  Major opcode of failed request:  155 (GLX)
  Minor opcode of failed request:  24 (X_GLXCreateNewContext)
  Value in failed request:  0x0
  Serial number of failed request:  33
  Current serial number in output stream:  34
QObject::~QObject: Timers cannot be stopped from another thread

I have tried other AVDs and they don't work.

Body:
My case: I work with Debian Jessie and Android Studio 2.2.3. My graphic card is an ATI Radeon HD 6850 by Sapphire.

The emulator says that there is a problem loading the graphic driver ("libGL error: unable to load driver: r600_dri.so"). As it is explained here, it seems that Google packaged with Android Studio an old version of one library (libstdc++.so.6), and the emulator fails when it tries to use the graphic card.

Solution? Very easy: to use the system libraries instead of the packaged in Android Studio. How? Adding "-use-system-libs" at the end of the command. So:

./emulator -avd EMULATOR_NAME -netspeed full -netdelay none -use-system-libs

The definitive solution (if you don't want to use the terminal) is to set the ANDROID_EMULATOR_USE_SYSTEM_LIBS environment variable to 1 for your user/system. With this change, when you run the emulator within Android Studio, it will also load the system libraries instead of the packaged.

PS - The easiest way I found to set the environment variable, it's to modify the script that launch the Android Studio (studio.sh, in my case it is inside /opt/android-stuido/bin), and add at the begining this:

export ANDROID_EMULATOR_USE_SYSTEM_LIBS=1

UPDATE December 2017: I had the same problem with Debian Stretch and Android Studio 3.0.1 (same graphic card). The same solution works for me.


问:
Hide select if when don´t found any results
I have a select like this:

```<code><select class="form-control" ng-change="filtro(selected)" ng-model="selected" ng-options="item.Nombre for item in Catalogos"></select>
</code>```

I try to hide select if I don´t have options with ng-hide as:

```<code><select class="form-control" ng-change="filtro(selected)" ng-model="selected" ng-options="item.Nombre for item in Catalogos " ng-hide="item.Catalogos == 0"></select>
</code>```

or with ng-show as:

```<code><select class="form-control" ng-show="Catalogos" ng-change="filtro(selected)" ng-model="selected" ng-options="item.Nombre for item in Catalogos "></select>
</code>```

But no one works, it still showing up, can anyone help me there?

Note: I found an issue, if I debbug select with chrome or firefox I
  get a default option as:

```<code><option value="?" selected="selected"></option>
</code>```

Is it possible to skip this?

答:
You should check the length of catalogos

```<code><select class="form-control" ng-show="Catalogos.length>0" ng-change="filtro(selected)" ng-model="selected" ng-options="item.Nombre for item in Catalogos "></select>
</code>```

Or you need to convert it to boolean

```<code><select class="form-control" ng-show="!!Catalogos" ng-change="filtro(selected)" ng-model="selected" ng-options="item.Nombre for item in Catalogos "></select>
</code>```

Same process can be followed for ng-hide

```<code><select class="form-control" ng-hide="Catalogos.length==0" ng-change="filtro(selected)" ng-model="selected" ng-options="item.Nombre for item in Catalogos "></select>
</code>```

Or

```<code><select class="form-control" ng-hide="!Catalogos" ng-change="filtro(selected)" ng-model="selected" ng-options="item.Nombre for item in Catalogos "></select>
</code>```

Body:
I have a select like this:

<select class="form-control" ng-change="filtro(selected)" ng-model="selected" ng-options="item.Nombre for item in Catalogos"></select>

I try to hide select if I don´t have options with ng-hide as:

<select class="form-control" ng-change="filtro(selected)" ng-model="selected" ng-options="item.Nombre for item in Catalogos " ng-hide="item.Catalogos == 0"></select>

or with ng-show as:

<select class="form-control" ng-show="Catalogos" ng-change="filtro(selected)" ng-model="selected" ng-options="item.Nombre for item in Catalogos "></select>

But no one works, it still showing up, can anyone help me there?

Note: I found an issue, if I debbug select with chrome or firefox I
  get a default option as:

<option value="?" selected="selected"></option>

Is it possible to skip this?

Body:
You should check the length of catalogos

<select class="form-control" ng-show="Catalogos.length>0" ng-change="filtro(selected)" ng-model="selected" ng-options="item.Nombre for item in Catalogos "></select>

Or you need to convert it to boolean

<select class="form-control" ng-show="!!Catalogos" ng-change="filtro(selected)" ng-model="selected" ng-options="item.Nombre for item in Catalogos "></select>

Same process can be followed for ng-hide

<select class="form-control" ng-hide="Catalogos.length==0" ng-change="filtro(selected)" ng-model="selected" ng-options="item.Nombre for item in Catalogos "></select>

Or

<select class="form-control" ng-hide="!Catalogos" ng-change="filtro(selected)" ng-model="selected" ng-options="item.Nombre for item in Catalogos "></select>


问:
Configure SSL and ACLs for kafka-console-consumer
I am adding SSL security to my Confluent-3.0.1 Kafka Cluster following the instructions here and here.

In the Linux transaction snippets below, I have replaced my server names with myserverA, myserverB and myserverC. I also obscured passwords. This is my first posting on a message board. I apologize for any poorly formatted sections of this post.

My questions:

What ACL controls the access to fetch offsets shown just below?
Do I need to change my configuration or SSL keys?

Many thanks for any assistance you may be able to provide.

I was able to produce data using the kafka-console-producer over SSL, but can not read the data using the kafka-console-consumer. I receive the following error:

```<code>[kafka@myserverA confluent-3.0.1]$ /kafka/confluent-3.0.1/bin/kafka-console-consumer --bootstrap-server myserverA:9093 --zookeeper myserverA:2181/kafka --topic ssl-test --from-beginning --new-consumer --consumer.config /kafka/data/client/ssl/client.properties
[2017-06-27 13:11:50,462] WARN Attempt to fetch offsets for partition ssl-test-0 failed due to: Not authorized to access topics: [Topic authorization failed.] (org.apache.kafka.clients.consumer.internals.Fetcher)
[2017-06-27 13:11:50,473] WARN Error while fetching metadata with correlation id 6 : {ssl-test=TOPIC_AUTHORIZATION_FAILED} (org.apache.kafka.clients.NetworkClient)
[2017-06-27 13:11:50,476] ERROR Unknown error when running consumer:  (kafka.tools.ConsoleConsumer$)
org.apache.kafka.common.errors.TopicAuthorizationException: Not authorized to access topics: [ssl-test]
</code>```

It is not clear if my problem is in the client configuration, or the inter-broker configuration.

The server.properties file on each of my three brokers includes the following:

```<code>###################### SSL Configuration ################
#
ssl.keystore.location=/kafka/data/ssl/keystore/kafka.keystore.jks
ssl.keystore.password=<hidden for this posting>
ssl.key.password=<hidden for this posting>
ssl.truststore.location=/kafka/data/ssl/truststore/kafka.truststore.jks
ssl.truststore.password=<hidden for this posting>

ssl.client.auth=requested
#ssl.cipher.suites=
ssl.enabled.protocols = TLSv1.2,TLSv1.1,TLSv1
ssl.keystore.type = JKS
ssl.truststore.type = JKS

security.inter.broker.protocol=ssl

# #### Enable ACLs ####
authorizer.class.name=kafka.security.auth.SimpleAclAuthorizer
allow.everyone.if.no.acl.found=true

super.users=User:CN=myserverA,OU=NBCUniversal,O=NBCUniversal,L=NY,ST=NY,C=US;User:myserverB,OU=NBCUniversal,O=NBCUniversal,L=NY,ST=NY,C=US;User:CN=myserverC,OU=NBCUniversal,O=NBCUniversal,L=NY,ST=NY,C=US
</code>```

I use the same client.properties for the producer.config and consumer.config. It contains the following:

```<code>###################### SSL Configuration ################
#
security.protocol=ssl

ssl.keystore.location=/kafka/data/client/ssl/keystore/kafka.client.keystore.jks
ssl.keystore.password=<hidden for this posting>
ssl.key.password=<hidden for this posting>
ssl.truststore.location=/kafka/data/client/ssl/truststore/kafka.client.truststore.jks
ssl.truststore.password=<hidden for this posting>

#ssl.provider=
#ssl.cipher.suites=
ssl.enabled.protocols = TLSv1.2,TLSv1.1,TLSv1
ssl.keystore.type = JKS
ssl.truststore.type = JKS
</code>```

I have a large number of ACL grants on the ssl-test topic. I have tried: 1)SSL Dnames with spaces after commas, 2) SSL Dnames with no spaces after commas, 3) SSL Common Names for broker certs

```<code>[root@myserverA ~]# /kafka/confluent-3.0.1/bin/kafka-acls --authorizer-properties zookeeper.connect=myserverA:2181/kafka --list --topic ssl-test
Current ACLs for resource `Topic:ssl-test`:
User:CN=Test Client,OU=Test Client Unit,O=Test Client Org,L=LA,ST=CA,C=US has Allow permission for operations: Read from hosts: *
User:CN=Test Client, OU=Test Client Unit, O=Test Client Org, L=LA, ST=CA, C=US has Allow permission for operations: Read from hosts: *
User:myserverA has Allow permission for operations: Write from hosts: *
User:myserverC has Allow permission for operations: Read from hosts: *
User:CN=myserverB,OU=NBCUniversal,O=NBCUniversal,L=NY,ST=NY,C=US has Allow permission for operations: Write from hosts: *
User:CN=myserverA,OU=NBCUniversal,O=NBCUniversal,L=NY,ST=NY,C=US has Allow permission for operations: Read from hosts: *
User:Test Client has Allow permission for operations: Read from hosts: *
User:Test Client has Allow permission for operations: Write from hosts: *
User:myserverB has Allow permission for operations: Write from hosts: *
User:CN=Test Client,OU=Test Client Unit,O=Test Client Org,L=LA,ST=CA,C=US has Allow permission for operations: Write from hosts: *
User:CN=myserverC,OU=NBCUniversal,O=NBCUniversal,L=NY,ST=NY,C=US has Allow permission for operations: Read from hosts: *
User:CN=myserverA,OU=NBCUniversal,O=NBCUniversal,L=NY,ST=NY,C=US has Allow permission for operations: Write from hosts: *
User:CN=myserverB,OU=NBCUniversal,O=NBCUniversal,L=NY,ST=NY,C=US has Allow permission for operations: Read from hosts: *
User:myserverB has Allow permission for operations: Read from hosts: *
User:myserverA has Allow permission for operations: Read from hosts: *
User:CN=Test Client, OU=Test Client Unit, O=Test Client Org, L=LA, ST=CA, C=US has Allow permission for operations: Write from hosts: *
 ser:myserverC has Allow permission for operations: Write from hosts: *
 ser:CN=myserverC,OU=NBCUniversal,O=NBCUniversal,L=NY,ST=NY,C=US has Allow permission for operations: Write from hosts: *
</code>```

The kafka-console-producer functions normally through SSL:

```<code>[kafka@myserverA confluent-3.0.1]$ bin/kafka-console-producer --broker-list myserverA:9093 --topic ssl-test --producer.config /kafka/data/client/ssl/client.properties
j
k
<Ctrl-D>
</code>```

答: There were multiple issues in my Kafka SSL configuration. However, the explicit error "WARN Attempt to fetch offsets for partition ssl-test-0 failed..." while running kafka-console-consumer was due to the fact that the Client Certificate was not included in the truststore for kafka node B and C.</p>

Body:
I am adding SSL security to my Confluent-3.0.1 Kafka Cluster following the instructions here and here.

In the Linux transaction snippets below, I have replaced my server names with myserverA, myserverB and myserverC. I also obscured passwords. This is my first posting on a message board. I apologize for any poorly formatted sections of this post.

My questions:

What ACL controls the access to fetch offsets shown just below?
Do I need to change my configuration or SSL keys?

Many thanks for any assistance you may be able to provide.

I was able to produce data using the kafka-console-producer over SSL, but can not read the data using the kafka-console-consumer. I receive the following error:

[kafka@myserverA confluent-3.0.1]$ /kafka/confluent-3.0.1/bin/kafka-console-consumer --bootstrap-server myserverA:9093 --zookeeper myserverA:2181/kafka --topic ssl-test --from-beginning --new-consumer --consumer.config /kafka/data/client/ssl/client.properties
[2017-06-27 13:11:50,462] WARN Attempt to fetch offsets for partition ssl-test-0 failed due to: Not authorized to access topics: [Topic authorization failed.] (org.apache.kafka.clients.consumer.internals.Fetcher)
[2017-06-27 13:11:50,473] WARN Error while fetching metadata with correlation id 6 : {ssl-test=TOPIC_AUTHORIZATION_FAILED} (org.apache.kafka.clients.NetworkClient)
[2017-06-27 13:11:50,476] ERROR Unknown error when running consumer:  (kafka.tools.ConsoleConsumer$)
org.apache.kafka.common.errors.TopicAuthorizationException: Not authorized to access topics: [ssl-test]

It is not clear if my problem is in the client configuration, or the inter-broker configuration.

The server.properties file on each of my three brokers includes the following:

###################### SSL Configuration ################
#
ssl.keystore.location=/kafka/data/ssl/keystore/kafka.keystore.jks
ssl.keystore.password=<hidden for this posting>
ssl.key.password=<hidden for this posting>
ssl.truststore.location=/kafka/data/ssl/truststore/kafka.truststore.jks
ssl.truststore.password=<hidden for this posting>

ssl.client.auth=requested
#ssl.cipher.suites=
ssl.enabled.protocols = TLSv1.2,TLSv1.1,TLSv1
ssl.keystore.type = JKS
ssl.truststore.type = JKS

security.inter.broker.protocol=ssl

# #### Enable ACLs ####
authorizer.class.name=kafka.security.auth.SimpleAclAuthorizer
allow.everyone.if.no.acl.found=true

super.users=User:CN=myserverA,OU=NBCUniversal,O=NBCUniversal,L=NY,ST=NY,C=US;User:myserverB,OU=NBCUniversal,O=NBCUniversal,L=NY,ST=NY,C=US;User:CN=myserverC,OU=NBCUniversal,O=NBCUniversal,L=NY,ST=NY,C=US

I use the same client.properties for the producer.config and consumer.config. It contains the following:

###################### SSL Configuration ################
#
security.protocol=ssl

ssl.keystore.location=/kafka/data/client/ssl/keystore/kafka.client.keystore.jks
ssl.keystore.password=<hidden for this posting>
ssl.key.password=<hidden for this posting>
ssl.truststore.location=/kafka/data/client/ssl/truststore/kafka.client.truststore.jks
ssl.truststore.password=<hidden for this posting>

#ssl.provider=
#ssl.cipher.suites=
ssl.enabled.protocols = TLSv1.2,TLSv1.1,TLSv1
ssl.keystore.type = JKS
ssl.truststore.type = JKS

I have a large number of ACL grants on the ssl-test topic. I have tried: 1)SSL Dnames with spaces after commas, 2) SSL Dnames with no spaces after commas, 3) SSL Common Names for broker certs

[root@myserverA ~]# /kafka/confluent-3.0.1/bin/kafka-acls --authorizer-properties zookeeper.connect=myserverA:2181/kafka --list --topic ssl-test
Current ACLs for resource `Topic:ssl-test`:
User:CN=Test Client,OU=Test Client Unit,O=Test Client Org,L=LA,ST=CA,C=US has Allow permission for operations: Read from hosts: *
User:CN=Test Client, OU=Test Client Unit, O=Test Client Org, L=LA, ST=CA, C=US has Allow permission for operations: Read from hosts: *
User:myserverA has Allow permission for operations: Write from hosts: *
User:myserverC has Allow permission for operations: Read from hosts: *
User:CN=myserverB,OU=NBCUniversal,O=NBCUniversal,L=NY,ST=NY,C=US has Allow permission for operations: Write from hosts: *
User:CN=myserverA,OU=NBCUniversal,O=NBCUniversal,L=NY,ST=NY,C=US has Allow permission for operations: Read from hosts: *
User:Test Client has Allow permission for operations: Read from hosts: *
User:Test Client has Allow permission for operations: Write from hosts: *
User:myserverB has Allow permission for operations: Write from hosts: *
User:CN=Test Client,OU=Test Client Unit,O=Test Client Org,L=LA,ST=CA,C=US has Allow permission for operations: Write from hosts: *
User:CN=myserverC,OU=NBCUniversal,O=NBCUniversal,L=NY,ST=NY,C=US has Allow permission for operations: Read from hosts: *
User:CN=myserverA,OU=NBCUniversal,O=NBCUniversal,L=NY,ST=NY,C=US has Allow permission for operations: Write from hosts: *
User:CN=myserverB,OU=NBCUniversal,O=NBCUniversal,L=NY,ST=NY,C=US has Allow permission for operations: Read from hosts: *
User:myserverB has Allow permission for operations: Read from hosts: *
User:myserverA has Allow permission for operations: Read from hosts: *
User:CN=Test Client, OU=Test Client Unit, O=Test Client Org, L=LA, ST=CA, C=US has Allow permission for operations: Write from hosts: *
 ser:myserverC has Allow permission for operations: Write from hosts: *
 ser:CN=myserverC,OU=NBCUniversal,O=NBCUniversal,L=NY,ST=NY,C=US has Allow permission for operations: Write from hosts: *

The kafka-console-producer functions normally through SSL:

[kafka@myserverA confluent-3.0.1]$ bin/kafka-console-producer --broker-list myserverA:9093 --topic ssl-test --producer.config /kafka/data/client/ssl/client.properties
j
k
<Ctrl-D>


问:
Are string literals const?
Both GCC and Clang do not complain if I assign a string literal to a char*, even when using lots of pedantic options (-Wall -W -pedantic -std=c99):

```<code>char *foo = "bar";
</code>```

while they (of course) do complain if I assign a const char* to a char*.

Does this mean that string literals are considered to be of char* type? Shouldn't they be const char*? It's not defined behavior if they get modified!

And (an uncorrelated question) what about command line parameters (ie: argv): is it considered to be an array of string literals?

答:
In both C89 and C99, string literals are of type char * (for historical reasons, as I understand it). You are correct that trying to modify one results in undefined behavior. GCC has a specific warning flag, -Wwrite-strings (which is not part of -Wall), that will warn you if you try to do so.

As for argv, the arguments are copied into your program's address space, and can safely be modified in your main() function.

EDIT: Whoops, had -Wno-write-strings copied by accident. Updated with the correct (positive) form of the warning flag.

ContentLicense: CC BY-SA 2.5

Title: Are string literals const?

Body:
Both GCC and Clang do not complain if I assign a string literal to a char*, even when using lots of pedantic options (-Wall -W -pedantic -std=c99):

char *foo = "bar";

while they (of course) do complain if I assign a const char* to a char*.

Does this mean that string literals are considered to be of char* type? Shouldn't they be const char*? It's not defined behavior if they get modified!

And (an uncorrelated question) what about command line parameters (ie: argv): is it considered to be an array of string literals?


问:
What does "object" mean in a purely object-oriented language

I often hear

In a purely object-oriented language, everything is an object.

Is an "object" defined as an instance of some class?

They said that Java isn't pure OO, because of its builtin types. So
are its builtin types not objects, and  in what sense?

Is Python3 pure OO?

Thanks.

答:
Short answer yes.  Objects are instantiated classes. To extend this to a real world analogy, you could have a class of Bike that represents all bikes on a general level.  An object of bike would represent one particular bike.

Java has 8 primitives that are not objects.  boolean, char, int, long, short, byte, float, double. Everything else is an object and inherits from Object class.  These primitives have wrapper classes that give them functionality of Objects, just replace the first letter in each with a capital letter.

In python everything is an object.  I can call (5).__add__(6) in python because 5 is literally an object.  In Java it is not.


问:
ngx-bootstrap typeahead with FormControl angular 2
here is a simple problem I can't find a solution to. I have a typeahead directive in input which lets a user to choose a category ( category array example -> [{ id: 1as1d, name: 'some category'},...]

How to set the id value to the FormControl field (which will appear in the submitted form) and display the name on the input (which will be showed in on the input while user is choosing)? Is there a way to separate what will be in the sent form and what is being showed while using FormControl?

I could only find a way to display and set the same variable either only id or only name.

```<code><input
    formControlName="category"
    [formControl]="userForm.controls['category']"
    [typeahead]="categoriesObservable"
    (typeaheadLoading)="toggleLoadingCategories($event)"
    (typeaheadNoResults)="toggleNoCategoriesFound($event)"
    (typeaheadOnBlur)="categoryFieldSelected($event)"
    (typeaheadOnSelect)="categoryFieldSelected($event)"
    typeaheadOptionsLimit="7"
    typeaheadOptionField="name"
    placeholder="Choose a category"
    class="form-control"/>
</code>```

答:
This will sound crazy but stay with me.

Just use a hidden input for the submit form and in the event typeaheadOnSelect assign the id value to the hidden input.

In case of loading data (editing old data) just use the category id to get the text and assign the name value to the typeahead.

Don't forget to use control.updateValueAndValidity() on the hidden input in typeaheadOnSelect event.

Body:
here is a simple problem I can't find a solution to. I have a typeahead directive in input which lets a user to choose a category ( category array example -> [{ id: 1as1d, name: 'some category'},...]

How to set the id value to the FormControl field (which will appear in the submitted form) and display the name on the input (which will be showed in on the input while user is choosing)? Is there a way to separate what will be in the sent form and what is being showed while using FormControl?

I could only find a way to display and set the same variable either only id or only name.

<input
    formControlName="category"
    [formControl]="userForm.controls['category']"
    [typeahead]="categoriesObservable"
    (typeaheadLoading)="toggleLoadingCategories($event)"
    (typeaheadNoResults)="toggleNoCategoriesFound($event)"
    (typeaheadOnBlur)="categoryFieldSelected($event)"
    (typeaheadOnSelect)="categoryFieldSelected($event)"
    typeaheadOptionsLimit="7"
    typeaheadOptionField="name"
    placeholder="Choose a category"
    class="form-control"/>


问:
Store token from OAuth2 server in cookie using Spring OAuth
Is there any configuration provided by Spring OAuth2 that does the creation of a cookie with the opaque or JWT token?
The configuration that I've found on the Internet so far describes the creation of an Authorization Server and a client for it. In my case the client is a gateway with an Angular 4 application sitting on top of it in the same deployable. The frontend makes requests to the gateway that routes them through Zuul.
Configuring the client using @EnableOAuth2Sso, an application.yml and a WebSecurityConfigurerAdapter makes all the necessary requests and redirects, adds the information to the SecurityContext but stores the information in a session, sending back a JSESSIONID cookie to the UI.

Is there any configuration or filter needed to create a cookie with the token information and then use a stateless session that I can use? Or do I have to create it myself and then create a filter that looks for the token?

    @SpringBootApplication
    @EnableOAuth2Sso
    @RestController
    public class ClientApplication extends WebSecurityConfigurerAdapter{

        @RequestMapping("/user")
        public String home(Principal user) {
            return "Hello " + user.getName();
        }

        public static void main(String[] args) {
            new SpringApplicationBuilder(ClientApplication.class).run(args);
        }

        @Override
        public void configure(HttpSecurity http) throws Exception {
            http
                    .antMatcher("/**").authorizeRequests()
                    .antMatchers("/", "/login**", "/webjars/**").permitAll()
                    .anyRequest()
                    .authenticated()
                    .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        }
    }

    server:
      port: 9999
      context-path: /client
    security:
      oauth2:
        client:
          clientId: acme
          clientSecret: acmesecret
          accessTokenUri: http://localhost:9080/uaa/oauth/token
          userAuthorizationUri: http://localhost:9080/uaa/oauth/authorize
          tokenName: access_token
          authenticationScheme: query
          clientAuthenticationScheme: form
        resource:
          userInfoUri: http://localhost:9080/uaa/me

```

答:
Make sure you have imported these classes present in javax.servlet:

```<code>import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
</code>```

Initialize cookie like this:

```<code>Cookie jwtCookie = new Cookie(APP_COOKIE_TOKEN, token.getToken());
jwtCookie.setPath("/");
jwtCookie.setMaxAge(20*60);
//Cookie cannot be accessed via JavaScript
jwtCookie.setHttpOnly(true);
</code>```

Add cookie in HttpServletResponse:

```<code>response.addCookie(jwtCookie);
</code>```

If you are using angular 4 and spring security+boot , then this github repo can become a big help:

Reference blog for this repo is:

ContentLicense: CC BY-SA 4.0

Body:
Make sure you have imported these classes present in javax.servlet:

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

Initialize cookie like this:

Cookie jwtCookie = new Cookie(APP_COOKIE_TOKEN, token.getToken());
jwtCookie.setPath("/");
jwtCookie.setMaxAge(20*60);
//Cookie cannot be accessed via JavaScript
jwtCookie.setHttpOnly(true);

Add cookie in HttpServletResponse:

response.addCookie(jwtCookie);

If you are using angular 4 and spring security+boot , then this github repo can become a big help:

Reference blog for this repo is:


问:
Padding for bitmap file
I want to be able to resize bitmap pictures in C and I believe that there is some padding problem that makes the new picture come out wrong, but I do not know what the problem is.

```<code>/**
* Copies a BMP piece by piece, just because.
*/

#include <stdio.h>
#include <stdlib.h>

#include "bmp.h"

int main(int argc, char *argv[])
{

double n = atof(argv[1]);

// ensure proper usage
if (argc != 4)
{
    fprintf(stderr, "Usage: ./resize n infile outfile\n");
    return 1;
}

if (n >= 100 || n < 0)
{
    fprintf(stderr, "n must be positibe and less than 100\n");
    return 1;
}

// remember filenames
char *infile = argv[2];
char *outfile = argv[3];

// open input file
FILE *inptr = fopen(infile, "r");
if (inptr == NULL)
{
    fprintf(stderr, "Could not open %s.\n", infile);
    return 2;
}

// open output file
FILE *outptr = fopen(outfile, "w");
if (outptr == NULL)
{
    fclose(inptr);
    fprintf(stderr, "Could not create %s.\n", outfile);
    return 3;
}

// read infile's BITMAPFILEHEADER
BITMAPFILEHEADER bf;
fread(&bf, sizeof(BITMAPFILEHEADER), 1, inptr);

// read infile's BITMAPINFOHEADER
BITMAPINFOHEADER bi;
fread(&bi, sizeof(BITMAPINFOHEADER), 1, inptr);

// ensure infile is (likely) a 24-bit uncompressed BMP 4.0
if (bf.bfType != 0x4d42 || bf.bfOffBits != 54 || bi.biSize != 40 ||
    bi.biBitCount != 24 || bi.biCompression != 0)
{
    fclose(outptr);
    fclose(inptr);
    fprintf(stderr, "Unsupported file format.\n");
    return 4;
}

// Change height and width
bi.biHeight *= n;
bi.biWidth *= n;

// determine padding for outfile scanlines
int padding = (4 - (bi.biWidth * sizeof(RGBTRIPLE)) % 4) % 4;

// Change size and image size
bi.biSizeImage = ((sizeof(RGBTRIPLE) * bi.biWidth) + padding) * abs(bi.biHeight);
bf.bfSize = bi.biSizeImage + sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);

// write outfile's BITMAPFILEHEADER
fwrite(&bf, sizeof(BITMAPFILEHEADER), 1, outptr);

// write outfile's BITMAPINFOHEADER
fwrite(&bi, sizeof(BITMAPINFOHEADER), 1, outptr);

// iterate over infile's scanlines
for (int i = 0, biHeight = abs(bi.biHeight); i < biHeight; i++)
{
    //resize vertically
    for (int j = 0; j < n; j++)
    {
        // temporary storage
        RGBTRIPLE triple;

        // read RGB triple from infile
        fread(&triple, sizeof(RGBTRIPLE), 1, inptr);

        // iterate over pixels in scanline
        for (int k = 0; k < bi.biWidth; k++)
        {
            // write RGB triple to outfile
            fwrite(&triple, sizeof(RGBTRIPLE), n, outptr);
        }
        // Add padding, if necessary
        for (int l = 0; l < padding; l++)
        {
            fwrite(0x00, 1, padding, outptr);
        }
        if (j == n - 1)
        {
            // skip over padding, if any
            fseek(inptr, padding, SEEK_CUR);
        }
        else
        {
            fseek(inptr, bi.biWidth, SEEK_CUR);
        }
    }
}

// close infile
fclose(inptr);

// close outfile
fclose(outptr);

// success
return 0;
}
</code>```

Sorry for the horrible spacing.

答:
You use the same padding for the infile as for the outfile and you mixed up the pixels.</p>

```<code>// read infile's BITMAPFILEHEADER
BITMAPFILEHEADER bf;
fread(&bf, sizeof(BITMAPFILEHEADER), 1, inptr);

// read infile's BITMAPINFOHEADER
BITMAPINFOHEADER bi_in;
fread(&bi_in, sizeof(BITMAPINFOHEADER), 1, inptr);

// ensure infile is (likely) a 24-bit uncompressed BMP 4.0
if (bf.bfType != 0x4d42 || bf.bfOffBits != 54 || bi_in.biSize != 40 ||
    bi_in.biBitCount != 24 || bi_in.biCompression != 0)
{
    fclose(outptr);
    fclose(inptr);
    fprintf(stderr, "Unsupported file format.\n");
    return 4;
}

// build outfile's BITMAPINFOHEADER and Change height and width
BITMAPINFOHEADER bi_out;
bi_out=bi_in;

bi_out.biHeight *= n;
bi_out.biWidth *= n;

// determine paddings
int padding_in  = (4 - (bi_in.biWidth  * sizeof(RGBTRIPLE)) % 4) % 4;
int padding_out = (4 - (bi_out.biWidth * sizeof(RGBTRIPLE)) % 4) % 4;

// Change size and image size
bi_out.biSizeImage = ((sizeof(RGBTRIPLE) * bi_out.biWidth) + padding_out) * abs(bi_out.biHeight);
bf.bfSize = bi_out.biSizeImage + sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);

// write outfile's BITMAPFILEHEADER
fwrite(&bf, sizeof(BITMAPFILEHEADER), 1, outptr);

// write outfile's BITMAPINFOHEADER
fwrite(&bi_out, sizeof(BITMAPINFOHEADER), 1, outptr);

// iterate over infile's scanlines
for (int i = abs(bi_in.biHeight); i--;)
{
    long StartOfScanline = ftell(inptr); //we have to return here
    //resize vertically, issue the same line n times
    for (int j = 0; j < n; j++)
    {
        fseek(inptr,StartOfScanline, SEEK_SET); //go to start of line
        for (int k=bi_in.biWidth; k--;) //for each pixel in line...
        {
            RGBTRIPLE triple;
            // read one RGB triple from infile
            fread(&triple, sizeof(RGBTRIPLE), 1, inptr);
            for (int l=n;l--;) //write out pix n times
                fwrite(&triple, sizeof(RGBTRIPLE), 1, outptr);
        }
        // Add padding, if necessary
        //This was wrong: fwrite needs a pointer to data, and not 0x00!!
        //for (int l = 0; l < padding_out; l++)
        //    fwrite(0x00, 1, 1, outptr);
        //FIXED:
        static const char Padding[4]={0,0,0,0};
        fwrite(Padding, padding_out, 1, outptr);

    }
    //add padding to infile
    fseek(inptr, padding_in, SEEK_CUR);
}
</code>```

Title: Padding for bitmap file

Body:
I want to be able to resize bitmap pictures in C and I believe that there is some padding problem that makes the new picture come out wrong, but I do not know what the problem is.

/**
* Copies a BMP piece by piece, just because.
*/

#include <stdio.h>
#include <stdlib.h>

#include "bmp.h"

int main(int argc, char *argv[])
{

double n = atof(argv[1]);

// ensure proper usage
if (argc != 4)
{
    fprintf(stderr, "Usage: ./resize n infile outfile\n");
    return 1;
}

if (n >= 100 || n < 0)
{
    fprintf(stderr, "n must be positibe and less than 100\n");
    return 1;
}

// remember filenames
char *infile = argv[2];
char *outfile = argv[3];

// open input file
FILE *inptr = fopen(infile, "r");
if (inptr == NULL)
{
    fprintf(stderr, "Could not open %s.\n", infile);
    return 2;
}

// open output file
FILE *outptr = fopen(outfile, "w");
if (outptr == NULL)
{
    fclose(inptr);
    fprintf(stderr, "Could not create %s.\n", outfile);
    return 3;
}

// read infile's BITMAPFILEHEADER
BITMAPFILEHEADER bf;
fread(&bf, sizeof(BITMAPFILEHEADER), 1, inptr);

// read infile's BITMAPINFOHEADER
BITMAPINFOHEADER bi;
fread(&bi, sizeof(BITMAPINFOHEADER), 1, inptr);

// ensure infile is (likely) a 24-bit uncompressed BMP 4.0
if (bf.bfType != 0x4d42 || bf.bfOffBits != 54 || bi.biSize != 40 ||
    bi.biBitCount != 24 || bi.biCompression != 0)
{
    fclose(outptr);
    fclose(inptr);
    fprintf(stderr, "Unsupported file format.\n");
    return 4;
}

// Change height and width
bi.biHeight *= n;
bi.biWidth *= n;

// determine padding for outfile scanlines
int padding = (4 - (bi.biWidth * sizeof(RGBTRIPLE)) % 4) % 4;

// Change size and image size
bi.biSizeImage = ((sizeof(RGBTRIPLE) * bi.biWidth) + padding) * abs(bi.biHeight);
bf.bfSize = bi.biSizeImage + sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);

// write outfile's BITMAPFILEHEADER
fwrite(&bf, sizeof(BITMAPFILEHEADER), 1, outptr);

// write outfile's BITMAPINFOHEADER
fwrite(&bi, sizeof(BITMAPINFOHEADER), 1, outptr);

// iterate over infile's scanlines
for (int i = 0, biHeight = abs(bi.biHeight); i < biHeight; i++)
{
    //resize vertically
    for (int j = 0; j < n; j++)
    {
        // temporary storage
        RGBTRIPLE triple;

        // read RGB triple from infile
        fread(&triple, sizeof(RGBTRIPLE), 1, inptr);

        // iterate over pixels in scanline
        for (int k = 0; k < bi.biWidth; k++)
        {
            // write RGB triple to outfile
            fwrite(&triple, sizeof(RGBTRIPLE), n, outptr);
        }
        // Add padding, if necessary
        for (int l = 0; l < padding; l++)
        {
            fwrite(0x00, 1, padding, outptr);
        }
        if (j == n - 1)
        {
            // skip over padding, if any
            fseek(inptr, padding, SEEK_CUR);
        }
        else
        {
            fseek(inptr, bi.biWidth, SEEK_CUR);
        }
    }
}

// close infile
fclose(inptr);

// close outfile
fclose(outptr);

// success
return 0;
}

Sorry for the horrible spacing.

Body:
You use the same padding for the infile as for the outfile and you mixed up the pixels.

// read infile's BITMAPFILEHEADER
BITMAPFILEHEADER bf;
fread(&bf, sizeof(BITMAPFILEHEADER), 1, inptr);

// read infile's BITMAPINFOHEADER
BITMAPINFOHEADER bi_in;
fread(&bi_in, sizeof(BITMAPINFOHEADER), 1, inptr);

// ensure infile is (likely) a 24-bit uncompressed BMP 4.0
if (bf.bfType != 0x4d42 || bf.bfOffBits != 54 || bi_in.biSize != 40 ||
    bi_in.biBitCount != 24 || bi_in.biCompression != 0)
{
    fclose(outptr);
    fclose(inptr);
    fprintf(stderr, "Unsupported file format.\n");
    return 4;
}

// build outfile's BITMAPINFOHEADER and Change height and width
BITMAPINFOHEADER bi_out;
bi_out=bi_in;

bi_out.biHeight *= n;
bi_out.biWidth *= n;

// determine paddings
int padding_in  = (4 - (bi_in.biWidth  * sizeof(RGBTRIPLE)) % 4) % 4;
int padding_out = (4 - (bi_out.biWidth * sizeof(RGBTRIPLE)) % 4) % 4;

// Change size and image size
bi_out.biSizeImage = ((sizeof(RGBTRIPLE) * bi_out.biWidth) + padding_out) * abs(bi_out.biHeight);
bf.bfSize = bi_out.biSizeImage + sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);

// write outfile's BITMAPFILEHEADER
fwrite(&bf, sizeof(BITMAPFILEHEADER), 1, outptr);

// write outfile's BITMAPINFOHEADER
fwrite(&bi_out, sizeof(BITMAPINFOHEADER), 1, outptr);

// iterate over infile's scanlines
for (int i = abs(bi_in.biHeight); i--;)
{
    long StartOfScanline = ftell(inptr); //we have to return here
    //resize vertically, issue the same line n times
    for (int j = 0; j < n; j++)
    {
        fseek(inptr,StartOfScanline, SEEK_SET); //go to start of line
        for (int k=bi_in.biWidth; k--;) //for each pixel in line...
        {
            RGBTRIPLE triple;
            // read one RGB triple from infile
            fread(&triple, sizeof(RGBTRIPLE), 1, inptr);
            for (int l=n;l--;) //write out pix n times
                fwrite(&triple, sizeof(RGBTRIPLE), 1, outptr);
        }
        // Add padding, if necessary
        //This was wrong: fwrite needs a pointer to data, and not 0x00!!
        //for (int l = 0; l < padding_out; l++)
        //    fwrite(0x00, 1, 1, outptr);
        //FIXED:
        static const char Padding[4]={0,0,0,0};
        fwrite(Padding, padding_out, 1, outptr);

    }
    //add padding to infile
    fseek(inptr, padding_in, SEEK_CUR);
}


问:
Twisted Python - Push data to websocket
I've a web-socket server which connects with the clients. Following is the code:-

```<code>from twisted.internet.protocol import Factory
from twisted.protocols.basic import LineReceiver
from twisted.internet import reactor

class Chat(LineReceiver):

    def __init__(self, users):
        self.users = users
        self.name = None
        self.state = "GETNAME"

    def connectionMade(self):
        self.sendLine("What's your name?")

    def connectionLost(self, reason):
        if self.users.has_key(self.name):
            del self.users[self.name]

    def lineReceived(self, line):
        if self.state == "GETNAME":
            self.handle_GETNAME(line)
        else:
            self.handle_CHAT(line)

    def handle_GETNAME(self, name):
        if self.users.has_key(name):
            self.sendLine("Name taken, please choose another.")
            return
        self.sendLine("Welcome, %s!" % (name,))
        self.name = name
        self.users[name] = self
        self.state = "CHAT"

    def handle_CHAT(self, message):
        # Need to send the message to the connected clients.

class ChatFactory(Factory):

    def __init__(self):
        self.users = {} # maps user names to Chat instances

    def buildProtocol(self, addr):
        return Chat(self.users)

reactor.listenTCP(8123, ChatFactory())
reactor.run()
</code>```

Clients get connected to the above code(server), and sends the data to the server.

Now, I've another python script, basically a scraper which scrapes the web, processes it and finally need to send the data to the connected clients.

script.py

```<code>while True:
    # call `send_message` function and send data to the connected clients.
</code>```

How can I achieve it?? Any example would be of great help!!

UPDATE

After using Autobahn

I've a server that fetches data from 3rd party API. I want to send this data to all the connected web-socket clients. Here is my code:-

```<code>class MyServerProtocol(WebSocketServerProtocol):
    def __init__(self):
        self.connected_users = []
        self.send_data()

    def onConnect(self, request):
        print("Client connecting: {0}".format(request.peer))

    def onOpen(self):
        print("WebSocket connection open.")
        self.connected_users.append(self)  # adding users to the connected_list

    def send_data(self):
        # fetch data from the API and forward it to the connected_users.
        for u in self.users:
            print 1111
            u.sendMessage('Hello, Some Data from API!', False)

    def onClose(self, wasClean, code, reason):
        connected_users.remove(self)  # remove user from the connected list of users
        print("WebSocket connection closed: {0}".format(reason))

if __name__ == '__main__':

    import sys

    from twisted.python import log
    from twisted.internet import reactor

    factory = WebSocketServerFactory(u"ws://127.0.0.1:9000")
    factory.protocol = MyServerProtocol

    reactor.listenTCP(9000, factory)
    reactor.run()
</code>```

My Server will never receive a message or probably will receive, but as of right now there's no such use-case, hence no need for OnMessage event for this example).

How do I write my send_data function in order to send data to all my connected clients??

答:
You need to avoid this pattern when writing software with Twisted:

```<code>while True:
    # call `send_message` function and send data to the connected clients.
</code>```

Twisted is a cooperative multitasking system.  "Cooperative" means that you have to give up control of execution periodically so that other tasks get a chance to run.

twisted.internet.task.LoopingCall can be used to replace many while ... loops (particularly while True loops):

```<code>from twisted.internet.task import LoopingCall
LoopingCall(one_iteration).start(iteration_interval)
</code>```

This will call one_iteration every iteration_interval seconds.  In between, it will give up control of execution so other tasks can run.

Making one_iteration send a message to a client is just a matter of giving one_iteration a reference to that client (or those clients, if there are many).

This is a variation on the FAQ How do I make Input on One Connection Result in Output on Another.

If you have a ChatFactory with a dict containing all your clients, just pass that factory to one_iteration:

```<code>LoopingCall(one_iteration, that_factory)
</code>```

or

```<code>LoopingCall(lambda: one_iteration(that_factory))
</code>```

Title: Twisted Python - Push data to websocket

Body:
I've a web-socket server which connects with the clients. Following is the code:-

from twisted.internet.protocol import Factory
from twisted.protocols.basic import LineReceiver
from twisted.internet import reactor

class Chat(LineReceiver):

    def __init__(self, users):
        self.users = users
        self.name = None
        self.state = "GETNAME"

    def connectionMade(self):
        self.sendLine("What's your name?")

    def connectionLost(self, reason):
        if self.users.has_key(self.name):
            del self.users[self.name]

    def lineReceived(self, line):
        if self.state == "GETNAME":
            self.handle_GETNAME(line)
        else:
            self.handle_CHAT(line)

    def handle_GETNAME(self, name):
        if self.users.has_key(name):
            self.sendLine("Name taken, please choose another.")
            return
        self.sendLine("Welcome, %s!" % (name,))
        self.name = name
        self.users[name] = self
        self.state = "CHAT"

    def handle_CHAT(self, message):
        # Need to send the message to the connected clients.

class ChatFactory(Factory):

    def __init__(self):
        self.users = {} # maps user names to Chat instances

    def buildProtocol(self, addr):
        return Chat(self.users)

reactor.listenTCP(8123, ChatFactory())
reactor.run()

Clients get connected to the above code(server), and sends the data to the server.

Now, I've another python script, basically a scraper which scrapes the web, processes it and finally need to send the data to the connected clients.

script.py

while True:
    # call `send_message` function and send data to the connected clients.

How can I achieve it?? Any example would be of great help!!

UPDATE

After using Autobahn

I've a server that fetches data from 3rd party API. I want to send this data to all the connected web-socket clients. Here is my code:-

class MyServerProtocol(WebSocketServerProtocol):
    def __init__(self):
        self.connected_users = []
        self.send_data()

    def onConnect(self, request):
        print("Client connecting: {0}".format(request.peer))

    def onOpen(self):
        print("WebSocket connection open.")
        self.connected_users.append(self)  # adding users to the connected_list

    def send_data(self):
        # fetch data from the API and forward it to the connected_users.
        for u in self.users:
            print 1111
            u.sendMessage('Hello, Some Data from API!', False)

    def onClose(self, wasClean, code, reason):
        connected_users.remove(self)  # remove user from the connected list of users
        print("WebSocket connection closed: {0}".format(reason))

if __name__ == '__main__':

    import sys

    from twisted.python import log
    from twisted.internet import reactor

    factory = WebSocketServerFactory(u"ws://127.0.0.1:9000")
    factory.protocol = MyServerProtocol

    reactor.listenTCP(9000, factory)
    reactor.run()

My Server will never receive a message or probably will receive, but as of right now there's no such use-case, hence no need for OnMessage event for this example).

How do I write my send_data function in order to send data to all my connected clients??

Body:
You need to avoid this pattern when writing software with Twisted:

while True:
    # call `send_message` function and send data to the connected clients.

Twisted is a cooperative multitasking system.  "Cooperative" means that you have to give up control of execution periodically so that other tasks get a chance to run.

twisted.internet.task.LoopingCall can be used to replace many while ... loops (particularly while True loops):

from twisted.internet.task import LoopingCall
LoopingCall(one_iteration).start(iteration_interval)

This will call one_iteration every iteration_interval seconds.  In between, it will give up control of execution so other tasks can run.

Making one_iteration send a message to a client is just a matter of giving one_iteration a reference to that client (or those clients, if there are many).

This is a variation on the FAQ How do I make Input on One Connection Result in Output on Another.

If you have a ChatFactory with a dict containing all your clients, just pass that factory to one_iteration:

LoopingCall(one_iteration, that_factory)

or

LoopingCall(lambda: one_iteration(that_factory))


问:
Error: Expecting a declaration TicTacToe Game
Hello yesterday I started Programming a little Tic Tac Toe game but today I found a mistake. The game ends in Draw if a return of '/'(just 'X' or 'O' if somebody wins) is shown and the counter shows 9 but it also ends if I make a mistake during game and input e.g. 34 (possible inputs are 1-9) and I reach 9 (Counter).

I want to change the '/' to 'B'
and use
but I get 'Expected a declaration' at {.

```<code>char Checker();
{
    if (matrix[0][0] && matrix[0][1] && matrix[0][2] && matrix[1][0] && matrix[1][1] && matrix[1][2] && matrix[2][0] && matrix[2][1] && matrix[2][2] == 'X' || 'O')
        return 'B';
}
</code>```

Can you help me fix this problem? If you want to see the full Code: https://pastebin.com/E5TzAG4t.
Sorry for my English its just a language I learned at School (Germany).

Edit: This is the Checking Code 1. to see if somebody wins 2. i there was made a Mistake during number insert

```<code>char Win()
{
    //Spieler X
    if (matrix[0][0] == 'X' && matrix[0][1] == 'X' && matrix[0][2] == 'X')
        return 'X';
    if (matrix[1][0] == 'X' && matrix[1][1] == 'X' && matrix[1][2] == 'X')
        return 'X';
    if (matrix[2][0] == 'X' && matrix[2][1] == 'X' && matrix[2][2] == 'X')
        return 'X';

    if (matrix[0][0] == 'X' && matrix[1][0] == 'X' && matrix[2][0] == 'X')
        return 'X';
    if (matrix[0][1] == 'X' && matrix[1][1] == 'X' && matrix[2][1] == 'X')
        return 'X';
    if (matrix[0][2] == 'X' && matrix[1][2] == 'X' && matrix[2][2] == 'X')
        return 'X';

    if (matrix[0][0] == 'X' && matrix[1][1] == 'X' && matrix[2][2] == 'X')
        return 'X';
    if (matrix[2][0] == 'X' && matrix[1][1] == 'X' && matrix[0][2] == 'X')
        return 'X';

    //Spieler O
    if (matrix[0][0] == 'O' && matrix[0][1] == 'O' && matrix[0][2] == 'O')
        return 'O';
    if (matrix[1][0] == 'O' && matrix[1][1] == 'O' && matrix[1][2] == 'O')
        return 'O';
    if (matrix[2][0] == 'O' && matrix[2][1] == 'O' && matrix[2][2] == 'O')
        return 'O';

    if (matrix[0][0] == 'O' && matrix[1][0] == 'O' && matrix[2][0] == 'O')
        return 'O';
    if (matrix[0][1] == 'O' && matrix[1][1] == 'O' && matrix[2][1] == 'O')
        return 'O';
    if (matrix[0][2] == 'O' && matrix[1][2] == 'O' && matrix[2][2] == 'O')
        return 'O';

    if (matrix[0][0] == 'O' && matrix[1][1] == 'O' && matrix[2][2] == 'O')
        return 'O';
    if (matrix[2][0] == 'O' && matrix[1][1] == 'O' && matrix[0][2] == 'O')
        return 'O';

        return '/';
}
char Checker()
{
    if (matrix[0][0] && matrix[0][1] && matrix[0][2] && matrix[1][0] && matrix[1][1] && matrix[1][2] && matrix[2][0] && matrix[2][1] && matrix[2][2] == 'X' || 'O' || '1' || '2' || '3' || '4' || '5' || '6' || '7' || '8' || '9')
        return 'B';
}
</code>```

答:
it seems like you want

```<code> if (matrix[0][0] && matrix[0][1] && matrix[0][2] && matrix[1][0] && matrix[1][1] && matrix[1][2] && matrix[2][0] && matrix[2][1] && matrix[2][2] == 'X' || 'O')
</code>```

to mean 'if m00 and m01 etc is X or O' sadly thats not what it means. YOu have to say it the long way

```<code>if((m00 == 'o' || m00 == 'x') && (m01 == 'o' || m01 == 'x') ...
</code>```

Body:
Hello yesterday I started Programming a little Tic Tac Toe game but today I found a mistake. The game ends in Draw if a return of '/'(just 'X' or 'O' if somebody wins) is shown and the counter shows 9 but it also ends if I make a mistake during game and input e.g. 34 (possible inputs are 1-9) and I reach 9 (Counter).

I want to change the '/' to 'B'
and use
but I get 'Expected a declaration' at {.

char Checker();
{
    if (matrix[0][0] && matrix[0][1] && matrix[0][2] && matrix[1][0] && matrix[1][1] && matrix[1][2] && matrix[2][0] && matrix[2][1] && matrix[2][2] == 'X' || 'O')
        return 'B';
}

Can you help me fix this problem? If you want to see the full Code: https://pastebin.com/E5TzAG4t.
Sorry for my English its just a language I learned at School (Germany).

Edit: This is the Checking Code 1. to see if somebody wins 2. i there was made a Mistake during number insert

char Win()
{
    //Spieler X
    if (matrix[0][0] == 'X' && matrix[0][1] == 'X' && matrix[0][2] == 'X')
        return 'X';
    if (matrix[1][0] == 'X' && matrix[1][1] == 'X' && matrix[1][2] == 'X')
        return 'X';
    if (matrix[2][0] == 'X' && matrix[2][1] == 'X' && matrix[2][2] == 'X')
        return 'X';

    if (matrix[0][0] == 'X' && matrix[1][0] == 'X' && matrix[2][0] == 'X')
        return 'X';
    if (matrix[0][1] == 'X' && matrix[1][1] == 'X' && matrix[2][1] == 'X')
        return 'X';
    if (matrix[0][2] == 'X' && matrix[1][2] == 'X' && matrix[2][2] == 'X')
        return 'X';

    if (matrix[0][0] == 'X' && matrix[1][1] == 'X' && matrix[2][2] == 'X')
        return 'X';
    if (matrix[2][0] == 'X' && matrix[1][1] == 'X' && matrix[0][2] == 'X')
        return 'X';

    //Spieler O
    if (matrix[0][0] == 'O' && matrix[0][1] == 'O' && matrix[0][2] == 'O')
        return 'O';
    if (matrix[1][0] == 'O' && matrix[1][1] == 'O' && matrix[1][2] == 'O')
        return 'O';
    if (matrix[2][0] == 'O' && matrix[2][1] == 'O' && matrix[2][2] == 'O')
        return 'O';

    if (matrix[0][0] == 'O' && matrix[1][0] == 'O' && matrix[2][0] == 'O')
        return 'O';
    if (matrix[0][1] == 'O' && matrix[1][1] == 'O' && matrix[2][1] == 'O')
        return 'O';
    if (matrix[0][2] == 'O' && matrix[1][2] == 'O' && matrix[2][2] == 'O')
        return 'O';

    if (matrix[0][0] == 'O' && matrix[1][1] == 'O' && matrix[2][2] == 'O')
        return 'O';
    if (matrix[2][0] == 'O' && matrix[1][1] == 'O' && matrix[0][2] == 'O')
        return 'O';

        return '/';
}
char Checker()
{
    if (matrix[0][0] && matrix[0][1] && matrix[0][2] && matrix[1][0] && matrix[1][1] && matrix[1][2] && matrix[2][0] && matrix[2][1] && matrix[2][2] == 'X' || 'O' || '1' || '2' || '3' || '4' || '5' || '6' || '7' || '8' || '9')
        return 'B';
}

Body:
it seems like you want

 if (matrix[0][0] && matrix[0][1] && matrix[0][2] && matrix[1][0] && matrix[1][1] && matrix[1][2] && matrix[2][0] && matrix[2][1] && matrix[2][2] == 'X' || 'O')

to mean 'if m00 and m01 etc is X or O' sadly thats not what it means. YOu have to say it the long way

if((m00 == 'o' || m00 == 'x') && (m01 == 'o' || m01 == 'x') ...


问:
Prevent page from showing after pressing back button
Is there any way to prevent my php page from showing content after i log out by pressing back button?</p>

答:
You need to empty the session on sign out first

```<code><?php
session_start();
session_destroy();
header("Location: index.php");
exit;
?>
</code>```

then on the top of each page check if the session is empty then redirect to login page:

```<code><?php
session_start();
if (!isset($_SESSION['user_id'])) {
header('Location: index.php');
}
</code>```

Body:
You need to empty the session on sign out first

<?php
session_start();
session_destroy();
header("Location: index.php");
exit;
?>

then on the top of each page check if the session is empty then redirect to login page:

<?php
session_start();
if (!isset($_SESSION['user_id'])) {
header('Location: index.php');
}


问:
Validators: Do they Stay disabled on postback when disabled ClientSide?
I have been learning alot about the standard asp.net Validators, and my latest discovery was about how to disable a validator client side, which was pretty cool.

now, if my initial post has the validator enabled, but client side, i disable it, does the server side recognize the client side change, and keep it, or does it get re-enabled the the page is sent back to the user?

Thanks!

Nate

答:
.NET Server side validator controls will be reset to whatever they have been set to last in the server side code during a postback.

So for example if you have set a required field validator to rqvControl.enabled = true in its .aspx tag, then after a postback it will be enabled no matter what its state was client side.

If you are setting the state of a validator on the client side, and you want to persist it, then you will need to set a value that you can read in your server code during a postback. This can be as simple as setting a hidden field value from your javascript that is doing the enable/disable operation. In your codebehind just handle the enabled state of your validator based off the value in your hidden field.


问:
How to get Excel 2010 to automatically change the row numbers in a function
I am computing a final report and I need to compute the value of a specific column in a spreadsheet of 150 rows

The function which i wrote is

```<code>=((SUM(I6:W6)/75)*.35*4)+(Y6*.1)+(Z6*.15)+(AA6*.3)+((AB6*4)/10 *.1)
</code>```

is working fine but then I am forced to copy it to each row of that specific column and update the row numbers to get the correct answer.

For example ,if I wanted to calculate the value for row number 16 for that column,I would have to manually enter this :

```<code>=((SUM(I16:W16)/75)*.35*4)+(Y16*.1)+(Z16*.15)+(AA16*.3)+((AB16*4)/10 *.1)
</code>```

This process is going to take a lot of time if I do it for all the records,any inputs on how to automatically get excel to update the row numbers ?

Thanks !!

答:
This is a standard feature of Excel.

You have just to copy "dragging".

I am looking for a video to post here.

Edit. Videos

http://www.metacafe.com/watch/1084306/excel_trick/

http://www.youtube.com/watch?v=VoQmaLh2L-A

HTH!

Body:
I am computing a final report and I need to compute the value of a specific column in a spreadsheet of 150 rows

The function which i wrote is

=((SUM(I6:W6)/75)*.35*4)+(Y6*.1)+(Z6*.15)+(AA6*.3)+((AB6*4)/10 *.1)

is working fine but then I am forced to copy it to each row of that specific column and update the row numbers to get the correct answer.

For example ,if I wanted to calculate the value for row number 16 for that column,I would have to manually enter this :

=((SUM(I16:W16)/75)*.35*4)+(Y16*.1)+(Z16*.15)+(AA16*.3)+((AB16*4)/10 *.1)

This process is going to take a lot of time if I do it for all the records,any inputs on how to automatically get excel to update the row numbers ?

Thanks !!


问:
Error installing TNTSearch and Laravel returning error on service provider
Trying to install and use the TNTSearch package on Laravel 5.4. In my composer.json I have added:

```<code>"teamtnt/tntsearch": "^1.0"
</code>```

I have then added:

```<code>TeamTNT\TNTSearch\TNTSearchServiceProvider::class,

'TNTSearch' => TeamTNT\TNTSearch\Facades\TNTSearch::class,
</code>```

To my config/app.php but when I try and create an index with php artisan make:console ProductIndexer i get the error:

[Symfony\Component\Debug\Exception\FatalThrowableError] Class
  'TeamTNT\TNTSearch\TNTSearchServiceProvider' not found

Any ideas? Note: I am not using Laravel Scout that has a driver package for TNT because I don't need to.

答:
The package you are installing isn't the Laravel Scout version, it's just the search package without the Laravel Provider.

If you wanna use the Laravel version you have to install github.com/teamtnt/laravel-scout-tntsearch-driver.

Body:
Trying to install and use the TNTSearch package on Laravel 5.4. In my composer.json I have added:

"teamtnt/tntsearch": "^1.0"

I have then added:

TeamTNT\TNTSearch\TNTSearchServiceProvider::class,

'TNTSearch' => TeamTNT\TNTSearch\Facades\TNTSearch::class,

To my config/app.php but when I try and create an index with php artisan make:console ProductIndexer i get the error:

[Symfony\Component\Debug\Exception\FatalThrowableError] Class
  'TeamTNT\TNTSearch\TNTSearchServiceProvider' not found

Any ideas? Note: I am not using Laravel Scout that has a driver package for TNT because I don't need to.


问:
Freezing Keras K.function() as tensorflow graph
I have a model trained in Keras, and I'm using its intermediate layer output by using K.function(). Is there a way to save this K.function() object as a tensorflow graph? I'd like to use this object in tensorflow serving but I don't see a way to freeze Keras K.function() objects

答:
I figured it out eventually, figured I should post it here in case anyone needs this in the future. I had to get the node names from the K.function() object.

```<code>encoder = K.function([...])  # define your Function object
encoder_tensor_names = [t.name for t in encoder.outputs]
encoder_node_names = [tn.replace(':0', '') for tn in encoder_tensor_names]  # node names are tensor names without :0
graph_def = tf.graph_util.convert_variables_to_constants(
    K.get_session(),
    K.get_session().graph.as_graph_def(),
    encoder_node_names
)
</code>```

Then follow the code in https://stackoverflow.com/a/44044405/5453184 to write out the binary (or text) file. The beauty of it is that tensorflow is smart enough to only retain the part of the graph that's required for the feedforward operation, and in my case it also freezes word embeddings so I no longer need separate word vector files.

Body:
I figured it out eventually, figured I should post it here in case anyone needs this in the future. I had to get the node names from the K.function() object.

encoder = K.function([...])  # define your Function object
encoder_tensor_names = [t.name for t in encoder.outputs]
encoder_node_names = [tn.replace(':0', '') for tn in encoder_tensor_names]  # node names are tensor names without :0
graph_def = tf.graph_util.convert_variables_to_constants(
    K.get_session(),
    K.get_session().graph.as_graph_def(),
    encoder_node_names
)

Then follow the code in https://stackoverflow.com/a/44044405/5453184 to write out the binary (or text) file. The beauty of it is that tensorflow is smart enough to only retain the part of the graph that's required for the feedforward operation, and in my case it also freezes word embeddings so I no longer need separate word vector files.


问:
Can't import dependency installed with Cocoapods
I've installed FBSDK with Cocoapods but can't import it in my AppDelegate.swift file for some reason. The FBSDK kit appears in my Xcode project so I feel like it should be working.

I'm not an iOS developer by any means, I'm just trying to write a simple native plugin for Flutter SDK. Anyone an idea?

--Here is what the pod file looks like--

```<code># Uncomment this line to define a global platform for your project
# platform :ios, '9.0'

if ENV['FLUTTER_FRAMEWORK_DIR'] == nil
  abort('Please set FLUTTER_FRAMEWORK_DIR to the directory containing Flutter.framework')
end

target 'Runner' do
  use_frameworks!

  # Pods for Runner
pod 'FBSDKCoreKit'
pod 'FBSDKLoginKit'
pod 'FBSDKShareKit'

  # Flutter Pods
  pod 'Flutter', :path => ENV['FLUTTER_FRAMEWORK_DIR']

  if File.exists? '../.flutter-plugins'
    flutter_root = File.expand_path('..')
    File.foreach('../.flutter-plugins') { |line|
      plugin = line.split(pattern='=')
      if plugin.length == 2
        name = plugin[0].strip()
        path = plugin[1].strip()
        resolved_path = File.expand_path("#{path}/ios", flutter_root)
        pod name, :path => resolved_path
      else
        puts "Invalid plugin specification: #{line}"
      end
    }
  end
end

post_install do |installer|
  installer.pods_project.targets.each do |target|
    target.build_configurations.each do |config|
      config.build_settings['ENABLE_BITCODE'] = 'NO'
    end
  end
end
</code>```

---EDIT---

I''m getting the following error atm: FBSDKCoreKit.framework: No such file or directory.When I open the Frameworks folder in xCode, all file names are in red:

But that exact folder in Finder is empty. So I guess that's why the error is showing. The question is how to fix this...

This is what my embedded binaries and linked frameworks and libraries look like in the project:

答:
As importing the FBSDKCoreKit.framework etc. will be performed in the [CP] Embed Pods Frameworks build phase when using CocoaPods, you should remove the references to these frameworks in the Embed Frameworks build phase.

CocoaPods will not create those references, I assume you have tried other ways of importing the Facebooks frameworks, and these link have been created in the process. You can also delete the references to the Facebook frameworks in the Frameworks Folder of you App-Project (the ones in your screenshot written in red, not the ones in the Pods-Project!), but keep the Pods_Runner.framework there.

From what I can tell, your Linked Frameworks and Libraries section looks valid.

If it still doesn't work, I'd advise you to create a new Xcode Project with an empty Podfile, and only include the Facebook frameworks via CocoaPods. Importing the Facebook-SDK in the AppDelegate should work then, otherwise I can share a sample project with you. Then you should check your build setting and build phases, maybe something is wrong there. If you still can't figure out the problem, you will probably need to re-create you xcode-project and import all your files again.

Without a sample Project that reproduces the error, that's the best advise I can give.

Good Luck! :)

Body:
I've installed FBSDK with Cocoapods but can't import it in my AppDelegate.swift file for some reason. The FBSDK kit appears in my Xcode project so I feel like it should be working.

I'm not an iOS developer by any means, I'm just trying to write a simple native plugin for Flutter SDK. Anyone an idea?

--Here is what the pod file looks like--

# Uncomment this line to define a global platform for your project
# platform :ios, '9.0'

if ENV['FLUTTER_FRAMEWORK_DIR'] == nil
  abort('Please set FLUTTER_FRAMEWORK_DIR to the directory containing Flutter.framework')
end

target 'Runner' do
  use_frameworks!

  # Pods for Runner
pod 'FBSDKCoreKit'
pod 'FBSDKLoginKit'
pod 'FBSDKShareKit'

  # Flutter Pods
  pod 'Flutter', :path => ENV['FLUTTER_FRAMEWORK_DIR']

  if File.exists? '../.flutter-plugins'
    flutter_root = File.expand_path('..')
    File.foreach('../.flutter-plugins') { |line|
      plugin = line.split(pattern='=')
      if plugin.length == 2
        name = plugin[0].strip()
        path = plugin[1].strip()
        resolved_path = File.expand_path("#{path}/ios", flutter_root)
        pod name, :path => resolved_path
      else
        puts "Invalid plugin specification: #{line}"
      end
    }
  end
end

post_install do |installer|
  installer.pods_project.targets.each do |target|
    target.build_configurations.each do |config|
      config.build_settings['ENABLE_BITCODE'] = 'NO'
    end
  end
end

---EDIT---

I''m getting the following error atm: FBSDKCoreKit.framework: No such file or directory.When I open the Frameworks folder in xCode, all file names are in red:

But that exact folder in Finder is empty. So I guess that's why the error is showing. The question is how to fix this...

This is what my embedded binaries and linked frameworks and libraries look like in the project:


问:
cannot install flutter_plugins_tools, dependency error
When I try to install plugin tools with

pub global activate flutter_plugin_tools

I get this error.

flutter git:(master) ✗ pub global activate flutter_plugin_tools
  Resolving dependencies... (1.0s)  Package http has no versions that
  match >=0.11.3+13 <0.12.0 derived from:
  - flutter_plugin_tools 0.0.1-dev depends on version ^0.11.3+13

答:
The issue is probably old Dart SDKs that are in your path. Check your path and remove them.

Originally answered on the GitHub issue by Devin Carew:

If you're running pub global activate directly, it's using the version
  of the dart sdk that's on your path, which may be different than the
  version shipped with flutter (you can run dart --version to see the
  version on your path). I suspect that you have an old version of dart,
  and pub is having trouble resolving a version of package:http that
  will work with it. You'll probably want to update your path to include
  path/to/flutter/bin/cache/dart-sdk/bin, or could try running flutter packages pub global activate flutter_plugin_tools.


问:
Dynamic Filename with Grunt Uglify
I am trying to set the version in the filename with Grunt Uglify, but it doesn't accept anything other than a string literal.

How can I replace "VERSION" dynamically by using a variable (e.g. ${VERSION}), or better yet, a command line argument?

```<code>grunt.initConfig({

  uglify: {
    min: {
       options: {}
      ,files: {
        "jquery.project-VERSION.min.js" : [ "jquery.project.js", "modules/*.js" ]
      }
    }
    ,dev: {
       options: {
        beautify: {
          width: 80
        }
      }
      ,files: {
        "jquery.project-VERSION.dev.js" : [ "jquery.project.js", "modules/*.js" ]
      }
    }
  }
});
</code>```

答:
As pointed out in a comment by @cartant, this can be done with a Grunt template, e.g. <%= version %>

So in my case it was

```<code>grunt.initConfig({

   version: 1.2.3

  ,uglify: {
    min: {
       options: {}
      ,files: {
        "jquery.project-<%= version %>.min.js" : [ "jquery.project.js", "modules/*.js" ]
      }
    }
    ,dev: {
       options: {
        beautify: {
          width: 80
        }
      }
      ,files: {
        "jquery.project-<%= version %>.dev.js" : [ "jquery.project.js", "modules/*.js" ]
      }
    }
  }
});
</code>```

Ref: Grunt > Configuring Tasks > Templates

Title: Dynamic Filename with Grunt Uglify

Body:
I am trying to set the version in the filename with Grunt Uglify, but it doesn't accept anything other than a string literal.

How can I replace "VERSION" dynamically by using a variable (e.g. ${VERSION}), or better yet, a command line argument?

grunt.initConfig({

  uglify: {
    min: {
       options: {}
      ,files: {
        "jquery.project-VERSION.min.js" : [ "jquery.project.js", "modules/*.js" ]
      }
    }
    ,dev: {
       options: {
        beautify: {
          width: 80
        }
      }
      ,files: {
        "jquery.project-VERSION.dev.js" : [ "jquery.project.js", "modules/*.js" ]
      }
    }
  }
});

Body:
As pointed out in a comment by @cartant, this can be done with a Grunt template, e.g. <%= version %>

So in my case it was

grunt.initConfig({

   version: 1.2.3

  ,uglify: {
    min: {
       options: {}
      ,files: {
        "jquery.project-<%= version %>.min.js" : [ "jquery.project.js", "modules/*.js" ]
      }
    }
    ,dev: {
       options: {
        beautify: {
          width: 80
        }
      }
      ,files: {
        "jquery.project-<%= version %>.dev.js" : [ "jquery.project.js", "modules/*.js" ]
      }
    }
  }
});

Ref: Grunt > Configuring Tasks > Templates


问:
drawing rectangle
I am writing a program that accepts coordinates from the user and drawing some shapes on the screen with stars(*)

e.g Rectangle i.e rectangle=100,150,50,50 as x,y,width,height. how can I do it??

答:
What 'drawing with stars' is? If this is text mode with  monospaced font, you'll need to print it in horizontal lines  of stars, calculating right lengths. For rectangles this is easy, for triangles, a bit less easy, pentagon is just a combination of a rectangle and some triangles. See Bresenham algorithm for inspiration.

Also note that text mode resolution is quite poor; standard terminal window in only 80 chars wide, and you can hardly have it far wider than say 200-300 chars, so correct rounding is important.

OwnerDisplayName: marry

Title: drawing rectangle