问:
How can I write a promise in AngularJS
I am trying to write a service, which does multiple async requests, I am using $q to return a promise, problem is I am writing some repetitive code, I want to remove the repetition.

```<code>app.factory('MyService',function($q){
     var ser = {
            getA:function(){
                var d=  $q.defer; //repetitive code
                asyn1().then(function(){
                    aync2().then(function(res){
                        //Process data
                        doSomething(res)
                        d.resolve();
                    })
                });
                return d.promise
            } ,
            getB:function(){
                var d=  $q.defer;
                asyn3().then(function(){
                    aync4().then(function(res){
                        //Process data
                        doSomething(res)
                        d.resolve();
                    })
                });
                return d.promise
            }
     }

     return ser;
});
</code>```

In each function, I am repeating the $q thing, how can I avoid the repetition.

答:
Demo on my jsFiddle page:
https://jsfiddle.net/MikaViko/kprbneha/       </p>

```<code>``var module = angular.module('app', []);
    module.controller('appController', ['$scope', '$q', function($scope, $q) {

      var fibonacci = [1, 1, 2, 3, 5, 8, 13, 20];

      $scope.getItem = function(index) {
        var promise = getItemPromise(index);
        promise.then(
          function(item) {
            $scope.item = item;
            $scope.error = "";
          },
          function(error) {
            $scope.error = error;
            $scope.item = null;
          }
        );
      };

      function getItemPromise(index) {
        var item = fibonacci[index];
        var deferred = $q.defer();

        if (item)
          deferred.resolve(item);
        else
          deferred.reject("L'item n'existe pas ou l'index n'est pas valide.");

        return deferred.promise;
      }

    }]);
</code>```

Title: How can I write a promise in AngularJS

Body:
I am trying to write a service, which does multiple async requests, I am using $q to return a promise, problem is I am writing some repetitive code, I want to remove the repetition.

app.factory('MyService',function($q){
     var ser = {
            getA:function(){
                var d=  $q.defer; //repetitive code
                asyn1().then(function(){
                    aync2().then(function(res){
                        //Process data
                        doSomething(res)
                        d.resolve();
                    })
                });
                return d.promise
            } ,
            getB:function(){
                var d=  $q.defer;
                asyn3().then(function(){
                    aync4().then(function(res){
                        //Process data
                        doSomething(res)
                        d.resolve();
                    })
                });
                return d.promise
            }
     }

     return ser;
});

In each function, I am repeating the $q thing, how can I avoid the repetition.

Body:
Demo on my jsFiddle page:
https://jsfiddle.net/MikaViko/kprbneha/

``var module = angular.module('app', []);
    module.controller('appController', ['$scope', '$q', function($scope, $q) {

      var fibonacci = [1, 1, 2, 3, 5, 8, 13, 20];

      $scope.getItem = function(index) {
        var promise = getItemPromise(index);
        promise.then(
          function(item) {
            $scope.item = item;
            $scope.error = "";
          },
          function(error) {
            $scope.error = error;
            $scope.item = null;
          }
        );
      };

      function getItemPromise(index) {
        var item = fibonacci[index];
        var deferred = $q.defer();

        if (item)
          deferred.resolve(item);
        else
          deferred.reject("L'item n'existe pas ou l'index n'est pas valide.");

        return deferred.promise;
      }

    }]);


来源: stackexchange

问:
C# Fastest search object which has nearest value given
I try to find an object in list which has nearest value that given
I wrote this :

```<code>float target = 100.0f;
int index = int.MaxValue;
float nearest = float.MaxValue;
for(int i = 0; i < objectList.Count; i++)
{
   if(Math.Abs(objectList[i].value - target) < nearest)
   {
       nearest = Math.Abs(objectList[i].value - target);
       index = i;
   }
}

//do something with objectList[index]
</code>```

This actually works, but when the list is too large, It consumes quite much time to search.

I know there are probably way to do it, but I don't know what is it.

答:
Unless your list is sorted there's really no other way than examining each object. You could save the distance in a variable so you're not computing it twice.</p>

```<code>float target = 100.0f;
int index = int.MaxValue;
float nearest = float.MaxValue;
for(int i = 0; i < objectList.Count; i++)
{
   float dist = Math.Abs(objectList[i].value - target);
   if(dist < nearest)
   {
       nearest = dist;
       index = i;
   }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I try to find an object in list which has nearest value that given
I wrote this :

float target = 100.0f;
int index = int.MaxValue;
float nearest = float.MaxValue;
for(int i = 0; i < objectList.Count; i++)
{
   if(Math.Abs(objectList[i].value - target) < nearest)
   {
       nearest = Math.Abs(objectList[i].value - target);
       index = i;
   }
}

//do something with objectList[index]

This actually works, but when the list is too large, It consumes quite much time to search.

I know there are probably way to do it, but I don't know what is it.

Body:
Unless your list is sorted there's really no other way than examining each object. You could save the distance in a variable so you're not computing it twice.

float target = 100.0f;
int index = int.MaxValue;
float nearest = float.MaxValue;
for(int i = 0; i < objectList.Count; i++)
{
   float dist = Math.Abs(objectList[i].value - target);
   if(dist < nearest)
   {
       nearest = dist;
       index = i;
   }
}


问:
To retrieve list of object from stored procedure SQL server through spring-jpa
I wrote a stored procedure ,

ALTER PROCEDURE [dbo].[getCustomerSearch]
    -- Add the parameters for the stored procedure here
    @clientNo varchar(50)

AS
BEGIN
    -- Insert statements for procedure here
    SELECT cs.* FROM [mm].[dbo].[CM_customerStatus] as cs  WHERE cs.[ClientNo] like @clientNo;
END

I want to access that list of table records from spring JPA repository as List of object.Is there any way to do this task???

答:
You can extend your JPA repository and use EntityManager to run a stored procedure in spring data jpa. Use createNamedStoredProcedureQuery to fire your stored procedure.

```<code>Query query = entityManager.createNamedStoredProcedureQuery("YOUR_PROCEDURE");
query.setParameter("arg", ARG);
query.getResultList();
</code>```

Also check this question for more details.

Body:
You can extend your JPA repository and use EntityManager to run a stored procedure in spring data jpa. Use createNamedStoredProcedureQuery to fire your stored procedure.

Query query = entityManager.createNamedStoredProcedureQuery("YOUR_PROCEDURE");
query.setParameter("arg", ARG);
query.getResultList();

Also check this question for more details.


问:
Creating class with variables vs passing variables as parameters into a method

Which is a better way to do this, in terms of performance or other factors?

Say I am creating a class with jut one method in it that takes 2 values and adds them together.

Is it better to have 2 instance variables to store the 2 values then have a method which uses these, or is it better to just pass the variables in as parameters when calling the method?

Note: this class is only ever created just to use this method.

public class MyClass {
    int value1;
    int value2;

public MyClass(int value1, int value2){
    this.value1 = value1;
    this.value2 = value2;
}

public int MyMethod(){
    return value1 + value2;
}
```

<p>or this way:</p>

<pre class="lang-java prettyprint-override"><code>public class MyClass {

public MyClass(){

}

public int MyMethod(int value1, int value2){
    return value1 + value2;
}
</code>```

Or would it be better to just use a static method, so I don't need to create an object every time I use the method?

答:
It depends very match on your intention.

If you name you value1 and value2 as engineWeight and wheelsWeight then you can name your method:

public int calculateWeightSum(){
    return value1 + value2;
}

In such case it will have sense to have such kind of approach.

The second approach(with method params) may be used as usual business logic of the object. You give variable to operate and it returns result. The result may depend on which object you make an invocation. That's the reason you don't mark this method as static. If you mark it as static, the object state won't affect the result.

Java doesn't have "global" variables. It has static public variables that can be treated very similarly. You can use them with both approaches, but the intention of using it here is very unclear. Probably in this case is better to make utility with static methods to do the job.

As for performance, it's pretty much the same in all the cases. But, in the approach with constructor you use additional memory to store field for each object. But, again. It depends very much on your intention, here it's difficult to judge until you provide more information about real task.
For now I just described my ideas on how it's convenient to use different approaches.

Body:
Which is a better way to do this, in terms of performance or other factors?

Say I am creating a class with jut one method in it that takes 2 values and adds them together.

Is it better to have 2 instance variables to store the 2 values then have a method which uses these, or is it better to just pass the variables in as parameters when calling the method?

Note: this class is only ever created just to use this method.

public class MyClass {
    int value1;
    int value2;

public MyClass(int value1, int value2){
    this.value1 = value1;
    this.value2 = value2;
}

public int MyMethod(){
    return value1 + value2;
}

or this way:

public class MyClass {

public MyClass(){

}

public int MyMethod(int value1, int value2){
    return value1 + value2;
}

Or would it be better to just use a static method, so I don't need to create an object every time I use the method?


问:
SDCH compression - gone with a wind?
I was long aware of this compression, but was curious why anyone else than Google implement it. Then I found following link: https://engineering.linkedin.com/shared-dictionary-compression-http-linkedin

Wow, LinkedIn implemented it too, looks like it worth the effort for big volume net traffics. So I went with Fiddler to investigate headers which are well defined for this compression, I mean dictionary negotiation, etc. Side note, latest Chrome, latest Fiddler and Chrome reports "Accept-Encoding" sdch as well as the rest - gzip, deflate

Guess what? I dont see it working, nor for Google (search queries) neither for LinkedIn. Nada! no dictionary negotiation, no download of dictionary, no server reporting it has a dictionary for the browser to download. So what happend? Is it dead? abandoned by Google and LinkedIn? It proved to be inefficient?

答: Short answer - it is dead for now</p>

Title: SDCH compression - gone with a wind?

Body: Short answer - it is dead for now


问:
ARM Template with DSC extension: Powershell file location from local destop
I would like to send the ARM template Project with related PS scripts for DSC to a third party. They would probably deploy option in VS to do the deployment. It is possible to attach the DSC script as part of the ARM project and on deploy picks up the dsc script from local disk? Under settings we have "ModulesUrl" it is possible to replace this with another parameter which points to local disk something like c:\myproject\IISInstall.ps1.zip</p>

```<code>{
  "apiVersion": "2015-06-15",
  "dependsOn": [
    "[concat('Microsoft.Compute/virtualMachines/', parameters('webSrvVmName'))]"
  ],
  "location": "[resourceGroup().location]",
  "name": "qawebsrv/iisinstall",
  "properties": {
    "publisher": "Microsoft.Powershell",
    "type": "DSC",
    "typeHandlerVersion": "2.19",
    "autoUpgradeMinorVersion": true,
    "settings": {
      "ModulesUrl": "https://dscscript.blob.core.windows.net/dscscripts/IISInstall.ps1.zip",
      "ConfigurationFunction": "[variables('configurationFunction')]",
      "Properties": {},
      "SasToken": "",
      "wmfVersion": "4.0"
    },
    "protectedSettings": {}
  },
  "tags": {
    "displayName": "VM Extensions"
  },
  "type": "Microsoft.Compute/virtualMachines/extensions"
}
</code>```

答:
No, this is not possible. Closest you can get to this is upload your script to a publicly available place and the VM will pull it.</p>

```<code>"properties": {
    "publisher": "Microsoft.Powershell",
    "type": "DSC",
    "typeHandlerVersion": "2.20",
    "autoUpgradeMinorVersion": true,
    "settings": {
        "configuration": {
            "url": "https://github.com/xxx.zip",
            "script": "scriptname.ps1",
            "function": "main"
        },
        "configurationArguments": {}
    },
    "protectedSettings": {}
}
</code>```

Body:
I would like to send the ARM template Project with related PS scripts for DSC to a third party. They would probably deploy option in VS to do the deployment. It is possible to attach the DSC script as part of the ARM project and on deploy picks up the dsc script from local disk? Under settings we have "ModulesUrl" it is possible to replace this with another parameter which points to local disk something like c:\myproject\IISInstall.ps1.zip

{
  "apiVersion": "2015-06-15",
  "dependsOn": [
    "[concat('Microsoft.Compute/virtualMachines/', parameters('webSrvVmName'))]"
  ],
  "location": "[resourceGroup().location]",
  "name": "qawebsrv/iisinstall",
  "properties": {
    "publisher": "Microsoft.Powershell",
    "type": "DSC",
    "typeHandlerVersion": "2.19",
    "autoUpgradeMinorVersion": true,
    "settings": {
      "ModulesUrl": "https://dscscript.blob.core.windows.net/dscscripts/IISInstall.ps1.zip",
      "ConfigurationFunction": "[variables('configurationFunction')]",
      "Properties": {},
      "SasToken": "",
      "wmfVersion": "4.0"
    },
    "protectedSettings": {}
  },
  "tags": {
    "displayName": "VM Extensions"
  },
  "type": "Microsoft.Compute/virtualMachines/extensions"
}

Body:
No, this is not possible. Closest you can get to this is upload your script to a publicly available place and the VM will pull it.

"properties": {
    "publisher": "Microsoft.Powershell",
    "type": "DSC",
    "typeHandlerVersion": "2.20",
    "autoUpgradeMinorVersion": true,
    "settings": {
        "configuration": {
            "url": "https://github.com/xxx.zip",
            "script": "scriptname.ps1",
            "function": "main"
        },
        "configurationArguments": {}
    },
    "protectedSettings": {}
}


问:
Receive array inputs from a single line in c#
Inputs are in the format: {10, 20, 30, 40, 50}
How should i split it into multiple elements using c#</p>

答:
First remove the brackets and spaces,

```<code>input = input.Replace("{", "");
input = input.Replace("}", "");
input = input.Replace(" ", "");
</code>```

Leaving you with this:

```<code>10,20,30,40,50
</code>```

Now you can split the string at the commas using this function:
https://msdn.microsoft.com/en-us/library/b873y76a(v=vs.110).aspx

Which would look like this:

```<code>IList<string> result = input.Split(',').ToList<string>();
</code>```

Body:
First remove the brackets and spaces,

input = input.Replace("{", "");
input = input.Replace("}", "");
input = input.Replace(" ", "");

Leaving you with this:

10,20,30,40,50

Now you can split the string at the commas using this function:
https://msdn.microsoft.com/en-us/library/b873y76a(v=vs.110).aspx

Which would look like this:

IList<string> result = input.Split(',').ToList<string>();


问:
The most optimized way of calculating distance between data in c++
I have n points in a 2D plane. I want to calculate the distance between each two points in c++. Position of m'th point in  the plan is (x(m),y(m)). This points changes during passing time. The number of time steps is equal to 10^5.
I wrote below code, but as n is a big number(5000) and I want to find the distance between points 10^5 times, I'm searching for the most optimized way to do that. Could anyone tell me what is the least time-consuming way to do that?

```<code>for(i=1;n;++)
   for(j=1;n;++)
      if (i>j)
         r(i,j)= r(j,i);
      else
         r(i,j)=sqrt((x(i)-x(j))^2+(y(i)-y(j))^2);
      end
   end
end
</code>```

I know that, in Matlab, I can find this by using bsxfun function. I want also to know which one could calculate distances faster? Matlab or c++?

答:
Regarding Matlab, you have also pdist which does exactly that (but is not so fast), and you should also read this.

About comparing Matlab and C first read this and this. Also keep in mind that Matlab, as a desktop program, requires knowing not only a general efficient way to implement your code but also the right way to do this in Matlab. One example is the difference between functions. Built-in functions are written in FORTRAN or C and run much faster then non-built-in functions. To know if a function is built-in, type:

```<code>which function_name
</code>```

and check if you see "built-in" at the start of the output:

```<code>built-in (C:\Program Files\MATLAB\...)
</code>```

Body:
I have n points in a 2D plane. I want to calculate the distance between each two points in c++. Position of m'th point in  the plan is (x(m),y(m)). This points changes during passing time. The number of time steps is equal to 10^5.
I wrote below code, but as n is a big number(5000) and I want to find the distance between points 10^5 times, I'm searching for the most optimized way to do that. Could anyone tell me what is the least time-consuming way to do that?

for(i=1;n;++)
   for(j=1;n;++)
      if (i>j)
         r(i,j)= r(j,i);
      else
         r(i,j)=sqrt((x(i)-x(j))^2+(y(i)-y(j))^2);
      end
   end
end

I know that, in Matlab, I can find this by using bsxfun function. I want also to know which one could calculate distances faster? Matlab or c++?

Body:
Regarding Matlab, you have also pdist which does exactly that (but is not so fast), and you should also read this.

About comparing Matlab and C first read this and this. Also keep in mind that Matlab, as a desktop program, requires knowing not only a general efficient way to implement your code but also the right way to do this in Matlab. One example is the difference between functions. Built-in functions are written in FORTRAN or C and run much faster then non-built-in functions. To know if a function is built-in, type:

which function_name

and check if you see "built-in" at the start of the output:

built-in (C:\Program Files\MATLAB\...)


问:
Quickly checking if arrays intersect
I want to check if two arrays a and b intersect. Given a = [3, 21] and b = [15, 26530, 21, 3], the answer should be true. Given
If a = [3, 21] and b = [15, 26530], the answer should be false.

I tried:

```<code>a.to_set.intersect?(b.to_set)
</code>```

but this method takes a long time. How can I do it quickly?

答:
Try this one.

```<code>(a & b).any?
</code>```

Anyway, I think the set operation should be the fastest one. Problem is you have to convert your arrays and maybe they are big.

Title: Quickly checking if arrays intersect

Body:
I want to check if two arrays a and b intersect. Given a = [3, 21] and b = [15, 26530, 21, 3], the answer should be true. Given
If a = [3, 21] and b = [15, 26530], the answer should be false.

I tried:

a.to_set.intersect?(b.to_set)

but this method takes a long time. How can I do it quickly?

Body:
Try this one.

(a & b).any?

Anyway, I think the set operation should be the fastest one. Problem is you have to convert your arrays and maybe they are big.


问:
How to align specific layout to bottom and fix size of imageview to cover remaining space?
I have a imageview & relative layout, where the layout containing two buttons should align to bottom and circular image should stretch to take remaining space. I tried from other answers but could not do it. I have code and image below.

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/cardview_light_background"
android:clickable="true">
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <include layout="@layout/toolbar_child_with_progress"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/toolbar_child"/>
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/toolbar_child">
        <RelativeLayout
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            >
                <ImageView
                    android:id="@+id/iv_SavedInvoice"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:src="@drawable/service_app_logo"
                    android:scaleType="fitStart"
                    android:adjustViewBounds="true"
                    android:layout_centerHorizontal="true"
                    />

                <LinearLayout
                    android:id="@+id/ll_inner"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical"
                    android:layout_below="@+id/iv_SavedInvoice"
                    android:layout_alignParentBottom="true"
                    >
                    <Button
                        style="@style/PrimaryButton"
                        android:layout_marginTop="20dp"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="@string/form_proof_replace_invoice"
                        android:id="@+id/button_ReplaceInvoice" />
                    <Button
                        style="@style/NoBorderButton"
                        android:layout_marginTop="20dp"
                        android:layout_marginBottom="20dp"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="@string/form_proof_next"
                        android:id="@+id/button_SavedProofNext" />
                </LinearLayout>
            </RelativeLayout>
    </ScrollView>
</RelativeLayout>
</code>```

答:
You should set layout_height   match_parent instead of  wrap_content.

```<code><LinearLayout
                    android:id="@+id/ll_inner"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical"
                    android:layout_below="@+id/iv_SavedInvoice"
                    android:layout_alignParentBottom="true"
                    >
</code>```

Secondly, Add android:fillViewport="true" in your ScrollView Section .

Body:
I have a imageview & relative layout, where the layout containing two buttons should align to bottom and circular image should stretch to take remaining space. I tried from other answers but could not do it. I have code and image below.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/cardview_light_background"
android:clickable="true">
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <include layout="@layout/toolbar_child_with_progress"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/toolbar_child"/>
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/toolbar_child">
        <RelativeLayout
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            >
                <ImageView
                    android:id="@+id/iv_SavedInvoice"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:src="@drawable/service_app_logo"
                    android:scaleType="fitStart"
                    android:adjustViewBounds="true"
                    android:layout_centerHorizontal="true"
                    />

                <LinearLayout
                    android:id="@+id/ll_inner"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical"
                    android:layout_below="@+id/iv_SavedInvoice"
                    android:layout_alignParentBottom="true"
                    >
                    <Button
                        style="@style/PrimaryButton"
                        android:layout_marginTop="20dp"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="@string/form_proof_replace_invoice"
                        android:id="@+id/button_ReplaceInvoice" />
                    <Button
                        style="@style/NoBorderButton"
                        android:layout_marginTop="20dp"
                        android:layout_marginBottom="20dp"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="@string/form_proof_next"
                        android:id="@+id/button_SavedProofNext" />
                </LinearLayout>
            </RelativeLayout>
    </ScrollView>
</RelativeLayout>

Body:
You should set layout_height   match_parent instead of  wrap_content.

<LinearLayout
                    android:id="@+id/ll_inner"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical"
                    android:layout_below="@+id/iv_SavedInvoice"
                    android:layout_alignParentBottom="true"
                    >

Secondly, Add android:fillViewport="true" in your ScrollView Section .


问:
how to access TextBox inside ListBox itemsSource which is Datatemplate?
I have a ListBox and its ItemsSource is linked with a ComboBox SelectedItem. Its template is associated with a DataTemplate. Everything is fine but how to access each TextBox inside ListBoxItems. I have 5 labels and 2 TextBoxes inside each ListItem. I want to access each and every TextBox and labels inside ListBoxItem. I need some idea how to access each TextBox inside each Item. For example, there is "wbprofileDesc" TextBox in first ListBoxItem. So I need to access this TextBox and write some functionality to it like keypress event. It need to work for each and every TextBox inside all the ListBoxItems individually. Assume there are 5 ListBoxItems. Also I need to fetch other controls also like wbselect(ComboBox), wbdepth, wbwidthvalue and etc. I am using MVVM model for this.

```<code><Window.Resources>
  <local:wbItemViewModel x:Key="wbItem"/>

  <DataTemplate x:Key="wbObjectsDataTemplate">
    <Grid Grid.ColumnSpan="1" Grid.RowSpan="1" Height="Auto" Width="642" Margin="0,0,0,-14">
      <Grid HorizontalAlignment="Left" VerticalAlignment="Top" Width="697"  Margin="10,0,0,0" Height="54" >
        <Grid.ColumnDefinitions>
          <ColumnDefinition Width="49*"/>
          <ColumnDefinition Width="91*"/>
          <ColumnDefinition Width="309*"/>
          <ColumnDefinition Width="306*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
          <RowDefinition Height="auto" />
          <RowDefinition/>
          <RowDefinition Height="auto" MinHeight="5"/>
        </Grid.RowDefinitions>

        <Label Content="{Binding WBName_lbl}" Margin="0,3,0,5" Grid.Row="0" Grid.Column="0" Grid.RowSpan="2"/>

        <ComboBox x:Name="wbselect" Margin="5,0,10,1" Grid.Column="1" Grid.ColumnSpan="1" Grid.Row="0">
          <ComboBoxItem x:Name="wbstraight" IsSelected="True" Content="straight"/>
          <ComboBoxItem x:Name="wbtapered" Content="tapered"/>
        </ComboBox>

        <!--KeyDown="{Binding Path=profileDesc}"-->
        <!-- KeyDown="profileDesc_KeyDown" -->
        <TextBox x:Name="wbprofileDesc" Margin="18,0,20,1" Grid.Column="2" Grid.Row="0" GotFocus="wbprofileDesc_GotFocus"/>
        <TextBox x:Name="wbdepth" Text="{Binding ElementName=wbwidthvalue, Path=Content, Mode=OneWay}" Margin="10,0,73,1" Grid.Column="3" Grid.Row="0"/>
        <Label x:Name="wbwidthvalue" Margin="10,0,190,5" Grid.Column="2" FontSize="8" Grid.Row="1"/>
        <Label x:Name="wbthicknessvalue" Margin="118,0,82,5" FontSize="8" Grid.Row="1" Grid.Column="2"/>
        <Label x:Name="wblengthvalue" Margin="208,0,0,5" FontSize="8" Grid.Row="1" Grid.Column="2"/>
        <Label x:Name="wbnexwidthvalue" Margin="10,0,178,5" FontSize="8" Grid.Row="1" Grid.Column="3"/>
        <Label x:Name="wbdepthvalue" Grid.Row="1" Grid.Column="3" FontSize="8" Margin="132,0,31,5"/>
        <!--<Label x:Name="totalvalue" Margin="30,10,24,16" Grid.Row="3" Grid.Column="3"/>-->
      </Grid>
    </Grid>
  </DataTemplate>
</Window.Resources>

<ListBox x:Name="wbListDataTemplate"
         ItemsSource="{Binding wbVisibleItems}"
         ItemTemplate="{DynamicResource wbObjectsDataTemplate}"
         DataContext="{DynamicResource wbItem}"
         Background="{x:Null}"
         SelectedItem="{Binding wbSelectedItem, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
         IsSynchronizedWithCurrentItem="True"
         Canvas.Top="51" Height="222" Width="686"/>
</code>```

答:
Here is an example of you could find the controls in the DataTemplate inside the event handler:

```<code>private void wbprofileDesc_GotFocus(object sender, RoutedEventArgs e)
{
    TextBox wbprofileDesc = sender as TextBox;
    Grid parentGrid = wbprofileDesc.Parent as Grid;

    ComboBox wbselect = parentGrid.Children.OfType<ComboBox>().FirstOrDefault(x => x.Name == "wbselect");
    Label wbwidthvalue = parentGrid.Children.OfType<Label>().FirstOrDefault(x => x.Name == "wbwidthvalue");
}
</code>```

Body:
I have a ListBox and its ItemsSource is linked with a ComboBox SelectedItem. Its template is associated with a DataTemplate. Everything is fine but how to access each TextBox inside ListBoxItems. I have 5 labels and 2 TextBoxes inside each ListItem. I want to access each and every TextBox and labels inside ListBoxItem. I need some idea how to access each TextBox inside each Item. For example, there is "wbprofileDesc" TextBox in first ListBoxItem. So I need to access this TextBox and write some functionality to it like keypress event. It need to work for each and every TextBox inside all the ListBoxItems individually. Assume there are 5 ListBoxItems. Also I need to fetch other controls also like wbselect(ComboBox), wbdepth, wbwidthvalue and etc. I am using MVVM model for this.

<Window.Resources>
  <local:wbItemViewModel x:Key="wbItem"/>

  <DataTemplate x:Key="wbObjectsDataTemplate">
    <Grid Grid.ColumnSpan="1" Grid.RowSpan="1" Height="Auto" Width="642" Margin="0,0,0,-14">
      <Grid HorizontalAlignment="Left" VerticalAlignment="Top" Width="697"  Margin="10,0,0,0" Height="54" >
        <Grid.ColumnDefinitions>
          <ColumnDefinition Width="49*"/>
          <ColumnDefinition Width="91*"/>
          <ColumnDefinition Width="309*"/>
          <ColumnDefinition Width="306*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
          <RowDefinition Height="auto" />
          <RowDefinition/>
          <RowDefinition Height="auto" MinHeight="5"/>
        </Grid.RowDefinitions>

        <ComboBox x:Name="wbselect" Margin="5,0,10,1" Grid.Column="1" Grid.ColumnSpan="1" Grid.Row="0">
          <ComboBoxItem x:Name="wbstraight" IsSelected="True" Content="straight"/>
          <ComboBoxItem x:Name="wbtapered" Content="tapered"/>
        </ComboBox>

        <TextBox x:Name="wbprofileDesc" Margin="18,0,20,1" Grid.Column="2" Grid.Row="0" GotFocus="wbprofileDesc_GotFocus"/>
        <TextBox x:Name="wbdepth" Text="{Binding ElementName=wbwidthvalue, Path=Content, Mode=OneWay}" Margin="10,0,73,1" Grid.Column="3" Grid.Row="0"/>

      </Grid>
    </Grid>
  </DataTemplate>
</Window.Resources>

<ListBox x:Name="wbListDataTemplate"
         ItemsSource="{Binding wbVisibleItems}"
         ItemTemplate="{DynamicResource wbObjectsDataTemplate}"
         DataContext="{DynamicResource wbItem}"
         Background="{x:Null}"
         SelectedItem="{Binding wbSelectedItem, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
         IsSynchronizedWithCurrentItem="True"
         Canvas.Top="51" Height="222" Width="686"/>

Body:
Here is an example of you could find the controls in the DataTemplate inside the event handler:

private void wbprofileDesc_GotFocus(object sender, RoutedEventArgs e)
{
    TextBox wbprofileDesc = sender as TextBox;
    Grid parentGrid = wbprofileDesc.Parent as Grid;

    ComboBox wbselect = parentGrid.Children.OfType<ComboBox>().FirstOrDefault(x => x.Name == "wbselect");
    Label wbwidthvalue = parentGrid.Children.OfType<Label>().FirstOrDefault(x => x.Name == "wbwidthvalue");
}


问:
converting date format
I got date as '14-Dec-2010' i want to get the month in number format for the given date.
that is., i want to convert the date to '14-12-2010'.

答:
```<code>import java.text.SimpleDateFormat;
import java.util.Date;

public class DateFormatter {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Date date = new Date("14-Dec-2010"); //deprecated. change it to your needs
        DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
        System.out.println(df.format(date));

    }

}
</code>```

ContentLicense: CC BY-SA 2.5

Title: converting date format


问:
Maximizing sum subject to different indicies
Suppose I have a matrix, A, of size n x p with n > p, each element of 0 <= A <= 1. I would like to find p elements in A, one in each column, such that the overall sum is maximized and each element is in a different row. Thus, there are n permute p different combinations to consider. Is there a name for this problem? I found ones such as the knapsack problem, but the setup is different. Additionally, are they are any efficient algorithms to compute this for say n=300, p=10? There are a few special cases to check, such as if the max in each column so happens to be on a different row. Otherwise, am I left to dynamic programming? Thanks!

答:
This is maximum matching in a weighted bipartite graph, also known as the assignment problem. Columns and rows are graph parts (resp. agents and tasks) and cells are edges (resp. task assignments).

This is effectively solved by the Hungarian algorithm which is polynomial.


问:
ngIf in angular 2 not working
```<code><div *ngFor="let message of messages">
  <div *ngIf="message.user===user">

  </div>

 <input [(ngModel)]="message"  />
<button (click)="sendMessage()">Send</button>
</code>```

Here user is the variable that I have assigned in the component. That is a string value 'user1'. If message.user === user1 then I need to show something but its not working.

答:
you need basic code like this...at least.

```<code><div *ngFor="let message of messages">
  <div *ngIf="message.user === user">
      user: {{ message.user }}
  </div>
</div>
<input [(ngModel)]="message"  />
<button (click)="sendMessage()">Send</button>
</code>```

Your component should have 'messages' prop as well.

Title: ngIf in angular 2 not working

Body:
 <input [(ngModel)]="message"  />
<button (click)="sendMessage()">Send</button>

Here user is the variable that I have assigned in the component. That is a string value 'user1'. If message.user === user1 then I need to show something but its not working.

Body:
you need basic code like this...at least.

<div *ngFor="let message of messages">
  <div *ngIf="message.user === user">
      user: {{ message.user }}
  </div>
</div>
<input [(ngModel)]="message"  />
<button (click)="sendMessage()">Send</button>

Your component should have 'messages' prop as well.


问:
how to set path for File Input Stream
i was trying to use a txt file but i got this eror "FileNotFoundException"
but it was readable and it exist but on line FileInputStream i got that error
whats the matter?</p>

```<code>        System.out.println(Files.isReadable(Paths.get("I:/Code/Coding/src/Files/" + path + ".txt")));
        System.out.println(Files.exists(Paths.get("I:/Code/Coding/src/Files/" + path + ".txt")));
        FileInputStream f1=new FileInputStream("I:/Code/Coding/src/Files/" + path + ".txt");
        reader = new ObjectInputStream(f1);

java.io.FileNotFoundException: I:\Code\Coding\src\Files\Artists.txt (The system cannot find the path specified)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(FileInputStream.java:195)
    at java.io.FileInputStream.<init>(FileInputStream.java:138)
    at java.io.FileInputStream.<init>(FileInputStream.java:93)
    at sample.Datebase.Server.readFiles(Server.java:70)
    at sample.Datebase.Server.run(Server.java:99)
    at sample.Datebase.Server.main(Server.java:54)
Exception in thread "main" java.lang.NullPointerException
    at sample.Datebase.Server.readFiles(Server.java:94)
    at sample.Datebase.Server.run(Server.java:99)
    at sample.Datebase.Server.main(Server.java:54)
</code>```

答:
FileNotFoundException - if the file exist but cannot be opened for reading then also throws FileNotFoundException exception

Read for Details FileInputStream

First, check the permission of that file. Is it opened for reading or not.

public static boolean isReadable(Path path): return true if the file
  exists and is readable but it is not guaranteed; Note that the result of this
  method is immediately outdated, there is no guarantee that a
  subsequent attempt to open the file for reading will succeed (or even
  that it will access the same file). Care should be taken when using
  this method in security sensitive applications.

Title: how to set path for File Input Stream

Body:
i was trying to use a txt file but i got this eror "FileNotFoundException"
but it was readable and it exist but on line FileInputStream i got that error
whats the matter?

        System.out.println(Files.isReadable(Paths.get("I:/Code/Coding/src/Files/" + path + ".txt")));
        System.out.println(Files.exists(Paths.get("I:/Code/Coding/src/Files/" + path + ".txt")));
        FileInputStream f1=new FileInputStream("I:/Code/Coding/src/Files/" + path + ".txt");
        reader = new ObjectInputStream(f1);

java.io.FileNotFoundException: I:\Code\Coding\src\Files\Artists.txt (The system cannot find the path specified)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(FileInputStream.java:195)
    at java.io.FileInputStream.<init>(FileInputStream.java:138)
    at java.io.FileInputStream.<init>(FileInputStream.java:93)
    at sample.Datebase.Server.readFiles(Server.java:70)
    at sample.Datebase.Server.run(Server.java:99)
    at sample.Datebase.Server.main(Server.java:54)
Exception in thread "main" java.lang.NullPointerException
    at sample.Datebase.Server.readFiles(Server.java:94)
    at sample.Datebase.Server.run(Server.java:99)
    at sample.Datebase.Server.main(Server.java:54)


问:
Solving a matrix equation with constraints on the answer in python
I'm currently trying to solve a matrix equation of the form Ax = b where A is an NxN square matrix and x,b are 1xN vectors. However, I require that all the elements x[i] be non-negative.

Imposing this constraint means that a solution may well not be possible (if you're doing this analytically there is only 1 unique solution, which if it has negative entries puts me out of luck) but there must be a way to find an x that gets as close as possible? I'm unsure what this is formally called so I've had little luck searching.

What I have so far:

```<code>N=10

A = np.random.rand(N,N)
B = np.random.rand(N)

A_inv = np.linalg.inv(A)
x = np.dot( A_inv, B )

x=
array([ 0.42216451,  1.70270083, -1.54040488,  2.18724233,  2.04278932, -1.76074253])
</code>```

Any help would be massively appreciated. Thanks!

答:
Your problem is called non-negative least-squares and scipy supports it.

Without testing, usage would look like:

```<code>import numpy as np
from scipy.optimize import nnls

N=10

A = np.random.rand(N,N)
B = np.random.rand(N)
x, rnorm = nnls(A, B)
</code>```

The algorithm is quite old and highly trusted, but only works for small-to-medium scale problems (as it calculates A.T * A internally). If you got huge problems (sparse problem with millions of variables), you should try some custom-formulation based on L-BFGS-B or better: a custom (iterative) algorithm.

Body:
I'm currently trying to solve a matrix equation of the form Ax = b where A is an NxN square matrix and x,b are 1xN vectors. However, I require that all the elements x[i] be non-negative.

Imposing this constraint means that a solution may well not be possible (if you're doing this analytically there is only 1 unique solution, which if it has negative entries puts me out of luck) but there must be a way to find an x that gets as close as possible? I'm unsure what this is formally called so I've had little luck searching.

What I have so far:

N=10

A = np.random.rand(N,N)
B = np.random.rand(N)

A_inv = np.linalg.inv(A)
x = np.dot( A_inv, B )

x=
array([ 0.42216451,  1.70270083, -1.54040488,  2.18724233,  2.04278932, -1.76074253])

Any help would be massively appreciated. Thanks!

Body:
Your problem is called non-negative least-squares and scipy supports it.

Without testing, usage would look like:

import numpy as np
from scipy.optimize import nnls

N=10

A = np.random.rand(N,N)
B = np.random.rand(N)
x, rnorm = nnls(A, B)

The algorithm is quite old and highly trusted, but only works for small-to-medium scale problems (as it calculates A.T * A internally). If you got huge problems (sparse problem with millions of variables), you should try some custom-formulation based on L-BFGS-B or better: a custom (iterative) algorithm.


问:
WooCommerce: change button class without overwrite template files
I want to change the button classes of WooCommerce with the classes from Bootstrap.

At the moment I've done that by overwriting the existing templates files. In many cases, the button classes are the only changes.

Is there any hook to do this for all buttons instead of overwriting the template files?

I couldn't find anything

答:
I don't know about a hook for this (there could be one), and I don't know about the Bootstrap classes. But if you want to avoid overwriting template files you could achieve it with some JavaScript.

Add this code to the functions.php and it will change the class names accordingly.

But the functions.php file will be overwritten with every theme update. So the proper way would be to create a child theme.

```<code>add_action( 'wp_head', 'change_button_class' );
function change_button_class() {
    ?>

    <script type="text/javascript">
    jQuery(document).ready(function($){
        $('.button-1').addClass('button-2').removeClass('button-1');
    });
    </script>

    <?php
}
</code>```

Update

Added script tag

Body:
I don't know about a hook for this (there could be one), and I don't know about the Bootstrap classes. But if you want to avoid overwriting template files you could achieve it with some JavaScript.

Add this code to the functions.php and it will change the class names accordingly.

But the functions.php file will be overwritten with every theme update. So the proper way would be to create a child theme.

add_action( 'wp_head', 'change_button_class' );
function change_button_class() {
    ?>

    <script type="text/javascript">
    jQuery(document).ready(function($){
        $('.button-1').addClass('button-2').removeClass('button-1');
    });
    </script>

    <?php
}

Update

Added script tag


问:
Direct3D: efficient way to get system memory bitmap from IDirect3DSurface9 (default pool)?
I have IDirect3DSurface9, default pool, YUV format. How can I efficiently get bitmap bits from it? At the moment I:

create render target:

device->CreateRenderTarget(surf_desc.Width, surf_desc.Height, D3DFMT_A8R8G8B8, D3DMULTISAMPLE_NONE, 0, TRUE, &render_target, NULL)

convert YUV to RGB32:

device->StretchRect(videomem_surf, NULL, render_target_, NULL, D3DTEXF_NONE)

(complete rectangle, no stretching)

create plain offscreen surface in system memory

device->CreateOffscreenPlainSurface(surf_desc.Width, surf_desc.Height, D3DFMT_A8R8G8B8, D3DPOOL_SYSTEMMEM, &sysmem_offscreen_surf, NULL)

copy data from video mem to sysmem:

device->GetRenderTargetData(render_target, sysmem_offscreen_surface)

GetDC from offscreen surface, create compatible DC and compatible bitmap, BitBlt from offscreen sufrace DC to compatible DC and copy bitmap bits to my buffer by GetDIBits()

this looks a bit of overhead, because of so many copying: from original surface to render target, then to offscreen surface, then to compatible bitmap, and then finally to my buffer. How can this be improved?

thanks

答:
Well as interjay points out ... you are nearly doing things the "correct" way.

The obvious improvements are to call CreateRenderTarget and CreateOffscreenPlainSurface once and then re-use them multiple times.  The fastest way of getting the bits back out would be to directly LockRect the surface.

Furthermore if you are needing to do this in real-time on something like video it would probably be better to set up an array of surfaces (both types).  You can then load multiple YUV frames on to the CreateRenderTarget'd surface and then once you have filled the array then copy the first to the OffscreenPlainSurface and lock it.

This way you will allow more of the commands to be pipelined and stop you calling lock and FORCING a synchronisation of the pipeline (ie the surface you are locking HAS to be ready before proceeding which causes a pipeline sync).


问:
C# Fastest search object which has nearest value given
I try to find an object in list which has nearest value that given
I wrote this :

```<code>float target = 100.0f;
int index = int.MaxValue;
float nearest = float.MaxValue;
for(int i = 0; i < objectList.Count; i++)
{
   if(Math.Abs(objectList[i].value - target) < nearest)
   {
       nearest = Math.Abs(objectList[i].value - target);
       index = i;
   }
}

//do something with objectList[index]
</code>```

This actually works, but when the list is too large, It consumes quite much time to search.

I know there are probably way to do it, but I don't know what is it.

答:
you can use linq expression like this:</p>

```<code> var  newList = objectList.Select(i => new { value = i, delta = Math.Abs(i - target) }).OrderByDescending(i=>i.delta);
    nearest = (newList.ToArray())[0].value;
</code>```

Body:
I try to find an object in list which has nearest value that given
I wrote this :

float target = 100.0f;
int index = int.MaxValue;
float nearest = float.MaxValue;
for(int i = 0; i < objectList.Count; i++)
{
   if(Math.Abs(objectList[i].value - target) < nearest)
   {
       nearest = Math.Abs(objectList[i].value - target);
       index = i;
   }
}

//do something with objectList[index]

This actually works, but when the list is too large, It consumes quite much time to search.

I know there are probably way to do it, but I don't know what is it.

Body:
you can use linq expression like this:

 var  newList = objectList.Select(i => new { value = i, delta = Math.Abs(i - target) }).OrderByDescending(i=>i.delta);
    nearest = (newList.ToArray())[0].value;


问:
How to list the profiles only when address exists
I have the relation set up this way, Profile has_many Addresses. In the index action, I am doing @profiles = Profile.all, which is giving me all the profiles, but I want to query Profile in such a way that, it will list only profiles when atleast one address exists for a profile.

The current approach I have is, I am checking in the view if the profile has an address, but I feel this is not right. Is there anyway to query like that?

答:
You can do this. It will fetch only those profiles which have an address linked to them.</p>

```<code>@profiles = Profile.joins(:addresses).distinct
</code>```

Body:
You can do this. It will fetch only those profiles which have an address linked to them.

@profiles = Profile.joins(:addresses).distinct


问:
python [SSL] PEM lib (_ssl.c:3309) error when verifying certificate
I am trying to send POST messages to a web server.
In order to do that, I am using python requests and trying to pass the requests.post method a certificate as an argument.

It looks something like that:

```<code>    if method_type == METHOD_TYPE_GET:
        resp = requests.get(base_url, data=request_data, verify=True, headers=headers, cert=certificate)
    if method_type == METHOD_TYPE_POST:
        resp = requests.post(base_url, data=request_data, verify=True, headers=headers, cert=certificate)
    return resp
</code>```

When 'certificate' is the path to a pem file, which contains the server's certificate. The file is of format:

-----BEGIN CERTIFICATE-----

-base64data-

-----END CERTIFICATE-----

When I try to execute the post method, I get an Exception of: [SSL] PEM lib (_ssl.c:3309)

Any idea what the problem is?

答:
please check your openssl - configuration file setting for the following parameter
extendedKeyUsage = clientAuth</p>

Body:
I am trying to send POST messages to a web server.
In order to do that, I am using python requests and trying to pass the requests.post method a certificate as an argument.

It looks something like that:

    if method_type == METHOD_TYPE_GET:
        resp = requests.get(base_url, data=request_data, verify=True, headers=headers, cert=certificate)
    if method_type == METHOD_TYPE_POST:
        resp = requests.post(base_url, data=request_data, verify=True, headers=headers, cert=certificate)
    return resp

When 'certificate' is the path to a pem file, which contains the server's certificate. The file is of format:

-----BEGIN CERTIFICATE-----

-base64data-

-----END CERTIFICATE-----

When I try to execute the post method, I get an Exception of: [SSL] PEM lib (_ssl.c:3309)

Any idea what the problem is?


问:
Wanted: a algorithm or SAS function for local high density of ordered binary (many 1's in a row)
Goal: Given a series of binary digits, see where there's a longer bunch of 1's (even if there are a few 0's mixed in).

Background: I'm programming a monte carlo simulation in SAS, and have (say) 100k variables with a 0 or 1.  I want to see if (somewhere) there is a cluster that is pretty dense.  I don't think 5 in a row of one's would be sufficiently dense (00011111010...), but maybe 100 one's in (01111...11111) would be great.  So, I guess I want a localized cluster.

I'm having the code for the variable be, so that n1, n2, etc. would be either 0 or 1,:

```<code>array var_of_binary{*} n1 - n100000;
</code>```

Am I asking for a solution (impossible) of the SAT-CNF which is "a classic problem that is known to be NP-complete"? (PS: I don't understand what that is, but I know it's unsolvable and too complex.)

I think making multiple passes computing density of length 21, 22, 23, ..., 1000 would work (this is pseudo-code, which I did not try to run):

```<code>static_max_of_1k = 1000;  /*check in lengths up to 1k, perhaps less*/
do i= 100 to static_max_of_1k ;
    do j=1 to 999000;
      density1 = sum(of var_of_binary{j} - var_of_binary{j+i })/i;
    /* save value of density1, probably in an array */
    end;
end;
</code>```

Note 1: I don't want a C++ solution (unless it works immediately in SAS as a subroutine without alteration).

Note 2: I don't want recursive code, since if it blows up, I wouldn't have a clue to debug it.  (I know my limitations.)

Note 3: I guess I'm doing a 1-dimensional variation of Detect High density pixel areas in a binary image which is sort of cool and a nice photo, but (again) beyond me.  I appreciated from afar the metacode of SimpleBlobDetector Class Reference.  I think I'm in over my head.

答:
Maybe this will help.  Generate data and then determine the runs and their size.  FREQ is the size of the run, J is the ID within REP and OBS is the ID of the first obs in the run.

```<code>data simulate;
   do rep=1 to 1e1;
      do j = 1 to 1e1;
         y = rand('BINOMIAL',.5,1);
         output;
         end;
      end;
   run;
proc summary data=simulate;
   by rep y notsorted;
   output out=runs(drop=_type_) idgroup(obs out[1](j)=);
   run;
proc print;
   run;
</code>```

Body:
Goal: Given a series of binary digits, see where there's a longer bunch of 1's (even if there are a few 0's mixed in).

Background: I'm programming a monte carlo simulation in SAS, and have (say) 100k variables with a 0 or 1.  I want to see if (somewhere) there is a cluster that is pretty dense.  I don't think 5 in a row of one's would be sufficiently dense (00011111010...), but maybe 100 one's in (01111...11111) would be great.  So, I guess I want a localized cluster.

I'm having the code for the variable be, so that n1, n2, etc. would be either 0 or 1,:

array var_of_binary{*} n1 - n100000;

Am I asking for a solution (impossible) of the SAT-CNF which is "a classic problem that is known to be NP-complete"? (PS: I don't understand what that is, but I know it's unsolvable and too complex.)

I think making multiple passes computing density of length 21, 22, 23, ..., 1000 would work (this is pseudo-code, which I did not try to run):

static_max_of_1k = 1000;  /*check in lengths up to 1k, perhaps less*/
do i= 100 to static_max_of_1k ;
    do j=1 to 999000;
      density1 = sum(of var_of_binary{j} - var_of_binary{j+i })/i;
    /* save value of density1, probably in an array */
    end;
end;

Note 1: I don't want a C++ solution (unless it works immediately in SAS as a subroutine without alteration).

Note 2: I don't want recursive code, since if it blows up, I wouldn't have a clue to debug it.  (I know my limitations.)

Note 3: I guess I'm doing a 1-dimensional variation of Detect High density pixel areas in a binary image which is sort of cool and a nice photo, but (again) beyond me.  I appreciated from afar the metacode of SimpleBlobDetector Class Reference.  I think I'm in over my head.

Body:
Maybe this will help.  Generate data and then determine the runs and their size.  FREQ is the size of the run, J is the ID within REP and OBS is the ID of the first obs in the run.

data simulate;
   do rep=1 to 1e1;
      do j = 1 to 1e1;
         y = rand('BINOMIAL',.5,1);
         output;
         end;
      end;
   run;
proc summary data=simulate;
   by rep y notsorted;
   output out=runs(drop=_type_) idgroup(obs out[1](j)=);
   run;
proc print;
   run;


问:
How to automate twilio outgoing call testing
Looking to add Twilio to one of the project.  Managed to setup outgoing calls with   But how can I automate the testing of these outgoing call scripts ?  or testing the simple IVR that I have setup.</p>

答:
Twilio developer evangelist here.

Twilio customer Simply Business wrote up an in depth series of blog posts describing how they implemented integration testing for their Twilio based code. I recommend you read through the posts for all the insights:

Part 1: Why testing Twilio integration is hard in our scenario

Automating tests in your local machine

Improving tests to make them deployable to CI environment


问:
Selecting distinct keys and their counts from a dictionary series in python
I have a pandas dictionary series, that takes the values like

```<code>   0 {AA:25,BB:31}
   1 {CC:45,AA:3}
   2 {BB:3,CD:4,AA:5}
</code>```

I want to create a dictionary out of it based on the key and its occurrence in series, like:

```<code>{AA:3,BB:2,CC:1,CD:1}
</code>```

答:
Maybe it's a bit late but this is another way of doing it by using pandas built-in functions.</p>

```<code>s = pd.Series([{'AA':25,'BB':31},
                 {'CC':45,'AA':3},
                 {'BB':3,'CD':4,'AA':5}])

#convert dict to a dataframe and count non nan elements and finally convert it to a dict.
s.apply(pd.Series).count().to_dict()
Out[651]: {'AA': 3, 'BB': 2, 'CC': 1, 'CD': 1}
</code>```

Body:
I have a pandas dictionary series, that takes the values like

   0 {AA:25,BB:31}
   1 {CC:45,AA:3}
   2 {BB:3,CD:4,AA:5}

I want to create a dictionary out of it based on the key and its occurrence in series, like:

{AA:3,BB:2,CC:1,CD:1}

Body:
Maybe it's a bit late but this is another way of doing it by using pandas built-in functions.

s = pd.Series([{'AA':25,'BB':31},
                 {'CC':45,'AA':3},
                 {'BB':3,'CD':4,'AA':5}])

#convert dict to a dataframe and count non nan elements and finally convert it to a dict.
s.apply(pd.Series).count().to_dict()
Out[651]: {'AA': 3, 'BB': 2, 'CC': 1, 'CD': 1}


问:
Aligning tables in HTML
I've got a HTML page. This is what I want it to look like desired page layout and this is what I've got so far. enter image description here

It's in SharePoint and I want to use inline CSS. HTML below, any suggestions welcome.

```<code><style type="text/css">
.tg  {border-collapse:collapse;border-spacing:0;}
.tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-     style:solid;border-width:1px;overflow:hidden;word-break:normal;}
.tg .tg-yw4l{vertical-align:top}
 </style>
<table class="tg" align="left" table border="1" style="padding-right:   10px;">
</code>```

```<code>    <h1>Devices</h1>
    <div id="devices">
    </div>
</td>
</code>```

```<code><table class="tg">
<//table align="center">
  <tr>
<    td class="tg-yw4l">
        <h1>Device Details</h1>
    <div id="devicedetails">
    </div>
</td>
<td class="tg-yw4l">
<h1>Specfication </h1>
    <div id="deviceoverview">
     <div id="devicekind">
    </div>
</code>```

```<code></table>
<p>  </p>
<table class="tg">
  <tr>
    <td class="tg-yw4l">
        <h1>Known Issues</h1>
    <div id="knowntitle">
        <div id="knownsystemissues">

    </div>
</td>
</tr>
</table>

<table class="tg" align="center">
  <tr>
   <td class="tg-yw4l" align="center">

      <h1>Accessories</h1>
    <div id="deviceacc">

</td>
</code>```

```<code><table class="tg" align="left" width="50%">
      <tr>
<td class="tg-yw4l">
    <h1>Typical Usage</h1>

    <div id="deviceuse">
    </div>
</td>
<//td class="tg-yw4l">

    <div id=" ">

    </div>
</code>```

答:
    Devices
    Devise Details
    Specification

    Known Issues
    Accessories

    Typical Usage

```

Title: Aligning tables in HTML

Body:
I've got a HTML page. This is what I want it to look like desired page layout and this is what I've got so far. enter image description here

It's in SharePoint and I want to use inline CSS. HTML below, any suggestions welcome.

Devices

<//table align="center">

Device Details

Specfication

Known Issues

Accessories

Typical Usage

<//td class="tg-yw4l">

Body:
<style>
  td {
    padding: 2rem;
    border: 1px solid black;
  }
</style>
<table>
  <tr>
    <td rowspan="3">Devices</td>
    <td>Devise Details</td>
    <td>Specification</td>
  </tr>
  <tr>
    <td>Known Issues</td>
    <td>Accessories</td>
  </tr>
  <tr>
    <td colspan="2">Typical Usage</td>
  </tr>
</table>


问:
How to add click listener in List View, If ListView have already button in xml?
How to add click listener in List View, If ListView have already button in xml? I want to click on button for open New Activity.

Here is my code.
WashDetail.xml

```<code>      <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:gravity="center"
            android:orientation="horizontal">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#000"
                android:text="Malaber Hill" />

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:layout_marginLeft="16dp"
                android:layout_marginEnd="20dp"
                android:text="Get Details"
                android:id="@+id/gardetails"
                android:textColor="#FFFFFF"
                android:textSize="20dp"
                android:textStyle="normal"

                />
 </LinearLayout>
</code>```

activity_wash_detail

```<code>    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
       <ListView
         android:layout_width="fill_parent"
         android:id="@+id/ls"
         android:layout_below="@+id/headerlay"
         android:focusable="true"
         android:clickable="true"
         android:duplicateParentState="true"
         android:focusableInTouchMode="true"
         android:layout_height="fill_parent">
        </ListView>
 </LinearLayout>
</code>```

WashDetailActivity.java

```<code>protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_wash_detail);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    listView = (ListView) findViewById(ls);
    GetDetails=(Button)findViewById(R.id.gardetails);
    Models = new ArrayList<>();
    Models.add(new WashDetailing(R.drawable.spl, "PP AUTOMATIVES", R.drawable.mahindra, "Authorized"));
    adapter = new WashDetailingAdapter(Models, getApplicationContext());

    listView.setAdapter(adapter);

    listView.setClickable(false);

     gardetails.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v)
         {
            Intent intent= new         Intent(getApplicationContext(),GarageDetailActivity.class);
            startActivity(intent);

        }
    });
}
</code>```

答:
use this code on your Listview Adapter class</p>

```<code>@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = context.getLayoutInflater();
    View listViewItem = inflater.inflate(R.layout.item_rating_rows, null, true);
    Button btn = (Button) listViewItem.findViewById(R.id.btn);

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Log.d("__onclick", "" + view.getId());
        }
    });
</code>```

Body:
How to add click listener in List View, If ListView have already button in xml? I want to click on button for open New Activity.

Here is my code.
WashDetail.xml

      <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:gravity="center"
            android:orientation="horizontal">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#000"
                android:text="Malaber Hill" />

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:layout_marginLeft="16dp"
                android:layout_marginEnd="20dp"
                android:text="Get Details"
                android:id="@+id/gardetails"
                android:textColor="#FFFFFF"
                android:textSize="20dp"
                android:textStyle="normal"

                />
 </LinearLayout>

activity_wash_detail

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
       <ListView
         android:layout_width="fill_parent"
         android:id="@+id/ls"
         android:layout_below="@+id/headerlay"
         android:focusable="true"
         android:clickable="true"
         android:duplicateParentState="true"
         android:focusableInTouchMode="true"
         android:layout_height="fill_parent">
        </ListView>
 </LinearLayout>

WashDetailActivity.java

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_wash_detail);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    listView = (ListView) findViewById(ls);
    GetDetails=(Button)findViewById(R.id.gardetails);
    Models = new ArrayList<>();
    Models.add(new WashDetailing(R.drawable.spl, "PP AUTOMATIVES", R.drawable.mahindra, "Authorized"));
    adapter = new WashDetailingAdapter(Models, getApplicationContext());

    listView.setAdapter(adapter);

    listView.setClickable(false);

     gardetails.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v)
         {
            Intent intent= new         Intent(getApplicationContext(),GarageDetailActivity.class);
            startActivity(intent);

        }
    });
}

Body:
use this code on your Listview Adapter class

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = context.getLayoutInflater();
    View listViewItem = inflater.inflate(R.layout.item_rating_rows, null, true);
    Button btn = (Button) listViewItem.findViewById(R.id.btn);

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Log.d("__onclick", "" + view.getId());
        }
    });


问:
iOS, LiveQuery - Subscribe to a range of events at once?
I'm trying out the LiveQuery SDK and I want to know, if it's possible to subscribe to create and update events, in one subscription...</p>

答:
Found it! That's how you subscribe to all events:

subscription = liveQueryClient.subscribe(chatRoomQuery)
 _ = subscription?.handleEvent { query, event in
     print(query)
     print(event)
}


问:
how to avoid countdown timer reset on page refresh , node js / socket io
server.js

```<code>io.on('connection', function (socket) {
  var addedUser = false;

  socket.on('setTimer', function(data) {
    timer.setEndTime(data.time);
    socket.broadcast.emit('currentEndTime', {time: timer.getEndTime() });
  });
  });
</code>```

client.js

```<code>$(function() {

    var timer = new Timer(),
    socket = io.connect('http://localhost:3000');

socket.on('currentEndTime', function (data) {
    //this is the full date time in ms.
    timer.setEndTimeFromServer(data.time);
});

 set = setInterval(function(){
  $('.time').trigger('click');
   clearInterval(set);
  },100);

   $('.time').on('click', function(e) {
    e.stopPropagation();
    var time = $(this).text() * 1000;
    timer.setEndTime(time);
    timer.timeRemaining();
        socket.emit('setTimer', { time: time });
    });
});
</code>```

Hi there, i am trying to integrate countdown timer for node js/socket io application. Timer works fine, but how do i avoid timer reset on new socket connection/page refresh. Thank You

答:
This is because of two things:

Your socket goes away when you hit the refresh button and a new one is created and thus your connection to the server (and hence the timer value) goes away when you hit the refresh button.

When you load the page first, you don't get the current value of the timer and print it on your page to start everything.

You can have each individual timer stored in a key value storage. You can use the IP Address as key and timer value as value or something like that. This way, you can retrieve the current value of the timer for the user when user connects to the server and continue counting down.

If you use the socket ID as key, it will do you no good except to pointlessly populate a key value storage and spike up your memory usage. Use something more persistent, such as IP Address, username, e-mail or something of that sort as key and current value of timer as value.

Also, your current solution is flawed because it faces the "refresh lag". When you hit the refresh button, you stop counting for the amount of time that is spent on re-rendering of your web page. If it's nothing more than a handful of milliseconds, you're fine; but as long as it goes to a few hundreds of milliseconds, this will make actual difference. Do the count down at the server side. Just notify the client at the set intervals. This will increase the server workload, but at least you're not bound to having bad timers.

If you're going to have a single countdown, like "x days, x hours, x minutes, x seconds remaining to Superbowl or some other big event", you're much better off without socket.io. Just send the timestamp to the big event to the client and do the remainder on the client side.

Body:
server.js

io.on('connection', function (socket) {
  var addedUser = false;

  socket.on('setTimer', function(data) {
    timer.setEndTime(data.time);
    socket.broadcast.emit('currentEndTime', {time: timer.getEndTime() });
  });
  });

client.js

$(function() {

    var timer = new Timer(),
    socket = io.connect('http://localhost:3000');

socket.on('currentEndTime', function (data) {
    //this is the full date time in ms.
    timer.setEndTimeFromServer(data.time);
});

 set = setInterval(function(){
  $('.time').trigger('click');
   clearInterval(set);
  },100);

   $('.time').on('click', function(e) {
    e.stopPropagation();
    var time = $(this).text() * 1000;
    timer.setEndTime(time);
    timer.timeRemaining();
        socket.emit('setTimer', { time: time });
    });
});

Hi there, i am trying to integrate countdown timer for node js/socket io application. Timer works fine, but how do i avoid timer reset on new socket connection/page refresh. Thank You


问:
Python 3: search for a specific string in a file
I have a txt file with strings assigned to each other like "sun - moon" and I want to get the assigned value (no matter which one) of a particular string if it would come from user input, and if not then create a new pair for file and write it to it:</p>

```<code>user_input = input()

if user_input in open('base.txt').read():
    print(True) # it's just to be sure that everything really works
else:
    base_file = open('base.txt', 'a+')
    base_file.write(user_input)
    base_file.write('\n')
    base_file.close()
</code>```

答:
A little addition to the current code.</p>

```<code>user_input = input()
flag=1
with open('base.txt') as f:
  data=f.read()
  if user_input in data:
    print(data)
    flag=0
if flag:
  base_file = open('base.txt', 'a+')
  base_file.write(user_input)
  base_file.write('\n')
  base_file.close()
</code>```

Body:
I have a txt file with strings assigned to each other like "sun - moon" and I want to get the assigned value (no matter which one) of a particular string if it would come from user input, and if not then create a new pair for file and write it to it:

user_input = input()

if user_input in open('base.txt').read():
    print(True) # it's just to be sure that everything really works
else:
    base_file = open('base.txt', 'a+')
    base_file.write(user_input)
    base_file.write('\n')
    base_file.close()

Body:
A little addition to the current code.

user_input = input()
flag=1
with open('base.txt') as f:
  data=f.read()
  if user_input in data:
    print(data)
    flag=0
if flag:
  base_file = open('base.txt', 'a+')
  base_file.write(user_input)
  base_file.write('\n')
  base_file.close()


问:
how to avoid error of adding string to generator expressions?
I need to iterate over folder names and then over images but I've got this error.  May someone tell me how to avoid the error?</p>

```<code>path = '/.../'

dirs = next(os.walk(path))[1] # get my folder names inside my directory

for i in dirs:
    for img in os.listdir(path+(x for x in dirs)): <------ TypeError: must be str, not generator
        img_path = os.path.join(path,img)
        print(img_path)
</code>```

答:
The error is coming from the previous line where you're trying to add path to a generator exp:

```<code>path+(x for x in dirs)
</code>```

You should join the path to the directory name using os.path.join:

```<code>for dir in dirs:
   for img in os.listdir(os.path.join(path, dir)):
      ...
</code>```

Body:
I need to iterate over folder names and then over images but I've got this error.  May someone tell me how to avoid the error?

path = '/.../'

dirs = next(os.walk(path))[1] # get my folder names inside my directory

for i in dirs:
    for img in os.listdir(path+(x for x in dirs)): <------ TypeError: must be str, not generator
        img_path = os.path.join(path,img)
        print(img_path)

Body:
The error is coming from the previous line where you're trying to add path to a generator exp:

path+(x for x in dirs)

You should join the path to the directory name using os.path.join:

for dir in dirs:
   for img in os.listdir(os.path.join(path, dir)):
      ...


问:
Ruby modules for functions
It is possible to add methods to a class using modules. E.g.,

```<code>class Test
  include Singleton
end
</code>```

Is it possible to do the same with methods? E.g.,

```<code>class Test
  include Singleton

  def test
    include Instructions_to_add_to_the_method
    puts 'done'
  end
end
</code>```

where:

```<code>module Instructions_to_add_to_the_method
  puts 'hi !'
end
</code>```

When calling Test.instance.test, I want:

```<code>hi !
done
</code>```

I do not wish to call another method, as it would give me issues with the scope of my variables.

答:
It is possible to add methods to a class using modules. E.g.,

```<code>class Test
  include Singleton
end
</code>```

No. This does not "add methods to a class". include simply makes Singleton the superclass of Test. Nothing more. Nothing is being "added to a class". It's just inheritance.

Is it possible to do the same with methods? E.g.,

```<code>class Test
  include Singleton

  def test
    include Instructions_to_add_to_the_method
    puts 'done'
  end
end
</code>```

There is no method Test#include, so this will simply raise a NoMethodError.

When calling Test.instance.test, I want:

```<code>hi !
done
</code>```

That's what inheritance is for:

```<code>class Test
  include Singleton

  def test
    super
    puts 'done'
  end
end

module Instructions_to_add_to_the_method
  def test
    puts 'hi'
  end
end

class Test
  include Instructions_to_add_to_the_method
end

Test.instance.test
# hi
# done
</code>```

Note that this way of using inheritance in Ruby is a little bit backward. If you really need something like this, you should use a language like Beta, where this is how inheritance works naturally.

A better solution would be something like the Template Method Software Design Pattern which in Ruby can be something as simple as yielding to a block:

```<code>class Test
  include Singleton

  def test
    yield
    puts 'done'
  end
end

Test.instance.test { puts 'hi' }
# hi
# done
</code>```

or taking a Proc as an argument:

```<code>class Test
  include Singleton

  def test(prc)
    prc.()
    puts 'done'
  end
end

Test.instance.test(-> { puts 'hi' })
# hi
# done
</code>```

or by calling a hook method:

```<code>class Test
  include Singleton

  def test
    extension_hook
    puts 'done'
  end

  def extension_hook; end
end

class HookedTest < Test
  def extension_hook
    puts 'hi'
  end
end

HookedTest.instance.test
# hi
# done
</code>```

I do not wish to call another method, as it would give me issues with the scope of my variables.

There are no variables in your code, so there can't possibly be any "issues" with them.

Title: Ruby modules for functions

Body:
It is possible to add methods to a class using modules. E.g.,

class Test
  include Singleton
end

Is it possible to do the same with methods? E.g.,

class Test
  include Singleton

  def test
    include Instructions_to_add_to_the_method
    puts 'done'
  end
end

where:

module Instructions_to_add_to_the_method
  puts 'hi !'
end

When calling Test.instance.test, I want:

hi !
done

I do not wish to call another method, as it would give me issues with the scope of my variables.

Body:
It is possible to add methods to a class using modules. E.g.,

class Test
  include Singleton
end

No. This does not "add methods to a class". include simply makes Singleton the superclass of Test. Nothing more. Nothing is being "added to a class". It's just inheritance.

Is it possible to do the same with methods? E.g.,

class Test
  include Singleton

  def test
    include Instructions_to_add_to_the_method
    puts 'done'
  end
end

There is no method Test#include, so this will simply raise a NoMethodError.

When calling Test.instance.test, I want:

hi !
done

That's what inheritance is for:

class Test
  include Singleton

  def test
    super
    puts 'done'
  end
end

module Instructions_to_add_to_the_method
  def test
    puts 'hi'
  end
end

class Test
  include Instructions_to_add_to_the_method
end

Test.instance.test
# hi
# done

Note that this way of using inheritance in Ruby is a little bit backward. If you really need something like this, you should use a language like Beta, where this is how inheritance works naturally.

A better solution would be something like the Template Method Software Design Pattern which in Ruby can be something as simple as yielding to a block:

class Test
  include Singleton

  def test
    yield
    puts 'done'
  end
end

Test.instance.test { puts 'hi' }
# hi
# done

or taking a Proc as an argument:

class Test
  include Singleton

  def test(prc)
    prc.()
    puts 'done'
  end
end

Test.instance.test(-> { puts 'hi' })
# hi
# done

or by calling a hook method:

class Test
  include Singleton

  def test
    extension_hook
    puts 'done'
  end

  def extension_hook; end
end

class HookedTest < Test
  def extension_hook
    puts 'hi'
  end
end

HookedTest.instance.test
# hi
# done

I do not wish to call another method, as it would give me issues with the scope of my variables.

There are no variables in your code, so there can't possibly be any "issues" with them.


问:
Graphene Django "Must provide query string"
I have setup a Graphene server using Django. When I run my queries through GraphiQL (the web client), everything works fine. However, when I run from anywhere else, I get the error: "Must provide query string."

I did some troubleshooting. GraphiQL sends POST data to the GraphQL server with Content-Type: application/json. Here is the body of the request that I copied from Chrome network tab for GraphiQL:

```<code>{"query":"query PartnersQuery {\n  partners{\n    name\n    url\n    logo\n  }\n}","variables":"null","operationName":"PartnersQuery"}
</code>```

When I copy it to Postman with Content-Type: application/json, I get the following response:

```<code>{
  "errors": [
    {
      "message": "Must provide query string."
    }
  ]
}
</code>```

What can be the cause of this problem? I have not done anything crazy with the schema. Just followed the tutorials from graphene's docs. What else can cause an issue like this?

答:
Checkout sample apps and see how they do things,

e.g.
https://github.com/mjtamlyn/graphene-tutorial
they do the following:

```<code>from django.views.decorators.csrf import csrf_exempt
from graphene_django.views import GraphQLView

url(r'^explore', GraphQLView.as_view(graphiql=True)),
url(r'^graphql', csrf_exempt(GraphQLView.as_view())),
</code>```

Body:
I have setup a Graphene server using Django. When I run my queries through GraphiQL (the web client), everything works fine. However, when I run from anywhere else, I get the error: "Must provide query string."

I did some troubleshooting. GraphiQL sends POST data to the GraphQL server with Content-Type: application/json. Here is the body of the request that I copied from Chrome network tab for GraphiQL:

{"query":"query PartnersQuery {\n  partners{\n    name\n    url\n    logo\n  }\n}","variables":"null","operationName":"PartnersQuery"}

When I copy it to Postman with Content-Type: application/json, I get the following response:

{
  "errors": [
    {
      "message": "Must provide query string."
    }
  ]
}

What can be the cause of this problem? I have not done anything crazy with the schema. Just followed the tutorials from graphene's docs. What else can cause an issue like this?

Body:
Checkout sample apps and see how they do things,

e.g.
https://github.com/mjtamlyn/graphene-tutorial
they do the following:

from django.views.decorators.csrf import csrf_exempt
from graphene_django.views import GraphQLView

url(r'^explore', GraphQLView.as_view(graphiql=True)),
url(r'^graphql', csrf_exempt(GraphQLView.as_view())),


问:
Swift 3- How to get button in UICollectionViewCell work
I am trying to implement an Edit button inside a cell.

Please refer to image:

What I done so far:

MainController:

```<code>class MainController: UICollectionViewController, UICollectionViewDelegateFlowLayout  {
  let imgCellId = "imgCellId"

  override func viewDidLoad() {
    collectionView?.backgroundColor = .white
    collectionView?.register(ImgItemCell.self, forCellWithReuseIdentifier: imgCellId)
  }

  override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
      let cell = collectionView.dequeueReusableCell(withReuseIdentifier: imgCellId, for: indexPath) as! ImgItemCell
      cell.editButton.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)

      return cell
  }

  func buttonPressed(){
    print("buttonPressed !")
  }

}
</code>```

ImgItemCell:

```<code>import Material

class ImgItemCell: UICollectionViewCell{

   override init(frame: CGRect){
       super.init(frame: frame)

       setupViews()
   }
   ...
   let editButton: RaisedButton = {
       let button = RaisedButton(title: "Edit", titleColor: .black) return button
   }()

  func setupViews(){
     ...
     addSubview(editButton)
     ...
  }

}
</code>```

Result: The button is not clickable. No log is printed when clicking on the button.

In android, I have done this by OnClickListener of button to perform action for each row. How can I do the same in Swift 3?

Solution: (it's working for me)

Hi all thank you for all suggestions, they’re more less the hint for me to come to the solution.

The root cause of my problem is view hierarchy (as @DatForis pointed out)

Explanation: I want a cell contains image and a layout of buttons so that I had view hierarchy as below

```<code>override func setupViews() {
    super.setupViews()

    addSubview(imgView)
    addSubview(buttonLayout)
    buttonLayout.addSubView(buttonList)
            buttonList.addSubview(editButton)
            buttonList.addSubview(shareButton)
  }
</code>```

this hierarchy somehow blocked the click event of button.

Therefore, I changed a bit in hierarchy

```<code>  override func setupViews() {
    super.setupViews()

    addSubview(imgView)
    addSubview(buttonLayout)
            buttonLayout.addSubview(editButton)
            buttonLayout.addSubview(shareButton)
   }
</code>```

and BAM ! it worked like a charm.

In fact, I need a proper explanation about why the hierarchy impact to children view.

By the way, I think most replies here are workable solution, but I selected @DonMag as final answer, because it’s clean and clear with a cool callback to Controller.

But again, my root problem is from view hierarchy.

答:
```<code>func setupViews() {
    ...
    addSubview(editButton)
    editButton.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)
}

func buttonPressed(sender:UIButton){
    print("buttonPressed !")
}
</code>```

Body:
I am trying to implement an Edit button inside a cell.

Please refer to image:

What I done so far:

MainController:

class MainController: UICollectionViewController, UICollectionViewDelegateFlowLayout  {
  let imgCellId = "imgCellId"

  override func viewDidLoad() {
    collectionView?.backgroundColor = .white
    collectionView?.register(ImgItemCell.self, forCellWithReuseIdentifier: imgCellId)
  }

  override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
      let cell = collectionView.dequeueReusableCell(withReuseIdentifier: imgCellId, for: indexPath) as! ImgItemCell
      cell.editButton.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)

      return cell
  }

  func buttonPressed(){
    print("buttonPressed !")
  }

}

ImgItemCell:

import Material

class ImgItemCell: UICollectionViewCell{

   override init(frame: CGRect){
       super.init(frame: frame)

       setupViews()
   }
   ...
   let editButton: RaisedButton = {
       let button = RaisedButton(title: "Edit", titleColor: .black) return button
   }()

  func setupViews(){
     ...
     addSubview(editButton)
     ...
  }

}

Result: The button is not clickable. No log is printed when clicking on the button.

In android, I have done this by OnClickListener of button to perform action for each row. How can I do the same in Swift 3?

Solution: (it's working for me)

Hi all thank you for all suggestions, they’re more less the hint for me to come to the solution.

The root cause of my problem is view hierarchy (as @DatForis pointed out)

Explanation: I want a cell contains image and a layout of buttons so that I had view hierarchy as below

override func setupViews() {
    super.setupViews()

    addSubview(imgView)
    addSubview(buttonLayout)
    buttonLayout.addSubView(buttonList)
            buttonList.addSubview(editButton)
            buttonList.addSubview(shareButton)
  }

this hierarchy somehow blocked the click event of button.

Therefore, I changed a bit in hierarchy

  override func setupViews() {
    super.setupViews()

    addSubview(imgView)
    addSubview(buttonLayout)
            buttonLayout.addSubview(editButton)
            buttonLayout.addSubview(shareButton)
   }

and BAM ! it worked like a charm.

In fact, I need a proper explanation about why the hierarchy impact to children view.

By the way, I think most replies here are workable solution, but I selected @DonMag as final answer, because it’s clean and clear with a cool callback to Controller.

But again, my root problem is from view hierarchy.


问:
Populate Enumerable.ToList with one line of code
Please see the person class below:

```<code>public class Person
    {
        int _id { get; set; }
        string _name { get; set; }

        public Person (int id, string name)
        {
            _id = id;
            _name = name;
        }

        public Person()
        {
        }

        public IEnumerable<Person> GetPeople()
        {
            _id = 1;
            _name = "James";
            yield return this;

            _id = 2;
            _name = "Michael";
            yield return this;

            _id = 3;
            _name = "Sarah";
            yield return this;
        }
    }
</code>```

and the client code below:

```<code>Person p1 = new Person();
IEnumerable<Person> personEnumerable = p1.GetPeople();
List<Person> personList = personEnumerable.ToList();
</code>```

Why does PersonList contain three entries for Sarah after this has run? What is the best way to populate personList in the client?

答:
Because GetPeople doesn't create new instances but modify the current one and returns it 3 times.

The following code produces the expected result:

```<code>    public static IEnumerable<Person> GetPeople()
    {
        yield return new Person(1, "James");
        yield return new Person(2, "Michael");
        yield return new Person(3, "Sarah");
    }
</code>```

Body:
Please see the person class below:

public class Person
    {
        int _id { get; set; }
        string _name { get; set; }

        public Person (int id, string name)
        {
            _id = id;
            _name = name;
        }

        public Person()
        {
        }

        public IEnumerable<Person> GetPeople()
        {
            _id = 1;
            _name = "James";
            yield return this;

            _id = 2;
            _name = "Michael";
            yield return this;

            _id = 3;
            _name = "Sarah";
            yield return this;
        }
    }

and the client code below:

Person p1 = new Person();
IEnumerable<Person> personEnumerable = p1.GetPeople();
List<Person> personList = personEnumerable.ToList();

Why does PersonList contain three entries for Sarah after this has run? What is the best way to populate personList in the client?

Body:
Because GetPeople doesn't create new instances but modify the current one and returns it 3 times.

The following code produces the expected result:

    public static IEnumerable<Person> GetPeople()
    {
        yield return new Person(1, "James");
        yield return new Person(2, "Michael");
        yield return new Person(3, "Sarah");
    }


问:
Bower: ENOGIT Git is not installed or not in the PATH
Git is installed and is in the path.

Platform: Red Hat Enterprise Linux 5.8.

```<code>>which git
/usr/local/bin/git
</code>```

Yet bower can't find it:

```<code>bower angular#1.0.6  ENOGIT git is not installed or not in the PATH
</code>```

What is the recommended work-around?

答:
I solved the problem by install Git Bash from Download Git Bash.

Setting this option 3 when installing the software as shown bellow.

Finally select the project folder by right click using Bash as shown below.

and type

npm install

. It works for me.

ContentLicense: CC BY-SA 4.0

Body:
Git is installed and is in the path.

Platform: Red Hat Enterprise Linux 5.8.

>which git
/usr/local/bin/git

Yet bower can't find it:

bower angular#1.0.6  ENOGIT git is not installed or not in the PATH

What is the recommended work-around?