问:
How do I run two while True statements in python?
I am trying to make a door swipe card system in Python for my Raspberry Pi. I broke the program into two: A Door Alarm and a Card Swipe Recording system. The two programs work individually but how do I combine the two programs into one python file? I've tried threading but it doesn't seem to work.

Below are the programs:
1.) Door Alarm: If door is left open for a certain duration, an led will blink, then an alarm will ring

```<code>import time
import RPi.GPIO as gpio

led = 37
buzzer = 11
door = 16

gpio.setmode(gpio.BOARD)
gpio.setwarnings(False)
gpio.setup(buzzer, gpio.OUT)
gpio.setup(led, gpio.OUT)
gpio.setup(door, gpio.IN, pull_up_down=gpio.PUD_UP)

def blink(buzzer):
    gpio.output(buzzer, True)
    time.sleep(0.1)
    gpio.output(buzzer, False)
    time.sleep(0.1)
    return

def blink(led):
    gpio.output(led, True)
    time.sleep(1)
    gpio.output(led, False)
    time.sleep(1)
    return

while True:
    if gpio.input(door):
        time.sleep(3)
        for i in range(0,5):
                blink(led)
        for i in range (0,5):
                blink(buzzer)
    else:
        gpio.output(buzzer, False)

gpio.cleanup()
</code>```

2.) Card Swipe Recording System: When someone swipes their card, the led blinks and a picture is taken

```<code>import datetime
import time
import os
import RPi.GPIO as gpio

led = 37
t = datetime.datetime.now()

gpio.setmode(gpio.BOARD)
gpio.setwarnings(False)
gpio.setup(led, gpio.OUT)

def blink(led):
    gpio.output(led, True)
    time.sleep(0.1)
    gpio.output(led, False)
    time.sleep(0.1)

while True:
    card = raw_input()
    f = open("Laptop Sign Out" + '.txt', 'a')
    f.write("OneCard Number: " + card[1:10] + " Time: " + t.strftime("%m-%d-%Y %H:%M:%S"))
    f.write('\n')
    f.write(';')
    f.write('\n')
    f.close()
    time.sleep(1)
    for i in range(0,3):
        blink(led)
    os.system('fswebcam ~/Desktop/Photos/%H%M%S.jpeg')
    time.sleep(3)

gpio.cleanup()
</code>```

(UPDATE) Also, below is my attempt at threading:

```<code>import time
import RPi.GPIO as gpio
import os
import datetime
from threading import Thread

led = 37
buzzer = 11
door = 16
t = datetime.datetime.now()

gpio.setmode(gpio.BOARD)
gpio.setwarnings(False)
gpio.setup(buzzer, gpio.OUT)
gpio.setup(led, gpio.OUT)
gpio.setup(door, gpio.IN, pull_up_down=gpio.PUD_UP)

def blink(buzzer):
    gpio.output(buzzer, True)
    time.sleep(0.1)
    gpio.output(buzzer, False)
    time.sleep(0.1)
    return

def blink(led):
    gpio.output(led, True)
    time.sleep(1)
    gpio.output(led, False)
    time.sleep(1)
    return

def doorsensor():
    while True:
        if gpio.input(door):
            time.sleep(3)
            for i in range(0,5):
                    blink(led)
            for i in range (0,5):
                    blink(buzzer)
        else:
            gpio.output(buzzer, False)

def cardreader():
    while True:
        card = raw_input()
        f = open("Laptop Sign Out" + '.txt', 'a')
        f.write("OneCard Number: " + card[1:10] + " Time: " + t.strftime("%m-%d-%Y %H:%M:%S"))
        f.write('\n')
        f.write(';')
        f.write('\n')
        f.close()
        time.sleep(1)
        for i in range(0,3):
            blink(led)
        os.system('fswebcam ~/Desktop/Photos/%H%M%S.jpeg')
        time.sleep(3)

f1 = Thread(target = doorsensor())
f2 = Thread(target = cardreader())

f2.start()
f1.start()

gpio.cleanup()
</code>```

答:
If you are attempting to run these two programs simultaneously, then you will have to use either threading or multiprocessing, which you say you have attempted. If you have, may we see your attempt as we may be then able to help you with your issue there.

One other issue is that all of your methods are named Blink, which is not allowed in Python, in python all of your methods should have different names.

Edit: For threading make sure to type threading.Thread(target = target) as your code

Body:
I am trying to make a door swipe card system in Python for my Raspberry Pi. I broke the program into two: A Door Alarm and a Card Swipe Recording system. The two programs work individually but how do I combine the two programs into one python file? I've tried threading but it doesn't seem to work.

Below are the programs:
1.) Door Alarm: If door is left open for a certain duration, an led will blink, then an alarm will ring

import time
import RPi.GPIO as gpio

led = 37
buzzer = 11
door = 16

gpio.setmode(gpio.BOARD)
gpio.setwarnings(False)
gpio.setup(buzzer, gpio.OUT)
gpio.setup(led, gpio.OUT)
gpio.setup(door, gpio.IN, pull_up_down=gpio.PUD_UP)

def blink(buzzer):
    gpio.output(buzzer, True)
    time.sleep(0.1)
    gpio.output(buzzer, False)
    time.sleep(0.1)
    return

def blink(led):
    gpio.output(led, True)
    time.sleep(1)
    gpio.output(led, False)
    time.sleep(1)
    return

while True:
    if gpio.input(door):
        time.sleep(3)
        for i in range(0,5):
                blink(led)
        for i in range (0,5):
                blink(buzzer)
    else:
        gpio.output(buzzer, False)

gpio.cleanup()

2.) Card Swipe Recording System: When someone swipes their card, the led blinks and a picture is taken

import datetime
import time
import os
import RPi.GPIO as gpio

led = 37
t = datetime.datetime.now()

gpio.setmode(gpio.BOARD)
gpio.setwarnings(False)
gpio.setup(led, gpio.OUT)

def blink(led):
    gpio.output(led, True)
    time.sleep(0.1)
    gpio.output(led, False)
    time.sleep(0.1)

while True:
    card = raw_input()
    f = open("Laptop Sign Out" + '.txt', 'a')
    f.write("OneCard Number: " + card[1:10] + " Time: " + t.strftime("%m-%d-%Y %H:%M:%S"))
    f.write('\n')
    f.write(';')
    f.write('\n')
    f.close()
    time.sleep(1)
    for i in range(0,3):
        blink(led)
    os.system('fswebcam ~/Desktop/Photos/%H%M%S.jpeg')
    time.sleep(3)

gpio.cleanup()

(UPDATE) Also, below is my attempt at threading:

import time
import RPi.GPIO as gpio
import os
import datetime
from threading import Thread

led = 37
buzzer = 11
door = 16
t = datetime.datetime.now()

gpio.setmode(gpio.BOARD)
gpio.setwarnings(False)
gpio.setup(buzzer, gpio.OUT)
gpio.setup(led, gpio.OUT)
gpio.setup(door, gpio.IN, pull_up_down=gpio.PUD_UP)

def blink(buzzer):
    gpio.output(buzzer, True)
    time.sleep(0.1)
    gpio.output(buzzer, False)
    time.sleep(0.1)
    return

def blink(led):
    gpio.output(led, True)
    time.sleep(1)
    gpio.output(led, False)
    time.sleep(1)
    return

def doorsensor():
    while True:
        if gpio.input(door):
            time.sleep(3)
            for i in range(0,5):
                    blink(led)
            for i in range (0,5):
                    blink(buzzer)
        else:
            gpio.output(buzzer, False)

def cardreader():
    while True:
        card = raw_input()
        f = open("Laptop Sign Out" + '.txt', 'a')
        f.write("OneCard Number: " + card[1:10] + " Time: " + t.strftime("%m-%d-%Y %H:%M:%S"))
        f.write('\n')
        f.write(';')
        f.write('\n')
        f.close()
        time.sleep(1)
        for i in range(0,3):
            blink(led)
        os.system('fswebcam ~/Desktop/Photos/%H%M%S.jpeg')
        time.sleep(3)

f1 = Thread(target = doorsensor())
f2 = Thread(target = cardreader())

f2.start()
f1.start()

gpio.cleanup()


来源: stackexchange

问:
MVVM with Android Architecture Components
I'm exploring the new Android Architecture Components and looking to implement it into an Android app. I am firmillair with MVVM as I use the paradigm on iOS development. Having read through the Android Architecture Components guide, provided by Google: https://developer.android.com/topic/libraries/architecture/guide.html

I have just a few questions...

In the above mentioned guide, Google use the UserRepository class that access these web service API - they go on to make this class a Singleton which is probably fine, if there were only ever one screen on the app that needed data from a REST API.

My concern, is this; it seems Google advocate the need to create a repository class on a per-ViewModel basis. This sounds very wrong to me, in having so many Singlton classes in the app. If we were to have 10 screens, with ten ViewModels - each needing its own Repository module - we then have ten singletons in our app. From an iOS dev perspective, this is wrong to have so many.

The solution to this, would be to have one mediator (Repository) class, that has public methods, exposing the API to get data from a REST API. The Web service part, would be in its own class. That way, we have a decent separation of concerns.

Is it best practice, to have one repository class, per, ViewModel - or to have one per app? I'm not 100% sure on this.

Lastly, I have the same concern when it comes to Room- is Google saying we create a DB on a per ViewModel bases or just one DB per app?

答:
I don't think the architecture guide suggests to create a separate repository class for each ViewModel. In the example that is shown Google uses a library called Dagger to inject the singleton repository class into the ViewModel. It is normally best practice to split repositories (or managers) on functionality. UserRepository is responsible for all user related api calls for example.

If you turn this repository into a singleton that you can inject in any ViewModel, any ViewModel now has access to that specific repository.

After quickly looking into Room I found this little snippet (link):

Note: You should follow the singleton design pattern when instantiating an AppDatabase object, as each RoomDatabase instance is fairly expensive, and you rarely need access to multiple instances.

This to me means that you can implement the RoomDatabase much in the same way you can use your repository classes. Simply inject them as a singleton into your ViewModel so you don't need to have multiple instances of the same database.

ContentLicense: CC BY-SA 3.0


问:
Babel unexpected token import when running mocha tests
The solutions offered in other related questions, such as including the proper presets (es2015) in .babelrc, are already implemented in my project.

I have two projects (lets call them A and B) which both use ES6 module syntax.  In Project A, I'm importing Project B which is installed via npm and lives in the node_modules folder. When I run my test suite for Project A, I'm getting the error:

SyntaxError: Unexpected token import

Which is preceded by this alleged erroneous line of code from Project B:

(function (exports, require, module, __filename, __dirname) { import
  createBrowserHistory from 'history/lib/createBrowserHistory';

The iife appears to be something npm or possibly babel related since my source file only contains "import createBrowserHistory from 'history/lib/createBrowserHistory'; The unit tests in Project B's test suite runs fine, and if I remove Project B as a dependency from Project A, my test suite then (still using es6 imports for internal project modules) works just fine.

Full Stack Trace:

```<code> SyntaxError: Unexpected token import
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:374:25)
    at Module._extensions..js (module.js:405:10)
    at Object.require.extensions.(anonymous function) [as .js] (/ProjectA/node_modules/babel-register/lib/node.js:138:7)
    at Module.load (module.js:344:32)
    at Function.Module._load (module.js:301:12)
    at Module.require (module.js:354:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (actionCreators.js:4:17)
    at Module._compile (module.js:398:26)
    at loader (/ProjectA/node_modules/babel-register/lib/node.js:130:5)
    at Object.require.extensions.(anonymous function) [as .js] (/ProjectA/node_modules/babel-register/lib/node.js:140:7)
    at Module.load (module.js:344:32)
    at Function.Module._load (module.js:301:12)
    at Module.require (module.js:354:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (/ProjectA/src/components/core/wrapper/wrapper.js:28:23)
    at Module._compile (module.js:398:26)
    at loader (/ProjectA/node_modules/babel-register/lib/node.js:130:5)
    at Object.require.extensions.(anonymous function) [as .js] (/ProjectA/node_modules/babel-register/lib/node.js:140:7)
    at Module.load (module.js:344:32)
    at Function.Module._load (module.js:301:12)
    at Module.require (module.js:354:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (/ProjectA/src/components/core/wrapper/wrapperSpec.js:15:16)
    at Module._compile (module.js:398:26)
    at loader (/ProjectA/node_modules/babel-register/lib/node.js:130:5)
    at Object.require.extensions.(anonymous function) [as .js] (/ProjectA/node_modules/babel-register/lib/node.js:140:7)
    at Module.load (module.js:344:32)
    at Function.Module._load (module.js:301:12)
    at Module.require (module.js:354:17)
    at require (internal/module.js:12:17)
    at /ProjectA/node_modules/mocha/lib/mocha.js:219:27
    at Array.forEach (native)
    at Mocha.loadFiles (/ProjectA/node_modules/mocha/lib/mocha.js:216:14)
    at Mocha.run (/ProjectA/node_modules/mocha/lib/mocha.js:468:10)
    at Object.<anonymous> (/ProjectA/node_modules/mocha/bin/_mocha:403:18)
    at Module._compile (module.js:398:26)
    at Object.Module._extensions..js (module.js:405:10)
    at Module.load (module.js:344:32)
    at Function.Module._load (module.js:301:12)
    at Function.Module.runMain (module.js:430:10)
    at startup (node.js:141:18)
    at node.js:980:3
</code>```

Here is my test command from package.json:

```<code>"test": "mocha --compilers js:babel-core/register '+(test|src)/**/*Spec.js'"
</code>```

This StackOverflow post is similar but doesn't offer a solution for my use of the command line:
import a module from node_modules with babel but failed

答:
I had the same issue and fixed it by reading from the babel documentation for integrating Babel with Mocha : </p>

```<code>{
  "scripts": {
    "test": "mocha --compilers js:babel-register"
  }
}
</code>```

Body:
The solutions offered in other related questions, such as including the proper presets (es2015) in .babelrc, are already implemented in my project.

I have two projects (lets call them A and B) which both use ES6 module syntax.  In Project A, I'm importing Project B which is installed via npm and lives in the node_modules folder. When I run my test suite for Project A, I'm getting the error:

SyntaxError: Unexpected token import

Which is preceded by this alleged erroneous line of code from Project B:

(function (exports, require, module, __filename, __dirname) { import
  createBrowserHistory from 'history/lib/createBrowserHistory';

The iife appears to be something npm or possibly babel related since my source file only contains "import createBrowserHistory from 'history/lib/createBrowserHistory'; The unit tests in Project B's test suite runs fine, and if I remove Project B as a dependency from Project A, my test suite then (still using es6 imports for internal project modules) works just fine.

Full Stack Trace:

 SyntaxError: Unexpected token import
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:374:25)
    at Module._extensions..js (module.js:405:10)
    at Object.require.extensions.(anonymous function) [as .js] (/ProjectA/node_modules/babel-register/lib/node.js:138:7)
    at Module.load (module.js:344:32)
    at Function.Module._load (module.js:301:12)
    at Module.require (module.js:354:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (actionCreators.js:4:17)
    at Module._compile (module.js:398:26)
    at loader (/ProjectA/node_modules/babel-register/lib/node.js:130:5)
    at Object.require.extensions.(anonymous function) [as .js] (/ProjectA/node_modules/babel-register/lib/node.js:140:7)
    at Module.load (module.js:344:32)
    at Function.Module._load (module.js:301:12)
    at Module.require (module.js:354:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (/ProjectA/src/components/core/wrapper/wrapper.js:28:23)
    at Module._compile (module.js:398:26)
    at loader (/ProjectA/node_modules/babel-register/lib/node.js:130:5)
    at Object.require.extensions.(anonymous function) [as .js] (/ProjectA/node_modules/babel-register/lib/node.js:140:7)
    at Module.load (module.js:344:32)
    at Function.Module._load (module.js:301:12)
    at Module.require (module.js:354:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (/ProjectA/src/components/core/wrapper/wrapperSpec.js:15:16)
    at Module._compile (module.js:398:26)
    at loader (/ProjectA/node_modules/babel-register/lib/node.js:130:5)
    at Object.require.extensions.(anonymous function) [as .js] (/ProjectA/node_modules/babel-register/lib/node.js:140:7)
    at Module.load (module.js:344:32)
    at Function.Module._load (module.js:301:12)
    at Module.require (module.js:354:17)
    at require (internal/module.js:12:17)
    at /ProjectA/node_modules/mocha/lib/mocha.js:219:27
    at Array.forEach (native)
    at Mocha.loadFiles (/ProjectA/node_modules/mocha/lib/mocha.js:216:14)
    at Mocha.run (/ProjectA/node_modules/mocha/lib/mocha.js:468:10)
    at Object.<anonymous> (/ProjectA/node_modules/mocha/bin/_mocha:403:18)
    at Module._compile (module.js:398:26)
    at Object.Module._extensions..js (module.js:405:10)
    at Module.load (module.js:344:32)
    at Function.Module._load (module.js:301:12)
    at Function.Module.runMain (module.js:430:10)
    at startup (node.js:141:18)
    at node.js:980:3

Here is my test command from package.json:

"test": "mocha --compilers js:babel-core/register '+(test|src)/**/*Spec.js'"

This StackOverflow post is similar but doesn't offer a solution for my use of the command line:
import a module from node_modules with babel but failed

Body:
I had the same issue and fixed it by reading from the babel documentation for integrating Babel with Mocha :

{
  "scripts": {
    "test": "mocha --compilers js:babel-register"
  }
}


问:
Validator "Restore" returned fail status on WAMP
trying to upgrade from 4.3.3sp1 to 4.3.4 on my localhost ( WAMP ).

However on the validation step it fails with:

```<code> Validation issue
 Validator "Restore" returned fail status Unable to
 prepare restore script.
</code>```

Tried changing file permissions and some other things I found on Google.

Did not manage to find any additional data about this even on their bugtracker.

Any help would be appreciated.

答:
Found the issue.

CS-Cart is trying to build the restore file name with this rule:

```<code>$target_restore_file_name = 'restore_' . date('Y-m-d_H:i:s', TIME) . '.php';
</code>```

But Windows does not allow ":" in the filenames. So a workaround would be to do something like this:

```<code>$target_restore_file_name = 'restore_' . date('Y-m-d_His', TIME) . '.php';
</code>```

Or other variations.

This code is in app/Tygh/UpgradeCenter/App.php in the prepareRestore() function

Hope this will help someone

Body:
trying to upgrade from 4.3.3sp1 to 4.3.4 on my localhost ( WAMP ).

However on the validation step it fails with:

 Validation issue
 Validator "Restore" returned fail status Unable to
 prepare restore script.

Tried changing file permissions and some other things I found on Google.

Did not manage to find any additional data about this even on their bugtracker.

Any help would be appreciated.

Body:
Found the issue.

CS-Cart is trying to build the restore file name with this rule:

$target_restore_file_name = 'restore_' . date('Y-m-d_H:i:s', TIME) . '.php';

But Windows does not allow ":" in the filenames. So a workaround would be to do something like this:

$target_restore_file_name = 'restore_' . date('Y-m-d_His', TIME) . '.php';

Or other variations.

This code is in app/Tygh/UpgradeCenter/App.php in the prepareRestore() function

Hope this will help someone


问:
Can anyone tell me why I'm getting the attributeError? 'str' object has no attribute 'real'
```<code>def getFFtMag(data):
    maglist = []
    for x in range(0, len(data)):
        dataVal = data[x]
        firstVal = dataVal.real
        secondVal = dataVal.imag
        mag = math.sqrt(firstVal*firstVal + secondVal*secondVal)
        maglist.append(mag)
    return maglist

>>> getFFtMag("25 - Copy.xlsx")
Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    getFFtMag("25 - Copy.xlsx")
  File "<pyshell#10>", line 5, in getFFtMag
    firstVal = dataVal.real
AttributeError: 'str' object has no attribute 'real'
>>>
</code>```

So can anyone tell me why my code is wrong?  The attached error seems to be popping up.  I'm new to python and learning what is going on.  Is the problem with my data that I inputted?  Thanks.

答:
You are passing a string to your function, and not data with a .real and .imag , and since a string does not have those fields, you get the according error.

You have to read the contents of your files first. I suggest to have a look at pandas .read_excel() function

Body:
def getFFtMag(data):
    maglist = []
    for x in range(0, len(data)):
        dataVal = data[x]
        firstVal = dataVal.real
        secondVal = dataVal.imag
        mag = math.sqrt(firstVal*firstVal + secondVal*secondVal)
        maglist.append(mag)
    return maglist

>>> getFFtMag("25 - Copy.xlsx")
Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    getFFtMag("25 - Copy.xlsx")
  File "<pyshell#10>", line 5, in getFFtMag
    firstVal = dataVal.real
AttributeError: 'str' object has no attribute 'real'
>>>

So can anyone tell me why my code is wrong?  The attached error seems to be popping up.  I'm new to python and learning what is going on.  Is the problem with my data that I inputted?  Thanks.


问:
T-sql :get SUM of Columns
I have a table that looks something like the following :

```<code>          W1  W2 w3
Gold      10    2    3
Silver     3    1    1
</code>```

but i need a result :

```<code>          W1  W2  w3
Gold      10  12  15
Silver     3  4  5
</code>```

Is there any way i can get that result?

My sql query :

```<code>SELECT
   week1=[1],week2=[2],week3=[3]
FROM
(
    SELECT
    [week]=DATEPART(ISO_WEEK,ta.enddate),ta.id
    FROM
    table1 ta where ta.enddate BETWEEN '2016/01/01' AND '2016/12/31'
) src
PIVOT
(
    SUM(id) FOR week IN (
        [1],[2],[3])
) piv
</code>```

答:
One thought, since you tagged this question with Reporting Services.  If, in the end, you are displaying the info using Reporting Services I would highly consider using the Matrix tool to do the pivoting and summation of the data because that is exactly what it does.

To further explain as it seems you are going to use SSRS.  Your matrix would have a dataset that would be similar to this:

```<code>SELECT
   [week]=DATEPART(ISO_WEEK,ta.enddate),
   ta.id,
   ta.MetalType as GoldorSilver
FROM  table1 ta
where ta.enddate BETWEEN '2016/01/01' AND '2016/12/31'
</code>```

The matrix would have a header and footer and column group would be [Week] with a Column Group total to do the sum across the week.  The row group footer would do the sum across all weeks.

Title: T-sql :get SUM of Columns

Body:
I have a table that looks something like the following :

          W1  W2 w3
Gold      10    2    3
Silver     3    1    1

but i need a result :

          W1  W2  w3
Gold      10  12  15
Silver     3  4  5

Is there any way i can get that result?

My sql query :

SELECT
   week1=[1],week2=[2],week3=[3]
FROM
(
    SELECT
    [week]=DATEPART(ISO_WEEK,ta.enddate),ta.id
    FROM
    table1 ta where ta.enddate BETWEEN '2016/01/01' AND '2016/12/31'
) src
PIVOT
(
    SUM(id) FOR week IN (
        [1],[2],[3])
) piv

Body:
One thought, since you tagged this question with Reporting Services.  If, in the end, you are displaying the info using Reporting Services I would highly consider using the Matrix tool to do the pivoting and summation of the data because that is exactly what it does.

To further explain as it seems you are going to use SSRS.  Your matrix would have a dataset that would be similar to this:

SELECT
   [week]=DATEPART(ISO_WEEK,ta.enddate),
   ta.id,
   ta.MetalType as GoldorSilver
FROM  table1 ta
where ta.enddate BETWEEN '2016/01/01' AND '2016/12/31'

The matrix would have a header and footer and column group would be [Week] with a Column Group total to do the sum across the week.  The row group footer would do the sum across all weeks.


问:
Matlab get all possible combinations less than a value
I have a matrix as follows:

```<code>id      value
=============
 1       0.5
 2       0.5
 3       0.8
 4       0.3
 5       0.2
</code>```

From this array, I wish to find all the possible combinations that have a sum less than or equal to 1. That is,

```<code>result
======
1 2
1 4 5
2 4 5
3 5
1 5
1 4
2 4
2 5
...
</code>```

In order to get the above result, my idea has been to initially compute all the possibilities of finding sum of elements in the array, like so:

```<code>for ii = 1 : length(a) % compute number of possibilities
     no_of_possibilities = no_of_possibilities + nchoosek(length(a),ii);
end
</code>```

Once this is done, then loop through all possible combinations.
I would like to know if there's an easier way of doing this.

答:
It is not in easy way, however is a faster way, as I removed the combination which its subsets are not passed the condition.

```<code>bitNo = length(A);         % number of bits
setNo = 2 ^ bitNo - 1;     % number of sets
subsets = logical(dec2bin(0:setNo, bitNo) - '0'); % all subsets
subsets = subsets(2:end,:); % all subsets minus empty set!
subsetCounter = 1;
resultCounter = 1;
result = {};
while(1)
    if( subsetCounter >= size(subsets,1))
         break;
    end
    if(sum(A(subsets(subsetCounter,:).',2)) <= 1)
         result{resultCounter} = A(subsets(subsetCounter,:).',1).';
         resultCounter = resultCounter + 1;
         subsetCounter = subsetCounter + 1;
    else
         % remove all bad cases related to the current subset
         subsets = subsets(sum((subsets & subsets(subsetCounter,:)) - subsets(subsetCounter,:),2) ~= 0,:);
    end
end
</code>```

Generate the subsets using this method. After that, check the condition for each subset. If the subset does not pass the condition, all its supersets are removed from the subsets. To do this, using sum((subsets & subsets(i,:)) - subsets(i,:),2) ~= 0 which mean get some rows from subsets which has not the same elements of the not passed subset. By doing this, we able to not to consider some bad cases anymore. Although, theoretically, this code is Θ(2^n).

Body:
I have a matrix as follows:

id      value
=============
 1       0.5
 2       0.5
 3       0.8
 4       0.3
 5       0.2

From this array, I wish to find all the possible combinations that have a sum less than or equal to 1. That is,

result
======
1 2
1 4 5
2 4 5
3 5
1 5
1 4
2 4
2 5
...

In order to get the above result, my idea has been to initially compute all the possibilities of finding sum of elements in the array, like so:

for ii = 1 : length(a) % compute number of possibilities
     no_of_possibilities = no_of_possibilities + nchoosek(length(a),ii);
end

Once this is done, then loop through all possible combinations.
I would like to know if there's an easier way of doing this.

Body:
It is not in easy way, however is a faster way, as I removed the combination which its subsets are not passed the condition.

bitNo = length(A);         % number of bits
setNo = 2 ^ bitNo - 1;     % number of sets
subsets = logical(dec2bin(0:setNo, bitNo) - '0'); % all subsets
subsets = subsets(2:end,:); % all subsets minus empty set!
subsetCounter = 1;
resultCounter = 1;
result = {};
while(1)
    if( subsetCounter >= size(subsets,1))
         break;
    end
    if(sum(A(subsets(subsetCounter,:).',2)) <= 1)
         result{resultCounter} = A(subsets(subsetCounter,:).',1).';
         resultCounter = resultCounter + 1;
         subsetCounter = subsetCounter + 1;
    else
         % remove all bad cases related to the current subset
         subsets = subsets(sum((subsets & subsets(subsetCounter,:)) - subsets(subsetCounter,:),2) ~= 0,:);
    end
end

Generate the subsets using this method. After that, check the condition for each subset. If the subset does not pass the condition, all its supersets are removed from the subsets. To do this, using sum((subsets & subsets(i,:)) - subsets(i,:),2) ~= 0 which mean get some rows from subsets which has not the same elements of the not passed subset. By doing this, we able to not to consider some bad cases anymore. Although, theoretically, this code is Θ(2^n).


问:
How to send a jsonObject with array of images and other details using retrofit 2.0?
When I try that request in POSTMAN, it works fine.
However, when I try to do the same using retrofit 2.0; I always received error 500 and I can't find out what I'm doing wrong!

The code below is the call using retrofit:

```<code>@Headers({"Content-Type: application/json"})
@POST("relatorio/{token}")
Call<JsonObject> uploadJson(@Path("token") String token, @Body JsonObject auditoria);

Call<JsonObject> call = uploadJson(details.get(KEY_TOKEN), json);
</code>```

And, here I have the construction of the parameters passed in the call:

```<code>JsonObject json = new JsonObject();
JsonArray steps = new JsonArray();
steps.add(new JsonParser().parse(data.getStringExtra("json")).getAsJsonObject());
json.add("steps", steps);
json.addProperty("title", basic.getString("title"));
json.addProperty("description", basic.getString("description"));
json.addProperty("autor", basic.getString("autor"));
json.addProperty("responsavel", details.get(KEY_USERNAME));
json.add("imagens", prepare());

private JsonArray prepare(){
    Set<String> keys = JsonFormFragmentPresenter.imagesList.keySet();
    JsonArray imagens = new JsonArray();

    for(String k : keys){
        for(String path : JsonFormFragmentPresenter.imagesList.get(k)){
            if(!path.equals(null) && !path.equals("")){
                imagens.add(path);
            }
        }
    }

    JsonFormFragmentPresenter.imagesList.clear();
    return imagens;
}
</code>```

Thank you,

答:
You need to use Multipart Format

Here is a Conde Sample Below

```<code>    @Multipart
    @POST("sync/contact/image")
    Call<Response> ImageUpload(@Part MultipartBody.Part file);

    @Multipart
    @POST("sync/image")
    Call<ResponseBody> MultiImageUpload(@PartMap() Map<String, RequestBody> mapFileAndName);

 public static HashMap<String, RequestBody> GetAllImage(Context context) {
        File files = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "/.ELMEX");
        File[] filesArray = files.listFiles();
        List<File> listOfNames = Arrays.asList(filesArray);
        HashMap<String, RequestBody> map = new HashMap<>(listOfNames.size());
        RequestBody file = null;

        for (int i = 0, size = listOfNames.size(); i < size; i++) {
            file = RequestBody.create(MediaType.parse("multipart/form-data"), listOfNames.get(i));
            map.put("file\"; filename=\"" + listOfNames.get(i).getName() + ".jpg", file);
            file = null;
        }

        return  map;
    }

 HashMap<String, RequestBody> map = UtilImage.GetAllImage(context);

        Call<ResponseBody> call = Retro.getRetroWS().MultiImageUpload(map);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                Log.d(TAG, "onResponse: ");
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.d(TAG, "onFailure: ");
            }
        });
</code>```

Body:
When I try that request in POSTMAN, it works fine.
However, when I try to do the same using retrofit 2.0; I always received error 500 and I can't find out what I'm doing wrong!

The code below is the call using retrofit:

@Headers({"Content-Type: application/json"})
@POST("relatorio/{token}")
Call<JsonObject> uploadJson(@Path("token") String token, @Body JsonObject auditoria);

Call<JsonObject> call = uploadJson(details.get(KEY_TOKEN), json);

And, here I have the construction of the parameters passed in the call:

JsonObject json = new JsonObject();
JsonArray steps = new JsonArray();
steps.add(new JsonParser().parse(data.getStringExtra("json")).getAsJsonObject());
json.add("steps", steps);
json.addProperty("title", basic.getString("title"));
json.addProperty("description", basic.getString("description"));
json.addProperty("autor", basic.getString("autor"));
json.addProperty("responsavel", details.get(KEY_USERNAME));
json.add("imagens", prepare());

private JsonArray prepare(){
    Set<String> keys = JsonFormFragmentPresenter.imagesList.keySet();
    JsonArray imagens = new JsonArray();

    for(String k : keys){
        for(String path : JsonFormFragmentPresenter.imagesList.get(k)){
            if(!path.equals(null) && !path.equals("")){
                imagens.add(path);
            }
        }
    }

    JsonFormFragmentPresenter.imagesList.clear();
    return imagens;
}

Thank you,

Body:
You need to use Multipart Format

Here is a Conde Sample Below

    @Multipart
    @POST("sync/contact/image")
    Call<Response> ImageUpload(@Part MultipartBody.Part file);

    @Multipart
    @POST("sync/image")
    Call<ResponseBody> MultiImageUpload(@PartMap() Map<String, RequestBody> mapFileAndName);

 public static HashMap<String, RequestBody> GetAllImage(Context context) {
        File files = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "/.ELMEX");
        File[] filesArray = files.listFiles();
        List<File> listOfNames = Arrays.asList(filesArray);
        HashMap<String, RequestBody> map = new HashMap<>(listOfNames.size());
        RequestBody file = null;

        for (int i = 0, size = listOfNames.size(); i < size; i++) {
            file = RequestBody.create(MediaType.parse("multipart/form-data"), listOfNames.get(i));
            map.put("file\"; filename=\"" + listOfNames.get(i).getName() + ".jpg", file);
            file = null;
        }

        return  map;
    }

 HashMap<String, RequestBody> map = UtilImage.GetAllImage(context);

        Call<ResponseBody> call = Retro.getRetroWS().MultiImageUpload(map);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                Log.d(TAG, "onResponse: ");
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.d(TAG, "onFailure: ");
            }
        });


问:
Different texture co-ordinates per object when instancing
I'm using instancing to draw the same quad multiple times, for the floor in a game engine. Each floor has different texture co-ordinates depending on it's size and my problem is that all instances are using the texture co-ordinates of the first instance.

This is how I am buffering the data.

```<code>public static void UploadTextureCooridnates()
{
    // Construct texture co-ordinate array
    List<Vector2> textureCoords = new List<Vector2>();
    foreach (Floor floor in Floor.collection)
    {
        float xCoordLeft = 0;
        float yCoordBottom = 0;
        float yCoordTop = floor.scale.X;
        float xCoordRight = floor.scale.Z;

        textureCoords.Add(new Vector2(xCoordLeft, yCoordBottom));
        textureCoords.Add(new Vector2(xCoordRight, yCoordBottom));
        textureCoords.Add(new Vector2(xCoordRight, yCoordTop));

        textureCoords.Add(new Vector2(xCoordLeft, yCoordBottom));
        textureCoords.Add(new Vector2(xCoordRight, yCoordTop));
        textureCoords.Add(new Vector2(xCoordLeft, yCoordTop));
    }
    Vector2[] texCoords = textureCoords.ToArray();

    // Buffer data
    GL.BindBuffer(BufferTarget.ArrayBuffer, VBOtexcoordsInstanced);
    GL.BufferData(BufferTarget.ArrayBuffer, new IntPtr(texCoords.Length * Vector2.SizeInBytes), texCoords, BufferUsageHint.StaticDraw);
    GL.EnableVertexAttribArray(1);
    GL.VertexAttribPointer(1, 2, VertexAttribPointerType.Float, false, 0, 0);
    GL.VertexAttribDivisor(1, 0);
}
</code>```

答:
If you really are using instancing to draw multiple quads, then clearly you must have:

A buffer object containing the positions of a single quad.

Some mechanism of getting per-instance data to offset those positions.

Your problem is your expectation. You're instancing with quads. That means your render call only uses 4-6 vertices. This will be just as true for your texture coordinates as your positions.

Your problem is that you're treating per-instance data as though it were per-vertex data. Texture coordinates change with each instance; therefore, they are per-instance data. But you don't have them use instancing, so they're treated as per-vertex data. So only the texture coordinates from the first 6 vertices will be used.

Of course, you can't really make them per-instance data either. Each vertex+instance pair has a separate texture coordinate value. And instancing doesn't provide a way to do that directly. Instead, you would have to use gl_VertexID and gl_InstanceID to fetch data directly from a buffer object; either an SSBO or a buffer texture.

And therefore, your problem really is this:

I'm using instancing to draw the same quad multiple times

Stop doing that. It's not worthwhile. Just put the positions in the CPU buffer data. Use proper buffer streaming techniques, and your performance will be reasonable.

Body:
I'm using instancing to draw the same quad multiple times, for the floor in a game engine. Each floor has different texture co-ordinates depending on it's size and my problem is that all instances are using the texture co-ordinates of the first instance.

This is how I am buffering the data.

public static void UploadTextureCooridnates()
{
    // Construct texture co-ordinate array
    List<Vector2> textureCoords = new List<Vector2>();
    foreach (Floor floor in Floor.collection)
    {
        float xCoordLeft = 0;
        float yCoordBottom = 0;
        float yCoordTop = floor.scale.X;
        float xCoordRight = floor.scale.Z;

        textureCoords.Add(new Vector2(xCoordLeft, yCoordBottom));
        textureCoords.Add(new Vector2(xCoordRight, yCoordBottom));
        textureCoords.Add(new Vector2(xCoordRight, yCoordTop));

        textureCoords.Add(new Vector2(xCoordLeft, yCoordBottom));
        textureCoords.Add(new Vector2(xCoordRight, yCoordTop));
        textureCoords.Add(new Vector2(xCoordLeft, yCoordTop));
    }
    Vector2[] texCoords = textureCoords.ToArray();

    // Buffer data
    GL.BindBuffer(BufferTarget.ArrayBuffer, VBOtexcoordsInstanced);
    GL.BufferData(BufferTarget.ArrayBuffer, new IntPtr(texCoords.Length * Vector2.SizeInBytes), texCoords, BufferUsageHint.StaticDraw);
    GL.EnableVertexAttribArray(1);
    GL.VertexAttribPointer(1, 2, VertexAttribPointerType.Float, false, 0, 0);
    GL.VertexAttribDivisor(1, 0);
}

ContentLicense: CC BY-SA 4.0


问:
NodeJS - SQL Server connection closed
I'm trying to call a register stored procedure from SQL Server. I'm using NodeJS with the mssql package. I got most of the code from the mssql Npm documentation. But it still doesn't work.

The code basically tries to initiate a ConnectionPool as a read the last update renamed connection to ConnectionPool, create a new request, introduce the parameters and the execute the stored procedure. I have it this way because I need to change the connection variable to another database every once in a while.

The error I get is:

ConnectionError: Connection is closed.

My code:

```<code>const sql = require('mssql');

const config = require('../config/dbPoly');

module.exports.registerUser = function(pUserName, pPassword, pNombre, pApellidos, pFK_TipoUsuario, callback) {

  var connection = new sql.ConnectionPool(config);
  var request = new sql.Request(connection);
  request.input('input_parameter', sql.VARCHAR(25), pUserName);
  request.input('input_parameter', sql.VARCHAR(16), pPassword);
  request.input('input_parameter', sql.VARCHAR(25), pNombre);
  request.input('input_parameter', sql.VARCHAR(50), pApellidos);
  request.input('input_parameter', sql.Int, pFK_TipoUsuario);

  request.execute('RegistrarUsuario', (err, result)=>{
    if(err){
      console.log(err);
    }
    else{
      console.log(result);
    }
  });
};
</code>```

答:
If someone else faces this problem, Prabodh's answer works perfectly.

I then faced another problem, it said the localhost was undefined in 1500ms. The reason was because my server field in the json config file had the following format: 'localhost\Server-Name'. I changed it just 'localhost' and problem fixed.

Also make sure your server has SQL Authentication enabled and not just Windows Authentication.

Title: NodeJS - SQL Server connection closed

Body:
I'm trying to call a register stored procedure from SQL Server. I'm using NodeJS with the mssql package. I got most of the code from the mssql Npm documentation. But it still doesn't work.

The code basically tries to initiate a ConnectionPool as a read the last update renamed connection to ConnectionPool, create a new request, introduce the parameters and the execute the stored procedure. I have it this way because I need to change the connection variable to another database every once in a while.

The error I get is:

ConnectionError: Connection is closed.

My code:

const sql = require('mssql');

const config = require('../config/dbPoly');

module.exports.registerUser = function(pUserName, pPassword, pNombre, pApellidos, pFK_TipoUsuario, callback) {

  var connection = new sql.ConnectionPool(config);
  var request = new sql.Request(connection);
  request.input('input_parameter', sql.VARCHAR(25), pUserName);
  request.input('input_parameter', sql.VARCHAR(16), pPassword);
  request.input('input_parameter', sql.VARCHAR(25), pNombre);
  request.input('input_parameter', sql.VARCHAR(50), pApellidos);
  request.input('input_parameter', sql.Int, pFK_TipoUsuario);

  request.execute('RegistrarUsuario', (err, result)=>{
    if(err){
      console.log(err);
    }
    else{
      console.log(result);
    }
  });
};


问:
Python plotting issue / masked array / hatching
Does anyone know why the following happens; I have an array of data which contains either 1's or 0's. Code below, where data = np.ma.masked_equal(data, 1) masks any points where data is 1, leaving hatching on zeros only. This doesn't work as expected (hatches everywhere). Any ideas?

```<code>import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.basemap import Basemap

data = np.zeros((324,432))
data[:,0:100] = 1

data = data.astype(np.int)

Lons_I,Lats_I = np.meshgrid(np.linspace(0,360,432),np.linspace(-90,90,324))

m = Basemap(projection='npstere',boundinglat=60,lon_0=0,resolution='c')
m.drawcoastlines(linewidth=0.3)
X, Y = m(Lons_I, Lats_I)
cs = m.contourf(X,Y,data,np.linspace(-5,5,26),cmap='RdBu_r',extend='both')

data = np.ma.masked_equal(data, 1)

plt.pcolor(X,Y,data, hatch=".",alpha=0)
cbar = m.colorbar(cs)

plt.show()
</code>```

答:
The problem is not the hatching. It's also not the np.ma.masked_equal function. You can try that out by exchanging 0s to 1s in the array; this wil port the problem to the 0s instead of the 1s.

The route towards the solution leads over ignoring the hatching and using a non-zero alpha. Using much less points, we observe that there are two different shades of the color,

```<code>data = np.zeros((18,25))
data[:,0:9] = 1
Lons_I,Lats_I = np.meshgrid(np.linspace(0,360,25),np.linspace(-90,90,18))

m = Basemap(projection='npstere',boundinglat=60,lon_0=0,resolution='c')
m.drawcoastlines(linewidth=0.3)
X, Y = m(Lons_I, Lats_I)

data = np.ma.masked_equal(data, 1)

plt.pcolor(X,Y,data, alpha=0.3)
</code>```

This tells us that part of the mesh is plotted more often than the other.

The reason is the spherical coordinate system in use. The plot goes once aroud the sphere (0,360), but also half around it in the orthogonal direction (-90,90). The outer points are then connected, such that part of the map is doubly colorized.

In return this means that it is possible to obtain the desired result by not using the complete half sphere. So instead of going from -90 to 90, we would start the grid at slightly less, going e.g. from -89.99 to 90.

```<code>import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.basemap import Basemap

data = np.zeros((324,432))
data[:,0:100] = 1

Lons_I,Lats_I = np.meshgrid(np.linspace(0,360,432),np.linspace(-89.99,90,324))

m = Basemap(projection='npstere',boundinglat=60,lon_0=0,resolution='c')
m.drawcoastlines(linewidth=0.3)
X, Y = m(Lons_I, Lats_I)
cs = m.contourf(X,Y,data,np.linspace(-5,5,26),cmap='RdBu_r',extend='both')

data = np.ma.masked_equal(data, 1)

plt.pcolor(X,Y,data, hatch=".", alpha=0)
cbar = m.colorbar(cs)

plt.show()
</code>```

Body:
Does anyone know why the following happens; I have an array of data which contains either 1's or 0's. Code below, where data = np.ma.masked_equal(data, 1) masks any points where data is 1, leaving hatching on zeros only. This doesn't work as expected (hatches everywhere). Any ideas?

import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.basemap import Basemap

data = np.zeros((324,432))
data[:,0:100] = 1

data = data.astype(np.int)

Lons_I,Lats_I = np.meshgrid(np.linspace(0,360,432),np.linspace(-90,90,324))

m = Basemap(projection='npstere',boundinglat=60,lon_0=0,resolution='c')
m.drawcoastlines(linewidth=0.3)
X, Y = m(Lons_I, Lats_I)
cs = m.contourf(X,Y,data,np.linspace(-5,5,26),cmap='RdBu_r',extend='both')

data = np.ma.masked_equal(data, 1)

plt.pcolor(X,Y,data, hatch=".",alpha=0)
cbar = m.colorbar(cs)

plt.show()

Body:
The problem is not the hatching. It's also not the np.ma.masked_equal function. You can try that out by exchanging 0s to 1s in the array; this wil port the problem to the 0s instead of the 1s.

The route towards the solution leads over ignoring the hatching and using a non-zero alpha. Using much less points, we observe that there are two different shades of the color,

data = np.zeros((18,25))
data[:,0:9] = 1
Lons_I,Lats_I = np.meshgrid(np.linspace(0,360,25),np.linspace(-90,90,18))

m = Basemap(projection='npstere',boundinglat=60,lon_0=0,resolution='c')
m.drawcoastlines(linewidth=0.3)
X, Y = m(Lons_I, Lats_I)

data = np.ma.masked_equal(data, 1)

plt.pcolor(X,Y,data, alpha=0.3)

This tells us that part of the mesh is plotted more often than the other.

The reason is the spherical coordinate system in use. The plot goes once aroud the sphere (0,360), but also half around it in the orthogonal direction (-90,90). The outer points are then connected, such that part of the map is doubly colorized.

In return this means that it is possible to obtain the desired result by not using the complete half sphere. So instead of going from -90 to 90, we would start the grid at slightly less, going e.g. from -89.99 to 90.

import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.basemap import Basemap

data = np.zeros((324,432))
data[:,0:100] = 1

Lons_I,Lats_I = np.meshgrid(np.linspace(0,360,432),np.linspace(-89.99,90,324))

m = Basemap(projection='npstere',boundinglat=60,lon_0=0,resolution='c')
m.drawcoastlines(linewidth=0.3)
X, Y = m(Lons_I, Lats_I)
cs = m.contourf(X,Y,data,np.linspace(-5,5,26),cmap='RdBu_r',extend='both')

data = np.ma.masked_equal(data, 1)

plt.pcolor(X,Y,data, hatch=".", alpha=0)
cbar = m.colorbar(cs)

plt.show()


问:
Exclude a specific method to be invoked by CDI Interceptor
I have an interceptor binding annotation :

```<code>@InterceptorBinding
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyBinding {
}
</code>```

To this CDI interceptor :

```<code>@Interceptor
@MyBinding
public class MyInterceptor  {

    @AroundInvoke
    public Object applyPolicy(InvocationContext ctx) throws Exception {
        return blablabla;
    }
}
</code>```

And a class annotated, that mean every methods of this class will invoke MyInterceptor

```<code>@MyBinding
public class GlobalController {

    public void methodA() {...}
    public void methodB() {...}
}
</code>```

All works fine, but I wish methodB not invoking my interceptor.

I tried both annotations @ExcludeClassInterceptors and @ExcludeDefaultInterceptors on my method but it doesn't works for me. I think these annotations are especially for exclude a method for EJB Interceptor, and not CDI Interceptor with Interceptor binding.

答:
Try @MyBinding at method level:

```<code>public class GlobalController {

  @MyBinding
  public void methodA() {...}

  public void methodB() {...}
}
</code>```

Body:
I have an interceptor binding annotation :

@InterceptorBinding
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyBinding {
}

To this CDI interceptor :

@Interceptor
@MyBinding
public class MyInterceptor  {

    @AroundInvoke
    public Object applyPolicy(InvocationContext ctx) throws Exception {
        return blablabla;
    }
}

And a class annotated, that mean every methods of this class will invoke MyInterceptor

@MyBinding
public class GlobalController {

    public void methodA() {...}
    public void methodB() {...}
}

All works fine, but I wish methodB not invoking my interceptor.

I tried both annotations @ExcludeClassInterceptors and @ExcludeDefaultInterceptors on my method but it doesn't works for me. I think these annotations are especially for exclude a method for EJB Interceptor, and not CDI Interceptor with Interceptor binding.

Body:
Try @MyBinding at method level:

public class GlobalController {

  @MyBinding
  public void methodA() {...}

  public void methodB() {...}
}


问:
C#: Properties that may require a network call?
I know that in C#, properties are supposed to be quick operations (not reading data from a network or file system, etc.) However, I am building a Silverlight app and I need to bind a XAML element to some network data on a ViewModel. As far as I am aware, binding can only be done to properties, not methods. Should I break the guideline here, or is there another way around this that's not occurring to me?</p>

```<code><ListBox ItemsSource="{Binding Users}" />

public IEnumerable<User> Users
{
    get
    {
        // may be cached
        return expensiveNetworkCall();
    }
}
</code>```

答: I would break the rule and bind to the property. Although, as @Tom states, you can bind to a method, it will not make a difference user-experience wise. You could use an ObservableCollection (instead of IEnumerable) and load the users on another thread. Maybe even with an explicit command bound to a button to initiate the expensive call.

ContentLicense: CC BY-SA 2.5

Body:
I know that in C#, properties are supposed to be quick operations (not reading data from a network or file system, etc.) However, I am building a Silverlight app and I need to bind a XAML element to some network data on a ViewModel. As far as I am aware, binding can only be done to properties, not methods. Should I break the guideline here, or is there another way around this that's not occurring to me?

<ListBox ItemsSource="{Binding Users}" />

public IEnumerable<User> Users
{
    get
    {
        // may be cached
        return expensiveNetworkCall();
    }
}


问:
How to log query string parameters with Postman
I'm using the tests of Postman to log into the console some of the details included in a JSON response.
The part of the test that logs is the following:

```<code>var data = JSON.parse(responseBody);

if (data.result[0] !== undefined) {
console.log(data.result[0].number, "|", data.result[0].category;
}
else console.log(QUERYSTRING_PARAMETER, "is not present");
</code>```

I've tried many sintaxes/formats to have the value of the QUERYSTRING_PARAMETER passed to the test. However when data.result is empty with every sintax I've tried, the test simply logs QUERYSTRING_PARAMETER not defined. How can I pass the value from the query string parameters in the URL to the test to be evaluated/logged?

Thanks in advance

答:
I'm not sure if it corresponds to what you need, but if you want data from your query, you may use the 'request' object (refer to the Postman sandbox, paragraph 'Request/response related properties').
You can get request method, url, headers and (maybe the one for you) data.

Alexandre

Body:
I'm using the tests of Postman to log into the console some of the details included in a JSON response.
The part of the test that logs is the following:

var data = JSON.parse(responseBody);

if (data.result[0] !== undefined) {
console.log(data.result[0].number, "|", data.result[0].category;
}
else console.log(QUERYSTRING_PARAMETER, "is not present");

I've tried many sintaxes/formats to have the value of the QUERYSTRING_PARAMETER passed to the test. However when data.result is empty with every sintax I've tried, the test simply logs QUERYSTRING_PARAMETER not defined. How can I pass the value from the query string parameters in the URL to the test to be evaluated/logged?

Thanks in advance


问:
What's the difference between <?> and <? extends Object> in Java Generics?
I've seen the wildcard  used before to mean any object - but recently saw a use of:

```<code><? extends Object>
</code>```

Since all objects extend Object, are these two usages synonymous?

答:
<?> is a shorthand for <? extends Object>.
You may read below shared link for more details.

```<code><?>
</code>```

"?" denotes any unknown type, It can represent any Type at in code for. Use this wildcard if you are not sure about Type.

```<code>ArrayList<?> unknownList = new ArrayList<Number>(); //can accept of type Number
unknownList = new ArrayList<Float>(); //Float is of type Number
</code>```

Note: <?> means anythings. So It can accept of Type which are not inherited from Object class.

```<code><? extends Object>
</code>```

<? extends Object> means you can pass an Object or a sub-class that extends Object class.

```<code>ArrayList<? extends Number> numberList = new ArrayList<Number>(); //Number of subclass
numberList = new ArrayList<Integer>(); //Integer extends Number
numberList = new ArrayList<Float>(); // Float extends Number
</code>```

T – used to denote type

E – used to denote element

K – keys

V - values

N – for numbers
Ref:

Body:
I've seen the wildcard  used before to mean any object - but recently saw a use of:

<? extends Object>

Since all objects extend Object, are these two usages synonymous?

Body:
<?> is a shorthand for <? extends Object>.
You may read below shared link for more details.

<?>

"?" denotes any unknown type, It can represent any Type at in code for. Use this wildcard if you are not sure about Type.

ArrayList<?> unknownList = new ArrayList<Number>(); //can accept of type Number
unknownList = new ArrayList<Float>(); //Float is of type Number

Note: <?> means anythings. So It can accept of Type which are not inherited from Object class.

<? extends Object>

<? extends Object> means you can pass an Object or a sub-class that extends Object class.

ArrayList<? extends Number> numberList = new ArrayList<Number>(); //Number of subclass
numberList = new ArrayList<Integer>(); //Integer extends Number
numberList = new ArrayList<Float>(); // Float extends Number

T – used to denote type

E – used to denote element

K – keys

V - values

N – for numbers
Ref:


问:
The request entity's media type 'text/plain' is not supported for this resource
I am writing a service with POST request as:

```<code>    [HttpPost]
    [ActionName("Post")]
    public HttpResponseMessage Post([FromBody]string JStringCont)
    {
       ....
    }
</code>```

Call to this service is given as:

```<code>    string jsonContent="[{some json}]"
    StringContent content = new StringContent(jsonContent);
    _oHttpClient = new HttpClient();
    _oHttpClient.DefaultRequestHeaders.Accept.Clear();
_oHttpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

response = _oHttpClient.PostAsync(requestURI, content).Result;
</code>```

Service is clearly getting called through sending a parameter stringcontent.
I am not allowed to change the way service is getting called.

I can make changes in service itself.

POST method is not able to accept in the string format.
What can be the parameter which I can use over there in POST request which will accept stringcontent??

Currently it is giving me Error:

Response: UnsupportedMediaType

{"Message":"The request entity's media type 'text/plain' is not supported for this resource.","ExceptionMessage":"No MediaTypeFormatter is available to read an object of type 'String' from content with media type 'text/plain'.","ExceptionType":"System.Net.Http.UnsupportedMediaTypeException","StackTrace":"   at System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent content, Type type, IEnumerable1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\r\n   at System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage request, Type type, IEnumerable1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)"}

答:
You should allow JsonMediaTypeFormatter parses requests with Content-Type: text/plain. So on startup your application (in Startup.cs or WebApiConfig.cs file) you need -

```<code>config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain"));
</code>```

config is HttpConfiguration object.

Body:
I am writing a service with POST request as:

    [HttpPost]
    [ActionName("Post")]
    public HttpResponseMessage Post([FromBody]string JStringCont)
    {
       ....
    }

Call to this service is given as:

    string jsonContent="[{some json}]"
    StringContent content = new StringContent(jsonContent);
    _oHttpClient = new HttpClient();
    _oHttpClient.DefaultRequestHeaders.Accept.Clear();
_oHttpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

response = _oHttpClient.PostAsync(requestURI, content).Result;

Service is clearly getting called through sending a parameter stringcontent.
I am not allowed to change the way service is getting called.

I can make changes in service itself.

POST method is not able to accept in the string format.
What can be the parameter which I can use over there in POST request which will accept stringcontent??

Currently it is giving me Error:

Response: UnsupportedMediaType

{"Message":"The request entity's media type 'text/plain' is not supported for this resource.","ExceptionMessage":"No MediaTypeFormatter is available to read an object of type 'String' from content with media type 'text/plain'.","ExceptionType":"System.Net.Http.UnsupportedMediaTypeException","StackTrace":"   at System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent content, Type type, IEnumerable1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\r\n   at System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage request, Type type, IEnumerable1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)"}

Body:
You should allow JsonMediaTypeFormatter parses requests with Content-Type: text/plain. So on startup your application (in Startup.cs or WebApiConfig.cs file) you need -

config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain"));

config is HttpConfiguration object.


问:
Pagination issue with ng2-smart-table
I'm using the ng2-smart-table in an Angular 2 app and I have a problem with the pagination in it. I'm loading a data object array and it shows correctly the first five (I have 20 in total) but the pagination at the bottom of the table shows << >> without numbers between the arrows and if I click on the right arrow it shows me the next 15 all together. The settings for the table are:

```<code>private tableSettings = {
    columns: {
        id: {
          title: 'ID',
          filter: false
        },
        name: {
          title: 'Name',
          filter: false
        },
    },
    hideSubHeader: true,
    attr: {
        class: 'id-field'
    },
    actions:{
        edit: false
    },
    delete:{
        confirmDelete: true
    },
    pager : {
        display : true,
        perPage:5
    }
}
</code>```

Any ideas why is it showing << >> instead of << 1 2 3 4 >> ??
Thanks!

答:
You haven't mentioned if you're using server data source or local. Assuming that you are using server data source, I guess you're not passing

```<code>X-Total-Count: 20
</code>```

in your response header, so the client knows how many records in total you have.

Hope it helps.

Title: Pagination issue with ng2-smart-table

Body:
I'm using the ng2-smart-table in an Angular 2 app and I have a problem with the pagination in it. I'm loading a data object array and it shows correctly the first five (I have 20 in total) but the pagination at the bottom of the table shows << >> without numbers between the arrows and if I click on the right arrow it shows me the next 15 all together. The settings for the table are:

private tableSettings = {
    columns: {
        id: {
          title: 'ID',
          filter: false
        },
        name: {
          title: 'Name',
          filter: false
        },
    },
    hideSubHeader: true,
    attr: {
        class: 'id-field'
    },
    actions:{
        edit: false
    },
    delete:{
        confirmDelete: true
    },
    pager : {
        display : true,
        perPage:5
    }
}

Any ideas why is it showing << >> instead of << 1 2 3 4 >> ??
Thanks!

Body:
You haven't mentioned if you're using server data source or local. Assuming that you are using server data source, I guess you're not passing

X-Total-Count: 20

in your response header, so the client knows how many records in total you have.

Hope it helps.


问:
Creating two textfields with only bottom border swift
I'm trying to create two UITextFields that both only have the bottom border, I got some code from another StackOverflow and it worked. However, when I copy and pasted the code again for my second TextField it only shows one TextField with the bottom border.

Here is the code:

```<code> let border = CALayer()
 let width = CGFloat(2.0)
 border.borderColor = UIColor.gray.cgColor
 border.frame = CGRect(x: 0, y: emailText.frame.size.height -
width, width:  emailText.frame.size.width, height:
emailText.frame.size.height)

border.frame = CGRect(x: 0, y: passwordText.frame.size.height
- width, width:  passwordText.frame.size.width, height:
passwordText.frame.size.height)

    border.borderWidth = width
    passwordText.layer.addSublayer(border)
    passwordText.layer.masksToBounds = true

    border.borderWidth = width
    emailText.layer.addSublayer(border)
    emailText.layer.masksToBounds = true
</code>```

Thanks for the help!

答: CALayers are instance-based, that means if you added the layer to a view, you cannot add it to a new one without removing it from the first view. Create two instances of CALayers or better yet, make an extension that produces the desired result.

Body:
I'm trying to create two UITextFields that both only have the bottom border, I got some code from another StackOverflow and it worked. However, when I copy and pasted the code again for my second TextField it only shows one TextField with the bottom border.

Here is the code:

 let border = CALayer()
 let width = CGFloat(2.0)
 border.borderColor = UIColor.gray.cgColor
 border.frame = CGRect(x: 0, y: emailText.frame.size.height -
width, width:  emailText.frame.size.width, height:
emailText.frame.size.height)

border.frame = CGRect(x: 0, y: passwordText.frame.size.height
- width, width:  passwordText.frame.size.width, height:
passwordText.frame.size.height)

    border.borderWidth = width
    passwordText.layer.addSublayer(border)
    passwordText.layer.masksToBounds = true

    border.borderWidth = width
    emailText.layer.addSublayer(border)
    emailText.layer.masksToBounds = true

Thanks for the help!


问:
SOAP UI - ERROR:Exception in request: javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure
I am trying to hit the third party webservice using SOAP UI and getting below exception:

ERROR:Exception in request: javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure

I dont have cacert or keystore from the third party webservice but I have signature.By using signature I'm able to hit the third party webservice through my application.

How to configure this signature in SOAP UI?

答:
This is an old thread but my solution might help someone.

In SoapUI version 5.3.0 I solved this problem by removing line:

```<code>if exist "%SOAPUI_HOME%..\jre\bin" goto SET_BUNDLED_JAVA
</code>```

from the soapui.bat and then using soapui.bat for program execution. It seems that Java embedded with SoapUI is a different version than mine which is JRE 1.8.0_131.

Body:
This is an old thread but my solution might help someone.

In SoapUI version 5.3.0 I solved this problem by removing line:

if exist "%SOAPUI_HOME%..\jre\bin" goto SET_BUNDLED_JAVA

from the soapui.bat and then using soapui.bat for program execution. It seems that Java embedded with SoapUI is a different version than mine which is JRE 1.8.0_131.


问:
How to make a correct Joomla URL using the Joomla Classes
I am busy making a Joomla!  component. And know i want to link to another component. So, as example i want to link from my component 'my_component' to 'his_component'. Normally this is simple to do. Just make a normal link like href="?option=com_his_component". But the problem is that one of my consumers uses SEO friendly URLs. And in that case this URL won't work.

Does anyone know a way to this the correct way (I think with the Joomla! Api)

答:
Just wrap that link with a call to JRoute::_($url):

```<code>$link = JRoute::_('index.php?option=com_his_component&foo=bar');
</code>```

Body:
Just wrap that link with a call to JRoute::_($url):

$link = JRoute::_('index.php?option=com_his_component&foo=bar');


问:
Drawing shapes on avcapture preview layer by extracting frames
I'm trying to get each frame presented in the AVCapture preview layer, I want to essentially use openCV to detect specific shapes (more specifically circles) and draw them on screen to user. I can't seem to get the correct method to update the preview layer of the screen, instead I am only able to get output frames from a queue which does not do anything to the preview.

Currently using the following method to extract frames from output buffer:

```<code>    // Create a UIImage from sample buffer data
- (UIImage *) imageFromSampleBuffer:(CMSampleBufferRef) sampleBuffer
{
    // Get a CMSampleBuffer's Core Video image buffer for the media data
    CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
    // Lock the base address of the pixel buffer
    CVPixelBufferLockBaseAddress(imageBuffer, 0);

    // Get the number of bytes per row for the pixel buffer
    void *baseAddress = CVPixelBufferGetBaseAddress(imageBuffer);

    // Get the number of bytes per row for the pixel buffer
    size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer);
    // Get the pixel buffer width and height
    size_t width = CVPixelBufferGetWidth(imageBuffer);
    size_t height = CVPixelBufferGetHeight(imageBuffer);

    // Create a device-dependent RGB color space
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

    // Create a bitmap graphics context with the sample buffer data
    CGContextRef context = CGBitmapContextCreate(baseAddress, width, height, 8,
                                                 bytesPerRow, colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst);
    // Create a Quartz image from the pixel data in the bitmap graphics context
    CGImageRef quartzImage = CGBitmapContextCreateImage(context);
    // Unlock the pixel buffer
    CVPixelBufferUnlockBaseAddress(imageBuffer,0);

    // Free up the context and color space
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);

    // Create an image object from the Quartz image
    UIImage *image = [UIImage imageWithCGImage:quartzImage];

    // Release the Quartz image
    CGImageRelease(quartzImage);

    return image;
    }
</code>```

Are there any ways to get each frame sent to be displayed on preview layer? or any other ways to implement hough detection using AVCapture session rather than opencv Cameras? Any help would be really appreciated!

答:
To do this the best way is to take each frame from the method:

```<code>- (UIImage *) imageFromSampleBuffer:(CMSampleBufferRef) sampleBuffer;
</code>```

in this method extract the UIImage and use a wrapper with OpenCV to find houghcircles in each frame. Hough circles will generate coordinates for where the circles are located, if any. I then can use the location of the circles to draw a CAShapeLayer on the view to show the circle. I use the following to draw the circles in the view:

```<code>circleLayer = [CAShapeLayer layer];
[circleLayer setPath:[[UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, radius, radius)] CGPath]];
[self.previewLayer addSublayer:circleLayer];
[circleLayer setStrokeColor:[[UIColor redColor] CGColor]];
[circleLayer setFillColor:[[UIColor clearColor] CGColor]];
</code>```

We can simply move the circle based on where the houghcircle is detected by the openCV algorithm like this:

```<code>[circleLayer setPosition:CGPointMake(x,y)];
</code>```

The parameters for the CGPoint might need to be tweaked based on orientation of the images captured and scaling factors. This solution works!

Body:
I'm trying to get each frame presented in the AVCapture preview layer, I want to essentially use openCV to detect specific shapes (more specifically circles) and draw them on screen to user. I can't seem to get the correct method to update the preview layer of the screen, instead I am only able to get output frames from a queue which does not do anything to the preview.

Currently using the following method to extract frames from output buffer:

    // Create a UIImage from sample buffer data
- (UIImage *) imageFromSampleBuffer:(CMSampleBufferRef) sampleBuffer
{
    // Get a CMSampleBuffer's Core Video image buffer for the media data
    CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
    // Lock the base address of the pixel buffer
    CVPixelBufferLockBaseAddress(imageBuffer, 0);

    // Get the number of bytes per row for the pixel buffer
    void *baseAddress = CVPixelBufferGetBaseAddress(imageBuffer);

    // Get the number of bytes per row for the pixel buffer
    size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer);
    // Get the pixel buffer width and height
    size_t width = CVPixelBufferGetWidth(imageBuffer);
    size_t height = CVPixelBufferGetHeight(imageBuffer);

    // Create a device-dependent RGB color space
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

    // Create a bitmap graphics context with the sample buffer data
    CGContextRef context = CGBitmapContextCreate(baseAddress, width, height, 8,
                                                 bytesPerRow, colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst);
    // Create a Quartz image from the pixel data in the bitmap graphics context
    CGImageRef quartzImage = CGBitmapContextCreateImage(context);
    // Unlock the pixel buffer
    CVPixelBufferUnlockBaseAddress(imageBuffer,0);

    // Free up the context and color space
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);

    // Create an image object from the Quartz image
    UIImage *image = [UIImage imageWithCGImage:quartzImage];

    // Release the Quartz image
    CGImageRelease(quartzImage);

    return image;
    }

Are there any ways to get each frame sent to be displayed on preview layer? or any other ways to implement hough detection using AVCapture session rather than opencv Cameras? Any help would be really appreciated!

Body:
To do this the best way is to take each frame from the method:

- (UIImage *) imageFromSampleBuffer:(CMSampleBufferRef) sampleBuffer;

in this method extract the UIImage and use a wrapper with OpenCV to find houghcircles in each frame. Hough circles will generate coordinates for where the circles are located, if any. I then can use the location of the circles to draw a CAShapeLayer on the view to show the circle. I use the following to draw the circles in the view:

circleLayer = [CAShapeLayer layer];
[circleLayer setPath:[[UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, radius, radius)] CGPath]];
[self.previewLayer addSublayer:circleLayer];
[circleLayer setStrokeColor:[[UIColor redColor] CGColor]];
[circleLayer setFillColor:[[UIColor clearColor] CGColor]];

We can simply move the circle based on where the houghcircle is detected by the openCV algorithm like this:

[circleLayer setPosition:CGPointMake(x,y)];

The parameters for the CGPoint might need to be tweaked based on orientation of the images captured and scaling factors. This solution works!


问:
How do ligature icons work in Material Icons?
Using Material Icons, a plus icon can be added as follows:

```<code><i class="material-icons">add</i>
</code>```

The text add is no longer visible. Why does this happen and where does the plus icon come from? I know it's defined in the font file, but how?

If it's due to the word add linked with the plus icon in the font file, then why doesn't the following work in Bootstrap, with its Glyphicons?

```<code><span style="font-family: 'Glyphicons Halflings'">\20ac</span>
</code>```

答:
EXPLANATION

When you strip all the technical information, the answer is really quite straightforward, the font file incorporates a few tables amongst which:

[MANDATORY] the list of characters

[MANDATORY] the hexadecimal codes of those characters

[OPTIONAL] one or more aliases/alternative names for those characters

The one or more aliases/alternative names are the 'ligatures' you are referring to and reside in the font file.

Essentially, when using a character/icon from a font file with ligatures, we have the option to use

the 'regular' hexadecimal code: &#xxxx;

or the alternative/alias/ligature name: ligature-name or alias

That is probably all the important info for a web designer to know.

EXTRAS

Go to CSS-Tricks: How do ligature icons work... to see usage examples and a brief explanation.

And if you want to mess around with your own icon font files I suggest you start using the IcoMoon APP:

start the APP, select an icon and select 'generate font' (bottom right)

Enable display of ligatures with the 'show ligatures'-button (top left 3rd button)

Body:
Using Material Icons, a plus icon can be added as follows:

add

The text add is no longer visible. Why does this happen and where does the plus icon come from? I know it's defined in the font file, but how?

If it's due to the word add linked with the plus icon in the font file, then why doesn't the following work in Bootstrap, with its Glyphicons?

\20ac

Body:
EXPLANATION

When you strip all the technical information, the answer is really quite straightforward, the font file incorporates a few tables amongst which:

[MANDATORY] the list of characters

[MANDATORY] the hexadecimal codes of those characters

[OPTIONAL] one or more aliases/alternative names for those characters

The one or more aliases/alternative names are the 'ligatures' you are referring to and reside in the font file.

Essentially, when using a character/icon from a font file with ligatures, we have the option to use

the 'regular' hexadecimal code: <i class="some-font-with-ligatures">&#xxxx;</i>

or the alternative/alias/ligature name: <i class="some-font-with-ligatures">ligature-name or alias</i>

That is probably all the important info for a web designer to know.

EXTRAS

Go to CSS-Tricks: How do ligature icons work... to see usage examples and a brief explanation.

And if you want to mess around with your own icon font files I suggest you start using the IcoMoon APP:

start the APP, select an icon and select 'generate font' (bottom right)

Enable display of ligatures with the 'show ligatures'-button (top left 3rd button)


问:
How to receive messages with sandboxed iframes?
I have an html page with a iframe that is sandboxed, so it can't access parent DOM. But is there a way I can still send serialized data from the iframe to the parent with event listeners and from the parent to the iframe too?</p>

答:
Yes. You can use post messages either from an iframe to its parent, or from a parent to its iframe.

postMessage should work fine, even from within a sandboxed iframe.


答:
Properties should only be used for simple data / member access and should never represent a lengthy operation such as a network call.  A method is much more appropriate for this scenario.

Having it as a method may be convenient today for your UI scenario but will lead to problems down the road.  Binding diretly to a method is not supported as easily as properties because a method implies an operation that probably shouldn't be bound to the UI.  For example if the underlying network connection hangs it will lead to a direct hang in hte UI.  This is a quick way to frustrate users.

Here's an alternative approach

Instead of an IEnumerable<Users> use a BindingCollection<Users>

Have the BindingCollection<Users> start off as empty and queue a network request for the users

When the network request is completed update the BindingCollection<Users> with the found data (make sure to Invoke back to the UI thread)

Title: C#: Properties that may require a network call?


答:
Create separate border object for email textfield and username textfield.</p>

```<code>let emailborder = CALayer()
let passwordborder = CALayer()

let width = CGFloat(2.0)
emailborder.borderColor = UIColor.gray.cgColor
emailborder.frame = CGRect(x: 0, y: emailText.frame.size.height -
width, width:  emailText.frame.size.width, height:
emailText.frame.size.height)

passwordborder.frame = CGRect(x: 0, y: passwordText.frame.size.height
- width, width:  passwordText.frame.size.width, height:
passwordText.frame.size.height)

passwordborder.borderWidth = width
passwordText.layer.addSublayer(passwordborder)
passwordText.layer.masksToBounds = true

emailborder.borderWidth = width
emailText.layer.addSublayer(emailborder)
emailText.layer.masksToBounds = true
</code>```

Title: Creating two textfields with only bottom border swift

Body:
Create separate border object for email textfield and username textfield.

let emailborder = CALayer()
let passwordborder = CALayer()

let width = CGFloat(2.0)
emailborder.borderColor = UIColor.gray.cgColor
emailborder.frame = CGRect(x: 0, y: emailText.frame.size.height -
width, width:  emailText.frame.size.width, height:
emailText.frame.size.height)

passwordborder.frame = CGRect(x: 0, y: passwordText.frame.size.height
- width, width:  passwordText.frame.size.width, height:
passwordText.frame.size.height)

passwordborder.borderWidth = width
passwordText.layer.addSublayer(passwordborder)
passwordText.layer.masksToBounds = true

emailborder.borderWidth = width
emailText.layer.addSublayer(emailborder)
emailText.layer.masksToBounds = true


问:
What is the best way to show reports with firebase?
I am currently using Cloud Functions to do aggregation in Firebase so that whenever a certain type of data entry occurs, I aggregate it accordingly and store it to show our reports. There are following concerns with this approach:-

Adding new reports would mean going over all the existing data and that could be expensive with firebase realtime database

Making any changes to existing reports is also non-trivial

I was considering a solution like Cloud Dataflow. However, one issue is that it is not part of the Spark or Flame plan of Firebase.

What is the best way to handle reporting with firebase, keeping both cost and performance in mind?

答:
Recommending a specific reporting solution is off-topic on Stack Overflow.

But in general I recommend separating your active data (that users need to access directly) from your historical data (that you keep mostly for reporting). Keep your active data in your Firebase Database, which is optimized for synchronizing data between users. Then keep your historical data in a separate data store that is optimized for reporting.

A quite common combination is to keep the historical data in BigQuery and then aggregate the data there. You can then write the aggregated data back to your Firebase Database, to make it available to your users.


问:
Open non text file without windows line ending
I took over a project that use the following function to read files:

```<code>char *fetchFile(char *filename) {
    char *buffer;
    int len;
    FILE *f = fopen(filename, "rb");
    if(f) {
        if(verbose) {
            fprintf(stdout, "Opened file %s successfully\n", filename);
        }
        fseek(f, 0, SEEK_END);
        len = ftell(f);
        fseek(f, 0, SEEK_SET);
        if(verbose) {
            fprintf(stdout, "Allocating memory for buffer for %s\n", filename);
        }
        buffer = malloc(len + 1);
        if(buffer) fread (buffer, 1, len, f);
        fclose (f);
        buffer[len] = '\0';
    } else {
        fprintf(stderr, "Error reading file %s\n", filename);
        exit(1);
    }
    return buffer;
}
</code>```

The rb mode is used because sometimes the file can be a spreadsheet and therefore I want the information as in a text file.

The program runs on a linux machine but the files to read come from linux and windows.

I am not sure of what approach is better to not have windows line ending mess with my code.

I was thinking of using dos2unix at the start of this function.
I also thought of opening in r mode, but I believe that could potentially mess things up when opening non-text files.

I would like to understand better the differences between using:

dos2unix,

r vs rb mode,

or any other solution which would fit
better the problem.

Note: I believe that I understand r vs rb modes, but if you could explain why it is a bad or good solution for this specific situation (I think it wouldn't be good because sometimes it opens spreadsheets but I am not sure of that).

答:
The code just copies the contents of a file to an allocated buffer. The UNIX way (YMMV) is to just memory map the file instead of reading it. Much faster.

```<code>// untested code
void* mapfile(const char *name)
{
    int fd;
    struct stat st;

    if ((fd = open(name, O_RDONLY)) == -1)
        return NULL;
    if (fstat(fd, &st)) {
        close(fd);
        return NULL;
    }

    void *p = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, 0, fd);
    close(fd);
    if (p == (void *)MAP_FAILED)
        p = NULL;

    return p;
}
</code>```

Something along these lines will work. Adjust settings if you want to write to the file as well.

Body:
I took over a project that use the following function to read files:

char *fetchFile(char *filename) {
    char *buffer;
    int len;
    FILE *f = fopen(filename, "rb");
    if(f) {
        if(verbose) {
            fprintf(stdout, "Opened file %s successfully\n", filename);
        }
        fseek(f, 0, SEEK_END);
        len = ftell(f);
        fseek(f, 0, SEEK_SET);
        if(verbose) {
            fprintf(stdout, "Allocating memory for buffer for %s\n", filename);
        }
        buffer = malloc(len + 1);
        if(buffer) fread (buffer, 1, len, f);
        fclose (f);
        buffer[len] = '\0';
    } else {
        fprintf(stderr, "Error reading file %s\n", filename);
        exit(1);
    }
    return buffer;
}

The rb mode is used because sometimes the file can be a spreadsheet and therefore I want the information as in a text file.

The program runs on a linux machine but the files to read come from linux and windows.

I am not sure of what approach is better to not have windows line ending mess with my code.

I was thinking of using dos2unix at the start of this function.
I also thought of opening in r mode, but I believe that could potentially mess things up when opening non-text files.

I would like to understand better the differences between using:

dos2unix,

r vs rb mode,

or any other solution which would fit
better the problem.

Note: I believe that I understand r vs rb modes, but if you could explain why it is a bad or good solution for this specific situation (I think it wouldn't be good because sometimes it opens spreadsheets but I am not sure of that).

Body:
The code just copies the contents of a file to an allocated buffer. The UNIX way (YMMV) is to just memory map the file instead of reading it. Much faster.

// untested code
void* mapfile(const char *name)
{
    int fd;
    struct stat st;

    if ((fd = open(name, O_RDONLY)) == -1)
        return NULL;
    if (fstat(fd, &st)) {
        close(fd);
        return NULL;
    }

    void *p = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, 0, fd);
    close(fd);
    if (p == (void *)MAP_FAILED)
        p = NULL;

    return p;
}

Something along these lines will work. Adjust settings if you want to write to the file as well.


问:
Google places autocomplete get the place type
I have a simple application where the user fills in the start and end point (with google places autocomplete) and then, with directions services, I draw the route on Google Maps.
I can calculate the gas needed for that route, the tolls that the driver must pay etc.

Its working fine so far.

Now I have to check if the start point or end point is an airport (I assume that I have to check the place type) and I have no idea how to achieve that.

I know that the places autocomplete object contains the place type and I was wondering if when selecting from the autocomplete I can pass to a hidden field the place type and then check if is the appropriate type.
(or any other more appropriate solution)

答:
The predictions in place autocomplete might be a bit confusing. Let's have a look at the following example. I would like to find 'aeroport El Prat Barcelona'

https://maps.googleapis.com/maps/api/place/autocomplete/json?input=aeroport%20El%20Prat%20Barcelona&key=YOUR_API_KEY

The first prediction has a text Aeroport, El Prat de Llobregat, Barcelona, Spain with place Id ChIJO46GD4eepBIRIn5B25NbcNQ. At first glance it seems to be airport, but when you check the types in the response you can see

```<code>"types":[
    "transit_station","point_of_interest","establishment","geocode"
]
</code>```

So this is not an airport, but the train station close to the airport as shown in the following screenshot.

At this point it looks like you cannot rely 100% on the type provided by autocomplete, because you can get something very close to the airport like the train or bus station that share the 'airport' in the name.

As a workaround I would suggest checking with places API nearby search if there is any airport close to coordinate returned by autocomplete. But this requires two additional steps:

Resolve place ID to coordinate. E.g. https://maps.googleapis.com/maps/api/geocode/json?place_id=ChIJO46GD4eepBIRIn5B25NbcNQ&key=YOUR_API_KEY will return 41.3042622,2.0733891

Use nearby search to figure out if there is an airport in radius, for example 500 meters https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=41.3042622%2C2.0733891&radius=500&type=airport&key=YOUR_API_KEY

The last request returns the airport as shown in the following screenshot

Body:
The predictions in place autocomplete might be a bit confusing. Let's have a look at the following example. I would like to find 'aeroport El Prat Barcelona'

https://maps.googleapis.com/maps/api/place/autocomplete/json?input=aeroport%20El%20Prat%20Barcelona&key=YOUR_API_KEY

The first prediction has a text Aeroport, El Prat de Llobregat, Barcelona, Spain with place Id ChIJO46GD4eepBIRIn5B25NbcNQ. At first glance it seems to be airport, but when you check the types in the response you can see

"types":[
    "transit_station","point_of_interest","establishment","geocode"
]

So this is not an airport, but the train station close to the airport as shown in the following screenshot.

At this point it looks like you cannot rely 100% on the type provided by autocomplete, because you can get something very close to the airport like the train or bus station that share the 'airport' in the name.

As a workaround I would suggest checking with places API nearby search if there is any airport close to coordinate returned by autocomplete. But this requires two additional steps:

Resolve place ID to coordinate. E.g. https://maps.googleapis.com/maps/api/geocode/json?place_id=ChIJO46GD4eepBIRIn5B25NbcNQ&key=YOUR_API_KEY will return 41.3042622,2.0733891

Use nearby search to figure out if there is an airport in radius, for example 500 meters https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=41.3042622%2C2.0733891&radius=500&type=airport&key=YOUR_API_KEY

The last request returns the airport as shown in the following screenshot


问:
While coding, an error of "name not defined" is generated
I was coding for the question "Write a Python function that takes two lists and returns True if they have at least one common member"

Code:

```<code>first = [a,b,c,d,e,f]
second = [a,s,d,f,g,h]
for word1 in first:
    for word2 in second:
     if word1==word2:
        print("success")
</code>```

Error:

```<code>first = list[a,b,c,d,e,f]
NameError: name 'a' is not defined
</code>```

How can I fix this?

答:
I assume that your lists are lists of string. So you forgot the quotes :

```<code>first = ['a','b','c','d','e','f']
second = ['a','s','d','f','g','h']
for word1 in first:
    for word2 in second:
     if word1==word2:
        print("success")
</code>```

a is a variable name, whereas 'a' is a string. So, indeed, here a is not defined because you have never affected any value to a.

For instance, if you really wanted to create a list from existing defined values you may have done :

```<code>a=5
b=10
l=[a,b]
</code>```

Here, l will be [5,10]

Body:
I was coding for the question "Write a Python function that takes two lists and returns True if they have at least one common member"

Code:

first = [a,b,c,d,e,f]
second = [a,s,d,f,g,h]
for word1 in first:
    for word2 in second:
     if word1==word2:
        print("success")

Error:

first = list[a,b,c,d,e,f]
NameError: name 'a' is not defined

How can I fix this?

Body:
I assume that your lists are lists of string. So you forgot the quotes :

first = ['a','b','c','d','e','f']
second = ['a','s','d','f','g','h']
for word1 in first:
    for word2 in second:
     if word1==word2:
        print("success")

a is a variable name, whereas 'a' is a string. So, indeed, here a is not defined because you have never affected any value to a.

For instance, if you really wanted to create a list from existing defined values you may have done :

a=5
b=10
l=[a,b]

Here, l will be [5,10]