问:
Generate parameter list with userdefined types at runtime (using C#)
As part of my project, I am trying to build a web UI where user will select a method and pass the values. My program should be able to call the method dynamically and build a parameter list on runtime to pass it to the method.

I have created a comma separated list (string) of key and value pairs. This key/value pair is nothing but the parameter name and value of my method (methodname stored in a variable). Example: string params = "ID:123;Name:Garry;Address:addressObject;AddressLine:108 Plaza Lane;City:Avenel;State:NJ;Zip:07001;". Where ID and Name are simple string varaibles while Address is user defined type. What follows after Address i.e. AddressLine, City, State and Zip is elements of Address object. And my method definition is

```<code>public string GetInfo(string ID, string Name, Address addressObject)
{
  //return something;
}
</code>```

I am dynamically calling the method (GetInfo) that is stored in sMethodName variable using DynamicProxy like :

```<code>string sMethodName = "GetInfo";
object result = (object) proxy.CallMethod(sMethodName, arguments);
</code>```

Challenge is how to pass the argument list dynamically? Till now I am just able to extract the values from the csv variable into NamedValueCollection. Here is the code:

```<code>public static void StoreParameterValues(string param)
{
    nvc = new NameValueCollection();
    param = param.TrimEnd(';');
    string[] parameters = param.Split(new char[] { ';' });
    foreach (string val in parameters)
    {
        string[] keyValue = val.Split(new char[] { ':' });
        nvc.Add(keyValue[0], keyValue[1]);
    }
}
</code>```

..and here is the code that tries to build the parameter:

```<code>string methodName = "GetInfo";
DynamicProxyFactory factory = new DynamicProxyFactory("http://../myservice.svc");
string sContract = "";
foreach (ServiceEndpoint endpoint in factory.Endpoints)
{
    sContract = endpoint.Contract.Name;
}
DynamicProxy proxy = factory.CreateProxy(sContract);
string[] values = null;
// Create the parameter list
object[] arguments = new object[nvc.Count];
int i = -1;
foreach (string key in nvc.Keys)
{
    values = nvc.GetValues(key);
    foreach (string value in values)
    {
        arguments[++i] = value;
    }
}
object result = (object) proxy.CallMethod(methodName, arguments);
</code>```

The above code works if I have simple primitive types but not sure how can I build the logic for any other userdefined types. How can I create a object dynamically of type stored in a variable? Not sure if I was able to put my question correctly. I hope so :)

Edit: 01/19/2011: Applied the suggestion from Chris - using Reflection instead of ComponentModel.
I have converted the code to make it more generic. This works now for all primitive and custom types (resursion). Code snippet below:

```<code>private object BuildParameterList(Type type)
{
    object item = new object();

    item = Activator.CreateInstance(type);

    PropertyInfo[] propArray = type.GetProperties(BindingFlags.Public|BindingFlags.Instance);

    for (int i = 0; i < propArray.Length; i++)
    {
        PropertyInfo pi = (PropertyInfo)propArray[i];

        ////Check for custom type
        if (IsCustomType(pi.PropertyType))
        {
            object item1 = BuildParameterList(pi.PropertyType);
            pi.SetValue(item, item1, null);
        }
        else
        {
            if (property.ContainsKey(pi.Name))
            {
                pi.SetValue(item, Convert.ChangeType(property[pi.Name], pi.PropertyType), null);
            }
        }
    }
    return item;
}
</code>```

But if one of the property is Color (I just tested with Color type, will fail with other system types aswell-i guess), then it fails at the following line. Not sure how to handle system types - Color or something similar.

```<code>pi.SetValue(item, Convert.ChangeType(property[pi.Name], pi.PropertyType), null);
</code>```

答:
Can you not find what types are expected by the method, by inspecting its ParameterInfos:

```<code>endpoint.Contract.ContractType.GetMethod(methodName).GetParameters();
</code>```

and then instantiating the custom types using:

```<code>Activator.CreateInstance(parameterType);
</code>```

Body:
As part of my project, I am trying to build a web UI where user will select a method and pass the values. My program should be able to call the method dynamically and build a parameter list on runtime to pass it to the method.

I have created a comma separated list (string) of key and value pairs. This key/value pair is nothing but the parameter name and value of my method (methodname stored in a variable). Example: string params = "ID:123;Name:Garry;Address:addressObject;AddressLine:108 Plaza Lane;City:Avenel;State:NJ;Zip:07001;". Where ID and Name are simple string varaibles while Address is user defined type. What follows after Address i.e. AddressLine, City, State and Zip is elements of Address object. And my method definition is

public string GetInfo(string ID, string Name, Address addressObject)
{
  //return something;
}

I am dynamically calling the method (GetInfo) that is stored in sMethodName variable using DynamicProxy like :

string sMethodName = "GetInfo";
object result = (object) proxy.CallMethod(sMethodName, arguments);

Challenge is how to pass the argument list dynamically? Till now I am just able to extract the values from the csv variable into NamedValueCollection. Here is the code:

public static void StoreParameterValues(string param)
{
    nvc = new NameValueCollection();
    param = param.TrimEnd(';');
    string[] parameters = param.Split(new char[] { ';' });
    foreach (string val in parameters)
    {
        string[] keyValue = val.Split(new char[] { ':' });
        nvc.Add(keyValue[0], keyValue[1]);
    }
}

..and here is the code that tries to build the parameter:

string methodName = "GetInfo";
DynamicProxyFactory factory = new DynamicProxyFactory("http://../myservice.svc");
string sContract = "";
foreach (ServiceEndpoint endpoint in factory.Endpoints)
{
    sContract = endpoint.Contract.Name;
}
DynamicProxy proxy = factory.CreateProxy(sContract);
string[] values = null;
// Create the parameter list
object[] arguments = new object[nvc.Count];
int i = -1;
foreach (string key in nvc.Keys)
{
    values = nvc.GetValues(key);
    foreach (string value in values)
    {
        arguments[++i] = value;
    }
}
object result = (object) proxy.CallMethod(methodName, arguments);

The above code works if I have simple primitive types but not sure how can I build the logic for any other userdefined types. How can I create a object dynamically of type stored in a variable? Not sure if I was able to put my question correctly. I hope so :)

Edit: 01/19/2011: Applied the suggestion from Chris - using Reflection instead of ComponentModel.
I have converted the code to make it more generic. This works now for all primitive and custom types (resursion). Code snippet below:

private object BuildParameterList(Type type)
{
    object item = new object();

    item = Activator.CreateInstance(type);

    PropertyInfo[] propArray = type.GetProperties(BindingFlags.Public|BindingFlags.Instance);

    for (int i = 0; i < propArray.Length; i++)
    {
        PropertyInfo pi = (PropertyInfo)propArray[i];

        ////Check for custom type
        if (IsCustomType(pi.PropertyType))
        {
            object item1 = BuildParameterList(pi.PropertyType);
            pi.SetValue(item, item1, null);
        }
        else
        {
            if (property.ContainsKey(pi.Name))
            {
                pi.SetValue(item, Convert.ChangeType(property[pi.Name], pi.PropertyType), null);
            }
        }
    }
    return item;
}

But if one of the property is Color (I just tested with Color type, will fail with other system types aswell-i guess), then it fails at the following line. Not sure how to handle system types - Color or something similar.

pi.SetValue(item, Convert.ChangeType(property[pi.Name], pi.PropertyType), null);

Body:
Can you not find what types are expected by the method, by inspecting its ParameterInfos:

endpoint.Contract.ContractType.GetMethod(methodName).GetParameters();

and then instantiating the custom types using:

Activator.CreateInstance(parameterType);


来源: stackexchange

问:
Rstudio cannot step into the source code
I built my own R library mlib001, and did Build/Build source package, which produced tar file in that libs directory. Now I can reference that library from another main/test R script file with:

library(mlib001)

I also went to Tools in that main code screen, Install Packages, Install from Package archive, then brows to the tar file for that library mlib001, import - all gets loaded fine. I then run the main code with CTRL-ALT-R, it runs fine and invokes functions from mlib001 and all completes ok. But if I set breakpoint in the main code to step into the function from the library, once I do step  in I get the message that source code is not available: "Debug location is approximate because the source code is not available". How do I resolve this so I can step into the functions with the debugger? Thanks

答: I'm not sure if this is applicable but I had similar problems because I copied some comments written elsewhere that included some scandinavian characters, like "ä".</p>

ContentLicense: CC BY-SA 3.0


问:
Function works as intended but when converted into an onEdit() function it doesn't run till the end
I have made this nice code which does the job if I fire it from the script editor, which is to check some dates and send out some e-mails if some dates are too close to each other, but if I convert it into an onEdit() function and do an edit it launched but doesn't finishes which is such a shame. The code I am using is below. Does anyone know why it does this?</p>

```<code>function onEdit1() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var readMeSheet = ss.getSheetByName("ReadMe");
  var today = new Date();
  readMeSheet.getRange(37,1).setValue(Utilities.formatDate(today,"GMT", "dd-MMM-yyyy"));
  var dateOfLastCheck = new Date(readMeSheet.getRange(37,2).getValue());
  var overdueCheck = Math.floor(today.getTime()-dateOfLastCheck.getTime());
  var days = (1000*60*60*24);
  var temp = overdueCheck/days;

  if ( overdueCheck/days > 2 ) {
  readMeSheet.getRange(37,2).setValue(Utilities.formatDate(today,"GMT", "dd-MMM-yyyy"));
  var lastActiveSheet = ss.getActiveSheet().getName();
  ss.setActiveSheet(ss.getSheetByName('Active Jobs'));
  var fEmptyRow = getFirstEmptyRow('Active Jobs');

  for ( i=2; i<fEmptyRow; i++ ){
  var jobDate = new Date(ss.getActiveSheet().getRange(i,15).getValue());
  var dif = Math.floor(jobDate.getTime()-today.getTime());
    if ( dif/days < 3) {
      switch(ss.getActiveSheet().getRange(i,8).getValue()){
        case "*******":
        case "*******":
        case "*******":
        case "*******":
        case "*******":
        case "*******":
        case "*******":
          var emailExtension = "@*******.com";
          break
        case "*******":
        case "*******":
        case "*******":
        case "*******":
        case "*******":
        case "*******":
        case "*******":
        case "*******":
        case "*******":
          var emailExtension = "@*******.*******.com";
          break
      }

      switch(ss.getActiveSheet().getRange(i,8).getValue()){
          case "*******":
          case "*******":
          case "*******":
          case "*******":
          case "*******":
              var teamLeader = ", *******@*******.com";
              break
          case "*******":
          case "*******":
          case "*******":
          case "*******":
              var teamLeader = ", *******@*******.com";
              break
          case "*******":
          case "*******":
              var teamLeader = ", *******@*******.com";
              break
      }

                         if (MailApp.getRemainingDailyQuota() > 0) {
                            //GmailApp.sendEmail(ss.getActiveSheet().getRange(i,8).getValue() + emailExtension + teamLeader, 'Please be aware the job ID'+ss.getActiveSheet().getRange(i,1).getValue()+' less than 3 days away from the report out date',
                              GmailApp.sendEmail("*******@*******.com", 'Please be aware the job ID'+ss.getActiveSheet().getRange(i,1).getValue()+' less than 3 days away from the report out date',
                              'Hello, could you please amend the job if it is not on schedule to complete within the next 3 days and inform the PAT leader? If everything is on track please disregard this e-mail. :)')
                                                                   }
                                                                 }
                                }
  ss.setActiveSheet(ss.getSheetByName(lastActiveSheet));
}
}

function getFirstEmptyRow(sheet) {
  var spr = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheet);
  var column = spr.getRange(2,1,spr.getMaxRows()-1,1);
  var values = column.getValues(); // get all data in one call
  for(var ct = values.length-1; ct > -1; ct--){
    if(values[ct][0] != ""){
      var emptyRow = ct + 3;
      break;
    }
  }
  return emptyRow;
}
</code>```

答:
1st thing: Change your method name to onEdit() [Not onEdit1] and try

Or you can configure a trigger manually.

Edit > Current project's triggers

Read further: https://developers.google.com/apps-script/guides/triggers/installable#managing_triggers_manually

Body:
I have made this nice code which does the job if I fire it from the script editor, which is to check some dates and send out some e-mails if some dates are too close to each other, but if I convert it into an onEdit() function and do an edit it launched but doesn't finishes which is such a shame. The code I am using is below. Does anyone know why it does this?

function onEdit1() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var readMeSheet = ss.getSheetByName("ReadMe");
  var today = new Date();
  readMeSheet.getRange(37,1).setValue(Utilities.formatDate(today,"GMT", "dd-MMM-yyyy"));
  var dateOfLastCheck = new Date(readMeSheet.getRange(37,2).getValue());
  var overdueCheck = Math.floor(today.getTime()-dateOfLastCheck.getTime());
  var days = (1000*60*60*24);
  var temp = overdueCheck/days;

  if ( overdueCheck/days > 2 ) {
  readMeSheet.getRange(37,2).setValue(Utilities.formatDate(today,"GMT", "dd-MMM-yyyy"));
  var lastActiveSheet = ss.getActiveSheet().getName();
  ss.setActiveSheet(ss.getSheetByName('Active Jobs'));
  var fEmptyRow = getFirstEmptyRow('Active Jobs');

  for ( i=2; i<fEmptyRow; i++ ){
  var jobDate = new Date(ss.getActiveSheet().getRange(i,15).getValue());
  var dif = Math.floor(jobDate.getTime()-today.getTime());
    if ( dif/days < 3) {
      switch(ss.getActiveSheet().getRange(i,8).getValue()){
        case "*******":
        case "*******":
        case "*******":
        case "*******":
        case "*******":
        case "*******":
        case "*******":
          var emailExtension = "@*******.com";
          break
        case "*******":
        case "*******":
        case "*******":
        case "*******":
        case "*******":
        case "*******":
        case "*******":
        case "*******":
        case "*******":
          var emailExtension = "@*******.*******.com";
          break
      }

      switch(ss.getActiveSheet().getRange(i,8).getValue()){
          case "*******":
          case "*******":
          case "*******":
          case "*******":
          case "*******":
              var teamLeader = ", *******@*******.com";
              break
          case "*******":
          case "*******":
          case "*******":
          case "*******":
              var teamLeader = ", *******@*******.com";
              break
          case "*******":
          case "*******":
              var teamLeader = ", *******@*******.com";
              break
      }

                         if (MailApp.getRemainingDailyQuota() > 0) {
                            //GmailApp.sendEmail(ss.getActiveSheet().getRange(i,8).getValue() + emailExtension + teamLeader, 'Please be aware the job ID'+ss.getActiveSheet().getRange(i,1).getValue()+' less than 3 days away from the report out date',
                              GmailApp.sendEmail("*******@*******.com", 'Please be aware the job ID'+ss.getActiveSheet().getRange(i,1).getValue()+' less than 3 days away from the report out date',
                              'Hello, could you please amend the job if it is not on schedule to complete within the next 3 days and inform the PAT leader? If everything is on track please disregard this e-mail. :)')
                                                                   }
                                                                 }
                                }
  ss.setActiveSheet(ss.getSheetByName(lastActiveSheet));
}
}

function getFirstEmptyRow(sheet) {
  var spr = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheet);
  var column = spr.getRange(2,1,spr.getMaxRows()-1,1);
  var values = column.getValues(); // get all data in one call
  for(var ct = values.length-1; ct > -1; ct--){
    if(values[ct][0] != ""){
      var emptyRow = ct + 3;
      break;
    }
  }
  return emptyRow;
}


问:
VBA: How to copy a row and paste the row underneath using the Offset function
The offset function is traditionally used for cells but I would like to use it to copy and paste entire rows.  How do you use the offset function for entire rows?  Here is my code, however, it is not working.  Thank you.</p>

```<code>Sub Macro()

Rows("2:2").Select
Selection.Copy
Offset(1, 0).Select
Selection.Insert Shift:=xlDown
Application.CutCopyMode = False

End Sub
</code>```

答:
Avoid Select wherever possible.</p>

```<code>Sub Macro()

Dim r As Long

Application.ScreenUpdating = False

For r = Range("A" & Rows.Count).End(xlUp).Row To 1 Step -1
    With Cells(r, 1).EntireRow
        .Copy
        .Resize(2).Offset(1, 0).Insert Shift:=xlDown
    End With
    Cells(r + 1, "S").Value = DateAdd("m", 1, Cells(r, "S"))
    Cells(r + 2, "S").Value = DateAdd("m", 2, Cells(r, "S"))
Next r

Application.ScreenUpdating = True

End Sub
</code>```

Body:
The offset function is traditionally used for cells but I would like to use it to copy and paste entire rows.  How do you use the offset function for entire rows?  Here is my code, however, it is not working.  Thank you.

Sub Macro()

Rows("2:2").Select
Selection.Copy
Offset(1, 0).Select
Selection.Insert Shift:=xlDown
Application.CutCopyMode = False

End Sub

Body:
Avoid Select wherever possible.

Sub Macro()

Dim r As Long

Application.ScreenUpdating = False

For r = Range("A" & Rows.Count).End(xlUp).Row To 1 Step -1
    With Cells(r, 1).EntireRow
        .Copy
        .Resize(2).Offset(1, 0).Insert Shift:=xlDown
    End With
    Cells(r + 1, "S").Value = DateAdd("m", 1, Cells(r, "S"))
    Cells(r + 2, "S").Value = DateAdd("m", 2, Cells(r, "S"))
Next r

Application.ScreenUpdating = True

End Sub


问:
Is it ok to use wildcard CORS with a csrf token?
I usually add * as the CORS allow origin header during development and wondered if I even have to change that if I use a csrf token to secure my site from forged requests.</p>

答:
The base case for CSRF protection are requests that actually change something on the server. If it's just a GET that doesn't change stuff, you are good to go, because the same origin policy in browsers will not allow an attacker website to create requests to the original site (through a valid, logged on user's browser of course). So there is the same origin policy as protection for GETs.

Until you add access-control-allow-origin: *. With that, a malicious website can contain Javascript to download data from your service, and will be able to access the response - because you allowed it to.

Of course if there is something like a header-sent token authentication or similar so that this is not possible, then you are good to go. But the question was whether * in the CORS header is ok if you have the standard CSRF protection - and unfortunately it is not.


问:
Linking against a local `extern` variable
I reckon this has been probably answered before. Please mark as a duplicate if it has!

I'm having trouble understanding what extern means for local variables (or local functions!). I can't seem to see how it is functionally different from a static local variable... For instance:

```<code>int foo(void) {
   extern int i;
   return i++;
}

int bar(void) {
   static int i;
   return i++;
}
</code>```

AFAICT, foo and bar are the same. The difference according to the C99 spec is that i in foo should have external linkage compared to the i in bar. That said, I can't think of any way to exploit that external linkage - since it is a local variable, it isn't accessible outside of foo, let alone outside of the file.

I'm sure I'm missing something here - what is it?

EDIT

Thank you to everyone who pointed out that I'm missing a type on extern and static. You are quite correct. As a frequent answerer on SO, I now understand the frustration of the barrage of down votes that follow this sort of oversight.

答:
```<code>int foo() {
   extern i;
   return i++;
}
</code>```

Here you instrument the interpreter to see that i is declared somewhere in some outside block, and to connect this object with an object i declared somewhere before -- in your case, in file scope.

In the second case you tell the interpreter to store the variable i in some permanent storage that is available all long the execution and it is local to the function.

The algorithm of linkage is defined in ISO 9899 in paragraph 6.2.2--Linkage of identifiers. -- part of it:

For an identifier declared with the storage-class specifier extern in a scope in which a prior declaration of that identifier is visible,23) if the prior declaration specifies internal or external linkage, the linkage of the identifier at the later declaration is the same as the linkage specified at the prior declaration

See also here

External linkage: An identifier with external linkage represents the same object or function throughout the entire program, that is, in all compilation units and libraries belonging to the program. The identifier is available to the linker. When a second declaration of the same identifier with external linkage occurs, the linker associates the identifier with the same object or function.

Body:
I reckon this has been probably answered before. Please mark as a duplicate if it has!

I'm having trouble understanding what extern means for local variables (or local functions!). I can't seem to see how it is functionally different from a static local variable... For instance:

int foo(void) {
   extern int i;
   return i++;
}

int bar(void) {
   static int i;
   return i++;
}

AFAICT, foo and bar are the same. The difference according to the C99 spec is that i in foo should have external linkage compared to the i in bar. That said, I can't think of any way to exploit that external linkage - since it is a local variable, it isn't accessible outside of foo, let alone outside of the file.

I'm sure I'm missing something here - what is it?

EDIT

Thank you to everyone who pointed out that I'm missing a type on extern and static. You are quite correct. As a frequent answerer on SO, I now understand the frustration of the barrage of down votes that follow this sort of oversight.

Body:
int foo() {
   extern i;
   return i++;
}

Here you instrument the interpreter to see that i is declared somewhere in some outside block, and to connect this object with an object i declared somewhere before -- in your case, in file scope.

In the second case you tell the interpreter to store the variable i in some permanent storage that is available all long the execution and it is local to the function.

The algorithm of linkage is defined in ISO 9899 in paragraph 6.2.2--Linkage of identifiers. -- part of it:

For an identifier declared with the storage-class specifier extern in a scope in which a prior declaration of that identifier is visible,23) if the prior declaration specifies internal or external linkage, the linkage of the identifier at the later declaration is the same as the linkage specified at the prior declaration

See also here

External linkage: An identifier with external linkage represents the same object or function throughout the entire program, that is, in all compilation units and libraries belonging to the program. The identifier is available to the linker. When a second declaration of the same identifier with external linkage occurs, the linker associates the identifier with the same object or function.


问:
PHP Function to create div which will be called x amount of times
I am attempting to make an html element that contains x amount of other divs created by a function where x is dependent on the number of elements $allposts contains.

```<code><div id="postings">
    <?php
    foreach($allposts as $key => $value){
        createPost($key, $value);
    }
    ?>
 </div>
</code>```

This html and php code above is my attempt to create a "posting" for each item that is found in the $allposts array.

```<code><?php
    function createPost($author, $input)
    {
        $data = [];
        $i = 0;
        foreach($input as $key => $value){
            $data[$i] = $value;
            $i++;
        }
        echo "<div>
                <span class='post-title'>$data[0]</span>
                <span class='post-author'>$author</span>
                <span class='post-date'>$data[1]</span>
                <p class='post-desc'>$data[2]</span>
            </div>";
     }
?>
</code>```

This is the php document that contains the function createPost($author, $input).

The function works but it seems that each time the function is being called, the previous post is overridden leaving only one post visible which ends up being the last one in the array.

答:
```<code><p class='post-desc'>$data[2]</span>;
</code>```

does not have the correct closing tag, maybe it is interfering with the formatting resulting in missing data upon rendering to the browser. Do you have a sample of the html source it puts out?
Indentation really helps with readability.

```<code><?php

function createPost($author, $input)
{
    $data = [];
    $i = 0;

    foreach($input as $key => $value) {
        $data[$i] = $value;
        $i++;
    }

    echo "<div>
            <span class='post-title'>$data[0]</span>
            <span class='post-author'>$author</span>
            <span class='post-date'>$data[1]</span>
            <p class='post-desc'>$data[2]</p>
          </div>";
}

?>
</code>```

Body:
I am attempting to make an html element that contains x amount of other divs created by a function where x is dependent on the number of elements $allposts contains.

    <?php
    foreach($allposts as $key => $value){
        createPost($key, $value);
    }
    ?>

This html and php code above is my attempt to create a "posting" for each item that is found in the $allposts array.

<?php
    function createPost($author, $input)
    {
        $data = [];
        $i = 0;
        foreach($input as $key => $value){
            $data[$i] = $value;
            $i++;
        }
        echo "

                $data[0]
                $author
                $data[1]

$data[2]

";
     }
?>

This is the php document that contains the function createPost($author, $input).

The function works but it seems that each time the function is being called, the previous post is overridden leaving only one post visible which ends up being the last one in the array.

Body:
<p class='post-desc'>$data[2]</span>;

does not have the correct closing tag, maybe it is interfering with the formatting resulting in missing data upon rendering to the browser. Do you have a sample of the html source it puts out?
Indentation really helps with readability.

<?php

function createPost($author, $input)
{
    $data = [];
    $i = 0;

    foreach($input as $key => $value) {
        $data[$i] = $value;
        $i++;
    }

    echo "<div>
            <span class='post-title'>$data[0]</span>
            <span class='post-author'>$author</span>
            <span class='post-date'>$data[1]</span>
            <p class='post-desc'>$data[2]</p>
          </div>";
}

?>


问:
R - Rename ID names of a spatial object
My goal is to change the ID names of a SpatialPolygon object. I know how to access the ID names but I'm stuck to rename them.

Here is an example (it's a SpatialPolygonDataFrame but in my 'real' case it's a SpatialPolygon, so without the necessary link between polygons and the data frame) :

```<code>library(rgdal)
library(rgeos)
library(sp)
library(maptools)

data(wrld_simpl)
mymap.sp <- wrld_simpl[which(wrld_simpl$ISO3 == "ATG" |
                             wrld_simpl$ISO3 == "BRA" |
                             wrld_simpl$ISO3 == "FRA" |
                             wrld_simpl$ISO3 == "CIV"), ]

# access to the ID names
sapply(slot(mymap.sp, "polygons"), function(x) slot(x, "ID"))
[1] "ATG" "BRA" "FRA" "CIV"
</code>```

Suppose I want to replace these ID names by "1", "2", "3", "4".

答:
If performance is not an issue, you can do this in a for loop:

```<code>new_IDs = paste0("ID", 1:4)
for (i in 1:length(slot(mymap.sp, "polygons"))){
  slot(slot(mymap.sp, "polygons")[[i]], "ID") = new_IDs[i]
}
</code>```

Title: R - Rename ID names of a spatial object

Body:
My goal is to change the ID names of a SpatialPolygon object. I know how to access the ID names but I'm stuck to rename them.

Here is an example (it's a SpatialPolygonDataFrame but in my 'real' case it's a SpatialPolygon, so without the necessary link between polygons and the data frame) :

library(rgdal)
library(rgeos)
library(sp)
library(maptools)

data(wrld_simpl)
mymap.sp <- wrld_simpl[which(wrld_simpl$ISO3 == "ATG" |
                             wrld_simpl$ISO3 == "BRA" |
                             wrld_simpl$ISO3 == "FRA" |
                             wrld_simpl$ISO3 == "CIV"), ]

# access to the ID names
sapply(slot(mymap.sp, "polygons"), function(x) slot(x, "ID"))
[1] "ATG" "BRA" "FRA" "CIV"

Suppose I want to replace these ID names by "1", "2", "3", "4".

Body:
If performance is not an issue, you can do this in a for loop:

new_IDs = paste0("ID", 1:4)
for (i in 1:length(slot(mymap.sp, "polygons"))){
  slot(slot(mymap.sp, "polygons")[[i]], "ID") = new_IDs[i]
}


问:
componentDidMount, getCurrentPosition delay
I use such a pattern to get user's current position:

```<code>componentDidMount() {
       let lat, lon;
     navigator.geolocation.getCurrentPosition(function(location) {
         lat = location.coords.latitude;
         lon = location.coords.longitude;
 });
   setTimeout(() => {
    this.setState({
      lat,
      lon
    })
    console.log(this.state.lon, this.state.lat);
 }, 1000);
     }
</code>```

It actually works but looks "patchy" because of setTimeout.
The core problem is in some delay of getting location and console throws undefined without setTimeout.
I tried a few another ways to fix it but all failed:

```<code>navigator.geolocation.getCurrentPosition(function(location) {
    this.setState({
         lat: location.coords.latitude,
         lon: location.coords.longitude
     })
 }).bind(this);
</code>```

and humble let _this = this for example.
Please, is there more wise way to setState, based on geolocation?

答:
As mentioned in the comments, you can either move your bind slightly or use an arrow function:</p>

```<code>componentDidMount() {
    navigator.geolocation.getCurrentPosition(function (location) {
      this.setState({
        lat: location.coords.latitude,
        lon: location.coords.longitude
      })
    }.bind(this));

    // OR
    navigator.geolocation.getCurrentPosition(location => {
      this.setState({
        lat: location.coords.latitude,
        lon: location.coords.longitude
      })
    });
}
</code>```

Body:
I use such a pattern to get user's current position:

componentDidMount() {
       let lat, lon;
     navigator.geolocation.getCurrentPosition(function(location) {
         lat = location.coords.latitude;
         lon = location.coords.longitude;
 });
   setTimeout(() => {
    this.setState({
      lat,
      lon
    })
    console.log(this.state.lon, this.state.lat);
 }, 1000);
     }

It actually works but looks "patchy" because of setTimeout.
The core problem is in some delay of getting location and console throws undefined without setTimeout.
I tried a few another ways to fix it but all failed:

navigator.geolocation.getCurrentPosition(function(location) {
    this.setState({
         lat: location.coords.latitude,
         lon: location.coords.longitude
     })
 }).bind(this);

and humble let _this = this for example.
Please, is there more wise way to setState, based on geolocation?

Body:
As mentioned in the comments, you can either move your bind slightly or use an arrow function:

componentDidMount() {
    navigator.geolocation.getCurrentPosition(function (location) {
      this.setState({
        lat: location.coords.latitude,
        lon: location.coords.longitude
      })
    }.bind(this));

    // OR
    navigator.geolocation.getCurrentPosition(location => {
      this.setState({
        lat: location.coords.latitude,
        lon: location.coords.longitude
      })
    });
}


问:
Filter objects with many-to-many table in Rails using has_scope
There are two tables: User and Industry. User can relate to many industries and a lot of users belong to one Industry.

Industry.rb

```<code>class Industry <ApplicationRecord
    has_many: users,: through =>: industry_users
    has_many: industry_users
end
</code>```

User.rb

```<code>class User <ApplicationRecord

  belongs_to: specialty
  has_many: industries,: through =>: industry_users
  has_many: industry_users

  scope: by_specialty, -> specialty {where (: specialty_id => specialty)}
  scope: by_period, -> started_at, ended_at {where ("graduation_date> =? AND graduation_date <=?", started_at, ended_at)}
end
</code>```

IndustryUser.rb

The relationship between them is many_to_many.
There is a third table IndustryUser which stores two columns.

```<code>class IndustryUser <ApplicationRecord
    belongs_to: user
    belongs_to: industry
end
</code>```

Now I'm developing an API. I use has_scope gem to filter users by parameters in get request. Above, I successfully filtered them on the specialty and the date of graduation.
For example, filtering on the specialty.

```<code>http://localhost:3000/v1/users?by_specialty=1
</code>```

Filtering by the date of graduation. You should provide period of time.

```<code>http://localhost:3000/v1/users?
by_period[started_at]=20040101&by_period[ended_at]=20070101
</code>```

I got stuck when I wanted to get users who belong to a particular industry.
Here is an example of a get query

```<code>http://localhost:3000/v1/users?by_industry=2
</code>```

For example. Here, I want it to render all users who are related to the second industry.
Does anyone know how to filter objects that relate to many-to-many relations using has_scope?

答:
I think it's going to be something like:

```<code>scope: by_industry, -> industry {User.joins(:industry_users).where(industry_users: {id: IndustryUser.where(industry: Industry.where(id: industry))})}
</code>```

This bit finds the correct industry:

```<code>Industry.where(id: industry)
</code>```

This bit finds IndustryUser records that reference the just-found Industry:

```<code>IndustryUser.where(industry: Industry.where(id: industry))
</code>```

And then you join on the found industry_users to find Users that are reference by the industry_users.

```<code>User.joins(:industry_users).where(industry_users: {id: IndustryUser.where(industry: Industry.where(id: industry))})
</code>```

Body:
There are two tables: User and Industry. User can relate to many industries and a lot of users belong to one Industry.

Industry.rb

class Industry <ApplicationRecord
    has_many: users,: through =>: industry_users
    has_many: industry_users
end

User.rb

class User <ApplicationRecord

  belongs_to: specialty
  has_many: industries,: through =>: industry_users
  has_many: industry_users

  scope: by_specialty, -> specialty {where (: specialty_id => specialty)}
  scope: by_period, -> started_at, ended_at {where ("graduation_date> =? AND graduation_date <=?", started_at, ended_at)}
end

IndustryUser.rb

The relationship between them is many_to_many.
There is a third table IndustryUser which stores two columns.

class IndustryUser <ApplicationRecord
    belongs_to: user
    belongs_to: industry
end

Now I'm developing an API. I use has_scope gem to filter users by parameters in get request. Above, I successfully filtered them on the specialty and the date of graduation.
For example, filtering on the specialty.

http://localhost:3000/v1/users?by_specialty=1

Filtering by the date of graduation. You should provide period of time.

http://localhost:3000/v1/users?
by_period[started_at]=20040101&by_period[ended_at]=20070101

I got stuck when I wanted to get users who belong to a particular industry.
Here is an example of a get query

http://localhost:3000/v1/users?by_industry=2

For example. Here, I want it to render all users who are related to the second industry.
Does anyone know how to filter objects that relate to many-to-many relations using has_scope?

Body:
I think it's going to be something like:

scope: by_industry, -> industry {User.joins(:industry_users).where(industry_users: {id: IndustryUser.where(industry: Industry.where(id: industry))})}

This bit finds the correct industry:

Industry.where(id: industry)

This bit finds IndustryUser records that reference the just-found Industry:

IndustryUser.where(industry: Industry.where(id: industry))

And then you join on the found industry_users to find Users that are reference by the industry_users.

User.joins(:industry_users).where(industry_users: {id: IndustryUser.where(industry: Industry.where(id: industry))})


问:
How can I hide a panel that is on a SplitContainer?
I want to hide panel2 on a split container and have panel1 utilize the space. I was hoping setting Panel2Collapsed would do the trick, but no luck. Ideas?</p>

答:
With Visual Studio 2017 it is a little more trick. This is what I got to work for me.  MyControl is inside panel1.</p>

```<code>'vb.net:

MySplitContainer.Panel2Collapsed = True
MySplitContainer.Panel2.Hide()
MySplitContainer.SplitterDistance = MySplitContainer.Height
MySplitContainer.Panel1.Anchor = AnchorStyles.Bottom
MyControl.Height = MySplitContainer.Height

'for C# just add a semi-colon onto the end of each line and it should work.
</code>```

OwnerDisplayName: CrashCodes

ContentLicense: CC BY-SA 2.5

Body:
With Visual Studio 2017 it is a little more trick. This is what I got to work for me.  MyControl is inside panel1.

'vb.net:

MySplitContainer.Panel2Collapsed = True
MySplitContainer.Panel2.Hide()
MySplitContainer.SplitterDistance = MySplitContainer.Height
MySplitContainer.Panel1.Anchor = AnchorStyles.Bottom
MyControl.Height = MySplitContainer.Height

'for C# just add a semi-colon onto the end of each line and it should work.


问:
Production API Key for Google Maps on Android

I have created an API Key in the Google Console API Credentials Page.

I have restricted access to Android Apps

I have added my package and the SHA-1 Key (generated using keytool and local keystore file).

I have added the key generated to the google_maps_api.xml under src/main/res/values/ folder.

When I build the release app and have it downloaded from my website, then google maps is showing as expected.
However, when I push this to play store for beta testing, google maps doesn't show.

I have tried multiple tutorials but nothing seems to work so far.

What else should I be doing? Any suggestion will be most welcome.

答:
It seems that when I run keytool -list -v -keystore mystore.keystore The SHA-1 fingerprint that I was getting is not the one that should be in the console. I connected my device to Android Studio and watched Logcat, and filtered my app name. I noticed the error that showed which fingerprint is being used.

I pasted this SHA-1 certificate fingerprint back into the google maps console, waited 5 minutes and all is working now.

I don't understand how is it that when I run the keytool command it is giving a different SHA-1 key from the one that I saw in the logcat console.


问:
Understanding assembly from a gcc output
I'm doing a high school course about computer fundamentals and I'm trying to understand assembly code and created a hello world in C and compiled it in assembly code. I understand that "mov r0,r3" moves data from register 3 to register 0. However, how do I figure out what what the value of r3 is?

Below is the assembly code that I'm using for my understanding from:

```<code>.arch armv6
.eabi_attribute 27, 3
.eabi_attribute 28, 1
.fpu vfp
.eabi_attribute 20, 1
.eabi_attribute 21, 1
.eabi_attribute 23, 3
.eabi_attribute 24, 1
.eabi_attribute 25, 1
.eabi_attribute 26, 2
.eabi_attribute 30, 6
.eabi_attribute 34, 1
.eabi_attribute 18, 4
.file   "hello.c"
.section    .rodata
.align  2
.LC0:
    .ascii  "Hello World\000"
    .text
    .align  2
    .global main
    .type   main, %function
main:
    @ args = 0, pretend = 0, frame = 0
    @ frame_needed = 1, uses_anonymous_args = 0
    stmfd   sp!, {fp, lr}
    add     fp, sp, #4
    ldr     r0, .L2
    bl      printf
    mov     r0, r3
    ldmfd   sp!, {fp, pc}
.L3:
    .align  2
.L2:
    .word   .LC0
    .size   main, .-main
    .ident  "GCC: (Raspbian 4.9.2-10) 4.9.2"
    .section    .note.GNU-stack,"",%progbits
</code>```

Below is my C code:

```<code>// Hello World program in C

#include<stdio.h>

main()
{
    printf("Hello World");
}
</code>```

答:
Use the GNU Debugger, "gdb"!

gdb --args ./store01 starts the GNU Debugger.

It should act something like a console.

You exit by typing quit.

But of course you want to run the programm step by step and check the register contetns. So type start, which jumpes to main() and skips the initialization stuff.

Then type disassemble or disas to show the assebler you're running.

Now run the program instruction per instruction per typing stepi.

And now the interesting part: type info registers r3 and watch the output!

And another fantastic thing: you can CHANGE the values runtime: try p $r0 = 2.

That's not all.

Here's the official documentation:https://www.gnu.org/software/gdb/documentation/

And a good, small and useful tutorial: http://thinkingeek.com/2013/01/12/arm-assembler-raspberry-pi-chapter-4

Body:
I'm doing a high school course about computer fundamentals and I'm trying to understand assembly code and created a hello world in C and compiled it in assembly code. I understand that "mov r0,r3" moves data from register 3 to register 0. However, how do I figure out what what the value of r3 is?

Below is the assembly code that I'm using for my understanding from:

.arch armv6
.eabi_attribute 27, 3
.eabi_attribute 28, 1
.fpu vfp
.eabi_attribute 20, 1
.eabi_attribute 21, 1
.eabi_attribute 23, 3
.eabi_attribute 24, 1
.eabi_attribute 25, 1
.eabi_attribute 26, 2
.eabi_attribute 30, 6
.eabi_attribute 34, 1
.eabi_attribute 18, 4
.file   "hello.c"
.section    .rodata
.align  2
.LC0:
    .ascii  "Hello World\000"
    .text
    .align  2
    .global main
    .type   main, %function
main:
    @ args = 0, pretend = 0, frame = 0
    @ frame_needed = 1, uses_anonymous_args = 0
    stmfd   sp!, {fp, lr}
    add     fp, sp, #4
    ldr     r0, .L2
    bl      printf
    mov     r0, r3
    ldmfd   sp!, {fp, pc}
.L3:
    .align  2
.L2:
    .word   .LC0
    .size   main, .-main
    .ident  "GCC: (Raspbian 4.9.2-10) 4.9.2"
    .section    .note.GNU-stack,"",%progbits

Below is my C code:

// Hello World program in C

#include<stdio.h>

main()
{
    printf("Hello World");
}


问:
Bash/sed: No such file or directory
I have a script called script.sh:

```<code>FILE=$1
sed -i.bak "s|needle|pin|g" $FILE
</code>```

If I run it like this:

```<code>bash ./script.sh /var/www/path/to/file
</code>```

I get this response:

```<code>: No such file or directoryth/to/file
</code>```

If I run sed by itself, passing in the same path:

```<code>sed -i.bak "s|needle|pin|g" "/var/www/path/to/file"
</code>```

It works fine (even substituting the values correctly).

What am I doing wrong?

Bonus observation: I'm assuming it's telling me the entry path is wrong but it's hard to tell because it says ": No such file or directoryth/to/file", which indicates to me that something else is wrong. Maybe something carriage-return related?

答:
You should use quotes around your variables to prevent word splitting and filename expansion:

```<code>file="$1"
sed -i.bak "s|needle|pin|g" "$file"
</code>```

(You should also not use all-caps variable names for non-environment variables.)

In bash, each command line (after it has been split in tokens) undergoes a series of shell expansions, in a particular order (emphasis mine):

brace expansion;

tilde expansion, parameter and variable expansion, arithmetic expansion, process substitution, and command substitution (done in a left-to-right fashion);

word splitting; and

filename expansion.

So, when you write:

```<code>file='filename with spaces'
sed "pat" $file
</code>```

the $file token will undergo a variable expansion, followed by word splitting, and the command will now look like:

```<code>sed pat filename with spaces
</code>```

meaning, sed received three words for filename, instead of one.

If you use double quotes, the results of parameter expansion, command substitution, and arithmetic expansion that occurred within the double quotes, are not subjected to word splitting and filename expansion. In our example:

```<code>file='filename with spaces'
sed "pat" "$file"
</code>```

is expanded to:

```<code>sed "pat" "filename with spaces"
</code>```

with spaces in filename preserved.

Title: Bash/sed: No such file or directory

Body:
I have a script called script.sh:

FILE=$1
sed -i.bak "s|needle|pin|g" $FILE

If I run it like this:

bash ./script.sh /var/www/path/to/file

I get this response:

: No such file or directoryth/to/file

If I run sed by itself, passing in the same path:

sed -i.bak "s|needle|pin|g" "/var/www/path/to/file"

It works fine (even substituting the values correctly).

What am I doing wrong?

Bonus observation: I'm assuming it's telling me the entry path is wrong but it's hard to tell because it says ": No such file or directoryth/to/file", which indicates to me that something else is wrong. Maybe something carriage-return related?

Body:
You should use quotes around your variables to prevent word splitting and filename expansion:

file="$1"
sed -i.bak "s|needle|pin|g" "$file"

(You should also not use all-caps variable names for non-environment variables.)

In bash, each command line (after it has been split in tokens) undergoes a series of shell expansions, in a particular order (emphasis mine):

brace expansion;

tilde expansion, parameter and variable expansion, arithmetic expansion, process substitution, and command substitution (done in a left-to-right fashion);

word splitting; and

filename expansion.

So, when you write:

file='filename with spaces'
sed "pat" $file

the $file token will undergo a variable expansion, followed by word splitting, and the command will now look like:

sed pat filename with spaces

meaning, sed received three words for filename, instead of one.

If you use double quotes, the results of parameter expansion, command substitution, and arithmetic expansion that occurred within the double quotes, are not subjected to word splitting and filename expansion. In our example:

file='filename with spaces'
sed "pat" "$file"

is expanded to:

sed "pat" "filename with spaces"

with spaces in filename preserved.


问:
javascript - what is the effect of applying prototype to functions that are not constructors?
So, I know how to apply the prototype property to modify constructors that will effectively affect instances. Theoretically, the prototype should work on a normal function as well (though not necessarily have an effect if it's not a prototype of a certain instance). So I tried the code (createNewFunction is a normal function that's not a constructor)(full code is at the end)

```<code>createNewPerson.prototype.xx = (function() { //alerts hello
            alert("hello");
        })();
</code>```

I'm wondering what this actually does as to how xx is appended to the function. Is it stored as variable xx that is equal to the anon function? Or is stored as this.xx = function? How will this compare to storing the following code:

```<code>createNewPerson.xx = (function() { //alerts hello
        alert("hello");
    })();
</code>```

This also makes me wonder as to how this this line will be stored(As in if it will be stored as var mm = 3, or it won't append at all?):

```<code>createNewPerson.mm = 3;
</code>```

Full code for reference:

function createNewPerson(name) {
  var obj = {};
  obj.name = name;
  obj.greeting = function() {
    alert('Hi! I\'m ' + this.name + '.');
  };
  return obj;
}

createNewPerson.mm = 3; //does nothing when i tested it

createNewPerson.xx = (function() { //alerts hello
  alert("hello");
})();
createNewPerson.prototype.xx = (function() { //alerts hello
  alert("hello");
})();
var salva = createNewPerson('Salva');```

答:
.prototype is just an object property like any other. Functions have one by default, and when you create objects in certain ways (e.g. by using a constructor), that .prototype property can be indirectly accessed in special ways. But there's nothing magical about the property itself or assigning things to it.

```<code>createNewPerson.prototype.xx = (function() { //alerts hello
    alert("hello");
})();
</code>```

This alerts "hello" and assigns the value undefined to the .prototype property's .xx property.

Is it stored as variable xx that is equal to the anon function?

It's stored as a property xx that is equal to undefined.

```<code>createNewPerson.xx = (function() { //alerts hello
    alert("hello");
})();
</code>```

This alerts "hello" and assigns the value undefined to the .xx property of the function itself.

This also makes me wonder as to how this this line will be stored(As in if it will be stored as var mm = 3, or it won't append at all?):

```<code>createNewPerson.mm = 3;
</code>```

I don't really understand what you said there, but all this does is assign the value 3 to an .mm property on the function itself.

Body:
So, I know how to apply the prototype property to modify constructors that will effectively affect instances. Theoretically, the prototype should work on a normal function as well (though not necessarily have an effect if it's not a prototype of a certain instance). So I tried the code (createNewFunction is a normal function that's not a constructor)(full code is at the end)

createNewPerson.prototype.xx = (function() { //alerts hello
            alert("hello");
        })();

I'm wondering what this actually does as to how xx is appended to the function. Is it stored as variable xx that is equal to the anon function? Or is stored as this.xx = function? How will this compare to storing the following code:

createNewPerson.xx = (function() { //alerts hello
        alert("hello");
    })();

This also makes me wonder as to how this this line will be stored(As in if it will be stored as var mm = 3, or it won't append at all?):

createNewPerson.mm = 3;

Full code for reference:

function createNewPerson(name) {
  var obj = {};
  obj.name = name;
  obj.greeting = function() {
    alert('Hi! I\'m ' + this.name + '.');
  };
  return obj;
}

createNewPerson.mm = 3; //does nothing when i tested it

createNewPerson.xx = (function() { //alerts hello
  alert("hello");
})();
createNewPerson.prototype.xx = (function() { //alerts hello
  alert("hello");
})();
var salva = createNewPerson('Salva');

Body:
.prototype is just an object property like any other. Functions have one by default, and when you create objects in certain ways (e.g. by using a constructor), that .prototype property can be indirectly accessed in special ways. But there's nothing magical about the property itself or assigning things to it.

createNewPerson.prototype.xx = (function() { //alerts hello
    alert("hello");
})();

This alerts "hello" and assigns the value undefined to the .prototype property's .xx property.

Is it stored as variable xx that is equal to the anon function?

It's stored as a property xx that is equal to undefined.

createNewPerson.xx = (function() { //alerts hello
    alert("hello");
})();

This alerts "hello" and assigns the value undefined to the .xx property of the function itself.

This also makes me wonder as to how this this line will be stored(As in if it will be stored as var mm = 3, or it won't append at all?):

createNewPerson.mm = 3;

I don't really understand what you said there, but all this does is assign the value 3 to an .mm property on the function itself.


问:
PHP Foreach inside foreach display data in table row
How can I display data in a tablerow inside a foreach function? The agenda variable works fine, the rows variable is the one making problems, I need it inside a  tag

```<code><?php
$agenda = $days = json_decode(get_field( "field_uc_content_json" ));
unset($agenda[0]); ?>

<table class="table">
    <thead>
        <tr>
          <th> Day </th>
          <th>Description</th>
          <th>Hours</th>
        </tr>
    </thead>
<tbody>
   <?php foreach($agenda as $column) { ?>
   <tr>
    <td><?php echo $column[0]; ?></td>
    <td><?php
    $rows = explode( "\n", $column[1]);
    foreach ($rows as $row) { ?>
    <tr> <?php echo $row; ?> </tr>
    <?php    } ?>
   </td>
</tbody>
</table>
</code>```

The second foreach

vardump agenda

vardump rows

答:
It because you variable </p>

```<code>$agenda = $days = json_decode(get_field( "field_uc_content_json" ));
unset($agenda[0]); ?>
</code>```

<p>it's a object and this you dont use like a array, you need manage like object in the explode, like this: </p>

```<code>$rows = explode( "\n", $column->1);
</code>```

Body:
How can I display data in a tablerow inside a foreach function? The agenda variable works fine, the rows variable is the one making problems, I need it inside a  tag

<?php
$agenda = $days = json_decode(get_field( "field_uc_content_json" ));
unset($agenda[0]); ?>

           Day
          Description
          Hours

   <?php foreach($agenda as $column) { ?>

    <?php echo $column[0]; ?>
    <?php
    $rows = explode( "\n", $column[1]);
    foreach ($rows as $row) { ?>

 <?php echo $row; ?>

    <?php    } ?>

The second foreach

vardump agenda

vardump rows

Body:
It because you variable

$agenda = $days = json_decode(get_field( "field_uc_content_json" ));
unset($agenda[0]); ?>

it's a object and this you dont use like a array, you need manage like object in the explode, like this:

$rows = explode( "\n", $column->1);


问:
Haskell Use guarded equation to create type
I want to create a type called TwoValued and it contains two values: a and b, and I'd like to make sure that a <= b

```<code>data TwoValued a b | a <= b = ValuePair a b
                   | otherwise = ValuePair b a
</code>```

But it's not working, I think guarded equation is not allowed here, so is there any other way to achieve what I want? Thanks.

答:
You are needing here a ADT (Abstract data type), so, first, create your data type correctly:

```<code>data TwoValued a = ValuePair a a deriving Show
</code>```

then make the constructor

```<code>makePair :: Ord a => a -> a -> TwoValued a a
makePair x y = if x < y then (ValuePair x y) else (ValuePair y x)
</code>```

Finally, export the module with just the function the user need to see (in this case makePair)

ContentLicense: CC BY-SA 4.0

Body:
I want to create a type called TwoValued and it contains two values: a and b, and I'd like to make sure that a <= b

data TwoValued a b | a <= b = ValuePair a b
                   | otherwise = ValuePair b a

But it's not working, I think guarded equation is not allowed here, so is there any other way to achieve what I want? Thanks.

Body:
You are needing here a ADT (Abstract data type), so, first, create your data type correctly:

data TwoValued a = ValuePair a a deriving Show

then make the constructor

makePair :: Ord a => a -> a -> TwoValued a a
makePair x y = if x < y then (ValuePair x y) else (ValuePair y x)

Finally, export the module with just the function the user need to see (in this case makePair)


问:
Most useful ActionScript packages / libraries
What are some useful plug-ins, packages or source-code for ActionScript?

Please include ActionScript version, name, link and description.

答:
<Shameless self-plug>

asMock : Dynamic mocking framework for AS3 with integration support for FlexUnit 1/4.0/4.1, ASUnit and fluint

</Shameless self-plug>


问:
Dockerize existing Django project
I can't wrap my head around how to dockerize existing Django app.
I've read this official manual by Docker explaining how to create Django project during the creation of Docker image, but what I need is to dockerize existing project using the same method.

The main purpose of this approach is that I have no need to build docker images locally all the time, instead what I want to achieve is to push my code to a remote repository which has docker-hub watcher attached to it and as soon as the code base is updated it's being built automatically on the server.

For now my Dockerfile looks like:

```<code>FROM python:3
ENV PYTHONUNBUFFERED 1
RUN mkdir /code
WORKDIR /code
ADD requirements.txt /code/
RUN pip install Django
RUN pip install djangorestframework
RUN pip install PyQRCode
ADD . /code/
</code>```

Can anyone please explain how should I compose Dockerfile and do I need to use docker-compose.yml (if yes: how?) to achieve functionality I've described?

Solution for this question:

```<code>FROM python:3
ENV PYTHONUNBUFFERED 1
RUN mkdir /code
WORKDIR /code
RUN pip install *name of package*
RUN pip install *name of another package*
ADD . /code/
EXPOSE 8000
CMD python3 manage.py runserver 0.0.0.0:8000
</code>```

OR

```<code>FROM python:3
ENV PYTHONUNBUFFERED 1
RUN mkdir /code
WORKDIR /code
ADD requirements.txt /code/
RUN pip install -r requirements.txt
ADD . /code/
EXPOSE 8000
CMD python3 manage.py runserver 0.0.0.0:8000
</code>```

requirements.txt should be a plain list of packages, for example:

```<code>Django==1.11
djangorestframework
pyqrcode
pypng
</code>```

答:
Warning: -onbuild images have been deprecated.

@AlexForbes raised very good points. But if you want a super simple Dockerfile for Django, you can probably just do:

```<code>FROM python:3-onbuild
RUN python manage.py collectstatic
CMD ["python", "manage.py"]
</code>```

You then run your container with:

```<code>docker run myimagename runserver
</code>```

The little -onbuild modifier does most of what you need. It creates /usr/src/app, sets it as the working directory, copies all your source code inside, and runs pip install -r requirements.txt (which you forgot to run). Finally we collect statics (might not be required in your case if statics are hosted somewhere), and set the default command to manage.py so everything is easy to run.

You would need docker-compose if you had to run other containers like Celery, Redis or any other background task or server not supplied by your environment.

Title: Dockerize existing Django project

Body:
I can't wrap my head around how to dockerize existing Django app.
I've read this official manual by Docker explaining how to create Django project during the creation of Docker image, but what I need is to dockerize existing project using the same method.

The main purpose of this approach is that I have no need to build docker images locally all the time, instead what I want to achieve is to push my code to a remote repository which has docker-hub watcher attached to it and as soon as the code base is updated it's being built automatically on the server.

For now my Dockerfile looks like:

FROM python:3
ENV PYTHONUNBUFFERED 1
RUN mkdir /code
WORKDIR /code
ADD requirements.txt /code/
RUN pip install Django
RUN pip install djangorestframework
RUN pip install PyQRCode
ADD . /code/

Can anyone please explain how should I compose Dockerfile and do I need to use docker-compose.yml (if yes: how?) to achieve functionality I've described?

Solution for this question:

FROM python:3
ENV PYTHONUNBUFFERED 1
RUN mkdir /code
WORKDIR /code
RUN pip install *name of package*
RUN pip install *name of another package*
ADD . /code/
EXPOSE 8000
CMD python3 manage.py runserver 0.0.0.0:8000

OR

FROM python:3
ENV PYTHONUNBUFFERED 1
RUN mkdir /code
WORKDIR /code
ADD requirements.txt /code/
RUN pip install -r requirements.txt
ADD . /code/
EXPOSE 8000
CMD python3 manage.py runserver 0.0.0.0:8000

requirements.txt should be a plain list of packages, for example:

Django==1.11
djangorestframework
pyqrcode
pypng

Body:
Warning: -onbuild images have been deprecated.

@AlexForbes raised very good points. But if you want a super simple Dockerfile for Django, you can probably just do:

FROM python:3-onbuild
RUN python manage.py collectstatic
CMD ["python", "manage.py"]

You then run your container with:

docker run myimagename runserver

The little -onbuild modifier does most of what you need. It creates /usr/src/app, sets it as the working directory, copies all your source code inside, and runs pip install -r requirements.txt (which you forgot to run). Finally we collect statics (might not be required in your case if statics are hosted somewhere), and set the default command to manage.py so everything is easy to run.

You would need docker-compose if you had to run other containers like Celery, Redis or any other background task or server not supplied by your environment.


问:
Animated GIF, should start animating on Button click
I have a problem with making a gif animation playable on click. I found tutorials on how to insert a gif into an app, but all those gifs starts to animate immediately when you open the app, which I don't want.

I want my gif to start animating when I click on it.
I also want to make this gif as a button.. So when I click on this picture/gif it will start animating and it will also send an SMS to a specific number.

I will paste my code for button and my MainActivity code.

答:
OK, I converted my comments to an answer, since this kind of a workaround can actually solve the problem.

Maybe some future users can take advantage of this "technique" as well.

but all those gifs starts to animate immediately when you open the app You'd probably have better luck if you split your animated GIF into its frames.
  And then animate those ones, instead.

Animated GIFs are just a sequence of frames. They play immediately.

I guess I have no other option then... There actually is another option: do something "in between". Show the first frame as a single image. When clicked, load the animated version.

  And this should be a viable solution: Easy and practical.


问:
While Loop to Iterate through Databases
I was wondering if someone could help me with creating a while loop to iterate through several databases to obtain data from one table from two columns.  this is was I have done so far.  nothing works because i do not know how to make the select statement work through each database with regards to the table that I am querying from each database (dbo.tbldoc)</p>

```<code>DECLARE @Loop int
DECLARE @DBName varchar(300)
DECLARE @SQL varchar(max)
DECLARE @tableName VARCHAR(255)

SET @Loop = 1
SET @DBName = ''

   WHILE @Loop = 1
BEGIN

   SELECT [name] FROM sys.databases
   WHERE [name] like 'z%' and create_date between '2010-10-17' and '2011-01-15'
   ORDER BY [name]

      SET @Loop = @@ROWCOUNT

   IF @Loop = 0
      BREAK

   SET @SQL = ('USE ['+ @DBNAME +']')
      IF EXISTS(SELECT [name] FROM sys.tables WHERE name != 'dbo.tbldoc' )
                  BEGIN
               SELECT SUM(PGCOUNT), CREATED FROM **dbo.tbldoc**
            END
            ELSE
            --BEGIN
               PRINT 'ErrorLog'
            END
</code>```

答:
You don't have to use a "USE DATABASE" statement. You can select from the particular database table by using a 3 part identifier as in:

select * from MyDatabase.dbo.MyTable

Title: While Loop to Iterate through Databases

Body:
I was wondering if someone could help me with creating a while loop to iterate through several databases to obtain data from one table from two columns.  this is was I have done so far.  nothing works because i do not know how to make the select statement work through each database with regards to the table that I am querying from each database (dbo.tbldoc)

DECLARE @Loop int
DECLARE @DBName varchar(300)
DECLARE @SQL varchar(max)
DECLARE @tableName VARCHAR(255)

SET @Loop = 1
SET @DBName = ''

   WHILE @Loop = 1
BEGIN

   SELECT [name] FROM sys.databases
   WHERE [name] like 'z%' and create_date between '2010-10-17' and '2011-01-15'
   ORDER BY [name]

      SET @Loop = @@ROWCOUNT

   IF @Loop = 0
      BREAK

   SET @SQL = ('USE ['+ @DBNAME +']')
      IF EXISTS(SELECT [name] FROM sys.tables WHERE name != 'dbo.tbldoc' )
                  BEGIN
               SELECT SUM(PGCOUNT), CREATED FROM **dbo.tbldoc**
            END
            ELSE
            --BEGIN
               PRINT 'ErrorLog'
            END


问:
Remove IBOutlet programmatically that is set in interface builder and add it again with same constraints
Lets say I have a ViewController in a .nib file with an IBOutlet imageView as subView with constraints, the imageView is connected to the ViewController class associated with the nib file. Now I remove the imageView with the following code:

```<code>imageView.removeFromSuperview()
</code>```

And later I want to add it again to the ViewController View with the same constraints as I set in the interface builder before I removed the imageView. My questions are:

Is it possible to do that in code without initialising the ViewController again?

If I add the imageView as SubView to the VC programmatically after I have removed it the constraints are no longer available. I would really like to skip setting the constraints again in code since they already exist in the interface builder, is that possible?

答:
I think you can just hide the image view like this:

```<code>imageView.isHidden = true
</code>```

or

```<code>imageView.alpha = 0
</code>```

Otherwise, you can store the constraints somewhere and add it back to the appropriate views later.

Body:
Lets say I have a ViewController in a .nib file with an IBOutlet imageView as subView with constraints, the imageView is connected to the ViewController class associated with the nib file. Now I remove the imageView with the following code:

imageView.removeFromSuperview()

And later I want to add it again to the ViewController View with the same constraints as I set in the interface builder before I removed the imageView. My questions are:

Is it possible to do that in code without initialising the ViewController again?

If I add the imageView as SubView to the VC programmatically after I have removed it the constraints are no longer available. I would really like to skip setting the constraints again in code since they already exist in the interface builder, is that possible?

Body:
I think you can just hide the image view like this:

imageView.isHidden = true

or

imageView.alpha = 0

Otherwise, you can store the constraints somewhere and add it back to the appropriate views later.


问:
ContextMenu Fails To Remove A Row From A ListView With A Custom Adapter
The Problem is: My ContextMenu Fails to Remove a Row from a ListView with a Custom Adapter and the app crashes with a NullPointerException, see Logcat output.

I have done Google searches and searched stackoverflow. None of the information I have found solves this problem.

My Question is: What is wrong with my code?
Please provide the correct code to solve this problem.

Java Code: class TestActivity

```<code>    public class TestActivity extends ListActivity {

    private String itemNameArray[];
    private String dateArray[];

    private ListView listview;
    CustomListViewAdapter customListViewAdapter;

                    @Override
                    public void onCreate(Bundle savedInstanceState) {
                        super.onCreate(savedInstanceState);

                        setContentView(R.layout.activity_test);

                        registerForContextMenu(getListView());

                        root = Environment.getExternalStorageDirectory() + File.separator + "/ListTestFiles";
                        getDir(root);

        listview = getListView();

        name=itemNameArray;
        lastmod=dateArray;

        CustomListViewAdapter customListViewAdapter = new CustomListViewAdapter(this, name, lastmod);

        listview.setAdapter(customListViewAdapter);

  } // End of onCreate code.

    class CustomListViewAdapter extends ArrayAdapter<String> {
        Context context;
        String[] nameArray;
        String[] modifiedArray;

        CustomListViewAdapter(Context c, String[] name, String[] lastmod)
        {
            super(c, R.layout.layout_item_view, R.id.rowtext, name);
            this.context = c;
            this.nameArray = name;
            this.modifiedArray = lastmod;
        }

        public View getView(int position, View convertView, ViewGroup parent)
        {
            LayoutInflater inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View row = inflater.inflate(R.layout.layout_item_view, parent, false);

            TextView myName;
            TextView myLastMod;

            myName=(TextView) row.findViewById(R.id.rowtext);
            myName.setText(nameArray[position]);

            myLastMod=(TextView) row.findViewById(R.id.textView6);
            myLastMod.setText(modifiedArray[position]);

            return row;
        }
    }

     @Override
     public void onCreateContextMenu(ContextMenu menu, View v,
                                     ContextMenu.ContextMenuInfo menuInfo) {
         super.onCreateContextMenu(menu, v, menuInfo);
             MenuInflater inflater = getMenuInflater();
             inflater.inflate(R.menu.context_menu, menu);
     }

    @Override
    public boolean onContextItemSelected(MenuItem itemMenu) {

        final AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)itemMenu.getMenuInfo();

        switch (itemMenu.getItemId()) {
            case R.id.context_menu_rename:
                Toast.makeText(this, "Rename", Toast.LENGTH_SHORT).show();
                return true;
            case R.id.context_menu_delete:
                // NOTE TESTING the line of code below caused a runtime error: java.lang.NullPointerException
                customListViewAdapter.remove(customListViewAdapter.getItem(info.position));
                customListViewAdapter.notifyDataSetChanged();

                Toast.makeText(getApplicationContext(), "position = " + info.position, Toast.LENGTH_SHORT).show();
                Toast.makeText(this, "Delete", Toast.LENGTH_SHORT).show();

                return true;

                return super.onContextItemSelected(itemMenu);
        }
    }

}
</code>```

Logcat output:

```<code>11-12 12:46:59.965  14265-14265/com.testing.listapp D/AndroidRuntime﹕ Shutting down VM
    --------- beginning of crash
11-12 12:46:59.981  14265-14265/com.testing.listapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.testing.listapp, PID: 14265
    java.lang.NullPointerException: Attempt to invoke virtual method 'void com.testing.listapp.TestActivity$CustomListViewAdapter.remove(java.lang.Object)' on a null object reference
            at com.testing.listapp.TestActivity.onContextItemSelected(TestActivity.java:5454)
            at android.app.Activity.onMenuItemSelected(Activity.java:2905)
            at com.android.internal.policy.impl.PhoneWindow$DialogMenuCallback.onMenuItemSelected(PhoneWindow.java:4701)
            at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:761)
            at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:152)
            at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:904)
            at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:894)
            at com.android.internal.view.menu.MenuDialogHelper.onClick(MenuDialogHelper.java:167)
            at com.android.internal.app.AlertController$AlertParams$3.onItemClick(AlertController.java:1082)
            at android.widget.AdapterView.performItemClick(AdapterView.java:305)
            at android.widget.AbsListView.performItemClick(AbsListView.java:1146)
            at android.widget.AbsListView$PerformClick.run(AbsListView.java:3053)
            at android.widget.AbsListView$3.run(AbsListView.java:3860)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5254)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
</code>```

Logcat output #2 :

```<code>11-13 10:45:21.229  21432-21432/com.testing.listapp D/AndroidRuntime﹕ Shutting down VM
    --------- beginning of crash
11-13 10:45:21.246  21432-21432/com.testing.listapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.testing.listapp, PID: 21432
    java.lang.UnsupportedOperationException
            at java.util.AbstractList.remove(AbstractList.java:638)
            at java.util.AbstractList$SimpleListIterator.remove(AbstractList.java:75)
            at java.util.AbstractCollection.remove(AbstractCollection.java:229)
            at android.widget.ArrayAdapter.remove(ArrayAdapter.java:244)
            at com.testing.listapp.TestActivity.onContextItemSelected(TestActivity.java:5468)
            at android.app.Activity.onMenuItemSelected(Activity.java:2905)
            at com.android.internal.policy.impl.PhoneWindow$DialogMenuCallback.onMenuItemSelected(PhoneWindow.java:4701)
            at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:761)
            at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:152)
            at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:904)
            at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:894)
            at com.android.internal.view.menu.MenuDialogHelper.onClick(MenuDialogHelper.java:167)
            at com.android.internal.app.AlertController$AlertParams$3.onItemClick(AlertController.java:1082)
            at android.widget.AdapterView.performItemClick(AdapterView.java:305)
            at android.widget.AbsListView.performItemClick(AbsListView.java:1146)
            at android.widget.AbsListView$PerformClick.run(AbsListView.java:3053)
            at android.widget.AbsListView$3.run(AbsListView.java:3860)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5254)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
</code>```

答:
Try to change the line

```<code>CustomListViewAdapter customListViewAdapter = new CustomListViewAdapter(this, name, lastmod);
</code>```

to:

```<code>customListViewAdapter = new CustomListViewAdapter(this, name, lastmod);
</code>```

just curious if is the local variable, anyway the instance variable CustomListViewAdapter has been initialized.

Have a look to the famous SO post that usually is given when there are NPE

Body:
The Problem is: My ContextMenu Fails to Remove a Row from a ListView with a Custom Adapter and the app crashes with a NullPointerException, see Logcat output.

I have done Google searches and searched stackoverflow. None of the information I have found solves this problem.

My Question is: What is wrong with my code?
Please provide the correct code to solve this problem.

Java Code: class TestActivity

    public class TestActivity extends ListActivity {

    private String itemNameArray[];
    private String dateArray[];

    private ListView listview;
    CustomListViewAdapter customListViewAdapter;

                    @Override
                    public void onCreate(Bundle savedInstanceState) {
                        super.onCreate(savedInstanceState);

                        setContentView(R.layout.activity_test);

                        registerForContextMenu(getListView());

                        root = Environment.getExternalStorageDirectory() + File.separator + "/ListTestFiles";
                        getDir(root);

        listview = getListView();

        name=itemNameArray;
        lastmod=dateArray;

        CustomListViewAdapter customListViewAdapter = new CustomListViewAdapter(this, name, lastmod);

        listview.setAdapter(customListViewAdapter);

  } // End of onCreate code.

    class CustomListViewAdapter extends ArrayAdapter<String> {
        Context context;
        String[] nameArray;
        String[] modifiedArray;

        CustomListViewAdapter(Context c, String[] name, String[] lastmod)
        {
            super(c, R.layout.layout_item_view, R.id.rowtext, name);
            this.context = c;
            this.nameArray = name;
            this.modifiedArray = lastmod;
        }

        public View getView(int position, View convertView, ViewGroup parent)
        {
            LayoutInflater inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View row = inflater.inflate(R.layout.layout_item_view, parent, false);

            TextView myName;
            TextView myLastMod;

            myName=(TextView) row.findViewById(R.id.rowtext);
            myName.setText(nameArray[position]);

            myLastMod=(TextView) row.findViewById(R.id.textView6);
            myLastMod.setText(modifiedArray[position]);

            return row;
        }
    }

     @Override
     public void onCreateContextMenu(ContextMenu menu, View v,
                                     ContextMenu.ContextMenuInfo menuInfo) {
         super.onCreateContextMenu(menu, v, menuInfo);
             MenuInflater inflater = getMenuInflater();
             inflater.inflate(R.menu.context_menu, menu);
     }

    @Override
    public boolean onContextItemSelected(MenuItem itemMenu) {

        final AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)itemMenu.getMenuInfo();

        switch (itemMenu.getItemId()) {
            case R.id.context_menu_rename:
                Toast.makeText(this, "Rename", Toast.LENGTH_SHORT).show();
                return true;
            case R.id.context_menu_delete:
                // NOTE TESTING the line of code below caused a runtime error: java.lang.NullPointerException
                customListViewAdapter.remove(customListViewAdapter.getItem(info.position));
                customListViewAdapter.notifyDataSetChanged();

                Toast.makeText(getApplicationContext(), "position = " + info.position, Toast.LENGTH_SHORT).show();
                Toast.makeText(this, "Delete", Toast.LENGTH_SHORT).show();

                return true;

                return super.onContextItemSelected(itemMenu);
        }
    }

}

Logcat output:

11-12 12:46:59.965  14265-14265/com.testing.listapp D/AndroidRuntime﹕ Shutting down VM
    --------- beginning of crash
11-12 12:46:59.981  14265-14265/com.testing.listapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.testing.listapp, PID: 14265
    java.lang.NullPointerException: Attempt to invoke virtual method 'void com.testing.listapp.TestActivity$CustomListViewAdapter.remove(java.lang.Object)' on a null object reference
            at com.testing.listapp.TestActivity.onContextItemSelected(TestActivity.java:5454)
            at android.app.Activity.onMenuItemSelected(Activity.java:2905)
            at com.android.internal.policy.impl.PhoneWindow$DialogMenuCallback.onMenuItemSelected(PhoneWindow.java:4701)
            at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:761)
            at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:152)
            at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:904)
            at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:894)
            at com.android.internal.view.menu.MenuDialogHelper.onClick(MenuDialogHelper.java:167)
            at com.android.internal.app.AlertController$AlertParams$3.onItemClick(AlertController.java:1082)
            at android.widget.AdapterView.performItemClick(AdapterView.java:305)
            at android.widget.AbsListView.performItemClick(AbsListView.java:1146)
            at android.widget.AbsListView$PerformClick.run(AbsListView.java:3053)
            at android.widget.AbsListView$3.run(AbsListView.java:3860)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5254)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

Logcat output #2 :

11-13 10:45:21.229  21432-21432/com.testing.listapp D/AndroidRuntime﹕ Shutting down VM
    --------- beginning of crash
11-13 10:45:21.246  21432-21432/com.testing.listapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.testing.listapp, PID: 21432
    java.lang.UnsupportedOperationException
            at java.util.AbstractList.remove(AbstractList.java:638)
            at java.util.AbstractList$SimpleListIterator.remove(AbstractList.java:75)
            at java.util.AbstractCollection.remove(AbstractCollection.java:229)
            at android.widget.ArrayAdapter.remove(ArrayAdapter.java:244)
            at com.testing.listapp.TestActivity.onContextItemSelected(TestActivity.java:5468)
            at android.app.Activity.onMenuItemSelected(Activity.java:2905)
            at com.android.internal.policy.impl.PhoneWindow$DialogMenuCallback.onMenuItemSelected(PhoneWindow.java:4701)
            at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:761)
            at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:152)
            at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:904)
            at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:894)
            at com.android.internal.view.menu.MenuDialogHelper.onClick(MenuDialogHelper.java:167)
            at com.android.internal.app.AlertController$AlertParams$3.onItemClick(AlertController.java:1082)
            at android.widget.AdapterView.performItemClick(AdapterView.java:305)
            at android.widget.AbsListView.performItemClick(AbsListView.java:1146)
            at android.widget.AbsListView$PerformClick.run(AbsListView.java:3053)
            at android.widget.AbsListView$3.run(AbsListView.java:3860)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5254)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

Body:
Try to change the line

CustomListViewAdapter customListViewAdapter = new CustomListViewAdapter(this, name, lastmod);

to:

customListViewAdapter = new CustomListViewAdapter(this, name, lastmod);

just curious if is the local variable, anyway the instance variable CustomListViewAdapter has been initialized.

Have a look to the famous SO post that usually is given when there are NPE


问:
Not able to get error value from props in Async submit validation
My submit action in my react-redux app is as follows

```<code>export function submitDetails(details, callback) {
return(resolve, reject) =>{
        axios.post(URL, {
        "email": details['email'],
        "name": details['username'],
        "password": details['password']
    }).then((data) =>{
            callback();
            console.log("Success", data);
            resolve(data);
    }).catch((error) => {
        // console.log('error here', error.response.data.message);
        console.log('error', error.response);
        reject(error.response)
    })
}
}
</code>```

The console prints the error successfully in this case if the email is already registered. However, when I try to print the same error on the users form as bellow

```<code><form onSubmit={handleSubmit(this.onFormSubmit.bind(this))}>
                        <Field
                            name="username"
                            lable="Username"
                            type="text"
                            component={ renderField }
                        />
                        <Field
                            name="email"
                            type="email"
                            lable="Email"
                            component={ renderField }
                        />
                        {console.log("cheki...",error)}
                        hahahaah{error}
                        {error  && <strong>{error}</strong>}
                        <Field
                            name="password"
                            type="password"
                            lable="Password"
                            component={ renderField }
                        />
                        <Field
                            name="confirm_password"
                            type="password"
                            lable="Confirm Password"
                            component={ renderField }
                        />
                        <button type="submit" className="btn btn-primary" disabled={submitting}>Register</button>
                        <Link className="btn btn-danger" to="/login">Cancel</Link>

                    </form>
</code>```

the error is never printed.
i.e const {error, submitting, handleSubmit} = this.props; the error variable is always null. Is there something I am doing wrong???

答:
First of all, if you want validation just onSubmit, you should use Submit Validation instead.

If what you want is really Async Validation, I can see two errors in your code.

You are not throwing an error;

```

    catch((error) => {
      console.log('error', error.response);
      // you should throw an error here, for example:
      // throw { username: 'That username is taken' }
      reject(error.response)
    })

```

You are getting error wrong. You should do:

```

    const {
      meta: { asyncValidating, touched, error },
      submitting,
      handleSubmit } = this.props;

```

Refer to this great example from redux-form docs.

Body:
My submit action in my react-redux app is as follows

export function submitDetails(details, callback) {
return(resolve, reject) =>{
        axios.post(URL, {
        "email": details['email'],
        "name": details['username'],
        "password": details['password']
    }).then((data) =>{
            callback();
            console.log("Success", data);
            resolve(data);
    }).catch((error) => {
        // console.log('error here', error.response.data.message);
        console.log('error', error.response);
        reject(error.response)
    })
}
}

The console prints the error successfully in this case if the email is already registered. However, when I try to print the same error on the users form as bellow

<form onSubmit={handleSubmit(this.onFormSubmit.bind(this))}>
                        <Field
                            name="username"
                            lable="Username"
                            type="text"
                            component={ renderField }
                        />
                        <Field
                            name="email"
                            type="email"
                            lable="Email"
                            component={ renderField }
                        />
                        {console.log("cheki...",error)}
                        hahahaah{error}
                        {error  && {error}}
                        <Field
                            name="password"
                            type="password"
                            lable="Password"
                            component={ renderField }
                        />
                        <Field
                            name="confirm_password"
                            type="password"
                            lable="Confirm Password"
                            component={ renderField }
                        />
                        <button type="submit" className="btn btn-primary" disabled={submitting}>Register</button>
                        <Link className="btn btn-danger" to="/login">Cancel</Link>

                    </form>

the error is never printed.
i.e const {error, submitting, handleSubmit} = this.props; the error variable is always null. Is there something I am doing wrong???

Body:
First of all, if you want validation just onSubmit, you should use Submit Validation instead.

If what you want is really Async Validation, I can see two errors in your code.

You are not throwing an error;

    catch((error) => {
      console.log('error', error.response);
      // you should throw an error here, for example:
      // throw { username: 'That username is taken' }
      reject(error.response)
    })

You are getting error wrong. You should do:

    const {
      meta: { asyncValidating, touched, error },
      submitting,
      handleSubmit } = this.props;

Refer to this great example from redux-form docs.


问:
Eager loading sibling records without including self
For serialization I want to include an array of sibling records which shares a common foreign key. I currently have the following:

```<code>class Foo < ActiveRecord::Base
  has_many :other_instances,
           source: :foo,
           class_name: 'Foo',
           foreign_key: 'event_id',
           primary_key: 'event_id'
</code>```

When used in an include, it produces the following queries:

```<code>  Foo Load (0.2ms)  SELECT  "foo".* FROM "foo" WHERE "foo"."id" = $1 LIMIT 1  [["id", 21138]]
  Foo Load (0.4ms)  SELECT "foo".* FROM "foo" WHERE "foo"."event_id" IN (11451)
</code>```

This mostly works, but the issue is that Foo.other_instances includes itself. Is there any way to exclude that additional record in rails? The expected includes would look something like this:

```<code>  Foo Load (0.4ms)  SELECT "foo".* FROM "foo" WHERE "foo"."event_id" IN (11451) AND "foo"."id" NOT IN (21138)
</code>```

Update:

Attempting to make the condition instance dependent as in @spikermann's results in the following:

Code:

```<code>has_many :other_instances,
         source: :foo,
         class_name: 'Foo',
         foreign_key: 'event_id',
         primary_key: 'event_id',
         ->(foo) { where.not(id: foo.id) }
</code>```

Called with:

```<code>Foo.includes(:other_instances).find(21138)
</code>```

Result:

```<code>DEPRECATION WARNING: The association scope 'other_instances' is instance dependent (the scope block takes an argument). Preloading happens before the individual instances are created. This means that there is no instance being passed to the association scope. This will most likely result in broken or incorrect behavior. Joining, Preloading and eager loading of these associations is deprecated and will be removed in the future. (called from check_preloadable! at /home/jordan/prog/knotweed/vendor/bundle/gems/activerecord-4.2.7.1/lib/active_record/reflection.rb:362)
NoMethodError: undefined method `id' for nil:NilClass
</code>```

答:
What about adding a scope:</p>

```<code>has_many :other_instances,
         source: :foo,
         class_name: 'Foo',
         foreign_key: 'event_id',
         primary_key: 'event_id',
         ->(foo) { where.not(id: foo.id) }
</code>```

Body:
For serialization I want to include an array of sibling records which shares a common foreign key. I currently have the following:

class Foo < ActiveRecord::Base
  has_many :other_instances,
           source: :foo,
           class_name: 'Foo',
           foreign_key: 'event_id',
           primary_key: 'event_id'

When used in an include, it produces the following queries:

  Foo Load (0.2ms)  SELECT  "foo".* FROM "foo" WHERE "foo"."id" = $1 LIMIT 1  [["id", 21138]]
  Foo Load (0.4ms)  SELECT "foo".* FROM "foo" WHERE "foo"."event_id" IN (11451)

This mostly works, but the issue is that Foo.other_instances includes itself. Is there any way to exclude that additional record in rails? The expected includes would look something like this:

  Foo Load (0.4ms)  SELECT "foo".* FROM "foo" WHERE "foo"."event_id" IN (11451) AND "foo"."id" NOT IN (21138)

Update:

Attempting to make the condition instance dependent as in @spikermann's results in the following:

Code:

has_many :other_instances,
         source: :foo,
         class_name: 'Foo',
         foreign_key: 'event_id',
         primary_key: 'event_id',
         ->(foo) { where.not(id: foo.id) }

Called with:

Foo.includes(:other_instances).find(21138)

Result:

DEPRECATION WARNING: The association scope 'other_instances' is instance dependent (the scope block takes an argument). Preloading happens before the individual instances are created. This means that there is no instance being passed to the association scope. This will most likely result in broken or incorrect behavior. Joining, Preloading and eager loading of these associations is deprecated and will be removed in the future. (called from check_preloadable! at /home/jordan/prog/knotweed/vendor/bundle/gems/activerecord-4.2.7.1/lib/active_record/reflection.rb:362)
NoMethodError: undefined method `id' for nil:NilClass

Body:
What about adding a scope:

has_many :other_instances,
         source: :foo,
         class_name: 'Foo',
         foreign_key: 'event_id',
         primary_key: 'event_id',
         ->(foo) { where.not(id: foo.id) }


问:
How to make an autocomplete address field with google maps api?
Using Google Maps API and JQuery I would like to have an Address field that when typing it will autocomplete the address entered there. How this could be achieved?</p>

答:
It is easy, but the Google API examples give you detailed explanation with how you can get the map to display the entered location. For only autocomplete feature, you can do something like this.

First, enable Google Places API Web Service. Get the API key. You will have to use it in the script tag in html file.

```<code><input type="text" id="location">
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=[YOUR_KEY_HERE]&libraries=places"></script>
<script src="javascripts/scripts.js"></scripts>
</code>```

Use script file to load the autocomplete class. Your scripts.js file will look something like this.

```<code>    // scripts.js custom js file
$(document).ready(function () {
   google.maps.event.addDomListener(window, 'load', initialize);
});

function initialize() {
    var input = document.getElementById('location');
    var autocomplete = new google.maps.places.Autocomplete(input);
}
</code>```

Body:
It is easy, but the Google API examples give you detailed explanation with how you can get the map to display the entered location. For only autocomplete feature, you can do something like this.

First, enable Google Places API Web Service. Get the API key. You will have to use it in the script tag in html file.

<input type="text" id="location">
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=[YOUR_KEY_HERE]&libraries=places"></script>
<script src="javascripts/scripts.js"></scripts>

Use script file to load the autocomplete class. Your scripts.js file will look something like this.

    // scripts.js custom js file
$(document).ready(function () {
   google.maps.event.addDomListener(window, 'load', initialize);
});

function initialize() {
    var input = document.getElementById('location');
    var autocomplete = new google.maps.places.Autocomplete(input);
}