问:
Is seeking to specific frames of an MJPEG video faster than doing the same for an h.264 file?
I am recording video and will need to seek to a specific frame in the video quickly and randomly.

I can record the video in MJPEG or h.264 compression standards.

I understand that MJPEG produces individual jpegs and produce larger file sizes than h.264, and h.264 compresses across multiple frames of video.

Does this difference mean that I will get faster seek times when
  seeking to a random location in the file using ffmpeg or gstreamer
  programmatically?

Will the MJPEG allow the frame-seek operation to reduce the IO requirements when reading just 1 frame from a video file?

答:
Go for MJPEG.

If you are looking for specific (Nth) frame, in H.264 case you must find the closest I-frame to the frame you seek, then decode all the frames between this I-frame and the Nth frame and even further if the Nth frame is a B-frame to restore full Nth frame. It takes milliseconds but may be critical for you.

MJPEG will have larger file size but no decoding overhead, so it is your choice unless your disk is very-very-very slow.

In any case, ffmpeg must go through all the video packets to count them so it is a tradeoff between your disk and processor speed.


来源: stackexchange

问:
Aurelia Custom attribute which changes the elements inner HTML
Use Case

I have a custom attribute which changes the content of the element it is attached, e.g. from non bold to bold.

Problem

With normal binding, the inner HTML does not get changed. I think, Aurelia is losing the binding as soon as the HTML is updated with "plain" Javascript.

You can see it in this GistRun: https://gist.run/?id=6f16ac1c8affb0277d7ad5c53d433482

Change the text in the area. There are five cases:

Case 1: no attribute. Text updated. This is fine.

Case 2: the text is not updated. Expected: update the text, but it should not be bold (missing value change call).

Case 3: text is updated but not bold (missing value change call). This is fine.

Case 4: text is not updated. Exptected: update text and make it bold

Case 5: text is updated and made bold. This is fine.

Question

Can someone explain me, what is happing internally with case 2 and 4?

CODE:

app.html

```<code><template>
  <require from="./bold-custom-attribute"></require>

  <textarea value.bind="content"></textarea>
  ```${content}```
  <pre bold>${content}```

```
  <pre bold.bind="content">${content}```

```
</template>
</code>```

bold-custom-attribute.js

```<code>export class BoldCustomAttribute {
  static inject = [Element];

  constructor(element) {
    this.element = element;
  }

  bind() {
    //this.bolden(this.element);
  }

  attached() {
    this.bolden(this.element);
  }

  valueChanged(newValue, oldValue){
    this.bolden(this.element);
  }

  bolden(anElement) {
    anElement.innerHTML = '<b>' + anElement.innerText + '</b>';
  }
}
</code>```

答: By modifying the HTML in the way you are, you cause new DOM elements to be created, and so Aurelia no longer has a reference to the DOM elements it needs to update bound values. </p>

ContentLicense: CC BY-SA 3.0

Body:
Use Case

I have a custom attribute which changes the content of the element it is attached, e.g. from non bold to bold.

Problem

With normal binding, the inner HTML does not get changed. I think, Aurelia is losing the binding as soon as the HTML is updated with "plain" Javascript.

You can see it in this GistRun: https://gist.run/?id=6f16ac1c8affb0277d7ad5c53d433482

Change the text in the area. There are five cases:

Case 1: no attribute. Text updated. This is fine.

Case 2: the text is not updated. Expected: update the text, but it should not be bold (missing value change call).

Case 3: text is updated but not bold (missing value change call). This is fine.

Case 4: text is not updated. Exptected: update text and make it bold

Case 5: text is updated and made bold. This is fine.

Question

Can someone explain me, what is happing internally with case 2 and 4?

CODE:

app.html

<template>
  <require from="./bold-custom-attribute"></require>

  <textarea value.bind="content"></textarea>

${content}

${content}

${content}

</template>

bold-custom-attribute.js

export class BoldCustomAttribute {
  static inject = [Element];

  constructor(element) {
    this.element = element;
  }

  bind() {
    //this.bolden(this.element);
  }

  attached() {
    this.bolden(this.element);
  }

  valueChanged(newValue, oldValue){
    this.bolden(this.element);
  }

  bolden(anElement) {
    anElement.innerHTML = '' + anElement.innerText + '';
  }
}


问:
Modal (Devise) for Rails App
I Have an application in RoR and I need to make a login modal.

I´m using the gem devise.

sessions_controller.rb

```<code>    class Users::SessionsController < Devise::SessionsController
     respond_to :js
    end
</code>```

In the devise folder of the views, I have the sessions folder with 2 files: _new.html.erb  and  new.js.erb

_new.html.erb

```<code><div class="modal-dialog modal-sm">
  <div class="modal-content">
    <div class="modal-header">
      <button class="close" data-dismiss="modal">x</button>
      <h2 class="dark">Log in</h2>
    </div>
    <div class="modal-body">
      <%= form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %>
      <div class="field">
        <%= f.label :email %><br />
        <%= f.email_field :email, autofocus: true %>
      </div>

      <div class="field">
        <%= f.label :password %><br />
        <%= f.password_field :password, autocomplete: "off" %>
      </div>

      <% if devise_mapping.rememberable? -%>
      <div class="field">
        <%= f.check_box :remember_me %>
        <%= f.label :remember_me %>
      </div>
      <% end -%>

      <div class="actions">
        <%= f.submit "Log in", class: "btn btn-md btn-black-line" %>
      </div>
      <% end %>
      <%= render "devise/shared/links" %>
    </div>
  </div>
</div>
</code>```

new.js.erb

```<code>$('#modaldevise').html('<%= j render('new') %>');
$('#modaldevise').modal();
</code>```

In my application.html.erb I use this code to use modal:

```<code><div id="modaldevise" class="modal fade"></div>
</code>```

Finally I have a side menu that have the login link:

```<code><%= link_to 'Login', new_user_session_path, 'data-toggle' => "modal" , 'data-target' => "#modaldevise" %>
</code>```

When I press the Login link, the background becomes darker and the modal is opened, but the information from the partial _new.html.erb is not showed.

What is wrong here?

答:
You can avoid using new.js.erb and do something like this:

application.html.erb

```<code><div id="modaldevise" class="modal fade">
  <%= render 'your_path/new' %>
</div>
</code>```

side menu

```<code><%= link_to 'Sign in', '#', "data-toggle" => "modal", "data-target"=>"#modaldevise" %>
</code>```

Title: Modal (Devise) for Rails App

Body:
I Have an application in RoR and I need to make a login modal.

I´m using the gem devise.

sessions_controller.rb

    class Users::SessionsController < Devise::SessionsController
     respond_to :js
    end

In the devise folder of the views, I have the sessions folder with 2 files: _new.html.erb  and  new.js.erb

_new.html.erb

      <button class="close" data-dismiss="modal">x</button>

Log in

      <%= form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %>

        <%= f.label :email %>

        <%= f.email_field :email, autofocus: true %>

        <%= f.label :password %>

        <%= f.password_field :password, autocomplete: "off" %>

      <% if devise_mapping.rememberable? -%>

        <%= f.check_box :remember_me %>
        <%= f.label :remember_me %>

      <% end -%>

        <%= f.submit "Log in", class: "btn btn-md btn-black-line" %>

      <% end %>
      <%= render "devise/shared/links" %>

new.js.erb

$('#modaldevise').html('<%= j render('new') %>');
$('#modaldevise').modal();

In my application.html.erb I use this code to use modal:

Finally I have a side menu that have the login link:

<%= link_to 'Login', new_user_session_path, 'data-toggle' => "modal" , 'data-target' => "#modaldevise" %>

When I press the Login link, the background becomes darker and the modal is opened, but the information from the partial _new.html.erb is not showed.

What is wrong here?

Body:
You can avoid using new.js.erb and do something like this:

application.html.erb

<div id="modaldevise" class="modal fade">
  <%= render 'your_path/new' %>
</div>

side menu

<%= link_to 'Sign in', '#', "data-toggle" => "modal", "data-target"=>"#modaldevise" %>


问:
Can I change the double click event handler (ondblClickRow) for a jQuery jqGrid plug-in after it has been rendered in ASP.NET MVC?
I have been using jqGrid with success; however, I've hit something I can't seem to get working.  I am returning a grid definition as a PartialViewResult via AJAX and appending the the results to a div.

I would then like to change the double click event for said grid.  I'm using Firebug and can seem to get to the grid element using $('#my-grid')[0] but when I attempt to call methods on it like below it tells me jqGrid is "not defined".

I'm pretty sure I've got the jqGrid stuff referenced correctly or I wouldn't have gotten this far (I have been displaying and editting data in grids already). Here's the code that gets and attempts to modify the grid definition:

```<code>    $(document).ready(function() {

        //Add the grid by pulling it via AJAX
        $.get('<%=Url.Action("Grid","Entity", new {id = "CustomerAccount"}) %>', function(htmlResult) {

            //Append grid definition to div
            $('#customer-list').append(htmlResult);
            var myGrid = $($('#CustomerAccount-grid')[0]);
            $(myGrid).jqGrid('setGridParam', { ondblClickRow: function(rowid, iRow, iCol, e) { console.log('dblclicked'); } })
                .trigger('reloadGrid');
            //NOTE: I've tried with and without the reloadGrid
}
</code>```

UPDATE: I think I've come to the conclusion now that I am sure I'm referencing the element as a jQuery object that there is a timing issue.  The simplified load of the grid definition below illustrates the issue:

```<code>//Append grid definition to div
$('#customer-list').load('<%=Url.Action("Grid","Entity", new {id = "CustomerAccount"}) %>',function() {

    console.log('sortname=' + $($('#CustomerAccount-grid:first')).jqGrid('getGridParam', 'sortname'));
  });
</code>```

This logs sortname=undefined; however, if I copy and paste the same line into Firebug it displays sortname=Name, which is correct.

FINAL UPDATE: A big part of my problem may have been that I was not getting the element as a jQuery object so I am crediting drachenstern with the solution (Thanks!) But, once beyond that the reason the event handler was still not being wired up was because the grid definition was being retrieved via AJAX and it did not exist when I attempted to bind the ondblclickrow.  The solution was simple: I merely added async: false to the grid definition call so that I will know the definition will always be there before additiona event handlers etc are bound.  I am retrieving the grid definition via AJAX because I am building the grids dynamically on the server side of my ASP.NET MVC app.  I am still retrieving the data for for the grid asynchonously.  Works great now.

答:
```<code>var myGrid = $('#my-grid')[0];
</code>```

This code sets myGrid to be a DOM element. So some other DOM elements would be:

```<code><a>, <div>, <input>, <body>, <table>, etc
</code>```

There is no native DOM property .jqGrid. Perhaps what you meant to do is to get the first child, but keep it in a jQuery wrapper? There are several options, depending on the readability you want. http://api.jquery.com/first/ allows you to use chaining and looks neater, and may be more performant for the given case. There's also:

```<code>var myGrid = $( $('#my-grid')[0] );
</code>```

or alternately:

```<code>$(myGrid).jqGrid('setGridParam',{ ondblClickRow: function(){console.log('Hello');}});
</code>```

and of course you could introduce a middle element:

```<code>var myGridTemp = $('#my-grid')[0];
var myGrid = $( myGridTemp );
myGrid.jqGrid('setGridParam',{ ondblClickRow: function(){console.log('Hello');}});
</code>```

But the primary problem is that the first line of your example only gives you the DOM element, not a jQuery element.

ContentLicense: CC BY-SA 2.5

Body:
I have been using jqGrid with success; however, I've hit something I can't seem to get working.  I am returning a grid definition as a PartialViewResult via AJAX and appending the the results to a div.

I would then like to change the double click event for said grid.  I'm using Firebug and can seem to get to the grid element using $('#my-grid')[0] but when I attempt to call methods on it like below it tells me jqGrid is "not defined".

I'm pretty sure I've got the jqGrid stuff referenced correctly or I wouldn't have gotten this far (I have been displaying and editting data in grids already). Here's the code that gets and attempts to modify the grid definition:

    $(document).ready(function() {

        //Add the grid by pulling it via AJAX
        $.get('<%=Url.Action("Grid","Entity", new {id = "CustomerAccount"}) %>', function(htmlResult) {

            //Append grid definition to div
            $('#customer-list').append(htmlResult);
            var myGrid = $($('#CustomerAccount-grid')[0]);
            $(myGrid).jqGrid('setGridParam', { ondblClickRow: function(rowid, iRow, iCol, e) { console.log('dblclicked'); } })
                .trigger('reloadGrid');
            //NOTE: I've tried with and without the reloadGrid
}

UPDATE: I think I've come to the conclusion now that I am sure I'm referencing the element as a jQuery object that there is a timing issue.  The simplified load of the grid definition below illustrates the issue:

//Append grid definition to div
$('#customer-list').load('<%=Url.Action("Grid","Entity", new {id = "CustomerAccount"}) %>',function() {

    console.log('sortname=' + $($('#CustomerAccount-grid:first')).jqGrid('getGridParam', 'sortname'));
  });

This logs sortname=undefined; however, if I copy and paste the same line into Firebug it displays sortname=Name, which is correct.

FINAL UPDATE: A big part of my problem may have been that I was not getting the element as a jQuery object so I am crediting drachenstern with the solution (Thanks!) But, once beyond that the reason the event handler was still not being wired up was because the grid definition was being retrieved via AJAX and it did not exist when I attempted to bind the ondblclickrow.  The solution was simple: I merely added async: false to the grid definition call so that I will know the definition will always be there before additiona event handlers etc are bound.  I am retrieving the grid definition via AJAX because I am building the grids dynamically on the server side of my ASP.NET MVC app.  I am still retrieving the data for for the grid asynchonously.  Works great now.

Body:
var myGrid = $('#my-grid')[0];

This code sets myGrid to be a DOM element. So some other DOM elements would be:

<a>, <div>, <input>, <body>, <table>, etc

There is no native DOM property .jqGrid. Perhaps what you meant to do is to get the first child, but keep it in a jQuery wrapper? There are several options, depending on the readability you want. http://api.jquery.com/first/ allows you to use chaining and looks neater, and may be more performant for the given case. There's also:

var myGrid = $( $('#my-grid')[0] );

or alternately:

$(myGrid).jqGrid('setGridParam',{ ondblClickRow: function(){console.log('Hello');}});

and of course you could introduce a middle element:

var myGridTemp = $('#my-grid')[0];
var myGrid = $( myGridTemp );
myGrid.jqGrid('setGridParam',{ ondblClickRow: function(){console.log('Hello');}});

But the primary problem is that the first line of your example only gives you the DOM element, not a jQuery element.


问:
Installed module using pip, not found
I am trying to install a package called "simpleguitk" via pip. (On Ubuntu 16.04 with Python 3.5)

After running

```<code>sudo -H pip3 install simpleguitk
</code>```

it says installation is completed successfully. (Except for the pygame dependecy which is actually optional)

```<code>Collecting simpleguitk
Using cached SimpleGUITk-1.1.3.tar.gz
Collecting Pillow>=2.0.0 (from simpleguitk)
Using cached Pillow-3.4.2-cp35-cp35m-manylinux1_x86_64.whl
Collecting pygame>=1.9.0 (from simpleguitk)
Could not find a version that satisfies the requirement pygame>=1.9.0 (from simpleguitk) (from versions: 1.9.2.dev1, 1.9.2b7, 1.9.2b8)
No matching distribution found for pygame>=1.9.0 (from simpleguitk)
</code>```

I cannot find the package at /usr/local/lib/python3.5/dist-packages
or /usr/lib/python3.5 or /usr/lib/python3

When I try to import the module it says:

```<code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named 'simpleguitk'
</code>```

I tried to reinstall it, but running:

```<code>sudo -H pip3 uninstall simpleguitk
</code>```

returns: "Cannot uninstall requirement simpleguitk, not installed
"

I have tried this on both pip 8.1.2 and pip 9.0.1 with the same results.
I have even reinstalled Ubuntu, but still the same.

I think Python Path is wrong as it does not have python 3.5 but I do not know how to fix it

```<code>['', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/gtk-2.0']
</code>```

答:
Make sure you're installing it for the version of python you're using, with</p>

```<code>/path/to/your/python -m pip install <package>
</code>```

Title: Installed module using pip, not found

Body:
I am trying to install a package called "simpleguitk" via pip. (On Ubuntu 16.04 with Python 3.5)

After running

sudo -H pip3 install simpleguitk

it says installation is completed successfully. (Except for the pygame dependecy which is actually optional)

Collecting simpleguitk
Using cached SimpleGUITk-1.1.3.tar.gz
Collecting Pillow>=2.0.0 (from simpleguitk)
Using cached Pillow-3.4.2-cp35-cp35m-manylinux1_x86_64.whl
Collecting pygame>=1.9.0 (from simpleguitk)
Could not find a version that satisfies the requirement pygame>=1.9.0 (from simpleguitk) (from versions: 1.9.2.dev1, 1.9.2b7, 1.9.2b8)
No matching distribution found for pygame>=1.9.0 (from simpleguitk)

I cannot find the package at /usr/local/lib/python3.5/dist-packages
or /usr/lib/python3.5 or /usr/lib/python3

When I try to import the module it says:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named 'simpleguitk'

I tried to reinstall it, but running:

sudo -H pip3 uninstall simpleguitk

returns: "Cannot uninstall requirement simpleguitk, not installed
"

I have tried this on both pip 8.1.2 and pip 9.0.1 with the same results.
I have even reinstalled Ubuntu, but still the same.

I think Python Path is wrong as it does not have python 3.5 but I do not know how to fix it

['', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/gtk-2.0']

Body:
Make sure you're installing it for the version of python you're using, with

/path/to/your/python -m pip install <package>


问:
Parallax in Polymer
I'm working in a parallax with Polymer. I read the documentation in the official web site, and put this on my project. But doesnt works.
This is my code:

```<code><dom-module id="ingeview-home">
  <template>
    <style>
      :host {
        display: block;
        color: var(--text-color-dark);
        padding: 20px 10%;
      }

      parallax-element {
        height: 100vh;
      }
      parallax-element > * {
        min-height: 500px;
      }
      parallax-layers {
        min-height: 500px;
      }
    </style>

    <h1>HOME</h1>

    <parallax-element>
      <parallax-layers>
        <div depth="0">
          <image src=../images/pincel.png></image>
        <div>
      </parallax-layers>
      <parallax-layers style="z-index: -1;">
        <div depth="-0.5">
         <image src=../images/raya.png></image>
        <div>
        <div>
         <image src=../images/pincel.png></image>
        <div>
      </parallax-layers>
      <parallax-layers style="z-index: 1;">
        <div depth="0.2">
         <image src=../images/raya.png></image>
        <div>
      </parallax-layers>
    </parallax-element>
  </template>

  <script>

    class IngeViewHome extends Polymer.Element {
      static get is() { return 'ingeview-home'; }
    }

    window.customElements.define(IngeViewHome.is, IngeViewHome);
  </script>
</dom-module>
</code>```

I'm search by a few hours, but cant find why dont appear anything

If you can explain how it works, I'll be grateful

答:
I have found a couple of the existing Polymer parallax web components are incompatible with Polymer 2.0, so I decided to implement it myself. I found this tutorial to be a good place to good start: https://www.w3schools.com/howto/howto_css_parallax.asp

Hopefully it helps you.

Title: Parallax in Polymer

Body:
I'm working in a parallax with Polymer. I read the documentation in the official web site, and put this on my project. But doesnt works.
This is my code:

<dom-module id="ingeview-home">
  <template>

HOME

    <parallax-element>
      <parallax-layers>

          <image src=../images/pincel.png></image>

      </parallax-layers>
      <parallax-layers style="z-index: -1;">

         <image src=../images/raya.png></image>

         <image src=../images/pincel.png></image>

      </parallax-layers>
      <parallax-layers style="z-index: 1;">

         <image src=../images/raya.png></image>

      </parallax-layers>
    </parallax-element>
  </template>

</dom-module>

I'm search by a few hours, but cant find why dont appear anything

If you can explain how it works, I'll be grateful


问:
Getting metadata of all files using Dropbox Python API
The Dropbox account I'm connected to using the Dropbox Python API has about 10k files in it's main folder. I'm interested in getting the metadata information of all files, the thing is that when I call the following:

```<code>client = dropbox.Dropbox('TOKEN HERE')
metadata = client.files_list_folder('').entries
fname = []
for i in metadata:
    fname.append(i)
print(len(fname))
</code>```

It prints out only 2000 files. I find it suspicious that it only prints the info of such round number, which makes me assume that's a hard limit.

I know there's the files_list_folder_continue function which, if I understood correctly, continues to look for metadata where the files_list_folder function left off but Im not sure how to implement it. I tried the following:

```<code>metadata = client.files_list_folder('').entries
metadata1 = client.files_list_folder_continue('').entries
met = pd.concat([metadata, metadata1], axis=0)
</code>```

But it produces the following error: dropbox.stone_validators.ValidationError: '' must be at least 1 characters, got 0. Clearly it has to do with the fact that I dont know how to use the files_list_folder_continue function. How can these be used?

答:
I realized there was a way to solve this, so I figured I post this if a beginner at python stumbles into the same doubt using python in the future:

```<code>metadata = client.files_list_folder('')
flist = []
if metadata.has_more == True:
    m1 = metadata.entries
    cur = metadata.cursor
    for i in m1:
        if isinstance(i, dropbox.files.FileMetadata):
            flist.append([i.name, i.size])
    m2 = client.files_list_folder_continue(cur)
    while m2.has_more == True:
        for i in m2.entries:
            if isinstance(i, dropbox.files.FileMetadata):
                flist.append([i.name, i.size])
        cur = m2.cursor
        m2 = client.files_list_folder_continue(cur)
</code>```

That gets the name and size of all files in the home directory of the dropbox folder.

Body:
The Dropbox account I'm connected to using the Dropbox Python API has about 10k files in it's main folder. I'm interested in getting the metadata information of all files, the thing is that when I call the following:

client = dropbox.Dropbox('TOKEN HERE')
metadata = client.files_list_folder('').entries
fname = []
for i in metadata:
    fname.append(i)
print(len(fname))

It prints out only 2000 files. I find it suspicious that it only prints the info of such round number, which makes me assume that's a hard limit.

I know there's the files_list_folder_continue function which, if I understood correctly, continues to look for metadata where the files_list_folder function left off but Im not sure how to implement it. I tried the following:

metadata = client.files_list_folder('').entries
metadata1 = client.files_list_folder_continue('').entries
met = pd.concat([metadata, metadata1], axis=0)

But it produces the following error: dropbox.stone_validators.ValidationError: '' must be at least 1 characters, got 0. Clearly it has to do with the fact that I dont know how to use the files_list_folder_continue function. How can these be used?

Body:
I realized there was a way to solve this, so I figured I post this if a beginner at python stumbles into the same doubt using python in the future:

metadata = client.files_list_folder('')
flist = []
if metadata.has_more == True:
    m1 = metadata.entries
    cur = metadata.cursor
    for i in m1:
        if isinstance(i, dropbox.files.FileMetadata):
            flist.append([i.name, i.size])
    m2 = client.files_list_folder_continue(cur)
    while m2.has_more == True:
        for i in m2.entries:
            if isinstance(i, dropbox.files.FileMetadata):
                flist.append([i.name, i.size])
        cur = m2.cursor
        m2 = client.files_list_folder_continue(cur)

That gets the name and size of all files in the home directory of the dropbox folder.


问:
Can I use a JQuery Variable to select MYSQL column?
When one of my forms (name= QuestionTypeSelector value=AddingFractions) posts, the following snippet of PHP is part of the code that runs:

```<code>$QuestionTypeSelector = $_POST['QuestionTypeSelector'];
 $db->query(" UPDATE answers SET QuestionType = '$QuestionTypeSelector' WHERE user_id=$id");
</code>```

$_POST['QuestionTypeSelector'] successfully returns AddingFractions and this successfully sets $QuestionTypeSelector = AddingFractions. In turn, this sets a column titled QuestionType equal to AddingFractions.

Instead of this, I want to set a column titled AddingFractionsScore equal to 2. I tried the following code but it doesn't work.

```<code>$QuestionTypeSelector = $_POST['QuestionTypeSelector'];
 $db->query(" UPDATE answers SET '$QuestionTypeSelector+Score' = '2' WHERE user_id=$id");
</code>```

In other words, I'm trying to use the JQuery variable to select the column. Any advice would be much appreciated. Thanks!

答:
This process is very dangerous because you might be victim of sql injection.
I suggest you to use a mapping array to select your column.
Es.
Your jQuery post a integer in a variable POST
$_POST['column'] = 0;
Then in your php page, you get the post value and use it ad key to retrieve the column name</p>

```<code>$availableColumns = array(
    'QuestionTypeSelector',
    'QuestionTypeSelector1,
);
</code>```

Body:
When one of my forms (name= QuestionTypeSelector value=AddingFractions) posts, the following snippet of PHP is part of the code that runs:

$QuestionTypeSelector = $_POST['QuestionTypeSelector'];
 $db->query(" UPDATE answers SET QuestionType = '$QuestionTypeSelector' WHERE user_id=$id");

$_POST['QuestionTypeSelector'] successfully returns AddingFractions and this successfully sets $QuestionTypeSelector = AddingFractions. In turn, this sets a column titled QuestionType equal to AddingFractions.

Instead of this, I want to set a column titled AddingFractionsScore equal to 2. I tried the following code but it doesn't work.

$QuestionTypeSelector = $_POST['QuestionTypeSelector'];
 $db->query(" UPDATE answers SET '$QuestionTypeSelector+Score' = '2' WHERE user_id=$id");

In other words, I'm trying to use the JQuery variable to select the column. Any advice would be much appreciated. Thanks!

Body:
This process is very dangerous because you might be victim of sql injection.
I suggest you to use a mapping array to select your column.
Es.
Your jQuery post a integer in a variable POST
$_POST['column'] = 0;
Then in your php page, you get the post value and use it ad key to retrieve the column name

$availableColumns = array(
    'QuestionTypeSelector',
    'QuestionTypeSelector1,
);


问:
Printing without newline (print 'a',) prints a space, how to remove?
I have this code:

```<code>>>> for i in xrange(20):
...     print 'a',
...
a a a a a a a a a a a a a a a a a a a a
</code>```

I want to output 'a', without ' ' like this:

```<code>aaaaaaaaaaaaaaaaaaaa
</code>```

Is it possible?

答:
There are a number of ways of achieving your result. If you're just wanting a solution for your case, use string multiplication as @Ant mentions. This is only going to work if each of your print statements prints the same string. Note that it works for multiplication of any length string (e.g. 'foo' * 20 works).

```<code>>>> print 'a' * 20
aaaaaaaaaaaaaaaaaaaa
</code>```

If you want to do this in general, build up a string and then print it once. This will consume a bit of memory for the string, but only make a single call to print. Note that string concatenation using += is now linear in the size of the string you're concatenating so this will be fast.

```<code>>>> for i in xrange(20):
...     s += 'a'
...
>>> print s
aaaaaaaaaaaaaaaaaaaa
</code>```

Or you can do it more directly using sys.stdout.write(), which print is a wrapper around. This will write only the raw string you give it, without any formatting. Note that no newline is printed even at the end of the 20 as.

```<code>>>> import sys
>>> for i in xrange(20):
...     sys.stdout.write('a')
...
aaaaaaaaaaaaaaaaaaaa>>>
</code>```

Python 3 changes the print statement into a print() function, which allows you to set an end parameter. You can use it in >=2.6 by importing from __future__. I'd avoid this in any serious 2.x code though, as it will be a little confusing for those who have never used 3.x. However, it should give you a taste of some of the goodness 3.x brings.

```<code>>>> from __future__ import print_function
>>> for i in xrange(20):
...     print('a', end='')
...
aaaaaaaaaaaaaaaaaaaa>>>
</code>```

Body:
I have this code:

>>> for i in xrange(20):
...     print 'a',
...
a a a a a a a a a a a a a a a a a a a a

I want to output 'a', without ' ' like this:

aaaaaaaaaaaaaaaaaaaa

Is it possible?

Body:
There are a number of ways of achieving your result. If you're just wanting a solution for your case, use string multiplication as @Ant mentions. This is only going to work if each of your print statements prints the same string. Note that it works for multiplication of any length string (e.g. 'foo' * 20 works).

>>> print 'a' * 20
aaaaaaaaaaaaaaaaaaaa

If you want to do this in general, build up a string and then print it once. This will consume a bit of memory for the string, but only make a single call to print. Note that string concatenation using += is now linear in the size of the string you're concatenating so this will be fast.

>>> for i in xrange(20):
...     s += 'a'
...
>>> print s
aaaaaaaaaaaaaaaaaaaa

Or you can do it more directly using sys.stdout.write(), which print is a wrapper around. This will write only the raw string you give it, without any formatting. Note that no newline is printed even at the end of the 20 as.

>>> import sys
>>> for i in xrange(20):
...     sys.stdout.write('a')
...
aaaaaaaaaaaaaaaaaaaa>>>

Python 3 changes the print statement into a print() function, which allows you to set an end parameter. You can use it in >=2.6 by importing from __future__. I'd avoid this in any serious 2.x code though, as it will be a little confusing for those who have never used 3.x. However, it should give you a taste of some of the goodness 3.x brings.

>>> from __future__ import print_function
>>> for i in xrange(20):
...     print('a', end='')
...
aaaaaaaaaaaaaaaaaaaa>>>


问:
Cannot strip newline from Cocoa NSMutableString
Hey, for the life of me, this is not working:..

```<code>NSMutableString *b64String = [[[NSMutableString alloc] initWithFormat:@"Basic %@", [string _base64Encoding:string]] autorelease];

    [b64String stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
    NSLog(@"(%@)", b64String);

    NSRange foundRange = [b64String rangeOfString:@"\n"];
    if (foundRange.location != NSNotFound)
        [b64String stringByReplacingOccurrencesOfString:@"\n"
                                            withString:@""
                                               options:0
                                                 range:foundRange];
    NSLog(@"(%@)", b64String);
</code>```

Both those methods I found on SO - and they don't seem to work... I've got to be doing something terribly wrong. But, if I break on the NSLog's, I can clearly see the "\n" in the string (in the debugger AND in the console out)

Also, this is true:

```<code>if (foundRange.location != NSNotFound)
</code>```

And I can see if execute the stringByReplacingOccurencesOfString method...

答:
You can trim newlines from a NSMutableString in-place, but you need to use the CFStringTrim method from Core Foundation.

Objective-C:

```<code>NSMutableString *string = [NSMutableString stringWithString:@"\nfoo bar baz\n"];
CFStringTrim((__bridge CFMutableStringRef)string, (__bridge CFStringRef)@"\n");
</code>```

Swift:

```<code>let string = NSMutableString(string: "\nfoo bar baz\n")
CFStringTrim(string as CFMutableString, "\n" as CFString)
</code>```

Body:
Hey, for the life of me, this is not working:..

NSMutableString *b64String = [[[NSMutableString alloc] initWithFormat:@"Basic %@", [string _base64Encoding:string]] autorelease];

    [b64String stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
    NSLog(@"(%@)", b64String);

    NSRange foundRange = [b64String rangeOfString:@"\n"];
    if (foundRange.location != NSNotFound)
        [b64String stringByReplacingOccurrencesOfString:@"\n"
                                            withString:@""
                                               options:0
                                                 range:foundRange];
    NSLog(@"(%@)", b64String);

Both those methods I found on SO - and they don't seem to work... I've got to be doing something terribly wrong. But, if I break on the NSLog's, I can clearly see the "\n" in the string (in the debugger AND in the console out)

Also, this is true:

if (foundRange.location != NSNotFound)

And I can see if execute the stringByReplacingOccurencesOfString method...

Body:
You can trim newlines from a NSMutableString in-place, but you need to use the CFStringTrim method from Core Foundation.

Objective-C:

NSMutableString *string = [NSMutableString stringWithString:@"\nfoo bar baz\n"];
CFStringTrim((__bridge CFMutableStringRef)string, (__bridge CFStringRef)@"\n");

Swift:

let string = NSMutableString(string: "\nfoo bar baz\n")
CFStringTrim(string as CFMutableString, "\n" as CFString)


问:
ngrx Effects: Are actions dispatched by one effect processed immediately by other effects?
I have an Angular (2) app with four ngrx actions:

START

Not processed by the reducer (no state change)

ngrx Effect calls an async task and maps to SUCCESS or ERROR

SUCCESS

Processed by the reducer

ngrx Effect maps to ADVANCE

ADVANCE

Not processed by the reducer

ngrx Effect navigates to a different route

ERROR

Processed by the reducer

No Effect

The problem is that the Effect that catches ADVANCE seems to run before the reducer that processes SUCCESS

Here's the Effects code:

```<code>@Effect() start$ = this.actions$
    .ofType('START')
    .map(toPayload)
    .switchMap(input => doAsyncTask(input)
        .map(result => ({type: 'SUCCESS', payload: result}))
        .catch(error => ({type: 'ERROR', payload: error})));

@Effect() success$ = this.actions$
    .ofType('SUCCESS')
    .map(() => ({type: 'ADVANCE'}));

@Effect({dispatch: false}) advance$ = this.actions$
    .ofType('ADVANCE')
    .withLatestFrom(this.store$.select(state => state.route))
    .map(action_route => action_route[1])
    .do(route => this.router.navigate([route.foo.bar]));
</code>```

The error that I am getting is Cannot read property 'bar' of null. The property foo is set by the reducer that processes SUCCESS.

If I add a delay to the SUCCESS effect, it all works nicely:

```<code>@Effect() success$ = this.actions$
    .ofType('SUCCESS')
    .delay(1)
    .map(() => ({type: 'ADVANCE'}));
</code>```

But having to add this delay doesn't make sense to me.

I added console.log statements everywhere and the output looks like this:

SUCCESS effect

ADVANCE effect (showing route.foo === null)

SUCCESS reducer (showing route.foo === something)

Error

I expected the SUCCESS effect and the SUCCESS reducer to run before the ADVANCE effect.

Am I doing something wrong?

Is it incorrect to expect that actions are processed by the reducers in the same order that they are dispatched?

Versions:

@angular/cli: 1.0.0-beta.32.3

node: 7.5.0

os: darwin x64

@angular/common: 2.4.7

@angular/compiler: 2.4.7

@angular/core: 2.4.7

@angular/forms: 2.4.7

@angular/http: 2.4.7

@angular/platform-browser: 2.4.7

@angular/platform-browser-dynamic: 2.4.7

@angular/router: 3.4.7

@angular/cli: 1.0.0-beta.32.3

@angular/compiler-cli: 2.4.7

@ngrx/core@1.2.0

@ngrx/effects@2.0.0

@ngrx/store@2.2.1

rxjs: 5.1.1

答:
To answer your concluding questions:

Am I doing something wrong?

No, I don't reckon you are doing anything wrong.

Is it incorrect to expect that actions are processed by the reducers in the same order that they are dispatched?

That order would seem logical but apparently you can't expect that at the moment

There seems to be a bug causing this behaviour. You are most probably experiencing it since you are directly mapping to another action. Usually, if you have an asynchronous operation or something like that, the reducer has time to finish before the effect listening to the next action starts.

Perhaps not a part of your question, but a solution to your specified problem would be to navigate to your new route directly in SUCCESS with the help of your payload, or pass the payload to ADVANCE.

Links below are reported issues in effects-, store- and rxjs-projects that are related to yours:

https://github.com/ngrx/effects/issues/58

https://github.com/ngrx/store/issues/279

/ReactiveX/rxjs/issues/2155 (too little reputation to link to this one as well)

Seems like they're working on it :)

Body:
I have an Angular (2) app with four ngrx actions:

START

Not processed by the reducer (no state change)

ngrx Effect calls an async task and maps to SUCCESS or ERROR

SUCCESS

Processed by the reducer

ngrx Effect maps to ADVANCE

ADVANCE

Not processed by the reducer

ngrx Effect navigates to a different route

ERROR

Processed by the reducer

No Effect

The problem is that the Effect that catches ADVANCE seems to run before the reducer that processes SUCCESS

Here's the Effects code:

@Effect() start$ = this.actions$
    .ofType('START')
    .map(toPayload)
    .switchMap(input => doAsyncTask(input)
        .map(result => ({type: 'SUCCESS', payload: result}))
        .catch(error => ({type: 'ERROR', payload: error})));

@Effect() success$ = this.actions$
    .ofType('SUCCESS')
    .map(() => ({type: 'ADVANCE'}));

@Effect({dispatch: false}) advance$ = this.actions$
    .ofType('ADVANCE')
    .withLatestFrom(this.store$.select(state => state.route))
    .map(action_route => action_route[1])
    .do(route => this.router.navigate([route.foo.bar]));

The error that I am getting is Cannot read property 'bar' of null. The property foo is set by the reducer that processes SUCCESS.

If I add a delay to the SUCCESS effect, it all works nicely:

@Effect() success$ = this.actions$
    .ofType('SUCCESS')
    .delay(1)
    .map(() => ({type: 'ADVANCE'}));

But having to add this delay doesn't make sense to me.

I added console.log statements everywhere and the output looks like this:

SUCCESS effect

ADVANCE effect (showing route.foo === null)

SUCCESS reducer (showing route.foo === something)

Error

I expected the SUCCESS effect and the SUCCESS reducer to run before the ADVANCE effect.

Am I doing something wrong?

Is it incorrect to expect that actions are processed by the reducers in the same order that they are dispatched?

Versions:

@angular/cli: 1.0.0-beta.32.3

node: 7.5.0

os: darwin x64

@angular/common: 2.4.7

@angular/compiler: 2.4.7

@angular/core: 2.4.7

@angular/forms: 2.4.7

@angular/http: 2.4.7

@angular/platform-browser: 2.4.7

@angular/platform-browser-dynamic: 2.4.7

@angular/router: 3.4.7

@angular/cli: 1.0.0-beta.32.3

@angular/compiler-cli: 2.4.7

@ngrx/core@1.2.0

@ngrx/effects@2.0.0

@ngrx/store@2.2.1

rxjs: 5.1.1


问:
Pyperclip is giving an error
I use python 2.7. I installed pyperclip using sudo pip install pyperclip and it was installed successfully.

Every time I use the following simple code

```<code>import pyperclip
pyperclip.copy('Hello World')
message=pyperclip.paste()
print (message)
</code>```

I get the following error:

```<code>/usr/lib/python2.7/dist-packages/gtk-2.0/gtk/__init__.py:57:
GtkWarning: could not open display   warnings.warn(str(e),
_gtk.Warning) /usr/local/lib/python2.7/dist-packages/pyperclip/__init__.py:102:
GtkWarning: IA__gtk_clipboard_get_for_display: assertion 'display !=
NULL' failed   cb = gtk.Clipboard() Traceback (most recent call last):
File "first.py", line 401, in <module>
    pyperclip.copy('Hello World')   File "/usr/local/lib/python2.7/dist-packages/pyperclip/__init__.py", line
102, in _copyGtk
    cb = gtk.Clipboard() RuntimeError: could not create GtkClipboard object
</code>```

答:
It always helps to read the documentation.

```<code>On Windows, no additional modules are needed.
</code>```

```<code>On Mac, the module uses pbcopy and pbpaste, which should come with the os.
On Linux, install xclip or xsel via package manager. For example, in Debian:
sudo apt-get install xclip
</code>```

Otherwise on Linux, you will need the gtk or PyQt4 modules installed.

gtk and PyQt4 modules are not available for Python 3,
and this module does not work with PyGObject yet.

So all you need to do at your terminal is sudo apt install xclip  and then the gtk and PyQt4 modules via pip (for python 2).

Title: Pyperclip is giving an error

Body:
I use python 2.7. I installed pyperclip using sudo pip install pyperclip and it was installed successfully.

Every time I use the following simple code

import pyperclip
pyperclip.copy('Hello World')
message=pyperclip.paste()
print (message)

I get the following error:

/usr/lib/python2.7/dist-packages/gtk-2.0/gtk/__init__.py:57:
GtkWarning: could not open display   warnings.warn(str(e),
_gtk.Warning) /usr/local/lib/python2.7/dist-packages/pyperclip/__init__.py:102:
GtkWarning: IA__gtk_clipboard_get_for_display: assertion 'display !=
NULL' failed   cb = gtk.Clipboard() Traceback (most recent call last):
File "first.py", line 401, in <module>
    pyperclip.copy('Hello World')   File "/usr/local/lib/python2.7/dist-packages/pyperclip/__init__.py", line
102, in _copyGtk
    cb = gtk.Clipboard() RuntimeError: could not create GtkClipboard object

Body:
It always helps to read the documentation.

On Windows, no additional modules are needed.

On Mac, the module uses pbcopy and pbpaste, which should come with the os.
On Linux, install xclip or xsel via package manager. For example, in Debian:
sudo apt-get install xclip

Otherwise on Linux, you will need the gtk or PyQt4 modules installed.

gtk and PyQt4 modules are not available for Python 3,
and this module does not work with PyGObject yet.

So all you need to do at your terminal is sudo apt install xclip  and then the gtk and PyQt4 modules via pip (for python 2).

ContentLicense: CC BY-SA 4.0


问:
Specifying which columns to drop with standard evaluation using the tidyr function gather_() in R
I'm trying to drop columns from the columns to be gathered using the gather() function in the R package tidyr.

This works fine when I specify what columns I want to gather (here, I'm gathering the mpg, cyl, and disp columns into variable and val columns:

```<code>library(tidyverse)

mtcars %>%
  select_("mpg", "cyl", "disp") %>%
  gather_("variable", "val", gather_cols = c("mpg", "cyl", "disp"))
</code>```

Let's say I had four variables, and instead of specifying which to gather, I wanted to specify which to drop (hp in this next case). This, probably obviously, doesn't work:

```<code>mtcars %>%
  select_("mpg", "cyl", "disp", "hp") %>%
  gather_("var", "val", gather_cols = c(-"hp"))
</code>```

The suggestion to use one_of - as in the answer to this question - doesn't seem to work. In a now-closed GitHub issue for tidyr, it is suggested to use dplyr::select_vars(), but this doesn't seem to work, either.

How could this - specifying which columns to drop with standard evaluation using gather()?

答:
I'm a bit unfamiliar with what tidyverse loads and how it manages environments -- I usually use regular tidyr -- but using tidyr::gather instead of gather_, would allow you to use this syntax:

```<code># here, gather takes the "key" and "value" args as objects
# as does dplyr::select
# and allows for additional objects off the data.frame
# to be passed as additional args

mtcars %>%
  dplyr::select(mpg, cyl, disp, hp) %>%
  tidyr::gather(var, val, -hp)
</code>```

Body:
I'm trying to drop columns from the columns to be gathered using the gather() function in the R package tidyr.

This works fine when I specify what columns I want to gather (here, I'm gathering the mpg, cyl, and disp columns into variable and val columns:

library(tidyverse)

mtcars %>%
  select_("mpg", "cyl", "disp") %>%
  gather_("variable", "val", gather_cols = c("mpg", "cyl", "disp"))

Let's say I had four variables, and instead of specifying which to gather, I wanted to specify which to drop (hp in this next case). This, probably obviously, doesn't work:

mtcars %>%
  select_("mpg", "cyl", "disp", "hp") %>%
  gather_("var", "val", gather_cols = c(-"hp"))

The suggestion to use one_of - as in the answer to this question - doesn't seem to work. In a now-closed GitHub issue for tidyr, it is suggested to use dplyr::select_vars(), but this doesn't seem to work, either.

How could this - specifying which columns to drop with standard evaluation using gather()?

Body:
I'm a bit unfamiliar with what tidyverse loads and how it manages environments -- I usually use regular tidyr -- but using tidyr::gather instead of gather_, would allow you to use this syntax:

# here, gather takes the "key" and "value" args as objects
# as does dplyr::select
# and allows for additional objects off the data.frame
# to be passed as additional args

mtcars %>%
  dplyr::select(mpg, cyl, disp, hp) %>%
  tidyr::gather(var, val, -hp)


问:
OnMapLoaded is never call on Android
I am trying to know when the map finished loading to fade in the map, but I can't get the OnMapLoaded() callback to be triggered. I'm using SupportMapFragment and I see everything OK but still not working. The OnMapReady works ok!

Here is my onCreate() code:

```<code>protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    supportRequestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);

    setContentView(R.layout.activity_map);

    View map = findViewById(R.id.map);
    map.setAlpha(0);

    createLocationRequest();
    getInstanceGoogleAPIClient();
    updateValuesFromBundle(savedInstanceState);

    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
}
</code>```

Then my OnMapReady():

```<code>@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    mMap.setOnMapLoadedCallback(this);
    try {
        boolean success = googleMap.setMapStyle(
                MapStyleOptions.loadRawResourceStyle(
                        this, R.raw.map_style));

        if (!success) {
            Log.e(TAG, "Style parsing failed.");
        }
    } catch (Resources.NotFoundException e) {
        Log.e(TAG, "Can't find style. Error: ", e);
    }
}
</code>```

And my OnMapLoaded():

```<code>@Override
public void onMapLoaded() {
    if (mMap != null) {
        View map = findViewById(R.id.map);
        map.animate().setDuration(700).alpha(1).setInterpolator(new AccelerateInterpolator()).start();
    }
}
</code>```

My Activity header:

```<code>public class MapActivity extends AppCompatActivity
    implements OnMapReadyCallback,
    GoogleMap.OnMapLoadedCallback,
    GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener,
    LocationListener { ... }
</code>```

答:
From the documentation:

This event will not fire if the map never loads due to connectivity issues, or if the map is continuously changing and never completes loading due to the user constantly interacting with the map.

So, check connectivity and make sure that the map is idle.

Title: OnMapLoaded is never call on Android

Body:
I am trying to know when the map finished loading to fade in the map, but I can't get the OnMapLoaded() callback to be triggered. I'm using SupportMapFragment and I see everything OK but still not working. The OnMapReady works ok!

Here is my onCreate() code:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    supportRequestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);

    setContentView(R.layout.activity_map);

    View map = findViewById(R.id.map);
    map.setAlpha(0);

    createLocationRequest();
    getInstanceGoogleAPIClient();
    updateValuesFromBundle(savedInstanceState);

    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
}

Then my OnMapReady():

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    mMap.setOnMapLoadedCallback(this);
    try {
        boolean success = googleMap.setMapStyle(
                MapStyleOptions.loadRawResourceStyle(
                        this, R.raw.map_style));

        if (!success) {
            Log.e(TAG, "Style parsing failed.");
        }
    } catch (Resources.NotFoundException e) {
        Log.e(TAG, "Can't find style. Error: ", e);
    }
}

And my OnMapLoaded():

@Override
public void onMapLoaded() {
    if (mMap != null) {
        View map = findViewById(R.id.map);
        map.animate().setDuration(700).alpha(1).setInterpolator(new AccelerateInterpolator()).start();
    }
}

My Activity header:

public class MapActivity extends AppCompatActivity
    implements OnMapReadyCallback,
    GoogleMap.OnMapLoadedCallback,
    GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener,
    LocationListener { ... }


问:
$routeProvider not redirecting to templateUrl
I am creating some CRUD pages using AngularJS and on a list of Users page, I am trying redirect to edit page once the user click on "Edit" button. But for some reason $routeProvider is not working.

Here is my index.html showing list of users

```<code><tr ng-repeat="user in usersData">
    <td>{{ user.firstname }}</td>
    <td>{{ user.lastname }}</td>
    <td>{{ user.jobtitle }}</td>
    <td>{{ user.userprofile.sex }}</td>
    <td>{{ user.userprofile.maritalstatus }}</td>
    <td><a ng-click="editUser(user.id)" class="btn btn-small btn-primary">edit</a></td>
    <td><a ng-click="deleteUser(user.id)" class="btn btn-small btn-danger">delete</a></td>
</tr>
</code>```

My app.js

```<code>var app = angular.module('benefitApp', ['ngRoute']);
app.config(function($routeProvider){
    $routeProvider
        .when("/editUser/:userId", {
                templateUrl : "templates/editUser.html"
            });
});

app.controller('userController', ['$scope','$http','$location',function($scope, $http, $location) {
  $http.get("https://localhost:8443/benefits/v1/users/").then(function (response){
      $scope.usersData = response.data;
  });
  $scope.editUser = function(userId) {
      $location.path('/editUser/' + userId);
  }
}]);
</code>```

My directory structure is as below

```<code>src/main/resources/static/js/app.js
src/main/resources/static/css/bootstrap.css
src/main/resources/templates/index.html
src/main/resources/templates/editUser.html
</code>```

What am i missing? On click of "Edit" button, the url in the browser changes to https://localhost:8443/home#!/editUser/1, but it never gets routed to editUser.html

答: Try adding the ng-view directive inside your app so that the $route service can render the correct template.</p>

Body:
I am creating some CRUD pages using AngularJS and on a list of Users page, I am trying redirect to edit page once the user click on "Edit" button. But for some reason $routeProvider is not working.

Here is my index.html showing list of users

    {{ user.firstname }}
    {{ user.lastname }}
    {{ user.jobtitle }}
    {{ user.userprofile.sex }}
    {{ user.userprofile.maritalstatus }}
    edit
    delete

My app.js

var app = angular.module('benefitApp', ['ngRoute']);
app.config(function($routeProvider){
    $routeProvider
        .when("/editUser/:userId", {
                templateUrl : "templates/editUser.html"
            });
});

app.controller('userController', ['$scope','$http','$location',function($scope, $http, $location) {
  $http.get("https://localhost:8443/benefits/v1/users/").then(function (response){
      $scope.usersData = response.data;
  });
  $scope.editUser = function(userId) {
      $location.path('/editUser/' + userId);
  }
}]);

My directory structure is as below

src/main/resources/static/js/app.js
src/main/resources/static/css/bootstrap.css
src/main/resources/templates/index.html
src/main/resources/templates/editUser.html

What am i missing? On click of "Edit" button, the url in the browser changes to https://localhost:8443/home#!/editUser/1, but it never gets routed to editUser.html


问:
A kernel matrix 3x3 on an array of an image / Gaussian filter
I am trying to implement a Gaussian filter. For this I am using a kernel 3x3 and an array of an image.The problem I am having is defining a sub-matrix 3x3 for each [i, j] element of the array. I wrote the details inside the code.

```<code>import numpy as np
import scipy
from scipy import misc
import matplotlib.pyplot as plt

imagen = scipy.misc.imread("C:\\Users\\Reymi\\Downloads\\imagen.png") #importing image of original size (1929, 1280)

imagen_real = scipy.pad(array=imagen, pad_width=[1, 1], mode='constant', constant_values=0) #add 1 column and 1 row of zeros to avoid the kernel of going outside the array. size is (1931, 1282)

imagen_nueva = np.empty((1931, 1282)) #the new image. the same size as the image I will filter

(dim_x,dim_y)=np.shape(imagen_real)

ker1 = np.array([[1/16, 1/8, 1/16],   #3x3 kernel
                [1/8, 1/4, 1/8],
                [1/16, 1/8, 1/16]])

def multiplicar_entero():

    global imagen_nueva
    for i in range(1,dim_x): #the range starts from 1 to avoid the column and row of zeros, and ends before the last col and row of zeros
        for j in range(1,dim_y):
            imagen_entry = np.empty((3, 3))      #Main problem here: how do I define a 3x3 matrix for each entry?
            valor = np.sum(imagen_entry*ker1)    #Matrix 3x3 is filled with the elements around each [i, j] entry of the array
            imagen_real[i, j] = valor
            imagen_nueva = np.append(imagen_real[i, j], (1931, 1282)) #This is supposed to each new [i, j] entry to the new image

print("La imagen con el blur effect es la siguiente:\n")

multiplicar_entero()   #calls function

plt.imshow(imagen_nueva)  #Show new image
plt.gray()
plt.show()
</code>```

Sorry for the long code. And thanks for any help.

答:
There are a few issues with your code as is:

You are using an image we don't have access to. Always use freely available images in examples so we can run the code. I used scipy.misc.ascent here.

Don't use global variables unless you really have to.

Always code in english with english variable names and english comments. It makes reviews like this much easier.

I did some fixes to your code below, and I guess you can see how I solved your problem. Specifically you want to use : indexing which allows you extract subsets of an array and use array[i, j] to assign the result:

```<code>import numpy as np
import scipy
from scipy import misc
import matplotlib.pyplot as plt

imagen = scipy.misc.ascent()  # Freely available image

(dim_x, dim_y) = np.shape(imagen)

ker1 = np.array([[1/16, 1/8, 1/16],   #3x3 kernel
                [1/8, 1/4, 1/8],
                [1/16, 1/8, 1/16]])

def multiplicar_entero(imagen):
    imagen_nueva = np.zeros(imagen.shape) #the new image. the same size as the image I will filter
    for i in range(1,dim_x-1): #the range starts from 1 to avoid the column and row of zeros, and ends before the last col and row of zeros
        for j in range(1,dim_y-1):
            imagen_entry = imagen[i-1:i+2, j-1:j+2]
            valor = np.sum(imagen_entry*ker1)    #Matrix 3x3 is filled with the elements around each [i, j] entry of the array
            imagen_nueva[i, j] = valor
    return imagen_nueva

imagen_nueva = multiplicar_entero(imagen)

plt.imshow(imagen_nueva)  #Show new image
plt.gray()
plt.show()
</code>```

Body:
I am trying to implement a Gaussian filter. For this I am using a kernel 3x3 and an array of an image.The problem I am having is defining a sub-matrix 3x3 for each [i, j] element of the array. I wrote the details inside the code.

import numpy as np
import scipy
from scipy import misc
import matplotlib.pyplot as plt

imagen = scipy.misc.imread("C:\\Users\\Reymi\\Downloads\\imagen.png") #importing image of original size (1929, 1280)

imagen_real = scipy.pad(array=imagen, pad_width=[1, 1], mode='constant', constant_values=0) #add 1 column and 1 row of zeros to avoid the kernel of going outside the array. size is (1931, 1282)

imagen_nueva = np.empty((1931, 1282)) #the new image. the same size as the image I will filter

(dim_x,dim_y)=np.shape(imagen_real)

ker1 = np.array([[1/16, 1/8, 1/16],   #3x3 kernel
                [1/8, 1/4, 1/8],
                [1/16, 1/8, 1/16]])

def multiplicar_entero():

    global imagen_nueva
    for i in range(1,dim_x): #the range starts from 1 to avoid the column and row of zeros, and ends before the last col and row of zeros
        for j in range(1,dim_y):
            imagen_entry = np.empty((3, 3))      #Main problem here: how do I define a 3x3 matrix for each entry?
            valor = np.sum(imagen_entry*ker1)    #Matrix 3x3 is filled with the elements around each [i, j] entry of the array
            imagen_real[i, j] = valor
            imagen_nueva = np.append(imagen_real[i, j], (1931, 1282)) #This is supposed to each new [i, j] entry to the new image

print("La imagen con el blur effect es la siguiente:\n")

multiplicar_entero()   #calls function

plt.imshow(imagen_nueva)  #Show new image
plt.gray()
plt.show()

Sorry for the long code. And thanks for any help.

Body:
There are a few issues with your code as is:

You are using an image we don't have access to. Always use freely available images in examples so we can run the code. I used scipy.misc.ascent here.

Don't use global variables unless you really have to.

Always code in english with english variable names and english comments. It makes reviews like this much easier.

I did some fixes to your code below, and I guess you can see how I solved your problem. Specifically you want to use : indexing which allows you extract subsets of an array and use array[i, j] to assign the result:

import numpy as np
import scipy
from scipy import misc
import matplotlib.pyplot as plt

imagen = scipy.misc.ascent()  # Freely available image

(dim_x, dim_y) = np.shape(imagen)

ker1 = np.array([[1/16, 1/8, 1/16],   #3x3 kernel
                [1/8, 1/4, 1/8],
                [1/16, 1/8, 1/16]])

def multiplicar_entero(imagen):
    imagen_nueva = np.zeros(imagen.shape) #the new image. the same size as the image I will filter
    for i in range(1,dim_x-1): #the range starts from 1 to avoid the column and row of zeros, and ends before the last col and row of zeros
        for j in range(1,dim_y-1):
            imagen_entry = imagen[i-1:i+2, j-1:j+2]
            valor = np.sum(imagen_entry*ker1)    #Matrix 3x3 is filled with the elements around each [i, j] entry of the array
            imagen_nueva[i, j] = valor
    return imagen_nueva

imagen_nueva = multiplicar_entero(imagen)

plt.imshow(imagen_nueva)  #Show new image
plt.gray()
plt.show()


问:
Adding comma separated items on separate lines to a dict in Python
I am using python 2.7, and using python dicts.

I have my output like this:

```<code>goods: apples, oranges
trunk_names: trunk01, trunk02, trunk03,trunk04,
             trunk05,trunk06, trunk07,trunk08,
             trunk09,trunk10, trunk11,trunk12
</code>```

My code:

```<code>    d = {}
    for line in output.split("\n"):
        if ":" not in line:
            continue
        key, value = line.strip().split(":", 1)
        d[key] = value
</code>```

Expected key and its value:

```<code> trunk_names: trunk01, trunk02, trunk03,trunk04,trunk05,trunk06, trunk07,trunk08,trunk09,trunk10, trunk11,trunk12
</code>```

Actual key and values being output:

```<code> trunk_names: trunk01, trunk02, trunk03,trunk04,
</code>```

答:
```<code>from collections import defaultdict

output = '''
goods: apples, oranges
trunk_names: trunk01, trunk02, trunk03,trunk04,
             trunk05,trunk06, trunk07,trunk08,
             trunk09,trunk10, trunk11,trunk12
'''

d = defaultdict(list)

current_key = None

for line in output.split('\n')[1:]:
    if ":" in line:
        current_key = line.split(':')[0].strip()
        values = line.split(':')[1]
    else:
        values = line

    d[current_key] += [
        value.strip()
        for value in values.split(',')
        if value.strip()
    ]

print(d)
</code>```

gives:

```<code>defaultdict(<type 'list'>, {'trunk_names': ['trunk01', 'trunk02', 'trunk03', 'trunk04', 'trunk05', 'trunk06', 'trunk07', 'trunk08', 'trunk09', 'trunk10', 'trunk11', 'trunk12'], 'goods': ['apples', 'oranges']})
</code>```

Body:
I am using python 2.7, and using python dicts.

I have my output like this:

goods: apples, oranges
trunk_names: trunk01, trunk02, trunk03,trunk04,
             trunk05,trunk06, trunk07,trunk08,
             trunk09,trunk10, trunk11,trunk12

My code:

    d = {}
    for line in output.split("\n"):
        if ":" not in line:
            continue
        key, value = line.strip().split(":", 1)
        d[key] = value

Expected key and its value:

 trunk_names: trunk01, trunk02, trunk03,trunk04,trunk05,trunk06, trunk07,trunk08,trunk09,trunk10, trunk11,trunk12

Actual key and values being output:

 trunk_names: trunk01, trunk02, trunk03,trunk04,

Body:
from collections import defaultdict

output = '''
goods: apples, oranges
trunk_names: trunk01, trunk02, trunk03,trunk04,
             trunk05,trunk06, trunk07,trunk08,
             trunk09,trunk10, trunk11,trunk12
'''

d = defaultdict(list)

current_key = None

for line in output.split('\n')[1:]:
    if ":" in line:
        current_key = line.split(':')[0].strip()
        values = line.split(':')[1]
    else:
        values = line

    d[current_key] += [
        value.strip()
        for value in values.split(',')
        if value.strip()
    ]

print(d)

gives:

defaultdict(<type 'list'>, {'trunk_names': ['trunk01', 'trunk02', 'trunk03', 'trunk04', 'trunk05', 'trunk06', 'trunk07', 'trunk08', 'trunk09', 'trunk10', 'trunk11', 'trunk12'], 'goods': ['apples', 'oranges']})


问:
CSS Overlapping divs of equal size
I want a div on the top of another div. Before putting the position:absolute, the p's on the top div look great, but when I put the position:absolute, it shows the three p's in a straight line with no spaces between them.

How do I make this div with position:absolute to have the p's in different lines, like it is supposed to be?

Here's an example of what I'm trying to do:

```<code><div class="box">
<p>Some text</p>

<div class="box-top">
<p>• Line 1</p>
<p>• Line 2</p>
<p>• Line 3</p>
</div>

</div>
</code>```

Like I said before, I want a div ("box-top") on the top of another div ("box").

答:
here's the answer. Hope this is what you are looking for.
One div has a black background. The overlapping div has a red background of opacity 50%.

If your p render inline instead of one above each other, chances are you did not define your DOCTYPE or did not use the html tags in your html document => use this as a starter skeleton.

```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>

  </body>
</html>
</code>```

Then here's the working example.

.flex {
  display:-webkit-box; /*OLD-iOS 6-,Safari 3.1-6 */
  display:-moz-box;    /*OLD-Firefox 19*/
  display:-ms-flexbox; /* TWEENER - IE 10 */
  display:-webkit-flex;/* NEW - Chrome */
  display: flex;
  position: relative;
}

.box {
  -webkit-box-flex: 1; /*iOS 6-, Safari 3.1-6 */
  -moz-box-flex: 1;  /* Firefox 19- */
  -webkit-flex: 1;          /* Chrome */
  -ms-flex: 1;              /* IE 10 */
  flex:1;
  position: absolute;
  background: black;
  min-width: 100%;
  min-height: 100%;
  width: auto;
  height: auto;
}

.box-top {
  -webkit-box-flex: 1; /*iOS 6-, Safari 3.1-6 */
  -moz-box-flex: 1;  /* Firefox 19- */
  -webkit-flex: 1;          /* Chrome */
  -ms-flex: 1;              /* IE 10 */
  flex:1;
  position: relative;
  background: rgba(255,0,0,0.5); /* red */
  color: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="flex">
<div class="box">
<p>Some text</p>
</div>
<div class="box-top">
<p>• Line 1</p>
<p>• Line 2</p>
<p>• Line 3</p>
</div>
</div></code>```

Title: CSS Overlapping divs of equal size

Body:
I want a div on the top of another div. Before putting the position:absolute, the p's on the top div look great, but when I put the position:absolute, it shows the three p's in a straight line with no spaces between them.

How do I make this div with position:absolute to have the p's in different lines, like it is supposed to be?

Here's an example of what I'm trying to do:

Some text

• Line 1

• Line 2

• Line 3

Like I said before, I want a div ("box-top") on the top of another div ("box").

Body:
here's the answer. Hope this is what you are looking for.
One div has a black background. The overlapping div has a red background of opacity 50%.

If your p render inline instead of one above each other, chances are you did not define your DOCTYPE or did not use the html tags in your html document => use this as a starter skeleton.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>

  </body>
</html>

Then here's the working example.

.flex {
  display:-webkit-box; /*OLD-iOS 6-,Safari 3.1-6 */
  display:-moz-box;    /*OLD-Firefox 19*/
  display:-ms-flexbox; /* TWEENER - IE 10 */
  display:-webkit-flex;/* NEW - Chrome */
  display: flex;
  position: relative;
}

.box {
  -webkit-box-flex: 1; /*iOS 6-, Safari 3.1-6 */
  -moz-box-flex: 1;  /* Firefox 19- */
  -webkit-flex: 1;          /* Chrome */
  -ms-flex: 1;              /* IE 10 */
  flex:1;
  position: absolute;
  background: black;
  min-width: 100%;
  min-height: 100%;
  width: auto;
  height: auto;
}

.box-top {
  -webkit-box-flex: 1; /*iOS 6-, Safari 3.1-6 */
  -moz-box-flex: 1;  /* Firefox 19- */
  -webkit-flex: 1;          /* Chrome */
  -ms-flex: 1;              /* IE 10 */
  flex:1;
  position: relative;
  background: rgba(255,0,0,0.5); /* red */
  color: white;
}

<div class="flex">
<div class="box">
<p>Some text</p>
</div>
<div class="box-top">
<p>• Line 1</p>
<p>• Line 2</p>
<p>• Line 3</p>
</div>
</div>


问:
Measuring the blocking part of Garbage Collection time
Java's garbage collector (GC) does not always stop the main thread. It may block all threads, or just run in parallel without pausing the other threads.

I can measure the total garbage collection time either by using
 garbageCollectorMXBean.getCollectionTime(); at the end of the program, or by running the VM with -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -verbose:gc.

However, I want to measure the portion of GCs during which the main thread is blocked (i.e. paused), so that I can measure the exact time that the main thread has been running. Is it possible to measure it?

答:
I guess your question boils down to measuring the "the exact time that the main thread has been running". In order to get to know this you don't need to measure the blocking time of the garbage collector.

The time a thread has been running corresponds to its CPU time. If you also want to consider the time waiting for I/O, then this approach won't work for you, but then the time the garbage collector pauses your thread should be negligible anyways.

I put together a simple proof of concept for you:

```<code>import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
import java.util.concurrent.TimeUnit;

public class CpuTime
{
    public static void main(String[] args) {

        // We obtain the thread mx bean and check if it support CPU time measuring.
        final ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean();
        if (!threadMxBean.isThreadCpuTimeSupported())
            throw new IllegalStateException("CPU time not supported on this platform");

        // This is important because the default value is platform-dependent.
        threadMxBean.setThreadCpuTimeEnabled(true);

        // Now we start the measurement ...
        final long threadId = Thread.currentThread().getId();
        final long wallTimeStart = System.nanoTime();
        final long cpuTimeStart = threadMxBean.getThreadCpuTime(Thread.currentThread().getId());

        // ... and do stupid things to give the garbage collector some work.
        for (int i = 0; i < 1_000_000_000; i++) {
            Long l = new Long(i);
        }

        // Finally we measure the cpu and wall time.
        final long wallTime = System.nanoTime() - wallTimeStart;
        final long cpuTime = threadMxBean.getThreadCpuTime(threadId) - cpuTimeStart;

        System.out.println("CPU time:  " + TimeUnit.NANOSECONDS.toMillis(cpuTime));
        System.out.println("Wall time: " + TimeUnit.NANOSECONDS.toMillis(wallTime));
    }
}
</code>```

Please note that this approach needs some tweaking for absolutely precise results. It should however get you started.

Body:
I guess your question boils down to measuring the "the exact time that the main thread has been running". In order to get to know this you don't need to measure the blocking time of the garbage collector.

The time a thread has been running corresponds to its CPU time. If you also want to consider the time waiting for I/O, then this approach won't work for you, but then the time the garbage collector pauses your thread should be negligible anyways.

I put together a simple proof of concept for you:

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
import java.util.concurrent.TimeUnit;

public class CpuTime
{
    public static void main(String[] args) {

        // We obtain the thread mx bean and check if it support CPU time measuring.
        final ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean();
        if (!threadMxBean.isThreadCpuTimeSupported())
            throw new IllegalStateException("CPU time not supported on this platform");

        // This is important because the default value is platform-dependent.
        threadMxBean.setThreadCpuTimeEnabled(true);

        // Now we start the measurement ...
        final long threadId = Thread.currentThread().getId();
        final long wallTimeStart = System.nanoTime();
        final long cpuTimeStart = threadMxBean.getThreadCpuTime(Thread.currentThread().getId());

        // ... and do stupid things to give the garbage collector some work.
        for (int i = 0; i < 1_000_000_000; i++) {
            Long l = new Long(i);
        }

        // Finally we measure the cpu and wall time.
        final long wallTime = System.nanoTime() - wallTimeStart;
        final long cpuTime = threadMxBean.getThreadCpuTime(threadId) - cpuTimeStart;

        System.out.println("CPU time:  " + TimeUnit.NANOSECONDS.toMillis(cpuTime));
        System.out.println("Wall time: " + TimeUnit.NANOSECONDS.toMillis(wallTime));
    }
}

Please note that this approach needs some tweaking for absolutely precise results. It should however get you started.


问:
How to set docker back to default configuration
I have installed docker compose and used it a little. Then decided I did not need it it. Now when I create containers by hand they are assigned a network with an ip address, gateway and other things. When I inspected older containers before i installed docker compose they do not have these network settings.

I have tried unoinstalling docker compose and reinstalling docker which did not work. Is there anything I can do? The reason I am asking is I can't link containers together because every new container is assigned an ip address and other network settings.

答:
Docker always does that, nothing to do with compose. Compose doesn't modify your Docker installation in any way, purely connects to the daemon to run commands under the hood.

By linking containers together I'm assuming you mean just so they can communicate with each other? --link is deprecated for some time now in favor of docker network .... Try the following:

```<code>$ docker network create test-net
$ docker run -d --name c1 --net test-net alpine:3.3 sleep 20000
$ docker run -it --name c2 --net test-net alpine:3.3 ping c1
</code>```

Body:
Docker always does that, nothing to do with compose. Compose doesn't modify your Docker installation in any way, purely connects to the daemon to run commands under the hood.

By linking containers together I'm assuming you mean just so they can communicate with each other? --link is deprecated for some time now in favor of docker network .... Try the following:

$ docker network create test-net
$ docker run -d --name c1 --net test-net alpine:3.3 sleep 20000
$ docker run -it --name c2 --net test-net alpine:3.3 ping c1


问:
Why won't Django acknowledge my class variable?
I've defined the following form class in a Django project (Django 1.11, Python 3.5), but when I execute python3 manage.py runserver, I receive a

```<code> NameError: name 'month_names' is not defined
</code>```

```<code>class MonthForm(forms.Form):
    month_names = [
        'January',
        'February',
        'March',
        'April',
        'May',
        'June',
        'July',
        'August',
        'September',
        'October',
        'November',
        'December'
        ]
    MONTH_CHOICES = [(i + 1, month_names[i]) for i in range(len(month_names))]
    month = forms.ChoiceField(choices=MONTH_CHOICES, label='Month',
                              widget=forms.Select())
</code>```

I can't figure out why this doesn't work. I've noticed that if I move the initial month_names assignment outside of the class definition, then it works. Any explanation would be greatly appreciated. Thank you in advance.

答:
The Form metaclass - DeclarativeFieldsMetaclass -  does not allow you to create (and by extension, bind) arbitrary objects that are not fields (i.e. instance of django.forms.fields.Field) on the class.

You'll have to declare such arbitrary objects outside the Form subclass.

Body:
I've defined the following form class in a Django project (Django 1.11, Python 3.5), but when I execute python3 manage.py runserver, I receive a

 NameError: name 'month_names' is not defined

class MonthForm(forms.Form):
    month_names = [
        'January',
        'February',
        'March',
        'April',
        'May',
        'June',
        'July',
        'August',
        'September',
        'October',
        'November',
        'December'
        ]
    MONTH_CHOICES = [(i + 1, month_names[i]) for i in range(len(month_names))]
    month = forms.ChoiceField(choices=MONTH_CHOICES, label='Month',
                              widget=forms.Select())

I can't figure out why this doesn't work. I've noticed that if I move the initial month_names assignment outside of the class definition, then it works. Any explanation would be greatly appreciated. Thank you in advance.


问:
dynamically attached textarea throws Error#1009 - but similar labels and textinputs do not
This code in my scene works perfectly fine with the comments:

```<code>import state;
import fl.controls.TextInput;
import fl.controls.TextArea;
import flash.events.TextEvent;

state.data.newNotice = new Object();
state.data.newNotice.title='';
state.data.newNotice.text='';

var noticeTitleInput:TextInput = new TextInput();
noticeTitleInput.width = noticeTitleEditor.width;
noticeTitleInput.height = noticeTitleEditor.height;
noticeTitleInput.text = '';
noticeTitleInput.setStyle("textFormat", state.data.fontFormat);
noticeTitleEditor.addChild(noticeTitleInput);

noticeTitleInput.addEventListener(TextEvent.TEXT_INPUT, onInput);

/*var noticeTextInput:TextArea = new TextArea();
noticeTextInput.wordWrap = true;
noticeTextInput.width = noticeEditor.width;
noticeTextInput.height = noticeEditor.height;
noticeTextInput.text = '';
noticeTextInput.setStyle("textFormat", state.data.fontFormat);
noticeEditor.addChild(noticeTextInput);

noticeTextInput.addEventListener(TextEvent.TEXT_INPUT, onInput);*/

function onInput(event:TextEvent):void {
    state.data.newNotice.title = noticeTitleInput.text;
//  state.data.newNotice.text = noticeTextInput.text;
}
</code>```

Uncomment it though and the textarea throws an error:

```<code>TypeError: Error #1009: Cannot access a property or method of a null object reference.
    at fl.controls::TextArea/drawLayout()
    at fl.controls::TextArea/draw()
    at fl.core::UIComponent/callLaterDispatcher()
TypeError: Error #2007: Parameter child must be non-null.
    at flash.display::DisplayObjectContainer/addChildAt()
    at fl.controls::BaseButton/drawBackground()
    at fl.controls::BaseButton/draw()
    at fl.core::UIComponent/drawNow()
    at fl.controls::ScrollBar/draw()
    at fl.controls::UIScrollBar/draw()
    at fl.core::UIComponent/callLaterDispatcher()
TypeError: Error #2007: Parameter child must be non-null.
    at flash.display::DisplayObjectContainer/addChildAt()
    at fl.controls::BaseButton/drawBackground()
    at fl.controls::BaseButton/draw()
    at fl.core::UIComponent/callLaterDispatcher()
TypeError: Error #2007: Parameter child must be non-null.
    at flash.display::DisplayObjectContainer/addChildAt()
    at fl.controls::BaseButton/drawBackground()
    at fl.controls::LabelButton/draw()
    at fl.core::UIComponent/callLaterDispatcher()
TypeError: Error #2007: Parameter child must be non-null.
    at flash.display::DisplayObjectContainer/addChildAt()
    at fl.controls::BaseButton/drawBackground()
    at fl.controls::BaseButton/draw()
    at fl.core::UIComponent/callLaterDispatcher()
TypeError: Error #2007: Parameter child must be non-null.
    at flash.display::DisplayObjectContainer/addChildAt()
    at fl.controls::BaseButton/drawBackground()
    at fl.controls::BaseButton/draw()
    at fl.core::UIComponent/callLaterDispatcher()
TypeError: Error #2007: Parameter child must be non-null.
    at flash.display::DisplayObjectContainer/addChildAt()
    at fl.controls::BaseButton/drawBackground()
    at fl.controls::BaseButton/draw()
    at fl.core::UIComponent/drawNow()
    at fl.controls::ScrollBar/draw()
    at fl.controls::UIScrollBar/draw()
    at fl.core::UIComponent/callLaterDispatcher()
TypeError: Error #2007: Parameter child must be non-null.
    at flash.display::DisplayObjectContainer/addChildAt()
    at fl.controls::BaseButton/drawBackground()
    at fl.controls::BaseButton/draw()
    at fl.core::UIComponent/callLaterDispatcher()
TypeError: Error #2007: Parameter child must be non-null.
    at flash.display::DisplayObjectContainer/addChildAt()
    at fl.controls::BaseButton/drawBackground()
    at fl.controls::LabelButton/draw()
    at fl.core::UIComponent/callLaterDispatcher()
TypeError: Error #2007: Parameter child must be non-null.
    at flash.display::DisplayObjectContainer/addChildAt()
    at fl.controls::BaseButton/drawBackground()
    at fl.controls::BaseButton/draw()
    at fl.core::UIComponent/callLaterDispatcher()
TypeError: Error #2007: Parameter child must be non-null.
    at flash.display::DisplayObjectContainer/addChildAt()
    at fl.controls::BaseButton/drawBackground()
    at fl.controls::BaseButton/draw()
    at fl.core::UIComponent/callLaterDispatcher()
</code>```

I don't understand why this is not working with a text area because, the same pattern was working for me with label and with textinput. What could be wrong?

答:
Flash components require 2 things: component classes and component graphics that is added to Library when you drag components from their panel. Some components require a number of additional assets so if they are not in Library for whatever reason (deleted by mistake or something) that could result in runtime errors and/or non-functional components.

Developer should always keep the Library organized!

Body:
This code in my scene works perfectly fine with the comments:

import state;
import fl.controls.TextInput;
import fl.controls.TextArea;
import flash.events.TextEvent;

state.data.newNotice = new Object();
state.data.newNotice.title='';
state.data.newNotice.text='';

var noticeTitleInput:TextInput = new TextInput();
noticeTitleInput.width = noticeTitleEditor.width;
noticeTitleInput.height = noticeTitleEditor.height;
noticeTitleInput.text = '';
noticeTitleInput.setStyle("textFormat", state.data.fontFormat);
noticeTitleEditor.addChild(noticeTitleInput);

noticeTitleInput.addEventListener(TextEvent.TEXT_INPUT, onInput);

/*var noticeTextInput:TextArea = new TextArea();
noticeTextInput.wordWrap = true;
noticeTextInput.width = noticeEditor.width;
noticeTextInput.height = noticeEditor.height;
noticeTextInput.text = '';
noticeTextInput.setStyle("textFormat", state.data.fontFormat);
noticeEditor.addChild(noticeTextInput);

noticeTextInput.addEventListener(TextEvent.TEXT_INPUT, onInput);*/

function onInput(event:TextEvent):void {
    state.data.newNotice.title = noticeTitleInput.text;
//  state.data.newNotice.text = noticeTextInput.text;
}

Uncomment it though and the textarea throws an error:

TypeError: Error #1009: Cannot access a property or method of a null object reference.
    at fl.controls::TextArea/drawLayout()
    at fl.controls::TextArea/draw()
    at fl.core::UIComponent/callLaterDispatcher()
TypeError: Error #2007: Parameter child must be non-null.
    at flash.display::DisplayObjectContainer/addChildAt()
    at fl.controls::BaseButton/drawBackground()
    at fl.controls::BaseButton/draw()
    at fl.core::UIComponent/drawNow()
    at fl.controls::ScrollBar/draw()
    at fl.controls::UIScrollBar/draw()
    at fl.core::UIComponent/callLaterDispatcher()
TypeError: Error #2007: Parameter child must be non-null.
    at flash.display::DisplayObjectContainer/addChildAt()
    at fl.controls::BaseButton/drawBackground()
    at fl.controls::BaseButton/draw()
    at fl.core::UIComponent/callLaterDispatcher()
TypeError: Error #2007: Parameter child must be non-null.
    at flash.display::DisplayObjectContainer/addChildAt()
    at fl.controls::BaseButton/drawBackground()
    at fl.controls::LabelButton/draw()
    at fl.core::UIComponent/callLaterDispatcher()
TypeError: Error #2007: Parameter child must be non-null.
    at flash.display::DisplayObjectContainer/addChildAt()
    at fl.controls::BaseButton/drawBackground()
    at fl.controls::BaseButton/draw()
    at fl.core::UIComponent/callLaterDispatcher()
TypeError: Error #2007: Parameter child must be non-null.
    at flash.display::DisplayObjectContainer/addChildAt()
    at fl.controls::BaseButton/drawBackground()
    at fl.controls::BaseButton/draw()
    at fl.core::UIComponent/callLaterDispatcher()
TypeError: Error #2007: Parameter child must be non-null.
    at flash.display::DisplayObjectContainer/addChildAt()
    at fl.controls::BaseButton/drawBackground()
    at fl.controls::BaseButton/draw()
    at fl.core::UIComponent/drawNow()
    at fl.controls::ScrollBar/draw()
    at fl.controls::UIScrollBar/draw()
    at fl.core::UIComponent/callLaterDispatcher()
TypeError: Error #2007: Parameter child must be non-null.
    at flash.display::DisplayObjectContainer/addChildAt()
    at fl.controls::BaseButton/drawBackground()
    at fl.controls::BaseButton/draw()
    at fl.core::UIComponent/callLaterDispatcher()
TypeError: Error #2007: Parameter child must be non-null.
    at flash.display::DisplayObjectContainer/addChildAt()
    at fl.controls::BaseButton/drawBackground()
    at fl.controls::LabelButton/draw()
    at fl.core::UIComponent/callLaterDispatcher()
TypeError: Error #2007: Parameter child must be non-null.
    at flash.display::DisplayObjectContainer/addChildAt()
    at fl.controls::BaseButton/drawBackground()
    at fl.controls::BaseButton/draw()
    at fl.core::UIComponent/callLaterDispatcher()
TypeError: Error #2007: Parameter child must be non-null.
    at flash.display::DisplayObjectContainer/addChildAt()
    at fl.controls::BaseButton/drawBackground()
    at fl.controls::BaseButton/draw()
    at fl.core::UIComponent/callLaterDispatcher()

I don't understand why this is not working with a text area because, the same pattern was working for me with label and with textinput. What could be wrong?


问:
From where should I install git: xcode-select --install or brew install git?
From where should I install git:
xcode-select --install or brew install git?

答:
I'd advise downloading with homebrew. You'll benefit from the frequent updates which will give you access to newer features and more stability.

It's nice that Apple decided to give users an easy way to download programming tools, but they are very out dated.


问:
Event on Keystone JS view not working
I'm doing an e-commerce site (learning purposes) with KeystoneJS. In the view where I display all the products I want to add a filter for sort the items by price and another one to show the products of only one brand. Two forms are needed but I don't get to submit only one

My products.pug looks like this

```<code>.container
  form(method='post')
    input(type='hidden', name='action', value='products')
    button(type='submit').btn.btn-primary Send
</code>```

And my products.js in routes/views/ looks like this

```<code>[...]
// Print a word when submit the form
view.on('post', { action: 'products' }, function(next) {
  console.log('POST')
  next()
})
// Get all products from db
view.on('init'...)
// Render
view.render('products')
</code>```

So basically what I want to do is to print POST when I hit the button in the view. Instead of that, I receive a 404 error page. I would really appreciate if you guys can help me

答:
Got it! In /routes/index.js I replaced

```<code>app.get('/products', route.views.products);
</code>```

for

```<code>app.all('/products', route.views.products);
</code>```

I feel dummy but happy.

Title: Event on Keystone JS view not working

Body:
I'm doing an e-commerce site (learning purposes) with KeystoneJS. In the view where I display all the products I want to add a filter for sort the items by price and another one to show the products of only one brand. Two forms are needed but I don't get to submit only one

My products.pug looks like this

.container
  form(method='post')
    input(type='hidden', name='action', value='products')
    button(type='submit').btn.btn-primary Send

And my products.js in routes/views/ looks like this

[...]
// Print a word when submit the form
view.on('post', { action: 'products' }, function(next) {
  console.log('POST')
  next()
})
// Get all products from db
view.on('init'...)
// Render
view.render('products')

So basically what I want to do is to print POST when I hit the button in the view. Instead of that, I receive a 404 error page. I would really appreciate if you guys can help me

Body:
Got it! In /routes/index.js I replaced

app.get('/products', route.views.products);

for

app.all('/products', route.views.products);

I feel dummy but happy.


问:
Script to delete all non-system objects in SQL Server 2008
Does anyone have a script that will delete all non-system tables/procs/views from a database?

I created some views, procs and tables which I need to clean up and doing them individually is too cumbersome.

答:
Wouldn't it be easier to drop/recreate the database?</p>

```<code>DROP DATABASE yourdbname
CREATE DATABASE yourdbname
</code>```

Body:
Wouldn't it be easier to drop/recreate the database?

DROP DATABASE yourdbname
CREATE DATABASE yourdbname


问:
turning string into a number
I am trying to calculate the price total of the below html code and add the result to the dom throuh the JS code further below:

```<code><div class="row">
<div class="col-xs-2 text-center">
<span class="p-name">IronBubble-head</span>
<span id="price-number">$25</span>
<label id="qty" for="qty">QTY</label><input type="number" value="1">
<span id="total">0</span>
<button class="btn btn-delete" type="button">Delete</button>
</div>
</div>
</code>```

and this javascript code:

```<code>function getTotalPrice(e) {
var Price = document.getElementById('price-number').value;
var Quantity = document.getElementById('qty').value;
var Total = document.getElementById('total');
total.innerHTML = Price * Quantity;
}
</code>```

Although the result I get is always NaN.
where is the mistake?

Thanks!

答:
Your #price-number element has $ character, that you cant make math operation, so you need clean first.

So you could use a .replace to remove $ character:

```<code>Price = Price.replace(/\$/, '');
</code>```

And instead of use .value you may use .innerHTML

```<code>var Price = document.getElementById('price-number').value;
</code>```

Another thing is to put the id="qty" in input element, cause the value is in there.

Like that:

function getTotalPrice() {
  var Price = document.getElementById('price-number').innerHTML;
  Price = Price.replace(/\$/, '');
  var Quantity = document.getElementById('qty').value;
  var Total = document.getElementById('total');
  total.innerHTML = Price * Quantity;
}

getTotalPrice();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
  <div class="col-xs-2 text-center">
    <span class="p-name">IronBubble-head</span>
    <span id="price-number">$25</span>
    <label for="qty">QTY</label><input id="qty" type="number" value="1">
    <span id="total">0</span>

    <button class="btn btn-calc" type="button" onclick="getTotalPrice()">Calc</button>
    <button class="btn btn-delete" type="button">Delete</button>
  </div>
</div></code>```

Title: turning string into a number

Body:
I am trying to calculate the price total of the below html code and add the result to the dom throuh the JS code further below:

IronBubble-head
$25
QTY<input type="number" value="1">
0
<button class="btn btn-delete" type="button">Delete</button>

and this javascript code:

function getTotalPrice(e) {
var Price = document.getElementById('price-number').value;
var Quantity = document.getElementById('qty').value;
var Total = document.getElementById('total');
total.innerHTML = Price * Quantity;
}

Although the result I get is always NaN.
where is the mistake?

Thanks!

Body:
Your #price-number element has $ character, that you cant make math operation, so you need clean first.

So you could use a .replace to remove $ character:

Price = Price.replace(/\$/, '');

And instead of use .value you may use .innerHTML

var Price = document.getElementById('price-number').value;

Another thing is to put the id="qty" in input element, cause the value is in there.

Like that:

function getTotalPrice() {
  var Price = document.getElementById('price-number').innerHTML;
  Price = Price.replace(/\$/, '');
  var Quantity = document.getElementById('qty').value;
  var Total = document.getElementById('total');
  total.innerHTML = Price * Quantity;
}

getTotalPrice();

<div class="row">
  <div class="col-xs-2 text-center">
    <span class="p-name">IronBubble-head</span>
    <span id="price-number">$25</span>
    <label for="qty">QTY</label><input id="qty" type="number" value="1">
    <span id="total">0</span>

    <button class="btn btn-calc" type="button" onclick="getTotalPrice()">Calc</button>
    <button class="btn btn-delete" type="button">Delete</button>
  </div>
</div>


问:
Partitioned View ( union all in view ) in google big query or any database
Is there a disadvantage of using Partitioned view. Example what I mean as below.

https://sqlsunday.com/2014/08/31/partitioned-views/

However instead of using date, I want to partition by other field type. e.g.
Product Type or Country.

so the view will be

```<code>Select '1' as Prod_type, 'USA' as Country , *
from fact_Sales_1_USA
union all
Select '2' as Prod_type, 'UK' as Country , *
from fact_Sales_2_UK
</code>```

This way it will prevent query from reading the whole table and just limit to the particular Product Type and Region.

One of disadvantage is our course the update of data slightly more complex?

Will it slow down a query where I don't use the field above?

答:
BigQuery does not currently support partitioning by non-date columns. The only way to emulate this is to have a separate table for each product type or region, for example, and then use a table wildcard to enable filtering on them.

If your tables have the following names, for example:

```<code>MyTable_USA_1
MyTable_USA_3
MyTable_UK_2
MyTable_France_1
...
</code>```

You can create a logical view as:

```<code>#standardSQL
SELECT
  *,
    _TABLE_SUFFIX AS country_and_product
FROM `MyTable_*`;
</code>```

Now when you query it, you can filter on the country (and optionally product number):

```<code>#standardSQL
SELECT
  * EXCEPT (country_and_product)
FROM CountryAndProductView
WHERE country_and_product LIKE 'UK_%'
  -- AND country_and_product LIKE '%_2'
</code>```

One thing to keep in mind is that there is a limit of 1000 tables per query, so this approach won't work if you have too many combinations of countries and products. If that's the case, you may need to "partition" just by one of them rather than by both.

Body:
Is there a disadvantage of using Partitioned view. Example what I mean as below.

https://sqlsunday.com/2014/08/31/partitioned-views/

However instead of using date, I want to partition by other field type. e.g.
Product Type or Country.

so the view will be

Select '1' as Prod_type, 'USA' as Country , *
from fact_Sales_1_USA
union all
Select '2' as Prod_type, 'UK' as Country , *
from fact_Sales_2_UK

This way it will prevent query from reading the whole table and just limit to the particular Product Type and Region.

One of disadvantage is our course the update of data slightly more complex?

Will it slow down a query where I don't use the field above?

Body:
BigQuery does not currently support partitioning by non-date columns. The only way to emulate this is to have a separate table for each product type or region, for example, and then use a table wildcard to enable filtering on them.

If your tables have the following names, for example:

MyTable_USA_1
MyTable_USA_3
MyTable_UK_2
MyTable_France_1
...

You can create a logical view as:

#standardSQL
SELECT
  *,
    _TABLE_SUFFIX AS country_and_product
FROM `MyTable_*`;

Now when you query it, you can filter on the country (and optionally product number):

#standardSQL
SELECT
  * EXCEPT (country_and_product)
FROM CountryAndProductView
WHERE country_and_product LIKE 'UK_%'
  -- AND country_and_product LIKE '%_2'

One thing to keep in mind is that there is a limit of 1000 tables per query, so this approach won't work if you have too many combinations of countries and products. If that's the case, you may need to "partition" just by one of them rather than by both.


问:
Run C# code on linux terminal
How can I execute a C# code on a linux terminal as a shell script.

I have this sample code:

```<code>public string Check(string _IPaddress,string _Port, int _SmsID)
{
ClassGlobal._client = new TcpClient(_IPaddress, Convert.ToInt32(_Port));
ClassGlobal.SMSID = _SmsID;
string _result = SendToCAS(_IPaddress, _Port, _SmsID );
if (_result != "") return (_result);
string _acoknoledgement = GetFromCAS();
return _acoknoledgement;
}
</code>```

When I run a shell bash I use #!/bin/bash. There is how to do the same with C#?

答:
Of course it can be done and the process is extremely simple.

Here I am explaining the steps for Ubuntu Linux.

Open terminal:

Ctrl + Alt + T

Type

```<code>gedit hello.cs
</code>```

In the gedit window that opens paste the following example code:

```<code>using System;
class HelloWorld {
  static void Main() {
    Console.WriteLine("Hello World!");
  }
}
</code>```

Save and close gedit.

Back in terminal type:

```<code>sudo apt update
sudo apt install mono-complete
mcs -out:hello.exe hello.cs
mono hello.exe
</code>```

Output:

```<code>Hello World!
</code>```

Title: Run C# code on linux terminal

Body:
How can I execute a C# code on a linux terminal as a shell script.

I have this sample code:

public string Check(string _IPaddress,string _Port, int _SmsID)
{
ClassGlobal._client = new TcpClient(_IPaddress, Convert.ToInt32(_Port));
ClassGlobal.SMSID = _SmsID;
string _result = SendToCAS(_IPaddress, _Port, _SmsID );
if (_result != "") return (_result);
string _acoknoledgement = GetFromCAS();
return _acoknoledgement;
}

When I run a shell bash I use #!/bin/bash. There is how to do the same with C#?

Body:
Of course it can be done and the process is extremely simple.

Here I am explaining the steps for Ubuntu Linux.

Open terminal:

Ctrl + Alt + T

Type

gedit hello.cs

In the gedit window that opens paste the following example code:

using System;
class HelloWorld {
  static void Main() {
    Console.WriteLine("Hello World!");
  }
}

Save and close gedit.

Back in terminal type:

sudo apt update
sudo apt install mono-complete
mcs -out:hello.exe hello.cs
mono hello.exe

Output:

Hello World!