问:
CarrierWave Multiple file Upload
I am trying to upload multiple files using carrier wave. Whenever I am trying to upload the file, I am able to upload the only single file. Even I have added the array of hash in permit({image: []}) under the floorplan controller.

It is the controller.

```<code>class FloorplansController < ApplicationController

def create
    @project = Project.find(params[:project_id])
    @floorplan  = Floorplan.create(params[:floorplan].permit(:name,{image: []}))
    @floorplan.user_id = current_user.id
    @floorplan.project_id = @project.id

    if @floorplan.save
        redirect_to project_path(@project)
    else
        render 'new'
    end
end
</code>```

end

It is the form partial from where I am uploading the files.

```<code>= simple_form_for([@project, @project.floorplans.build],input_html: {multiple: true }) do |f|
= f.input :name, label: "Name the Floorplan"
= f.input :image, input_html: {multiple: true }, name:"floorplan[image][]", label: "Attach the Floorplan Image"
= f.button :submit, class: "button"
</code>```

After that, I attached jquery file uploader as explained in RailsCast episode 381
floorplan.coffee
jQuery ->
    $('#new_floorplan').fileupload()

And these are my db migrations

```<code>class AddImageToFloorplans < ActiveRecord::Migration[5.1]
   def change
     add_column :floorplans, :image, :string
   end
end
</code>```

答:
1- in Gemfile

```<code>gem 'jquery-rails'
gem 'jquery-ui-rails'
gem 'nested_form_fields'
</code>```

2- application.js.erb

```<code>//= require jquery
//= require jquery_ujs
//= require nested_form_fields
//= require jquery-ui
//= require turbolinks
//= require_tree .
</code>```

3- in new action

```<code>def new
  @project = Peoject.new
  @project.@project.floorplans.build
end
</code>```

4.- in view form

```<code><%= form_for @project do |f| %>
    <%= f.text_field :name, class: 'form-control' %>
   <%=f.nested_fields_for :floorplans do |floorplan|%>
     <%=floorplan.remove_nested_fields_link 'Remove'%>
     <%=floorplan.file_field :image%>
   <%end%>
   <%=f.add_nested_fields_link :floorplans, 'Add Photo'%>
  <%= f.submit 'Submit', class: 'btn btn-primary' %>
<% end %>
</code>```

5- in create action

```<code>def create
    @project = Project.new(project_params)
    if @floorplan.save
        redirect_to project_path(@project)
    else
        render 'new'
    end
end

private
def project_params
  params.require(:project).permit(:name, floorplans_attributes: [:image])
end
</code>```

6- for more reference you can follow this

Title: CarrierWave Multiple file Upload

Body:
I am trying to upload multiple files using carrier wave. Whenever I am trying to upload the file, I am able to upload the only single file. Even I have added the array of hash in permit({image: []}) under the floorplan controller.

It is the controller.

class FloorplansController < ApplicationController

def create
    @project = Project.find(params[:project_id])
    @floorplan  = Floorplan.create(params[:floorplan].permit(:name,{image: []}))
    @floorplan.user_id = current_user.id
    @floorplan.project_id = @project.id

    if @floorplan.save
        redirect_to project_path(@project)
    else
        render 'new'
    end
end

end

It is the form partial from where I am uploading the files.

= simple_form_for([@project, @project.floorplans.build],input_html: {multiple: true }) do |f|
= f.input :name, label: "Name the Floorplan"
= f.input :image, input_html: {multiple: true }, name:"floorplan[image][]", label: "Attach the Floorplan Image"
= f.button :submit, class: "button"

After that, I attached jquery file uploader as explained in RailsCast episode 381
floorplan.coffee
jQuery ->
    $('#new_floorplan').fileupload()

And these are my db migrations

class AddImageToFloorplans < ActiveRecord::Migration[5.1]
   def change
     add_column :floorplans, :image, :string
   end
end

Body:
1- in Gemfile

gem 'jquery-rails'
gem 'jquery-ui-rails'
gem 'nested_form_fields'

2- application.js.erb

//= require jquery
//= require jquery_ujs
//= require nested_form_fields
//= require jquery-ui
//= require turbolinks
//= require_tree .

3- in new action

def new
  @project = Peoject.new
  @project.@project.floorplans.build
end

4.- in view form

<%= form_for @project do |f| %>
    <%= f.text_field :name, class: 'form-control' %>
   <%=f.nested_fields_for :floorplans do |floorplan|%>
     <%=floorplan.remove_nested_fields_link 'Remove'%>
     <%=floorplan.file_field :image%>
   <%end%>
   <%=f.add_nested_fields_link :floorplans, 'Add Photo'%>
  <%= f.submit 'Submit', class: 'btn btn-primary' %>
<% end %>

5- in create action

def create
    @project = Project.new(project_params)
    if @floorplan.save
        redirect_to project_path(@project)
    else
        render 'new'
    end
end

private
def project_params
  params.require(:project).permit(:name, floorplans_attributes: [:image])
end

6- for more reference you can follow this


来源: stackexchange

问:
Codeigniter session class not working
I loaded the session class in autoload.php, but when I use the CodeIgniter session nothing happens.

Example: I set flash data:

```<code>$this->session->set_flashdata('message', 'HELP!');
</code>```

When I print this information nothing happens!

Example:

```<code>echo $this->session->flashdata('message');
</code>```

What is the problem with my code?

NOTE: I'm having problems with CodeIgniter Session in general, problem with set_flashdata and set_userdata.

UPDATE:

It was a server problem, now it's solved.
Thanks for all!

答: Download the latest version Codeigniter (Version 3.1.6)  from Codeigniter official website and replace the system folder to your Codeigniter project and it will works.</p>

ContentLicense: CC BY-SA 3.0

Title: Codeigniter session class not working

Body:
I loaded the session class in autoload.php, but when I use the CodeIgniter session nothing happens.

Example: I set flash data:

$this->session->set_flashdata('message', 'HELP!');

When I print this information nothing happens!

Example:

echo $this->session->flashdata('message');

What is the problem with my code?

NOTE: I'm having problems with CodeIgniter Session in general, problem with set_flashdata and set_userdata.

UPDATE:

It was a server problem, now it's solved.
Thanks for all!


问:
No access to Program Files in Windows 7
I'm totally new to windows 7 and have just installed Apache server. I want to change httpd file... But when opening file with notepad and saving it, I get a message that I have no rights... My user is a member of Administrators group. What else can I do?

Thanks

P.S. Could you suggest any nice tutorials on dealing with user administration and admin accounts?

答: Maybe try a different editor, say NotePad++. Run in Administrator. Also make sure that Apache is not running and any related tasks are shut down. Try it in Safe Mode if you get desperate.</p>

ContentLicense: CC BY-SA 2.5

Title: No access to Program Files in Windows 7


问:
How to create Cairo Context for drawing in code with Gtk Sharp and C#
I have a few buttons and an area where I want to draw some things. I have been trying to create a surface for drawing with Cairo since Gtk's Drawing Area widget doesn't seem to know how to draw basic shapes (or I just failed to find how it does it).

I found some basic tutorials on this (for example: http://zetcode.com/gui/gtksharp/drawing/ or http://www.mono-project.com/docs/tools+libraries/libraries/Mono.Cairo/tutorial/) but can't figure out how to make the surface for drawing in my app, along with buttons and labels, not just a new blank window used only for Cairo drawing.

This is how my app looks for now:

So, I want the blank part in the middle to be my drawing area.

I tried this which I think should make the Drawing Area widget I have in my app drawable with Cairo:

I don't quite understand what I should do here.

I just need to draw some basic circles and lines on it so I don't really need Cairo, any help with how I could do any drawing with Gtk# would be greatly appreciated!

答:
You're on the right track. Unfortunately GTK# and Cairo have a few quirks. First, I would highly recommend using an EventBox widget instead of DrawingArea. Counter intuitively, I've never had much luck getting a DrawingArea to work properly. An EventBox works in much the same way except that you can make the background transparent by setting VisibleWindow to false.

```<code>public class YourWidget : EventBox
{
    public YourWidget() {
        Visible = true;
        VisibleWindow = false;
        ExposeEvent += OnExpose;
    }
}
</code>```

Next, the ordinates used when drawing in an event box are based on the origin of the parent window, i.e. the entire application window. Each widget object contains some properties, Allocation, that specify where it is within the parent window as well as how large it is. In order to draw within the limits of the custom widgets window, you have to reference off these points. This is only for custom widgets the extend the EventBox widget. If memory serves, widgets using a DrawingArea are reference from the widget location. Lastly, I would contain the Cairo Context within a using block so you don't forget to dispose of the object.

```<code>protected void OnExpose(object sender, ExposeEventArgs args) {
    using (Context cr = Gdk.CairoHelper.Create(this.GdkWindow)) {
          int top = Allocation.Top;
          int left = Allocation.Left;

          cr.Rectangle(left + 8, top + 8, 10, 10);
          cr.SetSourceRGB(255, 0, 0);
          cr.Fill();
    }
}
</code>```

Also, its been awhile since I've started a new GTK# application, but you may have to add the Mono.Cairo package to the project's references. Finally, I've used EventBox based widgets to create several custom widgets for a touch application that may also serve as a reference to get you started. I hope this all helps.

Body:
You're on the right track. Unfortunately GTK# and Cairo have a few quirks. First, I would highly recommend using an EventBox widget instead of DrawingArea. Counter intuitively, I've never had much luck getting a DrawingArea to work properly. An EventBox works in much the same way except that you can make the background transparent by setting VisibleWindow to false.

public class YourWidget : EventBox
{
    public YourWidget() {
        Visible = true;
        VisibleWindow = false;
        ExposeEvent += OnExpose;
    }
}

Next, the ordinates used when drawing in an event box are based on the origin of the parent window, i.e. the entire application window. Each widget object contains some properties, Allocation, that specify where it is within the parent window as well as how large it is. In order to draw within the limits of the custom widgets window, you have to reference off these points. This is only for custom widgets the extend the EventBox widget. If memory serves, widgets using a DrawingArea are reference from the widget location. Lastly, I would contain the Cairo Context within a using block so you don't forget to dispose of the object.

protected void OnExpose(object sender, ExposeEventArgs args) {
    using (Context cr = Gdk.CairoHelper.Create(this.GdkWindow)) {
          int top = Allocation.Top;
          int left = Allocation.Left;

          cr.Rectangle(left + 8, top + 8, 10, 10);
          cr.SetSourceRGB(255, 0, 0);
          cr.Fill();
    }
}

Also, its been awhile since I've started a new GTK# application, but you may have to add the Mono.Cairo package to the project's references. Finally, I've used EventBox based widgets to create several custom widgets for a touch application that may also serve as a reference to get you started. I hope this all helps.


问:
is there a link between dstream.checkpoint(checkpointInterval) and spark.streaming.receiver.writeAheadLog.enable
As per the spark streaming documentation, dstream which are queued but not processed will be written to checkpoint directory after every checkpointInterval.

but at the same time there is a configuration spark.streaming.receiver.writeAheadLog.enable = true
which as per the spark documentation "all the data received from a receiver gets written into a write ahead log in the configuration checkpoint directory"

what is the difference in each of the options given by spark?

答:
Metadata checkpointing - Incomplete batches - Batches whose jobs are queued but have not completed yet. This saves the metadata about the batches that are queued not completed yet and will not store the actual data received by the receiver.

On the other hand, if enabled writeAheadLogs will store the actual data thats received by the receiver.


问:
How to play widevine drm content in android webview
I want to play widevine drm content in webview android using html5 code.
I tried a lot not succeeded, does widevine not supported in webview?
please give a way to play widevine in webview android and let me know if widevine does not support in widevine and why?

Any help and suggestion would be appreciated.

答:
Unfortunately, the webview shipped with Android devices differs between devices and between Android versions.

There is an excellent overview here:

http://slides.com/html5test/the-android-browser#/42

You can test whether your device supports it by using an open source HTML5 player like Shaka in your webview and trying some of their demo content.

Shakaplayer includes a basic tutorial showing how to include the player in a webpage:

https://shaka-player-demo.appspot.com/docs/api/tutorial-basic-usage.html

You can also use a test app like the HTML5test Webview app - checking the streaming section to make sure MSE and DRM are both ticked:

https://play.google.com/store/apps/details?id=com.html5test.webview&hl=en


问:
How to preserve value type when serializing form data to JSON
I want to convert all form values to JSON so that I can send the JSON as body in my AJAX POST. I found this existing solution online:

```<code>function getFormData($form){
    var unindexed_array = $form.serializeArray();
    var indexed_array = {};

    $.map(unindexed_array, function(n, i){
        indexed_array[n['name']] = n['value'];
    });

    return indexed_array;
}
</code>```

Usage:

```<code>var $form = $("#form_data");
var data = getFormData($form);
</code>```

However, this approach (source) converts all values to type string, it does not preserve numbers as integers. I could not come up with a way to preserve the type of the values. What is the best way to do this?

HTML:

```<code><form id="myform">
    <div>
      <label>Number: </label>
      <input id="mynum" type="number" name="mynum"/>
    </div>
    <div>
      <label>name: </label>
      <input id="myname" type="text" name="myname"/>
    </div>
</form>
</code>```

答:
That is because all input values are by default of type string. If you want to convert the type to number type you have to do that manually.

One way to do that by looping through the JSON and use a manual function to parse string value back to the number type.

To create a manual function: http://pietschsoft.com/post/2008/01/14/JavaScript-intTryParse-Equivalent

The following code shows even if the input type is number, the type is actually string:

let type;
function checkFormData(){
  type = document.getElementById('mynum').value;
  console.log('The type of input#mynum is: ' +typeof type);
  return false;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="myform" onsubmit=" return checkFormData()">
  <div>
    <label>Number: </label>
    <input id="mynum" type="number" name="mynum"/>
  </div>
  <div>
    <label>name: </label>
    <input id="myname" type="text" name="myname"/>
  </div>
  <input type="submit" value="Submit"/>
</form></code>```

Body:
I want to convert all form values to JSON so that I can send the JSON as body in my AJAX POST. I found this existing solution online:

function getFormData($form){
    var unindexed_array = $form.serializeArray();
    var indexed_array = {};

    $.map(unindexed_array, function(n, i){
        indexed_array[n['name']] = n['value'];
    });

    return indexed_array;
}

Usage:

var $form = $("#form_data");
var data = getFormData($form);

However, this approach (source) converts all values to type string, it does not preserve numbers as integers. I could not come up with a way to preserve the type of the values. What is the best way to do this?

HTML:

<form id="myform">

      Number:
      <input id="mynum" type="number" name="mynum"/>

      name:
      <input id="myname" type="text" name="myname"/>

</form>

Body:
That is because all input values are by default of type string. If you want to convert the type to number type you have to do that manually.

One way to do that by looping through the JSON and use a manual function to parse string value back to the number type.

To create a manual function: http://pietschsoft.com/post/2008/01/14/JavaScript-intTryParse-Equivalent

The following code shows even if the input type is number, the type is actually string:

let type;
function checkFormData(){
  type = document.getElementById('mynum').value;
  console.log('The type of input#mynum is: ' +typeof type);
  return false;
}

<form id="myform" onsubmit=" return checkFormData()">
  <div>
    <label>Number: </label>
    <input id="mynum" type="number" name="mynum"/>
  </div>
  <div>
    <label>name: </label>
    <input id="myname" type="text" name="myname"/>
  </div>
  <input type="submit" value="Submit"/>
</form>


问:
Can HDFS block size be changed during job run? Custom Split and Variant Size
I am using hadoop 1.0.3. Can the input split/block be changed (increase/decrease) during run time based on some constraints. Is there a class to override to accomplish this mechanism like FileSplit/InputTextFormat? Can we have variant size blocks in HDFS depending on logical constraint in one job?</p>

答:
You're not limited to TextInputFormat... Thats entirely configurable based on the data source you are reading. Most examples are line delimited plaintext, but that obviously doesn't work for XML, for example.

No, block boundaries can't change during runtime as your data should already be on disk, and ready to read.

But the InputSplit is dependent upon the InputFormat for the given job, which should remain consistent throughout a particular job, but the Configuration object in the code is basically a Hashmap which can be changed while running, sure


问:
Using Binary Search with sorted Array with duplicates
I've been tasked with creating a method that will print all the indices where value x is found in a sorted array.

I understand that if we just scanned through the array from 0 to N (length of array) it would have a running time of O(n) worst case.  Since the array that will be passed into the method will be sorted, I'm assuming that I can take advantage of using a Binary Search since this will be O(log n).  However, this only works if the array has unique values.  Since the Binary Search will finish after the first "find" of a particular value.  I was thinking of doing a Binary Search for finding x in the sorted array, and then checking all values before and after this index, but then if the array contained all x values, it doesn't seem like it would be that much better.

I guess what I'm asking is, is there a better way to find all the indices for a particular value in a sorted array that is better than O(n)?

```<code>public void PrintIndicesForValue42(int[] sortedArrayOfInts)
{
    // search through the sortedArrayOfInts

    // print all indices where we find the number 42.
}
</code>```

Ex: sortedArray = { 1, 13, 42, 42, 42, 77, 78 } would print: "42 was found at Indices: 2, 3, 4"

答:
I came up with the solution using binary search, only thing is to do the binary search on both the sides if the match is found.

```<code>public static void main(String[] args) {
    int a[] ={1,2,2,5,5,6,8,9,10};
    System.out.println(2+" IS AVAILABLE  AT = "+findDuplicateOfN(a, 0, a.length-1, 2));
    System.out.println(5+" IS AVAILABLE  AT = "+findDuplicateOfN(a, 0, a.length-1, 5));
    int a1[] ={2,2,2,2,2,2,2,2,2};
    System.out.println(2+" IS AVAILABLE  AT = "+findDuplicateOfN(a1, 0, a1.length-1, 2));

    int a2[] ={1,2,3,4,5,6,7,8,9};
    System.out.println(10+" IS AVAILABLE  AT = "+findDuplicateOfN(a2, 0, a2.length-1, 10));
}

public static String findDuplicateOfN(int[] a, int l, int h, int x){
    if(l>h){
        return "";
    }
    int m = (h-l)/2+l;
    if(a[m] == x){
        String matchedIndexs = ""+m;
        matchedIndexs = matchedIndexs+findDuplicateOfN(a, l, m-1, x);
        matchedIndexs = matchedIndexs+findDuplicateOfN(a, m+1, h, x);
        return matchedIndexs;
    }else if(a[m]>x){
        return findDuplicateOfN(a, l, m-1, x);
    }else{
        return findDuplicateOfN(a, m+1, h, x);
    }
}

2 IS AVAILABLE  AT = 12
5 IS AVAILABLE  AT = 43
2 IS AVAILABLE  AT = 410236578
10 IS AVAILABLE  AT =
</code>```

I think this is still providing the results in O(logn) complexity.

Body:
I've been tasked with creating a method that will print all the indices where value x is found in a sorted array.

I understand that if we just scanned through the array from 0 to N (length of array) it would have a running time of O(n) worst case.  Since the array that will be passed into the method will be sorted, I'm assuming that I can take advantage of using a Binary Search since this will be O(log n).  However, this only works if the array has unique values.  Since the Binary Search will finish after the first "find" of a particular value.  I was thinking of doing a Binary Search for finding x in the sorted array, and then checking all values before and after this index, but then if the array contained all x values, it doesn't seem like it would be that much better.

I guess what I'm asking is, is there a better way to find all the indices for a particular value in a sorted array that is better than O(n)?

public void PrintIndicesForValue42(int[] sortedArrayOfInts)
{
    // search through the sortedArrayOfInts

    // print all indices where we find the number 42.
}

Ex: sortedArray = { 1, 13, 42, 42, 42, 77, 78 } would print: "42 was found at Indices: 2, 3, 4"

Body:
I came up with the solution using binary search, only thing is to do the binary search on both the sides if the match is found.

public static void main(String[] args) {
    int a[] ={1,2,2,5,5,6,8,9,10};
    System.out.println(2+" IS AVAILABLE  AT = "+findDuplicateOfN(a, 0, a.length-1, 2));
    System.out.println(5+" IS AVAILABLE  AT = "+findDuplicateOfN(a, 0, a.length-1, 5));
    int a1[] ={2,2,2,2,2,2,2,2,2};
    System.out.println(2+" IS AVAILABLE  AT = "+findDuplicateOfN(a1, 0, a1.length-1, 2));

    int a2[] ={1,2,3,4,5,6,7,8,9};
    System.out.println(10+" IS AVAILABLE  AT = "+findDuplicateOfN(a2, 0, a2.length-1, 10));
}

public static String findDuplicateOfN(int[] a, int l, int h, int x){
    if(l>h){
        return "";
    }
    int m = (h-l)/2+l;
    if(a[m] == x){
        String matchedIndexs = ""+m;
        matchedIndexs = matchedIndexs+findDuplicateOfN(a, l, m-1, x);
        matchedIndexs = matchedIndexs+findDuplicateOfN(a, m+1, h, x);
        return matchedIndexs;
    }else if(a[m]>x){
        return findDuplicateOfN(a, l, m-1, x);
    }else{
        return findDuplicateOfN(a, m+1, h, x);
    }
}

2 IS AVAILABLE  AT = 12
5 IS AVAILABLE  AT = 43
2 IS AVAILABLE  AT = 410236578
10 IS AVAILABLE  AT =

I think this is still providing the results in O(logn) complexity.


问:
How can I display the three level div in turn by using z-index?
The html code is as follow:

```<code><div class="first common">
    i am the first div.
    <div class="second common">
        i am the second div.
        <div class="third common">
            i am the third div.
        </div>
    </div>
</div>
</code>```

css:

```<code>.common {
    position: absolute;
    left: 50px;
    top: 50px;
    width: 200px;
    height: 200px;
    color: #fff;
}
.first {
    background-color: #8EE5EE;
}
.second {
    background-color: #7A67EE;
}
.third {
    background-color: #0000AA;
}
</code>```

The results are as follows

And now I want to put the first div in the front, the second div in the middle and the third div at the back (reverse) by using z-index if I could .
But I don't know how to do.

答:
With that html you cannot. A div that is a child of another div won't show behind it regardless of z-index. Restructure like this:

.outer {
  position: relative;
}

.common {
  position: absolute;
  width: 200px;
  height: 200px;
  color: #fff;
}

.first {
  background-color: #8EE5EE;
  left: 50px;
  top: 50px;
  z-index: 3;
}

.second {
  background-color: #7A67EE;
  left: 100px;
  top: 100px;
  z-index: 2;
}

.third {
  background-color: #0000AA;
  left: 150px;
  top: 150px;
  z-index: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="outer">
  <div class="first common"></div>
  <div class="second common"></div>
  <div class="third common"></div>
</div></code>```

Body:
The html code is as follow:

    i am the first div.

        i am the second div.

            i am the third div.

css:

.common {
    position: absolute;
    left: 50px;
    top: 50px;
    width: 200px;
    height: 200px;
    color: #fff;
}
.first {
    background-color: #8EE5EE;
}
.second {
    background-color: #7A67EE;
}
.third {
    background-color: #0000AA;
}

The results are as follows

And now I want to put the first div in the front, the second div in the middle and the third div at the back (reverse) by using z-index if I could .
But I don't know how to do.

Body:
With that html you cannot. A div that is a child of another div won't show behind it regardless of z-index. Restructure like this:

.outer {
  position: relative;
}

.common {
  position: absolute;
  width: 200px;
  height: 200px;
  color: #fff;
}

.first {
  background-color: #8EE5EE;
  left: 50px;
  top: 50px;
  z-index: 3;
}

.second {
  background-color: #7A67EE;
  left: 100px;
  top: 100px;
  z-index: 2;
}

.third {
  background-color: #0000AA;
  left: 150px;
  top: 150px;
  z-index: 1;
}

<div class="outer">
  <div class="first common"></div>
  <div class="second common"></div>
  <div class="third common"></div>
</div>


问:
What is the correct way with NPM to package a BUILT version of a forked Git repository?
I recently forked a GitHub repository to fix a problem, and created a pull request.  While I wait for the pull request to be accepted, I have pointed my local package.json at my forked repo, like so:

```<code>devDependencies: {
    "karma-mocha": "maloric/karma-mocha"
}
</code>```

However it turns out that karma-mocha requires a build step to be executed to generate lib/adapter.js - a vital part of the package.  This file is listed in .gitignore, so does not exist in the repository.  The build step is a grunt task that is normally executed when the package is published to npm, so adapter.js exists in the downloaded npm module.

My question is this: what is the correct way to package a forked, built version of the repository so that I can use it as a dependency?  As far as I can tell, I have the following options:

Build the repository locally, create a .tgz file with the built files, then host this somewhere and point my package.json to that file.

Build the repository locally, alter .gitignore to allow adapter.js, then push to a branch on Github and use that branch as my dependency.

Either of these would work, but I feel like I am missing something.  Does npm have a concept of forked packages?  Not every git repository can be used as a dependency without some sort of build/dist step, so what is the accepted way to do this kind of thing?

答:
That seems similar to karma-runner/karma-jasmine issue 38, not exactly the same library, but the same idea, and issue with adapter.js:

As you correctly pointed out, adapter.js generated by grunt build.

  adpater.js is placed only in npm repository when we run grunt release.

If you want use your version of karma-jasmine then you can remove lib/adapter.js from .gitignore.

So option 2.

Body:
I recently forked a GitHub repository to fix a problem, and created a pull request.  While I wait for the pull request to be accepted, I have pointed my local package.json at my forked repo, like so:

devDependencies: {
    "karma-mocha": "maloric/karma-mocha"
}

However it turns out that karma-mocha requires a build step to be executed to generate lib/adapter.js - a vital part of the package.  This file is listed in .gitignore, so does not exist in the repository.  The build step is a grunt task that is normally executed when the package is published to npm, so adapter.js exists in the downloaded npm module.

My question is this: what is the correct way to package a forked, built version of the repository so that I can use it as a dependency?  As far as I can tell, I have the following options:

Build the repository locally, create a .tgz file with the built files, then host this somewhere and point my package.json to that file.

Build the repository locally, alter .gitignore to allow adapter.js, then push to a branch on Github and use that branch as my dependency.

Either of these would work, but I feel like I am missing something.  Does npm have a concept of forked packages?  Not every git repository can be used as a dependency without some sort of build/dist step, so what is the accepted way to do this kind of thing?


问:
How to Remove/Disable Sign Up From Devise
I'm trying to remove/disable the user/sign_up path from Devise. I'm doing this because I don't want random people gaining access to the application. I have it  partly working by  adding the following in routes.rb

```<code>Rails.application.routes.draw do
  devise_scope :user do
    get "/sign_in" => "devise/sessions#new" # custom path to login/sign_in
    get "/sign_up" => "devise/registrations#new", as: "new_user_registration" # custom path to sign_up/registration
  end

...

devise_for :users, :skip => :registration

end
</code>```

However, this breaks <%= link_to "Profile", edit_user_registration_path, class: "btn btn-info btn-flat" %>

which I want to keep so that users can update their profile.
I know it's because of the devise_for :users, :skip => :registration

Is there a solution for this issue?

Running

Devise (4.2.0, 4.1.1, 4.1.0)

Rails 4.2.5

ruby 2.3.0p0 (2015-12-25 revision 53290) [x86_64-linux]

答:
I just had the same issue. My solution is a mix of these answers.

Comment out or remove :registerable in user.rb:

class User < ActiveRecord::Base
  devise :database_authenticatable, #:registerable,
         :recoverable, :rememberable, :trackable, :validatable
end
```

<ol start="2">
<li>Remove the registration paths from <code>devise_for</code> in <code>routes.rb</code>:</li>
</ol>

<pre class="lang-rb prettyprint-override"><code>devise_for :users, :skip => [:registrations], controllers: {
  sessions: 'users/sessions'
}
</code>```

Now Devise will skip all of the registration links from their view and also you no longer have the registration paths on your routes.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to remove/disable the user/sign_up path from Devise. I'm doing this because I don't want random people gaining access to the application. I have it  partly working by  adding the following in routes.rb

Rails.application.routes.draw do
  devise_scope :user do
    get "/sign_in" => "devise/sessions#new" # custom path to login/sign_in
    get "/sign_up" => "devise/registrations#new", as: "new_user_registration" # custom path to sign_up/registration
  end

...

devise_for :users, :skip => :registration

end

However, this breaks <%= link_to "Profile", edit_user_registration_path, class: "btn btn-info btn-flat" %>

which I want to keep so that users can update their profile.
I know it's because of the devise_for :users, :skip => :registration

Is there a solution for this issue?

Running

Devise (4.2.0, 4.1.1, 4.1.0)

Rails 4.2.5

ruby 2.3.0p0 (2015-12-25 revision 53290) [x86_64-linux]

Body:
I just had the same issue. My solution is a mix of these answers.

Comment out or remove :registerable in user.rb:

class User < ActiveRecord::Base
  devise :database_authenticatable, #:registerable,
         :recoverable, :rememberable, :trackable, :validatable
end

Remove the registration paths from devise_for in routes.rb:

devise_for :users, :skip => [:registrations], controllers: {
  sessions: 'users/sessions'
}

Now Devise will skip all of the registration links from their view and also you no longer have the registration paths on your routes.


问:
How to echo <img src with PHP variables as values of the src attribute
I am getting error when I try to echo image in PHP.  Here is my code:

```<code>$sql = "SELECT id, title, filename FROM images";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
    $pathx = "directory/images/";

    echo '
    <img src = "'$pathx'.'$row["filename"]'">
    ';
    //filenames in database end with appropriate image extensions like .png

}
</code>```

And I am getting this error:
    Parse error: syntax error, unexpected '$pathx' (T_VARIABLE), expecting ','
    or ';' in C:\xampp\htdocs\display.php on line 29

I have checked solutions from similar questions from here on Stackoverflow and implemented some of the accepted answers still my problem is not solved.

meanwhile something like the code below works well. So why is the one above not working?

```<code>echo'<img src = "directory/images/girl-g2109_5_720.jpg">';
</code>```

答:
Do like this

```<code>$pathx = "directory/images/";
$file = $row["filename"];

echo '<img src="'.$pathx.$file.'">';
</code>```

Output

```<code><img src="directory/images/girl-g2109_5_720.jpg">
</code>```

Body:
I am getting error when I try to echo image in PHP.  Here is my code:

$sql = "SELECT id, title, filename FROM images";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
    $pathx = "directory/images/";

    echo '

    ';
    //filenames in database end with appropriate image extensions like .png

}

And I am getting this error:
    Parse error: syntax error, unexpected '$pathx' (T_VARIABLE), expecting ','
    or ';' in C:\xampp\htdocs\display.php on line 29

I have checked solutions from similar questions from here on Stackoverflow and implemented some of the accepted answers still my problem is not solved.

meanwhile something like the code below works well. So why is the one above not working?

echo'';

Body:
Do like this

$pathx = "directory/images/";
$file = $row["filename"];

echo '<img src="'.$pathx.$file.'">';

Output

<img src="directory/images/girl-g2109_5_720.jpg">


问:
Converting unicode not working in c#
I am trying to convert unicode character in c# but it is not working

code:

```<code>using System;
using System;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading;

namespace test_request
{
    class MainClass
    {
        public static void Main (string[] args)
        {

            string unicode = "Not Your Boyfriend's Tunic";
            string str = System.Uri.UnescapeDataString(unicode);

            Console.WriteLine (str);
        }
    }
}
</code>```

Ouput:

```<code>Not Your Boyfriend's Tunic
</code>```

But expected output is this

Expected output:

```<code>Not Your Boyfriend's Tunic
</code>```

答:
Use below function:</p>

```<code>HttpUtility.HtmlDecode("Not Your Boyfriend's Tunic");
HttpUtility.HtmlEncode("Not Your Boyfriend's Tunic");
</code>```

Title: Converting unicode not working in c#

Body:
I am trying to convert unicode character in c# but it is not working

code:

using System;
using System;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading;

namespace test_request
{
    class MainClass
    {
        public static void Main (string[] args)
        {

            string unicode = "Not Your Boyfriend's Tunic";
            string str = System.Uri.UnescapeDataString(unicode);

            Console.WriteLine (str);
        }
    }
}

Ouput:

Not Your Boyfriend's Tunic

But expected output is this

Expected output:

Not Your Boyfriend's Tunic

Body:
Use below function:

HttpUtility.HtmlDecode("Not Your Boyfriend&#39;s Tunic");
HttpUtility.HtmlEncode("Not Your Boyfriend's Tunic");


答:
```<code>if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
    $pathx = "directory/images/";
    echo '<img src = "'.$pathx.$row["filename"].'">';
}
</code>```

OR use can also use following way to render img tag

```<code>if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
    $pathx = "directory/images/"; ?>
    <img src = "<?php echo $pathx.$row["filename"] ?>">
<?php } ?>
</code>```

Title: How to echo <img src with PHP variables as values of the src attribute

Body:
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
    $pathx = "directory/images/";
    echo '<img src = "'.$pathx.$row["filename"].'">';
}

OR use can also use following way to render img tag

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
    $pathx = "directory/images/"; ?>
    <img src = "<?php echo $pathx.$row["filename"] ?>">
<?php } ?>


问:
List of Stored Procedures/Functions Mysql Command Line
How can I see the list of the stored procedures or stored functions in mysql command line like show tables; or show databases; commands.

答:
Shows all the stored procedures:

```<code>SHOW PROCEDURE STATUS;
</code>```

Shows all the functions:

```<code>SHOW FUNCTION STATUS;
</code>```

Shows the definition of the specified procedure:

```<code>SHOW CREATE PROCEDURE [PROC_NAME];
</code>```

Shows you all the procedures of the given database:

```<code>SHOW PROCEDURE STATUS WHERE Db = '[db_name]';
</code>```

Body:
Shows all the stored procedures:

SHOW PROCEDURE STATUS;

Shows all the functions:

SHOW FUNCTION STATUS;

Shows the definition of the specified procedure:

SHOW CREATE PROCEDURE [PROC_NAME];

Shows you all the procedures of the given database:

SHOW PROCEDURE STATUS WHERE Db = '[db_name]';


问:
ASP.NET MVC - Find Absolute Path to the App_Data folder from Controller
What is the correct way to find the absolute path to the App_Data folder from a Controller in an ASP.NET MVC project? I'd like to be able to temporarily work with an .xml file and I don't want to hardcode the path.

This does not work:

```<code>[HandleError]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        string path = VirtualPathUtility.ToAbsolute("~/App_Data/somedata.xml");

        //.... do whatever

        return View();
    }

}
</code>```

I think outside of the web context VirtualPathUtility.ToAbsolute() doesn't work.
string path comes back as "C:\App_Data\somedata.xml"

Where should I determine the path of the .xml file in an MVC app?
global.asax and stick it an application-level variable?

答:
```<code>string Index = i;
            string FileName = "Mutton" + Index + ".xml";
            XmlDocument xmlDoc = new XmlDocument();

            var path = Path.Combine(Server.MapPath("~/Content/FilesXML"), FileName);
            xmlDoc.Load(path); // Can use xmlDoc.LoadXml(YourString);
</code>```

<p>this is the best Solution to get the path what is exactly need for now </p>

Body:
What is the correct way to find the absolute path to the App_Data folder from a Controller in an ASP.NET MVC project? I'd like to be able to temporarily work with an .xml file and I don't want to hardcode the path.

This does not work:

[HandleError]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        string path = VirtualPathUtility.ToAbsolute("~/App_Data/somedata.xml");

        //.... do whatever

        return View();
    }

}

I think outside of the web context VirtualPathUtility.ToAbsolute() doesn't work.
string path comes back as "C:\App_Data\somedata.xml"

Where should I determine the path of the .xml file in an MVC app?
global.asax and stick it an application-level variable?

Body:
string Index = i;
            string FileName = "Mutton" + Index + ".xml";
            XmlDocument xmlDoc = new XmlDocument();

            var path = Path.Combine(Server.MapPath("~/Content/FilesXML"), FileName);
            xmlDoc.Load(path); // Can use xmlDoc.LoadXml(YourString);

this is the best Solution to get the path what is exactly need for now


问:
What size should TabBar images be?
I have icons for a tabBar of size 100.

I checked at Apple's Human Interface Guidelines of 2013 and it says the image size should be 30x30 / 60x60.

But as the height of tab bar controller is 50, I kept the size of the image at 50x50.

Now, when I run the project, I see the ugly design below:

Any idea what size images I should use so that the design will be perfect?

Note: I am not writing text also (e.g. Home, Search, etc). The text of the tab button is there in the image itself.

答:
According to the latest Apple Human Interface Guidelines:

In portrait orientation, tab bar icons appear above tab titles. In landscape orientation, the icons and titles appear side-by-side. Depending on the device and orientation, the system displays either a regular or compact tab bar. Your app should include custom tab bar icons for both sizes.

I suggest you to use the above link to understand the full concept. Because apple update it's document in regular interval

Title: What size should TabBar images be?


问:
Dissolving hexmap polygon shape files
I am trying to produce an outline for a hexagonal cartogram by dissolving the inner polygons via the unionSpatialPolygons or aggregate functions. I am getting stray hexs that do not dissolve... a dummy example to show the problem:

```<code># grab a dummy example shape file
library(raster)
g <- getData(name = "GADM", country = "GBR", level = 2)
# par(mar = rep(0,4))
# plot(g)

# create a hexagonal cartogram
# library(devtools)
# install_github("sassalley/hexmapr")
library(hexmapr)
h <- calculate_cell_size(shape = g, seed = 1,
                         shape_details = get_shape_details(g),
                         learning_rate = 0.03, grid_type = 'hexagonal')
i <- assign_polygons(shape = g, new_polygons = h)
par(mar = rep(0,4))
plot(i)
</code>```

```<code># dissolve the polygons to get coastline
library(maptools)
j <- unionSpatialPolygons(SpP = i, IDs = rep(1, length(i)))
par(mar = rep(0,4))
plot(j)

# same result with aggregate in the raster package
k <- aggregate(x = i)
par(mar = rep(0,4))
plot(k)
</code>```

With the shapefile I am actually using (not for the UK) I get even more stray hexagons - some complete - some not.

答:
Suggested solution from Roger Bivand (via an email exchange):

```<code> g1 <- spTransform(x = g, CRSobj = CRS("+init=epsg:27700"))
 # cellsize from calculate_cell_size() above
 h1 <- spsample(x = g1, type="hexagonal", cellsize=38309)
 i2 <- HexPoints2SpatialPolygons(hex = h1)
 j2 <- unionSpatialPolygons(SpP = i2, IDs = rep(1, length(i2)))
 plot(j2)
</code>```

i.e. avoid assign_polygons() in hexmapr and utilize 1) spsample to generate shape positions and 2) HexPoints2SpatialPolygons for the hexagonal grid (both in sp package).

Title: Dissolving hexmap polygon shape files

Body:
I am trying to produce an outline for a hexagonal cartogram by dissolving the inner polygons via the unionSpatialPolygons or aggregate functions. I am getting stray hexs that do not dissolve... a dummy example to show the problem:

# grab a dummy example shape file
library(raster)
g <- getData(name = "GADM", country = "GBR", level = 2)
# par(mar = rep(0,4))
# plot(g)

# create a hexagonal cartogram
# library(devtools)
# install_github("sassalley/hexmapr")
library(hexmapr)
h <- calculate_cell_size(shape = g, seed = 1,
                         shape_details = get_shape_details(g),
                         learning_rate = 0.03, grid_type = 'hexagonal')
i <- assign_polygons(shape = g, new_polygons = h)
par(mar = rep(0,4))
plot(i)

# dissolve the polygons to get coastline
library(maptools)
j <- unionSpatialPolygons(SpP = i, IDs = rep(1, length(i)))
par(mar = rep(0,4))
plot(j)

# same result with aggregate in the raster package
k <- aggregate(x = i)
par(mar = rep(0,4))
plot(k)

With the shapefile I am actually using (not for the UK) I get even more stray hexagons - some complete - some not.

Body:
Suggested solution from Roger Bivand (via an email exchange):

 g1 <- spTransform(x = g, CRSobj = CRS("+init=epsg:27700"))
 # cellsize from calculate_cell_size() above
 h1 <- spsample(x = g1, type="hexagonal", cellsize=38309)
 i2 <- HexPoints2SpatialPolygons(hex = h1)
 j2 <- unionSpatialPolygons(SpP = i2, IDs = rep(1, length(i2)))
 plot(j2)

i.e. avoid assign_polygons() in hexmapr and utilize 1) spsample to generate shape positions and 2) HexPoints2SpatialPolygons for the hexagonal grid (both in sp package).


问:
Angular 2 on edit page , value not set in reactive form array
This is my product-edit-component.ts code. In this I am adding a product and its sizes. Size will be multiple. Product is create.But when i edit product, I want all value will be set to its correspond value from JSON

```<code>export class ProductEditComponent implements OnInit {
    id: number;
    routeId: any;
    returnUrl: string;
    errorMessage: any;
    constructor(
      private http: Http,
      private router: Router,
      private route: ActivatedRoute,
      private productService
      : ProductService,
      private flashMessageService: FlashMessagesService,
      private fb: FormBuilder,

    ) { }

    @Input() product: FormGroup;

    ngOnInit() {
      this.routeId = this.route.params.subscribe(
        params => {
          this.id = +params['id'];
        }
      )
      let postRequest = this.route.params.flatMap((params: Params) =>
      this.productService.getProduct(+params['id']))
      postRequest.subscribe(response =>
        this.product.setValue({
          title: response.json().title,
          description: response.json().description,
          sizes_attributes: response.json().sizes_attributes[0]
        })
      );

      this.returnUrl = this.route.snapshot.queryParams['successUrl'] || '/products'
      this.product = this.fb.group({
        title: ['', [Validators.required, Validators.minLength(5)]],
        description: ['', [Validators.required, Validators.minLength(5)]],
        sizes_attributes: this.fb.array([
          this.fb.group({
            size_number: ['', [Validators.required,Validators.maxLength(5)]],
          })
        ])
      })
    }
</code>```

This function for Add Size from template :

```<code>    initSize() {
      return this.fb.group({
        size_number: ['', [Validators.required,Validators.maxLength(5)]],
      });
    }

    addSize() {
      const control = <FormArray>this.product.controls['sizes_attributes'];
      control.push(this.initSize());
    }
</code>```

This function for remove Size from template :

```<code>    removeSize(i: number) {
      const control = <FormArray>this.product.controls['sizes_attributes'];
      control.removeAt(i);
    }
  }
</code>```

This is template for Edit-Page:

```<code><div class="container">
  <div class="row">
    <div class="col-sm-10">
      <div class="margin-20">
        <h4>Add Product</h4>
      </div>

      <form [formGroup]="product" novalidate (ngSubmit)="update(product)">
        <div class="form-group">
          <label>Title</label>
          <input type="text" class="form-control" formControlName="title">
          <small *ngIf="!product.controls.title.valid" class="text-danger">
            Name is required (minimum 5 characters).
          </small>
        </div>

        <div class="form-group">
          <label>Description</label>
          <input type="text" class="form-control" formControlName="description">
          <small *ngIf="!product.controls.description.valid" class="text-danger">
            Description is required (minimum 5 characters).
          </small>
        </div>

        <div formArrayName="sizes_attributes">
          <div *ngFor="let size of product.controls.sizes_attributes.controls; let i=index" class="panel panel-default">
            <div class="panel-heading">
              <span>Size {{i + 1}}</span>
              <span class="glyphicon glyphicon-remove pull-right" *ngIf="product.controls.sizes_attributes.controls.length > 1" (click)="removeSize(i)">X</span>
            </div>
            <div class="row" [formGroupName]="i">
              <div class="form-group col-md-6">
                <label>Size</label>
                <input type="text" class="form-control" formControlName="size_number">
                <small [hidden]="product.controls.sizes_attributes.controls[i].controls.size_number.valid" class="text-danger">
                  Size is required
                </small>
              </div>
            </div>
          </div>
        </div>

        <div class="margin-20">
          <a (click)="addSize()" style="cursor: default">
            Add another size +
          </a>
        </div>
        <div class="margin-20">
          <button type="submit" class="btn btn-primary pull-right" [disabled]="!product.valid">Submit</button>
        </div>
        <div class="clearfix"></div>

      </form>
    </div>
  </div>
</div>
</code>```

Json Data from API:

```<code>{
    "code": 200,
    "id": 30,
    "title": "43434",
    "description": "343434",
    "created_at": "2017-12-05T10:19:39.316Z",
    "updated_at": "2017-12-05T10:19:39.316Z",
    "user_id": 4,
    "sizes_attributes": [
        {
            "id": 58,
            "size_number": "34",
            "product_id": 30,
            "created_at": "2017-12-05T10:19:39.317Z",
            "updated_at": "2017-12-05T10:19:39.317Z"
        },
        {
            "id": 60,
            "size_number": "77",
            "product_id": 30,
            "created_at": "2017-12-06T04:59:25.318Z",
            "updated_at": "2017-12-06T04:59:25.318Z"
        }
    ]
}
</code>```

Problems:

On the above code title and description is set to product form but sizes data not set to sizes attributes controls form array.
  Please help

答:
```<code>  ngOnInit() {
    this.routeId = this.route.params.subscribe(
      params => {
        this.id = +params['id'];
      }
    )
    let postRequest = this.route.params.flatMap((params: Params) =>
    this.productService.getProduct(+params['id']))
    postRequest.subscribe(response =>
      this.product.setValue({
        title: response.json().title,
        description: response.json().description,
        sizes_attributes: this.get_sizes(response.json().sizes_attributes),
      })
    );

    this.returnUrl = this.route.snapshot.queryParams['successUrl'] || '/products'
    this.product = this.fb.group({
      title: ['', [Validators.required, Validators.minLength(5)]],
      description: ['', [Validators.required, Validators.minLength(5)]],
      sizes_attributes: this.fb.array([

      ])
    })
  }
</code>```

Get Sizes method for Add size value from existing database

```<code>  get_sizes(sizes){
     const control = <FormArray>this.product.controls['sizes_attributes']
    sizes.forEach((size, i) => {

       control.push(this.fb.group({
         id: size.id,
         size_number: [size.size_number, [Validators.required,Validators.maxLength(5)]],
         _destroy: '',
       })
     )
      })
      return control
  }
</code>```

Body:
This is my product-edit-component.ts code. In this I am adding a product and its sizes. Size will be multiple. Product is create.But when i edit product, I want all value will be set to its correspond value from JSON

export class ProductEditComponent implements OnInit {
    id: number;
    routeId: any;
    returnUrl: string;
    errorMessage: any;
    constructor(
      private http: Http,
      private router: Router,
      private route: ActivatedRoute,
      private productService
      : ProductService,
      private flashMessageService: FlashMessagesService,
      private fb: FormBuilder,

    ) { }

    @Input() product: FormGroup;

    ngOnInit() {
      this.routeId = this.route.params.subscribe(
        params => {
          this.id = +params['id'];
        }
      )
      let postRequest = this.route.params.flatMap((params: Params) =>
      this.productService.getProduct(+params['id']))
      postRequest.subscribe(response =>
        this.product.setValue({
          title: response.json().title,
          description: response.json().description,
          sizes_attributes: response.json().sizes_attributes[0]
        })
      );

      this.returnUrl = this.route.snapshot.queryParams['successUrl'] || '/products'
      this.product = this.fb.group({
        title: ['', [Validators.required, Validators.minLength(5)]],
        description: ['', [Validators.required, Validators.minLength(5)]],
        sizes_attributes: this.fb.array([
          this.fb.group({
            size_number: ['', [Validators.required,Validators.maxLength(5)]],
          })
        ])
      })
    }

This function for Add Size from template :

    initSize() {
      return this.fb.group({
        size_number: ['', [Validators.required,Validators.maxLength(5)]],
      });
    }

    addSize() {
      const control = <FormArray>this.product.controls['sizes_attributes'];
      control.push(this.initSize());
    }

This function for remove Size from template :

    removeSize(i: number) {
      const control = <FormArray>this.product.controls['sizes_attributes'];
      control.removeAt(i);
    }
  }

This is template for Edit-Page:

Add Product

      <form [formGroup]="product" novalidate (ngSubmit)="update(product)">

          Title
          <input type="text" class="form-control" formControlName="title">

            Name is required (minimum 5 characters).

          Description
          <input type="text" class="form-control" formControlName="description">

            Description is required (minimum 5 characters).

              Size {{i + 1}}
               1" (click)="removeSize(i)">X

                Size
                <input type="text" class="form-control" formControlName="size_number">

                  Size is required

            Add another size +

          <button type="submit" class="btn btn-primary pull-right" [disabled]="!product.valid">Submit</button>

      </form>

Json Data from API:

{
    "code": 200,
    "id": 30,
    "title": "43434",
    "description": "343434",
    "created_at": "2017-12-05T10:19:39.316Z",
    "updated_at": "2017-12-05T10:19:39.316Z",
    "user_id": 4,
    "sizes_attributes": [
        {
            "id": 58,
            "size_number": "34",
            "product_id": 30,
            "created_at": "2017-12-05T10:19:39.317Z",
            "updated_at": "2017-12-05T10:19:39.317Z"
        },
        {
            "id": 60,
            "size_number": "77",
            "product_id": 30,
            "created_at": "2017-12-06T04:59:25.318Z",
            "updated_at": "2017-12-06T04:59:25.318Z"
        }
    ]
}

Problems:

On the above code title and description is set to product form but sizes data not set to sizes attributes controls form array.
  Please help

Body:
  ngOnInit() {
    this.routeId = this.route.params.subscribe(
      params => {
        this.id = +params['id'];
      }
    )
    let postRequest = this.route.params.flatMap((params: Params) =>
    this.productService.getProduct(+params['id']))
    postRequest.subscribe(response =>
      this.product.setValue({
        title: response.json().title,
        description: response.json().description,
        sizes_attributes: this.get_sizes(response.json().sizes_attributes),
      })
    );

    this.returnUrl = this.route.snapshot.queryParams['successUrl'] || '/products'
    this.product = this.fb.group({
      title: ['', [Validators.required, Validators.minLength(5)]],
      description: ['', [Validators.required, Validators.minLength(5)]],
      sizes_attributes: this.fb.array([

      ])
    })
  }

Get Sizes method for Add size value from existing database

  get_sizes(sizes){
     const control = <FormArray>this.product.controls['sizes_attributes']
    sizes.forEach((size, i) => {

       control.push(this.fb.group({
         id: size.id,
         size_number: [size.size_number, [Validators.required,Validators.maxLength(5)]],
         _destroy: '',
       })
     )
      })
      return control
  }


问:
Add gitparameter in jenkins pipeline
I need the userInput when executing the pipeline.
The input will be the git branch of a particular repository.
As we can configure gitparameter in the jenkins job how do we configure it in the jenkins pipeline.
I have got the pipeline code as follows
>

```<code>   stage 'promotion'
   def userInput = input(
   id: 'userInput', message: 'Let\'s promote?', parameters: [
   [$class: 'GitParameterDefinition', description: 'Environment', name: 'env',type: 'Branch'],
   [$class: 'TextParameterDefinition', defaultValue: 'uat1', description: 'Target', name: 'target']
])
  echo ("Env: "+userInput['env'])
  echo ("Target: "+userInput['target'])
</code>```

All I get is an empty input box how do I configure it with the git repository in the pipeline itself.

答:
You can do it as follow:</p>

```<code>node {
stage ('input') {

   def userInput = input message: 'enter git details',
     parameters: [
     string(defaultValue: 'dev', description: 'branch name', name: 'branch'),
     string(defaultValue: '', description: 'repo url', name: 'url')
     ]

    git branch: userInput['branch'], credentialsId: 'creds', url: userInput['url']
   }
}
</code>```

Title: Add gitparameter in jenkins pipeline

Body:
I need the userInput when executing the pipeline.
The input will be the git branch of a particular repository.
As we can configure gitparameter in the jenkins job how do we configure it in the jenkins pipeline.
I have got the pipeline code as follows
>

   stage 'promotion'
   def userInput = input(
   id: 'userInput', message: 'Let\'s promote?', parameters: [
   [$class: 'GitParameterDefinition', description: 'Environment', name: 'env',type: 'Branch'],
   [$class: 'TextParameterDefinition', defaultValue: 'uat1', description: 'Target', name: 'target']
])
  echo ("Env: "+userInput['env'])
  echo ("Target: "+userInput['target'])

All I get is an empty input box how do I configure it with the git repository in the pipeline itself.

Body:
You can do it as follow:

node {
stage ('input') {

   def userInput = input message: 'enter git details',
     parameters: [
     string(defaultValue: 'dev', description: 'branch name', name: 'branch'),
     string(defaultValue: '', description: 'repo url', name: 'url')
     ]

    git branch: userInput['branch'], credentialsId: 'creds', url: userInput['url']
   }
}


问:
VsTac task failed, could not find file appAsTgz.tgz when using global Cordova toolset
When I use my globally installed Cordova 7.1.0 toolset and do an iOS remote build (to simulator or to Local Device), I almost immediately get the error message:

```<code>Error   MSB4018 The "VsTac" task failed unexpectedly.
System.IO.FileNotFoundException: Could not find file 'C:\Users\joe\AppData\Local\Temp\appAsTgz.tgz'.
File name: 'C:\Users\joe\AppData\Local\Temp\appAsTgz.tgz'
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy)
   at System.IO.FileStream..ctor(String path, FileMode mode)
   at Microsoft.VisualStudio.MultiDeviceHybridApps.MdaBuildTasks.RemoteBuild.AppAsTgzStream(String changeTimeFile, JObject lastChangeTimesMap)
   at Microsoft.VisualStudio.MultiDeviceHybridApps.MdaBuildTasks.RemoteBuild.Build()
   at Microsoft.VisualStudio.MultiDeviceHybridApps.MdaBuildTasks.VsTac.BuildPlatform()
   at Microsoft.VisualStudio.MultiDeviceHybridApps.MdaBuildTasks.VsTac.Execute()
   at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
   at Microsoft.Build.BackEnd.TaskBuilder.<ExecuteInstantiatedTask>d__26.MoveNext() MyFleetGoTest   C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\Microsoft\VisualStudio\v15.0\ApacheCordovaTools\vs-mda-targets\Microsoft.MDA.FileMirroring.targets 256
</code>```

I can do iOS and Android browser builds.  I can change the toolset to <vs:toolsetVersion>6.3.1</vs:toolsetVersion> and the error goes away and the message succeeds.

Is it possible to use the global Cordova 7.1.0 install instead of the VS TACO 6.3.1 toolset and get working iOS remote builds?  This is with Visual Studio 2017.

答:
Latest way to compile for iOS using Cordova and Visual Studio 2017 (15.5)

In Mac OS:

Install Xcode 9.*

Install Node.JS 6.*. (https://nodejs.org/dist/latest-v6.x/) - Newer NPM version doesn't work for now.

Install Xcode components via terminal:
  xcode-select -–install

Install "remotebuild" Microsoft tool for remote compile from Visual Studio (Windows):
  sudo npm install -g remotebuild

Install COCOA Pods (needed by newer Cordova 7.1.0):
  sudo gem install cocoapods

Setup COCOA Pods for your first use just running command (about 680 MB to download):
  pod setup

  - Set permissions:

sudo chown -R $USER:$GROUP ~/.npm

sudo chown -R $USER:$GROUP ~/.config

Start remotebuild to start listen:
  remotebuild

In Windows:

Install newer Visual Studio 2017 (15.5)...

Install Node.JS 6.*. (https://nodejs.org/dist/latest-v6.x/) - Newer NPM version doesn't work for now.

Install Global Cordova version (compatible with newer platforms and iOS versions):
  npm install -g cordova

Until now the VS 2017 has a bug (https://developercommunity.visualstudio.com/content/problem/94814/vs-153-cordova-cannot-use-global-cordova-anymore.html) when Cordova project loads the VS force set to use Cordova Toolset 6.3.1. To solve it (workaround):

Change the follow line in config.xml (open using xml editor):

From

<vs:toolsetVersion>6.3.1</vs:toolsetVersion>

To

<vs:toolsetVersion>GlobalCordovaVersion</vs:toolsetVersion>

Remove the follow lines from config.xml (open using xml editor):

<engine name="android" spec="5.2.1" /> //if the file has another line with a newer version

<engine name="ios" spec="4.2.0" /> //if the file has another line with a newer version

<engine name="windows" spec="4.4.2" /> //if the file has another line with a newer version

<preference name="windows-target-version" value="10.0" /> //if the file has another line with a newer version

Setup Visual Studio (Tools > Options > Tools For Apache Cordova) with the config generated by remotebuild (running in Mac OS). Screen example:
Remote Agent Output

Tip: Try a ping before configure. If you have a problem, use IP instead computer name.

Build. You can locate your *.ipa file in bin\iOS\Debug folder.

Body:
When I use my globally installed Cordova 7.1.0 toolset and do an iOS remote build (to simulator or to Local Device), I almost immediately get the error message:

Error   MSB4018 The "VsTac" task failed unexpectedly.
System.IO.FileNotFoundException: Could not find file 'C:\Users\joe\AppData\Local\Temp\appAsTgz.tgz'.
File name: 'C:\Users\joe\AppData\Local\Temp\appAsTgz.tgz'
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy)
   at System.IO.FileStream..ctor(String path, FileMode mode)
   at Microsoft.VisualStudio.MultiDeviceHybridApps.MdaBuildTasks.RemoteBuild.AppAsTgzStream(String changeTimeFile, JObject lastChangeTimesMap)
   at Microsoft.VisualStudio.MultiDeviceHybridApps.MdaBuildTasks.RemoteBuild.Build()
   at Microsoft.VisualStudio.MultiDeviceHybridApps.MdaBuildTasks.VsTac.BuildPlatform()
   at Microsoft.VisualStudio.MultiDeviceHybridApps.MdaBuildTasks.VsTac.Execute()
   at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
   at Microsoft.Build.BackEnd.TaskBuilder.<ExecuteInstantiatedTask>d__26.MoveNext() MyFleetGoTest   C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\Microsoft\VisualStudio\v15.0\ApacheCordovaTools\vs-mda-targets\Microsoft.MDA.FileMirroring.targets 256

I can do iOS and Android browser builds.  I can change the toolset to <vs:toolsetVersion>6.3.1</vs:toolsetVersion> and the error goes away and the message succeeds.

Is it possible to use the global Cordova 7.1.0 install instead of the VS TACO 6.3.1 toolset and get working iOS remote builds?  This is with Visual Studio 2017.


问:
How to equal two different ids from another table?
```<code>select student.student_fname,
student.student_mname,
student.student_lname, logs.time, logs.transaction,logs.entity_type,prof.professor_fname,prof.professor_mname,prof.professor_lname
from student_tbl as student,
logs_tbl as logs,
professor_tbl as prof
where student.student_id=logs.entity_id
and prof.professor_id=logs.entity_id
and logs.date ='$date_today'
and logs.course_id='$course'
and logs.sections_id='$sections'
and logs.rooms_id='$room'
group by logs.date,
logs.term,
logs.course_id,
logs.entity_id
order by logs.logs_id asc
</code>```

In student_tbl and professor_tbl I have student_id and professor_id that is equal to the entity_id of logs_tbl. How do i compare those two id from different tables to entity_id in logs_tbl? it is the only line that is giving me error. or maybe you have a suggestion? aside from sql injection stuff

UPDATE

i have student_tbl the columns there are: student_id, student_fname, student_mname, student_lname. i also have professor_tbl and the columns there are: professor_id, professor_fname, professor_mname, professor_lname, and my third table which has all the basis is the logs_tbl the columns there are: entity_id(this is where student_id and professor_id will equate), course_id,rooms_id,sections_id,time,date,transaction,entity_type.
This is what i want to display:

student_fname/professor_fname (depending on the entity_id)

student_mname/professor_mname (depending on the entity_id)

student_lname/professor_lname (depending on the entity_id)

time

transaction

entity_type

Sample data display:

Kris | Consta | Roca | 11:30 | in | student

Bob | Jones | Marley | 11:32 | in | student

Ronald | James | Leon | 11:35 | in | professor

Kris | Consta | Roca | 1:00 | out | student

Bob | Jones | Marley | 1:05 | out | student

Ronald | James | Leon | 1:06 | out | professor

答:
```<code>select student.student_fname,student.student_mname,student.student_lname, logs.time, logs.transaction,logs.entity_type,prof.professor_fname,prof.professor_mname,prof.professor_lname
from student_tbl as student
join logs_tbl as logs on student.student_id=logs.entity_id and logs.date ='$date_today' and logs.course_id='$course' and logs.sections_id='$sections' and logs.rooms_id='$room'
join professor_tbl as prof on prof.professor_id=logs.entity_id
group by logs.date, logs.term, logs.course_id, logs.entity_id
order by logs.logs_id asc
</code>```

You can do it using join.

Body:
select student.student_fname,
student.student_mname,
student.student_lname, logs.time, logs.transaction,logs.entity_type,prof.professor_fname,prof.professor_mname,prof.professor_lname
from student_tbl as student,
logs_tbl as logs,
professor_tbl as prof
where student.student_id=logs.entity_id
and prof.professor_id=logs.entity_id
and logs.date ='$date_today'
and logs.course_id='$course'
and logs.sections_id='$sections'
and logs.rooms_id='$room'
group by logs.date,
logs.term,
logs.course_id,
logs.entity_id
order by logs.logs_id asc

In student_tbl and professor_tbl I have student_id and professor_id that is equal to the entity_id of logs_tbl. How do i compare those two id from different tables to entity_id in logs_tbl? it is the only line that is giving me error. or maybe you have a suggestion? aside from sql injection stuff

UPDATE

i have student_tbl the columns there are: student_id, student_fname, student_mname, student_lname. i also have professor_tbl and the columns there are: professor_id, professor_fname, professor_mname, professor_lname, and my third table which has all the basis is the logs_tbl the columns there are: entity_id(this is where student_id and professor_id will equate), course_id,rooms_id,sections_id,time,date,transaction,entity_type.
This is what i want to display:

student_fname/professor_fname (depending on the entity_id)

student_mname/professor_mname (depending on the entity_id)

student_lname/professor_lname (depending on the entity_id)

time

transaction

entity_type

Sample data display:

Kris | Consta | Roca | 11:30 | in | student

Bob | Jones | Marley | 11:32 | in | student

Ronald | James | Leon | 11:35 | in | professor

Kris | Consta | Roca | 1:00 | out | student

Bob | Jones | Marley | 1:05 | out | student

Ronald | James | Leon | 1:06 | out | professor

Body:
select student.student_fname,student.student_mname,student.student_lname, logs.time, logs.transaction,logs.entity_type,prof.professor_fname,prof.professor_mname,prof.professor_lname
from student_tbl as student
join logs_tbl as logs on student.student_id=logs.entity_id and logs.date ='$date_today' and logs.course_id='$course' and logs.sections_id='$sections' and logs.rooms_id='$room'
join professor_tbl as prof on prof.professor_id=logs.entity_id
group by logs.date, logs.term, logs.course_id, logs.entity_id
order by logs.logs_id asc

You can do it using join.


问:
Why col-4 and col-8 are not in the same line without any CSS?

I have two columns, col-4 and col-8 inside col-12 and row. But the two columns are not in the same row. I am not able to understand why this is happening even when I am not writing any CSS just the bootstrap grid.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">

Home

About

Portfolio

Contact

```

答:
Every column needs a row parent in Bootstrap.

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>

Home

About

Portfolio

Contact

```

Body:
Every column needs a row parent in Bootstrap.

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container-fluid">
  <div class="row" id="first_row">
    <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
      <!-- Row added here. -->
      <div class="row">
        <div class="col-lg-4 col-md-4 col-sm-4 col-xs-4">
          <img src="//placehold.it/64x64" class="img-fluid" alt="Responsive image" id="avater_main">
        </div>
        <div class="col-lg-8 col-md-8 col-sm-8 col-xs-8">
         <!-- And a row here. -->
          <div class="row">
            <div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">Home</div>
            <div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">About</div>
            <div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">Portfolio</div>
            <div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">Contact</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>


问:
Table View Cells Not Selectable After Resigning UITextView as First Responder
I have a UITextView in a UITableViewCell. I have set it to become first responder when the cell is selected as so:

```<code>TPNTableViewCell *thisCell = (TPNTableViewCell *)[tblMain cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];

thisCell.txtHidden.text=@"";
[thisCell.txtHidden becomeFirstResponder];

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(goAwayKeyboard)];
[self.view addGestureRecognizer:tap];
</code>```

So when the cell is selected txtHidden becomes first responder. And then the selector goAwayKeyboard is triggered when you click out of the keyboard.

```<code>-(void)goAwayKeyboard
{
    TPNTableViewCell *thisCell = (TPNTableViewCell *)[tblMain cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    [thisCell.txtHidden resignFirstResponder];
}
</code>```

This works, however after the keyboard is resigned I can no longer select a cell in the table view. I can scroll the table view, but the cells aren't selectable and I can't figure out why.

答:
You should disable the tap gesture in go away keyboard, You can do this with the help of below code,</p>

```<code>tap.enabled = NO;
</code>```

Body:
I have a UITextView in a UITableViewCell. I have set it to become first responder when the cell is selected as so:

TPNTableViewCell *thisCell = (TPNTableViewCell *)[tblMain cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];

thisCell.txtHidden.text=@"";
[thisCell.txtHidden becomeFirstResponder];

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(goAwayKeyboard)];
[self.view addGestureRecognizer:tap];

So when the cell is selected txtHidden becomes first responder. And then the selector goAwayKeyboard is triggered when you click out of the keyboard.

-(void)goAwayKeyboard
{
    TPNTableViewCell *thisCell = (TPNTableViewCell *)[tblMain cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    [thisCell.txtHidden resignFirstResponder];
}

This works, however after the keyboard is resigned I can no longer select a cell in the table view. I can scroll the table view, but the cells aren't selectable and I can't figure out why.

Body:
You should disable the tap gesture in go away keyboard, You can do this with the help of below code,

tap.enabled = NO;


问:
App crashes when i use Cursor method to get data from SQlite
This is my code, the Cursor cursor= db.rawQuery is the reason. My app keep crashing

please tell me what's wrong:-

```<code>public QuestionController(Context context) {
    dbHelper= new DBHelper(context);
}

//Lấy danh sách câu hỏi
public ArrayList<Question> getQuestion(int num_exam, String subject){
    ArrayList<Question> lsData= new ArrayList<Question>();
    SQLiteDatabase db= dbHelper.getReadableDatabase();

    Cursor cursor= db.rawQuery("SELECT * FROM tracnghiem WHERE num_exam = '"+ num_exam+"' AND subject='"+subject+"' ORDER BY random()",null);
    cursor.moveToFirst();
    do {
        Question item;
        item= new Question(cursor.getInt(0), cursor.getString(1),cursor.getString(2),cursor.getString(3),
                cursor.getString(4),cursor.getString(5),cursor.getString(6),cursor.getInt(7),cursor.getString(8),cursor.getString(9),"");
        lsData.add(item);
    }while (cursor.moveToNext());
    cursor.close();
    return lsData;
</code>```

答:
Not that it is definitely the issue, but you should not assume that the Cursor is not empty by not checking the result of the moveToFirst method. That is moveToFist will return false if the move cannot be made e.g. if the Cursor is empty.

If the cursor is empty the moveToFist will not fail BUT an attempt to retrieve data via a get???? method will then fail with a row index error as you are attempting to access row 0 of the cursor when there isn't a row 0.

Again not that it is definitely the error you are experiencing. However you should replace :-

```<code>cursor.moveToFirst();
do {
    Question item;
    item= new Question(cursor.getInt(0), cursor.getString(1),cursor.getString(2),cursor.getString(3),
            cursor.getString(4),cursor.getString(5),cursor.getString(6),cursor.getInt(7),cursor.getString(8),cursor.getString(9),"");
    lsData.add(item);
}while (cursor.moveToNext());
cursor.close();
</code>```

with something like (this will loop through the cursor if it is not empty, and not fail if the cursor is empty) :-

```<code>while (cursor.moveToNext) {
    Question item;
    item= new Question(cursor.getInt(0), cursor.getString(1),cursor.getString(2),cursor.getString(3),
            cursor.getString(4),cursor.getString(5),cursor.getString(6),cursor.getInt(7),cursor.getString(8),cursor.getString(9),"");
    lsData.add(item);
}
cursor.close();
</code>```

Noting that lsData will have no elements should the Cursor itself be empty. You could add something, after cursor.close() and before return lsData along the lines of :-

```<code>if (lsData.size) < 1) {
    lsData.add(new Question(0,"Empty Cursor","","","","","",0,"".""."");
}
</code>```

It could then be easy to see if the Cursor was empty.

Body:
This is my code, the Cursor cursor= db.rawQuery is the reason. My app keep crashing

please tell me what's wrong:-

public QuestionController(Context context) {
    dbHelper= new DBHelper(context);
}

//Lấy danh sách câu hỏi
public ArrayList<Question> getQuestion(int num_exam, String subject){
    ArrayList<Question> lsData= new ArrayList<Question>();
    SQLiteDatabase db= dbHelper.getReadableDatabase();

    Cursor cursor= db.rawQuery("SELECT * FROM tracnghiem WHERE num_exam = '"+ num_exam+"' AND subject='"+subject+"' ORDER BY random()",null);
    cursor.moveToFirst();
    do {
        Question item;
        item= new Question(cursor.getInt(0), cursor.getString(1),cursor.getString(2),cursor.getString(3),
                cursor.getString(4),cursor.getString(5),cursor.getString(6),cursor.getInt(7),cursor.getString(8),cursor.getString(9),"");
        lsData.add(item);
    }while (cursor.moveToNext());
    cursor.close();
    return lsData;

Body:
Not that it is definitely the issue, but you should not assume that the Cursor is not empty by not checking the result of the moveToFirst method. That is moveToFist will return false if the move cannot be made e.g. if the Cursor is empty.

If the cursor is empty the moveToFist will not fail BUT an attempt to retrieve data via a get???? method will then fail with a row index error as you are attempting to access row 0 of the cursor when there isn't a row 0.

Again not that it is definitely the error you are experiencing. However you should replace :-

cursor.moveToFirst();
do {
    Question item;
    item= new Question(cursor.getInt(0), cursor.getString(1),cursor.getString(2),cursor.getString(3),
            cursor.getString(4),cursor.getString(5),cursor.getString(6),cursor.getInt(7),cursor.getString(8),cursor.getString(9),"");
    lsData.add(item);
}while (cursor.moveToNext());
cursor.close();

with something like (this will loop through the cursor if it is not empty, and not fail if the cursor is empty) :-

while (cursor.moveToNext) {
    Question item;
    item= new Question(cursor.getInt(0), cursor.getString(1),cursor.getString(2),cursor.getString(3),
            cursor.getString(4),cursor.getString(5),cursor.getString(6),cursor.getInt(7),cursor.getString(8),cursor.getString(9),"");
    lsData.add(item);
}
cursor.close();

Noting that lsData will have no elements should the Cursor itself be empty. You could add something, after cursor.close() and before return lsData along the lines of :-

if (lsData.size) < 1) {
    lsData.add(new Question(0,"Empty Cursor","","","","","",0,"".""."");
}

It could then be easy to see if the Cursor was empty.


问:
Calculations by Subgroup in a Column
I have a dataset that looks approximately like this:

```<code>> dataSet
   month detrend
1    Jan  315.71
2    Jan  317.45
3    Jan   317.5
4    Jan   317.1
5    Jan  315.71
6    Feb  317.45
7    Feb   313.5
8    Feb   317.1
9    Feb  314.37
10   Feb  315.41
11 March  316.44
12 March  315.73
13 March  318.73
14 March  315.55
15 March  312.64
.
.
.
</code>```

How do I compute the average by month?  E.g., I want something like

```<code>> by_month
   month ave_detrend
1    Jan  315.71
2    Feb  317.45
3  March   317.5
</code>```

答:
R has an inbuilt mean function: mean(x, trim = 0, na.rm = FALSE, ...)

I would do something like this:

```<code>january <- dataset[dataset[, "month"] == "january",]
januaryVector <- january[, "detrend"]
januaryAVG <- mean(januaryVector)
</code>```

Title: Calculations by Subgroup in a Column

Body:
I have a dataset that looks approximately like this:

> dataSet
   month detrend
1    Jan  315.71
2    Jan  317.45
3    Jan   317.5
4    Jan   317.1
5    Jan  315.71
6    Feb  317.45
7    Feb   313.5
8    Feb   317.1
9    Feb  314.37
10   Feb  315.41
11 March  316.44
12 March  315.73
13 March  318.73
14 March  315.55
15 March  312.64
.
.
.

How do I compute the average by month?  E.g., I want something like

> by_month
   month ave_detrend
1    Jan  315.71
2    Feb  317.45
3  March   317.5

Body:
R has an inbuilt mean function: mean(x, trim = 0, na.rm = FALSE, ...)

I would do something like this:

january <- dataset[dataset[, "month"] == "january",]
januaryVector <- january[, "detrend"]
januaryAVG <- mean(januaryVector)


问:
How can I display the three level div in turn by using z-index?
The html code is as follow:

```<code><div class="first common">
    i am the first div.
    <div class="second common">
        i am the second div.
        <div class="third common">
            i am the third div.
        </div>
    </div>
</div>
</code>```

css:

```<code>.common {
    position: absolute;
    left: 50px;
    top: 50px;
    width: 200px;
    height: 200px;
    color: #fff;
}
.first {
    background-color: #8EE5EE;
}
.second {
    background-color: #7A67EE;
}
.third {
    background-color: #0000AA;
}
</code>```

The results are as follows

And now I want to put the first div in the front, the second div in the middle and the third div at the back (reverse) by using z-index if I could .
But I don't know how to do.

答:
Try this.
I wrapped it in wrapper class. and reverse the left and top position of common class. no need to use z-index.

.wrapper {
    position: absolute;
    left: 200px;
    top: 200px;
}

.common {
    position: absolute;
    left: -50px;
    top: -50px;
    width: 200px;
    height: 200px;
    color: #fff;
}
.first {
    background-color: #0000AA;
}
.second {
    background-color: #7A67EE;
}
.third {
    background-color: #8EE5EE;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
<div class="first common">
    <div class="second common">
       <div class="third common">
       </div>
    </div>
</div>
</div></code>```

Body:
The html code is as follow:

    i am the first div.

        i am the second div.

            i am the third div.

css:

.common {
    position: absolute;
    left: 50px;
    top: 50px;
    width: 200px;
    height: 200px;
    color: #fff;
}
.first {
    background-color: #8EE5EE;
}
.second {
    background-color: #7A67EE;
}
.third {
    background-color: #0000AA;
}

The results are as follows

And now I want to put the first div in the front, the second div in the middle and the third div at the back (reverse) by using z-index if I could .
But I don't know how to do.

Body:
Try this.
I wrapped it in wrapper class. and reverse the left and top position of common class. no need to use z-index.

.wrapper {
    position: absolute;
    left: 200px;
    top: 200px;
}

.common {
    position: absolute;
    left: -50px;
    top: -50px;
    width: 200px;
    height: 200px;
    color: #fff;
}
.first {
    background-color: #0000AA;
}
.second {
    background-color: #7A67EE;
}
.third {
    background-color: #8EE5EE;
}

<div class="wrapper">
<div class="first common">
    <div class="second common">
       <div class="third common">
       </div>
    </div>
</div>
</div>


问:
Django: Calculate the Sum of the column values through query
I have a model:

```<code>class ItemPrice(models.Model):
     price = models.DecimalField(max_digits=8, decimal_places=2)
     # ...
</code>```

I tried this to calculate the sum of price in this queryset:

```<code>items = ItemPrice.objects.all().annotate(Sum('price'))
</code>```

What's wrong in this query? or is there any other way to calculate the Sum of price column?

I know this can be done by using for loop on queryset but i need an elegant solution.

Thanks!

答:
Use .aggregate(Sum('column'))['column__sum'] reefer my example below

```<code>sum = Sale.objects.filter(type='Flour').aggregate(Sum('column'))['column__sum']
</code>```

Body:
I have a model:

class ItemPrice(models.Model):
     price = models.DecimalField(max_digits=8, decimal_places=2)
     # ...

I tried this to calculate the sum of price in this queryset:

items = ItemPrice.objects.all().annotate(Sum('price'))

What's wrong in this query? or is there any other way to calculate the Sum of price column?

I know this can be done by using for loop on queryset but i need an elegant solution.

Thanks!

Body:
Use .aggregate(Sum('column'))['column__sum'] reefer my example below

sum = Sale.objects.filter(type='Flour').aggregate(Sum('column'))['column__sum']


问:
How can i fix my json output?
I have an issue to decode the json that i receive from CURL,
i used json_last_error to see what may be the reason and it looks like my json is malformed.

```<code>        // Make the REST call, returning the result
        $response = curl_exec($this->curl); // result is as per screenshot below

        $resp_json = json_decode($response, true);

        echo "```";
        print_r($resp_json); // display nothing
        echo "```";
</code>```

Click here to see the json output and the issue

from jsonlint, response is like...

```<code>{
    "RESPONSE_DATA": [{
                "property_address": "6\/192 Kingsgrove Road",
                "price": 0.0,
                "contact_name": "Nicholas Smith",
                "property_facing_direction": "unknown",
                "agent_name": "",
                "client_id": 46984,
                "property_suburb": "Kingsgrove",
                "agent_phone": "",
                "contact_phone": "0407 787 288",
                "ordered_datetime": "2017-12-05 04:15:03",
                "agent_email": "",
                "property_state": "NSW",
                "job_id": 2324,
                "im_job_id": "40432-o",
                "product_ids": 3000000,
                "confirmed_datetime": "",
                "photographer_comment": "Photography Premium Daylight 3 photos  $145.00\
                nAdd Per Premium Photo 2 at $20 .00 each\ n Total $185 .00 ","
                contact_company ":"
                Raine & Horne Commerical - Marrickville ","
                agent_id ":"
                ","
                preferred_datetime ":"
                2017 - 12 - 07 11: 00: 00 ","
                property_postcode ":0000,"
                status_code ":"
                N "}],"
                RESPONSE_MESSAGE ":"
                OK ","
                RESPONSE_CODE ":200}
</code>```

答:
There are 4 issues broking the json:

Unexpected newline

\n in photographer_comment

\ n in photographer_comment

property_postcode ":0000

That you can hardcode to replace it by:

```<code>$json = trim(preg_replace('/\s+/', ' ', $json));
$json = str_replace("\\n", "", $json);
$json = str_replace("\\ n", "", $json);
$json = str_replace(":0000", ":\"0000\"", $json);
</code>```

It's quick and dirty, and not covering other cases; you can try regex if you want to use a more general way. But I think it would be more reasonable to fix it at the data provider side.

Besides above, some keys' name are not good due to the tailing empty space, such as: "preferred_datetime "

Title: How can i fix my json output?

Body:
I have an issue to decode the json that i receive from CURL,
i used json_last_error to see what may be the reason and it looks like my json is malformed.

        // Make the REST call, returning the result
        $response = curl_exec($this->curl); // result is as per screenshot below

        $resp_json = json_decode($response, true);

        echo "
";
        print_r($resp_json); // display nothing
        echo "
";

Click here to see the json output and the issue

from jsonlint, response is like...

{
    "RESPONSE_DATA": [{
                "property_address": "6\/192 Kingsgrove Road",
                "price": 0.0,
                "contact_name": "Nicholas Smith",
                "property_facing_direction": "unknown",
                "agent_name": "",
                "client_id": 46984,
                "property_suburb": "Kingsgrove",
                "agent_phone": "",
                "contact_phone": "0407 787 288",
                "ordered_datetime": "2017-12-05 04:15:03",
                "agent_email": "",
                "property_state": "NSW",
                "job_id": 2324,
                "im_job_id": "40432-o",
                "product_ids": 3000000,
                "confirmed_datetime": "",
                "photographer_comment": "Photography Premium Daylight 3 photos  $145.00\
                nAdd Per Premium Photo 2 at $20 .00 each\ n Total $185 .00 ","
                contact_company ":"
                Raine & Horne Commerical - Marrickville ","
                agent_id ":"
                ","
                preferred_datetime ":"
                2017 - 12 - 07 11: 00: 00 ","
                property_postcode ":0000,"
                status_code ":"
                N "}],"
                RESPONSE_MESSAGE ":"
                OK ","
                RESPONSE_CODE ":200}

Body:
There are 4 issues broking the json:

Unexpected newline

\n in photographer_comment

\ n in photographer_comment

property_postcode ":0000

That you can hardcode to replace it by:

$json = trim(preg_replace('/\s+/', ' ', $json));
$json = str_replace("\\n", "", $json);
$json = str_replace("\\ n", "", $json);
$json = str_replace(":0000", ":\"0000\"", $json);

It's quick and dirty, and not covering other cases; you can try regex if you want to use a more general way. But I think it would be more reasonable to fix it at the data provider side.

Besides above, some keys' name are not good due to the tailing empty space, such as: "preferred_datetime "


问:
How to echo <img src with PHP variables as values of the src attribute
I am getting error when I try to echo image in PHP.  Here is my code:

```<code>$sql = "SELECT id, title, filename FROM images";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
    $pathx = "directory/images/";

    echo '
    <img src = "'$pathx'.'$row["filename"]'">
    ';
    //filenames in database end with appropriate image extensions like .png

}
</code>```

And I am getting this error:
    Parse error: syntax error, unexpected '$pathx' (T_VARIABLE), expecting ','
    or ';' in C:\xampp\htdocs\display.php on line 29

I have checked solutions from similar questions from here on Stackoverflow and implemented some of the accepted answers still my problem is not solved.

meanwhile something like the code below works well. So why is the one above not working?

```<code>echo'<img src = "directory/images/girl-g2109_5_720.jpg">';
</code>```

答:
It looks like there is an issue with the array concatenation.

The string '<img src = "' and variable $pathx are not concatenated properly.

There should be a concatenation operator ('.') in between.

Change the code to the following format to fix the issue.

Code

```<code>echo '<img src = "' . $pathx . $row["filename"] . '">';
</code>```

Output

```<code><img src="directory/images/girl-g2109_5_720.jpg">
</code>```

Body:
I am getting error when I try to echo image in PHP.  Here is my code:

$sql = "SELECT id, title, filename FROM images";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
    $pathx = "directory/images/";

    echo '

    ';
    //filenames in database end with appropriate image extensions like .png

}

And I am getting this error:
    Parse error: syntax error, unexpected '$pathx' (T_VARIABLE), expecting ','
    or ';' in C:\xampp\htdocs\display.php on line 29

I have checked solutions from similar questions from here on Stackoverflow and implemented some of the accepted answers still my problem is not solved.

meanwhile something like the code below works well. So why is the one above not working?

echo'';

Body:
It looks like there is an issue with the array concatenation.

The string '<img src = "' and variable $pathx are not concatenated properly.

There should be a concatenation operator ('.') in between.

Change the code to the following format to fix the issue.

Code

echo '<img src = "' . $pathx . $row["filename"] . '">';

Output

<img src="directory/images/girl-g2109_5_720.jpg">


答:
I think problem is in this line , Before line cursor.moveToFirst(); check one condition.

```<code>if(cursor!=null && cursor.getCount() > 0){
   if(cursor.moveToFirst()){
       //your process for fetching row.
   }
}
</code>```

Title: App crashes when i use Cursor method to get data from SQlite

Body:
I think problem is in this line , Before line cursor.moveToFirst(); check one condition.

if(cursor!=null && cursor.getCount() > 0){
   if(cursor.moveToFirst()){
       //your process for fetching row.
   }
}


问:
Indentation for files that don't have a registered formatter
It seems that I am getting this problem since version 1.18, honestly I don't remember.
With VSCodeVim installed I used to press the = key to get my code (Elixir, embedded elixir, ...) indented properly.

Am I missing something, like a configuration, that would allow me to re-indent my files without having a nagging "Formatter for file x not installed".

This is honestly the only things that nags me with VSCode so far, love the speed, the capabilities and the UI...

答:
Just posting my comment as an answer

Try using the reindent lines command. This command should work for many languages even if you don't have a formatting extension for that language installed