问:
ADD @url.action with parameter on Table cell in AJAX
I am new to this and I want to add a action method on table cell. The problem is Table is generated by java-script(AJAX).
Here's code:

```<code>$.ajax({
            url: "GetData",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            type: "POST",
            success: function (obj) {
                debugger;
                $tbl.empty();
                $tbl.append('<tr><th>ID</th><th>Name</th><th>Last Executed Date</th><th>Status</th></tr>');
                for (var i = 0; i < obj.length; i++) {
                    $tbl.append(' <tr><td> <a href="#">' + obj[i].senderId + '</a></td><td>' + obj[i].subject + '</td><td>' + obj[i].msg + '</td><td>TESTING</td></tr>');
                }
            }
        });
</code>```

Now instead of href="#"> I want to add Action Method @URL.Action on that . Here's my Action Method:

```<code><a href=@Url.Action("SingleSentShow","Home", new { msgId ='+obj[i].senderId+',receiverId='+obj[i].senderId+ })>
</code>```

But it shows error, I can't use javascript variable obj[i].senderId with c# code @Url.Action("SingleSentShow","Home", new { msgId ='+obj[i].senderId+'...
How can I fix this, or is there any other solution to add link or onClick on Table cell and pass data with it ?

答:
You can't mix server-side code and client-side code like that.

One option might be to put the base action URL in a JavaScript variable, and then append your query string parameters to it in JavaScript code.  Something like this:

```<code>var singleSentShowURL = '@Url.Action("SingleSentShow","Home")';
</code>```

This would result in something like this client-side:

```<code>var singleSentShowURL = '/Home/SingleSentShow';
</code>```

Then in your loop you could use that variable to manually build the URL.  Something like this:

```<code>$tbl.append(' <tr><td> <a href="' + singleSentShow + "?msgId=" + obj[i].senderId + "&receiverId=" + obj[i].senderId + '">' + '... the rest of your line');
</code>```

You might split it into multiple lines for readability:

```<code>var href = singleSentShow + "?msgId=" + obj[i].senderId + "&receiverId=" + obj[i].senderId;
$tbl.append(' <tr><td> <a href="' + href + '">' + '... the rest of your line');
</code>```

Body:
I am new to this and I want to add a action method on table cell. The problem is Table is generated by java-script(AJAX).
Here's code:

$.ajax({
            url: "GetData",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            type: "POST",
            success: function (obj) {
                debugger;
                $tbl.empty();
                $tbl.append('
ID	Name	Last Executed Date	Status
');
                for (var i = 0; i < obj.length; i++) {
                    $tbl.append('
 ' + obj[i].senderId + '	' + obj[i].subject + '	' + obj[i].msg + '	TESTING
');
                }
            }
        });

Now instead of  I want to add Action Method @URL.Action on that . Here's my Action Method:

But it shows error, I can't use javascript variable obj[i].senderId with c# code @Url.Action("SingleSentShow","Home", new { msgId ='+obj[i].senderId+'...
How can I fix this, or is there any other solution to add link or onClick on Table cell and pass data with it ?

Body:
You can't mix server-side code and client-side code like that.

One option might be to put the base action URL in a JavaScript variable, and then append your query string parameters to it in JavaScript code.  Something like this:

var singleSentShowURL = '@Url.Action("SingleSentShow","Home")';

This would result in something like this client-side:

var singleSentShowURL = '/Home/SingleSentShow';

Then in your loop you could use that variable to manually build the URL.  Something like this:

$tbl.append(' <tr><td> <a href="' + singleSentShow + "?msgId=" + obj[i].senderId + "&receiverId=" + obj[i].senderId + '">' + '... the rest of your line');

You might split it into multiple lines for readability:

var href = singleSentShow + "?msgId=" + obj[i].senderId + "&receiverId=" + obj[i].senderId;
$tbl.append(' <tr><td> <a href="' + href + '">' + '... the rest of your line');


来源: stackexchange

问:
Python error : index out of bounds
I was curious about image processing with python, so I found this great library imageio,
I tried to manipulate the pixels of a picture and save them in a new file,
but i had some problems with the loops
this is what the code looks like
enter image description here
and this the error that i Got !
IndexError: index 3507 is out of bounds for axis 0 with size 3507
the code :</p>

```<code> # -*- coding: iso-8859-1 -*-
    import imageio
    import numpy as np
    im = imageio.imread("JAFFRE009a.png")
    taille=im.shape  #taille is a tuple (Width,Height)
    print taille  # (4961,3507)
    matrice_pixels=open("matrice.txt",'w')
    for i in range(taille[1]):
        line=""
        for j in range(taille[0]):
            line+=repr(im[i][j])
        matrice_pixels.write(line+'\n')
    matrice_pixels.close()
</code>```

答:
EDIT

We can iterate through each row/column position and save to a file as below.It will take very long time depending upon file size.

Instead of writing your own function, you may want to take advantage of inbuilt binary save (which is more efficient) as

```<code>np.save('matrix.py', np_array)
</code>```

You can load this file as np array and manipulate

Or as a text file using np.save [ will take longer ]

```<code>np.save('matrix.txt', np_array)
</code>```

Working Code:

```<code>import imageio
import numpy as np
im = imageio.imread("9v9zU.png")
matrice_pixels=open("matric.txt","wb")
nx,ny = im.shape
for i in range(nx):
    line=""
    for j in range(ny):
        line+=repr(im[i][j])
    matrice_pixels.write(line+'\n')

matrice_pixels.close()

#Save as Binary data
np.save('matrix1.npy', im)

#Save as Human readable data
np.savetxt('matrix1.txt', im)
</code>```

Alternately, you may want to look into off the shelf libraries that will do what you are intending to do.
For e.g. This SO link discusses how to remove section of the picture based upon its color using PIL library.

Also , in future, please DO NOT post a picture of your code. Copy/pase to SO window so that we can copy and modify. In this case I had write everything down line by line to test(thankfully code was not that long).

ContentLicense: CC BY-SA 3.0

Title: Python error : index out of bounds

Body:
I was curious about image processing with python, so I found this great library imageio,
I tried to manipulate the pixels of a picture and save them in a new file,
but i had some problems with the loops
this is what the code looks like
enter image description here
and this the error that i Got !
IndexError: index 3507 is out of bounds for axis 0 with size 3507
the code :

 # -*- coding: iso-8859-1 -*-
    import imageio
    import numpy as np
    im = imageio.imread("JAFFRE009a.png")
    taille=im.shape  #taille is a tuple (Width,Height)
    print taille  # (4961,3507)
    matrice_pixels=open("matrice.txt",'w')
    for i in range(taille[1]):
        line=""
        for j in range(taille[0]):
            line+=repr(im[i][j])
        matrice_pixels.write(line+'\n')
    matrice_pixels.close()

Body:
EDIT

We can iterate through each row/column position and save to a file as below.It will take very long time depending upon file size.

Instead of writing your own function, you may want to take advantage of inbuilt binary save (which is more efficient) as

np.save('matrix.py', np_array)

You can load this file as np array and manipulate

Or as a text file using np.save [ will take longer ]

np.save('matrix.txt', np_array)

Working Code:

import imageio
import numpy as np
im = imageio.imread("9v9zU.png")
matrice_pixels=open("matric.txt","wb")
nx,ny = im.shape
for i in range(nx):
    line=""
    for j in range(ny):
        line+=repr(im[i][j])
    matrice_pixels.write(line+'\n')

matrice_pixels.close()

#Save as Binary data
np.save('matrix1.npy', im)

#Save as Human readable data
np.savetxt('matrix1.txt', im)

Alternately, you may want to look into off the shelf libraries that will do what you are intending to do.
For e.g. This SO link discusses how to remove section of the picture based upon its color using PIL library.

Also , in future, please DO NOT post a picture of your code. Copy/pase to SO window so that we can copy and modify. In this case I had write everything down line by line to test(thankfully code was not that long).


问:
Strange Maven Java Could not find or load main class issue
I'm having a strange problem with my Maven build for a project. For some reason it gives me an error when building (Run As -> Java Application in eclipse) that says "Could not find or load main class".

The strange part is, the manifest in the pom is 100% correct.

The process is, Clean, Build, Run As -> Java Application in Eclipse. Works fine.

Run As -> Maven Build... -> clean install. Generates jar that gives main class error.

Back to Eclipse Run As -> Java Application: Now also gives the main class error until cleaned and built again.

Does this sound familiar to anyone??

答: Right-click on your project(s) --> Maven --> Update Project...</p>


问:
Rails rendering wrong partial
I have successfully rendered an ajax request for a show controller(raffle). In the new modal, I am trying to render a partial from another controller(email) but I am getting the new form from the raffle controller. When I look in the terminal, it says that I am rendering the raffles/_new and the emails/_new, however, the email form is not showing. Here is the terminal info:

```<code>Raffle Load (0.2ms)  SELECT  "raffles".* FROM "raffles" WHERE
    "raffles"."id" = $1 LIMIT $2  [["id", 6], ["LIMIT", 1]]
      Rendering raffles/show.js.erb
      Rendered layouts/_errors.html.erb (0.5ms)
      Rendered raffles/_form.html.erb (12.0ms)
      Rendered emails/_new.html.erb (21.5ms)
      Rendered raffles/_show.html.erb (37.5ms)
      Rendered raffles/show.js.erb (51.3ms)
</code>```

My raffle controller's show action has:

```<code>def show
 @raffle = Raffle.find(params[:id])
 @email = Email.new
end
</code>```

My show view:

```<code><%= render '/emails/new', :locals => { :raffle_id => @raffle.id, :email => @email } %>
</code>```

emails/new is a partial which renders 'form' and form is:

```<code><%= form_for email do |f| %>
  <%= f.text_field :email, :placeholder => "Your Email" %>
  <%= f.hidden_field :raffle_id, :value => raffle_id %>
  <%= f.submit "Enter", :class => 'btn-pop' %>
<% end  %>
</code>```

For some reason, my show is showing raffles new form rather than emails new form. Might anybody know what is going on?

答:
I don't think it's the proper way because it doesn't keep my my code separated. But my work-around was to just hard code the email form into the raffle's show view.</p>

```<code><h3><%= @raffle.title %></h3>
<h5><%= @raffle.draw_date %> at <%= @raffle.draw_time %></h5>
<h5><strong>Raffle Closes:</strong> April 25th at 4:00 pm</h5>
<p><%= @raffle.description %></p>
<%= form_for @email, :url => new_email_path do |f| %>
  <%= f.text_field :email, :placeholder => "Your Email" %>
  <%= f.hidden_field :raffle_id, :value => @raffle_id %>
  <%= f.submit "Enter", :class => 'btn-pop' %>
<% end  %>
</code>```

Title: Rails rendering wrong partial

Body:
I have successfully rendered an ajax request for a show controller(raffle). In the new modal, I am trying to render a partial from another controller(email) but I am getting the new form from the raffle controller. When I look in the terminal, it says that I am rendering the raffles/_new and the emails/_new, however, the email form is not showing. Here is the terminal info:

Raffle Load (0.2ms)  SELECT  "raffles".* FROM "raffles" WHERE
    "raffles"."id" = $1 LIMIT $2  [["id", 6], ["LIMIT", 1]]
      Rendering raffles/show.js.erb
      Rendered layouts/_errors.html.erb (0.5ms)
      Rendered raffles/_form.html.erb (12.0ms)
      Rendered emails/_new.html.erb (21.5ms)
      Rendered raffles/_show.html.erb (37.5ms)
      Rendered raffles/show.js.erb (51.3ms)

My raffle controller's show action has:

def show
 @raffle = Raffle.find(params[:id])
 @email = Email.new
end

My show view:

<%= render '/emails/new', :locals => { :raffle_id => @raffle.id, :email => @email } %>

emails/new is a partial which renders 'form' and form is:

<%= form_for email do |f| %>
  <%= f.text_field :email, :placeholder => "Your Email" %>
  <%= f.hidden_field :raffle_id, :value => raffle_id %>
  <%= f.submit "Enter", :class => 'btn-pop' %>
<% end  %>

For some reason, my show is showing raffles new form rather than emails new form. Might anybody know what is going on?

Body:
I don't think it's the proper way because it doesn't keep my my code separated. But my work-around was to just hard code the email form into the raffle's show view.

<h3><%= @raffle.title %></h3>
<h5><%= @raffle.draw_date %> at <%= @raffle.draw_time %></h5>
<h5><strong>Raffle Closes:</strong> April 25th at 4:00 pm</h5>
<p><%= @raffle.description %></p>
<%= form_for @email, :url => new_email_path do |f| %>
  <%= f.text_field :email, :placeholder => "Your Email" %>
  <%= f.hidden_field :raffle_id, :value => @raffle_id %>
  <%= f.submit "Enter", :class => 'btn-pop' %>
<% end  %>


问:
Strongly-Typed Configuration in .NET Core ignores JsonProperty attribute
I've been playing with strongly-typed configuration in .NET Core and I've found some weird behavior.

POCO

```<code>public class ModuleConfiguration
{
    [JsonProperty("menu")]
    public List<MenuItem> MenuItems { get; set; }
}
</code>```

Settings.json

```<code>{
  "moduleConfiguration": {
    "menu": [
      {
        "id": 1,
        "name": "test"
      }
    ]
  }
}
</code>```

When I load the configuration:

```<code>var builder = new ConfigurationBuilder().AddJsonFile(path);
var config = builder.Build().GetSection("moduleConfiguration").Get<T>();
</code>```

the MenuItems collection is null, but if I change "menu" to "menuItems" (in settings.json), the collection is populated correctly.

Does it mean that JsonProperty attribute is being ignored?

答:
That's not how Microsoft.Extensions.Configuration (and Microsoft.Extensions.Configuration.Json in particular) works. It doesn't use JSON.NET to deserialize the configuration due to the fact that configuration settings can come from different sources, for example xml files, environment variable or command line parameters.

All of these are stored in a dictionary and queried.

For example if you want to access moduleConfiguration.menu via configuration you have to do Configuration["moduleConfiguration:menu"] (note that colon : is used as separator for child objects).

For the reasons named above, annotating the property via [JsonProperty("menu")] won't do anything, because JSON.NET isn't involved in the process and the Attributes are just meta data and do not do anything by themselves.

Also when you observe the source code on GitHub, you will see that it uses the JsonReader and a visitor pattern to populate the dictionary.

That being said: the property in C# and the properties in json (or xml or commandline parameters) must exactly (case insensitive).

ContentLicense: CC BY-SA 4.0

Body:
I've been playing with strongly-typed configuration in .NET Core and I've found some weird behavior.

POCO

public class ModuleConfiguration
{
    [JsonProperty("menu")]
    public List<MenuItem> MenuItems { get; set; }
}

Settings.json

{
  "moduleConfiguration": {
    "menu": [
      {
        "id": 1,
        "name": "test"
      }
    ]
  }
}

When I load the configuration:

var builder = new ConfigurationBuilder().AddJsonFile(path);
var config = builder.Build().GetSection("moduleConfiguration").Get<T>();

the MenuItems collection is null, but if I change "menu" to "menuItems" (in settings.json), the collection is populated correctly.

Does it mean that JsonProperty attribute is being ignored?


问:
How do I create a new project collection with the existing empty database using power shell script?
I have the sample script below to create a project collection (which is working fine):

```<code># Load client OM assembly.
[Reflection.Assembly]::LoadFile("C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\TestAgent\Microsoft.TeamFoundation.Client.dll");
[Reflection.Assembly]::LoadFile("C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\TestAgent\Microsoft.TeamFoundation.Common.dll");
[Reflection.Assembly]::LoadFile("C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\TestAgent\Microsoft.VisualStudio.Services.Client.dll");
[Reflection.Assembly]::LoadFile("C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\TestAgent\Microsoft.VisualStudio.Services.Common.dll");

$instanceBaseUrl = "http://TFSserver:8080/tfs/";
$tfsServer = new-object Microsoft.TeamFoundation.Client.TfsConfigurationServer $instanceBaseUrl;

$tpcSvc = $tfsServer.GetService([Microsoft.TeamFoundation.Framework.Client.ITeamProjectCollectionService]);
$job = $tpcSvc.QueueCreateCollection(
    "SampleMyCollectionNameTest_1215",      # collection name.
    "",                  # description.
    $false,              # don't make this the default collection.
    "~/SampleMyCollectionNameTest_1215/",   # virtual directory.
    "Started",           # State after creation.
    $null,               # no tokens.
    "Server=SLQ\Instance;Integrated Security=SSPI;",       # The SQL instance to create the collection on. Specify SERVER\INSTANCE if not using default instance
    $null,               # null because the collection database doesn't already exist.
    $null)               # null because the collection database doesn't already exist.

$collection = $tpcSvc.WaitForCollectionServicingToComplete($job)
</code>```

How do I create a new project collection with the existing empty database by using power shell script?

答:
Below is the script to create a team project collection on remote by using existing empty database</p>

```<code># Load client OM assembly.
[Reflection.Assembly]::Load("Microsoft.TeamFoundation.Client, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");

$instanceBaseUrl = "http://<tfsservername>:8080/tfs/";
$tfsServer = new-object Microsoft.TeamFoundation.Client.TfsConfigurationServer $instanceBaseUrl;

$collectionName = "<CollectionName>"
$sqlConnectionString = "Server=<SQLservername>;Integrated Security=SSPI;"

$servicingTokens = New-Object 'System.Collections.Generic.Dictionary[String,String]'
$servicingTokens.Add("SharePointAction","None")
$servicingTokens.Add("ReportingAction","None")

$databaseCategoryConnectionStrings = New-Object 'System.Collections.Generic.Dictionary[String,String]'
$databaseCategoryConnectionStrings.Add('Framework','Data Source=SQLservername;Initial Catalog=<Existing Empty Database Name>;Integrated Security=True;')

$defaultConnectionString = "Data Source=SQLservername;Initial Catalog=<Existing Empty Database Name>;Integrated Security=True;"

$tpcSvc = $tfsServer.GetService([Microsoft.TeamFoundation.Framework.Client.ITeamProjectCollectionService]);
$job = $tpcSvc.QueueCreateCollection(
    $collectionName,      # collection name.
    "",                  # description.
    $false,              # don't make this the default collection.
    "~/$collectionName/",   # virtual directory.
    "Started",           # State after creation.
    $servicingTokens,               # no SP, no reporting.
    $sqlConnectionString,       # The SQL instance to create the collection on. Specify SERVER\INSTANCE if not using default instance
    $defaultConnectionString,   # defaultConnectionString.
        $databaseCategoryConnectionStrings)               # databaseCategoryConnectionStrings

$collection = $tpcSvc.WaitForCollectionServicingToComplete($job)
</code>```

Body:
I have the sample script below to create a project collection (which is working fine):

# Load client OM assembly.
[Reflection.Assembly]::LoadFile("C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\TestAgent\Microsoft.TeamFoundation.Client.dll");
[Reflection.Assembly]::LoadFile("C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\TestAgent\Microsoft.TeamFoundation.Common.dll");
[Reflection.Assembly]::LoadFile("C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\TestAgent\Microsoft.VisualStudio.Services.Client.dll");
[Reflection.Assembly]::LoadFile("C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\TestAgent\Microsoft.VisualStudio.Services.Common.dll");

$instanceBaseUrl = "http://TFSserver:8080/tfs/";
$tfsServer = new-object Microsoft.TeamFoundation.Client.TfsConfigurationServer $instanceBaseUrl;

$tpcSvc = $tfsServer.GetService([Microsoft.TeamFoundation.Framework.Client.ITeamProjectCollectionService]);
$job = $tpcSvc.QueueCreateCollection(
    "SampleMyCollectionNameTest_1215",      # collection name.
    "",                  # description.
    $false,              # don't make this the default collection.
    "~/SampleMyCollectionNameTest_1215/",   # virtual directory.
    "Started",           # State after creation.
    $null,               # no tokens.
    "Server=SLQ\Instance;Integrated Security=SSPI;",       # The SQL instance to create the collection on. Specify SERVER\INSTANCE if not using default instance
    $null,               # null because the collection database doesn't already exist.
    $null)               # null because the collection database doesn't already exist.

$collection = $tpcSvc.WaitForCollectionServicingToComplete($job)

How do I create a new project collection with the existing empty database by using power shell script?

Body:
Below is the script to create a team project collection on remote by using existing empty database

# Load client OM assembly.
[Reflection.Assembly]::Load("Microsoft.TeamFoundation.Client, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");

$instanceBaseUrl = "http://<tfsservername>:8080/tfs/";
$tfsServer = new-object Microsoft.TeamFoundation.Client.TfsConfigurationServer $instanceBaseUrl;

$collectionName = "<CollectionName>"
$sqlConnectionString = "Server=<SQLservername>;Integrated Security=SSPI;"

$servicingTokens = New-Object 'System.Collections.Generic.Dictionary[String,String]'
$servicingTokens.Add("SharePointAction","None")
$servicingTokens.Add("ReportingAction","None")

$databaseCategoryConnectionStrings = New-Object 'System.Collections.Generic.Dictionary[String,String]'
$databaseCategoryConnectionStrings.Add('Framework','Data Source=SQLservername;Initial Catalog=<Existing Empty Database Name>;Integrated Security=True;')

$defaultConnectionString = "Data Source=SQLservername;Initial Catalog=<Existing Empty Database Name>;Integrated Security=True;"

$tpcSvc = $tfsServer.GetService([Microsoft.TeamFoundation.Framework.Client.ITeamProjectCollectionService]);
$job = $tpcSvc.QueueCreateCollection(
    $collectionName,      # collection name.
    "",                  # description.
    $false,              # don't make this the default collection.
    "~/$collectionName/",   # virtual directory.
    "Started",           # State after creation.
    $servicingTokens,               # no SP, no reporting.
    $sqlConnectionString,       # The SQL instance to create the collection on. Specify SERVER\INSTANCE if not using default instance
    $defaultConnectionString,   # defaultConnectionString.
        $databaseCategoryConnectionStrings)               # databaseCategoryConnectionStrings

$collection = $tpcSvc.WaitForCollectionServicingToComplete($job)


问:
Is there any viable alternative of MiniProfiler for .NET Core?
In older ASP.NET projects I used to include MiniProfiler, which displayed a neat table of execution times of measured methods. However, it does not work with .NET Core. Is there a viable alternative?

I know about Application Insights in Visual Studio, or dotTrace and dotMemory from JetBrains. However, I do not need to measure memory leaks, performance, etc. I really just need to annotate or inject pieces of code into critical controller and business layer methods, which are calling a 3rd party API and measure, how long did individual parts of code execute.

答: There is a profiling/self-profiling API in dotTrace, it is compatible with .NET Core and could meet your requirements: https://www.jetbrains.com/help/profiler/2016.3/Profiling_Guidelines__Advanced_Profiling_Using_dotTrace_API.html</p>


问:
Object oriented design in javascript and 'this' pointer
I am creating a object in javascript like this

```<code>function myobject() {
   this.myvar1 = 0;
   this.myvar2 = 0;
}

myobject.prototype.a = function(){
    this.myvar1 +=1;
    $('#button').click(function () {  // 'this' is undefined
        alert(this.myvar1)
     })
}

var mything = new myobject();
mything.a()
</code>```

What is the proper way to pass the this pointer to an anonymous function?

答:
To pass this to an inner function, "save" it to another variable.

```<code>myobject.prototype.a = function() {
    var self = this;
    self.myvar1 += 1;

    $('#button').click(function () {
         alert(self.myvar1);
    });
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am creating a object in javascript like this

function myobject() {
   this.myvar1 = 0;
   this.myvar2 = 0;
}

myobject.prototype.a = function(){
    this.myvar1 +=1;
    $('#button').click(function () {  // 'this' is undefined
        alert(this.myvar1)
     })
}

var mything = new myobject();
mything.a()

What is the proper way to pass the this pointer to an anonymous function?

Body:
To pass this to an inner function, "save" it to another variable.

myobject.prototype.a = function() {
    var self = this;
    self.myvar1 += 1;

    $('#button').click(function () {
         alert(self.myvar1);
    });
}


问:
JavaScript variable empty after call of getJSON()
I'm having this issue with importing data from a JSON file. I use the .getJSON function to get the data which means to work according to the console log, but once I move out of the getJSON sub function the array in data2 disappears. I've narrowed it down to this section here:

```<code>function prepData() {
    data2 = [];

    $.getJSON('http://localhost/data').done(function(json) {
        data2 =json;
        console.log(data2);
    });

    console.log(data2);
    SelectedData = data2;
    return SelectedData;
};
</code>```

What might the issue be here?

答: $.getJSON is asynchronous so it will executed parallel to your next console statement.</p>

Body:
I'm having this issue with importing data from a JSON file. I use the .getJSON function to get the data which means to work according to the console log, but once I move out of the getJSON sub function the array in data2 disappears. I've narrowed it down to this section here:

function prepData() {
    data2 = [];

    $.getJSON('http://localhost/data').done(function(json) {
        data2 =json;
        console.log(data2);
    });

    console.log(data2);
    SelectedData = data2;
    return SelectedData;
};

What might the issue be here?


问:
TypeScript enum to object array
I have an enum defined this way:

```<code>export enum GoalProgressMeasurements {
    Percentage = 1,
    Numeric_Target = 2,
    Completed_Tasks = 3,
    Average_Milestone_Progress = 4,
    Not_Measured = 5
}
</code>```

However, I'd like it to be represented as an object array/list from our API like below:

```<code>[{id: 1, name: 'Percentage'},
 {id: 2, name: 'Numeric Target'},
 {id: 3, name: 'Completed Tasks'},
 {id: 4, name: 'Average Milestone Progress'},
 {id: 5, name: 'Not Measured'}]
</code>```

Is there are easy and native way to do this or do I have to build a function that casts the enum to both an int and a string, and build the objects into an array?

答:
Enums are real objects that exist at runtime. So you are able to reverse the mapping doing something like this:

```<code>let value = GoalProgressMeasurements.Not_Measured;
console.log(GoalProgressMeasurements[value]);
// => Not_Measured
</code>```

Based on that you can use the following code:

```<code>export enum GoalProgressMeasurements {
    Percentage = 1,
    Numeric_Target = 2,
    Completed_Tasks = 3,
    Average_Milestone_Progress = 4,
    Not_Measured = 5
}

let map: {id: number; name: string}[] = [];

for(var n in GoalProgressMeasurements) {
    if (typeof GoalProgressMeasurements[n] === 'number') {
        map.push({id: <any>GoalProgressMeasurements[n], name: n});
    }
}

console.log(map);
</code>```

Reference: https://www.typescriptlang.org/docs/handbook/enums.html

Title: TypeScript enum to object array

Body:
I have an enum defined this way:

export enum GoalProgressMeasurements {
    Percentage = 1,
    Numeric_Target = 2,
    Completed_Tasks = 3,
    Average_Milestone_Progress = 4,
    Not_Measured = 5
}

However, I'd like it to be represented as an object array/list from our API like below:

[{id: 1, name: 'Percentage'},
 {id: 2, name: 'Numeric Target'},
 {id: 3, name: 'Completed Tasks'},
 {id: 4, name: 'Average Milestone Progress'},
 {id: 5, name: 'Not Measured'}]

Is there are easy and native way to do this or do I have to build a function that casts the enum to both an int and a string, and build the objects into an array?

Body:
Enums are real objects that exist at runtime. So you are able to reverse the mapping doing something like this:

let value = GoalProgressMeasurements.Not_Measured;
console.log(GoalProgressMeasurements[value]);
// => Not_Measured

Based on that you can use the following code:

export enum GoalProgressMeasurements {
    Percentage = 1,
    Numeric_Target = 2,
    Completed_Tasks = 3,
    Average_Milestone_Progress = 4,
    Not_Measured = 5
}

let map: {id: number; name: string}[] = [];

for(var n in GoalProgressMeasurements) {
    if (typeof GoalProgressMeasurements[n] === 'number') {
        map.push({id: <any>GoalProgressMeasurements[n], name: n});
    }
}

console.log(map);

Reference: https://www.typescriptlang.org/docs/handbook/enums.html


问:
trouble with code when converting PHP code from MySql to Sqlsrv
I have moved from MySql to Sqlsrv and was updating my PHP.  I'm not that versed in PHP and definitely not Sqlsrv, but have been using the PHP: SQLSRV Manual.
Here is my PHP code:

```<code><?php
include '../includes/dbconfig.php';
session_start();

if($_SERVER["REQUEST_METHOD"] == "POST") {

// username and password sent from Form
$myusername=$_POST['username'];
$mypassword=$_POST['password'];
//extract($_POST);

$sql="SELECT username FROM dbname WHERE username='$myusername' and userpassword='$mypassword'";
$result=sqlsrv_query($conn,$sql) or die(print_r(sqlsrv_errors(),true));

if ($result) {
   $rows = sqlsrv_has_rows( $result );
   if ($rows === true)
        echo "There are rows. <br />";
    {
        $_SESSION['login_user']=$myusername;
        header("Location: orderform.php");
    }
   else
    { $error="Your Login Name or Password is invalid"; }
}
}
?>
</code>```

The code that is causing the problem is:

```<code>{
$_SESSION['login_user']=$myusername;
header("Location: orderform.php");
}
</code>```

If I comment those lines out, the login form comes up and if I put a correct username and password, I get the "There are rows" comment.  If not, I get "Your Login Name or Password is invalid".  Once I put those lines back in, the login screen will not even come up.  I don't get an error or anything.  I've been working on this for 2 days...can someone help me out?

答:
I think you have wrong bracket structure:

```<code>   if ($rows === true)
        echo "There are rows. <br />";
    {
        $_SESSION['login_user']=$myusername;
        header("Location: orderform.php");
    }
   else
    { $error="Your Login Name or Password is invalid"; }
</code>```

Should be:

```<code>   if ($rows === true)
    {
        echo "There are rows. <br />";
        $_SESSION['login_user']=$myusername;
        header("Location: orderform.php");
    }
   else
    { $error="Your Login Name or Password is invalid"; }
</code>```

Body:
I have moved from MySql to Sqlsrv and was updating my PHP.  I'm not that versed in PHP and definitely not Sqlsrv, but have been using the PHP: SQLSRV Manual.
Here is my PHP code:

<?php
include '../includes/dbconfig.php';
session_start();

if($_SERVER["REQUEST_METHOD"] == "POST") {

// username and password sent from Form
$myusername=$_POST['username'];
$mypassword=$_POST['password'];
//extract($_POST);

$sql="SELECT username FROM dbname WHERE username='$myusername' and userpassword='$mypassword'";
$result=sqlsrv_query($conn,$sql) or die(print_r(sqlsrv_errors(),true));

if ($result) {
   $rows = sqlsrv_has_rows( $result );
   if ($rows === true)
        echo "There are rows.
";
    {
        $_SESSION['login_user']=$myusername;
        header("Location: orderform.php");
    }
   else
    { $error="Your Login Name or Password is invalid"; }
}
}
?>

The code that is causing the problem is:

{
$_SESSION['login_user']=$myusername;
header("Location: orderform.php");
}

If I comment those lines out, the login form comes up and if I put a correct username and password, I get the "There are rows" comment.  If not, I get "Your Login Name or Password is invalid".  Once I put those lines back in, the login screen will not even come up.  I don't get an error or anything.  I've been working on this for 2 days...can someone help me out?

Body:
I think you have wrong bracket structure:

   if ($rows === true)
        echo "There are rows. <br />";
    {
        $_SESSION['login_user']=$myusername;
        header("Location: orderform.php");
    }
   else
    { $error="Your Login Name or Password is invalid"; }

Should be:

   if ($rows === true)
    {
        echo "There are rows. <br />";
        $_SESSION['login_user']=$myusername;
        header("Location: orderform.php");
    }
   else
    { $error="Your Login Name or Password is invalid"; }


问:
SQL Server: How to call a user-defined function (UDF) on linked server?
i'm trying to call a User-Defined Function (UDF) on a linked server:

```<code>CREATE FUNCTION [dbo].[UserGroupMembershipNames](@UserGUID uniqueidentifier)
RETURNS VARCHAR(8000)
AS
BEGIN
    RETURN ASILIVE.ReportManager.dbo.UserGroupMembershipNames(@UserGUID)
END
</code>```

This doesn't work, as documented in PRB: User-Defined Function Call in Four-Part Linked Server Query Fails with Error Message 170. They also give a workaround:

For example, instead of the following query

```<code>Select * from Linked_Server.northwind.dbo.square_value(10)
</code>```

run a query with the Openquery function:

```<code>Select * from Openquery(Linked_Server,'select northwind.dbo.square_ value(10)')
</code>```

If the user-defined function takes variable or scalar parameters, you can use the sp_executesql stored procedure to avoid this behavior. For example:

```<code>exec Linked_Server.northwind.dbo.sp_executesql N'SELECT northwind.dbo.square_value(@input)',N'@input int',@input=10
</code>```

How would i apply this workaround to my situation, and the situation of this guy?

In other words:

How to call a UDF on a linked server?

答:
Not the prettiest solution but it works if you can work around passing parameters into the linked-server function</p>

```<code>CREATE FUNCTION fn_LocalFunction
(
   @SomeParamOfLinkedFunction VARCHAR(100)
)
RETURNS TABLE
AS
RETURN
    SELECT SomeField
    FROM OPENQUERY([YOURSERVER], 'SELECT * FROM [SOMEDB].dbo.fn_SomeRemoteFunction(NULL)') tst
    WHERE SomeCondition = @SomeParamOfLinkedFunction
</code>```

Body:
i'm trying to call a User-Defined Function (UDF) on a linked server:

CREATE FUNCTION [dbo].[UserGroupMembershipNames](@UserGUID uniqueidentifier)
RETURNS VARCHAR(8000)
AS
BEGIN
    RETURN ASILIVE.ReportManager.dbo.UserGroupMembershipNames(@UserGUID)
END

This doesn't work, as documented in PRB: User-Defined Function Call in Four-Part Linked Server Query Fails with Error Message 170. They also give a workaround:

For example, instead of the following query

Select * from Linked_Server.northwind.dbo.square_value(10)

run a query with the Openquery function:

Select * from Openquery(Linked_Server,'select northwind.dbo.square_ value(10)')

If the user-defined function takes variable or scalar parameters, you can use the sp_executesql stored procedure to avoid this behavior. For example:

exec Linked_Server.northwind.dbo.sp_executesql N'SELECT northwind.dbo.square_value(@input)',N'@input int',@input=10

How would i apply this workaround to my situation, and the situation of this guy?

In other words:

How to call a UDF on a linked server?

Body:
Not the prettiest solution but it works if you can work around passing parameters into the linked-server function

CREATE FUNCTION fn_LocalFunction
(
   @SomeParamOfLinkedFunction VARCHAR(100)
)
RETURNS TABLE
AS
RETURN
    SELECT SomeField
    FROM OPENQUERY([YOURSERVER], 'SELECT * FROM [SOMEDB].dbo.fn_SomeRemoteFunction(NULL)') tst
    WHERE SomeCondition = @SomeParamOfLinkedFunction


问:
Using seq_along and lapply to process multiple dataframes (CAPM)
I have 48 dataframes and I wish to calculate a linear regression for each of the stocks in each of the dataframes (the CAPM). Each dataframe contains the same amount of stocks which is around 470, the S&P 500 and has 36 months worth of data. Originally I had one large dataframe but I have successfully managed to split the data into the 48 dataframes (this might not have been the smartest move but it is the way I solved the problem).

When I run the following code, it works fine. Noting that I have hard coded in Block 1.

```<code>  beta_results <- lapply(symbols, function(x) {
  temp <-  as.data.frame(Block1)
  input <- as.formula(paste("temp$",x, "~ temp$SP500" ))
  capm <- lm(input)
  coefficients(capm)
 })
</code>```

Now rather than change the coding for each of the 48 blocks (ie Block1  to Block2 etc), I attempted the following, which in hindsight is complete rubbish. What I need is a way to increment the i from 1 to 48. I had tried to put all the dataframes in list, but given the way I have regression working I would be processing two lists and that was beyond me.

```<code>beta_results <- lapply(seq_along(symbols), function(i,x) {
 temp <-  as.data.frame(paste0("Block",i))
 input <- as.formula(paste("temp$",x, "~ temp$SP500" ))
 capm <- lm(input)
coefficients(capm)
})
</code>```

Code for some example dataframes etc are:

```<code> symbols <- c("A", "AAPL", "BRKB")
</code>```

Block1 to BlockN would take the form of

```<code>             A      AAPL  BRKB    SP500
2016-04-29 -0.139  0.111  0.122    0.150
2016-05-31  0.071  0.095  0.330    0.200
2016-06-30 -0.042 -0.009  0.230    0.150
2016-07-29  0.090  0.060  0.200    0.100
2016-08-31  0.023  0.013  0.005    0.050
2016-09-30  0.065  0.088  0.002    0.100
</code>```

答:
Consider a nested lapply where outer loop iterates through a list of dataframes and inner loop through each symbol. The result is a 48-member list, each containing 470 sets of beta coefficents.

Also, as an aside, it is preferred to use lists of many similiarly structured objects especially to run same operations and avoid flooding your global environment (manage 1 list vs 48 dataframes):

```<code># LIST OF DATA FRAMES FROM ALL GLOBAL VARIABLES CONTAINING "Block"
dfList <- mget(ls(pattern="Block"))

# NESTED LAPPLY
results_list <- lapply(dfList, function(df) {

  beta_results <- lapply(symbols, function(x) {
     input <- reformulate(quote(SP500), response=x)
     capm <- lm(input, data=df)
     coefficients(capm)
  })

})
</code>```

Body:
I have 48 dataframes and I wish to calculate a linear regression for each of the stocks in each of the dataframes (the CAPM). Each dataframe contains the same amount of stocks which is around 470, the S&P 500 and has 36 months worth of data. Originally I had one large dataframe but I have successfully managed to split the data into the 48 dataframes (this might not have been the smartest move but it is the way I solved the problem).

When I run the following code, it works fine. Noting that I have hard coded in Block 1.

  beta_results <- lapply(symbols, function(x) {
  temp <-  as.data.frame(Block1)
  input <- as.formula(paste("temp$",x, "~ temp$SP500" ))
  capm <- lm(input)
  coefficients(capm)
 })

Now rather than change the coding for each of the 48 blocks (ie Block1  to Block2 etc), I attempted the following, which in hindsight is complete rubbish. What I need is a way to increment the i from 1 to 48. I had tried to put all the dataframes in list, but given the way I have regression working I would be processing two lists and that was beyond me.

beta_results <- lapply(seq_along(symbols), function(i,x) {
 temp <-  as.data.frame(paste0("Block",i))
 input <- as.formula(paste("temp$",x, "~ temp$SP500" ))
 capm <- lm(input)
coefficients(capm)
})

Code for some example dataframes etc are:

 symbols <- c("A", "AAPL", "BRKB")

Block1 to BlockN would take the form of

             A      AAPL  BRKB    SP500
2016-04-29 -0.139  0.111  0.122    0.150
2016-05-31  0.071  0.095  0.330    0.200
2016-06-30 -0.042 -0.009  0.230    0.150
2016-07-29  0.090  0.060  0.200    0.100
2016-08-31  0.023  0.013  0.005    0.050
2016-09-30  0.065  0.088  0.002    0.100

Body:
Consider a nested lapply where outer loop iterates through a list of dataframes and inner loop through each symbol. The result is a 48-member list, each containing 470 sets of beta coefficents.

Also, as an aside, it is preferred to use lists of many similiarly structured objects especially to run same operations and avoid flooding your global environment (manage 1 list vs 48 dataframes):

# LIST OF DATA FRAMES FROM ALL GLOBAL VARIABLES CONTAINING "Block"
dfList <- mget(ls(pattern="Block"))

# NESTED LAPPLY
results_list <- lapply(dfList, function(df) {

  beta_results <- lapply(symbols, function(x) {
     input <- reformulate(quote(SP500), response=x)
     capm <- lm(input, data=df)
     coefficients(capm)
  })

})


问:
didReceiveMemoryWarning: what type of memory?
I have a base cordova app, with some objective-c code around cordova's framework. Sometimes I've didReceiveMemoryWarning notification, but I don't understand if the problem is the javascript inside the UIWebView or other.
The documentation says:

Your app never calls this method directly. Instead, this method is called when the system determines that the amount of available memory is low.

But my question is: what type of memory?
RAM? Heap allocations? Something else?

答: The memory issue represents to RAM, generally we are creating the app using different objects, and these objects take some memory to process the required task. If we aware about them we can easily manage the memory but sometimes  for beginners it is not managable to debug the memory, and didReceiveMemoryWarning occured. We can diagnose or debug this issue by instruments.


问:
How can I create this following style with CSS3?
I would like to get this style in CSS3:

CSS3 layout

For now, I have the simplest thing, the middle square with the following code:

HTML (pretty irrelevant, but I guess the tag does not need to be a div tag):

```<code><div id="divBorder">
</div>
</code>```

CSS:

```<code>#divBorder{
    border-style: solid;
    border-width: 1px;
    position: absolute;
    width: 300px;
    height: 300px;
    z-index: 15;
    top: 50%;
    left: 50%;
    margin: -110px 0 0 -160px;
}
</code>```

So, I just have basically centered the middle square in the center of the screen and that's all, I can't find a way to do the other two half squares on both sides of the full one.

I hope you can help me, thank you so much in advance!

答:
You can achieve the desired layout with the following markup, using flexbox.

body {
  margin: 0;
}

main {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

header {
  flex: 1;
  background-color: mediumspringgreen;
}

div {
  flex: 4;
  display: flex;
  background-color: darkviolet;
}

section {
  flex: 1;
}

section:nth-child(even) {
  flex: 2;
  background-color: darkorchid;
}

footer {
  flex: 1;
  background-color: deeppink;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><main>
  <header></header>
  <div>
    <section></section>
    <section></section>
    <section></section>
  </div>
  <footer></footer>
</main></code>```

Body:
I would like to get this style in CSS3:

CSS3 layout

For now, I have the simplest thing, the middle square with the following code:

HTML (pretty irrelevant, but I guess the tag does not need to be a div tag):

CSS:

#divBorder{
    border-style: solid;
    border-width: 1px;
    position: absolute;
    width: 300px;
    height: 300px;
    z-index: 15;
    top: 50%;
    left: 50%;
    margin: -110px 0 0 -160px;
}

So, I just have basically centered the middle square in the center of the screen and that's all, I can't find a way to do the other two half squares on both sides of the full one.

I hope you can help me, thank you so much in advance!

Body:
You can achieve the desired layout with the following markup, using flexbox.

body {
  margin: 0;
}

main {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

header {
  flex: 1;
  background-color: mediumspringgreen;
}

div {
  flex: 4;
  display: flex;
  background-color: darkviolet;
}

section {
  flex: 1;
}

section:nth-child(even) {
  flex: 2;
  background-color: darkorchid;
}

footer {
  flex: 1;
  background-color: deeppink;
}

<main>
  <header></header>
  <div>
    <section></section>
    <section></section>
    <section></section>
  </div>
  <footer></footer>
</main>


问:
Selecting column data from SQL ordered inside while loop
I have a database like this

```<code>|| ID    -     COL1   - COL2||
|| 1     -    row1A  -  1  ||
|| 2     -    row1A  -  1  ||
|| 3     -    row1A  -  2  ||
|| 4     -    row1B  -  2  ||
|| 5     -    row1A  -  3  ||
|| 6     -    row1B  -  3  ||
</code>```

i want to ECHO these data like this

```<code>$query = "SELECT * FROM DB WHERE COL1 = 'row1A'";
while($row = $stmt->fetch()){
    $col = $row['COL1'];
    echo "
     <div>Set1: $col</div> // = row1A, row1A  as where COL2 = 1
     <div>Set2: $col</div> // = row1A as where COL2 = 2
     <div>Set3: $col</div> // = row1A as where COL2 = 3
    ";
}
</code>```

I'm using this with a relation between 3 tables so each row1A will has its own name in different table, But right now i want to know how can i call the database ordered by COL2

For each SetN gets the value of COL1 WHERE COL2 = N

答:
Use ORDER BY in sql. Please check following code.

```<code>$query = "SELECT * FROM DB WHERE COL1 = 'row1A' ORDER BY COL2 ASC";
</code>```

Body:
I have a database like this

|| ID    -     COL1   - COL2||
|| 1     -    row1A  -  1  ||
|| 2     -    row1A  -  1  ||
|| 3     -    row1A  -  2  ||
|| 4     -    row1B  -  2  ||
|| 5     -    row1A  -  3  ||
|| 6     -    row1B  -  3  ||

i want to ECHO these data like this

$query = "SELECT * FROM DB WHERE COL1 = 'row1A'";
while($row = $stmt->fetch()){
    $col = $row['COL1'];
    echo "

Set1: $col
 // = row1A, row1A  as where COL2 = 1

Set2: $col
 // = row1A as where COL2 = 2

Set3: $col
 // = row1A as where COL2 = 3
    ";
}

I'm using this with a relation between 3 tables so each row1A will has its own name in different table, But right now i want to know how can i call the database ordered by COL2

For each SetN gets the value of COL1 WHERE COL2 = N

Body:
Use ORDER BY in sql. Please check following code.

$query = "SELECT * FROM DB WHERE COL1 = 'row1A' ORDER BY COL2 ASC";


问:
In rails, whether to use form helpers or not to?
In rails, is it recommended to use form helpers? Internally, everything boils down to plain html then why not write the html directly? Performance will obviously be better in writing direct html than using helpers. Is using form helpers like a convention or something that rails developers must follow?</p>

答:
The form helpers are especially useful to let rails handle creating forms based on your model. To cite the example of the API documentation:

The following code

```<code><% form_for :person, @person, :url => { :action => "create" } do |f| %>
  <%= f.text_field :first_name %>
  <%= f.text_field :last_name %>
  <%= submit_tag 'Create' %>
<% end %>
</code>```

generates this html

```<code><form action="/persons/create" method="post">
  <input id="person_first_name" name="person[first_name]" size="30" type="text" />
  <input id="person_last_name" name="person[last_name]" size="30" type="text" />
  <input name="commit" type="submit" value="Create" />
</form>
</code>```

You could write the html by yourself, but by using the form helpers you have to type less and make the form creation less dependent on the rails implementation. You always get a form that writes data into your model when you hit the submit button. If the rails developers ever change the implementation of this, you automatically get the correct html output from your helpers. If you had written the html manually, you would have to update all of it to reflect the changes of the inner workings of rails.

OwnerDisplayName: Chirantan

LastEditorDisplayName: tvanfosson

Body:
The form helpers are especially useful to let rails handle creating forms based on your model. To cite the example of the API documentation:

The following code

<% form_for :person, @person, :url => { :action => "create" } do |f| %>
  <%= f.text_field :first_name %>
  <%= f.text_field :last_name %>
  <%= submit_tag 'Create' %>
<% end %>

generates this html

<form action="/persons/create" method="post">
  <input id="person_first_name" name="person[first_name]" size="30" type="text" />
  <input id="person_last_name" name="person[last_name]" size="30" type="text" />
  <input name="commit" type="submit" value="Create" />
</form>

You could write the html by yourself, but by using the form helpers you have to type less and make the form creation less dependent on the rails implementation. You always get a form that writes data into your model when you hit the submit button. If the rails developers ever change the implementation of this, you automatically get the correct html output from your helpers. If you had written the html manually, you would have to update all of it to reflect the changes of the inner workings of rails.

OwnerDisplayName: Sebastian Dietz


问:
hardware_id on Branch.io for Android appears to _not_ be ADID, what is it?
On a branch.io webhook from android devices I am getting a value for hardware_id that appears to be a 64 bit number rather than a UUID format ADID as I understand they should be formatted.  Documentation indicates it is Android ID (adid?)

```<code>hardware_id: 'IDFA' (iOS) | 'Android ID' (Android),
</code>```

But I appear to be getting hardware_id from android os platform events on the webhook that are 64 bit numbers rather than uuids and that don't match android id when retrieved directly from the operating system in my app.  Am I misunderstanding what this field is?  Have others used this field successfully on a webhook to correlate user activity or is there a better field in branch.io?

答: It appears that the Android ID is normally the 64bit android device identifier.  Solved this by recording that value elsewhere rather than by trying to adjust or understand what information branch was sending.</p>

Body:
On a branch.io webhook from android devices I am getting a value for hardware_id that appears to be a 64 bit number rather than a UUID format ADID as I understand they should be formatted.  Documentation indicates it is Android ID (adid?)

hardware_id: 'IDFA' (iOS) | 'Android ID' (Android),

But I appear to be getting hardware_id from android os platform events on the webhook that are 64 bit numbers rather than uuids and that don't match android id when retrieved directly from the operating system in my app.  Am I misunderstanding what this field is?  Have others used this field successfully on a webhook to correlate user activity or is there a better field in branch.io?


问:
How to fix overlapping objects
I have recently started understanding on how to code in Android Studio and want to set up basic coding. I created 2 number objects and 1 button, 1 plain text object.
Without writing any piece of code, when I click on Run App button on Android Studio and select any Emulator, all the objects stack up on each other. Is there a simple way to fix this?

Following is the text in activity_main.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.myapplication70.MainActivity">

    <EditText
        android:id="@+id/editText3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Result"
        android:inputType="numberDecimal"
        tools:layout_editor_absoluteX="67dp"
        tools:layout_editor_absoluteY="223dp" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="number"
        tools:layout_editor_absoluteX="67dp"
        tools:layout_editor_absoluteY="60dp" />

    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="numberSigned"
        tools:layout_editor_absoluteX="67dp"
        tools:layout_editor_absoluteY="134dp" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        tools:layout_editor_absoluteX="100dp"
        tools:layout_editor_absoluteY="319dp" />

</android.support.constraint.ConstraintLayout>
</code>```

答:
Seeing your layout, you are currently missing constraints. COnstraints are critical for the objects to stay in the same place as they are in the editor on an actual device.

You can add them manually by dragging and dropping to create them, or automatically using "Infer constraints"

Title: How to fix overlapping objects

Body:
I have recently started understanding on how to code in Android Studio and want to set up basic coding. I created 2 number objects and 1 button, 1 plain text object.
Without writing any piece of code, when I click on Run App button on Android Studio and select any Emulator, all the objects stack up on each other. Is there a simple way to fix this?

Following is the text in activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.myapplication70.MainActivity">

    <EditText
        android:id="@+id/editText3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Result"
        android:inputType="numberDecimal"
        tools:layout_editor_absoluteX="67dp"
        tools:layout_editor_absoluteY="223dp" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="number"
        tools:layout_editor_absoluteX="67dp"
        tools:layout_editor_absoluteY="60dp" />

    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="numberSigned"
        tools:layout_editor_absoluteX="67dp"
        tools:layout_editor_absoluteY="134dp" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        tools:layout_editor_absoluteX="100dp"
        tools:layout_editor_absoluteY="319dp" />

</android.support.constraint.ConstraintLayout>


问:
Cannot create instance of Selenium webdriver.Firefox()
I'm running Python 3.6.0 on Windows 7. I have installed Selenium version 3.3.1:

```<code>Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 07:18:10) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import selenium
>>> selenium.__version__
'3.3.1'
</code>```

I also have the geckodriver executable in my Path:

```<code>geckodriver.exe --version
geckodriver 0.15.0
</code>```

I'm following the steps in the official Getting Started guide for Selenium

```<code>>>> from selenium import webdriver
>>> from selenium.webdriver.common.keys import Keys
>>> driver = webdriver.Firefox()
</code>```

However, calling webdriver.Firefox() never returns an instance. It simply hangs there until I manually hit ctrl+c, at which point the following stack trace is printed out:

```<code>>>> driver = webdriver.Firefox()
Traceback (most recent call last):
  File "C:\Python36-32\lib\socket.py", line 586, in readinto
    return self._sock.recv_into(b)
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "c:\dev_env\test\lib\site-packages\selenium\webdriver\firefox\webdriver.py", line 155, in __init__
    keep_alive=True)
  File "c:\dev_env\test\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 92, in __init__
    self.start_session(desired_capabilities, browser_profile)
  File "c:\dev_env\test\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 179, in start_session
    response = self.execute(Command.NEW_SESSION, capabilities)
  File "c:\dev_env\test\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 236, in execute
    response = self.command_executor.execute(driver_command, params)
  File "c:\dev_env\test\lib\site-packages\selenium\webdriver\remote\remote_connection.py", line 415, in execute
    return self._request(command_info[0], url, body=data)
  File "c:\dev_env\test\lib\site-packages\selenium\webdriver\remote\remote_connection.py", line 447, in _request
    resp = self._conn.getresponse()
  File "C:\Python36-32\lib\http\client.py", line 1331, in getresponse
    response.begin()
  File "C:\Python36-32\lib\http\client.py", line 297, in begin
    version, status, reason = self._read_status()
  File "C:\Python36-32\lib\http\client.py", line 258, in _read_status
    line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
  File "C:\Python36-32\lib\socket.py", line 586, in readinto
    return self._sock.recv_into(b)
KeyboardInterrupt
>>>
</code>```

Why am I unable to create the browser object as indicated in the official guide?

答:
I assume you already have geckodriver downloaded. Now all you have to do is :</p>

```<code>System.setProperty("webdriver.gecko.driver", path to geckodriver.exe);
</code>```

Body:
I'm running Python 3.6.0 on Windows 7. I have installed Selenium version 3.3.1:

Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 07:18:10) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import selenium
>>> selenium.__version__
'3.3.1'

I also have the geckodriver executable in my Path:

geckodriver.exe --version
geckodriver 0.15.0

I'm following the steps in the official Getting Started guide for Selenium

>>> from selenium import webdriver
>>> from selenium.webdriver.common.keys import Keys
>>> driver = webdriver.Firefox()

However, calling webdriver.Firefox() never returns an instance. It simply hangs there until I manually hit ctrl+c, at which point the following stack trace is printed out:

>>> driver = webdriver.Firefox()
Traceback (most recent call last):
  File "C:\Python36-32\lib\socket.py", line 586, in readinto
    return self._sock.recv_into(b)
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "c:\dev_env\test\lib\site-packages\selenium\webdriver\firefox\webdriver.py", line 155, in __init__
    keep_alive=True)
  File "c:\dev_env\test\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 92, in __init__
    self.start_session(desired_capabilities, browser_profile)
  File "c:\dev_env\test\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 179, in start_session
    response = self.execute(Command.NEW_SESSION, capabilities)
  File "c:\dev_env\test\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 236, in execute
    response = self.command_executor.execute(driver_command, params)
  File "c:\dev_env\test\lib\site-packages\selenium\webdriver\remote\remote_connection.py", line 415, in execute
    return self._request(command_info[0], url, body=data)
  File "c:\dev_env\test\lib\site-packages\selenium\webdriver\remote\remote_connection.py", line 447, in _request
    resp = self._conn.getresponse()
  File "C:\Python36-32\lib\http\client.py", line 1331, in getresponse
    response.begin()
  File "C:\Python36-32\lib\http\client.py", line 297, in begin
    version, status, reason = self._read_status()
  File "C:\Python36-32\lib\http\client.py", line 258, in _read_status
    line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
  File "C:\Python36-32\lib\socket.py", line 586, in readinto
    return self._sock.recv_into(b)
KeyboardInterrupt
>>>

Why am I unable to create the browser object as indicated in the official guide?

Body:
I assume you already have geckodriver downloaded. Now all you have to do is :

System.setProperty("webdriver.gecko.driver", path to geckodriver.exe);


问:
Ajax call is returning [object Object]
Html

```<code><div>
    <select id="method">
        <option value="get">GET</option>
        <option value="post">POST</option>
        <option value="put">PUT</option>
    </select>
    <input type="button" value="Try it" onclick="sendRequest()" />
    <span id='value1'>(Result)</span>
</div>
</code>```

Jquery

```<code>@section scripts {
    <script>
        // TODO: Replace with the URL of your WebService app
        var serviceUrl = 'http://localhost:99999/api/books';

        function sendRequest() {
            var method = $('#method').val();

            $.ajax({
                type: method,
                url: serviceUrl,
                dataType: 'json',
                success: function (data) {
                    $('#value1').text(data);
                    console.log(data);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    $('#value1').text(jqXHR.responseText || textStatus);
                }
            });
        }
    </script>
</code>```

The success function is showing up with arrays of [object, Object]. The console shows the data for each object, but it is not showing on the page.

For each book, I have to list the Id, Title, and the Author.

```<code>public IHttpActionResult Get()
        {
            IQueryable<BookDTO> books;
            books = from b in db.Books
                    select new BookDTO()
                    {
                        Id = b.Id,
                        Title = b.Title,
                        AuthorName = b.Author.Name
                    };
            return Ok(books);
</code>```

console.log Output

答:
As others noted, the reason you are seeing this is because assigning the data object to a text value. Since the object is not a string, Object.prototype.toString() is invoked which displays the string representation of the object, or "[object Object]".

Place a debugger statement and open your browser's development console / inspector and reload the page. Execution will halt at the location of the statement allowing you to interactively explore the object and figure out which fields are fit for display (e.g. if the data object contained information about a person, you would discover data.name and assign that to the element instead).

```<code>success: function (data) {
    $('#value1').text(data);
    debugger;
    console.log(data);
},
</code>```

Title: Ajax call is returning [object Object]

Body:
Html

    <select id="method">
        <option value="get">GET</option>
        <option value="post">POST</option>
        <option value="put">PUT</option>
    </select>
    <input type="button" value="Try it" onclick="sendRequest()" />
    (Result)

Jquery

@section scripts {

The success function is showing up with arrays of [object, Object]. The console shows the data for each object, but it is not showing on the page.

For each book, I have to list the Id, Title, and the Author.

public IHttpActionResult Get()
        {
            IQueryable<BookDTO> books;
            books = from b in db.Books
                    select new BookDTO()
                    {
                        Id = b.Id,
                        Title = b.Title,
                        AuthorName = b.Author.Name
                    };
            return Ok(books);

console.log Output

Body:
As others noted, the reason you are seeing this is because assigning the data object to a text value. Since the object is not a string, Object.prototype.toString() is invoked which displays the string representation of the object, or "[object Object]".

Place a debugger statement and open your browser's development console / inspector and reload the page. Execution will halt at the location of the statement allowing you to interactively explore the object and figure out which fields are fit for display (e.g. if the data object contained information about a person, you would discover data.name and assign that to the element instead).

success: function (data) {
    $('#value1').text(data);
    debugger;
    console.log(data);
},


问:
Making A UIView like Apple's home screen
I am trying to make a View that acts like Apple's springboard (Where all the apps are) so I can swipe to the right or left and show another set of items. I'm mainly having issues with the constraints and getting all the icons to appear normally across all screen sizes. I'm using just a basic UIView controller to try and accomplish this. What is the best way to use constraints with an array of images like Apple's springboard?

Thanks for your help.

答:
In the storyboard, I have dragged a UIPageViewController and two UIViewController. I have subclassed UIPageViewController to MyPageViewController.

The rest is done by code in MyPageViewController.swift:

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

    // can't be done in storyboard (-_-)
    delegate = self
    datasource = self
    setViewControllers([page1, page2], direction: .forward, animated: false, completion: nil)
}
</code>```

(where page1 and page2 are the two other UIViewController of your storyboard)

In case you wonder how to get page1 (after setting an identifier in storyboard):

```<code>let page1 = UIStoryboard(name: "MyStoryboard", bundle: nil).instantiateViewController(withIdentifier: "page1")
</code>```

Body:
In the storyboard, I have dragged a UIPageViewController and two UIViewController. I have subclassed UIPageViewController to MyPageViewController.

The rest is done by code in MyPageViewController.swift:

override func viewDidLoad() {
    super.viewDidLoad()

    // can't be done in storyboard (-_-)
    delegate = self
    datasource = self
    setViewControllers([page1, page2], direction: .forward, animated: false, completion: nil)
}

(where page1 and page2 are the two other UIViewController of your storyboard)

In case you wonder how to get page1 (after setting an identifier in storyboard):

let page1 = UIStoryboard(name: "MyStoryboard", bundle: nil).instantiateViewController(withIdentifier: "page1")


问:
Eclipse IDE project directory structure help [Java]
I have been learning Java and have had no problem with projects in which multiple .java files were in the same Default Package.
I am now trying to separate code and create folders for images, but everything I have tried has failed.

How do I properly add folders for images and other classes, and properly set the path to it?
All paths should be relative to the project, I know that much ;_;

Here's a link to a picture of my IDE and error message from program output:

http://img262.imageshack.us/img262/8415/directory.png

Thanks!!

答:
First off, your Java code itself should go into a package, not the default package. Next, you may be able to refer to the image file by prepending src/ to your path:

"src/Textures/Crate.png"

But better would be to get the image as a resource, not as a file using the Class#getResourceAsStream.


问:
How can I create an iOS web browser that proxies all traffic through a proxy server?
I'm looking to create an iOS app that implements a standard Safari-like web browser which proxies all of its traffic through a proxy server. Specifically, it must use its own a proxy configuration so that only its traffic is directed through the proxy, as opposed to using iOS's system settings.

I have some flexibility with what kind of proxy is used. I'd prefer a Socks5 proxy, but an HTTP / HTTPS proxy is okay too. Either way, it must support authentication.

I'd strongly prefer to use SFSafariViewController, as I'd like this web browser to be as close to the experience of using Safari as possible, but I understand that SFSafariViewController is limited and that may not be possible. Failing that, I'd hope to use WKWebView, but if that's not possible either, I can reluctantly fall back on UIWebView.

How would one go about accomplishing this?

edit: I should add that I'm not planning on releasing this app on the app store, so I'm open to methods that normally wouldn't fly there, like undocumented APIs and swizzling. All else being equal though I'd prefer to not utilize methods like that.

答: You can implement a local web server, hosted at localhost:<some_weird_port_number>, and make your WKWebView load only local addresses from that server. Your server will load what you want and how you want, and then will give it as a response to a web view.


问:
How can I set different icons for visited and unvisited external links with CSS?
I'm trying to set different icons for visited and unvisited external links. At first, I tried this:

```<code>a[href^="http"] {
    padding-right: 1.1em;
    background-image: url(external_link.gif);
    background-repeat: no-repeat;
    background-position: center right;
}
a[href^="http"]:visited {
    background-image: url(visited_external_link.gif);
}
</code>```

— but, obviously, it didn't work.

This:

```<code>a {
    padding-right: 1.1em;
    background-image: url(external_link.gif);
    background-repeat: no-repeat;
    background-position: center right;
}
a:visited {
    background-image: url(visited_external_link.gif);
}
a:not([href^="http"]) {
    background-image: none;
    padding-right: 0;
}
</code>```

— didn't work too.

So, how can I to set different icons or, in other words, change icon only for visited external links? Is it possible without classes?

答:
The pseudo element suggestions in other answers or other approaches (short of perhaps JavaScript) will not work.  Per W3 schools https://www.w3schools.com/cssref/sel_visited.asp:

Browsers limits the styles that can be set for a:visited links, due to security issues.

Allowed styles are:

color

background-color

border-color (and border-color for separate sides)

outline color

column-rule-color

the color parts of fill and stroke

All other styles are inherited from a:link.

Even using pseudo elements as others have recommended do not work since you still need to include :visited in the css declaration, which continues to prevent you from adding background images.

Body:
I'm trying to set different icons for visited and unvisited external links. At first, I tried this:

a[href^="http"] {
    padding-right: 1.1em;
    background-image: url(external_link.gif);
    background-repeat: no-repeat;
    background-position: center right;
}
a[href^="http"]:visited {
    background-image: url(visited_external_link.gif);
}

— but, obviously, it didn't work.

This:

a {
    padding-right: 1.1em;
    background-image: url(external_link.gif);
    background-repeat: no-repeat;
    background-position: center right;
}
a:visited {
    background-image: url(visited_external_link.gif);
}
a:not([href^="http"]) {
    background-image: none;
    padding-right: 0;
}

— didn't work too.

So, how can I to set different icons or, in other words, change icon only for visited external links? Is it possible without classes?


问:
Swift2 : checking the timeinterval repeatedly in iOS
As I have three time intervals one is less than 15 mins, second one greater than or equal to 15 and third one is greater than or equal to
30.In my case am checking only once the conditions.But i want to check the conditions for every 1 minute.Because after the certain timeinterval all the button colors for me should change into appYellowColor() only.Any help is appreciable.Thanks in advance! Here is my code.</p>

```<code> if NetworkService.weAreOnline(true) && interval/60 < 15  {

       print("appYellowColor()")
       startButton.backgroundColor = UIColor.appYellowColor()

 }
 else if NetworkService.weAreOnline(true) && interval/60 >= 15  && interval/60 < 30 {

       print("grayColor()")
       startButton.backgroundColor = UIColor.grayColor()
       startButton.userInteractionEnabled = false

 }
 else if NetworkService.weAreOnline(true) && interval/60 >= 30 {

       print("redColor()")
       startButton.backgroundColor = UIColor.redColor()
       startButton.userInteractionEnabled = false

 }
</code>```

答:
One of the possible ways to support repeating task is to put its logic into a function (it can be checkIsOnline() in your case) and schedule a Timer with repeats option.

```<code>let timer = Timer(fire: Date.init(timeIntervalSinceNow: 60), interval: 60, repeats: true) { (timer) in
    self.checkIsOnline()
}

RunLoop.main.add(timer, forMode: .defaultRunLoopMode)
</code>```

You can invalidate() your timer when app is going background and recreate it when app is about to get active.

Body:
As I have three time intervals one is less than 15 mins, second one greater than or equal to 15 and third one is greater than or equal to
30.In my case am checking only once the conditions.But i want to check the conditions for every 1 minute.Because after the certain timeinterval all the button colors for me should change into appYellowColor() only.Any help is appreciable.Thanks in advance! Here is my code.

 if NetworkService.weAreOnline(true) && interval/60 < 15  {

       print("appYellowColor()")
       startButton.backgroundColor = UIColor.appYellowColor()

 }
 else if NetworkService.weAreOnline(true) && interval/60 >= 15  && interval/60 < 30 {

       print("grayColor()")
       startButton.backgroundColor = UIColor.grayColor()
       startButton.userInteractionEnabled = false

 }
 else if NetworkService.weAreOnline(true) && interval/60 >= 30 {

       print("redColor()")
       startButton.backgroundColor = UIColor.redColor()
       startButton.userInteractionEnabled = false

 }

Body:
One of the possible ways to support repeating task is to put its logic into a function (it can be checkIsOnline() in your case) and schedule a Timer with repeats option.

let timer = Timer(fire: Date.init(timeIntervalSinceNow: 60), interval: 60, repeats: true) { (timer) in
    self.checkIsOnline()
}

RunLoop.main.add(timer, forMode: .defaultRunLoopMode)

You can invalidate() your timer when app is going background and recreate it when app is about to get active.


答:
No need for code, just theory.

You need a fourth timer. One set for a single minute (60 seconds). If started at the same time (or right after) as your other three, you just need to check a flag that the other three set. (And if any or all of those three are repeated, have this fourth timer reset things when sending a message in the pipeline.

Title: Swift2 : checking the timeinterval repeatedly in iOS


答:
You can ORDER any data in SQL Query by COLUMN with

ORDER BY

Like

```<code>$query = "SELECT * FROM DB WHERE COL1 = 'row1A' ORDER BY COL2 DESC (or ASC)";
</code>```

Title: Selecting column data from SQL ordered inside while loop

Body:
You can ORDER any data in SQL Query by COLUMN with

ORDER BY

Like

$query = "SELECT * FROM DB WHERE COL1 = 'row1A' ORDER BY COL2 DESC (or ASC)";


答:
.inner {
border:solid;

}

.outer {display: flex;
flex-direction:row;}

.side {width: 25%; height: 50px;}

.center {width: 50%; height: 50px}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="outer">
<div class="side inner"></div>
<div class="center inner"></div>
<div class="side inner"></div>
</div></code>```

You can use flexbox to do this. You can either set the width in procentage or you can look into sizing it with flexbox.

Title: How can I create this following style with CSS3?

Body:
.inner {
border:solid;

}

.outer {display: flex;
flex-direction:row;}

.side {width: 25%; height: 50px;}

.center {width: 50%; height: 50px}

<div class="outer">
<div class="side inner"></div>
<div class="center inner"></div>
<div class="side inner"></div>
</div>

You can use flexbox to do this. You can either set the width in procentage or you can look into sizing it with flexbox.


问:
When I do an android exception hook ,how to judge the assembler instruction is ARM or Thumb by address?
When I do an android exception hook ,how to judge the assembler instruction is ARM or Thumb by address ?   Doesn't the address of  thumb end with '0' ?
when I switch ARM to thumb,I use "BX targetaddr+1",but the address of thumb still end with '0'.I don't know why.</p>

```<code>void WriteillegalInstructionAndSaveOpcode(uint32_t addr, uint32_t    *OriginOpcode)
{
if(0x00000001 == (addr & 0x00000001))
{
    g_bIsThumb = 1;
    *OriginOpcode = *(uint32_t *)(addr & (~0x00000001));
    //Thumb illegal instruction : 0xdeXX
    uint32_t uiThumbillegalValue = 0x0000de00 | (0xFFFF0000 & *OriginOpcode);
    write_data_to_addr(addr & (~0x00000001), uiThumbillegalValue);
}
else
{
    g_bIsThumb = 0;
    //Arm illegal instruction: 0xf7fXaXXX
    *OriginOpcode = *(uint32_t *)addr;
    uint32_t uiArmillegalValue = 0x7f000f0;
    write_data_to_addr(addr, uiArmillegalValue);
}

LOGI("[+] g_bIsThumb is %08x \n",g_bIsThumb);
LOGI("[+] WriteillegalInstruction addr: %08x, OriginalOpcode is %08x",addr & (~0x00000001), *OriginOpcode);

}
</code>```

答:
android so this is a full sized arm not a cortex-m.  Thumb instructions are 16 bits aligned on 16 bits, thumb2 are extensions, so a variable number (two) of 16 bit items.  So one lsbit of thumb is zero.  ARM instructions are 32 bits and have to be aligned so two lsbits have to be zero.  When the lsbit is set is for when you are doing a bx, blx, or pop (or the vector table in a cortex-m) the instruction/action consuming that address strips the lsbit going into the pc, the pc does not contain the lsbit being set (for thumb) the cpsr instead reflects this.  When the bl or blx happens the lr gets the pc plus two instructions and the lsbit is set if in thumb mode otherwise clear.

I think on full sized arms but you have to check the ARM ARM or ARM TRM for that core execute exceptions in ARM mode.

So for your question:

Each exception mode also has a Saved Program Status Register (SPSR)
  which holds the CPSR of the task immediately before the exception
  occurred.

You should check the SPSR to check the T bit to see what mode you were in (assuming it was thumb or ARM), and then based on the exception examine what you need to examine to determine what address this bad instruction in this case was and then go read that item.  Being careful not to do a 32 bit read if it happens to be a thumb instruction not aligned on a 32 bit boundary.

Body:
When I do an android exception hook ,how to judge the assembler instruction is ARM or Thumb by address ?   Doesn't the address of  thumb end with '0' ?
when I switch ARM to thumb,I use "BX targetaddr+1",but the address of thumb still end with '0'.I don't know why.

void WriteillegalInstructionAndSaveOpcode(uint32_t addr, uint32_t    *OriginOpcode)
{
if(0x00000001 == (addr & 0x00000001))
{
    g_bIsThumb = 1;
    *OriginOpcode = *(uint32_t *)(addr & (~0x00000001));
    //Thumb illegal instruction : 0xdeXX
    uint32_t uiThumbillegalValue = 0x0000de00 | (0xFFFF0000 & *OriginOpcode);
    write_data_to_addr(addr & (~0x00000001), uiThumbillegalValue);
}
else
{
    g_bIsThumb = 0;
    //Arm illegal instruction: 0xf7fXaXXX
    *OriginOpcode = *(uint32_t *)addr;
    uint32_t uiArmillegalValue = 0x7f000f0;
    write_data_to_addr(addr, uiArmillegalValue);
}

LOGI("[+] g_bIsThumb is %08x \n",g_bIsThumb);
LOGI("[+] WriteillegalInstruction addr: %08x, OriginalOpcode is %08x",addr & (~0x00000001), *OriginOpcode);

}


问:
Analytics API: Getting Quota Limit Error on just 10000 out of the 50000 daily queries
I am using a WordPress plugin on my website to show the actual views on each post, pulling the number from Google Analytics. The plugin uses the Analytics API.

At first, it worked great. However, a few hours in, I run into an error that I have exceeded the daily request limit. The error didn't go away until the quota reset at midnight pacific time.

The thing is, I checked my quotas at the console, and I had made barely more than 10,000, nowhere near the 50,000 limit.

Quota

I was thinking of requesting to increase the quota, but since I am nowhere near the 50,000, this does not seem to be a solution. Let alone that to request an increase I should have been at about 80% of the current quota.

To avoid the problem, I can have the plugin check the post views every four hours, instead of every hour, through the plugin's settings. But, since I am supposed to have 50000 daily queries, I would prefer to update the views on an hourly basis.

I understand that the current quota at the Google Developer console is a estimate it is not 100% accurate. But could it be so much off, showing 10k when the real number is 50k?

Should I ask for an extension?

答:
You're most likely hitting the profile quota limit, which cannot be increased.

More information here

The 10,000 requests per view (profile) per day or the 10 concurrent requests per view (profile) cannot be increased.


问:
Randomize a text on screen with design
I'm using a PHP to connect to store the input text and after retrieving the text from the database I want to randomize it on the html but i don't know how
i think in jquery or css ??
i attached an image to show how the output look

here's a part of my code below
my code:

```<code><form action="" method="Post" >
   <input type='text' name='answer1' placeholder="input" >
     <input type='sumbit' value='sumbit' >
        </form>
            </div>
<div class="randomizedText">
    <?php echo gettext( $freqData ) ?>
</div>
</code>```

答:
You can use JQCloud or if you want you can download and use Awesome Tag Cloud using Jquery and Canvas HTML5 from here

BASIC USAGE

1. Load the latest version of jQuery library and jQuery awesomeCloud plugin in the document.

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="jquery.awesomeCloud.min.js"></script>
</code>```

2. Wrap the words/tags in an HTML element with a data-weight attribute that reflects it's "weight".

```<code><div id="demo">
<span data-weight="91"> Tag 1 </span>
<span data-weight="21"> Tag 2 </span>
<span data-weight="41"> Tag 3 </span>
<span data-weight="13"> Tag 4 </span>
<span data-weight="78"> Tag 5 </span>
...
</div>
</code>```

3. Call the plugin on the parent element and set the options for the tag cloud.

```<code><script>
$(document).ready(function(){
$("#demo").awesomeCloud({
"size" : {
"<a href="http://www.jqueryscript.net/tags.php?/grid/">grid</a>" : 16, // word spacing, smaller is more tightly packed
"factor" : 0, // font resize factor, 0 means automatic
"normalize" : false // reduces outliers for more attractive output
},
"color" : {
"background" : "rgba(255,255,255,0)", // background color, transparent by default
"start" : "#20f", // color of the smallest font, if options.color = "gradient""
"end" : "rgb(200,0,0)" // color of the largest font, if options.color = "gradient"
},
"options" : {
"color" : "random-dark", // random-light, random-dark, gradient
"rotationRatio" : 0.35, // 0 is all horizontal, 1 is all vertical
"printMultiplier" : 3, // set to 3 for nice printer output; higher numbers take longer
"sort" : "random" // highest, lowest or random
},
"font" : "'Times New Roman', Times, serif", //  the CSS font-family string
"shape" : "square" // circle, square, star or a theta function describing a shape
});
});
</script>
</code>```

For more Advanced Usages, please check the demo page or visit the official website.

Title: Randomize a text on screen with design

Body:
I'm using a PHP to connect to store the input text and after retrieving the text from the database I want to randomize it on the html but i don't know how
i think in jquery or css ??
i attached an image to show how the output look

here's a part of my code below
my code:

<form action="" method="Post" >
   <input type='text' name='answer1' placeholder="input" >
     <input type='sumbit' value='sumbit' >
        </form>

    <?php echo gettext( $freqData ) ?>

Body:
You can use JQCloud or if you want you can download and use Awesome Tag Cloud using Jquery and Canvas HTML5 from here

BASIC USAGE

1. Load the latest version of jQuery library and jQuery awesomeCloud plugin in the document.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="jquery.awesomeCloud.min.js"></script>

2. Wrap the words/tags in an HTML element with a data-weight attribute that reflects it's "weight".

<div id="demo">
<span data-weight="91"> Tag 1 </span>
<span data-weight="21"> Tag 2 </span>
<span data-weight="41"> Tag 3 </span>
<span data-weight="13"> Tag 4 </span>
<span data-weight="78"> Tag 5 </span>
...
</div>

3. Call the plugin on the parent element and set the options for the tag cloud.

<script>
$(document).ready(function(){
$("#demo").awesomeCloud({
"size" : {
"<a href="http://www.jqueryscript.net/tags.php?/grid/">grid</a>" : 16, // word spacing, smaller is more tightly packed
"factor" : 0, // font resize factor, 0 means automatic
"normalize" : false // reduces outliers for more attractive output
},
"color" : {
"background" : "rgba(255,255,255,0)", // background color, transparent by default
"start" : "#20f", // color of the smallest font, if options.color = "gradient""
"end" : "rgb(200,0,0)" // color of the largest font, if options.color = "gradient"
},
"options" : {
"color" : "random-dark", // random-light, random-dark, gradient
"rotationRatio" : 0.35, // 0 is all horizontal, 1 is all vertical
"printMultiplier" : 3, // set to 3 for nice printer output; higher numbers take longer
"sort" : "random" // highest, lowest or random
},
"font" : "'Times New Roman', Times, serif", //  the CSS font-family string
"shape" : "square" // circle, square, star or a theta function describing a shape
});
});
</script>

For more Advanced Usages, please check the demo page or visit the official website.


问:
How does a DBMS use File I/O to read a database?
I want to learn more about databases and how they work at a low level so I can try to write a really, really basic one for learning purposes. I was wondering if databases like MySQL and SQL Server use traditional File I/O to read the database files, or if there is a more advanced mechanism for reading disk sectors or specific blocks?

By traditional File I/O I mean using something like

```<code>FILE *fopen(const char *filename, const char *mode)
</code>```

in C.

I know that InnoDB uses 16kb pages in the database to store metadata and records. I don't know if they just precalculate how many pages they may need to skip in order to find a value based on an index and then seek that page in the file or if they have some more advanced access control.

答:
I found a research paper here by Joseph M. Hellerstein, Michael Stonebraker
and James Hamilton that explains storage management starting on page 210. It talks about how a DBMS can use the file system or raw disk access where it writes to logical, sequential blocks.

A DBMS can use either/or or even both types of disk access to manage the databases. You get slightly better performance from raw disk access but raw access comes with some disadvantages, like dedicating full partitions to a database. A large file can be used and often enough the file offset is close to the physical location on disk, so large files offer minimal degradation in I/O performance in best-case scenarios.

A virtual disk is another option for simulating raw disk access, and according to the research paper, is becoming the norm.

Body:
I want to learn more about databases and how they work at a low level so I can try to write a really, really basic one for learning purposes. I was wondering if databases like MySQL and SQL Server use traditional File I/O to read the database files, or if there is a more advanced mechanism for reading disk sectors or specific blocks?

By traditional File I/O I mean using something like

FILE *fopen(const char *filename, const char *mode)

in C.

I know that InnoDB uses 16kb pages in the database to store metadata and records. I don't know if they just precalculate how many pages they may need to skip in order to find a value based on an index and then seek that page in the file or if they have some more advanced access control.


问:
Error 1064 - using the IN statement
List customer names who ordered Apple Laptop (Choose your own join type). I have gour tables customer, orderline, ordertable, and product. I keep getting this error

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use
  near ''product' where product_name = 'Apple Laptop'))) LIMIT 0, 25' at
  line 4

```<code>select customer.cust_name
from customer
where customer.cust_id in (
        select cust_id
        from ordertable
        where order_id in (
                select order_id
                from orderline
                where product in (
                        select product_id
                        from 'product'
                        where product_name = 'Apple Laptop'
                        )
                )
        )
</code>```

答:
Without seeing your schema, this is a bit challenging, but after you removed the quotes from 'product' the error is saying that there is no column product in the outer clause. We can infer that you are selecting product_id in the deepest subquery, so the outer where clause likely needs to use product_id and not product.

```<code>select customer.cust_name
from customer
where customer.cust_id in (
        select cust_id
        from ordertable
        where order_id in (
                select order_id
                from orderline
                where product_id in ( -- <-- ERROR HERE
                        select product_id
                        from product
                        where product_name = 'Apple Laptop'
                        )
                )
        )
</code>```

Title: Error 1064 - using the IN statement

Body:
List customer names who ordered Apple Laptop (Choose your own join type). I have gour tables customer, orderline, ordertable, and product. I keep getting this error

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use
  near ''product' where product_name = 'Apple Laptop'))) LIMIT 0, 25' at
  line 4

select customer.cust_name
from customer
where customer.cust_id in (
        select cust_id
        from ordertable
        where order_id in (
                select order_id
                from orderline
                where product in (
                        select product_id
                        from 'product'
                        where product_name = 'Apple Laptop'
                        )
                )
        )

Body:
Without seeing your schema, this is a bit challenging, but after you removed the quotes from 'product' the error is saying that there is no column product in the outer clause. We can infer that you are selecting product_id in the deepest subquery, so the outer where clause likely needs to use product_id and not product.

select customer.cust_name
from customer
where customer.cust_id in (
        select cust_id
        from ordertable
        where order_id in (
                select order_id
                from orderline
                where product_id in ( -- <-- ERROR HERE
                        select product_id
                        from product
                        where product_name = 'Apple Laptop'
                        )
                )
        )


问:
Why does this C program just stops while running and shows no output?
Hellow guys, my friend made this program (I don't know what he is actually doing), but he asked me for help because it was not executing properly. I have studied the C++ till Objects and Overloading. I looked at the code and it seemed fine but when I tried to execute, it does not execute properly, after asking for the height, the DOS stops working and gets clsoed. I tried to figure out the problem, but I could not.

Below is the code of the program:

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

int main()
{
    int height, i, j;
    char character;

    printf("plz enter height\n");
    scanf("%d",height);

    printf("plz type character\n");
    scanf("%c",character);

    for(i=0;i<=height;i++){
        for(j=0;j<=i;j++){
        printf("%c",character);
        }
    printf("\n");
    }
}
</code>```

答:
```<code>int main()
{
    int height, i, j;
    char *character;

    printf("plz enter height\n");
    scanf("%d",&height);

    printf("plz type character\n");
    scanf("%s",&character); //if you consider charactere as string it works

    for(i=0;i<=height;i++){
        for(j=0;j<=i;j++){
        printf("%c",character);
        }
    printf("\n");
    }
}
</code>```

Body:
Hellow guys, my friend made this program (I don't know what he is actually doing), but he asked me for help because it was not executing properly. I have studied the C++ till Objects and Overloading. I looked at the code and it seemed fine but when I tried to execute, it does not execute properly, after asking for the height, the DOS stops working and gets clsoed. I tried to figure out the problem, but I could not.

Below is the code of the program:

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

int main()
{
    int height, i, j;
    char character;

    printf("plz enter height\n");
    scanf("%d",height);

    printf("plz type character\n");
    scanf("%c",character);

    for(i=0;i<=height;i++){
        for(j=0;j<=i;j++){
        printf("%c",character);
        }
    printf("\n");
    }
}


问:
What's wrong with my Scanner java code?
```<code>import java.util.Scanner;

public class Exercise5 {

 public static void main(String[] args) {
  Scanner in = new Scanner(System.in);

  System.out.print("Input first number: ");
  int num1 = in.nextInt(5);

  System.out.print("Input second number: ");
  int num2 = in.nextInt(25);

  System.out.println(num1 + " x " + num2 + " = " + num1 * num2);
 }

}
</code>```

**Here is my java code, the expect output should be like this:

Input first number: 25

Input second number: 5

25 x 5 = 125

After I plug in my code and run it, the output is too different with the answer

Here is the output:

```<code>Input first number: Exception in thread "main"   java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at Exercise5.main(Exercise5.java:27)
</code>```

How can I fix my code?

答:
FIXED CODE

```<code>import java.util.Scanner;

public class Exercise5 {

public static void main(String[] args) {
Scanner in = new Scanner(System.in);

 System.out.print("Input first number: ");
 int num1 = in.nextInt();

 System.out.print("Input second number: ");
 int num2 = in.nextInt();

 total = num1*num2

System.out.println(num1 + " x " + num2 + " = " + total);
}

}
</code>```

Your nextInt() will catch the user input so there is no need to put in values. You will manually put them in when prompted on the output window in your IDE.

I would also put the num1 and num2 into separate variables (Ex. int total = num1*num2) then print out the total in the println :)

Title: What's wrong with my Scanner java code?

Body:
import java.util.Scanner;

public class Exercise5 {

 public static void main(String[] args) {
  Scanner in = new Scanner(System.in);

  System.out.print("Input first number: ");
  int num1 = in.nextInt(5);

  System.out.print("Input second number: ");
  int num2 = in.nextInt(25);

  System.out.println(num1 + " x " + num2 + " = " + num1 * num2);
 }

}

**Here is my java code, the expect output should be like this:

Input first number: 25

Input second number: 5

25 x 5 = 125

After I plug in my code and run it, the output is too different with the answer

Here is the output:

Input first number: Exception in thread "main"   java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at Exercise5.main(Exercise5.java:27)

How can I fix my code?

Body:
FIXED CODE

import java.util.Scanner;

public class Exercise5 {

public static void main(String[] args) {
Scanner in = new Scanner(System.in);

 System.out.print("Input first number: ");
 int num1 = in.nextInt();

 System.out.print("Input second number: ");
 int num2 = in.nextInt();

 total = num1*num2

System.out.println(num1 + " x " + num2 + " = " + total);
}

}

Your nextInt() will catch the user input so there is no need to put in values. You will manually put them in when prompted on the output window in your IDE.

I would also put the num1 and num2 into separate variables (Ex. int total = num1*num2) then print out the total in the println :)