问:
Python 3 Calendar
Would anyone know how to make Python return a date format like this from the calendar function?:

```<code>date = "20170714"
</code>```

Basically I am looking for some enhancements if its possible for the API request to gather hourly weather data.. My problem is the code needs to be re-ran for each day.. Its a little clunky and time consuming to rerun the script 365 times to get a years worth of weather data, but its the only way I know how. Can a loop with the calendar function automate things?

```<code>from urllib.request import urlopen
from pandas.io.json import json_normalize
import json
import pandas as pd

api_key = ""
date = "20170714"
zip_code = "96345"

response = urlopen("http://api.wunderground.com/api/%s/history_%s/q/%s.json" % (api_key, date, zip_code))

json_data = response.read().decode('utf-8', 'replace')

data = json.loads(json_data)

for observation in data['history']['observations']:
     print("Date/Time:    " + observation['date']['pretty'])
     print("Temperature:  " + observation['tempi'])
     print("Humidity:     " + observation['hum'])

df = json_normalize(data['history']['observations'])

df = df[['date.pretty','tempi','hum']]
df['date.pretty'] = pd.to_datetime(df['date.pretty'])

print(df)
</code>```

This simple calendar script can return every day in the month of December 2013, but its not in a format that weather underground API would understand... Ultimately I am hoping to create a loop where the API request can gather a months data, (or even an entire year at a time) with the calendar function Vs one day manual fashion.... Is this possible??!

```<code>import calendar

tc = calendar.TextCalendar(firstweekday=0)

for i in tc.itermonthdays(2013,12):
    print(i)
</code>```

Thanks

答:
There are restrictions on how many requests you can make a day with a free API key, but this is the way I would suggest. As a note, anything date and/or time related I almost always use the arrow package. Something along these lines should work for you.</p>

```<code>import arrow # learn more: https://python.org/pypi/arrow
from WunderWeather import weather # learn more: https://python.org/pypi/WunderWeather

api_key = ''
extractor = weather.Extract(api_key)
zip = '96345'

# get 20170101 00:00
begin_date = arrow.get("2017","YYYY")
# get 20171231 23:00
end_date = arrow.get("2018","YYYY").shift(hours=-1)
for date in arrow.Arrow.range('hour',begin_date,end_date):
  # get date object for feature
  # http://wunderweather.readthedocs.io/en/latest/WunderWeather.html#WunderWeather.weather.Extract.date
  date_weather = extractor.date(zip,date.format('YYYYMMDD'))

  # use shortcut to get observations and data
  # http://wunderweather.readthedocs.io/en/latest/WunderWeather.html#WunderWeather.date.Observation
  for observation in date_weather.observations:
    print("Date:",observation.date_pretty)
    print("Temp:",observation.temp_f)
</code>```

Title: Python 3 Calendar

Body:
Would anyone know how to make Python return a date format like this from the calendar function?:

date = "20170714"

Basically I am looking for some enhancements if its possible for the API request to gather hourly weather data.. My problem is the code needs to be re-ran for each day.. Its a little clunky and time consuming to rerun the script 365 times to get a years worth of weather data, but its the only way I know how. Can a loop with the calendar function automate things?

from urllib.request import urlopen
from pandas.io.json import json_normalize
import json
import pandas as pd

api_key = ""
date = "20170714"
zip_code = "96345"

response = urlopen("http://api.wunderground.com/api/%s/history_%s/q/%s.json" % (api_key, date, zip_code))

json_data = response.read().decode('utf-8', 'replace')

data = json.loads(json_data)

for observation in data['history']['observations']:
     print("Date/Time:    " + observation['date']['pretty'])
     print("Temperature:  " + observation['tempi'])
     print("Humidity:     " + observation['hum'])

df = json_normalize(data['history']['observations'])

df = df[['date.pretty','tempi','hum']]
df['date.pretty'] = pd.to_datetime(df['date.pretty'])

print(df)

This simple calendar script can return every day in the month of December 2013, but its not in a format that weather underground API would understand... Ultimately I am hoping to create a loop where the API request can gather a months data, (or even an entire year at a time) with the calendar function Vs one day manual fashion.... Is this possible??!

import calendar

tc = calendar.TextCalendar(firstweekday=0)

for i in tc.itermonthdays(2013,12):
    print(i)

Thanks

Body:
There are restrictions on how many requests you can make a day with a free API key, but this is the way I would suggest. As a note, anything date and/or time related I almost always use the arrow package. Something along these lines should work for you.

import arrow # learn more: https://python.org/pypi/arrow
from WunderWeather import weather # learn more: https://python.org/pypi/WunderWeather

api_key = ''
extractor = weather.Extract(api_key)
zip = '96345'

# get 20170101 00:00
begin_date = arrow.get("2017","YYYY")
# get 20171231 23:00
end_date = arrow.get("2018","YYYY").shift(hours=-1)
for date in arrow.Arrow.range('hour',begin_date,end_date):
  # get date object for feature
  # http://wunderweather.readthedocs.io/en/latest/WunderWeather.html#WunderWeather.weather.Extract.date
  date_weather = extractor.date(zip,date.format('YYYYMMDD'))

  # use shortcut to get observations and data
  # http://wunderweather.readthedocs.io/en/latest/WunderWeather.html#WunderWeather.date.Observation
  for observation in date_weather.observations:
    print("Date:",observation.date_pretty)
    print("Temp:",observation.temp_f)


来源: stackexchange

问:
Finding serialVersionUID of serialized object
Is there a way to determine the generated serialVersionUID of a serialized Java object?

The problem is that I serialized an object without explicitely specifying the serialVersionUID. Now the deserialization process complains about class incompatibilities. However I didn't change the class in a way which would make it incompatible. So I assume that it is enough to specify the serialVersionUID in the class as it is stored in the object data. In order to do this I need to read the serialVersionUID from the serialized data.

答:
for Android developers,

you can also enable serialization inspection from Settings -> Editor -> Inspections -> enable "Serializable class without 'serialVersionUID' check" first, then ALT+ ENTER, the studio will create serialVersionUID for you.

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
Excel Macro Autofilter and Delete Rows
I am trying to get the coding below working but getting errors.

Coding selects another worksheet, then autofilter a column and delete row.

Line having trouble is .AutoFilter 1, "NoNo"

Run-time error '1004': AutoFilter method of Range clas failed.

Can I please get some assistance.

```<code>Private Sub Project()
Worksheets("YesYes").Select
With ActiveSheet
.AutoFilterMode = False
 With Range("y1", Range("y" & Rows.Count).End(xlUp))
    .AutoFilter 1, "*NoNo*"
    On Error Resume Next
    .Offset(1).SpecialCells(12).EntireRow.Delete
End With
.AutoFilterMode = False
End With
End Sub
</code>```

答:
Selecting does not necessarily "Activate" the worksheet.  Instead of:

```<code>Worksheets("YesYes").Select
With ActiveSheet
</code>```

Do this:

```<code>Worksheets("YesYes").Activate
With ActiveSheet
</code>```

Title: Excel Macro Autofilter and Delete Rows

Body:
I am trying to get the coding below working but getting errors.

Coding selects another worksheet, then autofilter a column and delete row.

Line having trouble is .AutoFilter 1, "NoNo"

Run-time error '1004': AutoFilter method of Range clas failed.

Can I please get some assistance.

Private Sub Project()
Worksheets("YesYes").Select
With ActiveSheet
.AutoFilterMode = False
 With Range("y1", Range("y" & Rows.Count).End(xlUp))
    .AutoFilter 1, "*NoNo*"
    On Error Resume Next
    .Offset(1).SpecialCells(12).EntireRow.Delete
End With
.AutoFilterMode = False
End With
End Sub

Body:
Selecting does not necessarily "Activate" the worksheet.  Instead of:

Worksheets("YesYes").Select
With ActiveSheet

Do this:

Worksheets("YesYes").Activate
With ActiveSheet


问:
Async communication between ViewModel and Model using MVVM-Light messaging?
I am starting off writing an app for WP7 that involves retrieving data via an HTTPWebRequest, I am trying to find the best way to get the data back to the ViewModel once the async request has returned with the data.

The Model and ViewModel are split into seperate projects in their own namespaces, so am not sure if the MVVM-Light can work in this way.  Or should I just use a lightweight IoC implementation and delegates/events to call back to the ViewModel once the call in the Model has returned?

答:
Try this out for size: http://amazedsaint.blogspot.com/2010/10/asynchronous-delegate-command-for-your.html. Great for testing as well, as none of your methods need to be Asynchronous, you just execute your Async Command.

I edited it slightly to extend the DelegateCommand so I could call RaiseCanExecuteChanged() method, as below:

```<code>public class AsyncDelegateCommand : DelegateCommand, ICommand
{

    BackgroundWorker _worker = new BackgroundWorker();
    Func<bool> _canExecute;

    /// <summary>
    /// The constructor
    /// </summary>
    /// <param name="action">The action to be executed</param>
    /// <param name="canExecute">Will be used to determine if the action can be executed</param>
    /// <param name="completed">Will be invoked when the action is completed</param>
    /// <param name="error">Will be invoked if the action throws an error</param>
    public AsyncDelegateCommand(Action action,
                                Func<bool> canExecute = null,
                                Action<object> completed = null,
                                Action<Exception> error = null
                                ) : base(action, canExecute)
    {
    ...
    }
}
</code>```

Hope that's of help.

Body:
Try this out for size: http://amazedsaint.blogspot.com/2010/10/asynchronous-delegate-command-for-your.html. Great for testing as well, as none of your methods need to be Asynchronous, you just execute your Async Command.

I edited it slightly to extend the DelegateCommand so I could call RaiseCanExecuteChanged() method, as below:

public class AsyncDelegateCommand : DelegateCommand, ICommand
{

    BackgroundWorker _worker = new BackgroundWorker();
    Func<bool> _canExecute;

    /// <summary>
    /// The constructor
    /// </summary>
    /// <param name="action">The action to be executed</param>
    /// <param name="canExecute">Will be used to determine if the action can be executed</param>
    /// <param name="completed">Will be invoked when the action is completed</param>
    /// <param name="error">Will be invoked if the action throws an error</param>
    public AsyncDelegateCommand(Action action,
                                Func<bool> canExecute = null,
                                Action<object> completed = null,
                                Action<Exception> error = null
                                ) : base(action, canExecute)
    {
    ...
    }
}

Hope that's of help.


问:
pybind11: how to package c++ and python code into a single package?
I am trying to package together an existing Python code and a new C++ 11 code using CMake and pybind 11. I think I am missing something simple to add into CMake scripts, but can't find it anywhere: pybind11 examples have only C++ code and none of Python, other online resources are rather convoluted and not up-to-date -- so I just can't figure out how to package functions in both languages together and make them available via Python's import my_package down the line... as an example, I have cloned the cmake_example from pybind11 and added a mult function into cmake_example/mult.py

```<code>def mult(a, b):
    return a * b
</code>```

how would I make it visible along with add and subtract to pass the test below?

```<code>import cmake_example as m

assert m.__version__ == '0.0.1'
assert m.add(1, 2) == 3
assert m.subtract(1, 2) == -1
assert m.mult(2, 2) == 4
</code>```

currently, this test fails..

Thanks!

答:
Once you've cloned the repo, cd to top level directory `cmake_example'

Change ./src/main.cpp to include a "mult" function:

```<code>#include <pybind11/pybind11.h>

int add(int i, int j) {
    return i + j;
}

int mult(int i, int j) {
   return i * j;
}

namespace py = pybind11;

PYBIND11_MODULE(cmake_example, m) {
    m.doc() = R"pbdoc(
        Pybind11 example plugin
        -----------------------

        .. currentmodule:: cmake_example

        .. autosummary::
           :toctree: _generate

           add
           subtract
           mult

    )pbdoc";

    m.def("add", &add, R"pbdoc(
        Add two numbers

        Some other explanation about the add function.
    )pbdoc");

   m.def("mult", &mult, R"pbdoc(
        Multiply two numbers

        Some other explanation about the mult function.
    )pbdoc");
</code>```

(the rest of the file is the same)

Now make it:

```<code>$ cmake -H. -Bbuild
$ cmake --build build -- -j3
</code>```

The module for import will be created in the ./build directory. Go to it, then within a python shell your example should work.

For the namespace import, you could do something with pkgutil:

create the directory structure:

```<code>./my_mod
    __init__.py
    cmake_example.***.so
</code>```

and another parallel structure

```<code>./extensions
    /my_mod
        __init__.py
        cmake_example_py.py
</code>```

and place in ./my_mod/__init__.py

```<code>import pkgutil
__path__ = pkgutil.extend_path(__path__, __name__)

from .cmake_example import add, subtract
from .cmake_example_py import mult
</code>```

in ./extensions/my_mod/__init__.py

```<code>from cmake_example_py import mult
</code>```

Then append both ./my_mod and ./extensions/my_mod to your $PYTHONPATH, it just might work (it does in my example)

Body:
I am trying to package together an existing Python code and a new C++ 11 code using CMake and pybind 11. I think I am missing something simple to add into CMake scripts, but can't find it anywhere: pybind11 examples have only C++ code and none of Python, other online resources are rather convoluted and not up-to-date -- so I just can't figure out how to package functions in both languages together and make them available via Python's import my_package down the line... as an example, I have cloned the cmake_example from pybind11 and added a mult function into cmake_example/mult.py

def mult(a, b):
    return a * b

how would I make it visible along with add and subtract to pass the test below?

import cmake_example as m

assert m.__version__ == '0.0.1'
assert m.add(1, 2) == 3
assert m.subtract(1, 2) == -1
assert m.mult(2, 2) == 4

currently, this test fails..

Thanks!

Body:
Once you've cloned the repo, cd to top level directory `cmake_example'

Change ./src/main.cpp to include a "mult" function:

#include <pybind11/pybind11.h>

int add(int i, int j) {
    return i + j;
}

int mult(int i, int j) {
   return i * j;
}

namespace py = pybind11;

PYBIND11_MODULE(cmake_example, m) {
    m.doc() = R"pbdoc(
        Pybind11 example plugin
        -----------------------

        .. currentmodule:: cmake_example

        .. autosummary::
           :toctree: _generate

           add
           subtract
           mult

    )pbdoc";

    m.def("add", &add, R"pbdoc(
        Add two numbers

        Some other explanation about the add function.
    )pbdoc");

   m.def("mult", &mult, R"pbdoc(
        Multiply two numbers

        Some other explanation about the mult function.
    )pbdoc");

(the rest of the file is the same)

Now make it:

$ cmake -H. -Bbuild
$ cmake --build build -- -j3

The module for import will be created in the ./build directory. Go to it, then within a python shell your example should work.

For the namespace import, you could do something with pkgutil:

create the directory structure:

./my_mod
    __init__.py
    cmake_example.***.so

and another parallel structure

./extensions
    /my_mod
        __init__.py
        cmake_example_py.py

and place in ./my_mod/__init__.py

import pkgutil
__path__ = pkgutil.extend_path(__path__, __name__)

from .cmake_example import add, subtract
from .cmake_example_py import mult

in ./extensions/my_mod/__init__.py

from cmake_example_py import mult

Then append both ./my_mod and ./extensions/my_mod to your $PYTHONPATH, it just might work (it does in my example)


问:
Deploy VM from template with pyvmomi
I’m new to python and pyvmomi
I have task to deploy a VM machine from a template,
I looked at examples under github but couldn’t find a script that do that,

https://github.com/vmware/pyvmomi

https://github.com/vmware/pyvmomi-community-samples

Can someone share example or reference to a guide ?

答: The link you provided to the community samples has the sample you are looking for. You need to look at the clone_vm.py file. There is an argument in there to allow you to set the template you are cloning from.</p>

Title: Deploy VM from template with pyvmomi


问:
Unable to return value after implode
This is my array

```<code>Array
(
[0] => Array
    (
        [0] => SC1MTTCS6J1WK
    )

[1] => Array
    (
        [0] => SC1MTTCSHJ1WK
    )
)
</code>```

But when I try to implode them using

```<code>$in_text = implode(",", $myArray3);
</code>```

I can't get the value instead I got this:

```<code>Array,Array
</code>```

Please assist thank you.

答:
Try this code,

```<code>$in_text = '';
foreach ($myArray3 as $key=>$val){
    if(is_array($val)) {
        $in_text .= ($in_text != '' ? ',' : ''). implode(",", $val);;
    } else {
        $in_text .= ($in_text != '' ? ',' : ''). $val;
    }
}
echo $in_text;
</code>```

PS: This will work upto two dimensional array.

Title: Unable to return value after implode

Body:
This is my array

Array
(
[0] => Array
    (
        [0] => SC1MTTCS6J1WK
    )

[1] => Array
    (
        [0] => SC1MTTCSHJ1WK
    )
)

But when I try to implode them using

$in_text = implode(",", $myArray3);

I can't get the value instead I got this:

Array,Array

Please assist thank you.

Body:
Try this code,

$in_text = '';
foreach ($myArray3 as $key=>$val){
    if(is_array($val)) {
        $in_text .= ($in_text != '' ? ',' : ''). implode(",", $val);;
    } else {
        $in_text .= ($in_text != '' ? ',' : ''). $val;
    }
}
echo $in_text;

PS: This will work upto two dimensional array.


问:
How can I download a logfile from Swisscom cloud foundry
I use ELK and write some additional (extensive) log information to a file called extensive.log.

How can I download this file to my local hard drive for further analysis?

I tried the cf-download plugin. But I do get a "permission or corrupt" error.

$ cf download app-name /home/SOME-PATH/logs/extensive.log

答:
You don't need any plugins, you can use scp or sftp.

The documentation is here, but this is a summary:

cf login and cf target

cf curl /v2/info | jq .app_ssh_endpoint this is your SSH host

cf ssh-code then copy the value, this is your password

cf app app-name --guid this is part of your user name

sftp -P 2222 cf:<app-guid>/<app-instance-num>@<ssh-host>, when prompted for a password, enter the passcode you copied in step #3.

Similarly, for scp you can run scp -P 2222 -oUser=cf:<app-guid>/<app-instance-num> my-local-file.json <ssh-host>:my-remote-file.json.

Hope that helps!


问:
How to get string from html form and store to JSON?
I'm coding a signup website, the layout is finish with html and css but I don't know how to get the user name, email and password from the html code and combine them to create a JSON file to send to the server.

```<code><form action="#">
  <div class="form-group">
    <label for="username">Username</label>
    <input class="form-control" type="text" name="username" id="username" placeholder="biker" required />
  </div>
  <div class="form-group">
    <label for="email">Email</label>
    <input class="form-control" type="text" name="email" id="email" placeholder="biker@gmail.com" required />
  </div>
  <div class="form-group">
    <label for="password">Password</label>
    <input class="form-control" type="password" name="password" id="password" placeholder="********" required />
  </div>
  <div class="form-group">
    <label for="passwordRepeat">Repeat Password</label>
    <input class="form-control" type="password" name="passwordRepeat" id="passwordRepeat" placeholder="********" required />
  </div>
  <div class="m-t-lg">
    <ul class="list-inline">
      <li>
        <input class="btn btn--form" type="submit" value="Register" id="registerbtn" />
      </li>
      <li>
        <a class="signup__link" href="#">I am already a member</a>
      </li>
    </ul>
  </div>
</form>
</code>```

I heard using javascript and jquery can do this but I have not learned Javascript yet, so I do all the search but still no luck.

答:
Did you try googling your case?
There are multiple similar treads on Stack Overflow too, e.g. https://stackoverflow.com/a/22195193/6108936

Long story short, if you add id to your form

<form action="#" id="myForm">

then you can simply serialize whole form. This requires includind jQuery though.

```<code><script>
var formData = JSON.stringify($("#myForm").serializeArray());

$.ajax({
  type: "POST",
  url: "yourRoute",
  data: formData,
  success: function(){},
  dataType: "json",
  contentType : "application/json"
});
</script>
</code>```

Side note. As you have signup form there, I strongly suggest adding

```<code><div style="position: absolute; left: -5000px;" aria-hidden="true">
  <input type="text" name="subject"  autofill="off" tabindex="-1" value="">
</div>
</code>```

inside your form. Then, before validation (either before posting everything as JSON of already in backend) check if subject has content. If yes, congrats, you can avoid the spamming.

Why it works? Bots do not understand whenever the field is hidden and fills all the fields. Only exception when the spam is submitted by a real person, not a bot.

And, unless you have your project under firewall, trust me, you want to do this or any other bot prevention.

Body:
I'm coding a signup website, the layout is finish with html and css but I don't know how to get the user name, email and password from the html code and combine them to create a JSON file to send to the server.

<form action="#">

    Username
    <input class="form-control" type="text" name="username" id="username" placeholder="biker" required />

    Email
    <input class="form-control" type="text" name="email" id="email" placeholder="biker@gmail.com" required />

    Password
    <input class="form-control" type="password" name="password" id="password" placeholder="********" required />

    Repeat Password
    <input class="form-control" type="password" name="passwordRepeat" id="passwordRepeat" placeholder="********" required />

        <input class="btn btn--form" type="submit" value="Register" id="registerbtn" />

        I am already a member

</form>

I heard using javascript and jquery can do this but I have not learned Javascript yet, so I do all the search but still no luck.

Body:
Did you try googling your case?
There are multiple similar treads on Stack Overflow too, e.g. https://stackoverflow.com/a/22195193/6108936

Long story short, if you add id to your form

<form action="#" id="myForm">

then you can simply serialize whole form. This requires includind jQuery though.

<script>
var formData = JSON.stringify($("#myForm").serializeArray());

$.ajax({
  type: "POST",
  url: "yourRoute",
  data: formData,
  success: function(){},
  dataType: "json",
  contentType : "application/json"
});
</script>

Side note. As you have signup form there, I strongly suggest adding

<div style="position: absolute; left: -5000px;" aria-hidden="true">
  <input type="text" name="subject"  autofill="off" tabindex="-1" value="">
</div>

inside your form. Then, before validation (either before posting everything as JSON of already in backend) check if subject has content. If yes, congrats, you can avoid the spamming.

Why it works? Bots do not understand whenever the field is hidden and fills all the fields. Only exception when the spam is submitted by a real person, not a bot.

And, unless you have your project under firewall, trust me, you want to do this or any other bot prevention.


问:
Angular 4 - Using Asynchronous custom validators
I have the following code:

HTML:

```<code><div [class]="new_workflow_row_class" id="new_workflow_row">
    <div class="col-sm-6">
        <label class="checkmark-container" i18n>New Workflow
            <input type="checkbox" id="new-workflow" name="new-workflow" [(ngModel)]="new_checkbox" (click)="uncheckBox($event, 'edit')">
            <span class="checkmark" id="new-workflow-checkmark" [class]="checkmark_class"><span id="new-workflow-checkmark-content"></span>{{checkmark_content}}</span>
        </label>
        <input type="text" *ngIf="new_checkbox" id="new_workflow_name" name="new_workflow_name" (keyup)="clearWorkflowError(true)" [(ngModel)]="new_workflow" placeholder="Enter Workflow Name">
        <p [hidden]="!show_workflow_error && !workflowForm.errors" class="workflow-error" i18n>The workflow name already exists. Please use a different name.</p>
    </div>
</div>
</code>```

Component.ts:

```<code>duplicateWorkflowValidator(control: FormControl) {
    console.log("this validator was called!");
    clearTimeout(this.workflowTimeout);

    return new Promise((resolve, reject) => {
        if (this.new_workflow != '') {
            this.workflowTimeout = setTimeout(() => {
                this
                    .requestService
                    .findWorkflow(control.value)
                    .subscribe((results: any) => {
                        let data: any = results.data;

                        if (data.duplicate) {
                            resolve({ duplicateWorkflow: { value: control.value}})
                        }
                        else if (results.status == "OK") {
                            resolve(null);
                        }
                    })
                ;
            }, 500);
        }
        else {
            resolve(null);
        }

    })

}
</code>```

Inside constructor for component.ts:

```<code>this.workflowForm = new FormGroup({
    name: new FormControl(this.new_workflow, [
        Validators.required,
    ], this.duplicateWorkflowValidator.bind(this))
});
</code>```

I am trying to bind this asynchronous validator to the reactive form but it's not working. I want to use the duplicateWorkflowValidator inside workflowForm and have it trigger an error message when it finds a duplicate workflow.

How do I a) bind the validator to the reactive form properly, b) access the validator errors? Thanks in advance, hopefully this makes sense.

答:
You are mixing template forms with reactive forms. Chose one approach. In the below example I am using reactive forms.

Try this simplified version. For demonstration purposes below the validator will fail when I type test, but succeed when I type anything else. You will need to change that to your service call.

https://angular-sjqjwh.stackblitz.io

Template:

```<code><form [formGroup]="myForm">
    <div>
        <div>
            <input type="text" formControlName="name">
            <div *ngIf="myForm.controls.name.hasError('duplicateWorkflow')">
                Workflow already exists!
            </div>
            {{ myForm.controls.name.hasError('duplicateWorkflow') | json }}
        </div>
    </div>
</form>
</code>```

Component

```<code>import { Component } from '@angular/core';
import { FormControl, FormGroup, Validators, Form, FormBuilder } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  workflowTimeout: number = 0;
  myForm: FormGroup;

  constructor(private fb: FormBuilder) {
    this.myForm = this.fb.group({
      name: new FormControl('',
        [Validators.required],
        this.duplicateWorkflowValidator.bind(this))
    });
  }

  duplicateWorkflowValidator(control: FormControl) {
    console.log("this validator was called!");

    return new Promise((resolve, reject) => {
      if (control.value === 'test') {
        this.workflowTimeout = setTimeout(() => {
          resolve({ duplicateWorkflow: { value: control.value } })
        }, 500);
      }
      else {
        resolve(null);
      }
    });
  }
}
</code>```

Body:
I have the following code:

HTML:

        New Workflow
            <input type="checkbox" id="new-workflow" name="new-workflow" [(ngModel)]="new_checkbox" (click)="uncheckBox($event, 'edit')">
            {{checkmark_content}}

        <input type="text" *ngIf="new_checkbox" id="new_workflow_name" name="new_workflow_name" (keyup)="clearWorkflowError(true)" [(ngModel)]="new_workflow" placeholder="Enter Workflow Name">

The workflow name already exists. Please use a different name.

Component.ts:

duplicateWorkflowValidator(control: FormControl) {
    console.log("this validator was called!");
    clearTimeout(this.workflowTimeout);

    return new Promise((resolve, reject) => {
        if (this.new_workflow != '') {
            this.workflowTimeout = setTimeout(() => {
                this
                    .requestService
                    .findWorkflow(control.value)
                    .subscribe((results: any) => {
                        let data: any = results.data;

                        if (data.duplicate) {
                            resolve({ duplicateWorkflow: { value: control.value}})
                        }
                        else if (results.status == "OK") {
                            resolve(null);
                        }
                    })
                ;
            }, 500);
        }
        else {
            resolve(null);
        }

    })

}

Inside constructor for component.ts:

this.workflowForm = new FormGroup({
    name: new FormControl(this.new_workflow, [
        Validators.required,
    ], this.duplicateWorkflowValidator.bind(this))
});

I am trying to bind this asynchronous validator to the reactive form but it's not working. I want to use the duplicateWorkflowValidator inside workflowForm and have it trigger an error message when it finds a duplicate workflow.

How do I a) bind the validator to the reactive form properly, b) access the validator errors? Thanks in advance, hopefully this makes sense.

Body:
You are mixing template forms with reactive forms. Chose one approach. In the below example I am using reactive forms.

Try this simplified version. For demonstration purposes below the validator will fail when I type test, but succeed when I type anything else. You will need to change that to your service call.

https://angular-sjqjwh.stackblitz.io

Template:

<form [formGroup]="myForm">
    <div>
        <div>
            <input type="text" formControlName="name">
            <div *ngIf="myForm.controls.name.hasError('duplicateWorkflow')">
                Workflow already exists!
            </div>
            {{ myForm.controls.name.hasError('duplicateWorkflow') | json }}
        </div>
    </div>
</form>

Component

import { Component } from '@angular/core';
import { FormControl, FormGroup, Validators, Form, FormBuilder } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  workflowTimeout: number = 0;
  myForm: FormGroup;

  constructor(private fb: FormBuilder) {
    this.myForm = this.fb.group({
      name: new FormControl('',
        [Validators.required],
        this.duplicateWorkflowValidator.bind(this))
    });
  }

  duplicateWorkflowValidator(control: FormControl) {
    console.log("this validator was called!");

    return new Promise((resolve, reject) => {
      if (control.value === 'test') {
        this.workflowTimeout = setTimeout(() => {
          resolve({ duplicateWorkflow: { value: control.value } })
        }, 500);
      }
      else {
        resolve(null);
      }
    });
  }
}


问:
How can I make jQuery find the element if the string placement is random in my selector?
If my HTML were to be

```<code><h1>Hi My Name Is John</h1>
</code>```

How would I make jQuery find this h1 element if I searched for Name and John?

If I use :contains and do $("h1:contains('Name John')") it won't find the element. It will only find the element if it's an exact match so it would be $("h1:contains('Name Is John')")

How can I make jQuery find the element if the string placement is random in my selector?

I've also gotten this to work, but this only works if it's an exact match

```<code>var aray = retrievedData; //This has strings stored in an array
    $("h1").each(function(i, that) {

        var key1 = aray[0];
        var key2 = aray[1];
        var key3 = aray[2];
        var thisText = $(this).text();
        if (thisText.includes(`${key1}`) || thisText.includes(`${key2}`) || thisText.includes(`${key3}`)) {
            //do something
            console.log(($(this).text()));
        }
    });
</code>```

Is there also a way to store these strings in an array and then loop the :contains or && through the h1?

So if I were to have

```<code><h1>Hi My Name is John</h1>
<h1>I like to eat spaghetti</h1>
</code>```

And I stored Name John and like spaghetti, how can I make jQuery automatically make a function for these specific strings and then loop through the h1?

答:
You could you loop through all the h1 and check with && and condition.

```<code>$("h1").each(function(){
   if($(this).text().indexOf("Name")=='-1' && $(this).text().indexOf("John")=='-1')
   {
      //YOUR CODE HERE...
   }
});
</code>```

Edit :
From what I understood :p,
checking all the words in each sentence(string) in the array,
If it matches with anything in any
 it will select it.

```<code>var arr = ["Name John","Hello World"];
$("h1").each(function(){
     for(var s= 0 ; s < arr.length ; s++)
     {
         let a1 = arr[s];
         a1 = a1.split(" ");
         let a2 = $(this).text().trim().split(" ");
         var z = $.map(a1,function(a){return $.inArray(a, a2) < 0 ? null : a;})
         if(z.length > 0)
         {
              //H1 contains some word in it
         }
     }
});
</code>```

Body:
If my HTML were to be

Hi My Name Is John

How would I make jQuery find this h1 element if I searched for Name and John?

If I use :contains and do $("h1:contains('Name John')") it won't find the element. It will only find the element if it's an exact match so it would be $("h1:contains('Name Is John')")

How can I make jQuery find the element if the string placement is random in my selector?

I've also gotten this to work, but this only works if it's an exact match

var aray = retrievedData; //This has strings stored in an array
    $("h1").each(function(i, that) {

        var key1 = aray[0];
        var key2 = aray[1];
        var key3 = aray[2];
        var thisText = $(this).text();
        if (thisText.includes(`${key1}`) || thisText.includes(`${key2}`) || thisText.includes(`${key3}`)) {
            //do something
            console.log(($(this).text()));
        }
    });

Is there also a way to store these strings in an array and then loop the :contains or && through the h1?

So if I were to have

Hi My Name is John

I like to eat spaghetti

And I stored Name John and like spaghetti, how can I make jQuery automatically make a function for these specific strings and then loop through the h1?

Body:
You could you loop through all the h1 and check with && and condition.

$("h1").each(function(){
   if($(this).text().indexOf("Name")=='-1' && $(this).text().indexOf("John")=='-1')
   {
      //YOUR CODE HERE...
   }
});

Edit :
From what I understood :p,
checking all the words in each sentence(string) in the array,
If it matches with anything in any <h1> it will select it.

var arr = ["Name John","Hello World"];
$("h1").each(function(){
     for(var s= 0 ; s < arr.length ; s++)
     {
         let a1 = arr[s];
         a1 = a1.split(" ");
         let a2 = $(this).text().trim().split(" ");
         var z = $.map(a1,function(a){return $.inArray(a, a2) < 0 ? null : a;})
         if(z.length > 0)
         {
              //H1 contains some word in it
         }
     }
});


问:
Rxjava observeOn and subscribeOn in Retrofit
observeOn:
This method simply changes the thread of all operators further downstream
(https://medium.com/upday-devs/rxjava-subscribeon-vs-observeon-9af518ded53a)

When calling API, I want to run the communicating with a server on IO thread and want to handle the result on mainThread.

I see the below code in many tutorials and no doubt it is correct.
but my understanding is opposite so I'd like to know what I'm misunderstanding.

```<code>requestInterface.callApi()
    .observeOn(AndroidSchedulers.mainThread())
    .subscribeOn(Schedulers.io())
    .subscribe())
</code>```

observeOn(AndroidSchedulers.mainThread())

: observeOn changes the thread of all operators further downstream, but in the example, the actual calling API function is upper than observeOn?

.subscribeOn(Schedulers.io())

: Weird part, it needs to be subscribed on main-thread, but subscribe on IO thread?

Please advise me What I'm misunderstanding?

答:
Basic, we will have

```<code>Observable.subscribe(Observer);// => Observer observe Observable and Observable subscribe Observer
</code>```

Example

```<code>requestInterface.callApi().subscribe(new Observer...); // requestInterface.callApi() <=> Observable
</code>```

From the http://reactivex.io/documentation/operators/subscribeon.html

SubscribeOn

SubscribeOn operator designates which thread the Observable will begin operating on, no matter at what point in the chain of operators that operator is called

ObserveOn (affect 2 things)

It instructs the Observable to send notifications to Observers on a specified Scheduler.

ObserveOn affects the thread that the Observable will use below where that operator appears

Example

```<code>registerUserReturnedObserverble()  // run on worker thread because subscribeOn(Schedulers.io()) (line 5)
.andThen(loginReturnObserverble()) // run on worker thread because subscribeOn(Schedulers.io()) (line 5)
.observeOn(AndroidSchedulers.mainThread())
.andThen(getUserDataReturnObserverble()) // run on main thread because .observeOn(AndroidSchedulers.mainThread()) is above this operator (line 3)
.subscribeOn(Schedulers.io())
.subscribe(new Observer<Void>{
    // run on main thread because observeOn(AndroidSchedulers.mainThread())
});
</code>```

Body:
observeOn:
This method simply changes the thread of all operators further downstream
(https://medium.com/upday-devs/rxjava-subscribeon-vs-observeon-9af518ded53a)

When calling API, I want to run the communicating with a server on IO thread and want to handle the result on mainThread.

I see the below code in many tutorials and no doubt it is correct.
but my understanding is opposite so I'd like to know what I'm misunderstanding.

requestInterface.callApi()
    .observeOn(AndroidSchedulers.mainThread())
    .subscribeOn(Schedulers.io())
    .subscribe())

observeOn(AndroidSchedulers.mainThread())

: observeOn changes the thread of all operators further downstream, but in the example, the actual calling API function is upper than observeOn?

.subscribeOn(Schedulers.io())

: Weird part, it needs to be subscribed on main-thread, but subscribe on IO thread?

Please advise me What I'm misunderstanding?

Body:
Basic, we will have

Observable.subscribe(Observer);// => Observer observe Observable and Observable subscribe Observer

Example

requestInterface.callApi().subscribe(new Observer...); // requestInterface.callApi() <=> Observable

From the http://reactivex.io/documentation/operators/subscribeon.html

SubscribeOn

SubscribeOn operator designates which thread the Observable will begin operating on, no matter at what point in the chain of operators that operator is called

ObserveOn (affect 2 things)

It instructs the Observable to send notifications to Observers on a specified Scheduler.

ObserveOn affects the thread that the Observable will use below where that operator appears

Example

registerUserReturnedObserverble()  // run on worker thread because subscribeOn(Schedulers.io()) (line 5)
.andThen(loginReturnObserverble()) // run on worker thread because subscribeOn(Schedulers.io()) (line 5)
.observeOn(AndroidSchedulers.mainThread())
.andThen(getUserDataReturnObserverble()) // run on main thread because .observeOn(AndroidSchedulers.mainThread()) is above this operator (line 3)
.subscribeOn(Schedulers.io())
.subscribe(new Observer<Void>{
    // run on main thread because observeOn(AndroidSchedulers.mainThread())
});


问:
GWT cell widgets with overlay types issues
I have taken the Cell Table example from google developer's guide and made the following changes:

Use overlays instead of Java POJOs

Use a EditTextCell to edit one column

For my surprise, when running the code the Cell Table is adding an extra property to the overlay objects pushed into it. They should look like:

{"name":"John", "address":"123 Fourth Road"}
{"name":"Mary", "address":"222 Lancer Lane"}

But instead they look like:

{"name":"John", "address":"123 Fourth Road", "$H":1}
{"name":"Mary", "address":"222 Lancer Lane", "$H":2}

Here is the modified code that demonstrates the issue:

```<code>import java.util.Arrays;
import java.util.List;

import com.google.gwt.cell.client.EditTextCell;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.ui.RootPanel;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class Overlay implements EntryPoint {

    private static class Contact extends JavaScriptObject {

        protected Contact() {}

        public static native Contact create(String name, String address) /*-{
            return {"name" : name , "address" : address};
        }-*/;
        public final native String getName() /*-{
            return this["name"];
        }-*/;
        public final native void setName(String name) /*-{
            this["name"] = name;
        }-*/;
        public final native String getAddress() /*-{
            return this["address"];
        }-*/;
        public final native void setAddress(String address) /*-{
            this["address"] = address;
        }-*/;
    }

    private static List<Contact> CONTACTS = Arrays.asList(
            Contact.create("John", "123 Fourth Road"),
            Contact.create("Mary", "222 Lancer Lane"));

    /**
     * This is the entry point method.
     */
    public void onModuleLoad() {

        CellTable<Contact> table = new CellTable<Contact>();
        // Create name column.
        Column<Contact, String> nameColumn = new Column<Contact, String>(new EditTextCell()) {
            public String getValue(Contact object) {
                return object.getName();
            }
        };
        // Create address column.
        TextColumn<Contact> addressColumn = new TextColumn<Contact>() {
            public String getValue(Contact contact) {
                return contact.getAddress();
            }
        };
        // Add the columns.
        table.addColumn(nameColumn, "Name");
        table.addColumn(addressColumn, "Address");
        table.setRowCount(CONTACTS.size(), true);
        // Push the data into the widget.
        printList();
        table.setRowData(0, CONTACTS);
        printList();
        RootPanel.get().add(table);
    }

    private void printList() {
        for(Contact contact : CONTACTS) {
            GWT.log(new JSONObject(contact).toString());
        }
    }

}
</code>```

I have checked that it is the editable column the one that causes the issue. If I remove it the table does not modify my overlays.

Anyway, this is a very weird behaviour. I don't feel it is safe to work with overlays if your widgets can add them unexpected properties.

Has anyone encountered this issue before or is this behaviour documented anywhere? Any hints to solve it?

Thanks a lot

答:
The correct answer to this issue was posted in the GWT development forum (link):

The $H property comes from the
  implementation of
  JavaScriptObject#hashCode() (in
  com.google.gwt.cire.client.impl.Impl#getHashCode(Object)).

In your case, this is due to
  AbstractEditableCell maintaining a map
  of value keys to their "view data",
  and your use (I guess) of the default
  ProvidesKey implementation
  (SimpleProvidesKey) which directly
  returns the item.

So, when rendering, the EditTextCell
  calls getViewData, which looks up the
  key in the map (and thus needs the
  hashcode of the key, hence the call to
  hashCode), and the key is your JSO
  (hence the new $H property).

I believe that giving a ProvidesKey
  implementation (in you case, returning
  the name property for instance) to the
  Celltable would solve your issue.

Body:
I have taken the Cell Table example from google developer's guide and made the following changes:

Use overlays instead of Java POJOs

Use a EditTextCell to edit one column

For my surprise, when running the code the Cell Table is adding an extra property to the overlay objects pushed into it. They should look like:

{"name":"John", "address":"123 Fourth Road"}
{"name":"Mary", "address":"222 Lancer Lane"}

But instead they look like:

{"name":"John", "address":"123 Fourth Road", "$H":1}
{"name":"Mary", "address":"222 Lancer Lane", "$H":2}

Here is the modified code that demonstrates the issue:

import java.util.Arrays;
import java.util.List;

import com.google.gwt.cell.client.EditTextCell;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.ui.RootPanel;

/**
 * Entry point classes define onModuleLoad().
 */
public class Overlay implements EntryPoint {

    private static class Contact extends JavaScriptObject {

        protected Contact() {}

        public static native Contact create(String name, String address) /*-{
            return {"name" : name , "address" : address};
        }-*/;
        public final native String getName() /*-{
            return this["name"];
        }-*/;
        public final native void setName(String name) /*-{
            this["name"] = name;
        }-*/;
        public final native String getAddress() /*-{
            return this["address"];
        }-*/;
        public final native void setAddress(String address) /*-{
            this["address"] = address;
        }-*/;
    }

    private static List<Contact> CONTACTS = Arrays.asList(
            Contact.create("John", "123 Fourth Road"),
            Contact.create("Mary", "222 Lancer Lane"));

    /**
     * This is the entry point method.
     */
    public void onModuleLoad() {

        CellTable<Contact> table = new CellTable<Contact>();
        // Create name column.
        Column<Contact, String> nameColumn = new Column<Contact, String>(new EditTextCell()) {
            public String getValue(Contact object) {
                return object.getName();
            }
        };
        // Create address column.
        TextColumn<Contact> addressColumn = new TextColumn<Contact>() {
            public String getValue(Contact contact) {
                return contact.getAddress();
            }
        };
        // Add the columns.
        table.addColumn(nameColumn, "Name");
        table.addColumn(addressColumn, "Address");
        table.setRowCount(CONTACTS.size(), true);
        // Push the data into the widget.
        printList();
        table.setRowData(0, CONTACTS);
        printList();
        RootPanel.get().add(table);
    }

    private void printList() {
        for(Contact contact : CONTACTS) {
            GWT.log(new JSONObject(contact).toString());
        }
    }

}

I have checked that it is the editable column the one that causes the issue. If I remove it the table does not modify my overlays.

Anyway, this is a very weird behaviour. I don't feel it is safe to work with overlays if your widgets can add them unexpected properties.

Has anyone encountered this issue before or is this behaviour documented anywhere? Any hints to solve it?

Thanks a lot


问:
ValueError: not enough values to unpack (expected 3, got 2) with matplotlib
I am trying to plot a temperature gradient on a map of the Gulf of Mexico using matplotlib. I defined lat,long,and temp as x,y,z. Ideally I'd like to have points for each coordinate plotted on top of a map with a colored temperature gradient. Here is the code I used (I shortened the data sets for simplicity):

```<code>poslat=[29.50736,24.50824,28.99417,27.0074,27.00416,26.51342,26.00732,25.99168,26.49908]
poslon=[-86.50889,-84.49289,-87.00188,-89.99935,-91.00347,-90.99752,-91.50267,-92.00522]
postemp = [24.73,24.753,24.753,24.756,24.778,24.859,24.859,24.859,24.867,24.867,24.867,25.224]
x,y,z=m(poslon,poslat,postemp)
m.plot(x,y,'ro',markersize=5)
plt.contour(x,y,z)
plt.colorbar()
plt.show()`
</code>```

and here are the errors I am getting:

```<code>    Warning (from warnings module):
  File "/Users/sydneyharned/anaconda3/lib/python3.6/site-packages/mpl_toolkits/basemap/__init__.py", line 1711
    if limb is not ax.axesPatch:
MatplotlibDeprecationWarning: The axesPatch function was deprecated in version 2.1. Use Axes.patch instead.
Traceback (most recent call last):
  File "/Users/sydneyharned/praccompproject.py", line 31, in <module>
    x,y,z=m(poslon,poslat,postemp)
ValueError: not enough values to unpack (expected 3, got 2)
</code>```

I can't seem to figure out values I'm missing.. does anyone know how to fix either of these? any help is appreciated.

答:
You should check return of function "m".

As debug info describes, "m" returns only two value, while in the usage of it, it needs three.

```<code>(x,y,z) = m(poslon,poslat,postemp)

# should return (x,y) maybe
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to plot a temperature gradient on a map of the Gulf of Mexico using matplotlib. I defined lat,long,and temp as x,y,z. Ideally I'd like to have points for each coordinate plotted on top of a map with a colored temperature gradient. Here is the code I used (I shortened the data sets for simplicity):

poslat=[29.50736,24.50824,28.99417,27.0074,27.00416,26.51342,26.00732,25.99168,26.49908]
poslon=[-86.50889,-84.49289,-87.00188,-89.99935,-91.00347,-90.99752,-91.50267,-92.00522]
postemp = [24.73,24.753,24.753,24.756,24.778,24.859,24.859,24.859,24.867,24.867,24.867,25.224]
x,y,z=m(poslon,poslat,postemp)
m.plot(x,y,'ro',markersize=5)
plt.contour(x,y,z)
plt.colorbar()
plt.show()`

and here are the errors I am getting:

    Warning (from warnings module):
  File "/Users/sydneyharned/anaconda3/lib/python3.6/site-packages/mpl_toolkits/basemap/__init__.py", line 1711
    if limb is not ax.axesPatch:
MatplotlibDeprecationWarning: The axesPatch function was deprecated in version 2.1. Use Axes.patch instead.
Traceback (most recent call last):
  File "/Users/sydneyharned/praccompproject.py", line 31, in <module>
    x,y,z=m(poslon,poslat,postemp)
ValueError: not enough values to unpack (expected 3, got 2)

I can't seem to figure out values I'm missing.. does anyone know how to fix either of these? any help is appreciated.

Body:
You should check return of function "m".

As debug info describes, "m" returns only two value, while in the usage of it, it needs three.

(x,y,z) = m(poslon,poslat,postemp)

# should return (x,y) maybe


答:
You can use</p>

```<code>$("h1:contains('Name'):contains('John')")
</code>```

Title: How can I make jQuery find the element if the string placement is random in my selector?

Body:
You can use

$("h1:contains('Name'):contains('John')")


问:
Ionic 2 Infinite Scroll event never fires
I'm trying to use ionic's infinite scroll.  However, no matter what I do I can't get this working.  Also, there example makes no sense to me what so ever.

I have this page I'm using to import messages:

```<code><astoot-layout [pageName]="pageName" [basePage]="this">
  <ion-content padding-horizontal padding class="messages-page-content">
    <!--<ion-scroll scrollY="true" class="messages">-->
    <ion-list>
      <ion-item *ngFor="let message of messages">
        <!--<div *ngFor="let message of messages" class="day-wrapper">-->
          <div [class]="'message message-' + getOwnerClassPrefix(message.senderUserId)">
            <div class="message-content message-content-text">{{message.messageText}}</div>
            <span class="message-timestamp">{{ getCreated(message.created) }}</span>
          </div>
        <!--</div>-->
      </ion-item>
    </ion-list>
    <ion-infinite-scroll (ionInfinite)="pullPage($event)">
      <ion-infinite-scroll-content>
      </ion-infinite-scroll-content>
    </ion-infinite-scroll>
    <!--</ion-scroll>-->
  </ion-content>
  <ion-footer>
    <ion-toolbar color="whatsapp" class="messages-page-footer" position="bottom">
      <ion-input [(ngModel)]="messageText" class="message-editor" placeholder="Type a message"></ion-input>

      <ion-buttons end>
        <button ion-button icon-only *ngIf="messageText" class="message-editor-button" (click)="sendTextMessage()">
          <ion-icon name="send"></ion-icon>
        </button>

        <button ion-button icon-only *ngIf="!messageText" class="message-editor-button">
          <ion-icon name="mic"></ion-icon>
        </button>
      </ion-buttons>
    </ion-toolbar>
  </ion-footer>

</astoot-layout>
</code>```

This is my pullPage Method which is never called:

```<code>pullPage(infiniteScroll: any) {
    //TODO Get nextPage
    setTimeout(() => {
      this.baseProvider.getList(this.filterByConversationId).subscribe(entities => {
          this.messages.concat(entities);
          infiniteScroll.complete();
      });
    }, 500);
}
</code>```

just incase its needed here is my layout component:

```<code><ion-header>
  <ion-navbar align-title="center">
      <button ion-button icon-only menuToggle>
        <ion-icon name="menu"></ion-icon>
      </button>
    <ion-title> {{pageName}} </ion-title>
    <ion-buttons end>
      <button [hidden]="!editOptions || editOptions.isEditing" (click)="toggleEdit()" ion-button>
        <ion-icon name="create"></ion-icon>
         Edit
      </button>
      <button [hidden]="!editOptions || !editOptions.isEditing" class="success" (click)="save()" ion-button>
        <ion-icon name="save"></ion-icon>
         Save
      </button>
      <button [hidden]="!editOptions || !editOptions.isEditing" class="warn" (click)="toggleEdit()" ion-button>
        <ion-icon name="save"></ion-icon>
         Cancel
      </button>
    </ion-buttons>
  </ion-navbar>
</ion-header>
<ng-content>
</ng-content>
</code>```

I'm generally confused on how ion-infinite-scroll even works how does it know when to signal, is it just based on the closest list above it?

How can I get the infinite scroll event to fired?

答:
For anyone who is encountering something similar, the problem is an open issue with ionic caused by the nested ion-content, Luckily in my case I could remove it

My messages page now call the component with out wrapping the content:

```<code><astoot-layout [pageName]="pageName" [basePage]="this"></astoot-layout>
</code>```

My layout page now looks like this:

```<code><ion-header>
  <ion-navbar align-title="center">
      <button ion-button icon-only menuToggle>
        <ion-icon name="menu"></ion-icon>
      </button>
    <ion-title> {{pageName}} </ion-title>
    <ion-buttons end>
      <button [hidden]="!editOptions || editOptions.isEditing" (click)="toggleEdit()" ion-button>
        <ion-icon name="create"></ion-icon>
         Edit
      </button>
      <button [hidden]="!editOptions || !editOptions.isEditing" class="success" (click)="save()" ion-button>
        <ion-icon name="save"></ion-icon>
         Save
      </button>
      <button [hidden]="!editOptions || !editOptions.isEditing" class="warn" (click)="toggleEdit()" ion-button>
        <ion-icon name="save"></ion-icon>
         Cancel
      </button>
    </ion-buttons>
  </ion-navbar>
</ion-header>
</code>```

Body:
I'm trying to use ionic's infinite scroll.  However, no matter what I do I can't get this working.  Also, there example makes no sense to me what so ever.

I have this page I'm using to import messages:

<astoot-layout [pageName]="pageName" [basePage]="this">
  <ion-content padding-horizontal padding class="messages-page-content">

    <ion-list>
      <ion-item *ngFor="let message of messages">

{{message.messageText}}

            {{ getCreated(message.created) }}

      </ion-item>
    </ion-list>
    <ion-infinite-scroll (ionInfinite)="pullPage($event)">
      <ion-infinite-scroll-content>
      </ion-infinite-scroll-content>
    </ion-infinite-scroll>

  </ion-content>
  <ion-footer>
    <ion-toolbar color="whatsapp" class="messages-page-footer" position="bottom">
      <ion-input [(ngModel)]="messageText" class="message-editor" placeholder="Type a message"></ion-input>

      <ion-buttons end>
        <button ion-button icon-only *ngIf="messageText" class="message-editor-button" (click)="sendTextMessage()">
          <ion-icon name="send"></ion-icon>
        </button>

        <button ion-button icon-only *ngIf="!messageText" class="message-editor-button">
          <ion-icon name="mic"></ion-icon>
        </button>
      </ion-buttons>
    </ion-toolbar>
  </ion-footer>

</astoot-layout>

This is my pullPage Method which is never called:

pullPage(infiniteScroll: any) {
    //TODO Get nextPage
    setTimeout(() => {
      this.baseProvider.getList(this.filterByConversationId).subscribe(entities => {
          this.messages.concat(entities);
          infiniteScroll.complete();
      });
    }, 500);
}

just incase its needed here is my layout component:

<ion-header>
  <ion-navbar align-title="center">
      <button ion-button icon-only menuToggle>
        <ion-icon name="menu"></ion-icon>
      </button>
    <ion-title> {{pageName}} </ion-title>
    <ion-buttons end>
      <button [hidden]="!editOptions || editOptions.isEditing" (click)="toggleEdit()" ion-button>
        <ion-icon name="create"></ion-icon>
         Edit
      </button>
      <button [hidden]="!editOptions || !editOptions.isEditing" class="success" (click)="save()" ion-button>
        <ion-icon name="save"></ion-icon>
         Save
      </button>
      <button [hidden]="!editOptions || !editOptions.isEditing" class="warn" (click)="toggleEdit()" ion-button>
        <ion-icon name="save"></ion-icon>
         Cancel
      </button>
    </ion-buttons>
  </ion-navbar>
</ion-header>
<ng-content>
</ng-content>

I'm generally confused on how ion-infinite-scroll even works how does it know when to signal, is it just based on the closest list above it?

How can I get the infinite scroll event to fired?

Body:
For anyone who is encountering something similar, the problem is an open issue with ionic caused by the nested ion-content, Luckily in my case I could remove it

My messages page now call the component with out wrapping the content:

<astoot-layout [pageName]="pageName" [basePage]="this"></astoot-layout>

My layout page now looks like this:

<ion-header>
  <ion-navbar align-title="center">
      <button ion-button icon-only menuToggle>
        <ion-icon name="menu"></ion-icon>
      </button>
    <ion-title> {{pageName}} </ion-title>
    <ion-buttons end>
      <button [hidden]="!editOptions || editOptions.isEditing" (click)="toggleEdit()" ion-button>
        <ion-icon name="create"></ion-icon>
        &nbsp;Edit
      </button>
      <button [hidden]="!editOptions || !editOptions.isEditing" class="success" (click)="save()" ion-button>
        <ion-icon name="save"></ion-icon>
        &nbsp;Save
      </button>
      <button [hidden]="!editOptions || !editOptions.isEditing" class="warn" (click)="toggleEdit()" ion-button>
        <ion-icon name="save"></ion-icon>
        &nbsp;Cancel
      </button>
    </ion-buttons>
  </ion-navbar>
</ion-header>


问:
Filtering the duplicates in subset sum combinations
Given an array, I've found all the combinations of subsets that equal a targeted sum, that's because I want the largest array possible.

For instance, the array [1, 2, 2, 2] for the target sum of "4" returns [[2, 2], [2, 2], [2, 2]].

```<code>subsets = []

def subset_sum(numbers, target, partial=[]):
    s = sum(partial)
    if s == target:
        subsets.append(partial)
    if s >= target:
        return
    for i in range(len(numbers)):
        n = numbers[i]
        remaining = numbers[i + 1:]
        subset_sum(remaining, target, partial + [n])

subsets.sort()
subsets.reversed()
</code>```

How can I remove values that are once mentioned in the subsets' list?
In the example above, how can I hay only one [2,2].

And that, show the values of the initial array that are not in this final list?
In the example above [1].

答:
You can use itertools.groupby to remove duplicate lists:

```<code>>>> import itertools
>>> lst = [[2, 2], [2, 2], [2, 2]]
>>> lst.sort()
>>> new_lst = list(k for k,_ in itertools.groupby(lst))
>>> print(new_lst)
[[2, 2]]
</code>```

Then simply flatten new_lst with itertools.chain.from_iterable and check if any of the elements from the initial list do not exist in this flattened list:

```<code>>>> initial = [1,2,2,2]
>>> print([x for x in initial if x not in itertools.chain.from_iterable(new_lst)])
[1]
</code>```

Note: You can probably make your subset_sum() return a list of non duplicate items also, but the above should also work fine.

Body:
Given an array, I've found all the combinations of subsets that equal a targeted sum, that's because I want the largest array possible.

For instance, the array [1, 2, 2, 2] for the target sum of "4" returns [[2, 2], [2, 2], [2, 2]].

subsets = []

def subset_sum(numbers, target, partial=[]):
    s = sum(partial)
    if s == target:
        subsets.append(partial)
    if s >= target:
        return
    for i in range(len(numbers)):
        n = numbers[i]
        remaining = numbers[i + 1:]
        subset_sum(remaining, target, partial + [n])

subsets.sort()
subsets.reversed()

How can I remove values that are once mentioned in the subsets' list?
In the example above, how can I hay only one [2,2].

And that, show the values of the initial array that are not in this final list?
In the example above [1].

Body:
You can use itertools.groupby to remove duplicate lists:

>>> import itertools
>>> lst = [[2, 2], [2, 2], [2, 2]]
>>> lst.sort()
>>> new_lst = list(k for k,_ in itertools.groupby(lst))
>>> print(new_lst)
[[2, 2]]

Then simply flatten new_lst with itertools.chain.from_iterable and check if any of the elements from the initial list do not exist in this flattened list:

>>> initial = [1,2,2,2]
>>> print([x for x in initial if x not in itertools.chain.from_iterable(new_lst)])
[1]

Note: You can probably make your subset_sum() return a list of non duplicate items also, but the above should also work fine.


问:
Automatically set cuda variables in pytorch
I'm trying to automatically set Variables to use cuda if a flag use_gpu is activated.

Usually I would do:

```<code>import torch
from torch import autograd
use_gpu = torch.cuda.is_available()

foo = torch.randn(5)

if use_gpu:
    fooV = autograd.Variable(foo.cuda())
else:
    fooV = autograd.Variable(foo)
</code>```

However, to do things faster when I have to initialise variables in different parts of the code I wanted to do something like this:

```<code>import torch
from torch import autograd
use_gpu = torch.cuda.is_available()

class Variable(autograd.Variable):
    def __init__(self, data, *args, **kwargs):
        if use_gpu:
            data = data.cuda()
        super(Variable, self).__init__(data, *args, **kwargs)

foo = torch.randn(5)
fooV = Variable(foo)
</code>```

Unfortunately, this doesn't seem to be working and fooV doesn't contain a cuda Tensor when the use_gpu is True.

答:
An alternative is to use type method on CPU Tensor to convert it to GPU Tensor,

```<code>if use_cuda:
    dtype = torch.cuda.FloatTensor
else:
    dtype = torch.FloatTensor

x = torch.rand(2,2).type(dtype)
</code>```

Also, you can find a discussion here.

Body:
I'm trying to automatically set Variables to use cuda if a flag use_gpu is activated.

Usually I would do:

import torch
from torch import autograd
use_gpu = torch.cuda.is_available()

foo = torch.randn(5)

if use_gpu:
    fooV = autograd.Variable(foo.cuda())
else:
    fooV = autograd.Variable(foo)

However, to do things faster when I have to initialise variables in different parts of the code I wanted to do something like this:

import torch
from torch import autograd
use_gpu = torch.cuda.is_available()

class Variable(autograd.Variable):
    def __init__(self, data, *args, **kwargs):
        if use_gpu:
            data = data.cuda()
        super(Variable, self).__init__(data, *args, **kwargs)

foo = torch.randn(5)
fooV = Variable(foo)

Unfortunately, this doesn't seem to be working and fooV doesn't contain a cuda Tensor when the use_gpu is True.

Body:
An alternative is to use type method on CPU Tensor to convert it to GPU Tensor,

if use_cuda:
    dtype = torch.cuda.FloatTensor
else:
    dtype = torch.FloatTensor

x = torch.rand(2,2).type(dtype)

Also, you can find a discussion here.


问:
Help with rotating xy-pixel coordinates, unsure about my function
Ok I have a small set of pixels (a character) stored with xy-coordinates. Now I want to rotate the image around its middlepoint with, let's say, a 105 degrees.

Is this the right way to do it?:

Each pixels distance from the middlepoint is its radius.
Then in python code

```<code>new_x = avg_pos_x+(math.cos(math.radians(105))*radius)
new_y = avg_pos_y-(math.sin(math.radians(105))*radius)
</code>```

It seems to work, but then again some pixels appear to be a bit random.

Edit:
Forgot that to rotate each pixel 105 degrees I also calculated the angle between the middlepoint and pixel and added 105 degrees to that.

答:
Looks right. The problem is of accuracy. Pixels near the center get bunched up and pixels far away get spread out.

What you need to do is interpolate the pixels so that it looks smooth.

e.g., when you rotate a pixel and it ends up half way between one pixel and another but you plot it on one you have an issue when it should really be half on one and half on the other. (if that makes any sense).

Since the screen has discrete pixels you have to determine how much of the original pixel contributes to the new pixel.

You do this by looking at the fractional part of the computed coordinates. Say your new_x is an integer, then you know it contributes all to the pixel. BUT say it has fractional part 0.25. This means some 25% of the pixel is actually in the next location. (depending on how you define the pixel origin)

Since your dealing with 2D is is more complex as you have 8 possible pixels. There are algorithms out that do it differently and may work better(faster) but this method will work.

Body:
Ok I have a small set of pixels (a character) stored with xy-coordinates. Now I want to rotate the image around its middlepoint with, let's say, a 105 degrees.

Is this the right way to do it?:

Each pixels distance from the middlepoint is its radius.
Then in python code

new_x = avg_pos_x+(math.cos(math.radians(105))*radius)
new_y = avg_pos_y-(math.sin(math.radians(105))*radius)

It seems to work, but then again some pixels appear to be a bit random.

Edit:
Forgot that to rotate each pixel 105 degrees I also calculated the angle between the middlepoint and pixel and added 105 degrees to that.


问:
How to find part of a string in a python array
I have an array with a column of numbers and a column of strings. I need to find the indices that contain a certain part of the string. Example:

```<code>array([['4', 'red crayon'],
       ['2', 'purple people eater'],
       ['6', 'red hammer'],
       ['12', 'green screwdriver']])
</code>```

I am in Intro Programming so my instructors told me to use if 'stringpart' in array[index] to get a boolean array to use in our problem solving. What I think should happen:

```<code>input:
'red' in array[:,1]
output:
(true,false,true,false)
</code>```

What actually happens is I get all false. I tested the code outside of functions, and applied it to an array with only the strings and it still gives me false. But I tried it with an one of the full strings 'red crayon' and it said true. This partial string code works for the instructors and other students. Why isn't it working for me?

答:
You need to check is the substring is present in any of the elements of the array:

```<code>a = [['4', 'red crayon'],
     ['2', 'purple people eater'],
     ['6', 'red hammer'],
     ['12', 'green screwdriver']]

[True if any(['red' in elt for elt in sub]) else False for sub in a]
</code>```

output:

```<code>[True, False, True, False]
</code>```

Body:
I have an array with a column of numbers and a column of strings. I need to find the indices that contain a certain part of the string. Example:

array([['4', 'red crayon'],
       ['2', 'purple people eater'],
       ['6', 'red hammer'],
       ['12', 'green screwdriver']])

I am in Intro Programming so my instructors told me to use if 'stringpart' in array[index] to get a boolean array to use in our problem solving. What I think should happen:

input:
'red' in array[:,1]
output:
(true,false,true,false)

What actually happens is I get all false. I tested the code outside of functions, and applied it to an array with only the strings and it still gives me false. But I tried it with an one of the full strings 'red crayon' and it said true. This partial string code works for the instructors and other students. Why isn't it working for me?

Body:
You need to check is the substring is present in any of the elements of the array:

a = [['4', 'red crayon'],
     ['2', 'purple people eater'],
     ['6', 'red hammer'],
     ['12', 'green screwdriver']]

[True if any(['red' in elt for elt in sub]) else False for sub in a]

output:

[True, False, True, False]


问:
3 images centered in a row
I am trying to have three images centered in a row and then centered on the page. I've got them all in a row but I cannot get them centered. Any suggestions on getting my group to the middle? I tried 0 auto on the contain class and on the social class. so close!!

My HTML: first thing is div class=contain to wrap the whole thing, but for some reason if I try to include the class contain in HTML it disppears on Stack Overflow so excuse that.

.contain {
  max-width: 960px;
  text-align: center;
}

.social {
  position: relative;
  display: inline-block;
  float: left;
  padding: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="contain">
  <div align="center;" class="social">
    <img src="http://theinvicto.com/wp-
content/uploads/2017/12/facebook.png" alt="" width="75" height="75" />
  </div>
  <div align="center;" class="social">
    <img src="http://theinvicto.com/wp-content/uploads/2017/12/twitter.png" alt="" width="75" height="75" />
  </div>
  <div align="center;" class="social">
    <img src="http://theinvicto.com/wp-
content/uploads/2017/12/instagram.png" alt="" width="75" height="75" />
  </div>
</div></code>```

答:
html

```<code><div class="content">
    <div>
        <img src="facebook.png" alt="" width="75" height="75"/>
    </div>

    <div>
        <img src="twitter.png" alt="" width="75" height="75"/>
    </div>

    <div>
        <img src="instagram.png" alt="" width="75" height="75" />
    </div>
</div>
</code>```

css

```<code>.content {
    text-align:center;
}
</code>```

Title: 3 images centered in a row

Body:
html

<div class="content">
    <div>
        <img src="facebook.png" alt="" width="75" height="75"/>
    </div>

    <div>
        <img src="twitter.png" alt="" width="75" height="75"/>
    </div>

    <div>
        <img src="instagram.png" alt="" width="75" height="75" />
    </div>
</div>

css

.content {
    text-align:center;
}


问:
Session variable from Select Option
I am trying to help users with filling form in the case if their submission was not successfully send.. The first part of the code down below works fine, but the second part is not "detected". Even if the statement is false Select Pair is not shown.

HTML output:

```<code><option selected='selected'> </option>
</code>```

This is just a small piece of my script.

Any suggestion how to fix this? Thanks!

```<code>if(isset($_SESSION['pair'])) {

echo "<option selected='selected'> " . $_SESSION['pair'] . "</option>";

} else {

echo "<option disabled='disabled'>Select Pair</option>";

}
</code>```

答:
unset($_SESSION['pair']);

And run the code again. Chances you didn't properly unset it hence only the first part work.

Title: Session variable from Select Option

Body:
I am trying to help users with filling form in the case if their submission was not successfully send.. The first part of the code down below works fine, but the second part is not "detected". Even if the statement is false Select Pair is not shown.

HTML output:

<option selected='selected'> </option>

This is just a small piece of my script.

Any suggestion how to fix this? Thanks!

if(isset($_SESSION['pair'])) {

echo "<option selected='selected'> " . $_SESSION['pair'] . "</option>";

} else {

echo "<option disabled='disabled'>Select Pair</option>";

}


问:
Select all folders with Automator
How can I create a custom Automator command to simply select all folders within a folder?

If I runned the action it would look like this.

Thanks!
Nicolas

答:
Here is an AppleScript you can add to a "Run AppleScript action" In Automator</p>

```<code>set theFolder to (choose folder)

tell application "Finder" to select every folder of theFolder
</code>```

Title: Select all folders with Automator

Body:
Here is an AppleScript you can add to a "Run AppleScript action" In Automator

set theFolder to (choose folder)

tell application "Finder" to select every folder of theFolder


问:
CREATE TABLE - Works in MySQL but not in Bash
I'm writing a bash script that connects to mysql and creates a database as follows:

mysql -u root -e "CREATE DATABASE test;"

I see the database gets created using the following command:

mysql -u root -e "SHOW databases;"

Which outputs:

```<code>+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
| test               |
+--------------------+
</code>```

Now I wish to USE this newly created database and CREATE TABLE, hence I run this code:

```<code>mysql -u root -e "USE test;"
mysql -u root -e "SELECT DATABASE();"
mysql -u root -e "CREATE TABLE information (id bigint NOT NULL AUTO_INCREMENT, name varchar(128), value_one int(255), value_two int(255), value_three int(255), value_four int(255), value_five bigint, value_six bigint);"
</code>```

In order for me to see which database is selected, the SELECT DATABASE(); statement returns:

```<code>+------------+
| DATABASE() |
+------------+
| NULL       |
+------------+
</code>```

The CREATE TABLE statement gives me this error:

```<code>ERROR 1046 (3D000) at line 1: No database selected
</code>```

Alternatively, I tried joining these together:

mysql -u root -e "USE test; CREATE TABLE information (...);"

With no exit at all. I still get the same error.

Given that mysql supports a connection to the database directly in the command:

mysql test -u root -e "CREATE TABLE information (...);"

Or as per this response:

mysql --database=test -u root -e "CREATE TABLE information (...);"

They didn't work for me either.

Does someone know why I cannot create a table?

Any help is appreciated.

UPDATE

According to @Genuine 's answer, it actually works in mysql but I cannot manage to run the query through bash. Here is what mysql looks like from the terminal:

I've done lots of reading about how to connect the bash script to the according database, and I reiterate that this should work:

mysql -u root -e "USE test; CREATE TABLE information (...);"

But it doesn't and still shoots the ERROR 1046 (3D000).

Is something wrong my bash syntax?

It's also worth mentioning that @Genuine pointed out the correct syntax:

USE test; SELECT DATABASE();

Which now displays:

```<code>+------------+
| DATABASE() |
+------------+
| test       |
+------------+
</code>```

Note: The above script snippets are written sequentially, meaning that I first CREATE DATABASE test;, then USE test; and lastly CREATE TABLE information (...);. My latest connection is through root@127.0.0.1 and I essentially utilise Sequel Pro to help me test my queries first.

答:
select database(); only can show the current database which is used. In shell, each of them is a separate statement，they are not in one session, so you can't use sql like that.

If you want to show what you want you can use sql like use test;select database()

And mysql -u root -e "USE test; CREATE TABLE information (...);" can work in my database, maybe you should check your sql firstly.

Body:
I'm writing a bash script that connects to mysql and creates a database as follows:

mysql -u root -e "CREATE DATABASE test;"

I see the database gets created using the following command:

mysql -u root -e "SHOW databases;"

Which outputs:

+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
| test               |
+--------------------+

Now I wish to USE this newly created database and CREATE TABLE, hence I run this code:

mysql -u root -e "USE test;"
mysql -u root -e "SELECT DATABASE();"
mysql -u root -e "CREATE TABLE information (id bigint NOT NULL AUTO_INCREMENT, name varchar(128), value_one int(255), value_two int(255), value_three int(255), value_four int(255), value_five bigint, value_six bigint);"

In order for me to see which database is selected, the SELECT DATABASE(); statement returns:

+------------+
| DATABASE() |
+------------+
| NULL       |
+------------+

The CREATE TABLE statement gives me this error:

ERROR 1046 (3D000) at line 1: No database selected

Alternatively, I tried joining these together:

mysql -u root -e "USE test; CREATE TABLE information (...);"

With no exit at all. I still get the same error.

Given that mysql supports a connection to the database directly in the command:

mysql test -u root -e "CREATE TABLE information (...);"

Or as per this response:

mysql --database=test -u root -e "CREATE TABLE information (...);"

They didn't work for me either.

Does someone know why I cannot create a table?

Any help is appreciated.

UPDATE

According to @Genuine 's answer, it actually works in mysql but I cannot manage to run the query through bash. Here is what mysql looks like from the terminal:

I've done lots of reading about how to connect the bash script to the according database, and I reiterate that this should work:

mysql -u root -e "USE test; CREATE TABLE information (...);"

But it doesn't and still shoots the ERROR 1046 (3D000).

Is something wrong my bash syntax?

It's also worth mentioning that @Genuine pointed out the correct syntax:

USE test; SELECT DATABASE();

Which now displays:

+------------+
| DATABASE() |
+------------+
| test       |
+------------+

Note: The above script snippets are written sequentially, meaning that I first CREATE DATABASE test;, then USE test; and lastly CREATE TABLE information (...);. My latest connection is through root@127.0.0.1 and I essentially utilise Sequel Pro to help me test my queries first.


问:
Print out all possible strings in C using recursion
My assignment is that code takes a string as input, and if there are x's in the string replace them with either a 0 or a 1, and print out all the possible string combinations. We have to use recursion for this as well. For example, if the input string was "1x0X" the output would be:

```<code>1000
1001
1100
1101
</code>```

I'm really struggling with how I'm supposed to find all the permutations of the string without having the complete string yet. I have a series of function that combine to print out all permutations of a list of numbers, but I don't know how to make a function where it only permutes certain elements of a list.

Does anyone have any suggestions on how to accomplish this?

答:
Recursion is best used when the recursive depth is limited and not too big.

Yet setting aside that axiom, below is a double recursive solution.  Its eats up stack space quickly (that is its biggest constraint) and so is not a robust solution.  Yet it gets the job.

For "code takes a string as input,", use fgets() - not shown.

Yet in the spirit of recursion why not recurse the input too?  The print_combo() recursion produces a linked list (LL) of characters and keeps track of the number of 'x' read.  Once an end-of-line/end-of-file occurs, it is time to print and the linked-list starts with the last character.

The foo() recursion prints the LL in reverse order, passing in a binary mask to direct the x substitution of 0 or 1.  The unsigned binary mask is good for typically 32 x's.  That is another restriction.

If you must, mouse over for the code.

```<code>typedef struct node {
  const struct node *prev;
  int ch;
} node;

// Print the line
void foo(const node *prev, unsigned mask) {
</code>```

```<code>    if (prev) {
        if (prev->ch == 'x' || prev->ch == 'X') {
          foo(prev->prev, mask >> 1);
          putchar("01"[mask & 1]);
        } else {
          foo(prev->prev, mask);
          putchar(prev->ch);
        }
      }
    }  </code>```

```<code>// Read, form the LL and then print
void print_combo(const node *prev, unsigned xcount) {
</code>```

```<code>    node n = {.prev = prev, .ch = getchar()};
      if (n.ch == '\n' || n.ch == EOF) {
        for (unsigned mask = 0; mask < (1u << xcount); mask++) {
          foo(prev, mask);
          putchar('\n');
        }
      } else {
        print_combo(&n, xcount + (n.ch == 'x' || n.ch == 'X'));
      }
    }  </code>```

```<code>int main(void) {
  print_combo(NULL, 0);
}
</code>```

Input

```<code>00x01x10x11
</code>```

Output

```<code>00001010011
00001010111
00001110011
00001110111
00101010011
00101010111
00101110011
00101110111
</code>```

Body:
My assignment is that code takes a string as input, and if there are x's in the string replace them with either a 0 or a 1, and print out all the possible string combinations. We have to use recursion for this as well. For example, if the input string was "1x0X" the output would be:

1000
1001
1100
1101

I'm really struggling with how I'm supposed to find all the permutations of the string without having the complete string yet. I have a series of function that combine to print out all permutations of a list of numbers, but I don't know how to make a function where it only permutes certain elements of a list.

Does anyone have any suggestions on how to accomplish this?

Body:
Recursion is best used when the recursive depth is limited and not too big.

Yet setting aside that axiom, below is a double recursive solution.  Its eats up stack space quickly (that is its biggest constraint) and so is not a robust solution.  Yet it gets the job.

For "code takes a string as input,", use fgets() - not shown.

Yet in the spirit of recursion why not recurse the input too?  The print_combo() recursion produces a linked list (LL) of characters and keeps track of the number of 'x' read.  Once an end-of-line/end-of-file occurs, it is time to print and the linked-list starts with the last character.

The foo() recursion prints the LL in reverse order, passing in a binary mask to direct the x substitution of 0 or 1.  The unsigned binary mask is good for typically 32 x's.  That is another restriction.

If you must, mouse over for the code.

typedef struct node {
  const struct node *prev;
  int ch;
} node;

// Print the line
void foo(const node *prev, unsigned mask) {

    if (prev) {
        if (prev->ch == 'x' || prev->ch == 'X') {
          foo(prev->prev, mask >> 1);
          putchar("01"[mask & 1]);
        } else {
          foo(prev->prev, mask);
          putchar(prev->ch);
        }
      }
    }

// Read, form the LL and then print
void print_combo(const node *prev, unsigned xcount) {

    node n = {.prev = prev, .ch = getchar()};
      if (n.ch == '\n' || n.ch == EOF) {
        for (unsigned mask = 0; mask < (1u << xcount); mask++) {
          foo(prev, mask);
          putchar('\n');
        }
      } else {
        print_combo(&n, xcount + (n.ch == 'x' || n.ch == 'X'));
      }
    }

int main(void) {
  print_combo(NULL, 0);
}

Input

00x01x10x11

Output

00001010011
00001010111
00001110011
00001110111
00101010011
00101010111
00101110011
00101110111


问:
Point azure hosted root domain to aws classic load balancer
I'm need to point an Azure hosted root domain/naked domain (example.com) to an AWS Elastic Load Balancer. Classic ELB's don't have IP's while A records can only point to IP's. Azure doesn't support the non-standard ALIAS/ANAME records that allow a CNAME-like configuration for A records.

Azure DNS provides a way to point to Azure cloud hosted websites using a combination of pointing the A record to the website's IP and creating a TXT record containing the DNS name of the website.

AWS Route 53 provides the ALIAS record type for connecting root domains to Load Balancers.

Is there a way to do this without resorting to using an extra server instance with a static (elastic) IP address just to do 301 redirects to www.example.com?

EDIT:I should add that since asking this question I found out that AWS network load balancers support both static and elastic IPs but we are on OpsWorks Chef 11 stacks which only supports classic load balancers.

答:
Azure doesn't support the non-standard ALIAS/ANAME records

Note that these are not non-standard records, because they aren't record types at all.  They are configuration entries that allow the nameservers to generate and return a standard A or AAAA record (or other standard types, in Route 53) based on information obtained dynamically by the nameserver, rather than based on static configuration.

But, there isn't another good solution to this. That's why these options exist.

A workaround is to use a service like http://wwwizer.com.

But your easiest and most straightforward solution is to host the domain on Route 53.  This doesn't require changing your registrar -- you only have to change the authoritative nameservers.  If you have subdomains that need their DNS hosted elsewhere for operational reasons, you can always delegate them.  But this is a limitation of the fundamental design of DNS.


问:
AFrame - Rotation of a-camera entity continuously 60 degrees at a time
My use case is to rotate camera 60 degree at a time depending on user swipe left or right. So I decide to try it with a-animation. I could drag the camera around like a-videosphere or a-sky and when I swipe it will spin 60 degrees and stop and I could continue swiping left or right, which move 60 degree, plus dragging the camera.

I would also like to see if I can get ease effect on the look-control if possible, couldn't find anything related online.

I tried:

1)  Setting the animation direction normal and reverse dynamically based on the mousedown and mouseup position, but it always spin one direction based on the initial value.

2) I tried binding the from and to, and set the from of the animation based on the rotation value of the a) vr-camera and b) camera-wrapper and set the to of the animation to camera.x camera.y + (+/-60degree) camera.z.  But animation always reset to the original position and start from that point and ignore the from value even the DOM is updated.

3) I tried to rotate the vr-camera without wrapper, and camera-wrapper but both reset the rotation to the original point.

4) I tried to look-controls="enabled: false" on the camera, this remove the dragging of the camera but the swipe still reset from original position.

      handleMouseDown(e) {
        console.log("mousedown");
        document.querySelector('a-animation').stop();
        this.mousedownPosition = { x: e.x, y: e.y };
      },
      handleMouseUp(e) {
        console.log("mouseup");
        this.mouseupPosition = { x: e.x, y: e.y };

        const direction = this.mousedownPosition.x > this.mouseupPosition.x ? 60 : -60;

        debugger;
        const cameraRotation = document.getElementById('camera-wrapper').getAttribute('rotation')
        this.fromRotation = `${cameraRotation.x} ${cameraRotation.y} ${cameraRotation.z}`;

        const yRotation = cameraRotation.y + direction;
        this.toRotation = `${cameraRotation.x} ${yRotation} ${cameraRotation.z}`;

        // Make sure DOM is updated before emit event
        this.$nextTick(function () {
          document.getElementById('camera-wrapper').emit('swipe');
        });

       },```
<pre class="snippet-code-html lang-html prettyprint-override"><code><a-scene  id="aframescene" class="aframebox" vr-mode-ui="enabled: false" embedded physics="gravity: 0;" debug>
        <a-entity id="camera-wrapper">
          <!--<a-camera id="vr-camera" look-controls="enabled: false" fov="60" easing="ease-in-out"> </a-camera>-->
          <a-camera id="vr-camera" look-controls="reverseMouseDrag: true" fov="60" easing="ease-in-out"> </a-camera>
          <a-animation
            id="swipe"
            :from="fromRotation"
            :to="toRotation"
            attribute="rotation"
            direction="normal"
            begin="swipe"
            dur="4000"
            repeat="0"
            easing="ease-in-out">
          </a-animation>
        </a-entity>

        <a-assets timeout="1">
          <video id="videoid" crossorigin="anonymous" src="video.src" type="video/mp4" webkit-playsinline playsinline ></video>
          <img id="imageid" crossorigin="anonymous" src="image.src"></img>
        </a-assets>

        <!-- Handle both image and video as src -->
        <a-entity id="sky" geometry="primitive: sphere; radius: 100"
                  :material="src: #imageid;  side:front; color:#FFF; shader:flat; npot:true'"
                  scale="-1 1 1">
        </a-entity>
      </a-scene></code>```

After the animation ran: The rotation value of camera-wrapper is 0 60 0, where I expected it to be 0 0 0, which is the same as the to value of the animation.

答:
I am able to use aframe-animation-component to bind the from and to values at run time.

require('aframe-animation-component');

      const scene = document.querySelector('a-scene');
      scene.addEventListener('mousedown', this.handleMouseDown);
      scene.addEventListener('mouseup', this.handleMouseUp);

      handleMouseDown(e) {
        this.mousedownPosition = { x: e.x, y: e.y };
      },
      handleMouseUp(e) {
        this.mouseupPosition = { x: e.x, y: e.y };
        const direction = this.mousedownPosition.x > this.mouseupPosition.x ? 60 : -60;

        const cameraRotation = document.getElementById('camera-wrapper').getAttribute('rotation')
        this.fromRotation = `${cameraRotation.x} ${cameraRotation.y} ${cameraRotation.z}`;

        const yRotation = cameraRotation.y + direction;
        this.toRotation = `${cameraRotation.x} ${yRotation} ${cameraRotation.z}`;

        // Make sure DOM is updated before emit event
        this.$nextTick(() => {
          document.getElementById('camera-wrapper').emit('swipe');
        });
      },```
<pre class="snippet-code-html lang-html prettyprint-override"><code><a-scene  id="aframescene" class="aframebox" vr-mode-ui="enabled: false" embedded physics="gravity: 0; debug: true" debug>
        <a-entity id="camera-wrapper"
                  :animation__rotation="`property: rotation; dir: normal; dur: 1000; startEvents:swipe ;
                  easing: easeInSine; from:${fromRotation}; to:${toRotation}`">
          <a-camera id="vr-camera" universal-controls look-controls="{enable: false}" fov="60"></a-camera>
        </a-entity>

        <!-- below replace a-videosphere and a-sky for video and image -->
        <a-entity id="sky" geometry="primitive: sphere; radius: 100"
                  :material="'src: ' + currentSource +'; side:front; color:#FFF; shader:flat; npot:true'"
                  scale="-1 1 1">
        </a-entity>
      </a-scene></code>```

Body:
My use case is to rotate camera 60 degree at a time depending on user swipe left or right. So I decide to try it with a-animation. I could drag the camera around like a-videosphere or a-sky and when I swipe it will spin 60 degrees and stop and I could continue swiping left or right, which move 60 degree, plus dragging the camera.

I would also like to see if I can get ease effect on the look-control if possible, couldn't find anything related online.

I tried:

1)  Setting the animation direction normal and reverse dynamically based on the mousedown and mouseup position, but it always spin one direction based on the initial value.

2) I tried binding the from and to, and set the from of the animation based on the rotation value of the a) vr-camera and b) camera-wrapper and set the to of the animation to camera.x camera.y + (+/-60degree) camera.z.  But animation always reset to the original position and start from that point and ignore the from value even the DOM is updated.

3) I tried to rotate the vr-camera without wrapper, and camera-wrapper but both reset the rotation to the original point.

4) I tried to look-controls="enabled: false" on the camera, this remove the dragging of the camera but the swipe still reset from original position.

      handleMouseDown(e) {
        console.log("mousedown");
        document.querySelector('a-animation').stop();
        this.mousedownPosition = { x: e.x, y: e.y };
      },
      handleMouseUp(e) {
        console.log("mouseup");
        this.mouseupPosition = { x: e.x, y: e.y };

        const direction = this.mousedownPosition.x > this.mouseupPosition.x ? 60 : -60;

        debugger;
        const cameraRotation = document.getElementById('camera-wrapper').getAttribute('rotation')
        this.fromRotation = `${cameraRotation.x} ${cameraRotation.y} ${cameraRotation.z}`;

        const yRotation = cameraRotation.y + direction;
        this.toRotation = `${cameraRotation.x} ${yRotation} ${cameraRotation.z}`;

        // Make sure DOM is updated before emit event
        this.$nextTick(function () {
          document.getElementById('camera-wrapper').emit('swipe');
        });

       },

          <video id="videoid" crossorigin="anonymous" src="video.src" type="video/mp4" webkit-playsinline playsinline ></video>

After the animation ran: The rotation value of camera-wrapper is 0 60 0, where I expected it to be 0 0 0, which is the same as the to value of the animation.

Body:
I am able to use aframe-animation-component to bind the from and to values at run time.

require('aframe-animation-component');

      const scene = document.querySelector('a-scene');
      scene.addEventListener('mousedown', this.handleMouseDown);
      scene.addEventListener('mouseup', this.handleMouseUp);

      handleMouseDown(e) {
        this.mousedownPosition = { x: e.x, y: e.y };
      },
      handleMouseUp(e) {
        this.mouseupPosition = { x: e.x, y: e.y };
        const direction = this.mousedownPosition.x > this.mouseupPosition.x ? 60 : -60;

        const cameraRotation = document.getElementById('camera-wrapper').getAttribute('rotation')
        this.fromRotation = `${cameraRotation.x} ${cameraRotation.y} ${cameraRotation.z}`;

        const yRotation = cameraRotation.y + direction;
        this.toRotation = `${cameraRotation.x} ${yRotation} ${cameraRotation.z}`;

        // Make sure DOM is updated before emit event
        this.$nextTick(() => {
          document.getElementById('camera-wrapper').emit('swipe');
        });
      },

<a-scene  id="aframescene" class="aframebox" vr-mode-ui="enabled: false" embedded physics="gravity: 0; debug: true" debug>
        <a-entity id="camera-wrapper"
                  :animation__rotation="`property: rotation; dir: normal; dur: 1000; startEvents:swipe ;
                  easing: easeInSine; from:${fromRotation}; to:${toRotation}`">
          <a-camera id="vr-camera" universal-controls look-controls="{enable: false}" fov="60"></a-camera>
        </a-entity>

        <!-- below replace a-videosphere and a-sky for video and image -->
        <a-entity id="sky" geometry="primitive: sphere; radius: 100"
                  :material="'src: ' + currentSource +'; side:front; color:#FFF; shader:flat; npot:true'"
                  scale="-1 1 1">
        </a-entity>
      </a-scene>