问:
document.execCommand('copy') doesn't work in firefox for codemirror textarea field
I am using a custom confirmation dialogue with a textarea(codemirror) on it with some text populated. As code mirrors hides the actual textarea element, firefox is not able to get the data from the hidden textarea field. The definition for the confirmation box goes like below:

```<code>var confirmationDialog = MD.ui.dialogs.confirm({
    title: title,
    text: '',
    type: 'dataUri',
    dataUri: formUrl,
    position: 'center',
    buttonForward: {
        text: 'Copy',
        action: function () {
            DataGridExportDialog.CopyToClipboard("#rawXmlImpExp");
        }
    },
    buttonCancel: {
        text: 'Cancel',
        action: function () {
            confirmationDialog.close();
            confirmationDialog.destroy();
        }
    }
});
</code>```

According to the requirement I have updated the confirm button functionality with copy to clipboard functionality so that on clicking on 'Copy' the text in the textarea should be copied to clipboard. Below is the copyToClipboard().

```<code>DataGridExportDialog.CopyToClipboard = function( containerId ) {
/*var textareaData = $('#rawXmlImpExp').val();
var range = document.createRange();
range.selectNodeContents(textareaData);
window.getSelection().addRange(range);*/

var copyTextarea = document.querySelector(containerId);
copyTextarea.select();

try {
    var successful = document.execCommand('copy');
    raiseMessage('Configuration XML copied to clip board.')
} catch (err) {
    raiseWarning('Unable to copy. Please do so manually.');
}}
</code>```

This implementation works fine on chrome but fails in firefox. Any ideas where my code fails on firefox.

答:
Unhided the textarea in try block and hidden the same in finally block.</p>

```<code>CopyToClipboard = function( containerId ) {
  const copyTextarea = $(containerId);
  try {
    $(copyTextarea).css('display','block');
    copyTextarea[0].select();
    document.execCommand('copy');
    raiseMessage('Configuration XML copied to clip board.');
  }
  catch (err) {
    raiseWarning('Unable to copy. Please do so manually.');
  }
  finally {
    $(copyTextarea).css('display','none');
  }
}
</code>```

Body:
I am using a custom confirmation dialogue with a textarea(codemirror) on it with some text populated. As code mirrors hides the actual textarea element, firefox is not able to get the data from the hidden textarea field. The definition for the confirmation box goes like below:

var confirmationDialog = MD.ui.dialogs.confirm({
    title: title,
    text: '',
    type: 'dataUri',
    dataUri: formUrl,
    position: 'center',
    buttonForward: {
        text: 'Copy',
        action: function () {
            DataGridExportDialog.CopyToClipboard("#rawXmlImpExp");
        }
    },
    buttonCancel: {
        text: 'Cancel',
        action: function () {
            confirmationDialog.close();
            confirmationDialog.destroy();
        }
    }
});

According to the requirement I have updated the confirm button functionality with copy to clipboard functionality so that on clicking on 'Copy' the text in the textarea should be copied to clipboard. Below is the copyToClipboard().

DataGridExportDialog.CopyToClipboard = function( containerId ) {
/*var textareaData = $('#rawXmlImpExp').val();
var range = document.createRange();
range.selectNodeContents(textareaData);
window.getSelection().addRange(range);*/

var copyTextarea = document.querySelector(containerId);
copyTextarea.select();

try {
    var successful = document.execCommand('copy');
    raiseMessage('Configuration XML copied to clip board.')
} catch (err) {
    raiseWarning('Unable to copy. Please do so manually.');
}}

This implementation works fine on chrome but fails in firefox. Any ideas where my code fails on firefox.

Body:
Unhided the textarea in try block and hidden the same in finally block.

CopyToClipboard = function( containerId ) {
  const copyTextarea = $(containerId);
  try {
    $(copyTextarea).css('display','block');
    copyTextarea[0].select();
    document.execCommand('copy');
    raiseMessage('Configuration XML copied to clip board.');
  }
  catch (err) {
    raiseWarning('Unable to copy. Please do so manually.');
  }
  finally {
    $(copyTextarea).css('display','none');
  }
}


来源: stackexchange

问:
Regex "match.Groups["T4"]" is not printing full content
Below Regex Match group giving truncated output for T4

```<code>var input = @": May 13 01:16:14.736 UTC: %XYZ-3-PQR: Hello R0 / 16, changed state";
        var regex = new Regex(@":\s+(?<Date>[^%]+)%(?<T1>[A-Za-z]+)-(?<T2>\d+)-(?<T3>[A-Za-z]+):\s+(?<T4>[\w]+)");
        var match = regex.Match(input);
        if (match.Success)
        {
            Console.WriteLine(match.Groups["Date"]);
            Console.WriteLine(match.Groups["T1"]);
            Console.WriteLine(match.Groups["T2"]);
            Console.WriteLine(match.Groups["T3"]);
            Console.WriteLine(match.Groups["T4"]);
        }
</code>```

Output,

Date: May 13 01:16:14.736 UTC:
T1: XYZ
T2: 3
T3: PQR
T4: Hello

T4 output should be: Hello R0 / 16, changed state

Regex Validation is also good. Is there anything we need to change Regex expression?

答:
It appears that you want to capture in T4 the remainder of the line.  If so, then just use .*, i.e. capture the T4 named group using this:

```<code>(?<T4>.*)
</code>```

Code:

```<code>var input = @": May 13 01:16:14.736 UTC: %XYZ-3-PQR: Hello R0 / 16, changed state";
var regex = new Regex(@":\s+(?<Date>[^%]+)%(?<T1>[A-Za-z]+)-(?<T2>\d+)-(?<T3>[A-Za-z]+):\s+(?<T4>.*)");
var match = regex.Match(input);
</code>```

Here is the output from your print statements with the above slight change to your regex:

```<code>May 13 01:16:14.736 UTC:
XYZ
3
PQR
Hello R0 / 16, changed state
</code>```

Demo

ContentLicense: CC BY-SA 3.0

Body:
Below Regex Match group giving truncated output for T4

var input = @": May 13 01:16:14.736 UTC: %XYZ-3-PQR: Hello R0 / 16, changed state";
        var regex = new Regex(@":\s+(?<Date>[^%]+)%(?<T1>[A-Za-z]+)-(?<T2>\d+)-(?<T3>[A-Za-z]+):\s+(?<T4>[\w]+)");
        var match = regex.Match(input);
        if (match.Success)
        {
            Console.WriteLine(match.Groups["Date"]);
            Console.WriteLine(match.Groups["T1"]);
            Console.WriteLine(match.Groups["T2"]);
            Console.WriteLine(match.Groups["T3"]);
            Console.WriteLine(match.Groups["T4"]);
        }

Output,

Date: May 13 01:16:14.736 UTC:
T1: XYZ
T2: 3
T3: PQR
T4: Hello

T4 output should be: Hello R0 / 16, changed state

Regex Validation is also good. Is there anything we need to change Regex expression?

Body:
It appears that you want to capture in T4 the remainder of the line.  If so, then just use .*, i.e. capture the T4 named group using this:

(?<T4>.*)

Code:

var input = @": May 13 01:16:14.736 UTC: %XYZ-3-PQR: Hello R0 / 16, changed state";
var regex = new Regex(@":\s+(?<Date>[^%]+)%(?<T1>[A-Za-z]+)-(?<T2>\d+)-(?<T3>[A-Za-z]+):\s+(?<T4>.*)");
var match = regex.Match(input);

Here is the output from your print statements with the above slight change to your regex:

May 13 01:16:14.736 UTC:
XYZ
3
PQR
Hello R0 / 16, changed state

Demo


问:
Could not format node 'Link' for execution as SQL
```<code>Table1 with
Name,
Address
CityID(foreign key from Table2)

and Table2 with

CityID,
CityName.
</code>```

I am using LINQ to SQL to retrieve data. When I try to oderby CityName I get the following error: base {System.SystemException} = {"Could not format node 'Link' for execution as SQL."}

Here's my LINQ code to retrieve data :

```<code>var Person = from person in db.Table1
                orderby person.Table2.CityName
                select person;
</code>```

Can someone point me why its causing the above mentioned error.

Thanks!

答:
Based on this bug report and my own testing (I was able to reproduce this), it looks like your Table2.CityName property may have Delay Loaded = True in the dbml designer.

Apparently you can't order by a delay-loaded property, so changing Delay Loaded to False on your Table2.CityName property in the DBML designer should take care of it.

ContentLicense: CC BY-SA 2.5

Body:
Table1 with
Name,
Address
CityID(foreign key from Table2)

and Table2 with

CityID,
CityName.

I am using LINQ to SQL to retrieve data. When I try to oderby CityName I get the following error: base {System.SystemException} = {"Could not format node 'Link' for execution as SQL."}

Here's my LINQ code to retrieve data :

var Person = from person in db.Table1
                orderby person.Table2.CityName
                select person;

Can someone point me why its causing the above mentioned error.

Thanks!


问:
What is equivelant of Unwind segue in Android Development
I am used to IOS development and there are unwind segues in Swift to exit to a certain view controller from the present view controller.

(If there is any) What is equivelant of Unwind segue in Android Development? What should I do to go back to a certain activity?

答:
This is handled in onBackPressed() of your Activity, which you can override if you want to do anything special. If you want finer control or more detail,
 you can read up on FragmentManager, which manages the backstack. popBackStack() and popBackStackImmediate() may be what you're looking for. Generally you shouldn't have to micromanage this too much. By default it'll take you back to the previous activity with no effort on your part.

One thing to take note of as an iOS dev jumping into Android, is there's a difference between back (the button at the bottom), and up (the button in the toolbar up top). The back button takes you back to the previous screen you saw(even to other apps), closes the keyboard, or dismisses certain windows. The up button basically returns you to the main screen of the app, popping the whole backstack. There's some fine points here, which Google does an excellent job explaining in the design guidelines.


问:
Nested if-else loops in R
I have a data frame named "crimes" which contains a "pre_rate" column that denotes the crime rate before a certain law is implemented. I would like to put each rate in a "rate_category" column using a nested if-else loop. I have the following code:

```<code>crimes$rate_category =
  with(crimes, ifelse(pre_rate > 0.26 && pre_rate < 0.87, 1,
    ifelse(pre_rate > 1.04 && pre_rate < 1.94, 2,
      ifelse(pre_rate > 2.03 && pre_rate < 2.96, 3,
        ifelse(pre_rate > 3.10 && pre_rate < 3.82, 4,
          ifelse(pre_rate > 4.20 && pre_rate < 11.00, 5, "NA"))))))
crimes
</code>```

and here's a reproducible example:

```<code>pre_rate = c(0.27, 1.91, 2.81, 3.21, 4.80)
crimes = data.frame(pre_rate)
crimes
</code>```

However, when I run the loop with my original data frame, all levels in the "rate_category" column is incorrectly set to 1. What seems to be the problem with the loop above?

答:
Instead of multiple nested ifelse(), a non-equi join and update on join can be used

```<code># OP's sample data set with one out-of-bounds value appended
crimes = data.frame(pre_rate = c(0.27, 1.91, 2.81, 3.21, 4.80, 1.0))

library(data.table)
# specify categories, lower, and upper bounds
bounds <- data.table(
  cat = 1:5,
  lower = c(0.26, 1.04, 2.03, 3.10, 4.2),
  upper = c(0.87, 1.94, 2.96, 3.82, 11)
)
# non-equi join and update on join
setDT(crimes)[bounds, on = .(pre_rate > lower, pre_rate < upper), rate_category := cat][]
</code>```

```<code>   pre_rate rate_category
1:     0.27             1
2:     1.91             2
3:     2.81             3
4:     3.21             4
5:     4.80             5
6:     1.00            NA
</code>```

Note that pre-rate values which are outside of any of the given intervals do get a NA rate_category automatically.

Title: Nested if-else loops in R

Body:
I have a data frame named "crimes" which contains a "pre_rate" column that denotes the crime rate before a certain law is implemented. I would like to put each rate in a "rate_category" column using a nested if-else loop. I have the following code:

crimes$rate_category =
  with(crimes, ifelse(pre_rate > 0.26 && pre_rate < 0.87, 1,
    ifelse(pre_rate > 1.04 && pre_rate < 1.94, 2,
      ifelse(pre_rate > 2.03 && pre_rate < 2.96, 3,
        ifelse(pre_rate > 3.10 && pre_rate < 3.82, 4,
          ifelse(pre_rate > 4.20 && pre_rate < 11.00, 5, "NA"))))))
crimes

and here's a reproducible example:

pre_rate = c(0.27, 1.91, 2.81, 3.21, 4.80)
crimes = data.frame(pre_rate)
crimes

However, when I run the loop with my original data frame, all levels in the "rate_category" column is incorrectly set to 1. What seems to be the problem with the loop above?

Body:
Instead of multiple nested ifelse(), a non-equi join and update on join can be used

# OP's sample data set with one out-of-bounds value appended
crimes = data.frame(pre_rate = c(0.27, 1.91, 2.81, 3.21, 4.80, 1.0))

library(data.table)
# specify categories, lower, and upper bounds
bounds <- data.table(
  cat = 1:5,
  lower = c(0.26, 1.04, 2.03, 3.10, 4.2),
  upper = c(0.87, 1.94, 2.96, 3.82, 11)
)
# non-equi join and update on join
setDT(crimes)[bounds, on = .(pre_rate > lower, pre_rate < upper), rate_category := cat][]

   pre_rate rate_category
1:     0.27             1
2:     1.91             2
3:     2.81             3
4:     3.21             4
5:     4.80             5
6:     1.00            NA

Note that pre-rate values which are outside of any of the given intervals do get a NA rate_category automatically.


问:
Global variable at top of the JavaScript file
Say I declare a global JavaScript variable at the top of a JavaScript file to equal 0

i.e.

```<code>var jVar=0;
</code>```

Then I call a function in the JavaScript to set that variable to 1
ie.

```<code>function setVarToOne(){
    jVar=1;
}
</code>```

If I then reload the page what will the variable equal before the setVarToOne function is called ?

Will the jVar keep the value it was set to in the function or will it be re-initialised to 0?

What I need to understand is, what happens to JavaScript variables when the page is reloaded?

Thanks

答:
When you reload the page the  jVar will be set to 0; because you are initializing it at very first level var jVar=0;
As your function is not called during reload.
If you make a call to setVarToOne() then and only then your global variable value will get change.

You are also having options to set the value at localStorage

```<code>localStorage.setItem(id, value);
</code>```

Body:
Say I declare a global JavaScript variable at the top of a JavaScript file to equal 0

i.e.

var jVar=0;

Then I call a function in the JavaScript to set that variable to 1
ie.

function setVarToOne(){
    jVar=1;
}

If I then reload the page what will the variable equal before the setVarToOne function is called ?

Will the jVar keep the value it was set to in the function or will it be re-initialised to 0?

What I need to understand is, what happens to JavaScript variables when the page is reloaded?

Thanks

Body:
When you reload the page the  jVar will be set to 0; because you are initializing it at very first level var jVar=0;
As your function is not called during reload.
If you make a call to setVarToOne() then and only then your global variable value will get change.

You are also having options to set the value at localStorage

localStorage.setItem(id, value);


问:
Request to URL defined with ingress.kubernetes.io/auth-url annotation is done with HTTP/1.0
I am using auth-url and auth-signin annotation for authenticating access to app. Problem is that request to URL defined with auth-url is always done with HTTP/1.0 and not with HTTP/1.1 as expected. From logs you can see that all other requests are done with HTTP/1.1.

Version used: nginx-ingress-controller:0.9.0-beta.19

Logs from ELB:

```<code>2017-11-30T14:28:30.606436Z dev-sandbox-2cb4 201.137.96.59:58692 10.10.0.101:80 0.000044 0.031215 0.000039 302 302 0 154 "GET https://example.net:443/testing/ HTTP/1.1" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36" ECDHE-RSA-AES128-GCM-SHA256 TLSv1.2
2017-11-30T14:28:30.623944Z dev-sandbox-2cb4 24.134.104.23:40704 10.10.7.144:80 0.000029 0.01263 0.000068 401 401 0 21 "GET https://example.net:443/oauth2/auth HTTP/1.0" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36" ECDHE-RSA-AES128-GCM-SHA256 TLSv1.2
2017-11-30T14:28:30.699239Z dev-sandbox-2cb4 201.137.96.59:58692 10.10.3.6:80 0.000028 0.001223 0.000046 302 302 0 395 "GET https://example.net:443/oauth2/start?rd=https://example.net/testing/ HTTP/1.1" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36" ECDHE-RSA-AES128-GCM-SHA256 TLSv1.2
</code>```

Annotation:

```<code>  annotations:
    ingress.kubernetes.io/auth-url: "https://$host/oauth2/auth"
    ingress.kubernetes.io/auth-signin: "https://$host/oauth2/start"
</code>```

Problem is that in the environment I need to use only 1.1 is allowed.

Is this something to be expected or am I doing something wrong?

答:
Issue can be solved by adding

```<code>proxy_http_version          1.1;
</code>```

under location = {{ $authPath }} block in nginx ingress template.

See https://github.com/kubernetes/ingress-nginx/pull/1787.

Body:
I am using auth-url and auth-signin annotation for authenticating access to app. Problem is that request to URL defined with auth-url is always done with HTTP/1.0 and not with HTTP/1.1 as expected. From logs you can see that all other requests are done with HTTP/1.1.

Version used: nginx-ingress-controller:0.9.0-beta.19

Logs from ELB:

2017-11-30T14:28:30.606436Z dev-sandbox-2cb4 201.137.96.59:58692 10.10.0.101:80 0.000044 0.031215 0.000039 302 302 0 154 "GET https://example.net:443/testing/ HTTP/1.1" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36" ECDHE-RSA-AES128-GCM-SHA256 TLSv1.2
2017-11-30T14:28:30.623944Z dev-sandbox-2cb4 24.134.104.23:40704 10.10.7.144:80 0.000029 0.01263 0.000068 401 401 0 21 "GET https://example.net:443/oauth2/auth HTTP/1.0" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36" ECDHE-RSA-AES128-GCM-SHA256 TLSv1.2
2017-11-30T14:28:30.699239Z dev-sandbox-2cb4 201.137.96.59:58692 10.10.3.6:80 0.000028 0.001223 0.000046 302 302 0 395 "GET https://example.net:443/oauth2/start?rd=https://example.net/testing/ HTTP/1.1" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36" ECDHE-RSA-AES128-GCM-SHA256 TLSv1.2

Annotation:

  annotations:
    ingress.kubernetes.io/auth-url: "https://$host/oauth2/auth"
    ingress.kubernetes.io/auth-signin: "https://$host/oauth2/start"

Problem is that in the environment I need to use only 1.1 is allowed.

Is this something to be expected or am I doing something wrong?

Body:
Issue can be solved by adding

proxy_http_version          1.1;

under location = {{ $authPath }} block in nginx ingress template.

See https://github.com/kubernetes/ingress-nginx/pull/1787.


问:
Dynamic key in psql row_to_json
I have a query:

```<code>SELECT
row_to_json(( SELECT s FROM (
    SELECT
        id,
        addr_id,
        target,
        status
) s
)) FROM shop;
</code>```

which returns me such rows:

```<code>{"id": 1, "addr_id": 12, "target": null, "status": "ACTIVE"}
</code>```

How can I rewrite my query, so value of row (addr_id) would be the key of my json:

```<code>{12: {"id": 1, "target": null, "status": "ACTIVE"}}
</code>```

答:
Use json_build_object instead of row_to_json. I think this makes the query more readable as well.

```<code>SELECT
  json_build_object(shop.addr_id, json_build_object(
    'id', shop.id,
    'target', shop.target,
    'status', shop.status
  ))
FROM shop;
</code>```

Title: Dynamic key in psql row_to_json

Body:
I have a query:

SELECT
row_to_json(( SELECT s FROM (
    SELECT
        id,
        addr_id,
        target,
        status
) s
)) FROM shop;

which returns me such rows:

{"id": 1, "addr_id": 12, "target": null, "status": "ACTIVE"}

How can I rewrite my query, so value of row (addr_id) would be the key of my json:

{12: {"id": 1, "target": null, "status": "ACTIVE"}}

Body:
Use json_build_object instead of row_to_json. I think this makes the query more readable as well.

SELECT
  json_build_object(shop.addr_id, json_build_object(
    'id', shop.id,
    'target', shop.target,
    'status', shop.status
  ))
FROM shop;


问:
How to separate a list into two different lists ?(Python2.7)
My current data is in the format of :

```<code>[  1982,      1, 108108,   5568],
[  1982,      2,  64488,   2433],
...,
[  2007,    498,   4341,    395],
[  2007,    499,   4328,    274],
[  2007,    500,   4323,   -118]]
</code>```

I want to put all of the data that is from 1982 into one list, and all of the data that is from 2007 into another list.

How would I do this?

答:
If you have only two elements 1982 & 2007 then you can try below function ,
or you can add your condition in elif case :

```<code>def ListBreak(alist):
    flist,slist =[],[]
    for each in alist:
        if each[0] == 1982:
            flist.append(each)
        else:
            slist.append(each)
    return flist,slist
</code>```

Here function will return two list that you can simply unpack using :

```<code>f,s = ListBreak(yourList)
</code>```

Hope this helps :)

Body:
My current data is in the format of :

[  1982,      1, 108108,   5568],
[  1982,      2,  64488,   2433],
...,
[  2007,    498,   4341,    395],
[  2007,    499,   4328,    274],
[  2007,    500,   4323,   -118]]

I want to put all of the data that is from 1982 into one list, and all of the data that is from 2007 into another list.

How would I do this?

Body:
If you have only two elements 1982 & 2007 then you can try below function ,
or you can add your condition in elif case :

def ListBreak(alist):
    flist,slist =[],[]
    for each in alist:
        if each[0] == 1982:
            flist.append(each)
        else:
            slist.append(each)
    return flist,slist

Here function will return two list that you can simply unpack using :

f,s = ListBreak(yourList)

Hope this helps :)


问:
Reciving a 'NoMethodError in ContactsController#update' for some odd reason
I'm currently building a simple CRM and right now I'm trying to nest a feature which will allow users to assign tasks inside a contacts section.

So the issue...

When I click on the edit contact section than from the edit form when I click on the submit form I get a "NoMethodError in ContactsController#Update". But I never changed anything in my Contacts Controller.

Below is a screenshot of the whole error page.

The Error Page

Below is my entire contacts_controller.rb file.

```<code>class ContactsController < ApplicationController
def index
    @contacts = Contact.all
end

def show
    @contact = Contact.find(params[:id])
end

def new
    @contact = Contact.new
end

def edit
    @contact = Contact.find(params[:id])
end

def create
    @contact = Contact.new(contact_params)

    if @contact.save
        redirect_to @contact
    else
        render 'new'
    end
end

def update
    @contact = Contact.find(params[:id])

    if @contact.update(contact_params)
        redirect_to @contact
    else
        render 'edit'
    end
end

def destroy
    @contact = Contact.find(params[:id])
    @contact.destroy

    redirect_to contacts_path
end

private
def contact_params
    params.require(:contact).permit(:first_name, :last_name, :job_title, :twitter_url, :linkedin_url, :facebook_url, :medium_url, :email_field, :telephone_field)
end
end
</code>```

I have no idea at all what happened to make my controller break...

If you need any of my other code please ask.

Thank you ahead of time!

=============================

This is my edit.html.erb view code:

```<code> <hr>
 <h1>Edit Contact</h1>
 <%= render 'form' %>
 <%= link_to 'Back', contacts_path %>
</code>```

This is my _form.html.erb code:

```<code> <%= form_with model: @contact, local: true do |form| %>

  <p>
  <%= form.text_field :first_name, placeholder: "Enter Contact Name" %>
  </p>

  <p>
  <%= form.label :job_title %><br>
  <%= form.text_field :job_title %>
  </p>
  <p>
  <%= form.label :twitter_url %><br>
  <%= form.text_field :twitter_url %>
  </p>
  <p>
  <%= form.label :linkedin_url %><br>
  <%= form.text_field :linkedin_url %>
  </p>
  <p>
  <%= form.label :facebook_url %><br>
  <%= form.text_field :facebook_url %>
  </p>
  <p>
  <%= form.label :medium_url %><br>
  <%= form.text_field :medium_url %>
  </p>
  <p>
  <%= form.label :email_field %><br>
  <%= form.text_field :email_field %>
  </p>
  <p>
  <%= form.label :telephone_field %><br>
  <%= form.text_field :telephone_field %>
  </p>
  <p>
  <%= form.submit %>
  </p>
  <% end %>
</code>```

This is my records in my model:

```<code>  t.string :first_name
  t.string :last_name
  t.string :job_title
  t.string :twitter_url
  t.string :linkedin_url
  t.string :facebook_url
  t.string :medium_url
  t.string :email_field
  t.string :telephone_field
</code>```

Here is my contact.rb model code

```<code>class Contact < ApplicationRecord
has_many :notes
has_many :tasks
validates :title, presence: true,
                  length: { minimum: 5}
</code>```

end

答: You need to replace validates :title, presence: true,length: { minimum: 5} to validates :job_title, presence: true,length: { minimum: 5}

Body:
I'm currently building a simple CRM and right now I'm trying to nest a feature which will allow users to assign tasks inside a contacts section.

So the issue...

When I click on the edit contact section than from the edit form when I click on the submit form I get a "NoMethodError in ContactsController#Update". But I never changed anything in my Contacts Controller.

Below is a screenshot of the whole error page.

The Error Page

Below is my entire contacts_controller.rb file.

class ContactsController < ApplicationController
def index
    @contacts = Contact.all
end

def show
    @contact = Contact.find(params[:id])
end

def new
    @contact = Contact.new
end

def edit
    @contact = Contact.find(params[:id])
end

def create
    @contact = Contact.new(contact_params)

    if @contact.save
        redirect_to @contact
    else
        render 'new'
    end
end

def update
    @contact = Contact.find(params[:id])

    if @contact.update(contact_params)
        redirect_to @contact
    else
        render 'edit'
    end
end

def destroy
    @contact = Contact.find(params[:id])
    @contact.destroy

    redirect_to contacts_path
end

private
def contact_params
    params.require(:contact).permit(:first_name, :last_name, :job_title, :twitter_url, :linkedin_url, :facebook_url, :medium_url, :email_field, :telephone_field)
end
end

I have no idea at all what happened to make my controller break...

If you need any of my other code please ask.

Thank you ahead of time!

=============================

This is my edit.html.erb view code:

Edit Contact

 <%= render 'form' %>
 <%= link_to 'Back', contacts_path %>

This is my _form.html.erb code:

 <%= form_with model: @contact, local: true do |form| %>

  <%= form.text_field :first_name, placeholder: "Enter Contact Name" %>

  <%= form.label :job_title %>

  <%= form.text_field :job_title %>

  <%= form.label :twitter_url %>

  <%= form.text_field :twitter_url %>

  <%= form.label :linkedin_url %>

  <%= form.text_field :linkedin_url %>

  <%= form.label :facebook_url %>

  <%= form.text_field :facebook_url %>

  <%= form.label :medium_url %>

  <%= form.text_field :medium_url %>

  <%= form.label :email_field %>

  <%= form.text_field :email_field %>

  <%= form.label :telephone_field %>

  <%= form.text_field :telephone_field %>

  <%= form.submit %>

  <% end %>

This is my records in my model:

  t.string :first_name
  t.string :last_name
  t.string :job_title
  t.string :twitter_url
  t.string :linkedin_url
  t.string :facebook_url
  t.string :medium_url
  t.string :email_field
  t.string :telephone_field

Here is my contact.rb model code

class Contact < ApplicationRecord
has_many :notes
has_many :tasks
validates :title, presence: true,
                  length: { minimum: 5}

end


问:
TFS2018 package step and include files
I am using Octopus for the Package Application step in the build procedure. Under Advanced options I specify /bin/*.dll for include files. However the build doesn't pick up the files. If I leave the include empty it picks up all the files. Is the syntax not valid like this

/bin/*.dll

I also tried

bin/*.dll

but without luck. Any idea what might be wrong?

Here is a screenshot of the build steps...

Here is the log for the Octopus package step

2017-12-02T17:28:15.4090188Z ##[debug]Evaluating condition for step:
  'Package MyProject' 2017-12-02T17:28:15.4090955Z ##[debug]Evaluating:
  succeeded() 2017-12-02T17:28:15.4091343Z ##[debug]Evaluating
  succeeded: 2017-12-02T17:28:15.4092307Z ##[debug]=> (Boolean) True
  2017-12-02T17:28:15.4093048Z ##[debug]Expanded: True
  2017-12-02T17:28:15.4093619Z ##[debug]Result: True
  2017-12-02T17:28:15.4095310Z ##[section]Starting: Package MyProject
  2017-12-02T17:28:15.4101223Z
  ============================================================================== 2017-12-02T17:28:15.4101741Z Task         : Package Application
  2017-12-02T17:28:15.4102147Z Description  : Package your application
  into a NuPkg or Zip file. 2017-12-02T17:28:15.4102500Z Version      :
  2.0.78 2017-12-02T17:28:15.4102834Z Author       : Octopus Deploy 2017-12-02T17:28:15.4103263Z Help         : Version: 2.0.78. More
  Information
  2017-12-02T17:28:15.4103847Z
  ============================================================================== 2017-12-02T17:28:15.4115642Z ##[debug]tf vc resolvePath
  $\MyParentFolder\MyProject\MyProject /loginType:OAuth
  /login:.,******** /noprompt 2017-12-02T17:28:15.8042302Z

[debug]C:\a\w\2\s\MyParentFolder\MyProject\MyProject 2017-12-02T17:28:16.8462262Z ##[debug]VstsTaskSdk 0.6.4 commit

a074a158dbd70b5a72d1295ee42684c30a262b19 2017-12-02T17:28:16.9168209Z

[debug]Entering C:\a\w_tasks\OctopusPack_179fac12-2402-486e-80cf-5a6a8571f7c0\2.0.78\Octopus-Pack.ps1.

2017-12-02T17:28:16.9521027Z ##[debug]Env:INPUT_PACKAGEID: 'MyProject'
  2017-12-02T17:28:16.9547735Z ##[debug]Env:INPUT_PACKAGEFORMAT: 'NuPkg'
  2017-12-02T17:28:16.9596389Z ##[debug]Env:INPUT_PACKAGEVERSION:
  '20171202.3' 2017-12-02T17:28:16.9645182Z

[debug]Env:INPUT_OUTPUTPATH: 'C:\a\w\2\a' 2017-12-02T17:28:16.9645553Z ##[debug]Env:INPUT_SOURCEPATH:

'C:\a\w\2\s\MyParentFolder\MyProject\MyProject'
  2017-12-02T17:28:16.9651385Z ##[debug]Env:INPUT_NUGETAUTHOR: 'MyBrand'
  2017-12-02T17:28:16.9699352Z ##[debug]Env:INPUT_NUGETTITLE:
  'MyParentFolder.B2BAccounts' 2017-12-02T17:28:16.9715752Z

[debug]Env:INPUT_NUGETDESCRIPTION: 'My service' 2017-12-02T17:28:16.9729595Z ##[debug]Env:INPUT_NUGETRELEASENOTES

(empty) 2017-12-02T17:28:16.9786830Z

[debug]Env:INPUT_NUGETRELEASENOTESFILE: 'C:\a\w\2\s' 2017-12-02T17:28:16.9812364Z ##[debug]Env:INPUT_OVERWRITE: 'false'

2017-12-02T17:28:16.9843490Z ##[debug] Converted to bool: False
  2017-12-02T17:28:16.9868739Z ##[debug]Env:INPUT_INCLUDE: './bin/.dll'
  2017-12-02T17:28:16.9896116Z ##[debug]Env:INPUT_LISTFILES: 'false'
  2017-12-02T17:28:16.9914671Z ##[debug] Converted to bool: False
  2017-12-02T17:28:16.9947636Z No Release notes file found
  2017-12-02T17:28:17.0153048Z ##[debug]Entering Invoke-VstsTool.
  2017-12-02T17:28:17.0269801Z ##[debug] FileName:
  'C:\a\w_tasks\OctopusPack_179fac12-2402-486e-80cf-5a6a8571f7c0\2.0.78\Octo.exe'
  2017-12-02T17:28:17.0289645Z ##[debug] Arguments: 'pack
  --id="MyProject" --format=NuPkg --version=20171202.3 --outFolder="C:\a\w\2\a" --basePath="C:\a\w\2\s\MyParentFolder\MyProject\MyProject" --author="RB" --title="MyParentFolder.B2BAccounts" --description="My service" --releaseNotes=""  --overwrite=False --include="./bin/.dll"'
  2017-12-02T17:28:17.0336805Z ##[debug] RequireExitCodeZero: 'True'
  2017-12-02T17:28:17.0375950Z

[command]"C:\a\w_tasks\OctopusPack_179fac12-2402-486e-80cf-5a6a8571f7c0\2.0.78\Octo.exe"

pack --id="MyProject" --format=NuPkg --version=20171202.3
  --outFolder="C:\a\w\2\a" --basePath="C:\a\w\2\s\MyParentFolder\MyProject\MyProject" --author="RB" --title="MyParentFolder.B2BAccounts" --description="My service" --releaseNotes=""  --overwrite=False --include="./bin/*.dll"
  2017-12-02T17:28:17.1287470Z Octopus Deploy Command Line Tool, version
  4.22.1 2017-12-02T17:28:17.1294636Z  2017-12-02T17:28:17.3764140Z Packing MyProject version "20171202.3"... 2017-12-02T17:28:17.3926084Z
  Saving "MyProject.20171202.3.nupkg" to "C:\a\w\2\a"...
  2017-12-02T17:28:17.4063617Z  2017-12-02T17:28:17.4063997Z
  System.InvalidOperationException: Cannot create a package that has no
  dependencies nor content. 2017-12-02T17:28:17.4064229Z    at
  NuGet.Packaging.PackageBuilder.Save(Stream stream)
  2017-12-02T17:28:17.4064537Z    at
  Octopus.Cli.Commands.NuGetPackageBuilder.BuildPackage(String basePath,
  IList`1 includes, ManifestMetadata metadata, String outFolder, Boolean
  overwrite, Boolean verboseInfo) 2017-12-02T17:28:17.4064836Z    at
  Octopus.Cli.Commands.PackCommand.<>c__DisplayClass18_0.b__0()
  2017-12-02T17:28:17.4065077Z    at
  System.Threading.Tasks.Task.InnerInvoke() 2017-12-02T17:28:17.4065264Z
  at System.Threading.Tasks.Task.Execute() 2017-12-02T17:28:17.4065487Z
  --- End of stack trace from previous location where exception was thrown --- 2017-12-02T17:28:17.4065866Z    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task) 2017-12-02T17:28:17.4066304Z    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task) 2017-12-02T17:28:17.4066598Z    at
  Octopus.Cli.Program.Run(String[] args) 2017-12-02T17:28:17.4067897Z
  Exit code: -3 2017-12-02T17:28:17.4164951Z ##[debug]Exit code: -3
  2017-12-02T17:28:17.4309447Z ##[debug]Leaving Invoke-VstsTool.
  2017-12-02T17:28:17.4341893Z ##[debug]Leaving
  C:\a\w_tasks\OctopusPack_179fac12-2402-486e-80cf-5a6a8571f7c0\2.0.78\Octopus-Pack.ps1.
  2017-12-02T17:28:17.4387076Z ##[debug]Caught exception from task
  script. 2017-12-02T17:28:17.4420714Z ##[debug]Error record:
  2017-12-02T17:28:17.5138233Z ##[debug]Invoke-VstsTool : Process
  'Octo.exe' exited with code '-3'. 2017-12-02T17:28:17.5149782Z

[debug]At C:\a\w_tasks\OctopusPack_179fac12-2402-486e-80cf-5a6a8571f7c0\2.0.78\Octopus-Pack.ps1:52

char:5 2017-12-02T17:28:17.5163924Z ##[debug]+     Invoke-VstsTool
  -FileName $octoPath -Arguments $Arguments -Requir ... 2017-12-02T17:28:17.5176209Z ##[debug]+

  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2017-12-02T17:28:17.5189971Z ##[debug]    + CategoryInfo          :
  NotSpecified: (:) [Write-Error], WriteErrorException
  2017-12-02T17:28:17.5202114Z ##[debug]    + FullyQualifiedErrorId :
  Microsoft.PowerShell.Commands.WriteErrorException,Invoke-VstsTool
  2017-12-02T17:28:17.6236509Z ##[debug]  2017-12-02T17:28:17.6456023Z

[debug]Script stack trace: 2017-12-02T17:28:17.6456411Z ##[debug]at Invoke-Tool,

C:\a\w_tasks\OctopusPack_179fac12-2402-486e-80cf-5a6a8571f7c0\2.0.78\ps_modules\VstsTaskSdk\ToolFunctions.ps1:
  line 86 2017-12-02T17:28:17.6456866Z ##[debug]at ,
  C:\a\w_tasks\OctopusPack_179fac12-2402-486e-80cf-5a6a8571f7c0\2.0.78\Octopus-Pack.ps1:
  line 52 2017-12-02T17:28:17.6457192Z ##[debug]at , : line 1 2017-12-02T17:28:17.6457473Z ##[debug]at ,
  : line 22 2017-12-02T17:28:17.6457737Z ##[debug]at
  , : line 18 2017-12-02T17:28:17.6458018Z

[debug]at , : line 1 2017-12-02T17:28:17.6458303Z ##[debug]Exception:

2017-12-02T17:28:17.6458589Z

[debug]Microsoft.PowerShell.Commands.WriteErrorException: Process 'Octo.exe' exited with code '-3'. 2017-12-02T17:28:17.6637507Z

[error]Process 'Octo.exe' exited with code '-3'. 2017-12-02T17:28:17.6637766Z ##[debug]Processed: ##vso[task.logissue

type=error]Process 'Octo.exe' exited with code '-3'.
  2017-12-02T17:28:17.6644964Z ##[debug]Processed: ##vso[task.complete
  result=Failed] 2017-12-02T17:28:17.6965505Z ##[section]Finishing:
  Package MyProject

答: The trick was to use a pattern like ** /bin/*.dll. The double star will match any number of preceding folders.</p>

Title: TFS2018 package step and include files


答:
You can use json_build_object.

```<code>SELECT
json_build_object(addr_id,
row_to_json(( SELECT s FROM (
    SELECT
        id,
        target,
        status
) s
))) FROM shop;
</code>```

Title: Dynamic key in psql row_to_json

Body:
You can use json_build_object.

SELECT
json_build_object(addr_id,
row_to_json(( SELECT s FROM (
    SELECT
        id,
        target,
        status
) s
))) FROM shop;


问:
Access to a single pixel in C#
I'm working on a school project right now. It's meant to be a 3D editing software, (like a very minimized version of Maya). I have to write it in C#, using the 'Windows Application Project'.
I intend to implement all the 3D stuff myself, from projections to shading.
My question is, how can I get direct access to a single pixel in the C# windows application?
I know I'm going to have a main view port in the window. But I haven't decided yet how it will be made. Is there a built in object that I can use, that will let me define the boundaries of the view port, and then paint each pixel individually?
(I'm just shooting in the dark here, I don't know much about C#. I mostly program in C)

Thanks,
Malki.

答:
Using the CreateGraphics() method, this should work:

```<code>Bitmap b = new Bitmap(Width, Height, this.CreateGraphics());
//pixel is:
Color c = b.GetPixel(x, y);
</code>```

To set a pixel to a specific colour, use this instead of Color c = b.GetPixel(x,y):

```<code>b.SetPixel(x, y, c); // where c is a Color
</code>```

If you want a viewport, place a panel or a PictureBox (maybe with Dock: Fill), then use:

```<code>Bitmap b = new Bitmap(viewport.Width, viewport.Height, viewport.CreateGraphics());
</code>```

instead of the first line used previously.

But from what you want to do, I think it would be better to use the OnPaint event:

```<code>void pnlViewport_Paint(object sender, PaintEventArgs e) {
    if ( e.ClipRectange.Width < 1 || e.ClipRectangle.Height < 1 ) return;
    Bitmap b = new Bitmap(e.ClipRectangle.Width, e.ClipRectangle.Height, e.Graphics);
    // ...
}
</code>```

This event fires every time the control needs painted. The first line checks whether the area being drawn is empty - this will not just save CPU time, but your application may crash - you are getting it to make a 0x0 bitmap.

EDIT: Yes, this is resizable, if Dock = DockStyle.Fill; As your window resizes, the control expands to fill the space. It is then repainted - firing the event.

EDIT 2: As pointed out by others, this is still slow. It does sound like it is a requirement to do the 3D drawing yourself, so maybe SDL.NET (which I think can use hardware acceleration) is the way to go. It even has a (slow) SurfaceControl to use.

OwnerDisplayName: Malki

Title: Access to a single pixel in C#

Body:
Using the CreateGraphics() method, this should work:

Bitmap b = new Bitmap(Width, Height, this.CreateGraphics());
//pixel is:
Color c = b.GetPixel(x, y);

To set a pixel to a specific colour, use this instead of Color c = b.GetPixel(x,y):

b.SetPixel(x, y, c); // where c is a Color

If you want a viewport, place a panel or a PictureBox (maybe with Dock: Fill), then use:

Bitmap b = new Bitmap(viewport.Width, viewport.Height, viewport.CreateGraphics());

instead of the first line used previously.

But from what you want to do, I think it would be better to use the OnPaint event:

void pnlViewport_Paint(object sender, PaintEventArgs e) {
    if ( e.ClipRectange.Width < 1 || e.ClipRectangle.Height < 1 ) return;
    Bitmap b = new Bitmap(e.ClipRectangle.Width, e.ClipRectangle.Height, e.Graphics);
    // ...
}

This event fires every time the control needs painted. The first line checks whether the area being drawn is empty - this will not just save CPU time, but your application may crash - you are getting it to make a 0x0 bitmap.

EDIT: Yes, this is resizable, if Dock = DockStyle.Fill; As your window resizes, the control expands to fill the space. It is then repainted - firing the event.

EDIT 2: As pointed out by others, this is still slow. It does sound like it is a requirement to do the 3D drawing yourself, so maybe SDL.NET (which I think can use hardware acceleration) is the way to go. It even has a (slow) SurfaceControl to use.

OwnerDisplayName: person-b

LastEditorDisplayName: person-b


问:
How do I make a textfield editable for 10 seconds on the click of a button?
Using JavaFX, on the click of a button I want to do this:

```<code>spinBtn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
    field.setDisable(false);
    //Delay for 10 seconds
    field.setDisable(true);
    }
});
</code>```

I quickly realized that sleeping wouldn't work as it freezes the GUI completely. I've also tried sleeping threads to get a timer but that still freezes the GUI if input where I want the delay. (Example below)

```<code>spinBtn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
    ExampleTimerThread exampleSleepyThread = new ExampleTimerThread();//this extends Thread
    exampleSleepyThread.start();
//thread sleeps for 10 secs & sets public static boolean finished = true; after sleep
    while(finished == true){
        field.setDisable(false);
        }
    }
});
</code>```

What could I do to prevent this code from freezing the GUI up?
I know in Swing, there is a timer. Is there something similar in JavaFX?

答:
Use PauseTransition to delay events:

```<code>spinBtn.setOnAction(e -> {
    field.setDisabled(false);
    PauseTransition pt = new PauseTransition(Duration.seconds(10));
    pt.setOnFinished(ev -> {
        field.setDisabled(true);
    });
    pt.play();
});
</code>```

Body:
Using JavaFX, on the click of a button I want to do this:

spinBtn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
    field.setDisable(false);
    //Delay for 10 seconds
    field.setDisable(true);
    }
});

I quickly realized that sleeping wouldn't work as it freezes the GUI completely. I've also tried sleeping threads to get a timer but that still freezes the GUI if input where I want the delay. (Example below)

spinBtn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
    ExampleTimerThread exampleSleepyThread = new ExampleTimerThread();//this extends Thread
    exampleSleepyThread.start();
//thread sleeps for 10 secs & sets public static boolean finished = true; after sleep
    while(finished == true){
        field.setDisable(false);
        }
    }
});

What could I do to prevent this code from freezing the GUI up?
I know in Swing, there is a timer. Is there something similar in JavaFX?

Body:
Use PauseTransition to delay events:

spinBtn.setOnAction(e -> {
    field.setDisabled(false);
    PauseTransition pt = new PauseTransition(Duration.seconds(10));
    pt.setOnFinished(ev -> {
        field.setDisabled(true);
    });
    pt.play();
});


问:
Ionic PWA serviceworker - no CORS
I need to implement serviceworker file caching, but using a no-cors flag.
This is because I get a CORS error on my webserver for below code. The code is from the standard Ionic 2 starter template (inside serviceworker.js). I can't use the standard code because for some reason the requests trigger an authentication flow in which there is a redirect to some URL, which fails because of a CORS error.

How would I do that in the nicest (cq. easiest) way?

```<code>// TODO: Implement this without CORS (set no-cors flag)
self.toolbox.precache(
  [
    // './build/main.js',
    // './build/vendor.js',
    // './build/main.css',
    // './build/polyfills.js',
   // 'index.html',
   // 'manifest.json'
  ]
);
</code>```

EDIT: It's not really an authentication error that happens, the user is definitely already authenticated. But because of the redirect during the authentication the request for the files above goes wrong. I found this article: What is an opaque request, and what it serves for? which indicates settings the no cors flag would be the solution. The error I get, like on that page is:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://abc' is therefore not allowed access.
If an opaque response serves your needs, set the request's mode to 'no-cors'
to fetch the resource with CORS disabled.

答:
Solved it myself like below. The install event is what triggers the app to store files locally.</p>

```<code>/**
 * Check out https://googlechromelabs.github.io/sw-toolbox/ for
 * more info on how to use sw-toolbox to custom configure your service worker.
 */

'use strict';
importScripts('./build/sw-toolbox.js');

self.toolbox.options.cache = {
  name: 'ionic-cache'
};

// pre-cache our key assets
// TODO: Implemente this without using CORS (set no-cors flag)
/*
self.toolbox.precache(
  [
    './build/main.js',
    './build/vendor.js',
    './build/main.css',
    './build/polyfills.js',
    'index.html',
    'manifest.json'
  ]
);
*/

// MANUAL precaching in order to evade CORS error on SharePoint

var aFilesToCache = [
  './assets/json/propertyLUT.js',
  './assets/json/propertyvalues.js',
  './build/main.js',
  './build/vendor.js',
  './build/main.css',
  './build/polyfills.js',
  'index.html',
  'manifest.json'
];

self.addEventListener('fetch', function(event) {
  console.log('Handling fetch event for', event.request.url);

  event.respondWith(

    // Opens Cache objects that start with 'font'.
    caches.open('pwa_').then(function(cache) {
      return cache.match(event.request).then(function(response) {
        if (response) {
          console.log('Found response in cache:', response);

          return response;
        }
      }).catch(function(error) {

        // Handles exceptions that arise from match() or fetch().
        console.error('Error in fetch handler:', error);

        throw error;
      });
    })
  );
});

self.addEventListener('install', event => {
  function onInstall(event, filesToCache) {
    console.log('Hit event INSTALL');
    return Promise.all(filesToCache.map(function(aUrl)
    {
      return caches.open('pwa_').then(function(cache)
      {
        debugger;
        aUrl = resolveURL(aUrl, self.location.href);
        return fetch(aUrl, { mode: 'no-cors' })
            .then(function(response)
            {
              return cache.put(aUrl, response.clone());
            });

      })
    }))
  }

  event.waitUntil(
    onInstall(event, aFilesToCache).then( () => self.skipWaiting() )
  );
});

function resolveURL(relative, base) {
  var stack = base.split("/"),
      parts = relative.split("/");
  stack.pop(); // remove current file name (or empty string)
               // (omit if "base" is the current folder without trailing slash)
  for (var i=0; i<parts.length; i++) {
      if (parts[i] == ".")
          continue;
      if (parts[i] == "..")
          stack.pop();
      else
          stack.push(parts[i]);
  }
  return stack.join("/");
}
/*
foreach(aUrl in aFilesToCache)
{
  var corsRequest = new Request(url, {mode: 'no-cors'});
  fetch(corsRequest).then(response => {
    return cache.put("pwa_" + url, response);
  }); // response won't be opaque.
}
*/

// dynamically cache any other local assets
self.toolbox.router.any('/*', self.toolbox.fastest);

// for any other requests go to the network, cache,
// and then only use that cached resource if your user goes offline
self.toolbox.router.default = self.toolbox.networkFirst;
</code>```

Title: Ionic PWA serviceworker - no CORS

Body:
I need to implement serviceworker file caching, but using a no-cors flag.
This is because I get a CORS error on my webserver for below code. The code is from the standard Ionic 2 starter template (inside serviceworker.js). I can't use the standard code because for some reason the requests trigger an authentication flow in which there is a redirect to some URL, which fails because of a CORS error.

How would I do that in the nicest (cq. easiest) way?

// TODO: Implement this without CORS (set no-cors flag)
self.toolbox.precache(
  [
    // './build/main.js',
    // './build/vendor.js',
    // './build/main.css',
    // './build/polyfills.js',
   // 'index.html',
   // 'manifest.json'
  ]
);

EDIT: It's not really an authentication error that happens, the user is definitely already authenticated. But because of the redirect during the authentication the request for the files above goes wrong. I found this article: What is an opaque request, and what it serves for? which indicates settings the no cors flag would be the solution. The error I get, like on that page is:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://abc' is therefore not allowed access.
If an opaque response serves your needs, set the request's mode to 'no-cors'
to fetch the resource with CORS disabled.

Body:
Solved it myself like below. The install event is what triggers the app to store files locally.

/**
 * Check out https://googlechromelabs.github.io/sw-toolbox/ for
 * more info on how to use sw-toolbox to custom configure your service worker.
 */

'use strict';
importScripts('./build/sw-toolbox.js');

self.toolbox.options.cache = {
  name: 'ionic-cache'
};

// pre-cache our key assets
// TODO: Implemente this without using CORS (set no-cors flag)
/*
self.toolbox.precache(
  [
    './build/main.js',
    './build/vendor.js',
    './build/main.css',
    './build/polyfills.js',
    'index.html',
    'manifest.json'
  ]
);
*/

// MANUAL precaching in order to evade CORS error on SharePoint

var aFilesToCache = [
  './assets/json/propertyLUT.js',
  './assets/json/propertyvalues.js',
  './build/main.js',
  './build/vendor.js',
  './build/main.css',
  './build/polyfills.js',
  'index.html',
  'manifest.json'
];

self.addEventListener('fetch', function(event) {
  console.log('Handling fetch event for', event.request.url);

  event.respondWith(

    // Opens Cache objects that start with 'font'.
    caches.open('pwa_').then(function(cache) {
      return cache.match(event.request).then(function(response) {
        if (response) {
          console.log('Found response in cache:', response);

          return response;
        }
      }).catch(function(error) {

        // Handles exceptions that arise from match() or fetch().
        console.error('Error in fetch handler:', error);

        throw error;
      });
    })
  );
});

self.addEventListener('install', event => {
  function onInstall(event, filesToCache) {
    console.log('Hit event INSTALL');
    return Promise.all(filesToCache.map(function(aUrl)
    {
      return caches.open('pwa_').then(function(cache)
      {
        debugger;
        aUrl = resolveURL(aUrl, self.location.href);
        return fetch(aUrl, { mode: 'no-cors' })
            .then(function(response)
            {
              return cache.put(aUrl, response.clone());
            });

      })
    }))
  }

  event.waitUntil(
    onInstall(event, aFilesToCache).then( () => self.skipWaiting() )
  );
});

function resolveURL(relative, base) {
  var stack = base.split("/"),
      parts = relative.split("/");
  stack.pop(); // remove current file name (or empty string)
               // (omit if "base" is the current folder without trailing slash)
  for (var i=0; i<parts.length; i++) {
      if (parts[i] == ".")
          continue;
      if (parts[i] == "..")
          stack.pop();
      else
          stack.push(parts[i]);
  }
  return stack.join("/");
}
/*
foreach(aUrl in aFilesToCache)
{
  var corsRequest = new Request(url, {mode: 'no-cors'});
  fetch(corsRequest).then(response => {
    return cache.put("pwa_" + url, response);
  }); // response won't be opaque.
}
*/

// dynamically cache any other local assets
self.toolbox.router.any('/*', self.toolbox.fastest);

// for any other requests go to the network, cache,
// and then only use that cached resource if your user goes offline
self.toolbox.router.default = self.toolbox.networkFirst;


答: The shorthand character class \w doesn't match spaces (or slashes, or commas) so the capture is stopping at the first space. Add a space (and slash, comma and any other non word characters you're expecting) to the character class e.g. [\w /,]

Title: Regex "match.Groups["T4"]" is not printing full content

Body:
Below Regex Match group giving truncated output for T4

var input = @": May 13 01:16:14.736 UTC: %XYZ-3-PQR: Hello R0 / 16, changed state";
        var regex = new Regex(@":\s+(?<Date>[^%]+)%(?<T1>[A-Za-z]+)-(?<T2>\d+)-(?<T3>[A-Za-z]+):\s+(?<T4>[\w]+)");
        var match = regex.Match(input);
        if (match.Success)
        {
            Console.WriteLine(match.Groups["Date"]);
            Console.WriteLine(match.Groups["T1"]);
            Console.WriteLine(match.Groups["T2"]);
            Console.WriteLine(match.Groups["T3"]);
            Console.WriteLine(match.Groups["T4"]);
        }

Output,

Date: May 13 01:16:14.736 UTC:
T1: XYZ
T2: 3
T3: PQR
T4: Hello

T4 output should be: Hello R0 / 16, changed state

Regex Validation is also good. Is there anything we need to change Regex expression?


问:
Take Unknown number of Inputs as String
Input has an unknown amount of lines of Strings of length 20 each. I am using BufferedReader to take inputs from the console. After the last input it's just waiting for the input. How can I terminate the process?

Example Input:

```<code>10100101111011111111
00000000000000000000
01011101110110101111
</code>```

Above 3 lines are given as input. But its not given there are going to be 3 line of input. That is unknown and my programme is just waiting for the next input after the last line, when it should be terminating.

There is no terminator specified in the problem.

答:
Below code will stop reading the input, once it encounters the "stop". You can use any string in place of "stop"

```<code>while ((strLine = br.nextLine()) != null) {

<Your code>

    if (strLine.equalsIgnoreCase("stop")) {
        break;
    }

}
br.close();
</code>```

You can try the below method, if you can't take more than three inputs from the user. This code will automatically stop taking input after reading 3 inputs:

```<code>Scanner sc = new Scanner(System.in);
String[] arr=new String[3];
for(int i=0;i<=2;i++) {
arr[i]=sc.nextLine();
}
</code>```

This is another method:

```<code>while (!(strLine = sc.nextLine()).isEmpty()) { <Your code> }
</code>```

But you need to press enter twice after giving the input.

Next method is,

```<code>while ((strLine = sc.nextLine()).isEmpty()) { <Your code> }
</code>```

For this you need to give all your input in the same line and press enter once.

Hope this helps.

Title: Take Unknown number of Inputs as String

Body:
Input has an unknown amount of lines of Strings of length 20 each. I am using BufferedReader to take inputs from the console. After the last input it's just waiting for the input. How can I terminate the process?

Example Input:

10100101111011111111
00000000000000000000
01011101110110101111

Above 3 lines are given as input. But its not given there are going to be 3 line of input. That is unknown and my programme is just waiting for the next input after the last line, when it should be terminating.

There is no terminator specified in the problem.

Body:
Below code will stop reading the input, once it encounters the "stop". You can use any string in place of "stop"

while ((strLine = br.nextLine()) != null) {

<Your code>

    if (strLine.equalsIgnoreCase("stop")) {
        break;
    }

}
br.close();

You can try the below method, if you can't take more than three inputs from the user. This code will automatically stop taking input after reading 3 inputs:

Scanner sc = new Scanner(System.in);
String[] arr=new String[3];
for(int i=0;i<=2;i++) {
arr[i]=sc.nextLine();
}

This is another method:

while (!(strLine = sc.nextLine()).isEmpty()) { <Your code> }

But you need to press enter twice after giving the input.

Next method is,

while ((strLine = sc.nextLine()).isEmpty()) { <Your code> }

For this you need to give all your input in the same line and press enter once.

Hope this helps.


问:
SolrNet - The given key was not present in the dictionary
I'm using SolrNet with vb.net 2.0 and can't seem to instantiate solr.

Dim solr As ISolrOperations(Of PMWProperty) = ServiceLocator.Current.GetInstance(Of PMWProperty)()

throws the exception:

[KeyNotFoundException: The given key was not present in the dictionary.]
   System.ThrowHelper.ThrowKeyNotFoundException() +28
   System.Collections.Generic.Dictionary`2.get_Item(TKey key) +7456108
   SolrNet.Utils.Container.DoGetInstance(Type serviceType, String key) +22
   Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance(Type serviceType, String key) +47

[ActivationException: Activation error occured while trying to get instance of type PMWProperty, key ""]
   Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance(Type serviceType, String key) +104
   Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance() +5

I have a class PMWProperty with only a few fields that match to my solr schema.  I can run queries through the solr url just fine (localhost:8983/solr), but can't get it working in my code.

What key is it looking at?  The exception seems to say that the key is "", but what should it be?  Why do I need a key?

答:
You need to get ISolrOperations(Of PMWProperty) from the service locator, not PMWProperty, so the code should look like this:

```<code>Dim solr As ISolrOperations(Of PMWProperty) = ServiceLocator.Current.GetInstance(Of ISolrOperations(Of PMWProperty))()
</code>```

Body:
You need to get ISolrOperations(Of PMWProperty) from the service locator, not PMWProperty, so the code should look like this:

Dim solr As ISolrOperations(Of PMWProperty) = ServiceLocator.Current.GetInstance(Of ISolrOperations(Of PMWProperty))()


问:
Asterisk pjsip loading all endpoints on startup
Asterisk is loading all mysql reatime endpoints on startup, this is causing pjsip to crash and not accept registrations.  Is there an option in the .conf file i can add to not load the endpoints?</p>

答:
i have configured my asterisk in proxy mode with no registration peer with following configuration

```<code>[transport-udp]
type=transport protocol=udp             ;
bind=0.0.0.0
context=default                         ; to be returned as device state (default: "0")
t38_udptl=yes                           ; Whether T 38 UDPTL support is enabled or not (default: "no")
t38_udptl_ec=none                       ; T 38 UDPTL error correction method (default: "none")
t38_udptl_maxdatagram=0                 ; T 38 UDPTL maximum datagram size (default:; "0")
fax_detect=no                           ; Whether CNG tone detection is enabled (default: "no")
fax_detect_timeout=30
</code>```

when i make a call with prxoy mode i got following error on asterisk console

[Dec  4 12:37:53] ERROR[5116]: chan_pjsip.c:2205 request: Unable to
  create PJSIP channel with empty endpoint name

Body:
i have configured my asterisk in proxy mode with no registration peer with following configuration

[transport-udp]
type=transport protocol=udp             ;
bind=0.0.0.0
context=default                         ; to be returned as device state (default: "0")
t38_udptl=yes                           ; Whether T 38 UDPTL support is enabled or not (default: "no")
t38_udptl_ec=none                       ; T 38 UDPTL error correction method (default: "none")
t38_udptl_maxdatagram=0                 ; T 38 UDPTL maximum datagram size (default:; "0")
fax_detect=no                           ; Whether CNG tone detection is enabled (default: "no")
fax_detect_timeout=30

when i make a call with prxoy mode i got following error on asterisk console

[Dec  4 12:37:53] ERROR[5116]: chan_pjsip.c:2205 request: Unable to
  create PJSIP channel with empty endpoint name


问:
Python + OpenCV = How to crop circle?
The below is the code:

```<code>self.img = cv2.imread(image,)
circle = cv2.HoughCircles(self.img, 3,
                          dp=1.5, minDist=1000, minRadius=100, maxRadius=1000)
red = (0,0,255)
x = circle[0][0][0]
y = circle[0][0][1]
r = circle[0][0][2]
cv2.circle(self.img, (x, y), r, red, 2)

    x - X
    y - Y
    r - Radius
    For example: 521.25, 506.25, 318.919
</code>```

From the code how to crop the circle from the given example ?

答:
After circles=cv2.HoughCircles(img,...)</p>
```<code>if len(circles) == 1:
    x, y, r = circles[0][0]
    print x, y, r
    mask = np.zeros((w0,h0),dtype=np.uint8)
    cv2.circle(mask,(x,y),r,(255,255,255),-1,8,0)
    #cv2.imwrite(argv[2],mask)
    out = img*mask
    white = 255-mask
    cv2.imwrite(argv[2],out+white)
</code>```

Title: Python + OpenCV = How to crop circle?

Body:
The below is the code:

self.img = cv2.imread(image,)
circle = cv2.HoughCircles(self.img, 3,
                          dp=1.5, minDist=1000, minRadius=100, maxRadius=1000)
red = (0,0,255)
x = circle[0][0][0]
y = circle[0][0][1]
r = circle[0][0][2]
cv2.circle(self.img, (x, y), r, red, 2)

    x - X
    y - Y
    r - Radius
    For example: 521.25, 506.25, 318.919

From the code how to crop the circle from the given example ?

Body:
After circles=cv2.HoughCircles(img,...)

if len(circles) == 1:
    x, y, r = circles[0][0]
    print x, y, r
    mask = np.zeros((w0,h0),dtype=np.uint8)
    cv2.circle(mask,(x,y),r,(255,255,255),-1,8,0)
    #cv2.imwrite(argv[2],mask)
    out = img*mask
    white = 255-mask
    cv2.imwrite(argv[2],out+white)


问:
How to check if $_POST[image] is set
Re asking how to check if $_POST[FILE] isset
I have a file input and if I submit my form without an image I want something to happen if I uploaded a file in the input I want something different to happen.

```<code>if (!isset($_POST[image])) { }
</code>```

seems to trigger regardless of whether or not I have uploaded a file in the input or not.

```<code><label>
    <p>Profile Picture:</p>
    <input type="file" name="image" value="" />
</label>
</code>```

My last question was marked as a duplicate of this answer Check whether file is uploaded however

```<code>if (!file_exists($_FILE['image'])) { }
</code>```

didn't work either it is still showing truthy even when an image is uploaded. So not the answer I need.

答:
To check if there is a file uploaded is you need to check the size of the file.

Then to check if its an image or not is you need to use the getimagesize() function. See my script below:

HTML:

```<code><form action="index.php?act=s" method="post" enctype="multipart/form-data">
<input type="file" name="image" value=""/>
<input type="submit">
</form>
</code>```

PHP:

```<code><?php
if(isset($_GET['act'])){
    // Check if there is a file uploaded
    if($_FILES["image"]["size"]>0){
        echo "There is a file uploaded<br>";
        // Check if its an image
            $check_if_image = getimagesize($_FILES["image"]["tmp_name"]);
            if($check_if_image !== false) {
                echo "Image = " . $check_if_image["mime"] . ".";
            } else {
                echo "Not an image";
            }
    }
    else{
        echo "There is NO file uploaded<br>";
    }
}
?>
</code>```

Title: How to check if $_POST[image] is set

Body:
Re asking how to check if $_POST[FILE] isset
I have a file input and if I submit my form without an image I want something to happen if I uploaded a file in the input I want something different to happen.

if (!isset($_POST[image])) { }

seems to trigger regardless of whether or not I have uploaded a file in the input or not.

Profile Picture:

    <input type="file" name="image" value="" />

My last question was marked as a duplicate of this answer Check whether file is uploaded however

if (!file_exists($_FILE['image'])) { }

didn't work either it is still showing truthy even when an image is uploaded. So not the answer I need.

Body:
To check if there is a file uploaded is you need to check the size of the file.

Then to check if its an image or not is you need to use the getimagesize() function. See my script below:

HTML:

<form action="index.php?act=s" method="post" enctype="multipart/form-data">
<input type="file" name="image" value=""/>
<input type="submit">
</form>

PHP:

<?php
if(isset($_GET['act'])){
    // Check if there is a file uploaded
    if($_FILES["image"]["size"]>0){
        echo "There is a file uploaded<br>";
        // Check if its an image
            $check_if_image = getimagesize($_FILES["image"]["tmp_name"]);
            if($check_if_image !== false) {
                echo "Image = " . $check_if_image["mime"] . ".";
            } else {
                echo "Not an image";
            }
    }
    else{
        echo "There is NO file uploaded<br>";
    }
}
?>

ContentLicense: CC BY-SA 4.0


问:
Enable Run button for Service add-on in Kodi

I am contributing to the Kodi PartyMode AutoStart add-on.

I would like to add the option to manually trigger the plugin using Kodi's existing "Run" button for add-ons (which is disabled at the moment), so that users can test their settings without having to reboot the device.

I assume that the button is disabled because the add-on is a Service add-on, which are designed to run (per Kodi documentation) at startup or upon login.

My question: is there something I can set in the .py or settings file to enable this Run button, and trigger the plugin, or would I need to change the entire add-on type?

答:
You can define multiple extension points in your addon.xml so your service can also have a script extension point and act on that. So you would have both these.

```<code><extension point="xbmc.python.script" library="defaultscript.py">
    <provides>executable</provides>
</extension>
</code>```

See:
https://github.com/trakt/script.trakt/blob/master/addon.xml#L10-L13

Body:
You can define multiple extension points in your addon.xml so your service can also have a script extension point and act on that. So you would have both these.

<extension point="xbmc.python.script" library="defaultscript.py">
    <provides>executable</provides>
</extension>

See:
https://github.com/trakt/script.trakt/blob/master/addon.xml#L10-L13


问:
React-Native: Google maps only showing the logo, beige background and the makter
I am trying to get Google Maps to work in React-Native, but I'm only getting this far:

What I have so far

My code:

```<code>    import React, { Component } from 'react';
import { AppRegistry, StyleSheet, Text, View } from 'react-native';
import MapView from 'react-native-maps';

class Additional extends Component {
render() {
  return (
<View style={styles.container}>

    <MapView style={styles.map}
        region={{
            latitude: 4.895168,
            longitude: 52.370216,
            latitudeDelta: 0.1,
            longitudeDelta: 0.1,
        }}
    >

    <MapView.Marker
        coordinate={{
            latitude: 4.895168,
            longitude: 52.370216
            }}
            title={"titel"}
            description={"descriptie"}
            />
    </MapView>
</View>
  );
      }
}

Additional.navigationOptions = {
  title: 'Second Screen Title',
};

const styles = StyleSheet.create({
  container: {
        flex: 1,
        position: 'absolute',
        top: 0,
        left: 0,
        bottom: 0,
        right: 0,
        justifyContent: 'flex-end',
        alignItems: 'center',
  },
  map: {
      position: 'absolute',
      top: 0,
      left: 0,
      bottom: 0,
      right: 0
  },
});

export default Additional;
</code>```

I have followed this tutorial for the api key and adding google maps:
Tutorial

This is my second page, the other one page is using a weather-api.
But according to the live-debugger nothing is conflicting.

Does anyone know what's going on? Thanks!

Edit/additional information:
I have activated my API on the google-api webpage.

Edit/additional information:
My androidmanifest

答:
I was missing a bunch of permissions:</p>

```<code><permission      android:name="com.shop.shoppinglist.permission.MAPS_RECEIVE"
 android:protectionLevel="signature"/>
<uses-permission android:name="com.shop.addtask.permission.MAPS_RECEIVE"/>
<uses-permission
 android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
</code>```

Body:
I am trying to get Google Maps to work in React-Native, but I'm only getting this far:

What I have so far

My code:

    import React, { Component } from 'react';
import { AppRegistry, StyleSheet, Text, View } from 'react-native';
import MapView from 'react-native-maps';

class Additional extends Component {
render() {
  return (
<View style={styles.container}>

    <MapView style={styles.map}
        region={{
            latitude: 4.895168,
            longitude: 52.370216,
            latitudeDelta: 0.1,
            longitudeDelta: 0.1,
        }}
    >

    <MapView.Marker
        coordinate={{
            latitude: 4.895168,
            longitude: 52.370216
            }}
            title={"titel"}
            description={"descriptie"}
            />
    </MapView>
</View>
  );
      }
}

Additional.navigationOptions = {
  title: 'Second Screen Title',
};

const styles = StyleSheet.create({
  container: {
        flex: 1,
        position: 'absolute',
        top: 0,
        left: 0,
        bottom: 0,
        right: 0,
        justifyContent: 'flex-end',
        alignItems: 'center',
  },
  map: {
      position: 'absolute',
      top: 0,
      left: 0,
      bottom: 0,
      right: 0
  },
});

export default Additional;

I have followed this tutorial for the api key and adding google maps:
Tutorial

This is my second page, the other one page is using a weather-api.
But according to the live-debugger nothing is conflicting.

Does anyone know what's going on? Thanks!

Edit/additional information:
I have activated my API on the google-api webpage.

Edit/additional information:
My androidmanifest

Body:
I was missing a bunch of permissions:

<permission      android:name="com.shop.shoppinglist.permission.MAPS_RECEIVE"
 android:protectionLevel="signature"/>
<uses-permission android:name="com.shop.addtask.permission.MAPS_RECEIVE"/>
<uses-permission
 android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>


问:
Duplicate symbol issues
During a refactor of an iOS project, I ran into this bear of a bug. During the linking phase, I get this message:

ld: duplicate symbol _OBJC_IVAR_$_TinCanViewController.currentViewController in /path/to/TinCanViewController-E98A666B7AF2673A.o and /path/to/TinCanViewController-E98A666B7AF2673A.o

As far as I can tell, it looks like it claims TinCanViewController-E98A666B7AF2673A.o is declaring the specified symbol twice; both paths are pointing to the exact same .o file. I ran nm on that specific file, and it only included that symbol once:

00008150 S _OBJC_IVAR_$_TinCanViewController.currentViewController

I ran nm on all the other .o files in the directory to see if they were somehow declaring this symbol, too, but they're not. This happens to any member I add to the TinCanViewController class - it's not specific to currentViewController.

I feel like I must be somehow linking against the class twice somehow, but I've pretty assiduously gone through and checked all references to this class. In the refactored version, there are basically none. The AppDelegate includes it, but right now it's basically just a passthrough class that loads another ViewController at the start. No other classes in the project include it.

Any suggestions on what might be causing this or how I might debug it better?

答:
This problem solve here when I deleted (using Xcode) all files .m and .h from Class folder then I cleaned Project (Command + Shift + K) and Builded again. So I drag the files from Finder to Class Folder in Xcode again. Finally, I cleaned and build my Project again...

Good Luck !!!

Title: Duplicate symbol issues


问:
How to access static array list in another java package
I am working in JAVA Maven project. I have one class

```<code>package com.fist.program;

import java.util.ArrayList;
import java.util.Arrays;

public class BundleVersionManagement {

    public static ArrayList<String> BundleVer = new ArrayList<String>();
    public static ArrayList<String> BundleName= new ArrayList<String>();

    public BundleVersionManagement(){

    }

    public void SetBundleVersion(String BundleVersion) {
        if(BundleVer.contains(BundleVersion)==false){
            BundleVer.add(BundleVersion);
        }
    }

    public void SetBundleName(String Bndnm) {
        if(BundleName.contains(Bndnm)==false){
            BundleName.add(Bndnm);
        }
    }

    public void  DisplayArr(){
        System.out.println("common program ::: BundleVersionManagement::: bundle versions :");
        System.out.println(Arrays.toString(BundleVer.toArray()));
        System.out.println("common program ::: BundleVersionManagement::: bundle name :");
        System.out.println(Arrays.toString(BundleName.toArray()));
    }
}
</code>```

Above class it's working fine.
I want to use above static arraylist in another package class.

```<code>package com.first.secondProgram;

import com.fist.program.BundleVersionManagement;

public abstract class Handler<T> {

    static{

        BundleVersionManagement hbm = new BundleVersionManagement();
            NameFromxml= hbm.BundleName;
            System.out.println("common handler ::: Print array list:");
            hbm.DisplayArr();
    }
}
</code>```

Problem is that class BundleVersionManagement add arraylist successfully as per log :

```<code>[1.123, 2.057, 3.018, 4.012, 5.018, 6.011, 7.119]
</code>```

But when I print same arraylist in Hanlder class of another package, it's display blank :

```<code>common handler ::: Print array list: common util :::
BundleVersionManagement::: bundle versions : [] common util :::
BundleVersionManagement::: bundle name : []
</code>```

Can you please help me how to access array list string another package.

答:
There is nothing wrong with your access of arraylist as such - in the second case you just haven't yet added any items into it.

A static block will run before any instance methods are run, so you probably are adding your items later than that. If you call the DisplayArr method after you've added your items, it will work.

Body:
I am working in JAVA Maven project. I have one class

package com.fist.program;

import java.util.ArrayList;
import java.util.Arrays;

public class BundleVersionManagement {

    public static ArrayList<String> BundleVer = new ArrayList<String>();
    public static ArrayList<String> BundleName= new ArrayList<String>();

    public BundleVersionManagement(){

    }

    public void SetBundleVersion(String BundleVersion) {
        if(BundleVer.contains(BundleVersion)==false){
            BundleVer.add(BundleVersion);
        }
    }

    public void SetBundleName(String Bndnm) {
        if(BundleName.contains(Bndnm)==false){
            BundleName.add(Bndnm);
        }
    }

    public void  DisplayArr(){
        System.out.println("common program ::: BundleVersionManagement::: bundle versions :");
        System.out.println(Arrays.toString(BundleVer.toArray()));
        System.out.println("common program ::: BundleVersionManagement::: bundle name :");
        System.out.println(Arrays.toString(BundleName.toArray()));
    }
}

Above class it's working fine.
I want to use above static arraylist in another package class.

package com.first.secondProgram;

import com.fist.program.BundleVersionManagement;

public abstract class Handler<T> {

    static{

        BundleVersionManagement hbm = new BundleVersionManagement();
            NameFromxml= hbm.BundleName;
            System.out.println("common handler ::: Print array list:");
            hbm.DisplayArr();
    }
}

Problem is that class BundleVersionManagement add arraylist successfully as per log :

[1.123, 2.057, 3.018, 4.012, 5.018, 6.011, 7.119]

But when I print same arraylist in Hanlder class of another package, it's display blank :

common handler ::: Print array list: common util :::
BundleVersionManagement::: bundle versions : [] common util :::
BundleVersionManagement::: bundle name : []

Can you please help me how to access array list string another package.


问:
Scheduler not queuing jobs
I'm trying to test out Airflow on Kubernetes. The Scheduler, Worker, Queue, and Webserver are all on different deployments and I am using a Celery Executor to run my tasks.

Everything is working fine except for the fact that the Scheduler is not able to queue up jobs. Airflow is able to run my tasks fine when I manually execute it from the Web UI or CLI but I am trying to test the scheduler to make it work.

My configuration is almost the same as it is on a single server:

```<code>sql_alchemy_conn = postgresql+psycopg2://username:password@localhost/db
broker_url = amqp://user:password@$RABBITMQ_SERVICE_HOST:5672/vhost
celery_result_backend = amqp://user:password@$RABBITMQ_SERVICE_HOST:5672/vhost
</code>```

I believe that with these configurations, I should be able to make it run but for some reason, only the workers are able to see the DAGs and their state, but not the scheduler, even though the scheduler is able to log their heartbeats just fine. Is there anything else I should debug or look at?

答:
First, you use postgres as database for airflow, don't you? Do you deploy a pod and service for postgres? If it is the case, do you verify that in your config file you have : </p>

```<code>sql_alchemy_conn = postgresql+psycopg2://username:password@serviceNamePostgres/db
</code>```

<p>You can use this github. I used it 3 weeks ago for a first test and it worked pretty well.
The entrypoint is useful to verify that rabbitMq and Postgres are well configured. </p>

Title: Scheduler not queuing jobs

Body:
I'm trying to test out Airflow on Kubernetes. The Scheduler, Worker, Queue, and Webserver are all on different deployments and I am using a Celery Executor to run my tasks.

Everything is working fine except for the fact that the Scheduler is not able to queue up jobs. Airflow is able to run my tasks fine when I manually execute it from the Web UI or CLI but I am trying to test the scheduler to make it work.

My configuration is almost the same as it is on a single server:

sql_alchemy_conn = postgresql+psycopg2://username:password@localhost/db
broker_url = amqp://user:password@$RABBITMQ_SERVICE_HOST:5672/vhost
celery_result_backend = amqp://user:password@$RABBITMQ_SERVICE_HOST:5672/vhost

I believe that with these configurations, I should be able to make it run but for some reason, only the workers are able to see the DAGs and their state, but not the scheduler, even though the scheduler is able to log their heartbeats just fine. Is there anything else I should debug or look at?

Body:
First, you use postgres as database for airflow, don't you? Do you deploy a pod and service for postgres? If it is the case, do you verify that in your config file you have :

sql_alchemy_conn = postgresql+psycopg2://username:password@serviceNamePostgres/db

You can use this github. I used it 3 weeks ago for a first test and it worked pretty well.
The entrypoint is useful to verify that rabbitMq and Postgres are well configured.


问:
Passing data from html to python using ajax
Greeting everyone, I'm trying to pass json data from html to python, Im getting the data but the format is incorrect,

Below is my code

HTML

```<code><select class="js-example-basic-multiple" id="Status" name="Status" multiple="multiple" style="display:inline-block;">
    {% comment %} <option value="ALL" checked="1">ALL</option> {% endcomment %}
    <option value="new">New</option>
    <option value="bid">Bid</option>
    <option value="inprogress">In Progress</option>
    <option value="onhold">On Hold</option>
    <option value="completed">Completed</option>
    <option value="archived">Archived</option>
</select>
</code>```

javascript

```<code>$('#Status').change(function(){
    var selected_status = $('#Status').select2('val');
    var status_text = JSON.stringify(selected_status);
    $.ajax({
            url : '/dashboard/marketing/', // the endpoint
            type : 'GET', // http method
            data : { 'stat' : status_text,
                    'csrfmiddlewaretoken': '{{csrf_token}}'
                }, // data sent with the post request
            // handle a successful response
            success : function(data) {
            },
    });
});
</code>```

view.py

```<code>stat = request.GET.getlist('stat')
    print(stat)
    for selected_status in stat:
        get_project_on_status = Project.objects.all().filter(project_stage=selected_status)
        for project in get_project_on_status:
            project_on_status_list.append(project)
</code>```

The result I wanted is :

```<code>["new","bid","inprogress","onhold","completed"]
</code>```

but what I'm getting is :

```<code>['["new","bid","inprogress","onhold","completed"]']
</code>```

How can i remove the extra bracket? thanks!

答:
I don't know much about python, but you need to ensure that your values aren't stringified using JSON.stringify.

```<code>var status_text = selected_status; // Remove JSON.stringify from here

$.ajax({
  url : '/dashboard/marketing/', // the endpoint
  type : 'GET', // http method
  data : { 'stat' : status_text,
           'csrfmiddlewaretoken': '{{csrf_token}}'
         }, // data sent with the post request
  // handle a successful response
  success : function(data) {
  },
...
</code>```

Also, jQuery automatically handles encoding of the data. So, the actual parameters name which is submitted to the server will be stat[].

I think you will need to change the name of parameter to stat[] while retrieving the values on python side. Maybe, in this line:

```<code>stat = request.GET.getlist('stat[]')
</code>```

For more details about how parameters are being sent, observe this fiddle.

Body:
Greeting everyone, I'm trying to pass json data from html to python, Im getting the data but the format is incorrect,

Below is my code

HTML

<select class="js-example-basic-multiple" id="Status" name="Status" multiple="multiple" style="display:inline-block;">
    {% comment %} <option value="ALL" checked="1">ALL</option> {% endcomment %}
    <option value="new">New</option>
    <option value="bid">Bid</option>
    <option value="inprogress">In Progress</option>
    <option value="onhold">On Hold</option>
    <option value="completed">Completed</option>
    <option value="archived">Archived</option>
</select>

javascript

$('#Status').change(function(){
    var selected_status = $('#Status').select2('val');
    var status_text = JSON.stringify(selected_status);
    $.ajax({
            url : '/dashboard/marketing/', // the endpoint
            type : 'GET', // http method
            data : { 'stat' : status_text,
                    'csrfmiddlewaretoken': '{{csrf_token}}'
                }, // data sent with the post request
            // handle a successful response
            success : function(data) {
            },
    });
});

view.py

stat = request.GET.getlist('stat')
    print(stat)
    for selected_status in stat:
        get_project_on_status = Project.objects.all().filter(project_stage=selected_status)
        for project in get_project_on_status:
            project_on_status_list.append(project)

The result I wanted is :

["new","bid","inprogress","onhold","completed"]

but what I'm getting is :

['["new","bid","inprogress","onhold","completed"]']

How can i remove the extra bracket? thanks!

Body:
I don't know much about python, but you need to ensure that your values aren't stringified using JSON.stringify.

var status_text = selected_status; // Remove JSON.stringify from here

$.ajax({
  url : '/dashboard/marketing/', // the endpoint
  type : 'GET', // http method
  data : { 'stat' : status_text,
           'csrfmiddlewaretoken': '{{csrf_token}}'
         }, // data sent with the post request
  // handle a successful response
  success : function(data) {
  },
...

Also, jQuery automatically handles encoding of the data. So, the actual parameters name which is submitted to the server will be stat[].

I think you will need to change the name of parameter to stat[] while retrieving the values on python side. Maybe, in this line:

stat = request.GET.getlist('stat[]')

For more details about how parameters are being sent, observe this fiddle.


问:
Why are HTML5 and XHTML 2 separate standards?
Is there a reason why these two standards are being developed separately? They seem to be solving the same problem but what are the differences and, if they are to remain separate, what roles are they expected to take in web development in the future?</p>

答:
XHTML2 is dead.

Have a look at the first chapter of HTML5 FOR WEB DESIGNERS by Jeremy Keith which explains superbly the differences in a summarized way.

OwnerDisplayName: Tim Wardle

LastEditorDisplayName: hsivonen


问:
How to make nested async requests in jquery?
inside main.js:

```<code>$.when(
    $.get('foo/bar.html'),
    $.get('lorem/ipsum.html')
).done(function(data1, data2){
     someCode();
});
</code>```

inside lorem/ipsum.html:

```<code>$.when(
    $.get('otherStuff.html'),
    $.get('example.html')
).done(function(data1, data2){
     moreCode();
});
</code>```

How can I make someCode() run after moreCode()?

答:
I think your code work just fine.

You can try to make invalid url https://XXjsonplaceholder.typicode.com and someCode will not be hit

var url1 = "https://jsonplaceholder.typicode.com/users/1";
var url2 = "https://jsonplaceholder.typicode.com/users/2";

/*
$.get(url1).done(function (result1) {
 console.log(result1);
});
*/

$.when(
  $.get(url1),
  $.get(url2)
).then(function(result1, result2) {
  console.log("result1");
  console.log(result1[0]);

  console.log("result2");
  console.log(result2[0]);

  someCode();
});

function someCode() {
  console.log("someCode here");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

Body:
inside main.js:

$.when(
    $.get('foo/bar.html'),
    $.get('lorem/ipsum.html')
).done(function(data1, data2){
     someCode();
});

inside lorem/ipsum.html:

$.when(
    $.get('otherStuff.html'),
    $.get('example.html')
).done(function(data1, data2){
     moreCode();
});

How can I make someCode() run after moreCode()?

Body:
I think your code work just fine.

You can try to make invalid url https://XXjsonplaceholder.typicode.com and someCode will not be hit

var url1 = "https://jsonplaceholder.typicode.com/users/1";
var url2 = "https://jsonplaceholder.typicode.com/users/2";

/*
$.get(url1).done(function (result1) {
 console.log(result1);
});
*/

$.when(
  $.get(url1),
  $.get(url2)
).then(function(result1, result2) {
  console.log("result1");
  console.log(result1[0]);

  console.log("result2");
  console.log(result2[0]);

  someCode();
});

function someCode() {
  console.log("someCode here");
}

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


问:
How i can get value from Binded Textbox in ListView?? (C# UWP)
```<code>string test = ((My_ListItem)lvList.Items[0]).m_strValue;
</code>```

I tried to use that code, but I couldn't get Textbox user-inputted value, just outputs a default value when I added listview item. how can I get inputted value in binded Textbox in ListView?

This is my code:

```<code>public class My_ListItem
{
    public string m_strItemName { get; set; }
    public string m_strValue { get; set; }

    public My_ListItem(string IN_strItemName, string IN_strValue)
    {
        m_strItemName = IN_strItemName;
        m_strValue = IN_strValue;
    }
}
</code>```

XML Codes are here

```<code><ListView x:Name="lvList" HorizontalAlignment="Left" Height="125"
 Margin="30,243,0,0" VerticalAlignment="Top" Width="573"
 AutomationProperties.SizeOfSet="-3">
   <ListView.ItemTemplate>
     <DataTemplate>
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="{Binding m_strItemName}" Padding="10"/>
            <TextBox Text="{Binding m_strValue}" Width="300" />
        </StackPanel>
     </DataTemplate>
   </ListView.ItemTemplate>
</ListView>
</code>```

答: You need TwoWay Binding for the TextBox <TextBox Text="{Binding m_strValue, Mode=TwoWay}" Width="300" />

Body:
string test = ((My_ListItem)lvList.Items[0]).m_strValue;

I tried to use that code, but I couldn't get Textbox user-inputted value, just outputs a default value when I added listview item. how can I get inputted value in binded Textbox in ListView?

This is my code:

public class My_ListItem
{
    public string m_strItemName { get; set; }
    public string m_strValue { get; set; }

    public My_ListItem(string IN_strItemName, string IN_strValue)
    {
        m_strItemName = IN_strItemName;
        m_strValue = IN_strValue;
    }
}

XML Codes are here

<ListView x:Name="lvList" HorizontalAlignment="Left" Height="125"
 Margin="30,243,0,0" VerticalAlignment="Top" Width="573"
 AutomationProperties.SizeOfSet="-3">
   <ListView.ItemTemplate>
     <DataTemplate>
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="{Binding m_strItemName}" Padding="10"/>
            <TextBox Text="{Binding m_strValue}" Width="300" />
        </StackPanel>
     </DataTemplate>
   </ListView.ItemTemplate>
</ListView>


问:
Remote JMX connection
I'm trying to open a JMX connection to java application running on a remote machine.

The application JVM is configured with the following options:

com.sun.management.jmxremote

com.sun.management.jmxremote.port=1088

com.sun.management.jmxremote.authenticate=false

com.sun.management.jmxremote.ssl=false

I'm able to connect using localhost:1088 using jconsole or jvisualvm.
But I'm not able to connect using xxx.xxx.xxx.xxx:1088 from a remote machine.

There is no firewall between the servers, or on the OS. But to eliminate this possibility I telnet xxx.xxx.xxx.xxx 1088 and I think it connects, as the console screen turns blank.

Both servers are Windows Server 2008 x64. Tried with 64-bit JVM and 32-bit, neither work.

答:
To enable JMX remote, pass below VM parameters along with JAVA Command.</p>

```<code>    -Dcom.sun.management.jmxremote
    -Dcom.sun.management.jmxremote.port=453
    -Dcom.sun.management.jmxremote.authenticate=false
    -Dcom.sun.management.jmxremote.ssl=false
    -Djava.rmi.server.hostname=myDomain.in
</code>```

Title: Remote JMX connection

Body:
To enable JMX remote, pass below VM parameters along with JAVA Command.

    -Dcom.sun.management.jmxremote
    -Dcom.sun.management.jmxremote.port=453
    -Dcom.sun.management.jmxremote.authenticate=false
    -Dcom.sun.management.jmxremote.ssl=false
    -Djava.rmi.server.hostname=myDomain.in


问:
What are mapping files for building against UWP / Centennial projects and how do I make them?
I'm trying to plow through some basic automation for building some UWP / Centennial projects, and  I'm at the point where I need to take a test-signed AppX, unpack and real-sign it, then re-pack and real-sign the AppX itself. For example,

makeappx unpack /p "%CD%\UpgradeTestAppX_1.0.3.0_x64.appx" /d "%CD%\unpacked" /o /l

That works fine, as does running the signing tools to sign the contents inside "%CD%\unpacked"

The issue I'm running into is a documentation gap.

/f Specifies the mapping file.

/m    Specifies the path to an input app manifest which will be used as the basis for generating the output app package or resource package's manifest. When you use this option, you must also use /f and include a [ResourceMetadata] section in the mapping file to specify the resource dimensions to be included in the generated manifest.

I've seen this "mapping file" mentioned several times, but I can't locate what precisely they mean. The term is too generic to me to infer what it is or how to make one. The best I can figure is that it might be referring to an

...App package block map (AppxBlockMap.xml)...

But then there's this:

<mapping file> File name that specifies the package source an destination

But that's not what seems to match to this other type of file that happens to have the word map in it, or at least a <mapping file> seems more generic to me than App package block map.

Is the <mapping file> for MakeAppX's current documentation the same as an App package block map?

Where can I reference an example or guide of this mapping file that helps me understand what all it can be leveraged for? If the mapping file is the AppxBlockMap.xml file, then I just want to know what all can be done with it for its intended purpose.

答:
The official doc describes a mapping file here.
If your makeappx command only use /f, you don't need to specify resource file, then your mapping file can be a text which is wrote like the following:

```<code>[Files]
"C:\MyApp\StartPage.html"               "default.html"
"C:\Program Files (x86)\example.txt"    "misc\example.txt"
"\\MyServer\path\icon.png"              "icon.png"
"my app files\readme.txt"               "my app files\readme.txt"
"CustomManifest.xml"                    "AppxManifest.xml"
</code>```

If you used /m command, then you must use /f and include a [ResourceMetadata] section like the following:

```<code>[ResourceMetadata]
"ResourceDimensions"                    "language-en-us"
"ResourceId"                            "English"

[Files]
"images\en-us\logo.png"                 "en-us\logo.png"
"en-us.pri"                             "resources.pri"
</code>```

Body:
The official doc describes a mapping file here.
If your makeappx command only use /f, you don't need to specify resource file, then your mapping file can be a text which is wrote like the following:

[Files]
"C:\MyApp\StartPage.html"               "default.html"
"C:\Program Files (x86)\example.txt"    "misc\example.txt"
"\\MyServer\path\icon.png"              "icon.png"
"my app files\readme.txt"               "my app files\readme.txt"
"CustomManifest.xml"                    "AppxManifest.xml"

If you used /m command, then you must use /f and include a [ResourceMetadata] section like the following:

[ResourceMetadata]
"ResourceDimensions"                    "language-en-us"
"ResourceId"                            "English"

[Files]
"images\en-us\logo.png"                 "en-us\logo.png"
"en-us.pri"                             "resources.pri"


问:
DownloadManager: download a file to cache partition
I am using the public api of class DownloadManager, I am able to download files to sdcard, so-called external storage. However, when I tried to download a file to other places, like /cache partition, it throw a security exception which says "Destination must be on external storage".

Does anyone know how to bypass this limitation and write downloaded file to /cache partition ?

Thanks a lot.

答:
Actually I found a way to download files to /cache partition.
In the DownloadManager class, there is an api
setDestinationUri(), call this function with parameter "null", the android would download files to /cache partition. Moreover, if the parameter is not null, the uri must start with "/mnt/sdcard/..." otherwise an exception would be thrown.</p>