问:
load part of the html page when filtering results with ajax
I want to filter a search results using 3 checkboxs. The results are presented in the div with the id=posts_results

```<code>   <div class="checkbox">
      <label><input type="checkbox" id="id1" class="typePost" value="En groupe"> val1 </label>
   </div>
   <div class="checkbox">
      <label><input type="checkbox" id="id2" class="typePost" value="En groupe"> val2 </label>
   </div>
   <div class="checkbox">
      <label><input type="checkbox" id="id3" class="typePost"  value="A domicile"> val3</label>
   </div>
   <div class="checkbox">
      <label><input type="checkbox" id="id4" class="typePost" value="Par webcam"> val4</label>
   </div>

  <div id="posts_results">

            {% include 'posts/posts_results.html' %}

   </div>

    <script>
        $('.typePost').change(function (request, response) {

        var v1=$('#id1').is(":checked")? 1:0;
        var V2=$('#id2').is(":checked")? 1:0;
        var V3=$('#id3').is(":checked")? 1:0;
        var v4=$('#id4').is(":checked")? 1:0;
        $.ajax({

            url: '/posts/type_lesson/',
            dataType: 'json',
            type: "GET",
            data: {
                group: groupChecked,
                webcam: webcamChecked,
                home: homeChecked,
                move: moveChecked,
                distance: distance,
            },
            success: function (object_list) {

                $('#posts_results').load("my_page.html", object_list);
                alert('after')
            }

        });

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

this is my url:

```<code>url(r'^filter/$', views.filter, name='filter_type_lesson'),
</code>```

and this is my view:

```<code>def filter(request):
if request.method=='GET':

    #as an exemple I'll send all posts
    data= PostFullSerializer(Post.objects.all(), many=True)
    return JsonResponse(data.data, safe=False)
</code>```

The filter function excute some filters according to the json sent data, serialize the filtered posts and send them back (in this case I send all the posts as an example).

The results are displayed using a forloop in the div with id "posts_results" and the html is in the file posts_results.html.

The json data are sent but the ajax success function does not update or load the div

and it is also possible to stay

答:
I like to stay away from raw POST data as much as possible and let the forms API do the heavy lifting. You can do what you have already with a lot less code in a much more secure way.

Make a form with four BooleanFields named for the BooleanFields in your model. You can override how they are displayed in the HTML with the label variable.

```<code>class TheForm(forms.Form):
    my_field = forms.BooleanField(required=False, label="What I want it to say")
    my_field2 = forms.BooleanField(required=False, label="What I want it to say 2", help_text="Something else")
    my_field3 = forms.BooleanField(required=False, label="What I want it to say 3", help_text="Something else")
</code>```

Output as <form class="my_form">{% csrf_token %}{{form.as_table}}</form>

Submit it with JS like this:

```<code>$('.my_form input[type=checkbox]').change(function(e){
    e.preventDefault()
    $.post('module/filer/', $('.my_form').serialize(), function(data) {
        // Handle data
    });
});
</code>```

When the form is submitted and validated take the cleaned_data attribute and filter your models like this

```<code>models = Post.objets.filter(**form.cleaned_data)
</code>```

This will work because the form fields and named the same as the fields in your model. The same as doing Post.objects.filter(my_field=True, my_field2=True, my_field3=False). Then you can do whatever you want with it. I would use a FormView to do all this:

```<code>class MyView(FormView):
    form_class = TheForm

    def form_valid(self, form):
        models = Post.objets.filter(**form.cleaned_data)
        data= PostFullSerializer(data, many=True)
        return JsonResponse(data.data, safe=False)
</code>```

Now nothing is going to update the div by itself. It is only created when the HTML is initially requested. In your success function you'll need to append your elements manually like this:

```<code>$('.my_form input[type=checkbox]').change(function(e){
    e.preventDefault()
    $.post('module/filer/', $('.my_form').serialize(), function(data) {
        var post_results = $('#post_results').html(''); // Clear out old html
        $.each(data, function(item) {
            // Create new divs from ajax data and append it to main div
            var div = $('<div>');
            div.append($('<div>').html(item.my_field));
            div.append($('<div>').html(item.my_field2).addClass('something'));
            div.appendTo(post_results);
        });
    });
});
</code>```

You can also just past rendered HTML through ajax and do $('#post_results').html(data);. Instead of calling json response you would call self.render_to_response on the FormView.

Body:
I want to filter a search results using 3 checkboxs. The results are presented in the div with the id=posts_results

      <input type="checkbox" id="id1" class="typePost" value="En groupe"> val1

      <input type="checkbox" id="id2" class="typePost" value="En groupe"> val2

      <input type="checkbox" id="id3" class="typePost"  value="A domicile"> val3

      <input type="checkbox" id="id4" class="typePost" value="Par webcam"> val4

            {% include 'posts/posts_results.html' %}

Body:
I like to stay away from raw POST data as much as possible and let the forms API do the heavy lifting. You can do what you have already with a lot less code in a much more secure way.

Make a form with four BooleanFields named for the BooleanFields in your model. You can override how they are displayed in the HTML with the label variable.

class TheForm(forms.Form):
    my_field = forms.BooleanField(required=False, label="What I want it to say")
    my_field2 = forms.BooleanField(required=False, label="What I want it to say 2", help_text="Something else")
    my_field3 = forms.BooleanField(required=False, label="What I want it to say 3", help_text="Something else")

Output as <form class="my_form">{% csrf_token %}{{form.as_table}}</form>

Submit it with JS like this:

$('.my_form input[type=checkbox]').change(function(e){
    e.preventDefault()
    $.post('module/filer/', $('.my_form').serialize(), function(data) {
        // Handle data
    });
});

When the form is submitted and validated take the cleaned_data attribute and filter your models like this

models = Post.objets.filter(**form.cleaned_data)

This will work because the form fields and named the same as the fields in your model. The same as doing Post.objects.filter(my_field=True, my_field2=True, my_field3=False). Then you can do whatever you want with it. I would use a FormView to do all this:

class MyView(FormView):
    form_class = TheForm

    def form_valid(self, form):
        models = Post.objets.filter(**form.cleaned_data)
        data= PostFullSerializer(data, many=True)
        return JsonResponse(data.data, safe=False)

Now nothing is going to update the div by itself. It is only created when the HTML is initially requested. In your success function you'll need to append your elements manually like this:

$('.my_form input[type=checkbox]').change(function(e){
    e.preventDefault()
    $.post('module/filer/', $('.my_form').serialize(), function(data) {
        var post_results = $('#post_results').html(''); // Clear out old html
        $.each(data, function(item) {
            // Create new divs from ajax data and append it to main div
            var div = $('<div>');
            div.append($('<div>').html(item.my_field));
            div.append($('<div>').html(item.my_field2).addClass('something'));
            div.appendTo(post_results);
        });
    });
});

You can also just past rendered HTML through ajax and do $('#post_results').html(data);. Instead of calling json response you would call self.render_to_response on the FormView.


来源: stackexchange

问:
Cannot Resolve Symbol ArrayList on OncreateView (fragment)
I want to initialize a new array list in a Fragment (onCreateView), but it says (cannot resolve symbol) and I don't know why.

How to fix that? since it seems that some statements change in the onCreateView method.

Thx

答:
Ok, I have found the solution.

I just needed to add an ArrayList , before initializing.

```<code>ArrayList articlesList = new ArrayList<Articles>();
ListView listview = (ListView) view.findViewById(R.id.list);
ArticlesAdapter adapter = new ArticlesAdapter(getActivity().getApplicationContext(), R.layout.articles, articlesList);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Ok, I have found the solution.

I just needed to add an ArrayList , before initializing.

ArrayList articlesList = new ArrayList<Articles>();
ListView listview = (ListView) view.findViewById(R.id.list);
ArticlesAdapter adapter = new ArticlesAdapter(getActivity().getApplicationContext(), R.layout.articles, articlesList);


问:
Modifying assembly instructions before loading
I have a DLL that I need to load (I have written it and compiled it), and I would like to insert instructions between existing instructions of the assembly code before loading the DLL into memory. Of course, you can't just read every byte and insert them between there because instructions sometimes are multiple bytes.

I was thinking of using something like Udis86 and reading instructions one by one and then writing them to memory, and between them writing my other instructions. Is this a good approach or is there something better?

答:
You have (at least) two choices:

open the DLL file and modify it using file read/write operations

load the DLL and modify the instructions before they execute

Both are possible, though with the latter it will be necessary to circumvent or disable security protection:  code (as opposed to data) is loaded into memory which is not writable in most (if not all—not sure about CE) Windows environments.

With the code loaded, there is direct o/s support to find symbol addresses.  Modifying a file will require either advanced knowledge about decoding the symbol information and interpreting the file offset, or searching for patterns placed in the file specifically for the purpose.  This can be logic in the DllMain entry point which is called to initialize the DLL, or any other function within the DLL which is known to execute early enough.

There are also the techniques of DLL injection which could accomplish the same ends.

But, Instead of all this, what about arranging for the DLL to use some callback function  pass to it once you've composed the code to execute?  It's hard to tell what's useful without knowing more about what you are trying to accomplish.

As for how to do it, an easy way is to write the instructions in an assembly module, assemble it, and then examine the generated bytes.  Naturally, you should thoroughly understand the target assembly language so that branch and relative jump offsets—as well as data references—are computed or fixed up correctly.  While is it possible and sometimes practical to disassemble instructions at runtime, it's usually easier to have already identified the instructions through some other means (like a debugger) and have the program look for the byte sequence and then perform whatever transformations are needed.

ContentLicense: CC BY-SA 2.5


问:
how could I swipe the page from left to right in order to go back in a webview?
In a web view,I want to swipe the page from left to right in order to go back,just like what safari did.
what should I do?</p>

答:
TL/DR: Currently, you'll need a third party package for that. Use the react-native-wkwebview-reborn package and set the  allowsBackForwardNavigationGestures prop to true. Example:

WebView.ios.js:

```<code>import React from 'react';
import WKWebView from 'react-native-wkwebview-reborn';

export default (props) => <WKWebView allowsBackForwardNavigationGestures {...props} />
</code>```

WebView.js

```<code>import { WebView } from 'react-native';

export default WebView;
</code>```

It's a drop-in replacement, so you won't need to change much code.

Why:

The WebView component from React Native uses UIWebView under the hood, which is not recommended by Apple anymore:

It has worse performance and does not support a lot of features, like 3D Touch and swipe back gesture.

Join this discussion so react native updates their core component.

Body:
TL/DR: Currently, you'll need a third party package for that. Use the react-native-wkwebview-reborn package and set the  allowsBackForwardNavigationGestures prop to true. Example:

WebView.ios.js:

import React from 'react';
import WKWebView from 'react-native-wkwebview-reborn';

export default (props) => <WKWebView allowsBackForwardNavigationGestures {...props} />

WebView.js

import { WebView } from 'react-native';

export default WebView;

It's a drop-in replacement, so you won't need to change much code.

Why:

The WebView component from React Native uses UIWebView under the hood, which is not recommended by Apple anymore:

It has worse performance and does not support a lot of features, like 3D Touch and swipe back gesture.

Join this discussion so react native updates their core component.


问:
Updating dictionary values of keys from a .txt file
So I've created a dictionary off the txt file "PM.txt" where the key is the player and the value is their penalty minutes. I know dictionary keys have to be unique so how would I update the value of the key adding it to the current value, as the key exists more than once in the txt file.

```<code>    "PM.txt"
    Neil,2
    Paul,5
    Neil,10
    Santos,2
    Neil,2
    Santos,10
    Paul,2
    Alex,2
</code>```

So far I have this which returns:

{'Alex': 2, 'Santos': 10, 'Paul': 2, 'Neil': 2}

```<code>    def pm_dict(filename):
        f = open(filename, 'r')
        dict = {}
        for line in f:
            x = line.split(",")
            player = x[0]
            minutes = x[1]
            c = len(minutes)-2
            minutes = minutes[0:c]
            dict[player] = minutes

        return dict
</code>```

But how would I create a function or a helper for it to return:

{'Alex': 2, 'Santos': 12, 'Paul': 7, 'Neil': 14}

答:
in your for loop, instead of dict[player] = minutes:

```<code>if player not in dict:
    dict[player] = 0

dict[player] += minutes
</code>```

Also, instead of:

```<code>        minutes = x[1]
        c = len(minutes)-2
        minutes = minutes[0:c]
</code>```

You can do:

```<code>minutes = x[1].strip()
</code>```

Body:
So I've created a dictionary off the txt file "PM.txt" where the key is the player and the value is their penalty minutes. I know dictionary keys have to be unique so how would I update the value of the key adding it to the current value, as the key exists more than once in the txt file.

    "PM.txt"
    Neil,2
    Paul,5
    Neil,10
    Santos,2
    Neil,2
    Santos,10
    Paul,2
    Alex,2

So far I have this which returns:

{'Alex': 2, 'Santos': 10, 'Paul': 2, 'Neil': 2}

    def pm_dict(filename):
        f = open(filename, 'r')
        dict = {}
        for line in f:
            x = line.split(",")
            player = x[0]
            minutes = x[1]
            c = len(minutes)-2
            minutes = minutes[0:c]
            dict[player] = minutes

        return dict

But how would I create a function or a helper for it to return:

{'Alex': 2, 'Santos': 12, 'Paul': 7, 'Neil': 14}

Body:
in your for loop, instead of dict[player] = minutes:

if player not in dict:
    dict[player] = 0

dict[player] += minutes

Also, instead of:

        minutes = x[1]
        c = len(minutes)-2
        minutes = minutes[0:c]

You can do:

minutes = x[1].strip()


问:
Setting up a frame in Java
I am new to Java and I've been trying to setup a frame, but my code does not work, either because the code is just wrong, or because there is something wrong with my software. I am using Eclipse.

So this is my code:

```<code>package Frame;

import javax.swing.JFrame;

public class App {

 class FrameApp extends JFrame {

     public static void main(String[] args) {

        JFrame frame = new JFrame("FirstFrame");
        frame.setTitle("MFF");
        frame.setSize(300, 700);
        frame.setVisible(true);

     }
  }

}
</code>```

it returns

The method main cannot be declared static; static methods can only be
  declared in a static or top level type

答:
the problem is that you are declaring the main method in an inner class. that's what the thrown exception means.
This will work for you.

```<code>package Frame;

import javax.swing.JFrame;

class FrameApp extends JFrame{
public FrameApp(String name){
super(name);
}
}

public class App {

 public static void main(String[] args) {

    FrameApp frame = new FrameApp("FirstFrame");
    frame.setTitle("MFF");
    frame.setSize(300, 700);
    frame.setVisible(true);

 }

}
</code>```

Enjoy! :)

Title: Setting up a frame in Java

Body:
I am new to Java and I've been trying to setup a frame, but my code does not work, either because the code is just wrong, or because there is something wrong with my software. I am using Eclipse.

So this is my code:

package Frame;

import javax.swing.JFrame;

public class App {

 class FrameApp extends JFrame {

     public static void main(String[] args) {

        JFrame frame = new JFrame("FirstFrame");
        frame.setTitle("MFF");
        frame.setSize(300, 700);
        frame.setVisible(true);

     }
  }

}

it returns

The method main cannot be declared static; static methods can only be
  declared in a static or top level type

Body:
the problem is that you are declaring the main method in an inner class. that's what the thrown exception means.
This will work for you.

package Frame;

import javax.swing.JFrame;

class FrameApp extends JFrame{
public FrameApp(String name){
super(name);
}
}

public class App {

 public static void main(String[] args) {

    FrameApp frame = new FrameApp("FirstFrame");
    frame.setTitle("MFF");
    frame.setSize(300, 700);
    frame.setVisible(true);

 }

}

Enjoy! :)


问:
JSON: getElementById returns Undefined
I have a text input where I write a barcode it returns the name and the price from the database.

My code looks like this:

View:

```<code><script>
function showProduct(str) {
    if (str == "") {
        document.getElementById("txtHint").innerHTML = "";
        return;
    } else {
        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        }
        xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                console.log(this.responseText);
                var jsonObject =  JSON.stringify(this.responseText);
                document.getElementById("nameHint").innerHTML = jsonObject["name"];
                document.getElementById("priceHint").innerHTML = jsonObject["price"];
}
        };
        xmlhttp.open("GET","/getproduct/q="+str,true);
        xmlhttp.send();
    }
}
</script>
{{ Form::open() }}
{{Form::text('barcode', null, ['onchange'=>"showProduct(this.value)"])}}
<div id="nameHint></div>
<div id="priceHint></div>
{{Form::close}}
</code>```

The controller:

```<code>public function getProduct($id){
    ini_set('display_errors', 1);error_reporting(E_ALL);

    $sql = DB::select('select * from inventory where barcode = ?', [$id]);
    $name = $sql[0]->name;
    $price= $sql[0]->price;

    echo json_encode(array("name"=>$name, "price"=>$price));
}
</code>```

When I write the barcode it shows: undefined where it had to show the name and the price. What I missed?

答:
You have a JSON string (this.responseText), you want a JavaScript object (jsonObject). You want to use JSON.parse, which turns a JSON string into a JavaScript object, instead of JSON.stringify, which does the reverse, turning a JavaScript object into a JSON string.

var jsonObject =  JSON.parse(this.responseText);
                // ^-- here
```

Title: JSON: getElementById returns Undefined

Body:
I have a text input where I write a barcode it returns the name and the price from the database.

My code looks like this:

View:

{{ Form::open() }}
{{Form::text('barcode', null, ['onchange'=>"showProduct(this.value)"])}}

{{Form::close}}

The controller:

public function getProduct($id){
    ini_set('display_errors', 1);error_reporting(E_ALL);

    $sql = DB::select('select * from inventory where barcode = ?', [$id]);
    $name = $sql[0]->name;
    $price= $sql[0]->price;

    echo json_encode(array("name"=>$name, "price"=>$price));
}

When I write the barcode it shows: undefined where it had to show the name and the price. What I missed?


问:
How to use multiple jobs during configuration?
I'm working on a script to build Git from sources on Solaris. Git has about 12 dependencies, and most of them are Autotools based. The script takes longer than it should to execute because the checking performed by Autotools happens on a single thread. (Its especially painful during testing as the same steps are repeatedly performed).

I found some reading on the subject, like Parallel Building Tricks, but it does not discuss multiple jobs during configure. And trying the obvious does not work as expected:

```<code>$ ./configure -j 4
configure: error: unrecognized option: `-j'
Try `./configure --help' for more information
</code>```

How do I tell Autotools and ./configure to use multiple jobs to perform its checking (similar to make -j 8)?

答:
You can't.

Sorry this is not a satisfying answer, but configure is just a shell script. There's no way to tell shell scripts to execute in parallel like that.

Body:
I'm working on a script to build Git from sources on Solaris. Git has about 12 dependencies, and most of them are Autotools based. The script takes longer than it should to execute because the checking performed by Autotools happens on a single thread. (Its especially painful during testing as the same steps are repeatedly performed).

I found some reading on the subject, like Parallel Building Tricks, but it does not discuss multiple jobs during configure. And trying the obvious does not work as expected:

$ ./configure -j 4
configure: error: unrecognized option: `-j'
Try `./configure --help' for more information

How do I tell Autotools and ./configure to use multiple jobs to perform its checking (similar to make -j 8)?


问:
A PHP Error was encountered Severity: Notice Message: Trying to get property of non-object
I got error in codeigniter and I dont know how to solve this. My error is:-
A PHP Error was encountered

Severity: Notice

Message: Trying to get property of non-object

Filename: views/umparam.php

Line Number: 25

controller code:

```<code>public function edit($record_mpid)
    {
        $this->load->model('mparam');
        $record = $this->mparam->getAllRecords($record_mpid);
        $this->load->view('umparam',['record'=>$record]);
    }
}
</code>```

Model code:

```<code>public function getAllRecords($record_mpid)
        {
            $query = $this->db->get_where('mparam', array('mpid'=> $record_mpid));
            if ( $query->num_rows() > 0){
                return $query->row();
            }
        }
    }
</code>```

view code:

```<code><div class="form-group">
                    <label class="col-md-4 control-label" for="textinput">Parameter</label>
                    <div class="col-md-6">
                     <?php echo form_input(['name'=>'parameter','class'=>'form-control','placeholder'=>'Parameter','value'=>set_value('parameter', $record->parameter)]); ?> // line no 25

                    </div>
                     <div class="col-md-6">
                        <?php echo form_error('parameter'); ?>
                     </div>
                </div>
</code>```

Please help.Thank you!!

答:
On your controller function

```<code>public function edit($record_mpid) {
   $this->load->model('mparam');
   $data['record'] = $this->mparam->getAllRecords($record_mpid);
   $this->load->view('umparam', $data);
}
</code>```

Then on view

```<code><div class="form-group">
<label class="col-md-4 control-label" for="textinput">Parameter</label>
<div class="col-md-6">
<?php
$att = array(
    'name' => 'field_name',
    'class' => 'form-control',
    'placeholder' => 'Enter something',
    'value' => set_value('field_name', $record->parameter)
);

echo form_input($att);
?>
</div>
<div class="col-md-6">
<?php echo form_error('field_name', '<p>', '</p>'); ?>
</div>
</div>
</code>```

Model

```<code>public function getAllRecords($record_mpid) {
    $this->db->where('mpid', $record_mpid);
    $query = $this->db->get('mparam');

    if ($query->num_rows() > 0) {
        return $query->row(); // will return single item;
    }

    return false;

}
</code>```

Body:
I got error in codeigniter and I dont know how to solve this. My error is:-
A PHP Error was encountered

Severity: Notice

Message: Trying to get property of non-object

Filename: views/umparam.php

Line Number: 25

controller code:

public function edit($record_mpid)
    {
        $this->load->model('mparam');
        $record = $this->mparam->getAllRecords($record_mpid);
        $this->load->view('umparam',['record'=>$record]);
    }
}

Model code:

public function getAllRecords($record_mpid)
        {
            $query = $this->db->get_where('mparam', array('mpid'=> $record_mpid));
            if ( $query->num_rows() > 0){
                return $query->row();
            }
        }
    }

view code:

                    Parameter

                     <?php echo form_input(['name'=>'parameter','class'=>'form-control','placeholder'=>'Parameter','value'=>set_value('parameter', $record->parameter)]); ?> // line no 25

                        <?php echo form_error('parameter'); ?>

Please help.Thank you!!

Body:
On your controller function

public function edit($record_mpid) {
   $this->load->model('mparam');
   $data['record'] = $this->mparam->getAllRecords($record_mpid);
   $this->load->view('umparam', $data);
}

Then on view

<div class="form-group">
<label class="col-md-4 control-label" for="textinput">Parameter</label>
<div class="col-md-6">
<?php
$att = array(
    'name' => 'field_name',
    'class' => 'form-control',
    'placeholder' => 'Enter something',
    'value' => set_value('field_name', $record->parameter)
);

echo form_input($att);
?>
</div>
<div class="col-md-6">
<?php echo form_error('field_name', '<p>', '</p>'); ?>
</div>
</div>

Model

public function getAllRecords($record_mpid) {
    $this->db->where('mpid', $record_mpid);
    $query = $this->db->get('mparam');

    if ($query->num_rows() > 0) {
        return $query->row(); // will return single item;
    }

    return false;

}


问:
Keras merge layer warning
I'm keeping getting this warning:

lstm.py:119: UserWarning: The merge function is deprecated and will be removed after 08/2017. Use instead layers from keras.layers.merge, e.g. add, concatenate, etc.
    merged_vector = merge([l1, l2], mode=lambda x: (x[0] - x[1])**2, output_shape=lambda x: x[0])
  /Library/Python/2.7/site-packages/keras/legacy/layers.py:456: UserWarning: The Merge layer is deprecated and will be removed after 08/2017. Use instead layers from keras.layers.merge, e.g. add, concatenate, etc.
    name=name)

Which is related to the following line of code:

```<code>merged_vector = merge([l1, l2], mode=lambda x: (x[0] - x[1])**2, output_shape=lambda x: x[0])
</code>```

My model works fine, but how do I implement a custom merge in Keras 2.0.2? Thank you.

答:
Answering my own question:</p>

```<code># Custom Merge
def euclid_dist(v):
    return (v[0] - v[1])**2

def out_shape(shapes):
    return shapes[0]

merged_vector = Lambda(euclid_dist, output_shape=out_shape)([l1, l2])
</code>```

Title: Keras merge layer warning

Body:
I'm keeping getting this warning:

lstm.py:119: UserWarning: The merge function is deprecated and will be removed after 08/2017. Use instead layers from keras.layers.merge, e.g. add, concatenate, etc.
    merged_vector = merge([l1, l2], mode=lambda x: (x[0] - x[1])**2, output_shape=lambda x: x[0])
  /Library/Python/2.7/site-packages/keras/legacy/layers.py:456: UserWarning: The Merge layer is deprecated and will be removed after 08/2017. Use instead layers from keras.layers.merge, e.g. add, concatenate, etc.
    name=name)

Which is related to the following line of code:

merged_vector = merge([l1, l2], mode=lambda x: (x[0] - x[1])**2, output_shape=lambda x: x[0])

My model works fine, but how do I implement a custom merge in Keras 2.0.2? Thank you.

Body:
Answering my own question:

# Custom Merge
def euclid_dist(v):
    return (v[0] - v[1])**2

def out_shape(shapes):
    return shapes[0]

merged_vector = Lambda(euclid_dist, output_shape=out_shape)([l1, l2])


问:
Cannot run Swift under Ubuntu after closing the terminal
I am trying to run the Swift compiler under Ubuntu. I followed this tutorial: https://itsfoss.com/use-swift-linux/ and everything seemed to work fine. I was able to run swift under Ubuntu.

However, when I closed the terminal, I was not able to run Swift anymore. The program was not found until I installed it again. I could not find any answers to this question as there aren't many people running Swift under Ubuntu.

答:
It's not uninstalled, you just don't have the environment variables set up anymore, so Bash can't find the path to Swift. You can change that by exporting the appropriate environment variables in your .bashrc file.

When you followed the tutorial, you ran the following command:

```<code>export PATH=path_to_swift_usr_bin:$PATH
</code>```

This command adds the path to the swift binary to your PATH environment variable. The PATH variable holds a list of places where Ubuntu will look for programs to run from the command-line. So if the Swift executable is not in one of the places listed in the PATH, your terminal will never find it.

There is a file in your home folder (the folder ~, which is an abbreviation for /home/username, where username is your username) named .bashrc, which runs whenever you open a new terminal window. If you need an environment variable to be available whenever you open the terminal, you should add the export line for that variable to your .bashrc.

In this case, your .basrhc should contain the same line above.

The important thing to remember is that your environment variables are not preserved between command-line sessions, so if you want to have an environment variable available every time you use the command-line, it needs to be defined in your .bashrc.

Body:
It's not uninstalled, you just don't have the environment variables set up anymore, so Bash can't find the path to Swift. You can change that by exporting the appropriate environment variables in your .bashrc file.

When you followed the tutorial, you ran the following command:

export PATH=path_to_swift_usr_bin:$PATH

This command adds the path to the swift binary to your PATH environment variable. The PATH variable holds a list of places where Ubuntu will look for programs to run from the command-line. So if the Swift executable is not in one of the places listed in the PATH, your terminal will never find it.

There is a file in your home folder (the folder ~, which is an abbreviation for /home/username, where username is your username) named .bashrc, which runs whenever you open a new terminal window. If you need an environment variable to be available whenever you open the terminal, you should add the export line for that variable to your .bashrc.

In this case, your .basrhc should contain the same line above.

The important thing to remember is that your environment variables are not preserved between command-line sessions, so if you want to have an environment variable available every time you use the command-line, it needs to be defined in your .bashrc.


问:
How do I avoid "anti-aliasing effect" when creating a PGraphics object that's smaller than the window, then scale it up to the windows size?
When ran, the program displays a 3D sphere rendered in a P3D environment in the PGraphics object 'g', which is shown by taking the rendered PGraphics object and displaying it through the image() method in the main graphics context, which happens to be P2D.

The purpose of the program is to show how window size doesn't always correlate with render size. If you play an old Widows98 game in full screen, the game most likely will be rendered at 480p no matter what, so taking it into full screen just decreases the pixels per inch, plus making the image appear blurry. Which is fine, since fullscreen at 480p is preferred over windowed mode ( esp. if you're on 4K X_X )

the mouse's y position in the window changes the 3d camera's field of view, and the x position changes the rendering resolution of the P3D context used to display the sphere. Additionally, the P3D context is drawn in the main (P2D) context through the image() method, and is 'forcefully'. displayed at the size of the window. So if the P3D render resolution is smaller than the window, then it will start to look blurry and more pixelated, and if the render resolution is larger, you get a strange sharpening effect.

Now, my program works fine as it is, but. Another purpose of the program is shadowed by this issue, it's how the 'crispness' of the sphere fades as the render resolution decreases. You might say that it's clearly shown, but what I'm looking for is an image where there is no "anti-alias" effect going on. I want the image to preserve the pixels as the resolution gets smaller, so you can see the actual shape of the sphere at say, 50 x 50 pixels.

The noSmooth() method doesn't seem to work, and before you tell me to just do

```<code>g.loadPixels();
</code>```

and then do a double for loop to draw the raw pixels to the 2d context. No, it's sloppy. I know that there must be some reason why this blurring is going on. I'm hoping that it's the image() method and that I should be using a different method or I should add another method before it to remove image blurring.

```<code>PGraphics g;

void setup(){
  size(1000,1000,P2D);
  frameRate(1000);
  noSmooth();
}

void draw(){
  background(200);
  float res = map(mouseX,0,width,0.75,128);
  if (res==0) {
    res=1;
  }

  g = createGraphics((int)(width/res),(int)(height/res),P3D);
  g.noSmooth(); // is this thing working?????
  float cameraZ = ((height/2.0) / tan(PI*60.0/360.0));

  g.beginDraw();
    g.perspective(radians(map(mouseY,0,height,0.1,160)), width/height, cameraZ/10.0, cameraZ*10.0);
    g.camera(g.width/2.0, g.height/2.0, (height/2.0) / tan(PI*30.0 / 180.0), g.width/2.0, g.height/2.0, 0, 0, 1, 0);

    g.background(200);
    g.translate(g.width/2 ,g.height/2);
    g.sphere(100);
  g.endDraw();

  image(g, 0, 0, width, height); // this is where it all comes together
  text("rendering resolution: "+g.width+" x "+g.height,0,14);
  text("fps: "+frameRate,0,14*2);
}
</code>```

答:
Replace g.noSmooth() with ((PGraphicsOpenGL)g).textureSampling(2);

Credits go to Vallentin as I oddly enough had the same question with the P3D renderer

Body:
When ran, the program displays a 3D sphere rendered in a P3D environment in the PGraphics object 'g', which is shown by taking the rendered PGraphics object and displaying it through the image() method in the main graphics context, which happens to be P2D.

The purpose of the program is to show how window size doesn't always correlate with render size. If you play an old Widows98 game in full screen, the game most likely will be rendered at 480p no matter what, so taking it into full screen just decreases the pixels per inch, plus making the image appear blurry. Which is fine, since fullscreen at 480p is preferred over windowed mode ( esp. if you're on 4K X_X )

the mouse's y position in the window changes the 3d camera's field of view, and the x position changes the rendering resolution of the P3D context used to display the sphere. Additionally, the P3D context is drawn in the main (P2D) context through the image() method, and is 'forcefully'. displayed at the size of the window. So if the P3D render resolution is smaller than the window, then it will start to look blurry and more pixelated, and if the render resolution is larger, you get a strange sharpening effect.

Now, my program works fine as it is, but. Another purpose of the program is shadowed by this issue, it's how the 'crispness' of the sphere fades as the render resolution decreases. You might say that it's clearly shown, but what I'm looking for is an image where there is no "anti-alias" effect going on. I want the image to preserve the pixels as the resolution gets smaller, so you can see the actual shape of the sphere at say, 50 x 50 pixels.

The noSmooth() method doesn't seem to work, and before you tell me to just do

g.loadPixels();

and then do a double for loop to draw the raw pixels to the 2d context. No, it's sloppy. I know that there must be some reason why this blurring is going on. I'm hoping that it's the image() method and that I should be using a different method or I should add another method before it to remove image blurring.

PGraphics g;

void setup(){
  size(1000,1000,P2D);
  frameRate(1000);
  noSmooth();
}

void draw(){
  background(200);
  float res = map(mouseX,0,width,0.75,128);
  if (res==0) {
    res=1;
  }

  g = createGraphics((int)(width/res),(int)(height/res),P3D);
  g.noSmooth(); // is this thing working?????
  float cameraZ = ((height/2.0) / tan(PI*60.0/360.0));

  g.beginDraw();
    g.perspective(radians(map(mouseY,0,height,0.1,160)), width/height, cameraZ/10.0, cameraZ*10.0);
    g.camera(g.width/2.0, g.height/2.0, (height/2.0) / tan(PI*30.0 / 180.0), g.width/2.0, g.height/2.0, 0, 0, 1, 0);

    g.background(200);
    g.translate(g.width/2 ,g.height/2);
    g.sphere(100);
  g.endDraw();

  image(g, 0, 0, width, height); // this is where it all comes together
  text("rendering resolution: "+g.width+" x "+g.height,0,14);
  text("fps: "+frameRate,0,14*2);
}


问:
WatchKit error - unable to find interface controller class
```<code>the app was working fine, I was doing some adjustment and suddenly it stopped loading.
I launch the simulator and the storyboard doesn't start.
I get this error:

WatchKit error - unable to find interface controller class
2016-01-18 11:56:30.019 ABWatch Extension[13593:122454] WatchKit error - unable to find interface controller class '_TtC17ABWatch_Extension23HomeInterfaceController' to instantiate
2016-01-18 11:56:30.027 ABWatch Extension[13593:122426] *********** ERROR -[SPRemoteInterface _interfaceControllerClientIDForControllerID:] clientIdentifier for interfaceControllerID:35160002 not found
</code>```

答: In Interface Builder set the right Module on your InterfaceController's Custom Class section. It is probably empty. Image illustration</p>


问:
NodeJS Express AMP form req.body. POST undefined, GET success
NodeJS, AMP-form, TLS/SSL, Nginx, npm, HTTP/2
all Least Version.

POST

```<code>var bodyParser = require('body-parsre');
app.use(bodyParser.urlencoded({true}); // tried false
app.use(bodyParser.json()); // tried text(), json({type:*})

app.post('/post', function(req, res) {
    res.setHeader('Content-Type', 'text/plain');
    console.log('sent the name ' + req.body.name);
    console.log(util.inspect(req.body));
    console.log('request ' + req.query);
    res.json('Yo' + req.body.name);
});
</code>```

Shell Console.log result Undefined

```<code>sent the name undefined
{}
request /vote?__amp_source_origin=https%3A%2F%2Fexample.com
</code>```

Browser Console Success

```<code>Yo tanaka
</code>```

HTML no doubt

```<code>Powered by AMP ⚡ HTML – Version
<form method="post" action-xhr="https://example.com/post" target="_top" novalidate="">
    <input type="text" name="name" value="a" placeholder="Name..." required="">
    <input type="submit" value="Subscribe" disabled="">
</form>

vote?__amp_source_origin=https%3A%2F%2Fexample.com  200 fetch
preview Yo tanka
response Yo tanaka
</code>```

GET

```<code>Need not Body-Parser.
//var bodyParser = require('body-parsre');
//app.use(bodyParser.urlencoded({true}); // tried false
//app.use(bodyParser.json()); // tried text(), json({type:*})

// Use req.request
app.get('/post', function(req, res) {
    res.setHeader('Content-Type', 'text/plain');
    console.log('sent the name ' + req.query);
    console.log('request ' + req.query);
    res.json('Yo' + req.query);
});
</code>```

Form method get

```<code><form method="get" action-xhr="https://example.com/post" target="_top" novalidate="">
</code>```

Shell Console.log result

```<code>sent the name tanaka
{name: tanaka}
request [/vote?__amp_source_origin=https%3A%2F%2Fexample.com,
         {name:tanaka}]
</code>```

Browser Console Success

```<code>Yo tanaka
</code>```

I wanna POST.
I think body-parser Cause.

```<code>npm list --depth=0
ds@1.0.0 /usr/local/src/ds
├── body-parser@1.17.1
├── cookie-session@2.0.0-beta.1 extraneous
├── express@4.15.2
├── express-session@1.15.2 extraneous
├── helmet@3.5.0
├── mongodb@2.2.25
├── mongoose@4.9.2 extraneous
├── nunjucks@3.0.0
├── safe-regex@1.1.0 extraneous
└── session@0.1.0 extraneous
</code>```

body-parser Least Version
https://github.com/expressjs/body-parser

Is BODYPARSER and AMPFORM incompatible with each other?

答:
I think, the problem is CORS, And the json is write like this: res.json("Yo")

```<code>   app.post('/post', function(req, res) {
         res.header("Access-Control-Allow-Origin", "*");
         res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
         res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
         console.log('sent the name ' + req.body['name']);
         console.log('sent the name ' + req.body[0]);
         console.log('sent the name ' + req.body.name);
         console.log('sent the name ' + req.body.test); // input name test
         console.log(util.inspect(req.body));
        res.json('Yo');
        });
</code>```

Body:
NodeJS, AMP-form, TLS/SSL, Nginx, npm, HTTP/2
all Least Version.

POST

var bodyParser = require('body-parsre');
app.use(bodyParser.urlencoded({true}); // tried false
app.use(bodyParser.json()); // tried text(), json({type:*})

app.post('/post', function(req, res) {
    res.setHeader('Content-Type', 'text/plain');
    console.log('sent the name ' + req.body.name);
    console.log(util.inspect(req.body));
    console.log('request ' + req.query);
    res.json('Yo' + req.body.name);
});

Shell Console.log result Undefined

sent the name undefined
{}
request /vote?__amp_source_origin=https%3A%2F%2Fexample.com

Browser Console Success

Yo tanaka

HTML no doubt

Powered by AMP ⚡ HTML – Version
<form method="post" action-xhr="https://example.com/post" target="_top" novalidate="">
    <input type="text" name="name" value="a" placeholder="Name..." required="">
    <input type="submit" value="Subscribe" disabled="">
</form>

vote?__amp_source_origin=https%3A%2F%2Fexample.com  200 fetch
preview Yo tanka
response Yo tanaka

GET

Need not Body-Parser.
//var bodyParser = require('body-parsre');
//app.use(bodyParser.urlencoded({true}); // tried false
//app.use(bodyParser.json()); // tried text(), json({type:*})

// Use req.request
app.get('/post', function(req, res) {
    res.setHeader('Content-Type', 'text/plain');
    console.log('sent the name ' + req.query);
    console.log('request ' + req.query);
    res.json('Yo' + req.query);
});

Form method get

<form method="get" action-xhr="https://example.com/post" target="_top" novalidate="">

Shell Console.log result

sent the name tanaka
{name: tanaka}
request [/vote?__amp_source_origin=https%3A%2F%2Fexample.com,
         {name:tanaka}]

Browser Console Success

Yo tanaka

I wanna POST.
I think body-parser Cause.

npm list --depth=0
ds@1.0.0 /usr/local/src/ds
├── body-parser@1.17.1
├── cookie-session@2.0.0-beta.1 extraneous
├── express@4.15.2
├── express-session@1.15.2 extraneous
├── helmet@3.5.0
├── mongodb@2.2.25
├── mongoose@4.9.2 extraneous
├── nunjucks@3.0.0
├── safe-regex@1.1.0 extraneous
└── session@0.1.0 extraneous

body-parser Least Version
https://github.com/expressjs/body-parser

Is BODYPARSER and AMPFORM incompatible with each other?

Body:
I think, the problem is CORS, And the json is write like this: res.json("Yo")

   app.post('/post', function(req, res) {
         res.header("Access-Control-Allow-Origin", "*");
         res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
         res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
         console.log('sent the name ' + req.body['name']);
         console.log('sent the name ' + req.body[0]);
         console.log('sent the name ' + req.body.name);
         console.log('sent the name ' + req.body.test); // input name test
         console.log(util.inspect(req.body));
        res.json('Yo');
        });


问:
Data files when using intepreted languages
Say I have some data which I want several kinds of. I think the easiest example could be tiles in a game: I would have grass, rock, tree, etc. each with different sets of values.

I would immediately go ahead and make a file and read it in at runtime, so I wouldn't have to recompile it all for a tweak with something like C++. But if I was using Python, or some other intepreted language, would there be much point in having to make the file in a format like:

kind grass

  colour 0xdfdfdf

  walk
  true

  see true

Rather than:

class grass(tile):

  def
  init(self):

  I can't remember how to init. parents

   self.colour = 0xdfdfdf

The obvious benefit of the first is lost, when you don't compile.

答:
Several other reasons, not least that a non-coder may change config, let's make them comfortable.

You may have many different config files for different situations. If you use your code-based approach you have true, syntactically more complex, code replicated for each different config instance. I'd claim that multiple copies of code is a bad thing.

Furthermore, config need not come from a file, it might (for example) be in a database - in distributed systems that may be better than a file. Hence separating code and config can give flexibility.


问:
Cannot access class variable outside class - kivy
Anytime i try to run my app i get error.

Error: AttributeError: 'NoneType' object has no attribute 'text'

See code snippet below

```<code>class Login(Screen):

    email_obj = ObjectProperty()
    password_obj = ObjectProperty()
    conn = lite.connect("database/nairamanager.db")
    cursor = conn.cursor()

    def init(self, **kwargs):
        super().__init__(**kwargs)

    # Display an alert on login validation
    def login_alert(self):
        p = LoginAlert()
        p.open()

    # Get user from database
    def login_nm_user(self):
        self.cursor.execute("SELECT * FROM user_tb WHERE email_db = ? AND password_db = ?;", (self.email_obj.text, self.password_obj.text))
        if self.cursor.fetchall():
            self.manager.current = "news_feed_screen"
        else:
            return self.login_alert()
            self.conn.commit()
            # self.conn.close

    # Get user email
    def get_user_email(self):
        self.cursor.execute("SELECT * FROM user_tb WHERE email_db = ?;", (self.email_obj.text))
        self.user_email = self.cursor.fetchone()[0]
        self.conn.commit()
        print(self.user_email)

login = Login()
login.get_user_email()
print(login.user_email)
</code>```

.kv code
Below is the Login class in the kivy lang file

```<code><Login>:

email_obj: email_text
password_obj: password_text

GridLayout:
    size: root.size
    rows: 2
    rows_minimum: {0:0,1:root.height*.7}
    spacing: 50
    GridLayout:
        rows: 2
        row_default_minimum: True
        rows_minimum: {0:root.height*.1,1:root.height*.01}
        BoxLayout:
            orientation: "horizontal"
            BackButton:
                text: "L"
                size_hint: (.1,1)
                halign: "center"
                markup: True
                on_press:
                    root.manager.current = "login_signup_screen"
                    root.manager.transition.direction = "left"
            TopLabel:
                text: "[b]Lets get you logged in...[/b]"
                size_hint: (.9,1)
        BorderLabel:

    # Login form
    BoxLayout:
        orientation: "vertical"
        spacing: 20
        UniTextInput:
            id: email_text
            hint_text: "Email"
            size_hint: (.6,1)
            pos_hint: {"center_x":.5}
        UniTextInput:
            id: password_text
            hint_text: "Password"
            password: True
            size_hint: (.6,1)
            pos_hint: {"center_x":.5}
        GreenButton
            id: main_login_button
            text: "Login"
            size_hint: (.6,1)
            pos_hint: {"center_x":.5}
            on_press:
                root.login_nm_user()
                root.get_user_email()

        # Fake widget for spacing
        Widget:
        Widget:
        Widget:
</code>```

Please, how do i fix this?

答:
To share a variable to all screens, you can make it an attribute of the screenmanager.

Like this:

from kivy.app import App
from kivy.uix.screenmanager import Screen, ScreenManager
from kivy.lang import Builder
from kivy.properties import StringProperty

class MyScreenManager(ScreenManager):
    user_email = StringProperty()

class Login(Screen):

    def login(self, user, pw):
        # login
        # if pass
        self.manager.user_email = user
        self.manager.current = "screen2"

root = Builder.load_string('''

MyScreenManager:

    Login:
        name: "login"
        id: login
        BoxLayout:

            orientation: 'vertical'

            TextInput:
                id: email_input
            TextInput:
                id: password_input
            Button:
                text: "Login"
                on_release: login.login(email_input.text, password_input.text)

    Screen:
        name: "screen2"
        BoxLayout:
            orientation: "vertical"
            Label:
                text: "Wellcome {}!".format(root.user_email)
            Button:
                text: "Go to screen 3"
                on_release: root.current = "screen3"

    Screen:
        name: "screen3"
        BoxLayout:
            orientation: "vertical"
            Label:
                text: "Wellcome {}!".format(root.user_email)
            Button:
                text: "Go back to screen 2"
                on_release: root.current = "screen2"

''')

class MyApp(App):

    def build(self):
       return root

MyApp().run()
```

That said, I see you define a init method. If you really want to overite the __init__, remember the underscores.

In this particular example, you dont really do anything in the init. super().__init__() gets executed anyways when you create a new Screen

Body:
Anytime i try to run my app i get error.

Error: AttributeError: 'NoneType' object has no attribute 'text'

See code snippet below

class Login(Screen):

    email_obj = ObjectProperty()
    password_obj = ObjectProperty()
    conn = lite.connect("database/nairamanager.db")
    cursor = conn.cursor()

    def init(self, **kwargs):
        super().__init__(**kwargs)

    # Display an alert on login validation
    def login_alert(self):
        p = LoginAlert()
        p.open()

    # Get user from database
    def login_nm_user(self):
        self.cursor.execute("SELECT * FROM user_tb WHERE email_db = ? AND password_db = ?;", (self.email_obj.text, self.password_obj.text))
        if self.cursor.fetchall():
            self.manager.current = "news_feed_screen"
        else:
            return self.login_alert()
            self.conn.commit()
            # self.conn.close

    # Get user email
    def get_user_email(self):
        self.cursor.execute("SELECT * FROM user_tb WHERE email_db = ?;", (self.email_obj.text))
        self.user_email = self.cursor.fetchone()[0]
        self.conn.commit()
        print(self.user_email)

login = Login()
login.get_user_email()
print(login.user_email)

.kv code
Below is the Login class in the kivy lang file

<Login>:

email_obj: email_text
password_obj: password_text

GridLayout:
    size: root.size
    rows: 2
    rows_minimum: {0:0,1:root.height*.7}
    spacing: 50
    GridLayout:
        rows: 2
        row_default_minimum: True
        rows_minimum: {0:root.height*.1,1:root.height*.01}
        BoxLayout:
            orientation: "horizontal"
            BackButton:
                text: "L"
                size_hint: (.1,1)
                halign: "center"
                markup: True
                on_press:
                    root.manager.current = "login_signup_screen"
                    root.manager.transition.direction = "left"
            TopLabel:
                text: "[b]Lets get you logged in...[/b]"
                size_hint: (.9,1)
        BorderLabel:

    # Login form
    BoxLayout:
        orientation: "vertical"
        spacing: 20
        UniTextInput:
            id: email_text
            hint_text: "Email"
            size_hint: (.6,1)
            pos_hint: {"center_x":.5}
        UniTextInput:
            id: password_text
            hint_text: "Password"
            password: True
            size_hint: (.6,1)
            pos_hint: {"center_x":.5}
        GreenButton
            id: main_login_button
            text: "Login"
            size_hint: (.6,1)
            pos_hint: {"center_x":.5}
            on_press:
                root.login_nm_user()
                root.get_user_email()

        # Fake widget for spacing
        Widget:
        Widget:
        Widget:

Please, how do i fix this?

Body:
To share a variable to all screens, you can make it an attribute of the screenmanager.

Like this:

from kivy.app import App
from kivy.uix.screenmanager import Screen, ScreenManager
from kivy.lang import Builder
from kivy.properties import StringProperty

class MyScreenManager(ScreenManager):
    user_email = StringProperty()

class Login(Screen):

    def login(self, user, pw):
        # login
        # if pass
        self.manager.user_email = user
        self.manager.current = "screen2"

root = Builder.load_string('''

MyScreenManager:

    Login:
        name: "login"
        id: login
        BoxLayout:

            orientation: 'vertical'

            TextInput:
                id: email_input
            TextInput:
                id: password_input
            Button:
                text: "Login"
                on_release: login.login(email_input.text, password_input.text)

    Screen:
        name: "screen2"
        BoxLayout:
            orientation: "vertical"
            Label:
                text: "Wellcome {}!".format(root.user_email)
            Button:
                text: "Go to screen 3"
                on_release: root.current = "screen3"

    Screen:
        name: "screen3"
        BoxLayout:
            orientation: "vertical"
            Label:
                text: "Wellcome {}!".format(root.user_email)
            Button:
                text: "Go back to screen 2"
                on_release: root.current = "screen2"

''')

class MyApp(App):

    def build(self):
       return root

MyApp().run()

That said, I see you define a init method. If you really want to overite the __init__, remember the underscores.

In this particular example, you dont really do anything in the init. super().__init__() gets executed anyways when you create a new Screen


答:
First convert your minute to int:

```<code>minutes = int(x[1])
</code>```

Then you add it to your dictionary:

```<code>if player in dict:
  dict[player] += minutes
else:
  dict[player] = minutes
</code>```

Title: Updating dictionary values of keys from a .txt file

Body:
First convert your minute to int:

minutes = int(x[1])

Then you add it to your dictionary:

if player in dict:
  dict[player] += minutes
else:
  dict[player] = minutes


问:
Print a trie in Ocaml
Every function listed below works as expected. (except the last one)

I'm trying to make the to_list work, I want it to return a list of char lists, but I so far I managed only to implement it with simple prints  returning unit

```<code>type trie = Trie of bool * (char * trie) list
let empty = Trie (false, [])

let explode wd = (*breaks up a word in a list of chars*)
    let rec exp i acc =
        if i = -1 then acc else exp (i-1) (wd.[i]::acc) in
        exp (String.length wd - 1) []

let insert tr wd = (*insert a word into the trie*)
let rec insert' wd tr = match wd, tr with
    | [], Trie (_, l) -> Trie (true, l)
    | wh::wt, Trie (b, l) ->
        try Trie(b, (wh, insert' wt (List.assoc wh l))::List.remove_assoc wh l)
        with Not_found -> Trie (b, (wh, insert' wt empty) :: l)
        in insert' (explode wd) tr

let from_list = List.fold_left insert empty  (*makes trie from string list*)

let to_list tr = (*prints all trie words*)
    let rec to_list' (Trie (b, l)) acc =
        if b then
            (
                List.iter print_char (List.rev acc);
                print_char '\n'
            )
        else ();
        List.iter (fun (c, t) -> to_list' t (c::acc)) l in
    to_list' tr []
</code>```

EDIT : Thanks to @Goswin von Brederlow I made my to_list printing function clearer.

What I tried :

```<code>let to_list tr = (*fails at compile time*)
    let rec to_list' acc = function
        | Trie(_, []) -> [List.rev acc]
        | Trie(true, (c, h)::_) -> (List.rev acc) :: to_list' (c::acc) h
        | Trie(_, l) -> List.map (fun (c, t) -> to_list' (c::acc) t) in
        to_list' [] a tr
</code>```

Example :

```<code>let t = from_list ["hello"; "hell"; "helsinki"; "here"];;
# to_list t;;
here
helsinki
hell
hello
- : unit = ()
</code>```

Does it fail because List.map can return only type 'a list and not any n-depth nested lists ?

答:
List.map can return a list of lists. This is not your problem.

You say that your to_list function doesn't compile, but you don't show the error. This makes it harder to offer advice.

The first problem I see in the code is this:

```<code>List.map (fun (c, t) -> to_list' (c::acc) t)
</code>```

There's just one argument here. But generally you would want to supply two arguments: a function (which is what you have) and a list (which you don't have).

Title: Print a trie in Ocaml

Body:
Every function listed below works as expected. (except the last one)

I'm trying to make the to_list work, I want it to return a list of char lists, but I so far I managed only to implement it with simple prints  returning unit

type trie = Trie of bool * (char * trie) list
let empty = Trie (false, [])

let explode wd = (*breaks up a word in a list of chars*)
    let rec exp i acc =
        if i = -1 then acc else exp (i-1) (wd.[i]::acc) in
        exp (String.length wd - 1) []

let insert tr wd = (*insert a word into the trie*)
let rec insert' wd tr = match wd, tr with
    | [], Trie (_, l) -> Trie (true, l)
    | wh::wt, Trie (b, l) ->
        try Trie(b, (wh, insert' wt (List.assoc wh l))::List.remove_assoc wh l)
        with Not_found -> Trie (b, (wh, insert' wt empty) :: l)
        in insert' (explode wd) tr

let from_list = List.fold_left insert empty  (*makes trie from string list*)

let to_list tr = (*prints all trie words*)
    let rec to_list' (Trie (b, l)) acc =
        if b then
            (
                List.iter print_char (List.rev acc);
                print_char '\n'
            )
        else ();
        List.iter (fun (c, t) -> to_list' t (c::acc)) l in
    to_list' tr []

EDIT : Thanks to @Goswin von Brederlow I made my to_list printing function clearer.

What I tried :

let to_list tr = (*fails at compile time*)
    let rec to_list' acc = function
        | Trie(_, []) -> [List.rev acc]
        | Trie(true, (c, h)::_) -> (List.rev acc) :: to_list' (c::acc) h
        | Trie(_, l) -> List.map (fun (c, t) -> to_list' (c::acc) t) in
        to_list' [] a tr

Example :

let t = from_list ["hello"; "hell"; "helsinki"; "here"];;
# to_list t;;
here
helsinki
hell
hello
- : unit = ()

Does it fail because List.map can return only type 'a list and not any n-depth nested lists ?

Body:
List.map can return a list of lists. This is not your problem.

You say that your to_list function doesn't compile, but you don't show the error. This makes it harder to offer advice.

The first problem I see in the code is this:

List.map (fun (c, t) -> to_list' (c::acc) t)

There's just one argument here. But generally you would want to supply two arguments: a function (which is what you have) and a list (which you don't have).


问:
Exception handling with superclass-java
If I wanted to use a superclass to handle an exception do I still need to use try catch to handle the exception? This is the code for the super class and the class I used to test it. I tried to use the method quotient in the test class but I needed to add a try catch statement to do what I wanted it to do. </p>

```<code> public class ExceptionA {

public static int quotient(int numerator, int denominator)
  throws ArithmeticException
{
  return numerator / denominator; // possible division by zero
}

}

public class ExceptionTest {

public static void main(String[] args) {

  Scanner scanner = new Scanner(System.in);
  boolean continueLoop = true;

  do
 {
     try
     {
         System.out.println("Please enter an integer numerator");
         int numerator = scanner.nextInt();
         System.out.println("Please enter an integer denominator");
         int denominator = scanner.nextInt();

         int result = ExceptionA.quotient(numerator, denominator);
         System.out.printf("%nResult: %d / %d = %d%n", numerator,
         denominator , result);
         continueLoop = false;
     }
     catch ( ArithmeticException arithmeticException)
     {
         System.err.printf("%nException: %s%n" , arithmeticException);
         System.out.printf("Zero is an invalid denominator. Please try again."
                 + "%n%n");
     }

     } while(continueLoop);

 }
 }
</code>```

答: If the method throws an exception, then you are either going to have to write the method to throw an exception, or use a try/catch to handle the exception. At some point you will have to use a try/catch, especially if you call the code in your main method.

Title: Exception handling with superclass-java

Body:
If I wanted to use a superclass to handle an exception do I still need to use try catch to handle the exception? This is the code for the super class and the class I used to test it. I tried to use the method quotient in the test class but I needed to add a try catch statement to do what I wanted it to do.

 public class ExceptionA {

public static int quotient(int numerator, int denominator)
  throws ArithmeticException
{
  return numerator / denominator; // possible division by zero
}

}

public class ExceptionTest {

public static void main(String[] args) {

  Scanner scanner = new Scanner(System.in);
  boolean continueLoop = true;

  do
 {
     try
     {
         System.out.println("Please enter an integer numerator");
         int numerator = scanner.nextInt();
         System.out.println("Please enter an integer denominator");
         int denominator = scanner.nextInt();

         int result = ExceptionA.quotient(numerator, denominator);
         System.out.printf("%nResult: %d / %d = %d%n", numerator,
         denominator , result);
         continueLoop = false;
     }
     catch ( ArithmeticException arithmeticException)
     {
         System.err.printf("%nException: %s%n" , arithmeticException);
         System.out.printf("Zero is an invalid denominator. Please try again."
                 + "%n%n");
     }

     } while(continueLoop);

 }
 }


问:
Angular2/Rxjs HTTP Catch Asynchronous Transform Issue
I'm attempting to call an HTTP Post method in Angular 2 to retrieve a PDF file, so I'm setting the ResponseContentType to be Blob, like this:

```<code>let headers = new Headers({
        'Content-Type': 'application/json',
        'ApplicationName': 'ControlEnroll',
        'Accept': 'application/pdf'
    });
let options = new RequestOptions({
        headers: headers,
        responseType: ResponseContentType.Blob
    });
</code>```

Now, I have no problem with when the post() call is a success, but when it is an error I am having problems with pulling out the error message returned from my WebAPI method because it is wrapped in a Blob.

Since this is Angular 2, my post() call and structure looks like this right now:

```<code>return this.http.post(postUrl, {
        // ... some body parameters here ...
    }, options)
        .map(resp => {
            let blob: Blob = resp.blob();
            // Use the file-save library to persist this to disk.
            window['saveAs'](blob, 'File.pdf');

            return resp;
        }).catch(error => {
            // What to do?
        });
</code>```

The problem is in the catch() method I know that the error being provided is a Response object containing a Blob body. The only way to extract the text from the Blob object that I know of is to use a FileReader and an event listener, like this:

```<code>let body = error.json();
let reader = new FileReader();

reader.addEventListener('loadend', function () {
    console.log(reader.result);
});

reader.readAsText(body);
</code>```

However, this won't happen immediately; it's an event listener. Yet, the catch() must [likey] throw an error of some sort out to the outside that is Observable, right? How can I handle this catch() method in a way that will let me pull the string out of the Blob, yet allow someone else to subscribe to this entire method and use the normal subscribe(successFn, errorFn) structure? Is it possible?

答:
The selector function passed to the catch operator can return an observable that will be used to continue the observable chain in the event of an error.

So your selector function can return an observable that waits for the loadend event from the FileReader and then throws an error with the message you've read from the BLOB. Something like this:

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/fromEvent';
import 'rxjs/add/operator/do';

...
.catch(error => {
  let reader = new FileReader();
  let loadend = Observable.fromEvent(reader, 'loadend');
  reader.readAsText(error.blob());
  return loadend.do(() => { throw new Error(reader.result /* or whatever */); });
})
```

Body:
I'm attempting to call an HTTP Post method in Angular 2 to retrieve a PDF file, so I'm setting the ResponseContentType to be Blob, like this:

let headers = new Headers({
        'Content-Type': 'application/json',
        'ApplicationName': 'ControlEnroll',
        'Accept': 'application/pdf'
    });
let options = new RequestOptions({
        headers: headers,
        responseType: ResponseContentType.Blob
    });

Now, I have no problem with when the post() call is a success, but when it is an error I am having problems with pulling out the error message returned from my WebAPI method because it is wrapped in a Blob.

Since this is Angular 2, my post() call and structure looks like this right now:

return this.http.post(postUrl, {
        // ... some body parameters here ...
    }, options)
        .map(resp => {
            let blob: Blob = resp.blob();
            // Use the file-save library to persist this to disk.
            window['saveAs'](blob, 'File.pdf');

            return resp;
        }).catch(error => {
            // What to do?
        });

The problem is in the catch() method I know that the error being provided is a Response object containing a Blob body. The only way to extract the text from the Blob object that I know of is to use a FileReader and an event listener, like this:

let body = error.json();
let reader = new FileReader();

reader.addEventListener('loadend', function () {
    console.log(reader.result);
});

reader.readAsText(body);

However, this won't happen immediately; it's an event listener. Yet, the catch() must [likey] throw an error of some sort out to the outside that is Observable, right? How can I handle this catch() method in a way that will let me pull the string out of the Blob, yet allow someone else to subscribe to this entire method and use the normal subscribe(successFn, errorFn) structure? Is it possible?


问:
Cakephp 3.0 ROOT variable gets set wrong
After a stock install and creation of a basic controller, the environment variables are being set wrong.

For example, ROOT gets set as follows:

/var/www/html/appname/src//var/www/html/appname

In other words, the Apache webserver DocumentRoot is being appended to it.

Why?

答:
What I learned is that if I specify the absolute path to the file in a controller, the Apache DocumentRoot gets appended to the ROOT variable. For example:

```<code>public function getFile() {
    // disable the default layout for the view
    $this->viewBuilder()->layout(false);
    $path = ROOT . '/file/file.txt';
    $this->response->file($path, array('download' => true));
    return $this->response;
}
</code>```

The browser cannot find the file at location /var/www/html/app/src//var/www/html/app/src/file/file.txt

However the following works as expected:

```<code>public function getFile() {
    // disable the default layout for the view
    $this->viewBuilder()->layout(false);
    $path = '/file/file.txt';
    $this->response->file($path, array('download' => true));
    return $this->response;
}
</code>```

The ROOT location seems to get automatically pre-prended to the path I have set above. I was not aware of this and haven't read anything about it in the documentation, so I am still not sure why it works this way.

Body:
What I learned is that if I specify the absolute path to the file in a controller, the Apache DocumentRoot gets appended to the ROOT variable. For example:

public function getFile() {
    // disable the default layout for the view
    $this->viewBuilder()->layout(false);
    $path = ROOT . '/file/file.txt';
    $this->response->file($path, array('download' => true));
    return $this->response;
}

The browser cannot find the file at location /var/www/html/app/src//var/www/html/app/src/file/file.txt

However the following works as expected:

public function getFile() {
    // disable the default layout for the view
    $this->viewBuilder()->layout(false);
    $path = '/file/file.txt';
    $this->response->file($path, array('download' => true));
    return $this->response;
}

The ROOT location seems to get automatically pre-prended to the path I have set above. I was not aware of this and haven't read anything about it in the documentation, so I am still not sure why it works this way.


问:
How to use types/select2 in a Angular 2 project?
I am developing Angular 2 project with Typescript. I want to be able to use select2 and I don't see any stable feature rich plugins equivalent to select2. However I came across types/select2 in DefinitelyTyped project. I'm not sure how to use them in my project. I can't find examples of other DefinitelyTyped libraries also. I'm new to both TS and Angular 2. Can someone provide pointers on how I should used this ?

I understand I can include the library using my package.json but no idea how I can use in a component.

答:
With @types/select2 installed, it allows the typescript compiler to do static type checking to ensure the Select2 library is being called correctly. It does not change the way you use the select2 - you still need to install the Select2 library and use it as you would have without type checking.

For external dependencies (like jQuery or Select2) you should install their corresponding type definition files, so that the typescript compiler can resolve the external types at compile-time.  This is preferred over declaring an any types (i.e. declare var $: any)

Make sure you install jQuery types as well :

```<code>npm install @types/jquery
</code>```

This will install the type definitions under node_modules/@types/jQuery. By default, the typescript compiler will resolve types from the node_modules/@types folder.

For TypeScript NodeJS packages, you can generate type definition files as part of the compilation step and specify index.d.ts in the typings property of your package.json file. In this case, you don't necessarily need to export the type definitions to node_modules/@types.

Body:
With @types/select2 installed, it allows the typescript compiler to do static type checking to ensure the Select2 library is being called correctly. It does not change the way you use the select2 - you still need to install the Select2 library and use it as you would have without type checking.

For external dependencies (like jQuery or Select2) you should install their corresponding type definition files, so that the typescript compiler can resolve the external types at compile-time.  This is preferred over declaring an any types (i.e. declare var $: any)

Make sure you install jQuery types as well :

npm install @types/jquery

This will install the type definitions under node_modules/@types/jQuery. By default, the typescript compiler will resolve types from the node_modules/@types folder.

For TypeScript NodeJS packages, you can generate type definition files as part of the compilation step and specify index.d.ts in the typings property of your package.json file. In this case, you don't necessarily need to export the type definitions to node_modules/@types.


问:
select varchar as date in mySQL
I have a date column in the format

25 Mar 2017 07:19 pm

I want to select date in the format dd/mm/yyyy

I have tried: cast(date as DATE), STR_TO_DATE(date, '%d/%m/%Y') but everything returns null

any help will be appreciated.

答:
Use

```<code>select str_to_date('25 Mar 2017 07:19 pm', '%d %M %Y')
</code>```

The format specified has to match the input pattern. As the month name is included, use %M.

Title: select varchar as date in mySQL

Body:
Use

select str_to_date('25 Mar 2017 07:19 pm', '%d %M %Y')

The format specified has to match the input pattern. As the month name is included, use %M.


问:
Issue with using variables inside a class function (Swift Playgrounds)
I want to create a function so when a button gets pressed, the content of a variable changes. The function does get called, but I can't use any external variables inside it.

This is the code I'm having trouble with:

```<code>class Responder: NSObject {
    func pressed(sender: UIButton) {
        // Can't change the value of "a" here
    }
}

var a: Int = 0

let responder = Responder()
let bt = UIButton(frame: CGRect(x: 0.0, y: 0.0, width: 200.0, height: 200.0))
bt.addTarget(responder, action: #selector(Responder.pressed), for: .touchUpInside)
</code>```

What can I do to make this work?

答:
It does work. You can change the value of a in pressed. I added code to your pressed method, as follows:

```<code>import UIKit
import PlaygroundSupport

class Responder: NSObject {
    func pressed(sender: UIButton) {
        a = a+1
        print(a)
    }
}
var a: Int = 0

let responder = Responder()
let bt = UIButton(frame: CGRect(x: 0.0, y: 0.0, width: 200.0, height: 200.0))
bt.addTarget(responder, action: #selector(Responder.pressed), for: .touchUpInside)
PlaygroundPage.current.liveView = bt
</code>```

The button appears, and each time I tap it, a higher number is printed out, starting with 1 (because a was 0 to start with). This proves that your code can change a.

Body:
I want to create a function so when a button gets pressed, the content of a variable changes. The function does get called, but I can't use any external variables inside it.

This is the code I'm having trouble with:

class Responder: NSObject {
    func pressed(sender: UIButton) {
        // Can't change the value of "a" here
    }
}

var a: Int = 0

let responder = Responder()
let bt = UIButton(frame: CGRect(x: 0.0, y: 0.0, width: 200.0, height: 200.0))
bt.addTarget(responder, action: #selector(Responder.pressed), for: .touchUpInside)

What can I do to make this work?

Body:
It does work. You can change the value of a in pressed. I added code to your pressed method, as follows:

import UIKit
import PlaygroundSupport

class Responder: NSObject {
    func pressed(sender: UIButton) {
        a = a+1
        print(a)
    }
}
var a: Int = 0

let responder = Responder()
let bt = UIButton(frame: CGRect(x: 0.0, y: 0.0, width: 200.0, height: 200.0))
bt.addTarget(responder, action: #selector(Responder.pressed), for: .touchUpInside)
PlaygroundPage.current.liveView = bt

The button appears, and each time I tap it, a higher number is printed out, starting with 1 (because a was 0 to start with). This proves that your code can change a.


Title: How do I take differences of two rows based on conditional statement?

Body:
I'm having a lot of trouble with this really easy problem. Below is a sample of my data:

            EUR.20MA.1 EUR.LAST.2
2013-11-04          1     1.3514
2013-11-05         -1     1.3474
2013-11-06          1     1.3513
2013-11-07          0     1.3419
2013-11-08         -1     1.3367
2013-11-11          1     1.3407

Basically whenever the signal changes from 1 to 0, or 1 to -1, I want to take the difference of that row with the subsequent row. Hence, output would look like:

         EUR.20MA.1 EUR.LAST.2  Difference
11/4/2013   1       1.3514      0.004
11/5/2013  -1       1.3474      0
11/6/2013   1       1.3513      0.0094
11/7/2013   0       1.3419      0
11/8/2013  -1       1.3367      0
11/11/2013  1       1.3407      0
11/12/2013  1       1.3436      0
11/13/2013  1       1.3487      0.0026
11/14/2013 -1       1.3461      0

Dput below:

structure(list(EUR.20MA.1 = c(1, -1, 1, 0, -1, 1, 1, 1, -1, 1
), EUR.LAST.2 = c(1.3514, 1.3474, 1.3513, 1.3419, 1.3367, 1.3407,
1.3436, 1.3487, 1.3461, 1.3496)), .Names = c("EUR.20MA.1", "EUR.LAST.2"
), row.names = c("2013-11-04", "2013-11-05", "2013-11-06", "2013-11-07",
"2013-11-08", "2013-11-11", "2013-11-12", "2013-11-13", "2013-11-14",
"2013-11-15"), class = "data.frame")

Body:
A lengthier dplyr version, using lags instead of leads and results on the next row.

library(dplyr)
df <- st %>%
  mutate(EUR.20MA.1_lag = lag(EUR.20MA.1),
         EUR.LAST.2_lag = lag(EUR.LAST.2),
         signal = (EUR.20MA.1_lag == 1 & EUR.20MA.1 == 0) |
                  (EUR.20MA.1_lag == 1 & EUR.20MA.1 == -1),
         difference = if_else(signal, EUR.LAST.2 - EUR.LAST.2_lag, 0))

df

#    EUR.20MA.1 EUR.LAST.2 EUR.20MA.1_lag EUR.LAST.2_lag signal difference
# 1           1     1.3514             NA             NA  FALSE     0.0000
# 2          -1     1.3474              1         1.3514   TRUE    -0.0040
# 3           1     1.3513             -1         1.3474  FALSE     0.0000
# 4           0     1.3419              1         1.3513   TRUE    -0.0094
# 5          -1     1.3367              0         1.3419  FALSE     0.0000
# 6           1     1.3407             -1         1.3367  FALSE     0.0000
# 7           1     1.3436              1         1.3407  FALSE     0.0000
# 8           1     1.3487              1         1.3436  FALSE     0.0000
# 9          -1     1.3461              1         1.3487   TRUE    -0.0026
# 10          1     1.3496             -1         1.3461  FALSE     0.0000


问:
Object reference not set to an instance of an object. but the Properties are accessable
I am passing a IList into another class which looks as follows:

```<code>public class KundenViewModel
{
    public IList<Kunde> _kunden;

    /// <summary>
    /// Add a list of Kunde to the View
    /// </summary>
    /// <param name="kunden">A list of Kunde objects</param>
    public KundenViewModel(IList<Kunde> kunden)
    {
        foreach (var k in kunden)
        {
            var test = k._Name;
            _kunden.Add(k);
        }
        //_kunden.AddRange(kunden);
    }

    /// <summary>
    /// Add one Object of Kunde to the View
    /// </summary>
    /// <param name="kunde">A Kunde Object</param>
    public KundenViewModel(Kunde kunde)
    {
        _kunden.Add(kunde);
    }
}
</code>```

But at runtime I receive at the Line 14 (_kunden.Add(k);) the error "Object reference not set to an instance of an object." Well I would say the object has never been initialized, but It has been and I also can access the properties for example the line before, there is no error.

Thanks in Advance

答: You have yet to initialise _kunden. You only declared it atm, meaning that you are currently trying to add k to null.</p>

Body:
I am passing a IList into another class which looks as follows:

public class KundenViewModel
{
    public IList<Kunde> _kunden;

    ///
    /// Add a list of Kunde to the View
    ///
    /// <param name="kunden">A list of Kunde objects</param>
    public KundenViewModel(IList<Kunde> kunden)
    {
        foreach (var k in kunden)
        {
            var test = k._Name;
            _kunden.Add(k);
        }
        //_kunden.AddRange(kunden);
    }

    ///
    /// Add one Object of Kunde to the View
    ///
    /// <param name="kunde">A Kunde Object</param>
    public KundenViewModel(Kunde kunde)
    {
        _kunden.Add(kunde);
    }
}

But at runtime I receive at the Line 14 (_kunden.Add(k);) the error "Object reference not set to an instance of an object." Well I would say the object has never been initialized, but It has been and I also can access the properties for example the line before, there is no error.

Thanks in Advance


问:
I need to create a 2D array from JSON data for a 'Datatables plugin for jQuery' table
My 2D testtable array works as expected filling the rows in the table.
My tabledata array created from JSON data creates an array but will not fill the rows in the table. For some reason it seems Datatables won't recognize the array as an array. There are no errors in the console. Just a message in the table stating "No data available in table". I'm a confused because the tabledata array should work. Any ideas why it does not. I tried creating the tabledata array a few other ways with no luck.

```<code>var tableData = [];
var testTable = [['1','2','3','4','5','6'], ['7','8','9','10','11','12']]

$(function() {
    populateTableDataArray('data/test.json');
    $('#example').DataTable({
        data: tableData
    });
    console.log(tableData);
});

function populateTableDataArray(file) {
    $.getJSON(file, function(data) {
        $.each(data, function(key, value) {
            tableData.push([value[0], value[1], value[2], value[6], value[7], value[8]]);
        });
    });
};
</code>```

Test JSON data

```<code>{"1": ["4999", "HARVEST MARKET", "2285 MARKET St", "San Francisco", "37.764607", "-122.432452", "2016-10-03T00:00:00", "77", "High risk food holding temperature", "High Risk"], "2": ["2134", "CHIEFTAIN IRISH PUB, THE", "198 05th St", "San Francisco", "37.781567", "-122.405059", "2016-11-09T00:00:00", "87", "High risk food holding temperature", "High Risk"]}
</code>```

Output from Datatables using tabledata array

Output from Datatables using testtable array

答:
As charlietf mentions, the problem is asynchronicity. A quick workaround could be to load the JSON from within dataTables itself, and then reuse your code from populateTableDataArray() in the dataSrc callback :

$('#example').DataTable({
   ajax: {
     url: 'https://api.myjson.com/bins/1dtiov',
     dataSrc: function(data) {
       var tableData = [];
       $.each(data, function(key, value) {
         tableData.push([value[0], value[1], value[2], value[6], value[7], value[8]]);
       });
       return tableData
     }
   },
   columns: [
     { data: 0, title: '1'}, //TODO, add some meaningful titles
     { data: 1, title: '2'},
     { data: 2, title: '3'},
     { data: 3, title: '4'},
     { data: 4, title: '5'}
   ]
})
```

<p>markup</p>

<pre class="lang-html prettyprint-override"><code><table id="example"></table>
</code>```

see it in action -> http://jsfiddle.net/yzrshckf/

Replace the myjson.com reference with the path to your JSON, i.e data/test.json.

Body:
My 2D testtable array works as expected filling the rows in the table.
My tabledata array created from JSON data creates an array but will not fill the rows in the table. For some reason it seems Datatables won't recognize the array as an array. There are no errors in the console. Just a message in the table stating "No data available in table". I'm a confused because the tabledata array should work. Any ideas why it does not. I tried creating the tabledata array a few other ways with no luck.

var tableData = [];
var testTable = [['1','2','3','4','5','6'], ['7','8','9','10','11','12']]

$(function() {
    populateTableDataArray('data/test.json');
    $('#example').DataTable({
        data: tableData
    });
    console.log(tableData);
});

function populateTableDataArray(file) {
    $.getJSON(file, function(data) {
        $.each(data, function(key, value) {
            tableData.push([value[0], value[1], value[2], value[6], value[7], value[8]]);
        });
    });
};

Test JSON data

{"1": ["4999", "HARVEST MARKET", "2285 MARKET St", "San Francisco", "37.764607", "-122.432452", "2016-10-03T00:00:00", "77", "High risk food holding temperature", "High Risk"], "2": ["2134", "CHIEFTAIN IRISH PUB, THE", "198 05th St", "San Francisco", "37.781567", "-122.405059", "2016-11-09T00:00:00", "87", "High risk food holding temperature", "High Risk"]}

Output from Datatables using tabledata array

Output from Datatables using testtable array

Body:
As charlietf mentions, the problem is asynchronicity. A quick workaround could be to load the JSON from within dataTables itself, and then reuse your code from populateTableDataArray() in the dataSrc callback :

$('#example').DataTable({
   ajax: {
     url: 'https://api.myjson.com/bins/1dtiov',
     dataSrc: function(data) {
       var tableData = [];
       $.each(data, function(key, value) {
         tableData.push([value[0], value[1], value[2], value[6], value[7], value[8]]);
       });
       return tableData
     }
   },
   columns: [
     { data: 0, title: '1'}, //TODO, add some meaningful titles
     { data: 1, title: '2'},
     { data: 2, title: '3'},
     { data: 3, title: '4'},
     { data: 4, title: '5'}
   ]
})

markup

<table id="example"></table>

see it in action -> http://jsfiddle.net/yzrshckf/

Replace the myjson.com reference with the path to your JSON, i.e data/test.json.


问:
host_vars and group_vars are not getting loaded
I have below folder structure, which seem to make it build and load the roles, but the group and host vars are not being loaded. How come?

/etc/ansible/

```<code>- hosts
- requirements.yml
- group_vars/
    - app/
        - postgres.yml
- host_vars/
    - app1/
        - postgres.yml
- roles
</code>```

/documents/ansible/

```<code>- playbook.yml
- vagrant
</code>```

host file

```<code># Application servers
[app]
192.168.60.6

# Group multi
[multi:children]
app

#variables applied to all servers
[multi:vars]
ansible_ssh_user=vagrant
ansible_ssh_private_key_file=~/.vagrant.d/insecure_private_key
</code>```

**vagrant **

```<code># -*- mode: ruby -*-
# vi: set ft=ruby :

Vagrant.configure("2") do |config|

  # Genral Vagrant VM Configuration.
  config.vm.box = "geerlingguy/centos7"
  config.ssh.insert_key = false
  config.vm.synced_folder ".", "/vagrant", disabled: true
  config.vm.provider :virtualbox do |v|
    v.memory = 256
    v.linked_clone = true
  end

  config.vm.provision "ansible" do |ansible|
    ansible.playbook = "playbook.yml"
  end

# Application server 1
config.vm.define "app1" do |app|
  app.vm.hostname = "orc-app1.dev"
  app.vm.network :private_network, ip: "192.168.60.6"
end

end
</code>```

答:
Vagrant by default uses its own, auto-generated inventory file in .vagrant/provisioners/ansible/inventory/vagrant_ansible_inventory.

There is an option ansible.inventory_path in Vagrant to point to the inventory file/directory other than the auto-generated one, but you don't use it to point to the /etc/ansible/hosts in Vagrantfile, so Vagrant is completely unaware of it. Likewise it does not look for host_vars and group_vars in the /etc/ansible.

On the other hand, the path to roles is not overridden by the inventory file, so the fact that Vagrant uses its own one does not influence the path for roles.

They are loaded by default from /etc/ansible/roles (or whatever directory Ansible uses as its default, for example /usr/local/etc/ansible/roles on macOS).

Body:
I have below folder structure, which seem to make it build and load the roles, but the group and host vars are not being loaded. How come?

/etc/ansible/

- hosts
- requirements.yml
- group_vars/
    - app/
        - postgres.yml
- host_vars/
    - app1/
        - postgres.yml
- roles

/documents/ansible/

- playbook.yml
- vagrant

host file

# Application servers
[app]
192.168.60.6

# Group multi
[multi:children]
app

#variables applied to all servers
[multi:vars]
ansible_ssh_user=vagrant
ansible_ssh_private_key_file=~/.vagrant.d/insecure_private_key

**vagrant **

# -*- mode: ruby -*-
# vi: set ft=ruby :

Vagrant.configure("2") do |config|

  # Genral Vagrant VM Configuration.
  config.vm.box = "geerlingguy/centos7"
  config.ssh.insert_key = false
  config.vm.synced_folder ".", "/vagrant", disabled: true
  config.vm.provider :virtualbox do |v|
    v.memory = 256
    v.linked_clone = true
  end

  config.vm.provision "ansible" do |ansible|
    ansible.playbook = "playbook.yml"
  end

# Application server 1
config.vm.define "app1" do |app|
  app.vm.hostname = "orc-app1.dev"
  app.vm.network :private_network, ip: "192.168.60.6"
end

end


问:
SVG: How to remove the offset from tspan for multiline text with text-anchor set to middle?
I have some multi-line text and I am using <text> and <tspan> to handle this.  I want each line to be centered, so I am using in the main <text> tag text-anchor="middle". However, even with dx=0, the entire block is still shifted by the total length text.

How can I do multi-lined <tspan> centered SVG text?

e.g.

```<code><text text-anchor="middle" font-size="12px">
    This would normally be centered
    <tspan>
        this should be too.
    </tspan>
</text>
</code>```

答:
You could specify the same x for the tspan as the text e.g.

<svg>
<text x="100" y="30" text-anchor="middle" font-size="12px">
    This would normally be centered
    <tspan x="100" dy="30">
        this should be too.
    </tspan>
</text>
</svg>```
</div>
</div>
</p>

<p>or use a transform and set x="0" for the tspan...</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <svg>
    <text transform="translate(100, 30)" text-anchor="middle" font-size="12px">
        This would normally be centered
        <tspan x="0" dy="30">
            this should be too.
        </tspan>
    </text>
    </svg></code>```

Body:
I have some multi-line text and I am using <text> and <tspan> to handle this.  I want each line to be centered, so I am using in the main <text> tag text-anchor="middle". However, even with dx=0, the entire block is still shifted by the total length text.

How can I do multi-lined <tspan> centered SVG text?

e.g.

<text text-anchor="middle" font-size="12px">
    This would normally be centered
    <tspan>
        this should be too.
    </tspan>
</text>

Body:
You could specify the same x for the tspan as the text e.g.

<svg>
<text x="100" y="30" text-anchor="middle" font-size="12px">
    This would normally be centered
    <tspan x="100" dy="30">
        this should be too.
    </tspan>
</text>
</svg>

or use a transform and set x="0" for the tspan...

    <svg>
    <text transform="translate(100, 30)" text-anchor="middle" font-size="12px">
        This would normally be centered
        <tspan x="0" dy="30">
            this should be too.
        </tspan>
    </text>
    </svg>


问:
check for the option label string
I'm using the option Label string for my Html.DropDownList but my datasource is a SelectList. How I would check for the option label back on the server? The backing type for the variable is an EnumType. I inspected the value and it says 0 but it won't let me check for 0.

Thanks,
rod.

答:
How about casting the value back to the enum type on the server:</p>

```<code>[HttpPost]
public ActionResult Index(int selectedValue)
{
    MyEnum label = (MyEnum)selectedValue;
    ...
}
</code>```

Title: check for the option label string

Body:
How about casting the value back to the enum type on the server:

[HttpPost]
public ActionResult Index(int selectedValue)
{
    MyEnum label = (MyEnum)selectedValue;
    ...
}


问:
Unhandled Promise rejection: Template parse errors on Angular 2
I'm new on angular 2 and I'm trying to create a trivial module, but I get an error.

app.component.html

```<code>import { Component } from '@angular/core';
import { Cronometro } from '../app/modules/cronometro';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  //directives:[Cronometro]
})
export class AppComponent {

}
</code>```

app.component.html

```<code><h1>
  {{title}}
</h1>
<h2>Cronometro</h2>
<cronometro></cronometro>
</code>```

cronometro.ts

```<code>import {Component} from '@angular/core';

@Component({
  selector: 'cronometro',
  templateUrl: 'app/modules/cronometro.html'
})

export class Cronometro {
  title = 'My First Angular App';

  public horas:number = 0;
  public minutos:number = 0;
  public segundos:number = 0;
  public started = null;

  constructor(){

  }

  start(){
    if(!this.started){
      this.started = true;
      console.log("start");
      this.started = setInterval(
        ()=>{
          this.segundos++;
          if(this.segundos == 60){
            this.minutos++;
            this.segundos = 0;
            if(this.minutos == 60){
              this.minutos = 0;
              this.horas++;
            }
          }
        }
        ,10);
    }
  }

  lapse(){

  }

  stop(){
    console.log("stop");
    clearInterval(this.started);
    this.started = null;
  }
}
</code>```

cronometro.html

```<code><button (click) = "start()" >Start</button>
<button (click) = "lapse()" >Lapso</button>
<button (click) = "stop()" >Stop</button>
<div >
  <p>{{horas}}:{{minutos}}:{{segundos}}</p>
</div>
</code>```

and this the error message

```<code>Unhandled Promise rejection: Template parse errors:
'cronometro' is not a known element:
1. If 'cronometro' is an Angular component, then verify that it is part of this module.
2. To allow any element add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("
</h1>
<h2>Cronometro</h2>
[ERROR ->]<cronometro></cronometro>
"): ng:///AppModule/AppComponent.html@4:0 ; Zone: <root> ; Task: Promise.then ; Value: Error: Template parse errors:
'cronometro' is not a known element:
1. If 'cronometro' is an Angular component, then verify that it is part of this module.
2. To allow any element add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("
</h1>
<h2>Cronometro</h2>
[ERROR ->]<cronometro></cronometro>
"): ng:///AppModule/AppComponent.html@4:0
</code>```

How would I make this a known element?

答:
You need to add the component to the NgModule, as error suggests:

If 'cronometro' is an Angular component, then verify that it is part of this module.

In your app.module.ts, add it to the declarations array:

```<code>@NgModule({
  declarations: [AppComponent, Cronometro ],
})
export class AppModule { }
</code>```

I suggest you use Angular CLI, because it will do this automatically when you use its commands to generate components/directives/etc.

ContentLicense: CC BY-SA 4.0

Body:
I'm new on angular 2 and I'm trying to create a trivial module, but I get an error.

app.component.html

import { Component } from '@angular/core';
import { Cronometro } from '../app/modules/cronometro';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  //directives:[Cronometro]
})
export class AppComponent {

}

app.component.html

  {{title}}

Cronometro

<cronometro></cronometro>

cronometro.ts

import {Component} from '@angular/core';

@Component({
  selector: 'cronometro',
  templateUrl: 'app/modules/cronometro.html'
})

export class Cronometro {
  title = 'My First Angular App';

  public horas:number = 0;
  public minutos:number = 0;
  public segundos:number = 0;
  public started = null;

  constructor(){

  }

  start(){
    if(!this.started){
      this.started = true;
      console.log("start");
      this.started = setInterval(
        ()=>{
          this.segundos++;
          if(this.segundos == 60){
            this.minutos++;
            this.segundos = 0;
            if(this.minutos == 60){
              this.minutos = 0;
              this.horas++;
            }
          }
        }
        ,10);
    }
  }

  lapse(){

  }

  stop(){
    console.log("stop");
    clearInterval(this.started);
    this.started = null;
  }
}

cronometro.html

<button (click) = "start()" >Start</button>
<button (click) = "lapse()" >Lapso</button>
<button (click) = "stop()" >Stop</button>

{{horas}}:{{minutos}}:{{segundos}}

and this the error message

Unhandled Promise rejection: Template parse errors:
'cronometro' is not a known element:
1. If 'cronometro' is an Angular component, then verify that it is part of this module.
2. To allow any element add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("

Cronometro

[ERROR ->]<cronometro></cronometro>
"): ng:///AppModule/AppComponent.html@4:0 ; Zone: <root> ; Task: Promise.then ; Value: Error: Template parse errors:
'cronometro' is not a known element:
1. If 'cronometro' is an Angular component, then verify that it is part of this module.
2. To allow any element add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("

Cronometro

[ERROR ->]<cronometro></cronometro>
"): ng:///AppModule/AppComponent.html@4:0

How would I make this a known element?

Body:
You need to add the component to the NgModule, as error suggests:

If 'cronometro' is an Angular component, then verify that it is part of this module.

In your app.module.ts, add it to the declarations array:

@NgModule({
  declarations: [AppComponent, Cronometro ],
})
export class AppModule { }

I suggest you use Angular CLI, because it will do this automatically when you use its commands to generate components/directives/etc.