问:
Access - conditional statement
Coming from the excel world, how to I create a conditional statement to populate one field based on the value on the other, something that in excel would look like:

```<code>=if(A1="A","Yes","No")
</code>```

Thank you

EDIT:

Ok, I've done the following:

```<code>=IIF([FundingStream]="A", "N/A", "Student Finance")
</code>```

But I've got an error:
Invalid SQL syntax - cannot use multiple columns in a column-level CHECK constraint

I'm entering this expression in the Validation Rule of the properties of a Field that N/A or Student Finance should appear.

EDIT 2:

I've done as suggested below. When I type in the FundingStream, it does not change the LoanCRN field at all. See the screenshot below:

答:
Although they can serve some of the same purposes, relational databases system require a different paradigm.  The simple idea of setting one column value based on another is actually rather complex when compared to a spreadsheet.  You will only face continued frustration if you try to convert your spreadsheet literally.

The following statement in a Validation Rule is not an assignment, rather it is a Boolean comparison operation:  It returns true or false.  It constrains the values which can be saved to the database, but it does not change the column values.

```<code>[Field1] = Iif([FundingStream]="A", "N/A", "Student Finance")
</code>```

As a further side note, some languages have two different symbols for assignment and comparison, for instance := for assignment and == for equality comparison.  But many languages, like VBA, interpret a single = based on context.  If you understand the difference, the context usually becomes apparent what the equal sign means in a particular case.

To change the values of one field based on another requires other techniques.  The flexibility of any code or macro driven environment, like Access, provide various ways of doing this that can't all be outlined here.  However, the two most obvious that come to mind are:

VBA code in a form module

Probably the most direct way of doing this is in the AfterUpdate event:

```<code>Private Sub FundingStream_AfterUpdate()
    If Me.FundingStream = "A" Then
        Me.LoanCRN = "N/A"
    Else
        Me.LoanCRN = "Student Finance"
    End If
End Sub
</code>```

This assumes that you at least have two controls on your form:  FundingStream and LoanCRN.  This will do what you want... initially.  However, now you would need to consider whether the user can also update LoanCRN directly.  If they should never update LoanCRN directly, you could either 1) set the control property Locked = True, or 2) hide the control on the form so the user can't even see it, or 3) eliminate the actual control and just reference the record source column property directly, like Me![LoanCRN].  More details for any of those techniques is beyond this question.

But that's not all!  You need to consider appropriate default values.  What happens if the user never actually changes the FundingStream control?  Then your code would never run and so LoanCRN might not be set properly. In the end, it is likely that you will need further code elsewhere on the form, e.g. in Form_AfterUpdate(), Form_Current, etc.

The benefit to this approach is that you have all the flexibility of the data entry form to shape exactly how you want the data to flow.  The difficulty is in avoiding missing and conflicting behavior on the form.  This technique ultimately requires appropriate use of table and column constraints (i.e. Validation Rules and indexes) and familiarity with form and control events.

This also only works for the particular form.  If you have other forms or VBA code that change the FundingStream value, you would also need to add the same code in all those locations to ensure LoanCRN value is always valid.

Before Change Data Macro

Define a Before Change macro on the table to update values.  Use If and SetField macro actions to set LoanCRM based on FundingStream.

From a naive perspective, this is actually the most direct, easy way to do it.  The Data Macro is called automatically every time a record is saved, no matter if it is updated on a form or in VBA code.

This also has many restrictions and does not allow flexibility of adding many dynamic conditions, especially conditions present at data entry.  If your macro logic is not robust, it can cause unnecessary errors that prevent the entire set of data from being saved.

Title: Access - conditional statement

Body:
Coming from the excel world, how to I create a conditional statement to populate one field based on the value on the other, something that in excel would look like:

=if(A1="A","Yes","No")

Thank you

EDIT:

Ok, I've done the following:

=IIF([FundingStream]="A", "N/A", "Student Finance")

But I've got an error:
Invalid SQL syntax - cannot use multiple columns in a column-level CHECK constraint

I'm entering this expression in the Validation Rule of the properties of a Field that N/A or Student Finance should appear.

EDIT 2:

I've done as suggested below. When I type in the FundingStream, it does not change the LoanCRN field at all. See the screenshot below:

Body:
Although they can serve some of the same purposes, relational databases system require a different paradigm.  The simple idea of setting one column value based on another is actually rather complex when compared to a spreadsheet.  You will only face continued frustration if you try to convert your spreadsheet literally.

The following statement in a Validation Rule is not an assignment, rather it is a Boolean comparison operation:  It returns true or false.  It constrains the values which can be saved to the database, but it does not change the column values.

[Field1] = Iif([FundingStream]="A", "N/A", "Student Finance")

As a further side note, some languages have two different symbols for assignment and comparison, for instance := for assignment and == for equality comparison.  But many languages, like VBA, interpret a single = based on context.  If you understand the difference, the context usually becomes apparent what the equal sign means in a particular case.

To change the values of one field based on another requires other techniques.  The flexibility of any code or macro driven environment, like Access, provide various ways of doing this that can't all be outlined here.  However, the two most obvious that come to mind are:

VBA code in a form module

Probably the most direct way of doing this is in the AfterUpdate event:

Private Sub FundingStream_AfterUpdate()
    If Me.FundingStream = "A" Then
        Me.LoanCRN = "N/A"
    Else
        Me.LoanCRN = "Student Finance"
    End If
End Sub

This assumes that you at least have two controls on your form:  FundingStream and LoanCRN.  This will do what you want... initially.  However, now you would need to consider whether the user can also update LoanCRN directly.  If they should never update LoanCRN directly, you could either 1) set the control property Locked = True, or 2) hide the control on the form so the user can't even see it, or 3) eliminate the actual control and just reference the record source column property directly, like Me![LoanCRN].  More details for any of those techniques is beyond this question.

But that's not all!  You need to consider appropriate default values.  What happens if the user never actually changes the FundingStream control?  Then your code would never run and so LoanCRN might not be set properly. In the end, it is likely that you will need further code elsewhere on the form, e.g. in Form_AfterUpdate(), Form_Current, etc.

The benefit to this approach is that you have all the flexibility of the data entry form to shape exactly how you want the data to flow.  The difficulty is in avoiding missing and conflicting behavior on the form.  This technique ultimately requires appropriate use of table and column constraints (i.e. Validation Rules and indexes) and familiarity with form and control events.

This also only works for the particular form.  If you have other forms or VBA code that change the FundingStream value, you would also need to add the same code in all those locations to ensure LoanCRN value is always valid.

Before Change Data Macro

Define a Before Change macro on the table to update values.  Use If and SetField macro actions to set LoanCRM based on FundingStream.

From a naive perspective, this is actually the most direct, easy way to do it.  The Data Macro is called automatically every time a record is saved, no matter if it is updated on a form or in VBA code.

This also has many restrictions and does not allow flexibility of adding many dynamic conditions, especially conditions present at data entry.  If your macro logic is not robust, it can cause unnecessary errors that prevent the entire set of data from being saved.


来源: stackexchange

问:
Get/set variable inside if statement
I have a small example to define and assign to arr array.

```<code>var arr;

if (arr = [1]) { // arr is an array here, it contains 1 element
    console.log(arr.length); // 1
}
</code>```

Then, I want to get length of the array

```<code>var arr;

// arr is an array here, but why cannot I assign to length property?
if (arr = [1] && arr.length) {
    console.log(arr.length);
}
</code>```

Uncaught TypeError: Cannot read property 'length' of undefined

答:
your if should be like this if ((arr = [1]) && arr.length)

you need to give high precedence to array assignment part . to assign first then compare .

precedence is nothing but . which part code execute first based on operator precedence  so in your code  && is higher precedence than assignment operator  = so while arr not assigned so it is undefined

var arr;

// arr is an array here, but why cannot I assign to length property?
if ((arr = [1]) && arr.length) {
  console.log(arr.length);
}```

ContentLicense: CC BY-SA 3.0

Title: Get/set variable inside if statement

Body:
I have a small example to define and assign to arr array.

var arr;

if (arr = [1]) { // arr is an array here, it contains 1 element
    console.log(arr.length); // 1
}

Then, I want to get length of the array

var arr;

// arr is an array here, but why cannot I assign to length property?
if (arr = [1] && arr.length) {
    console.log(arr.length);
}

Uncaught TypeError: Cannot read property 'length' of undefined

ContentLicense: CC BY-SA 4.0


问:
What is Azul "Zing"?
What is Azul "Zing" platform?

Visiting Azul site (link) turned into a marketing horror - and after wading through every little bit of it, I still don't have a clue.

Does anyone have any experience with it? What are the requirement for your application to be "Zing"-ed? (Zing-able?) If, for example, I have an application that loads an object graph into memory and constantly traverses huge chunks of it (so most of it is "warm" - can't store parts in slow data-stores) - can Azul help me? (I already know Terracotta BigMemory can't...)

I want to clarify - I'm looking for feedback from someone who actually "zingified" their product and put it on the Azul VM successfully (or saw that it doesn't work).

Ran.

[Edit 1 - added page link]
[Edit 2- Experience wanted]

答:
Remember what Azul used to do: make customized multicore Java appliances.  An Azul machine might have 60 or 100 cores and there was all sorts of cleverness to take advantage of the parallelization (the one that impressed me was the optimistic locking: a thread that was supposed to obtain a lock just assumed that it had the lock and went forward and if it turned out later that, no, it was supposed to have blocked, it somehow unwound all its changes and went back and waited).

The problem is, of course, that custom hardware is a graveyard.  Azul had spent all this time making software for hardware no one would buy.  So, as a corporation they imitated their own product: they backed up, unwound their changes, and ported all their clevernesses (the optimistic locking, the hypervisor, other stuff) from custom hardware to commodity multicore machines so instead of paying $100,000 for an 80-core machine, you can spent $20,000 for 10 eight-core machines in a cloud*.

[ * All numbers surgically extracted from my anatomy. ]

Is it a good idea? Does it work?  I don't know, but I hope so.  I met all the Azul guys at the 2003 JavaOne and they really impressed me.

ContentLicense: CC BY-SA 2.5

Title: What is Azul "Zing"?


答:
```<code>var arr;

// arr is an array here, but why cannot I assign to length property?
if (arr = [1] && arr.length) {
    console.log(arr.length);
}
</code>```

fails due to operator precedence. && has higher precedence than the assignment =, so it is evaluated first.

[1] && arr.length expression consists of an array literal and the arr.length expression. And arr.length fails, since arr is undefined at that point.

References:

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Operator_Precedence

Title: Get/set variable inside if statement

Body:
var arr;

// arr is an array here, but why cannot I assign to length property?
if (arr = [1] && arr.length) {
    console.log(arr.length);
}

fails due to operator precedence. && has higher precedence than the assignment =, so it is evaluated first.

[1] && arr.length expression consists of an array literal and the arr.length expression. And arr.length fails, since arr is undefined at that point.

References:

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Operator_Precedence


问:
Ansible: How do I get IP address from only FQDN in Ansible?
So, here's the setup.

I am passing a list of FQDN's via extra vars to the playbook, but the key of control machine are copied with their corresponding IP addresses. Also their is no specific group of these in the inventory.

The host for this playbook is a server which may or may not be part of this list that I am passing via extra vars. So, the playbook doesn't have facts of these nodes whatsoever.

So, my question is how do I get the IP addresses of the respective hosts on the fly so that I can loop over them to do some checks for some properties that I have set using their FQDN's via another playbook/ role previously. (Note: I strictly need FQDN's to set these said properties)

I have used delegate_to module, and passing FQDN's and it works but it asks if I want to continue connecting(yes/ no) and waits for user input for the initial run (if given yes, It works as expected). Is their any other simpler, cleaner way to solve this?
  (Note: Bare in mind I cannot modify the contents of inventory like putting alias etc)

Here is the snippet of the code:

```<code>- name: Checks
  become_user: hdfs
  shell: hdfs dfsadmin –report
  delegate_to: "{{ item.host_name }}"
  with_items:
    - "{{rackDetails}}"
</code>```

Here is the snippet of the master yml file where the above role is called :

```<code>- name: Checks for the property
  hosts: servernode
  roles:
    - Checks
</code>```

Inventory code snippet looks like this:

[servernode]

  10.0.2.15 ansible_ssh_user=grant ansible_ssh_pass=grant

  [all]

  10.0.2.15 ansible_ssh_user=grant ansible_ssh_pass=grant

  10.0.2.16 ansible_ssh_user=grant ansible_ssh_pass=grant

  10.0.2.17 ansible_ssh_user=grant ansible_ssh_pass=grant

  10.0.2.18 ansible_ssh_user=grant ansible_ssh_pass=grant

  10.0.2.19 ansible_ssh_user=grant ansible_ssh_pass=grant

And finally, this is what I am passing via extra vars:

```<code>{"rackDetails":[{"host_name":"prod_node1.paas.com","rack_name":"/rack1"},{"host_name":"prod_node2.paas.com","rack_name":"/rack2"},{"host_name":"prod_node3.paas.com","rack_name":"/rack3"}]}
</code>```

答:
I wonder if delegate_to works if the hosts are passed as extra vars but not living inside inventory.

Anyway, you can use the dig lookup plugin:
http://docs.ansible.com/ansible/playbooks_lookups.html#the-dns-lookup-dig

```<code>{{ lookup('dig', item.host_name) }}
</code>```

Body:
So, here's the setup.

I am passing a list of FQDN's via extra vars to the playbook, but the key of control machine are copied with their corresponding IP addresses. Also their is no specific group of these in the inventory.

The host for this playbook is a server which may or may not be part of this list that I am passing via extra vars. So, the playbook doesn't have facts of these nodes whatsoever.

So, my question is how do I get the IP addresses of the respective hosts on the fly so that I can loop over them to do some checks for some properties that I have set using their FQDN's via another playbook/ role previously. (Note: I strictly need FQDN's to set these said properties)

I have used delegate_to module, and passing FQDN's and it works but it asks if I want to continue connecting(yes/ no) and waits for user input for the initial run (if given yes, It works as expected). Is their any other simpler, cleaner way to solve this?
  (Note: Bare in mind I cannot modify the contents of inventory like putting alias etc)

Here is the snippet of the code:

- name: Checks
  become_user: hdfs
  shell: hdfs dfsadmin –report
  delegate_to: "{{ item.host_name }}"
  with_items:
    - "{{rackDetails}}"

Here is the snippet of the master yml file where the above role is called :

- name: Checks for the property
  hosts: servernode
  roles:
    - Checks

Inventory code snippet looks like this:

[servernode]

  10.0.2.15 ansible_ssh_user=grant ansible_ssh_pass=grant

  [all]

  10.0.2.15 ansible_ssh_user=grant ansible_ssh_pass=grant

  10.0.2.16 ansible_ssh_user=grant ansible_ssh_pass=grant

  10.0.2.17 ansible_ssh_user=grant ansible_ssh_pass=grant

  10.0.2.18 ansible_ssh_user=grant ansible_ssh_pass=grant

  10.0.2.19 ansible_ssh_user=grant ansible_ssh_pass=grant

And finally, this is what I am passing via extra vars:

{"rackDetails":[{"host_name":"prod_node1.paas.com","rack_name":"/rack1"},{"host_name":"prod_node2.paas.com","rack_name":"/rack2"},{"host_name":"prod_node3.paas.com","rack_name":"/rack3"}]}

Body:
I wonder if delegate_to works if the hosts are passed as extra vars but not living inside inventory.

Anyway, you can use the dig lookup plugin:
http://docs.ansible.com/ansible/playbooks_lookups.html#the-dns-lookup-dig

{{ lookup('dig', item.host_name) }}


问:
Stuck at [$injector:nomod] Module 'app' is not available
I seem to be a bit stuck here trying to setup my new app.

I tried:

```<code>import angular from 'angular';
var myApp = angular.module('myApp', []);
</code>```

and I tried:

```<code>const angular = require('angular');
var myApp = angular.module('myApp', []);
</code>```

I still keep getting

```<code>Uncaught Error: [$injector:modulerr] Failed to instantiate module app due to:
Error: [$injector:nomod] Module 'app' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
http://errors.angularjs.org/1.6.4/$injector/nomod?p0=app
    at eval (eval at <anonymous> (http://localhost:8080/app.bundle.js:322:1),
</code>```

I already installed angular with npm and this is from my package.json

```<code>  "dependencies": {
    "angular": "^1.5.0",
    "angular-route": "^1.6.4",
    "bootstrap": "^3.3.7"
  },
</code>```

Any ideas?

答:
As the error says

Error: [$injector:nomod] Module 'app' is not available!

Somewhere  in your application you are trying to use ng-app='app' , rename it to ng-app='myApp'

Body:
I seem to be a bit stuck here trying to setup my new app.

I tried:

import angular from 'angular';
var myApp = angular.module('myApp', []);

and I tried:

const angular = require('angular');
var myApp = angular.module('myApp', []);

I still keep getting

Uncaught Error: [$injector:modulerr] Failed to instantiate module app due to:
Error: [$injector:nomod] Module 'app' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
http://errors.angularjs.org/1.6.4/$injector/nomod?p0=app
    at eval (eval at <anonymous> (http://localhost:8080/app.bundle.js:322:1),

I already installed angular with npm and this is from my package.json

  "dependencies": {
    "angular": "^1.5.0",
    "angular-route": "^1.6.4",
    "bootstrap": "^3.3.7"
  },

Any ideas?


问:
catching button clicks in javascript without server interaction
I've got a sign up form that requires the user to enter their email and password, both are in two separate text boxes. I want to provide a button that the user can click so that the password (which is masked) will appear in a popup when the user clicks the button.

Currently my JavaScript code for this is as follows:

```<code>    function toggleShowPassword() {
        var button = $get('PASSWORD_TEXTBOX_ID');
        var password;
        if (button)
        {
            password = button.value;
            alert(password);
            button.value = password;
        }
   }
</code>```

The problem is that every time the user clicks the button, the password is cleared in both Firefox and IE. I want them to be able to see their password in clear text to verify without having to retype their password.

My questions are:

Why does the password field keep getting reset with each button click?

How can I make it so the password field is NOT cleared once the user has seen his/her password in clear text?

答:
You didn't say you were using ASP.NET, but...

By design, ASP.NET clears during postback the value of TextBox controls whose Mode is Password.  I work around this in a subclass with the following code:

```
// If the TextMode is "password", the Text property won't work
if ( TextMode == System.Web.UI.WebControls.TextBoxMode.Password )
    Attributes[ "value" ] = stringValue;
```

OwnerDisplayName: eviljack

Body:
I've got a sign up form that requires the user to enter their email and password, both are in two separate text boxes. I want to provide a button that the user can click so that the password (which is masked) will appear in a popup when the user clicks the button.

Currently my JavaScript code for this is as follows:

    function toggleShowPassword() {
        var button = $get('PASSWORD_TEXTBOX_ID');
        var password;
        if (button)
        {
            password = button.value;
            alert(password);
            button.value = password;
        }
   }

The problem is that every time the user clicks the button, the password is cleared in both Firefox and IE. I want them to be able to see their password in clear text to verify without having to retype their password.

My questions are:

Why does the password field keep getting reset with each button click?

How can I make it so the password field is NOT cleared once the user has seen his/her password in clear text?

Body:
You didn't say you were using ASP.NET, but...

By design, ASP.NET clears during postback the value of TextBox controls whose Mode is Password.  I work around this in a subclass with the following code:

// If the TextMode is "password", the Text property won't work
if ( TextMode == System.Web.UI.WebControls.TextBoxMode.Password )
    Attributes[ "value" ] = stringValue;

OwnerDisplayName: harpo


问:
Has anyone tracked down whether IronPython or IronRuby will support Attributes?
I have scanned 'the Google' and have not found the definitive answer on whether the Iron* languages (any or all) will end up with Attribute support..

Anyone?

Thanks - Jon

答: There was some discussion about the plans in the ironpython mailing list recently - link text</p>

OwnerDisplayName: jdharley

OwnerDisplayName: srivatsn


问:
Get txt lines into variables, divide by separators check and rewrite txt send command
I searched trough various examples and solutions but I can't get one working by now.

This is what I have:
foo.txt:

```<code>var1:var2:var3:var4
var1:var2:var3:var4
var1:var2:var3:var4
</code>```

etc.

I need a script which get to foo.txt open it and get var3.
if var3 is less than 25,
outputs
'echo command user password sendammount $var4 sendto $var2'
and then raise var3 by 1 in the txt, saves it and goes to next line doing the same, if var3 is already 25 it just skips the line doing nothing and going to the next one, once last line fullfilled, script closes (It should run every hour but i've read it could be done with watch -n 5 foo.sh ).

```<code>var1=$(echo $STR | cut -f1 -d-)
var2=$(echo $STR | cut -f2 -d-)
</code>```

What it does:

```<code>ABCDE-123456
var1:ABCDE
var2:123456
</code>```

I don't get where do I edit the divider in the var1=$(echo $STR | cut -f1 -d-) expression?

Also can I set the variable just by deleting the echo?
I tried to lookup the editing part but I can't get my logic working till there..

答:
Let me know how much I win.</p>

```<code>#!/bin/bash
function usage(){
    echo "Usage: $0 <input_file>"
}

# Ensure we have an input file
if [ "$#" -lt 1 ]; then
    usage
    exit 1
elif [ "$1" = "-h" -o "$1" = "-?" -o "$1" = "--help" ]; then
    usage
    exit 0
fi

input_file="$1"

# Get number of lines in file
nLines=$( wc -l "${input_file}" | cut -d' ' -f1 )

# Loop over each line in the file
for (( ii=1; ii<=nLines; ii++ ));do
    # Extract the line
    line=$( sed -n "${ii}p" "${input_file}" )

    # Parse by ':'
    var1=$( echo "${line}" | cut -d: -f1 )
    var2=$( echo "${line}" | cut -d: -f2 )
    var3=$( echo "${line}" | cut -d: -f3 )
    var4=$( echo "${line}" | cut -d: -f4 )

    # Parse var3 into whole part and decimal part
    whole=$( echo ${var3} | cut -d. -f1 )
    decimal=$( echo ${var3} | cut -d. -f2 )

    # If the whole part is less than 25...
    if [ ${whole} -lt 25 ]; then
        # Print desired command
        echo command user password sendammount $var4 sendto $var2
        # Increment whole part
        (( whole++ ))
        # Write back to original file based on whether there was a decimal part
        if [ -z "${decimal}" ]; then
            sed -i "${ii}s/^.*$/${var1}:${var2}:${whole}:${var4}/" "${input_file}"
        else
            sed -i "${ii}s/^.*$/${var1}:${var2}:${whole}.${decimal}:${var4}/" "${input_file}"
        fi
    fi
done
</code>```

Body:
I searched trough various examples and solutions but I can't get one working by now.

This is what I have:
foo.txt:

var1:var2:var3:var4
var1:var2:var3:var4
var1:var2:var3:var4

etc.

I need a script which get to foo.txt open it and get var3.
if var3 is less than 25,
outputs
'echo command user password sendammount $var4 sendto $var2'
and then raise var3 by 1 in the txt, saves it and goes to next line doing the same, if var3 is already 25 it just skips the line doing nothing and going to the next one, once last line fullfilled, script closes (It should run every hour but i've read it could be done with watch -n 5 foo.sh ).

var1=$(echo $STR | cut -f1 -d-)
var2=$(echo $STR | cut -f2 -d-)

What it does:

ABCDE-123456
var1:ABCDE
var2:123456

I don't get where do I edit the divider in the var1=$(echo $STR | cut -f1 -d-) expression?

Also can I set the variable just by deleting the echo?
I tried to lookup the editing part but I can't get my logic working till there..

Body:
Let me know how much I win.

#!/bin/bash
function usage(){
    echo "Usage: $0 <input_file>"
}

# Ensure we have an input file
if [ "$#" -lt 1 ]; then
    usage
    exit 1
elif [ "$1" = "-h" -o "$1" = "-?" -o "$1" = "--help" ]; then
    usage
    exit 0
fi

input_file="$1"

# Get number of lines in file
nLines=$( wc -l "${input_file}" | cut -d' ' -f1 )

# Loop over each line in the file
for (( ii=1; ii<=nLines; ii++ ));do
    # Extract the line
    line=$( sed -n "${ii}p" "${input_file}" )

    # Parse by ':'
    var1=$( echo "${line}" | cut -d: -f1 )
    var2=$( echo "${line}" | cut -d: -f2 )
    var3=$( echo "${line}" | cut -d: -f3 )
    var4=$( echo "${line}" | cut -d: -f4 )

    # Parse var3 into whole part and decimal part
    whole=$( echo ${var3} | cut -d. -f1 )
    decimal=$( echo ${var3} | cut -d. -f2 )

    # If the whole part is less than 25...
    if [ ${whole} -lt 25 ]; then
        # Print desired command
        echo command user password sendammount $var4 sendto $var2
        # Increment whole part
        (( whole++ ))
        # Write back to original file based on whether there was a decimal part
        if [ -z "${decimal}" ]; then
            sed -i "${ii}s/^.*$/${var1}:${var2}:${whole}:${var4}/" "${input_file}"
        else
            sed -i "${ii}s/^.*$/${var1}:${var2}:${whole}.${decimal}:${var4}/" "${input_file}"
        fi
    fi
done


问:
How to create boxplot with large amount of continuous x-variables and continuous y-variables with R (not ggplot)
How to create boxplot with large amount of continuous x-variables and continuous y-variableswith R
don't use ggplot.
Just like the following figure, the x-axis and y-axis are all continuous numerical variable.
example boxplot</p>

答:
You have a multiple options:

http://www.statmethods.net/graphs/boxplot.html

https://www.r-bloggers.com/box-plot-with-r-tutorial/

https://stat.ethz.ch/R-manual/R-devel/library/graphics/html/boxplot.html

https://plot.ly/r/box-plots/


问:
python attribute lookup without any descriptor magic?
I've started to use the python descriptor protocol more extensively in the code I've been writing.  Typically, the default python lookup magic is what I want to happen, but sometimes I'm finding I want to get the descriptor object itself instead the results of its __get__ method. Wanting to know the type of the descriptor, or access state stored in the descriptor, or somesuch thing.

I wrote the code below to walk the namespaces in what I believe is the correct ordering, and return the attribute raw regardless of whether it is a descriptor or not. I'm surprised though that I can't find a built-in function or something in the standard library to do this -- I figure it has to be there and I just haven't noticed it or googled for the right search term.

Is there functionality somewhere in the python distribution that already does this (or something similar)?

Thanks!

```<code>from inspect import isdatadescriptor

def namespaces(obj):
    obj_dict = None
    if hasattr(obj, '__dict__'):
        obj_dict = object.__getattribute__(obj, '__dict__')

    obj_class = type(obj)
    return obj_dict, [t.__dict__ for t in obj_class.__mro__]

def getattr_raw(obj, name):
    # get an attribute in the same resolution order one would normally,
    # but do not call __get__ on the attribute even if it has one
    obj_dict, class_dicts = namespaces(obj)

    # look for a data descriptor in class hierarchy; it takes priority over
    # the obj's dict if it exists
    for d in class_dicts:
        if name in d and isdatadescriptor(d[name]):
            return d[name]

    # look for the attribute in the object's dictionary
    if obj_dict and name in obj_dict:
        return obj_dict[name]

    # look for the attribute anywhere in the class hierarchy
    for d in class_dicts:
        if name in d:
            return d[name]

    raise AttributeError
</code>```

Edit Wed, Oct 28, 2009.

Denis's answer gave me a convention to use in my descriptor classes to get the descriptor objects themselves. But, I had an entire class hierarchy of descriptor classes, and I didn't want to begin every __get__ function with a boilerplate

```<code>def __get__(self, instance, instance_type):
    if instance is None:
        return self
    ...
</code>```

To avoid this, I made the root of the descriptor class tree inherit from the following:

```<code>def decorate_get(original_get):
    def decorated_get(self, instance, instance_type):
        if instance is None:
            return self
        return original_get(self, instance, instance_type)
    return decorated_get

class InstanceOnlyDescriptor(object):
    """All __get__ functions are automatically wrapped with a decorator which
    causes them to only be applied to instances. If __get__ is called on a
    class, the decorator returns the descriptor itself, and the decorated
    __get__ is not called.
    """
    class __metaclass__(type):
        def __new__(cls, name, bases, attrs):
            if '__get__' in attrs:
                attrs['__get__'] = decorate_get(attrs['__get__'])
            return type.__new__(cls, name, bases, attrs)
</code>```

答:
The inspect library provides a function to retrieve an attribute without any descriptor magic: inspect.getattr_static.

Documentation: https://docs.python.org/3/library/inspect.html#fetching-attributes-statically

(This is an old question, but I keep coming across it when trying to remember how to do this, so I'm posting this answer so I can find it again!)

Body:
I've started to use the python descriptor protocol more extensively in the code I've been writing.  Typically, the default python lookup magic is what I want to happen, but sometimes I'm finding I want to get the descriptor object itself instead the results of its __get__ method. Wanting to know the type of the descriptor, or access state stored in the descriptor, or somesuch thing.

I wrote the code below to walk the namespaces in what I believe is the correct ordering, and return the attribute raw regardless of whether it is a descriptor or not. I'm surprised though that I can't find a built-in function or something in the standard library to do this -- I figure it has to be there and I just haven't noticed it or googled for the right search term.

Is there functionality somewhere in the python distribution that already does this (or something similar)?

Thanks!

from inspect import isdatadescriptor

def namespaces(obj):
    obj_dict = None
    if hasattr(obj, '__dict__'):
        obj_dict = object.__getattribute__(obj, '__dict__')

    obj_class = type(obj)
    return obj_dict, [t.__dict__ for t in obj_class.__mro__]

def getattr_raw(obj, name):
    # get an attribute in the same resolution order one would normally,
    # but do not call __get__ on the attribute even if it has one
    obj_dict, class_dicts = namespaces(obj)

    # look for a data descriptor in class hierarchy; it takes priority over
    # the obj's dict if it exists
    for d in class_dicts:
        if name in d and isdatadescriptor(d[name]):
            return d[name]

    # look for the attribute in the object's dictionary
    if obj_dict and name in obj_dict:
        return obj_dict[name]

    # look for the attribute anywhere in the class hierarchy
    for d in class_dicts:
        if name in d:
            return d[name]

    raise AttributeError

Edit Wed, Oct 28, 2009.

Denis's answer gave me a convention to use in my descriptor classes to get the descriptor objects themselves. But, I had an entire class hierarchy of descriptor classes, and I didn't want to begin every __get__ function with a boilerplate

def __get__(self, instance, instance_type):
    if instance is None:
        return self
    ...

To avoid this, I made the root of the descriptor class tree inherit from the following:

def decorate_get(original_get):
    def decorated_get(self, instance, instance_type):
        if instance is None:
            return self
        return original_get(self, instance, instance_type)
    return decorated_get

class InstanceOnlyDescriptor(object):
    """All __get__ functions are automatically wrapped with a decorator which
    causes them to only be applied to instances. If __get__ is called on a
    class, the decorator returns the descriptor itself, and the decorated
    __get__ is not called.
    """
    class __metaclass__(type):
        def __new__(cls, name, bases, attrs):
            if '__get__' in attrs:
                attrs['__get__'] = decorate_get(attrs['__get__'])
            return type.__new__(cls, name, bases, attrs)


问:
Firebase Auth Couldn't Verify Domain
I have a Firebase account, and I want to tailor the email address from which verification emails are sent. I follow the instructions.

I have a domain registered with 1&1 and set up as instructed.

But after about 2 days, I get the following.

Please can anyone advise.  Thanks

答:
Maybe the trailing space on your TXT record?</p>

```<code>$ dig txt thewhozoo.com

; <<>> DiG 9.8.3-P1 <<>> txt thewhozoo.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 59407
;; flags: qr rd ra; QUERY: 1, ANSWER: 2, AUTHORITY: 0, ADDITIONAL: 0

;; QUESTION SECTION:
;thewhozoo.com.         IN  TXT

;; ANSWER SECTION:
thewhozoo.com.      3600    IN  TXT "firebase=thewhozoo-143913 "
thewhozoo.com.      3600    IN  TXT "v=spf1 include:_spf.firebasemail.com ~all "

;; Query time: 45 msec
;; SERVER: 192.168.1.1#53(192.168.1.1)
;; WHEN: Thu Jun  8 23:49:07 2017
;; MSG SIZE  rcvd: 125
</code>```

Title: Firebase Auth Couldn't Verify Domain

Body:
Maybe the trailing space on your TXT record?

$ dig txt thewhozoo.com

; <<>> DiG 9.8.3-P1 <<>> txt thewhozoo.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 59407
;; flags: qr rd ra; QUERY: 1, ANSWER: 2, AUTHORITY: 0, ADDITIONAL: 0

;; QUESTION SECTION:
;thewhozoo.com.         IN  TXT

;; ANSWER SECTION:
thewhozoo.com.      3600    IN  TXT "firebase=thewhozoo-143913 "
thewhozoo.com.      3600    IN  TXT "v=spf1 include:_spf.firebasemail.com ~all "

;; Query time: 45 msec
;; SERVER: 192.168.1.1#53(192.168.1.1)
;; WHEN: Thu Jun  8 23:49:07 2017
;; MSG SIZE  rcvd: 125


问:
Do code blocks completely replace delegates?
Now that blocks are finally supported for iphone/ipad development, do these completely remove the need for delegates or are delegates still cleaner as a complete interface implementation while blocks are more appropriate for single tasks?</p>

答:
Delegates - You can use delegate when you want to know the Process/Events/State. For example In NSURLConnectionDelegate you will get the status of data with two or more delegate methods .didReceive:NSData  connectionDidFinishLoading

Blocks - You can use block only when you expect a result or error

Best reference - http://blog.stablekernel.com/blocks-or-delegates/


问:
How to check Global Reversible Encryption though JNA?
I am trying to retrieve the global value of the Reversible Encryption setting in Windows through JNA (Java Native Access) programmatically.

I am able to read other values from the Global user password policy via JNA such as

Enforce password history

Maximum password age

Minimum password age

Minimum password length

But there is no information on how you can get specifically the value of Reversible Encryption in Java? I tried to google but to no avail. Anyone knows?

答:
The reversible encryption setting is available in WMI in the RSOP_SecuritySettingBoolean class, using the key ClearTextPassword.

It is possible to query WMI via the command line (e.g., wmic /NAMESPACE:\\root\RSOP\Computer path RSOP_SecuritySettingBoolean) or through powershell.  I have implemented a WMI Util class using JNA that implements C code to query WMI that you are welcome to copy if you'd prefer a programmatic approach (you'll need a few more classes there.)

You can also execute this on the command line: Secedit.exe /export /cfg c:\cfg.txt and read the output file, looking for the value of ClearTextPassword.

It also looks like you can possibly fetch the value with a binary dump of the contents of registry key \HKEY_LOCAL_MACHINE\SAM\SAM\Domains\Account\F in which case the value would be stored in the 4 most significant bits of the byte at offset 0x004C.  You can read the registry using JNA's Advapi32Util class (in this case, probably registryGetBinaryValue()).

I also found a registry location that may be helpful (completely untested):
\HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\SeCEdit\Reg Values. This points to similar settings in Machine/System/CurrentControlSet/Services/Netlogon/Parameters which may or may not be helpful


问:
Does NumPy handle 1:1 aliasing of complex-number operations correctly?
Say a and b are disjoint 1D complex NumPy arrays, and I do numpy.multiply(a, b, b).

Is b guaranteed to contain the same values as I would get via b[:] = numpy.multiply(a, b)?

I haven't actually been able to produce incorrect results, but I don't know if I'm just being lucky with my particular compilation or platform or if I can actually rely on that, hence the question.

Notice that with float (i.e. real numbers) the answer would obviously yes, since a reasonable implementation can't make it fail, but with complex numbers it's easy for the cross-multiply operation to give incorrect results by writing the real part and then reading an imaginary part:

```<code># say the real part is at [0] and the imaginary part is at [1] and c is the product of a & b
c[0] = a[0] * b[0] - a[1] * b[1]
c[1] = a[0] * b[1] + a[1] * b[0]  # if c[0] overlaps a[0] or b[0] then this is wrong
</code>```

答: Yes. Complex values ought to be treated atomically. If it doesn't work like that, then it's a bug that we'll fix.</p>

Body:
Say a and b are disjoint 1D complex NumPy arrays, and I do numpy.multiply(a, b, b).

Is b guaranteed to contain the same values as I would get via b[:] = numpy.multiply(a, b)?

I haven't actually been able to produce incorrect results, but I don't know if I'm just being lucky with my particular compilation or platform or if I can actually rely on that, hence the question.

Notice that with float (i.e. real numbers) the answer would obviously yes, since a reasonable implementation can't make it fail, but with complex numbers it's easy for the cross-multiply operation to give incorrect results by writing the real part and then reading an imaginary part:

# say the real part is at [0] and the imaginary part is at [1] and c is the product of a & b
c[0] = a[0] * b[0] - a[1] * b[1]
c[1] = a[0] * b[1] + a[1] * b[0]  # if c[0] overlaps a[0] or b[0] then this is wrong


答:
JS parses your if statement as

```<code> if (arr = ([1] && arr.length)) {
</code>```

The reason is that && binds more tightly than the assignment operator. As a result, JS is trying to evaluate [1] && arr.length at a point in time where arr is not yet defined.

You need to write

```<code>if ((arr = [1]) && arr.length) {
</code>```

Title: Get/set variable inside if statement

Body:
JS parses your if statement as

 if (arr = ([1] && arr.length)) {

The reason is that && binds more tightly than the assignment operator. As a result, JS is trying to evaluate [1] && arr.length at a point in time where arr is not yet defined.

You need to write

if ((arr = [1]) && arr.length) {


问:
What is the use of openid id_token
I am implementing openid connect for google and microsoft. Openid provides the id_token which also content the user info. I am still confused. How to use id_token. In oauth2 we are storing the access_token in our db. so we use access_token to get user profile. If I am getting the profile mean user is authenticate and user will login into app. So in id_token case, should I validate the token. If token is validate then user will login. I am really confused. Please help me out. Please provide the flow of authentication.</p>

答: If token is not required for authentication. It is only useful in public clients to get some user attributes aka claims.</p>

Title: What is the use of openid id_token


问:
Java 8 List<V> into Map<K, V>
I want to translate a List of objects into a Map using Java 8's streams and lambdas.

This is how I would write it in Java 7 and below.

```<code>private Map<String, Choice> nameMap(List<Choice> choices) {
        final Map<String, Choice> hashMap = new HashMap<>();
        for (final Choice choice : choices) {
            hashMap.put(choice.getName(), choice);
        }
        return hashMap;
}
</code>```

I can accomplish this easily using Java 8 and Guava but I would like to know how to do this without Guava.

In Guava:

```<code>private Map<String, Choice> nameMap(List<Choice> choices) {
    return Maps.uniqueIndex(choices, new Function<Choice, String>() {

        @Override
        public String apply(final Choice input) {
            return input.getName();
        }
    });
}
</code>```

And Guava with Java 8 lambdas.

```<code>private Map<String, Choice> nameMap(List<Choice> choices) {
    return Maps.uniqueIndex(choices, Choice::getName);
}
</code>```

答:
Here is solution by StreamEx</p>

```<code>StreamEx.of(choices).toMap(Choice::getName, c -> c);
</code>```

Title: Java 8 List<V> into Map<K, V>

Body:
I want to translate a List of objects into a Map using Java 8's streams and lambdas.

This is how I would write it in Java 7 and below.

private Map<String, Choice> nameMap(List<Choice> choices) {
        final Map<String, Choice> hashMap = new HashMap<>();
        for (final Choice choice : choices) {
            hashMap.put(choice.getName(), choice);
        }
        return hashMap;
}

I can accomplish this easily using Java 8 and Guava but I would like to know how to do this without Guava.

In Guava:

private Map<String, Choice> nameMap(List<Choice> choices) {
    return Maps.uniqueIndex(choices, new Function<Choice, String>() {

        @Override
        public String apply(final Choice input) {
            return input.getName();
        }
    });
}

And Guava with Java 8 lambdas.

private Map<String, Choice> nameMap(List<Choice> choices) {
    return Maps.uniqueIndex(choices, Choice::getName);
}

Body:
Here is solution by StreamEx

StreamEx.of(choices).toMap(Choice::getName, c -> c);


问:
Ionic 3 project cannot be built for ios after installing OneSignal plugin
I created a new project and installed OneSignal plugin.

sudo ionic cordova plugin add onesignal-cordova-plugin

sudo npm install --save @ionic-native/onesignal

After that I built for Android was okay, yet I built for iOS.

sudo ionic cordova build ios

It gave me a message like this -->

```<code>    Lolzzs-MacBook-Pro:myOnesignal lolzzlolzz$ sudo ionic cordova build ios
> cordova platform add --save ios
✖ Running command - failed!
[ERROR] An error occurred while running cordova platform add --save ios (exit code 1):

        Using cordova-fetch for cordova-ios@~4.4.0
        Adding ios project...
        Creating Cordova project for the iOS platform:
                Path: platforms/ios
                Package: io.ionic.starter
                Name: MyApp
        iOS project created with cordova-ios@4.4.0
        Installing "cordova-plugin-console" for ios
        Installing "cordova-plugin-device" for ios
        Installing "cordova-plugin-splashscreen" for ios
        Installing "cordova-plugin-statusbar" for ios
        Installing "cordova-plugin-whitelist" for ios
        Installing "ionic-plugin-keyboard" for ios
        Installing "onesignal-cordova-plugin" for ios
        Failed to install 'onesignal-cordova-plugin': undefined
        Error: /usr/local/lib/ruby/gems/2.4.0/gems/claide-1.0.1/lib/claide/command.rb:439:in
 `help!': [!] You cannot run CocoaPods as root. (CLAide::Help)

        Usage:

            $ pod COMMAND

              CocoaPods, the Cocoa library package manager.

        Commands:
+ cache      Manipulate the CocoaPods cache
            + env        Display pod environment
            + init       Generate a Podfile for the current directory
            + install    Install project dependencies according to versions from a
                         Podfile.lock
            + ipc        Inter-process communication
            + lib        Develop pods
            + list       List pods
            + outdated   Show outdated project dependencies
            + repo       Manage spec-repositories
            + setup      Setup the CocoaPods environment
            + spec       Manage pod specs
            + update     Update outdated project dependencies and create new Podfile.lock

        Options:

            --silent     Show nothing
            --version    Show the version of the tool
            --verbose    Show more debugging information
            --no-ansi    Show output without ANSI codes
            --help       Show help banner of specified command
                from /usr/local/lib/ruby/gems/2.4.0/gems/cocoapods-1.2.1/lib/cocoapods/comma
nd.rb:47:in `run'
                from /usr/local/lib/ruby/gems/2.4.0/gems/cocoapods-1.2.1/bin/pod:55:in `<top
 (required)>'
                from /usr/local/bin/pod:22:in `load'
                from /usr/local/bin/pod:22:in `<main>'
</code>```

答:
after a long time trying to build my project with the exact same error with oneSignal

I saw a instruction to go to platform/ios
and run:

sudo gem install cocoapods

and

pod install --repo-update

and that worked

Body:
I created a new project and installed OneSignal plugin.

sudo ionic cordova plugin add onesignal-cordova-plugin

sudo npm install --save @ionic-native/onesignal

After that I built for Android was okay, yet I built for iOS.

sudo ionic cordova build ios

It gave me a message like this -->

    Lolzzs-MacBook-Pro:myOnesignal lolzzlolzz$ sudo ionic cordova build ios
> cordova platform add --save ios
✖ Running command - failed!
[ERROR] An error occurred while running cordova platform add --save ios (exit code 1):

        Using cordova-fetch for cordova-ios@~4.4.0
        Adding ios project...
        Creating Cordova project for the iOS platform:
                Path: platforms/ios
                Package: io.ionic.starter
                Name: MyApp
        iOS project created with cordova-ios@4.4.0
        Installing "cordova-plugin-console" for ios
        Installing "cordova-plugin-device" for ios
        Installing "cordova-plugin-splashscreen" for ios
        Installing "cordova-plugin-statusbar" for ios
        Installing "cordova-plugin-whitelist" for ios
        Installing "ionic-plugin-keyboard" for ios
        Installing "onesignal-cordova-plugin" for ios
        Failed to install 'onesignal-cordova-plugin': undefined
        Error: /usr/local/lib/ruby/gems/2.4.0/gems/claide-1.0.1/lib/claide/command.rb:439:in
 `help!': [!] You cannot run CocoaPods as root. (CLAide::Help)

        Usage:

            $ pod COMMAND

              CocoaPods, the Cocoa library package manager.

        Commands:
+ cache      Manipulate the CocoaPods cache
            + env        Display pod environment
            + init       Generate a Podfile for the current directory
            + install    Install project dependencies according to versions from a
                         Podfile.lock
            + ipc        Inter-process communication
            + lib        Develop pods
            + list       List pods
            + outdated   Show outdated project dependencies
            + repo       Manage spec-repositories
            + setup      Setup the CocoaPods environment
            + spec       Manage pod specs
            + update     Update outdated project dependencies and create new Podfile.lock

        Options:

            --silent     Show nothing
            --version    Show the version of the tool
            --verbose    Show more debugging information
            --no-ansi    Show output without ANSI codes
            --help       Show help banner of specified command
                from /usr/local/lib/ruby/gems/2.4.0/gems/cocoapods-1.2.1/lib/cocoapods/comma
nd.rb:47:in `run'
                from /usr/local/lib/ruby/gems/2.4.0/gems/cocoapods-1.2.1/bin/pod:55:in `<top
 (required)>'
                from /usr/local/bin/pod:22:in `load'
                from /usr/local/bin/pod:22:in `'


问:
How to speed real time opencv image processing on android studio
Iam working on opencv real time image matching by using Imgproc.TemplateMatching(),the app was working but it's slow. Any one have idea to help me how ican speed my template matching.
this is my MainActivity:

package com.example.altayeb.myapplication2;

```<code>import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SurfaceView;

import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.JavaCameraView;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.android.Utils;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.core.Scalar;
import org.opencv.imgproc.Imgproc;

import java.io.FileNotFoundException;
import java.io.InputStream;

public class MainActivity extends AppCompatActivity implements CameraBridgeViewBase.CvCameraViewListener2{
    private static String TAG="MainActivity";
    InputStream stream = null;
    BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
    MediaPlayer md50,md20,md10,md5,md2,mdwelcom;

    Mat mRgba,gray1,gray2,tmpl,outputimage;
    int match_method;
    Bitmap bmp;
    Point matchLoc;
    int count=1;
    Uri uri;

    BaseLoaderCallback mloaderCallback=new BaseLoaderCallback(this) {
        @Override
        public void onManagerConnected(int status) {
            switch (status){
                case BaseLoaderCallback.SUCCESS:
                {javaCameraView.enableView();
                    break;}
                default:
                { super.onManagerConnected(status);
                    break;}
            }
        }
    };
    JavaCameraView javaCameraView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        javaCameraView=(JavaCameraView)findViewById(R.id.java_camera_view);
        javaCameraView.setVisibility(SurfaceView.VISIBLE);

        md50 = MediaPlayer.create(getApplication(),R.raw.fifty);
        md20 = MediaPlayer.create(getApplication(),R.raw.twenty);
        md10 = MediaPlayer.create(getApplication(),R.raw.tensound);
        md5 = MediaPlayer.create(getApplication(),R.raw.five);
        md2 = MediaPlayer.create(getApplication(),R.raw.tow);
        mdwelcom = MediaPlayer.create(getApplication(),R.raw.welcom);

        javaCameraView.setCvCameraViewListener(this);

    }

    @Override
    protected void onPause() {
        super.onPause();
        if(javaCameraView!=null){
            javaCameraView.disableView();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(javaCameraView!=null){
            javaCameraView.disableView();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(OpenCVLoader.initDebug()){
            Log.i(TAG,"Seccessfully");
            mloaderCallback.onManagerConnected(LoaderCallbackInterface.SUCCESS);
        }
        else
        {
            Log.i(TAG,"Not Seccessfully");
            OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_1_0,this,mloaderCallback);
        }
    }

    @Override
    public void onCameraViewStarted(int width, int height) {
        mRgba=new Mat(height,width, CvType.CV_32FC1);
        gray1=new Mat(height,width, CvType.CV_32FC1);
        gray2=new Mat(height,width, CvType.CV_32FC1);
        mdwelcom.start();

    }

    @Override
    public void onCameraViewStopped() {
        mRgba.release();
    }

    @Override
    public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) {
       mRgba=inputFrame.rgba();
       gray1=inputFrame.gray();
        match(gray1);
      // return match(mRgba);
        return mRgba;
    }
    //Matching Method
    //public Mat match(Mat source){
        public void match(Mat source){

        switch (count) {
            case 1:{
                uri = Uri.parse("android.resource://com.example.altayeb.myapplication2/drawable/fifty1");
                break;
            }
            case 2:{
                uri = Uri.parse("android.resource://com.example.altayeb.myapplication2/drawable/fifty2");
                break;

            }
            case 3:{
                uri = Uri.parse("android.resource://com.example.altayeb.myapplication2/drawable/tow1");
                break;
            }
            case 4:{
                uri = Uri.parse("android.resource://com.example.altayeb.myapplication2/drawable/tow2");
                break;
            }

            case 5:{
                uri = Uri.parse("android.resource://com.example.altayeb.myapplication2/drawable/ten1");
                break;
            }
            case 6:{
                uri = Uri.parse("android.resource://com.example.altayeb.myapplication2/drawable/ten2");
                break;
            }
            case 7:{
                uri = Uri.parse("android.resource://com.example.altayeb.myapplication2/drawable/twenty1");
                break;
            }
            case 8:{
                uri = Uri.parse("android.resource://com.example.altayeb.myapplication2/drawable/twenty2");
                break;
            }
            case 9:{
                uri = Uri.parse("android.resource://com.example.altayeb.myapplication2/drawable/five1");
                break;
            }
            case 10:{
                uri = Uri.parse("android.resource://com.example.altayeb.myapplication2/drawable/five2");
                break;
            }
        }
        try {
            stream = getContentResolver().openInputStream(uri);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        bmpFactoryOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;

        bmp = BitmapFactory.decodeStream(stream, null, bmpFactoryOptions);
        tmpl = new Mat();
        Utils.bitmapToMat(bmp, tmpl);
        match_method = Imgproc.TM_CCOEFF_NORMED;

       // Imgproc.cvtColor(source,gray1,Imgproc.COLOR_RGB2GRAY);
        Imgproc.cvtColor(tmpl,gray2,Imgproc.COLOR_RGB2GRAY);
       // outputimage=new Mat(mRgba.cols() - gray2.cols() + 1,mRgba.rows() - gray2.rows() + 1,CvType.CV_8UC1);
            outputimage=new Mat(source.cols() - gray2.cols() + 1,source.rows() - gray2.rows() + 1,CvType.CV_8UC1);
       Imgproc.matchTemplate(source,gray2,outputimage,match_method);
      //  Core.normalize(outputimage, outputimage, 0, 1, Core.NORM_MINMAX, -1, new Mat());

        Core.MinMaxLocResult mmr = Core.minMaxLoc(outputimage);
        matchLoc = mmr.maxLoc;
        double minMatchQiality = 0.68;
        if(mmr.maxVal>=minMatchQiality){
           Imgproc.rectangle(mRgba, matchLoc, new Point(matchLoc.x + gray2.cols(), matchLoc.y + gray2.rows()), new Scalar(255, 0, 0));
            switch (count) {
                case 1:{ md50.start();
                break;}
                case 2:{md50.start();
                    break;}
                case 3:{
                    md2.start();
                    break;
                }
                case 4:{
                    md2.start();
                    break;
                }

                 case 5:{
                    md10.start();
                    break;
                }
                case 6:{
                    md10.start();
                    break;
                }

                case 7:{
                    md20.start();
                    break;
                }
                case 8:{
                    md20.start();
                    break;
                }
                case 9:{
                    md5.start();
                    break;
                }
                case 10:{
                    md5.start();
                    break;
                }
            }}
        else    {
            if(count>=10){count=1;}
            else {count++;}
        }
       // return  mRgba;
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id=item.getItemId();
        if(id==R.id.about){
            Intent i2 = new Intent(getApplicationContext(),About.class);
            startActivity(i2);
        }
        if(id==R.id.help){
            Intent i3 = new Intent(getApplicationContext(),Help.class);
            startActivity(i3);
        }

        return super.onOptionsItemSelected(item);
    }

    public class CustomizableCameraView extends JavaCameraView {

        public CustomizableCameraView(Context context, AttributeSet attrs) {
            super(context, attrs);
        }

        public void setPreviewFPS(double min, double max){
            Camera.Parameters params = mCamera.getParameters();
            params.setPreviewFpsRange((int)(min*1000), (int)(max*1000));
            mCamera.setParameters(params);
        }
    }
}
</code>```

答:
You can try the following:

Check the size of the captured photos. If they are very large, template matching is going to take a lot of time. Reducing the image size speeds up matching, just that you will have to resize your templates as well.

See whether you really need to do template matching on the entire image. Cropping out only the real region of interest, if there is one, can help a lot.

You can also do some profiling to see where exactly the bottlenecks are. Is the program still slow even if you do not perform template matching?

Body:
Iam working on opencv real time image matching by using Imgproc.TemplateMatching(),the app was working but it's slow. Any one have idea to help me how ican speed my template matching.
this is my MainActivity:

package com.example.altayeb.myapplication2;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SurfaceView;

import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.JavaCameraView;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.android.Utils;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.core.Scalar;
import org.opencv.imgproc.Imgproc;

import java.io.FileNotFoundException;
import java.io.InputStream;

public class MainActivity extends AppCompatActivity implements CameraBridgeViewBase.CvCameraViewListener2{
    private static String TAG="MainActivity";
    InputStream stream = null;
    BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
    MediaPlayer md50,md20,md10,md5,md2,mdwelcom;

    Mat mRgba,gray1,gray2,tmpl,outputimage;
    int match_method;
    Bitmap bmp;
    Point matchLoc;
    int count=1;
    Uri uri;

    BaseLoaderCallback mloaderCallback=new BaseLoaderCallback(this) {
        @Override
        public void onManagerConnected(int status) {
            switch (status){
                case BaseLoaderCallback.SUCCESS:
                {javaCameraView.enableView();
                    break;}
                default:
                { super.onManagerConnected(status);
                    break;}
            }
        }
    };
    JavaCameraView javaCameraView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        javaCameraView=(JavaCameraView)findViewById(R.id.java_camera_view);
        javaCameraView.setVisibility(SurfaceView.VISIBLE);

        md50 = MediaPlayer.create(getApplication(),R.raw.fifty);
        md20 = MediaPlayer.create(getApplication(),R.raw.twenty);
        md10 = MediaPlayer.create(getApplication(),R.raw.tensound);
        md5 = MediaPlayer.create(getApplication(),R.raw.five);
        md2 = MediaPlayer.create(getApplication(),R.raw.tow);
        mdwelcom = MediaPlayer.create(getApplication(),R.raw.welcom);

        javaCameraView.setCvCameraViewListener(this);

    }

    @Override
    protected void onPause() {
        super.onPause();
        if(javaCameraView!=null){
            javaCameraView.disableView();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(javaCameraView!=null){
            javaCameraView.disableView();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(OpenCVLoader.initDebug()){
            Log.i(TAG,"Seccessfully");
            mloaderCallback.onManagerConnected(LoaderCallbackInterface.SUCCESS);
        }
        else
        {
            Log.i(TAG,"Not Seccessfully");
            OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_1_0,this,mloaderCallback);
        }
    }

    @Override
    public void onCameraViewStarted(int width, int height) {
        mRgba=new Mat(height,width, CvType.CV_32FC1);
        gray1=new Mat(height,width, CvType.CV_32FC1);
        gray2=new Mat(height,width, CvType.CV_32FC1);
        mdwelcom.start();

    }

    @Override
    public void onCameraViewStopped() {
        mRgba.release();
    }

    @Override
    public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) {
       mRgba=inputFrame.rgba();
       gray1=inputFrame.gray();
        match(gray1);
      // return match(mRgba);
        return mRgba;
    }
    //Matching Method
    //public Mat match(Mat source){
        public void match(Mat source){

        switch (count) {
            case 1:{
                uri = Uri.parse("android.resource://com.example.altayeb.myapplication2/drawable/fifty1");
                break;
            }
            case 2:{
                uri = Uri.parse("android.resource://com.example.altayeb.myapplication2/drawable/fifty2");
                break;

            }
            case 3:{
                uri = Uri.parse("android.resource://com.example.altayeb.myapplication2/drawable/tow1");
                break;
            }
            case 4:{
                uri = Uri.parse("android.resource://com.example.altayeb.myapplication2/drawable/tow2");
                break;
            }

            case 5:{
                uri = Uri.parse("android.resource://com.example.altayeb.myapplication2/drawable/ten1");
                break;
            }
            case 6:{
                uri = Uri.parse("android.resource://com.example.altayeb.myapplication2/drawable/ten2");
                break;
            }
            case 7:{
                uri = Uri.parse("android.resource://com.example.altayeb.myapplication2/drawable/twenty1");
                break;
            }
            case 8:{
                uri = Uri.parse("android.resource://com.example.altayeb.myapplication2/drawable/twenty2");
                break;
            }
            case 9:{
                uri = Uri.parse("android.resource://com.example.altayeb.myapplication2/drawable/five1");
                break;
            }
            case 10:{
                uri = Uri.parse("android.resource://com.example.altayeb.myapplication2/drawable/five2");
                break;
            }
        }
        try {
            stream = getContentResolver().openInputStream(uri);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        bmpFactoryOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;

        bmp = BitmapFactory.decodeStream(stream, null, bmpFactoryOptions);
        tmpl = new Mat();
        Utils.bitmapToMat(bmp, tmpl);
        match_method = Imgproc.TM_CCOEFF_NORMED;

       // Imgproc.cvtColor(source,gray1,Imgproc.COLOR_RGB2GRAY);
        Imgproc.cvtColor(tmpl,gray2,Imgproc.COLOR_RGB2GRAY);
       // outputimage=new Mat(mRgba.cols() - gray2.cols() + 1,mRgba.rows() - gray2.rows() + 1,CvType.CV_8UC1);
            outputimage=new Mat(source.cols() - gray2.cols() + 1,source.rows() - gray2.rows() + 1,CvType.CV_8UC1);
       Imgproc.matchTemplate(source,gray2,outputimage,match_method);
      //  Core.normalize(outputimage, outputimage, 0, 1, Core.NORM_MINMAX, -1, new Mat());

        Core.MinMaxLocResult mmr = Core.minMaxLoc(outputimage);
        matchLoc = mmr.maxLoc;
        double minMatchQiality = 0.68;
        if(mmr.maxVal>=minMatchQiality){
           Imgproc.rectangle(mRgba, matchLoc, new Point(matchLoc.x + gray2.cols(), matchLoc.y + gray2.rows()), new Scalar(255, 0, 0));
            switch (count) {
                case 1:{ md50.start();
                break;}
                case 2:{md50.start();
                    break;}
                case 3:{
                    md2.start();
                    break;
                }
                case 4:{
                    md2.start();
                    break;
                }

                 case 5:{
                    md10.start();
                    break;
                }
                case 6:{
                    md10.start();
                    break;
                }

                case 7:{
                    md20.start();
                    break;
                }
                case 8:{
                    md20.start();
                    break;
                }
                case 9:{
                    md5.start();
                    break;
                }
                case 10:{
                    md5.start();
                    break;
                }
            }}
        else    {
            if(count>=10){count=1;}
            else {count++;}
        }
       // return  mRgba;
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id=item.getItemId();
        if(id==R.id.about){
            Intent i2 = new Intent(getApplicationContext(),About.class);
            startActivity(i2);
        }
        if(id==R.id.help){
            Intent i3 = new Intent(getApplicationContext(),Help.class);
            startActivity(i3);
        }

        return super.onOptionsItemSelected(item);
    }

    public class CustomizableCameraView extends JavaCameraView {

        public CustomizableCameraView(Context context, AttributeSet attrs) {
            super(context, attrs);
        }

        public void setPreviewFPS(double min, double max){
            Camera.Parameters params = mCamera.getParameters();
            params.setPreviewFpsRange((int)(min*1000), (int)(max*1000));
            mCamera.setParameters(params);
        }
    }
}


问:
ASP.NET MVC2 Reading JSON data with controller
I have problems to receive json values from my javascript/jQuery request to my controller.

MyClass looks like the following:

```<code>function MyClass() {
    this.MyString = null;
    this.MyInt = null;
    this.Subs = null;
}
</code>```

My Request looks like the following:

```<code>var testData1 = new MyClass();
testData1.MyInt = 1234;
testData1.MyString = "abcDEF";
testData1.Subs = new Array();
var testData2 = new MyClass();
testData2.MyInt = 5678;
testData2.MyString = "GHIjkl";
testData1.Subs.push(testData2);
var jsonData = JSON.stringify(testData1);
var self = this;
$.ajax({
    url: '/Home/Request',
    type: 'POST',
    dataType: 'json',
    data: jsonData,
    contentType: 'application/json; charset=utf-8',
    success: function (x) {
        self.ParseResult(x);
    }
});
</code>```

Now I have a controller:

```<code>public JsonResult Request(MyClass myObj)
{
    var answer = ...
    return Json(answer, JsonRequestBehavior.DenyGet);
}
</code>```

With the following class:

```<code>public class  MyClass
{
    public string MyString { get; set; }
    public int MyInt { get; set; }
    public List<MyClass> Subs { get; set; }
}
</code>```

All names in jsonData are exactly the same like in my class "MyClass". But there are no values in myObj.

Where is the Problem. Is there anything I can do to get this mapping working correctly?

Thank you very much in advance,

Chris

UPDATE:

Thank you for your repley. I have used the JavascriptSerializer. But I have the problem, that myString is null:

```<code>public JsonResult Data(string myString)
{
    JavaScriptSerializer serializer = new JavaScriptSerializer();
    var data = serializer.Deserialize<MyClass>(myString);
var answer = ...
    return Json(answer, JsonRequestBehavior.DenyGet);
}
</code>```

Where is the value? Should I take the value from the request-data?

@Dave Ward

You second solution is working. But I have a problem with the subs.

```<code>var testData1 = new MyClass();
testData1.MyInt = 1234;
testData1.MyString = "abcDEF";
testData1.Subs = new Array();
for (var i = 0; i < 10; i++) {
    var testData2 = new MyClass();
    testData2.MyInt = i;
    testData2.MyString = "abcDEF";
    testData1.Subs.push(testData2);
}
</code>```

I get 10 Subs in my controller, but all are empty. What can I do?

@Dave Ward, @ALL

Using the traditional settings my 10 Subs are bot empty, they are not there. Subs count is 0 (not NULL).
I tried to change the Subs Type from List to IEnumerable but that didn't help.
Do you know anything else I can do to get Subs filled in my controller?

Ok, thank you Dave Ward, I will use the JSON method.

For somebody else having the same problem this controller code could be from help:

```<code>MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(myString));
var serializer = new DataContractJsonSerializer(typeof(MyClass));
MyClass se = serializer.ReadObject(ms) as MyClass;
ms.Close();
</code>```

答:
You can take a look Omar Al Zabir's article about json, xml request and response handling he  provided a really good solution for solving this common situations.

Create REST API using ASP.NET MVC that speaks both Json and plain Xml

Body:
I have problems to receive json values from my javascript/jQuery request to my controller.

MyClass looks like the following:

function MyClass() {
    this.MyString = null;
    this.MyInt = null;
    this.Subs = null;
}

My Request looks like the following:

var testData1 = new MyClass();
testData1.MyInt = 1234;
testData1.MyString = "abcDEF";
testData1.Subs = new Array();
var testData2 = new MyClass();
testData2.MyInt = 5678;
testData2.MyString = "GHIjkl";
testData1.Subs.push(testData2);
var jsonData = JSON.stringify(testData1);
var self = this;
$.ajax({
    url: '/Home/Request',
    type: 'POST',
    dataType: 'json',
    data: jsonData,
    contentType: 'application/json; charset=utf-8',
    success: function (x) {
        self.ParseResult(x);
    }
});

Now I have a controller:

public JsonResult Request(MyClass myObj)
{
    var answer = ...
    return Json(answer, JsonRequestBehavior.DenyGet);
}

With the following class:

public class  MyClass
{
    public string MyString { get; set; }
    public int MyInt { get; set; }
    public List<MyClass> Subs { get; set; }
}

All names in jsonData are exactly the same like in my class "MyClass". But there are no values in myObj.

Where is the Problem. Is there anything I can do to get this mapping working correctly?

Thank you very much in advance,

Chris

UPDATE:

Thank you for your repley. I have used the JavascriptSerializer. But I have the problem, that myString is null:

public JsonResult Data(string myString)
{
    JavaScriptSerializer serializer = new JavaScriptSerializer();
    var data = serializer.Deserialize<MyClass>(myString);
var answer = ...
    return Json(answer, JsonRequestBehavior.DenyGet);
}

Where is the value? Should I take the value from the request-data?

@Dave Ward

You second solution is working. But I have a problem with the subs.

var testData1 = new MyClass();
testData1.MyInt = 1234;
testData1.MyString = "abcDEF";
testData1.Subs = new Array();
for (var i = 0; i < 10; i++) {
    var testData2 = new MyClass();
    testData2.MyInt = i;
    testData2.MyString = "abcDEF";
    testData1.Subs.push(testData2);
}

I get 10 Subs in my controller, but all are empty. What can I do?

@Dave Ward, @ALL

Using the traditional settings my 10 Subs are bot empty, they are not there. Subs count is 0 (not NULL).
I tried to change the Subs Type from List to IEnumerable but that didn't help.
Do you know anything else I can do to get Subs filled in my controller?

Ok, thank you Dave Ward, I will use the JSON method.

For somebody else having the same problem this controller code could be from help:

MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(myString));
var serializer = new DataContractJsonSerializer(typeof(MyClass));
MyClass se = serializer.ReadObject(ms) as MyClass;
ms.Close();


问:
Insert into ... values ( SELECT ... FROM ... )
I am trying to INSERT INTO a table using the input from another table. Although this is entirely feasible for many database engines, I always seem to struggle to remember the correct syntax for the SQL engine of the day (MySQL, Oracle, SQL Server, Informix, and DB2).

Is there a silver-bullet syntax coming from an SQL standard (for example, SQL-92) that would allow me to insert the values without worrying about the underlying database?

答:
If you go the INSERT VALUES route to insert multiple rows, make sure to delimit the VALUES into sets using parentheses, so:    </p>

```<code>INSERT INTO `receiving_table`
  (id,
  first_name,
  last_name)
VALUES
  (1002,'Charles','Babbage'),
  (1003,'George', 'Boole'),
  (1001,'Donald','Chamberlin'),
  (1004,'Alan','Turing'),
  (1005,'My','Widenius');
</code>```

<p>Otherwise MySQL objects that "Column count doesn't match value count at row 1", and you end up writing a trivial post when you finally figure out what to do about it. </p>

Body:
If you go the INSERT VALUES route to insert multiple rows, make sure to delimit the VALUES into sets using parentheses, so:

INSERT INTO `receiving_table`
  (id,
  first_name,
  last_name)
VALUES
  (1002,'Charles','Babbage'),
  (1003,'George', 'Boole'),
  (1001,'Donald','Chamberlin'),
  (1004,'Alan','Turing'),
  (1005,'My','Widenius');

Otherwise MySQL objects that "Column count doesn't match value count at row 1", and you end up writing a trivial post when you finally figure out what to do about it.


问:
.NET Standard Class Library in .NET Framework 4.7 project
I'd like to share code between a .NET Framework 4.7 solution and a .NET Core solution for use in AWS Lambda.

I have created a .NET Standard 1.6 class library project and have moved some code from the .NET Framework 4.7 solution into this project in order to share it.

All is working fine except for one thing - the code is for a DTO class that is serialized by the BinaryFormatter in the .NET solution.

For example:

```<code>[Serializable]
public class BillableOptionalOperationDto
{
    public string OperationDescription { get; set; }
    public string Note { get; set; }
    public decimal UnitPriceIncGst { get; set; }
}
</code>```

I have created a polyfill so that the code compiles in the .NET Standard project.

```<code>namespace System
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Delegate)]
    public class SerializableAttribute : Attribute
    {
    }
}
</code>```

The .NET Standard project is published as a Nuget package to our Nuget Server in TeamCity.

In the .NET Framework solution, I (quite rightly) get this error:

Error CS0433  The type 'SerializableAttribute' exists in both
  'AutoGuru.Shared.Quoting, Version=1.0.0.0, Culture=neutral,
  PublicKeyToken=null' and 'mscorlib, Version=4.0.0.0, Culture=neutral,
  PublicKeyToken=b77a5c561934e089'

Is there a way to use the BinaryFormatter on a class in a .NET Standard 1.6 class library?

答:
You won't be able to serialize using a BinaryFormatter using the .NET Core runtime but you can at least cross compile using this nuget package

https://www.nuget.org/packages/System.Runtime.Serialization.Formatters/

Note though that assembly binding with .NET Standard is a total mess and, without a ton of assembly redirects, your code will compile fine but throw assembly not found exceptions at runtime. Supposedly .NET Standard 2.0 will fix that but I'm not holding my breath.

Body:
I'd like to share code between a .NET Framework 4.7 solution and a .NET Core solution for use in AWS Lambda.

I have created a .NET Standard 1.6 class library project and have moved some code from the .NET Framework 4.7 solution into this project in order to share it.

All is working fine except for one thing - the code is for a DTO class that is serialized by the BinaryFormatter in the .NET solution.

For example:

[Serializable]
public class BillableOptionalOperationDto
{
    public string OperationDescription { get; set; }
    public string Note { get; set; }
    public decimal UnitPriceIncGst { get; set; }
}

I have created a polyfill so that the code compiles in the .NET Standard project.

namespace System
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Delegate)]
    public class SerializableAttribute : Attribute
    {
    }
}

The .NET Standard project is published as a Nuget package to our Nuget Server in TeamCity.

In the .NET Framework solution, I (quite rightly) get this error:

Error CS0433  The type 'SerializableAttribute' exists in both
  'AutoGuru.Shared.Quoting, Version=1.0.0.0, Culture=neutral,
  PublicKeyToken=null' and 'mscorlib, Version=4.0.0.0, Culture=neutral,
  PublicKeyToken=b77a5c561934e089'

Is there a way to use the BinaryFormatter on a class in a .NET Standard 1.6 class library?


问:
Google Speech Recognition Streaming API via curl
I would like to use Googles Speech Recognition API via the streaming method, so I stream my file and get the text in real time back. That is needed so I know when something was said in the audio file. The problem is, that I don't use any of the languages Google provides an SDK for and their documentation doesn't show how to make such a request without their SDKs.

Does someone know how to do it?

答:
The Streaming support for Google Cloud Speech Recognition API is available only through gRPC, the reason being it is tough or almost impossible to implement streaming with just plain old REST APIs.

Streaming Speech Recognition allows you to stream audio to the Cloud
  Speech API and receive a stream speech recognition results in real
  time as the audio is processed. See also the audio limits for
  streaming speech recognition requests. Streaming speech recognition is
  available via gRPC only.

Having said that the Cloud Speech API Client library is available in the following languages and covers a decent spectrum of common developer languages.

C#

Go

Java

Node.JS

PHP

Python

Ruby

Since you haven't mentioned the language you're using, and if you do use a language other than one from the above list, you could very well look into the client library source code (for a different language) and how it uses gRPC to do the streaming and implement it in the language you're using.

Again the only limitation now is a language which gRPC has support for. Compared to the above list, gRPC has support for C++ and Objective C. So if you are using one of them, this could very well be a viable option albeit with a lot of digging into the client library codebase.

I do agree that having support for C++ and/or ObjectiveC in the google client libraries will be really useful for developers.

UPDATE:
On a quick search, I found this github repo which has few samples on how to call the Google Cloud Speech API using C++ (still not sure if that is the language you're using though).


问:
Cannot call value of non-function type 'ThreadConfined.Type' - Swift 4.0
I upgraded a project I am working on to Swift 4.0.  After doing so I realized this was not the best idea.  I've fixed all bugs but one and can't figure it out.  I have installed RealmSwift in my project and am getting the following error in one of the Realm files.

ERROR: Cannot call value of non-function type 'ThreadConfined.Type'

```<code> public init(to threadConfined: Confined) {
    let bridged = (threadConfined as! AssistedObjectiveCBridgeable).bridged
    swiftMetadata = bridged.metadata
    type = type(of: threadConfined).  ****ERROR CALLED ON THIS LINE****
    objectiveCReference = RLMThreadSafeReference(threadConfined: bridged.objectiveCValue as! RLMThreadConfined)
}
</code>```

Lesson learned about upgrading too soon.  I was hoping someone could give me a hand so I can start developing again.  Any thoughts?

答: Realm's master branch now contains support for Swift 4 and beta 1 of Xcode 9 (#5006). Using a build of Realm Swift from source should get you up and running.</p>

Body:
I upgraded a project I am working on to Swift 4.0.  After doing so I realized this was not the best idea.  I've fixed all bugs but one and can't figure it out.  I have installed RealmSwift in my project and am getting the following error in one of the Realm files.

ERROR: Cannot call value of non-function type 'ThreadConfined.Type'

 public init(to threadConfined: Confined) {
    let bridged = (threadConfined as! AssistedObjectiveCBridgeable).bridged
    swiftMetadata = bridged.metadata
    type = type(of: threadConfined).  ****ERROR CALLED ON THIS LINE****
    objectiveCReference = RLMThreadSafeReference(threadConfined: bridged.objectiveCValue as! RLMThreadConfined)
}

Lesson learned about upgrading too soon.  I was hoping someone could give me a hand so I can start developing again.  Any thoughts?


问:
How to access custom array in custom list view class
So I have a List of type "Item_Array_Class" on My homescreen

Here is that class:

```<code>public class Item_Array_Class {
    String vendor;
    String category;
    String price;
    Bitmap item_Image;
    int Index;

    public Item_Array_Class(String vendor, String category, String price, Bitmap item_Image, int Index) {
        this.vendor = vendor;
        this.category = category;
        this.price = price;
        this.item_Image = item_Image;
        this.Index = Index;
    }

    public String get_vendor() {
        return vendor;
    }

    public String get_category() {
        return category;
    }

    public String get_price() {
        return price;
    }

    public Bitmap get_Image() {
        return item_Image;
    }

    public int get_Index() { return Index; }
    }
</code>```

I want to access this List while making my custom listview so that I can pull out the Image and Vendor from the array and display them since the custom view is just an ImageView and a textView.

So here's the code I've got for my custom list view class:`

```<code>class custom_list_view extends ArrayAdapter
 {
 public custom_list_view(Context context, HomeScreen.Item_Array_Class[]
item_array)
{
    super(context, R.layout.custom_list_view, item_array);
}

@Override
public View getView(int position, View convertView, ViewGroup parent)
{
    LayoutInflater inflater = LayoutInflater.from(getContext());
    View customView_Var = inflater.inflate(R.layout.custom_list_view, parent, false);

    TextView item_title_TV = (TextView) customView_Var.findViewById(R.id.custom_list_title);
    ImageView item_image = (ImageView) customView_Var.findViewById(R.id.custom_list_image);

    //get the data from the array here <-------
    String vendor = item_array.get(position).get_Vendor(); //Cannot resolve symbol 'item_array'

    item_title_TV.setText();
    item_image.setImageBitmap();

    return customView_Var;
}
}
</code>```

What I was hoping to do was somehow go something like:

```<code>String vendor = item_array.get(position).get_Vendor();
</code>```

however, I can't seem to access the item_array I pass it in the constructor. I can just call getItem(position) but then I have no way to only get the Image and vendor. Any help would be greatly appreciated.

TL;DR: how can I access my HomeScreens custom List within the class for my custom list view to pull the Image and Vendor from each slot in the list to put on the Image View and Text view for each item in the ListView.

答:
Do this...

```<code>class custom_list_view extends ArrayAdapter
 {
private List<HomeScreen.Item_Array_Class> item_array
item_array
 public custom_list_view(Context context, List<HomeScreen.Item_Array_Class>
item_array)
{
    super(context, R.layout.custom_list_view, item_array);
this.item_array = item_array;
}
</code>```

Now try ti get

```<code>item_array.get(position)
</code>```

Body:
So I have a List of type "Item_Array_Class" on My homescreen

Here is that class:

public class Item_Array_Class {
    String vendor;
    String category;
    String price;
    Bitmap item_Image;
    int Index;

    public Item_Array_Class(String vendor, String category, String price, Bitmap item_Image, int Index) {
        this.vendor = vendor;
        this.category = category;
        this.price = price;
        this.item_Image = item_Image;
        this.Index = Index;
    }

    public String get_vendor() {
        return vendor;
    }

    public String get_category() {
        return category;
    }

    public String get_price() {
        return price;
    }

    public Bitmap get_Image() {
        return item_Image;
    }

    public int get_Index() { return Index; }
    }

I want to access this List while making my custom listview so that I can pull out the Image and Vendor from the array and display them since the custom view is just an ImageView and a textView.

So here's the code I've got for my custom list view class:`

class custom_list_view extends ArrayAdapter
 {
 public custom_list_view(Context context, HomeScreen.Item_Array_Class[]
item_array)
{
    super(context, R.layout.custom_list_view, item_array);
}

@Override
public View getView(int position, View convertView, ViewGroup parent)
{
    LayoutInflater inflater = LayoutInflater.from(getContext());
    View customView_Var = inflater.inflate(R.layout.custom_list_view, parent, false);

    TextView item_title_TV = (TextView) customView_Var.findViewById(R.id.custom_list_title);
    ImageView item_image = (ImageView) customView_Var.findViewById(R.id.custom_list_image);

    //get the data from the array here <-------
    String vendor = item_array.get(position).get_Vendor(); //Cannot resolve symbol 'item_array'

    item_title_TV.setText();
    item_image.setImageBitmap();

    return customView_Var;
}
}

What I was hoping to do was somehow go something like:

String vendor = item_array.get(position).get_Vendor();

however, I can't seem to access the item_array I pass it in the constructor. I can just call getItem(position) but then I have no way to only get the Image and vendor. Any help would be greatly appreciated.

TL;DR: how can I access my HomeScreens custom List within the class for my custom list view to pull the Image and Vendor from each slot in the list to put on the Image View and Text view for each item in the ListView.

Body:
Do this...

class custom_list_view extends ArrayAdapter
 {
private List<HomeScreen.Item_Array_Class> item_array
item_array
 public custom_list_view(Context context, List<HomeScreen.Item_Array_Class>
item_array)
{
    super(context, R.layout.custom_list_view, item_array);
this.item_array = item_array;
}

Now try ti get

item_array.get(position)


问:
Override AutoSize for derived Label Control in C#
I am trying to extend the System.Windows.Forms.Label class to support vertically drawn text.  I do this by creating a new property called MyLabelOrientation that the user can set to Horizontal or Vertical.  When the user changes this setting, the values for width and height are swapped to resize the control to its new orientation.  Finally, I override the OnPaint function to draw my Label.

I would like to extend the AutoSize property for this control as well so that my Label will auto-size to the text it contains.  For the horizontal orientation, the base functionality implements this for me.  For the vertical orientation, I create a Graphics object and set the height of the control to the width of the SizeF object returned from Graphics.MeasureString(Text, Font).  You can see an example of the code I'm using below.

```<code>using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.ComponentModel.Design;
using System.Windows.Forms.Design;

public class MyLabel : Label
{
    public enum MyLabelOrientation {Horizontal, Vertical};
    protected MyLabelOrientation m_orientation = MyLabelOrientation.Horizontal;

    [Category("Appearance")]
    public virtual MyLabelOrientation Orientation
    {
        get { return m_orientation; }
        set
        {
            m_orientation = value;
            int temp = Height;
            Width = Height;
            Height = temp;
            Refresh();
        }
    }

    private Size ResizeLabel()
    {
        Graphics g = Graphics.FromHwnd(this.Handle);
        SizeF newSize = g.MeasureString(Text, Font);
        if (m_orientation == MyLabelOrientation.Horizontal)
            Width = (int)newSize.Width;
        else
            Height = (int)newSize.Width;
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        Brush textBrush = new SolidBrush(this.ForeColor);

        if (m_orientation == LabelOrientation.Vertical)
        {
            e.Graphics.TranslateTransform(Width, 0);
            e.Graphics.RotateTransform(90);
            e.Graphics.DrawString(Text, Font, textBrush, Padding.Left, Padding.Top);
        }
        else
        {
            base.OnPaint(e);
        }
    }
}
</code>```

However, setting AutoSize to true seems to prevent and/or override any changes to the size of the control.  This means that I can't change the width or height when I want to change the Label's orientation.  I'm wondering if this behavior can be overridden, so that I can test whether AutoSize is set, and then adjust the size of the control according to it's orientation.

答:
I have not done this before, I believe you can theoretically override a property declaration (via the new keyword) and check the orientation before proceeding:

```<code>override public bool AutoSize
{
   set
   {
      if( /* orientation is horizontal */ )
      {
          base.AutoSize = value;
      }
      else
      {
          // do what you need to do
      }
   }
}
</code>```

Body:
I am trying to extend the System.Windows.Forms.Label class to support vertically drawn text.  I do this by creating a new property called MyLabelOrientation that the user can set to Horizontal or Vertical.  When the user changes this setting, the values for width and height are swapped to resize the control to its new orientation.  Finally, I override the OnPaint function to draw my Label.

I would like to extend the AutoSize property for this control as well so that my Label will auto-size to the text it contains.  For the horizontal orientation, the base functionality implements this for me.  For the vertical orientation, I create a Graphics object and set the height of the control to the width of the SizeF object returned from Graphics.MeasureString(Text, Font).  You can see an example of the code I'm using below.

using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.ComponentModel.Design;
using System.Windows.Forms.Design;

public class MyLabel : Label
{
    public enum MyLabelOrientation {Horizontal, Vertical};
    protected MyLabelOrientation m_orientation = MyLabelOrientation.Horizontal;

    [Category("Appearance")]
    public virtual MyLabelOrientation Orientation
    {
        get { return m_orientation; }
        set
        {
            m_orientation = value;
            int temp = Height;
            Width = Height;
            Height = temp;
            Refresh();
        }
    }

    private Size ResizeLabel()
    {
        Graphics g = Graphics.FromHwnd(this.Handle);
        SizeF newSize = g.MeasureString(Text, Font);
        if (m_orientation == MyLabelOrientation.Horizontal)
            Width = (int)newSize.Width;
        else
            Height = (int)newSize.Width;
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        Brush textBrush = new SolidBrush(this.ForeColor);

        if (m_orientation == LabelOrientation.Vertical)
        {
            e.Graphics.TranslateTransform(Width, 0);
            e.Graphics.RotateTransform(90);
            e.Graphics.DrawString(Text, Font, textBrush, Padding.Left, Padding.Top);
        }
        else
        {
            base.OnPaint(e);
        }
    }
}

However, setting AutoSize to true seems to prevent and/or override any changes to the size of the control.  This means that I can't change the width or height when I want to change the Label's orientation.  I'm wondering if this behavior can be overridden, so that I can test whether AutoSize is set, and then adjust the size of the control according to it's orientation.

Body:
I have not done this before, I believe you can theoretically override a property declaration (via the new keyword) and check the orientation before proceeding:

override public bool AutoSize
{
   set
   {
      if( /* orientation is horizontal */ )
      {
          base.AutoSize = value;
      }
      else
      {
          // do what you need to do
      }
   }
}


问:
What is the `g` in angular selectors for?
Some ngx-charts components have a g in the selector like this:

```<code>selector: 'g[ngx-charts-line]'
</code>```

What is the g for?

答: g is just the line element's tag name which ngx-charts used in a line chart.

Body:
Some ngx-charts components have a g in the selector like this:

selector: 'g[ngx-charts-line]'

What is the g for?


问:
Pass Value to the Same Page
I have a request.aspx page which displays some fields. I have a copy button which actually copies values for the page into a new request.aspx page.so the user can submit without enter all the info again.

This involves, passing a flag to request.aspx which decides, whether its a new request or loading an existing one. Now I am wondering what are the better ways to pass this flag to the same page.

Can we use QueryStringor Session or ViewState(since its the same page) or a hidden field that stores the request ID so the copy page can pull up info based on request ID.
I am not sure which is the preferred and best way to do this.

答:
Query String is pass parameter from one page to another.

Session is to store value in server memory for each of the user access so each session value will be unique for each PC

ViewState is to store information in the hidden field of the page, so when you close the browser then information will loss.

My suggestion for you is query string, thank you.

Title: Pass Value to the Same Page


问:
Unable to build/publish Azure Data Factory application
Every Data Factory application I try to create in visual studio 2015, even the sample ones, are unable to build or publish due to:

"Object reference not set to an instance of an object." error on every .json file.

Is there some important configuration I'm missing or some dependencies I need to add to the project? Thanks

答:
I was facing the same issue and it was because of the fips Algorithm policy enabled on the machine.

Resolution:

Disable FIPS Algoirthm policy via regedit and restart the Visual Studio.

Location:

HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Lsa\FipsAlgorithmPolicy