问:
How to know current position of UIView in left or right of screen?

I'm making an draggable UIView which can move anywhere on screen. And I set it automatically hide 1/2 part of it after 3 seconds with this code:

```<code>-(void)hidePart {
    if (self.frame.origin.x > 0) {
        [UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionTransitionNone animations:^{
        self.frame = CGRectMake(0 - self.frame.origin.x - self.frame.size.width/3, self.frame.origin.y, self.frame.size.width, self.frame.size.height);
        } completion:^(BOOL finished) {
        }];
    }
}
</code>```

It's work normally if I put UIView near left edge of screen. But if I drag and put it near right edge, after 3 secs it will run to left side and go out of screen. I know it's cause by I set the frame of it after 3 secs delay equal to: (current X - frame) and current X is very big in this case.

I wondering how can I make it better? I mean if this UIView is closer to left edge it will go out to left side and in case it's closer to the right edge, it will go out to right side?

答:
Firstly, You should recognize that at which part of the view the draggable view is, left or right.

```<code>CGFloat pointLeft = CGRectGetMidX(self.frame);
BOOL isLeft = CGRectGetMidX(self.frame) < kScreenWidth/2;
</code>```

Then, animate the view to left or right in terms of it.
You have finished the left.

Body:
I'm making an draggable UIView which can move anywhere on screen. And I set it automatically hide 1/2 part of it after 3 seconds with this code:

-(void)hidePart {
    if (self.frame.origin.x > 0) {
        [UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionTransitionNone animations:^{
        self.frame = CGRectMake(0 - self.frame.origin.x - self.frame.size.width/3, self.frame.origin.y, self.frame.size.width, self.frame.size.height);
        } completion:^(BOOL finished) {
        }];
    }
}

It's work normally if I put UIView near left edge of screen. But if I drag and put it near right edge, after 3 secs it will run to left side and go out of screen. I know it's cause by I set the frame of it after 3 secs delay equal to: (current X - frame) and current X is very big in this case.

I wondering how can I make it better? I mean if this UIView is closer to left edge it will go out to left side and in case it's closer to the right edge, it will go out to right side?

Body:
Firstly, You should recognize that at which part of the view the draggable view is, left or right.

CGFloat pointLeft = CGRectGetMidX(self.frame);
BOOL isLeft = CGRectGetMidX(self.frame) < kScreenWidth/2;

Then, animate the view to left or right in terms of it.
You have finished the left.


来源: stackexchange

问:
setTimeout waits too long in Node.js
I think I have a misunderstanding of what setTimeout does exactly in JavaScript. I have this script:

```<code>function recursiveFibonacci(n) {
    if ( n === 0 ) {
        return 1;
    } else if ( n === 1 ) {
        return 1;
    } else {
        return recursiveFibonacci(n-1) + recursiveFibonacci(n-2);
    }
}

setTimeout( () => {console.log("one second");}, 1000);

console.log(recursiveFibonacci(42));
</code>```

What I would expect to happen is that recursiveFibonacci starts chugging away on the 43rd value in the Fibonacci sequence. This takes about 4 seconds on my computer. So, after 1 second of work the evaluation would be interrupted and the console would log:

```<code>one second
</code>```

and then about 3 seconds later log:

```<code>433494437
</code>```

Instead what happens is that, after 4 seconds, the console logs:

```<code>433494437
one second
</code>```

all at once. Why is this the case? How can I get setTimeout to work? Is it the case that the JavaScript interpreter is not actually interrupted by  setTimeout but rather if it finishes its other jobs then it will wait until the given amount of time has passed before calling the given function?

Edit:

I found this tool very useful for understanding the relevant concepts:

Loupe

答:
Javascript in node.js is event driven and single threaded.  Since your reverseFibonacci() function is synchronous, it does not allow anything else to run until it is done.

So, even though the timer fires and the timer callback is put into the internal nodejs event queue, the JS interpreter can't get to the next event in the event queue until your reverseFibonacci() function is done.

setTimeout() does not interrupt the currently running Javascript.  Instead, it puts an event in the event queue and when the currently running Javascript is done, the JS interpreter will then pull the next event out of the event queue and run it.

So, the order of events in your scenario is this:

Schedule a timer event for 1 second from now.

Start running reverseFibonacci()

Timer fires (internally in nodejs) 1 second later and inserts an event into the nodejs event queue.

4+ seconds later your reverseFibonacci(42) finishes running.

Since the currently running JS has finished, the JS interpreter pulls the next event out of the event queue and processes it, resulting in your timer callback finally getting called.

Timers schedule with setTimeout() runs as soon as possible after their scheduled time, but if the Javascript interpreter is busy running other code, they don't interrupt that code.  The timer system puts an event into the event queue and, when that other code is done, then the Javascript interpreter will pull the next event out of the event queue and run it (your timer callback will get called).

ContentLicense: CC BY-SA 3.0

Title: setTimeout waits too long in Node.js

Body:
I think I have a misunderstanding of what setTimeout does exactly in JavaScript. I have this script:

function recursiveFibonacci(n) {
    if ( n === 0 ) {
        return 1;
    } else if ( n === 1 ) {
        return 1;
    } else {
        return recursiveFibonacci(n-1) + recursiveFibonacci(n-2);
    }
}

setTimeout( () => {console.log("one second");}, 1000);

console.log(recursiveFibonacci(42));

What I would expect to happen is that recursiveFibonacci starts chugging away on the 43rd value in the Fibonacci sequence. This takes about 4 seconds on my computer. So, after 1 second of work the evaluation would be interrupted and the console would log:

one second

and then about 3 seconds later log:

433494437

Instead what happens is that, after 4 seconds, the console logs:

433494437
one second

all at once. Why is this the case? How can I get setTimeout to work? Is it the case that the JavaScript interpreter is not actually interrupted by  setTimeout but rather if it finishes its other jobs then it will wait until the given amount of time has passed before calling the given function?

Edit:

I found this tool very useful for understanding the relevant concepts:

Loupe


Title: How to get the surrounding numbers of a specific number in the form of 3x3 matrix in numpy?

Body:
I wrote a function to get the surrounding numbers of a number by passing their index as a parameter in the form of a 3X3 matrix.

import numpy as np
ar = np.arange(0,120)
ar = np.reshape(ar,(12,10))

def get_surroundings(ar,i,j):
    if ((i>0) & (i<ar.shape[0])) & ((j>0) & (j<ar.shape[1])):
        temp = np.array([[ar[i-1][j-1],ar[i-1][j],ar[i-1][j+1]],[ar[i][j-1],ar[i][j],ar[i][j+1]],[ar[i+1][j-1],ar[i+1][j],ar[i+1][j-1]]])
        return temp

get_surroundings(ar,9,5)

ar is a 12x10 matrix like below :

array([[  0,   1,   2,   3,   4,   5,   6,   7,   8,   9],
   [ 10,  11,  12,  13,  14,  15,  16,  17,  18,  19],
   [ 20,  21,  22,  23,  24,  25,  26,  27,  28,  29],
   [ 30,  31,  32,  33,  34,  35,  36,  37,  38,  39],
   [ 40,  41,  42,  43,  44,  45,  46,  47,  48,  49],
   [ 50,  51,  52,  53,  54,  55,  56,  57,  58,  59],
   [ 60,  61,  62,  63,  64,  65,  66,  67,  68,  69],
   [ 70,  71,  72,  73,  74,  75,  76,  77,  78,  79],
   [ 80,  81,  82,  83,  84,  85,  86,  87,  88,  89],
   [ 90,  91,  92,  93,  94,  95,  96,  97,  98,  99],
   [100, 101, 102, 103, 104, 105, 106, 107, 108, 109],
   [110, 111, 112, 113, 114, 115, 116, 117, 118, 119]])

I get the result from the function like below :

 array([[ 84,  85,  86],
       [ 94,  95,  96],
       [104, 105, 104]])

Is there a numpy function to achieve the same?
If i give (ar,0,0) then output should be

array([[ 0,  0,  0],
       [ 0,  10,  11],
       [0, 20, 21]])

Similarly if (ar,11,0) then output should be

array([[ 0, 100, 101],
       [ 0 , 110, 111],
       [ 0 , 0,0]])

Body:
You can use scikit-image as view_as_windows to create such sliding windows after padding with zeros using np.pad -

from skimage.util.shape import view_as_windows

def get_windows(ar, W, i, j):
    h0,h1 = (W[0]-1)//2, (W[1]-1)//2
    ar_ext = np.pad(ar,((h0,h0),(h1,h1)),'constant',constant_values=(0,0))
    return view_as_windows(ar_ext, (W[0],W[1]))[i,j]

Sample run -

1) Input array :

In [39]: ar
Out[39]:
array([[  0,   1,   2,   3,   4,   5,   6,   7,   8,   9],
       [ 10,  11,  12,  13,  14,  15,  16,  17,  18,  19],
       [ 20,  21,  22,  23,  24,  25,  26,  27,  28,  29],
       [ 30,  31,  32,  33,  34,  35,  36,  37,  38,  39],
       [ 40,  41,  42,  43,  44,  45,  46,  47,  48,  49],
       [ 50,  51,  52,  53,  54,  55,  56,  57,  58,  59],
       [ 60,  61,  62,  63,  64,  65,  66,  67,  68,  69],
       [ 70,  71,  72,  73,  74,  75,  76,  77,  78,  79],
       [ 80,  81,  82,  83,  84,  85,  86,  87,  88,  89],
       [ 90,  91,  92,  93,  94,  95,  96,  97,  98,  99],
       [100, 101, 102, 103, 104, 105, 106, 107, 108, 109],
       [110, 111, 112, 113, 114, 115, 116, 117, 118, 119]])

2) Output with a window of (3,3) in an inner place :

In [40]: get_windows(ar, (3,3), 9,5)
(1, 1)
Out[40]:
array([[ 84,  85,  86],
       [ 94,  95,  96],
       [104, 105, 106]])

3) Output with a window of (5,5) in an inner place :

In [41]: get_windows(ar, (5,5), 9,5)
(2, 2)
Out[41]:
array([[ 73,  74,  75,  76,  77],
       [ 83,  84,  85,  86,  87],
       [ 93,  94,  95,  96,  97],
       [103, 104, 105, 106, 107],
       [113, 114, 115, 116, 117]])

4) Output with a window of (5,3) in an inner place :

In [30]: get_windows(ar, (5,3), 9,5)
Out[30]:
array([[ 74,  75,  76],
       [ 84,  85,  86],
       [ 94,  95,  96],
       [104, 105, 106],
       [114, 115, 116]])

5) Output with a window of (5,5) in a boundary place :

In [42]: get_windows(ar, (5,5), 0,0)
(2, 2)
Out[42]:
array([[ 0,  0,  0,  0,  0],
       [ 0,  0,  0,  0,  0],
       [ 0,  0,  0,  1,  2],
       [ 0,  0, 10, 11, 12],
       [ 0,  0, 20, 21, 22]])


问:
I need user input to tell the program which list to use?
So i'm pretty new to python and i'm making a hangman program.  Here is the code I have so far.

```<code>import random
print('Welcome to hangman')
print('Type one of the following categories')
Animal=['Cat','Dog','Bird','Cow','Fish','Lizard']
Clothing=['Shirt','Jeans','Sweatshirt','Shoes','Hat','Scarf']
Weather=['Rain','Snow','Sunny','Sleet','Windy','Storms']
Colors=['Red','Blue','Green','Purple','Yellow','Grey']
print('Animal, Clothing, Weather, Colors')

category=input()
randomwordindex=random.randint(1,7)
</code>```

Where it says category=input() I want the user input to be one of the lists I have above.  Then I can use category with an random integer to pick a random word to start the game.  How do I get the input() to be the list and not a string value?

Edit: Okay I got it thanks guys.

Here is the code that I have currently.  I'll probably add a for loop eventually and clean up my while loop so it's one line.

```<code>import random

print('Welcome to hangman')
print('Type one of the following categories')

Animal=['Cat','Dog','Bird','Cow','Fish','Lizard']
Clothing=['Shirt','Jeans','Sweatshirt','Shoes','Hat','Scarf']
Weather=['Rain','Snow','Sunny','Sleet','Windy','Stormy']
Colors=['Red','Blue','Green','Purple','Yellow','Grey']

print('Type 1 for Animal, 2 for Clothing, 3 for Weather, 4 for Colors')

category=int(input())

while category > 4:
    print('Your input isn\'t one of the categories. Make sure your choice is a number from 1 to 4.')
    print('Try entering again')
    print('Type 1 for Animal, 2 for Clothing, 3 for Weather, 4 for Colors')
    category=int(input())

while category == 0:
    print('Your input isn\'t one of the categories. Make sure your choice is a number from 1 to 4.')
    print('Try entering again')
    print('Type 1 for Animal, 2 for Clothing, 3 for Weather, 4 for Colors')
    category=int(input())

if category == 1: secretword=random.choice(Animal)
if category == 2: secretword=random.choice(Clothing)
if category == 3: secretword=random.choice(Weather)
if category == 4: secretword=random.choice(Colors)
</code>```

now the variable secretword stores the word that is randomly chosen from the list.

答:
You can check if given input string is a valid option else display valid options and wait till user enters one of the correct option or exit.

You can also display the keys by displaying from dictionary and not hard coding them.

```<code>import sys
import random

categories = {
    'animal': ['Cat','Dog','Bird','Cow','Fish','Lizard'],
    'clothing': ['Shirt','Jeans','Sweatshirt','Shoes','Hat','Scarf'],
    'weather': ['Rain','Snow','Sunny','Sleet','Windy','Storms'],
    'colors': ['Red','Blue','Green','Purple','Yellow','Grey'],
    'exit' : []
    }
keys = ""

print('Welcome to hangman')
print('Type one of the following categories')
for key, value in categories.items():
    keys = keys + key + " "
print(keys)
category = input()
while (True):
    if (category.isalpha() and (category.lower() in categories.keys())):
        if (category.lower() == 'exit'):
            print("Thanks for playing hangman!")
            sys.exit()
        print(categories[category.lower()])
        randomwordindex=random.randint(1,7)
        print(randomwordindex)
        ## TODO : play hangman, for now break to avoid infinite loop
        break
    else:
        print("valid options are: " + keys)
        category = input()
</code>```

Sample Run

```<code>Welcome to hangman
Type one of the following categories
animal clothing weather colors exit
anim
valid options are: animal clothing weather colors exit
clo
valid options are: animal clothing weather colors exit
1231
valid options are: animal clothing weather colors exit
acsa12
valid options are: animal clothing weather colors exit
animal
['Cat', 'Dog', 'Bird', 'Cow', 'Fish', 'Lizard']
7
>>>

=============== RESTART ~/hangman.py ===============
Welcome to hangman
Type one of the following categories
animal clothing weather colors exit
asn
valid options are: animal clothing weather colors exit
1231
valid options are: animal clothing weather colors exit
sadxasdn
valid options are: animal clothing weather colors exit
exit
Thanks for playing hangman!
>>>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
So i'm pretty new to python and i'm making a hangman program.  Here is the code I have so far.

import random
print('Welcome to hangman')
print('Type one of the following categories')
Animal=['Cat','Dog','Bird','Cow','Fish','Lizard']
Clothing=['Shirt','Jeans','Sweatshirt','Shoes','Hat','Scarf']
Weather=['Rain','Snow','Sunny','Sleet','Windy','Storms']
Colors=['Red','Blue','Green','Purple','Yellow','Grey']
print('Animal, Clothing, Weather, Colors')

category=input()
randomwordindex=random.randint(1,7)

Where it says category=input() I want the user input to be one of the lists I have above.  Then I can use category with an random integer to pick a random word to start the game.  How do I get the input() to be the list and not a string value?

Edit: Okay I got it thanks guys.

Here is the code that I have currently.  I'll probably add a for loop eventually and clean up my while loop so it's one line.

import random

print('Welcome to hangman')
print('Type one of the following categories')

Animal=['Cat','Dog','Bird','Cow','Fish','Lizard']
Clothing=['Shirt','Jeans','Sweatshirt','Shoes','Hat','Scarf']
Weather=['Rain','Snow','Sunny','Sleet','Windy','Stormy']
Colors=['Red','Blue','Green','Purple','Yellow','Grey']

print('Type 1 for Animal, 2 for Clothing, 3 for Weather, 4 for Colors')

category=int(input())

while category > 4:
    print('Your input isn\'t one of the categories. Make sure your choice is a number from 1 to 4.')
    print('Try entering again')
    print('Type 1 for Animal, 2 for Clothing, 3 for Weather, 4 for Colors')
    category=int(input())

while category == 0:
    print('Your input isn\'t one of the categories. Make sure your choice is a number from 1 to 4.')
    print('Try entering again')
    print('Type 1 for Animal, 2 for Clothing, 3 for Weather, 4 for Colors')
    category=int(input())

if category == 1: secretword=random.choice(Animal)
if category == 2: secretword=random.choice(Clothing)
if category == 3: secretword=random.choice(Weather)
if category == 4: secretword=random.choice(Colors)

now the variable secretword stores the word that is randomly chosen from the list.

Body:
You can check if given input string is a valid option else display valid options and wait till user enters one of the correct option or exit.

You can also display the keys by displaying from dictionary and not hard coding them.

import sys
import random

categories = {
    'animal': ['Cat','Dog','Bird','Cow','Fish','Lizard'],
    'clothing': ['Shirt','Jeans','Sweatshirt','Shoes','Hat','Scarf'],
    'weather': ['Rain','Snow','Sunny','Sleet','Windy','Storms'],
    'colors': ['Red','Blue','Green','Purple','Yellow','Grey'],
    'exit' : []
    }
keys = ""

print('Welcome to hangman')
print('Type one of the following categories')
for key, value in categories.items():
    keys = keys + key + " "
print(keys)
category = input()
while (True):
    if (category.isalpha() and (category.lower() in categories.keys())):
        if (category.lower() == 'exit'):
            print("Thanks for playing hangman!")
            sys.exit()
        print(categories[category.lower()])
        randomwordindex=random.randint(1,7)
        print(randomwordindex)
        ## TODO : play hangman, for now break to avoid infinite loop
        break
    else:
        print("valid options are: " + keys)
        category = input()

Sample Run

Welcome to hangman
Type one of the following categories
animal clothing weather colors exit
anim
valid options are: animal clothing weather colors exit
clo
valid options are: animal clothing weather colors exit
1231
valid options are: animal clothing weather colors exit
acsa12
valid options are: animal clothing weather colors exit
animal
['Cat', 'Dog', 'Bird', 'Cow', 'Fish', 'Lizard']
7
>>>

=============== RESTART ~/hangman.py ===============
Welcome to hangman
Type one of the following categories
animal clothing weather colors exit
asn
valid options are: animal clothing weather colors exit
1231
valid options are: animal clothing weather colors exit
sadxasdn
valid options are: animal clothing weather colors exit
exit
Thanks for playing hangman!
>>>


问:
In Xcode, the phone simulator orientation is not in portrait form?
I'm using Swift SpriteKit. This is my scene for an app I am currently making:

I made the width and height of the frame so it works with the iphone 7, but when I run it in the iPhone 7 simulator it looks like this:

How do I fix this?

答:
If you mean the simulator is in horizontal orientation:

Open up the simulator, in the menu bar go to Hardware > Rotate Left/Right


问:
UIAlertview in iphone application
I am new to iphone application.I am working on my first app.I have to implement alertview with three textfields and three labels(currentpassword,newpassword,verifypassword) and two uibuttons(submit,cancel).Title is:changepassword.upto now,I found only single textfield and two uibutton fields.can anybody tell me,how can i done this?give me a example or detailed explanation.</p>

答: You've got a lot of stuff there. As the commenters note, a modal viewController is the way to go. You can have it slide up from the bottom and cover everything with setModalTransitionStyle:UIModalTransitionStyleCoverVertical.

ContentLicense: CC BY-SA 2.5

Title: UIAlertview in iphone application


问:
Node.js, PostgreSQL error: no pg_hba.conf entry for host
I am following this article ((http://nodeexamples.com/2012/09/21/connecting-to-a-postgresql-database-from-node-js-using-the-pg-module/). I have already deployed my app to heroku and currently using express, node.js, to try and connect to a PostgresSQL database in Heroku that I just installed. I get to the very end of the article and I use the command

```<code>node myfile.js
</code>```

I get this error

```<code>error: no pg_hba.conf entry for host "...", user "...", database "...", ...
</code>```

How do I go about creating one and where in my app directory should I put it?

Below is the entire error message. I changed the strings for IP address, user, and database but it looks basically just like it.

```<code>events.js:72
    throw er; // Unhandled 'error' event
          ^
error: no pg_hba.conf entry for host "00.000.000.00", user "username", database "databasename", SSL off
at Connection.parseE (/Users/user/workspace/MyApp/app/node_modules/pg/lib/connection.js:526:11)
at Connection.parseMessage (/Users/user/workspace/MyApp/app/node_modules/pg/lib/connection.js:356:17)
at Socket.<anonymous> (/Users/user/workspace/MyApp/app/node_modules/pg/lib/connection.js:105:22)
at Socket.emit (events.js:95:17)
at Socket.<anonymous> (_stream_readable.js:748:14)
at Socket.emit (events.js:92:17)
at emitReadable_ (_stream_readable.js:410:10)
at emitReadable (_stream_readable.js:406:5)
at readableAddChunk (_stream_readable.js:168:9)
at Socket.Readable.push (_stream_readable.js:130:10)
</code>```

Edit: I did some more research and found that the 'pg_hba.conf' file is in my

```<code>/usr/local/var/postgres
</code>```

and I added this line into the 'pg_hba.conf' file

```<code># TYPE  DATABASE        USER            ADDRESS                 METHOD
 host   all             all                                     trust
</code>```

also tried

```<code># TYPE  DATABASE        USER            ADDRESS                 METHOD
host   all             all              0.0.0.0/0               md5
</code>```

but it keeps saying there is no entry for my host, user, database, etc...
is my 'pg_hba.conf' syntax wrong in any way?

答:
In the case sequelize ignores all of your efforts to turn ssl on, you can try to convince pg to enable ssl for all conncetions by default:</p>

```<code>var pg = require('pg');
pg.defaults.ssl = true;

const Sequelize = require('sequelize');
const sequelize = new Sequelize('postgres://...');
</code>```

Body:
I am following this article ((http://nodeexamples.com/2012/09/21/connecting-to-a-postgresql-database-from-node-js-using-the-pg-module/). I have already deployed my app to heroku and currently using express, node.js, to try and connect to a PostgresSQL database in Heroku that I just installed. I get to the very end of the article and I use the command

node myfile.js

I get this error

error: no pg_hba.conf entry for host "...", user "...", database "...", ...

How do I go about creating one and where in my app directory should I put it?

Below is the entire error message. I changed the strings for IP address, user, and database but it looks basically just like it.

events.js:72
    throw er; // Unhandled 'error' event
          ^
error: no pg_hba.conf entry for host "00.000.000.00", user "username", database "databasename", SSL off
at Connection.parseE (/Users/user/workspace/MyApp/app/node_modules/pg/lib/connection.js:526:11)
at Connection.parseMessage (/Users/user/workspace/MyApp/app/node_modules/pg/lib/connection.js:356:17)
at Socket.<anonymous> (/Users/user/workspace/MyApp/app/node_modules/pg/lib/connection.js:105:22)
at Socket.emit (events.js:95:17)
at Socket.<anonymous> (_stream_readable.js:748:14)
at Socket.emit (events.js:92:17)
at emitReadable_ (_stream_readable.js:410:10)
at emitReadable (_stream_readable.js:406:5)
at readableAddChunk (_stream_readable.js:168:9)
at Socket.Readable.push (_stream_readable.js:130:10)

Edit: I did some more research and found that the 'pg_hba.conf' file is in my

/usr/local/var/postgres

and I added this line into the 'pg_hba.conf' file

# TYPE  DATABASE        USER            ADDRESS                 METHOD
 host   all             all                                     trust

also tried

# TYPE  DATABASE        USER            ADDRESS                 METHOD
host   all             all              0.0.0.0/0               md5

but it keeps saying there is no entry for my host, user, database, etc...
is my 'pg_hba.conf' syntax wrong in any way?

Body:
In the case sequelize ignores all of your efforts to turn ssl on, you can try to convince pg to enable ssl for all conncetions by default:

var pg = require('pg');
pg.defaults.ssl = true;

const Sequelize = require('sequelize');
const sequelize = new Sequelize('postgres://...');


问:
Error converting Simple Captcha to string using tesseract
I want to automate some login processes for a ticketing system. There is a simple captcha at the login screen. I am able to take a partial snapshot of it, but as soon as I send that image to image_to_string() function, there is a error. The error says:

"[Win Error 2] The system cannot find the file specified"

答:
The problem here is not that tesseract can't find your image, it's that Windows can't find tesseract.

pytesseract internally runs subprocess.Popen(['tesseract', input_file]), and this throws the error. But if you try subprocess.Popen(['tesseract']), you'll get the exact same error.

If you read the installation instructions you'll see:

You must be able to invoke the tesseract command as tesseract.

And:

If this isn't the case, for example because tesseract isn't in your PATH, you will have to change the "tesseract_cmd" variable at the top of tesseract.py

So you can either add tesseract to your PATH or modify the tesseract_cmd to point directly to your tesseract executable.


问:
How to get a substring from a specific character to the end of the string in swift 4?
I currently have a string containing a path to an image file like so:

```<code>/Users/user/Library/Developer/CoreSimulator/Devices/Hidden/data/Containers/Data/Application/Hidden/Documents/AppName/2017-07-07_21:14:52_0.jpeg
</code>```

I'm trying to retrieve the full name of my image file like so: 2017-07-07_21:14:52_0.jpeg

How would I get the substring starting after the last / to the end of the file path?

I've seen questions related to using substrings:

Swift: How to get substring from start to last index of character

How does String substring work in Swift 3

Substring from String in Swift

However, the provided answers did not help me with my specific problem.

I'm sure it may be something very simple, but all I keep getting is the wrong range of substrings.

Thanks!

答:
Try this :

1)

```<code>var str = "/Users/user/Library/Developer/CoreSimulator/Devices/Hidden/data/Containers/Data/Application/Hidden/Documents/AppName/2017-07-07_21:14:52_0.jpeg"
let array = str.components(separatedBy: "/")

print(array[array.count-1])    //2017-07-07_21:14:52_0.jpeg
</code>```

2)

```<code>let str = "/Users/user/Library/Developer/CoreSimulator/Devices/Hidden/data/Containers/Data/Application/Hidden/Documents/AppName/2017-07-07_21:14:52_0.jpeg"

var fileName = URL(fileURLWithPath: str).lastPathComponent

print(fileName) //2017-07-07_21:14:52_0.jpeg

let fileName = URL(fileURLWithPath: path).deletingPathExtension().lastPathComponent
print(fileName) //2017-07-07_21:14:52_0
</code>```

Body:
I currently have a string containing a path to an image file like so:

/Users/user/Library/Developer/CoreSimulator/Devices/Hidden/data/Containers/Data/Application/Hidden/Documents/AppName/2017-07-07_21:14:52_0.jpeg

I'm trying to retrieve the full name of my image file like so: 2017-07-07_21:14:52_0.jpeg

How would I get the substring starting after the last / to the end of the file path?

I've seen questions related to using substrings:

Swift: How to get substring from start to last index of character

How does String substring work in Swift 3

Substring from String in Swift

However, the provided answers did not help me with my specific problem.

I'm sure it may be something very simple, but all I keep getting is the wrong range of substrings.

Thanks!

Body:
Try this :

1)

var str = "/Users/user/Library/Developer/CoreSimulator/Devices/Hidden/data/Containers/Data/Application/Hidden/Documents/AppName/2017-07-07_21:14:52_0.jpeg"
let array = str.components(separatedBy: "/")

print(array[array.count-1])    //2017-07-07_21:14:52_0.jpeg

2)

let str = "/Users/user/Library/Developer/CoreSimulator/Devices/Hidden/data/Containers/Data/Application/Hidden/Documents/AppName/2017-07-07_21:14:52_0.jpeg"

var fileName = URL(fileURLWithPath: str).lastPathComponent

print(fileName) //2017-07-07_21:14:52_0.jpeg

let fileName = URL(fileURLWithPath: path).deletingPathExtension().lastPathComponent
print(fileName) //2017-07-07_21:14:52_0


问:
Find highest scoring pair of nodes in graph.
I'm trying so solve an optimization problem where I want to find a combination of two nodes with the highest impact/importance in a graph. Lets say I want to base this on betweenness centrality (BC). I guess the more sensible approach is to select one node (maybe one with a high BC), then calculate the BC for the resulting network and then remove the node with the highest value for BC. My goal is to generate a list of the highest scoring combinations of nodes when removed from the original graph. I've implemented a simplified method that picks out random nodes and if the score is higher than the previous, one of the two nodes is reused in the next combination. I'm not sure if this approach is good enough of if the code will "get stuck" at local optima combinations.
Any pointers to steer me in the right direction would be appreciated.</p>

答:
Several approximate betweenness centrality calculation algorithms have been proposed.

Your general method is good, and it is somewhat similar to the one used in Fast approximation of betweenness centrality through sampling [Riondato, Kornaropoulos] 2015. here here.

Quoting:

"Since exact computation in large networks is prohibitively expensive,
  we present two efficient randomized algorithms for betweenness
  estimation. The algorithms are based on random sampling of shortest
  paths and offer probabilistic guarantees on the quality of the
  approximation. [...] The first algorithm estimates the betweenness of all vertices (or edges): all approximate values are within an additive factor ε ∈ (0, 1) from the real values, with probability at least 1 − δ. The second algorithm focuses on the top-K vertices (or edges) with highest betweenness and estimate their betweenness value to within a multiplicative factor ε, with probability at least 1 − δ. This is the first algorithm that can compute such approximation for the top-K vertices (or edges). "

The time complexity for both algorithms is O(r*(|E|+|V| log |V|)), where r is the sample size (which determines the accuracy).

Their second algorithm is quite relevant for your use case (K=2):

"This is the first algorithm that can compute such approximation for
  the top-K vertices (or edges)."


问:
CSS Styling text areas like notebook-look
It is possible to style a text area so each row have a dotted
underline (like a notebook or a notes-block)?

The number of lines should be fixed to lets say 10.

答: Scroll breaks every solution, a complete solution for this should also make lines scroll with text. This is difficult to accomplish just by adding a background image to a textarea.</p>


问:
Flex: Hide (or Remove) Label Text without Changing the Button Size
I have a button with variable-length of label text.  I have a User Setting that can turn on or off the label text on this button.

How can I implement this?

NOTE: the button's background has a gradient color.

I tried using BlendMode.LAYER, no luck;

I tried using Button.resizeHandler

```<code>    private function resizeHandler(event:ResizeEvent):void
    {
        if (event.oldWidth > this.width)
            this.width = event.oldWidth;
        if (event.oldHeight > this.height)
            this.height = event.oldHeight;
    }
</code>```

but it only worked if the initial UserSetting value is true.

How about embedded font? I don't know how to apply it to button

答: You can use the property minWidth and maxWidth. minWidth to specify the minimum width that the button should have. and maxWidth to specify the maximum width the button can have.</p>

Body:
I have a button with variable-length of label text.  I have a User Setting that can turn on or off the label text on this button.

How can I implement this?

NOTE: the button's background has a gradient color.

I tried using BlendMode.LAYER, no luck;

I tried using Button.resizeHandler

    private function resizeHandler(event:ResizeEvent):void
    {
        if (event.oldWidth > this.width)
            this.width = event.oldWidth;
        if (event.oldHeight > this.height)
            this.height = event.oldHeight;
    }

but it only worked if the initial UserSetting value is true.

How about embedded font? I don't know how to apply it to button


问:
CakePHP can't get ajax GET working
I can't seem to get AJAX POST or GET working with my CAKEPHP site. I am trying to create autocomplete but can't seem to submit or fetch the data using ajax.  I can get auto complete working using tags but I cannot display the data from my table. I am not sure what is going wrong if i'm not using the right url or some other problem.
Here is my search.ctp

```<code><?php use Cake\Routing\Router; ?>

    <?php echo $this->Form->input('id', ['type' => 'text']); ?>

<script>
    $.ajax({
    type:       "POST",
    url:        "<?php echo Router::url(array('controller' => 'Invoices', 'action' => 'search')); ?>",
    success:    function(response) {
        $("#id").autocomplete({ source: response });
    }
});
</script>
</code>```

Here is my search function in my InvoicesController.

```<code>    public function search()
{
    $this->loadComponent('RequestHandler');
    if ($this->request->is('ajax'))
    {
        $name = $this->request->query['term'];
        $resultArr = $this->Invoices
    ->find()
    ->where(
        ['Invoices.id LIKE' => ($name . '%')],
        ['Invoices.id' => 'string']
    );

        $resultsArr = [];
        foreach ($resultArr as $result)
        {
             $resultsArr[] = (strval($result['id']));
        }

        $this->set('resultsArr', $resultsArr);
        // This line is what handles converting your array into json
        // To get this to work you must load the request handler
        $this->set('_serialize', ['resultsArr']);

    }
}
</code>```

This is the error that is produced when I try to type in an ID.

This is what i want to produce which I have been able to do by using an array in search.ctp

and here is my table I am trying to fetch the IDs from.

答:
There are two methods.

$this->request->query('term');

$_REQUEST['term'];

Title: CakePHP can't get ajax GET working

Body:
I can't seem to get AJAX POST or GET working with my CAKEPHP site. I am trying to create autocomplete but can't seem to submit or fetch the data using ajax.  I can get auto complete working using tags but I cannot display the data from my table. I am not sure what is going wrong if i'm not using the right url or some other problem.
Here is my search.ctp

<?php use Cake\Routing\Router; ?>

    <?php echo $this->Form->input('id', ['type' => 'text']); ?>

Here is my search function in my InvoicesController.

    public function search()
{
    $this->loadComponent('RequestHandler');
    if ($this->request->is('ajax'))
    {
        $name = $this->request->query['term'];
        $resultArr = $this->Invoices
    ->find()
    ->where(
        ['Invoices.id LIKE' => ($name . '%')],
        ['Invoices.id' => 'string']
    );

        $resultsArr = [];
        foreach ($resultArr as $result)
        {
             $resultsArr[] = (strval($result['id']));
        }

        $this->set('resultsArr', $resultsArr);
        // This line is what handles converting your array into json
        // To get this to work you must load the request handler
        $this->set('_serialize', ['resultsArr']);

    }
}

This is the error that is produced when I try to type in an ID.

This is what i want to produce which I have been able to do by using an array in search.ctp

and here is my table I am trying to fetch the IDs from.


问:
Scala: Replacing double quotes with single quotes
How do you replace single quotes with double quotes in Scala? I have a data file that has some records with "abc" (double quotes). I need to replace these quotes with single quotes and convert it to a data frame. </p>

```<code>val customSchema_1 =
  StructType(Array(
  StructField("ID", StringType, true),
  StructField("KEY", StringType, true),
  StructField("CODE", StringType, true))

val df_1 = sqlContext.read
  .format("com.databricks.spark.csv")
  .option("delimiter", "¦")
  .schema(customSchema_1)
  .load("example")
</code>```

答:
You can create a simple udf to replace double quote with single quote

Here is a simple example

```<code>import org.apache.spark.sql.functions.udf

val removeDoubleQuotes = udf( (x:String) => s.replace("\"","'"))

//If df is the dataframe and use the udf to colName to replace " with '

df.withColumn("colName", removeDoubleQuotes($"colName"))
</code>```

Hope this helps!

Body:
How do you replace single quotes with double quotes in Scala? I have a data file that has some records with "abc" (double quotes). I need to replace these quotes with single quotes and convert it to a data frame.

val customSchema_1 =
  StructType(Array(
  StructField("ID", StringType, true),
  StructField("KEY", StringType, true),
  StructField("CODE", StringType, true))

val df_1 = sqlContext.read
  .format("com.databricks.spark.csv")
  .option("delimiter", "¦")
  .schema(customSchema_1)
  .load("example")

Body:
You can create a simple udf to replace double quote with single quote

Here is a simple example

import org.apache.spark.sql.functions.udf

val removeDoubleQuotes = udf( (x:String) => s.replace("\"","'"))

//If df is the dataframe and use the udf to colName to replace " with '

df.withColumn("colName", removeDoubleQuotes($"colName"))

Hope this helps!


问:
Create database constraints forcing insert into 2 tables at once
Suppose I have 2 database tables user and topic.

Users can have multiple topics, and a topic can have multiple users associated with it. It is a many to many relationship.

I have a user_id PK in the user table and a topic_id PK in the topic table.

I know I can enforce the many to many relationship by using a 3rd child table (call it linking_table) which has a FK to the user_id and a FK to the topic_id.

Suppose I am OK with users being created at will, but I do not want someone to be able to create a topic without it being associated with a user. In other words, I want it such that a topic row should never exist without there being a row in the linking table which links a user to that topic. On the other hand, I also don't want there to be a row in linking_table between a user and a topic which does not exist yet.

It seems I want it to be that you cannot insert a row into topic without also inserting a row into linking_table at the same time.

Is this kind of constraint possible or even reasonable? Without this constraint, it would be possible to insert into the topic table, and not create a link in linking_table at all.

Edit:

Something has occurred to me. It doesn't matter if a topic is created and not associated with a user. I will only be accessing backend data via a user, and the linking table is what will link a user to a topic, so even if theoretically there are topics not connected to users, it doesn't matter from any practical perspective. It's similar to a detached linked list node. Since it isn't referenced, it doesn't matter if it exists, assuming I do some sort of clean up on the table and remove any orphaned topics.

答:
Regarding your statement : In other words, I want it such that a topic row should never exist without there being a row in the linking table which links a user to that topic. --> This is not possible as it is not possible to Insert in both the tables simultaneously.

Regarding your statement : "On the other hand, I also don't want there to be a row in linking_table between a user and a topic which does not exist yet." --> You can add foreign key in the "linking_table" referencing to "topic_id" PK column of "topic table".


问:
String length always 0
I am trying to teach myself C,so I am writing a program to see if a string is present at the end of another string.

```<code>#include <stdio.h>
#include <stdlib.h>

int containsAtEnd(char *s,  char *t);
int strlen(char *s);

int main()
{
    char *x = "tacocat";
    char *y = "bol";
    printf("%d\n", strend(x, y));
    getchar();
    return 0;
}

int strlen(char *s)
{
    int i;
    for (i = 0; i != '\0'; ++i)
        ;
    printf("%d", i);
    return i;
}

int containsAtEnd(char *s, char *t)
{
    int tlen = strlen(*t);
    int slen = strlen(*s);
    int i = 0;
    s += slen - tlen;
    while ((*s == *t) && *s != '\0')
        i++; s++; t++;
    if (i < (tlen-1))
        return 0;
    else
        return 1;
}
</code>```

Yet,  regardless of the strings given in the main function, "001" is always printed, indicating that the length of both the strings in 0 and the second string is present in the first.

答:
Please try if the following code can help you. I would also advice you to use an IDE or an analysis program that tells you about taking pointer from integer without a cast and conditions that are always true (or always false).  </p>

```<code>#include <stdio.h>

int containsAtEnd(char *s,  char *t);
int strlen(char *s);

int strlen(char *s)
{
    int i;
    for (i = 0; s[i] != '\0'; ++i)
        ;
    printf("%d", i);
    return i;
}

int containsAtEnd(char *s, char *t)
{
    int tlen = strlen(t);
    int slen = strlen(s);
    int i = 0;
    s += slen - tlen;
    while ((*s == *t) && *s != '\0') {
        i++; s++; t++;
    }
    if (i < (tlen-1))
        return 0;
    else
        return 1;
}

int main()
{
    char *x = "tacocat";
    char *y = "bol";
    printf("%d\n", containsAtEnd(x, y));

    char *x2 = "foobarbaz";
    char *y2 = "bar";
    printf("%d\n", containsAtEnd(x2, y2));

    getchar();
    return 0;
}
</code>```

Title: String length always 0

Body:
I am trying to teach myself C,so I am writing a program to see if a string is present at the end of another string.

#include <stdio.h>
#include <stdlib.h>

int containsAtEnd(char *s,  char *t);
int strlen(char *s);

int main()
{
    char *x = "tacocat";
    char *y = "bol";
    printf("%d\n", strend(x, y));
    getchar();
    return 0;
}

int strlen(char *s)
{
    int i;
    for (i = 0; i != '\0'; ++i)
        ;
    printf("%d", i);
    return i;
}

int containsAtEnd(char *s, char *t)
{
    int tlen = strlen(*t);
    int slen = strlen(*s);
    int i = 0;
    s += slen - tlen;
    while ((*s == *t) && *s != '\0')
        i++; s++; t++;
    if (i < (tlen-1))
        return 0;
    else
        return 1;
}

Yet,  regardless of the strings given in the main function, "001" is always printed, indicating that the length of both the strings in 0 and the second string is present in the first.

Body:
Please try if the following code can help you. I would also advice you to use an IDE or an analysis program that tells you about taking pointer from integer without a cast and conditions that are always true (or always false).

#include <stdio.h>

int containsAtEnd(char *s,  char *t);
int strlen(char *s);

int strlen(char *s)
{
    int i;
    for (i = 0; s[i] != '\0'; ++i)
        ;
    printf("%d", i);
    return i;
}

int containsAtEnd(char *s, char *t)
{
    int tlen = strlen(t);
    int slen = strlen(s);
    int i = 0;
    s += slen - tlen;
    while ((*s == *t) && *s != '\0') {
        i++; s++; t++;
    }
    if (i < (tlen-1))
        return 0;
    else
        return 1;
}

int main()
{
    char *x = "tacocat";
    char *y = "bol";
    printf("%d\n", containsAtEnd(x, y));

    char *x2 = "foobarbaz";
    char *y2 = "bar";
    printf("%d\n", containsAtEnd(x2, y2));

    getchar();
    return 0;
}


问:
Telegram Bot SDK add command
I am using laravel 5.4 and Telegram Bot SDK.

I want to add a command to my bot.

I try to add StartCommand of the documentation but I get error.

```<code>Command class "Vendor\App\Commands\StartCommand" not found!
</code>```

but the documentation says:

You may store your custom commands in any directory as long as your commands can be autoloaded based on your composer.json settings

and I store StartCommand class in app\StartCommand.php.

here is my composer.json:

```<code>...
,
"autoload": {
    "classmap": [
      "database"
    ],
    "psr-4": {
      "App\\": "app/"
    }
},
...
</code>```

here is telegrom-bot-sdk config at `config\telegram.php:

```<code>...
    'commands' => [
        Telegram\Bot\Commands\HelpCommand::class,
        Vendor\App\Commands\StartCommand::class,
    ],
];
</code>```

答:
I have to use current namespace of my file.

If I store command file in app\, I should use

```<code>namespace App;
</code>```

in my code instead of

```<code>namespace Vendor\App\Commands;
</code>```

and in config\telegram.php:

```<code>...
    'commands' => [
        Telegram\Bot\Commands\HelpCommand::class,
        App\StartCommand::class,
    ],
];
</code>```

Title: Telegram Bot SDK add command

Body:
I am using laravel 5.4 and Telegram Bot SDK.

I want to add a command to my bot.

I try to add StartCommand of the documentation but I get error.

Command class "Vendor\App\Commands\StartCommand" not found!

but the documentation says:

You may store your custom commands in any directory as long as your commands can be autoloaded based on your composer.json settings

and I store StartCommand class in app\StartCommand.php.

here is my composer.json:

...
,
"autoload": {
    "classmap": [
      "database"
    ],
    "psr-4": {
      "App\\": "app/"
    }
},
...

here is telegrom-bot-sdk config at `config\telegram.php:

...
    'commands' => [
        Telegram\Bot\Commands\HelpCommand::class,
        Vendor\App\Commands\StartCommand::class,
    ],
];

Body:
I have to use current namespace of my file.

If I store command file in app\, I should use

namespace App;

in my code instead of

namespace Vendor\App\Commands;

and in config\telegram.php:

...
    'commands' => [
        Telegram\Bot\Commands\HelpCommand::class,
        App\StartCommand::class,
    ],
];


问:
MongoDB: How to execute a query to result of another query (nested queries)?
I need to apply a set of filters (queries) to a collection. By default, the MongoDB applies AND operator to all queries submitted to find function. Instead of whole AND I need to apply each query sequentially (one by one). That is, I need to run the first-query and get a set of documents, run the second-query to result of first-query, and so on.

Is this Possible?

```<code>db.list.find({..q1..}).find({..q2..}).find({..q3..});
</code>```

Instead Of:

```<code>db.list.find({..q1..}, {..q2..}, {..q3..});
</code>```

Why do I need this?

Bcoz, the second-query needs to apply an aggregate function to result of first-query, instead of applying the aggregate to whole collection.

答:
Yes this is possible in MongoDB. You can write nested queries as per the requirement.Even in my application I created nested MongoDb queries.If you are familiar with  SQL syntax then compare this with in of sql syntax:

```<code>     select cname from table where cid in (select .....)
</code>```

In the same way you can create nested MongoDB queries on different collections also.

Body:
I need to apply a set of filters (queries) to a collection. By default, the MongoDB applies AND operator to all queries submitted to find function. Instead of whole AND I need to apply each query sequentially (one by one). That is, I need to run the first-query and get a set of documents, run the second-query to result of first-query, and so on.

Is this Possible?

db.list.find({..q1..}).find({..q2..}).find({..q3..});

Instead Of:

db.list.find({..q1..}, {..q2..}, {..q3..});

Why do I need this?

Bcoz, the second-query needs to apply an aggregate function to result of first-query, instead of applying the aggregate to whole collection.

Body:
Yes this is possible in MongoDB. You can write nested queries as per the requirement.Even in my application I created nested MongoDb queries.If you are familiar with  SQL syntax then compare this with in of sql syntax:

     select cname from table where cid in (select .....)

In the same way you can create nested MongoDB queries on different collections also.


答:
To answer your direct question: You can search for the last
occurrence of a string and get the substring from that position:

```<code>let path = "/Users/user/.../AppName/2017-07-07_21:14:52_0.jpeg"
if let r = path.range(of: "/", options: .backwards) {
    let imageName = String(path[r.upperBound...])
    print(imageName)  // 2017-07-07_21:14:52_0.jpeg
}
</code>```

(Code updated for Swift 4 and later.)

But what you really want is the "last path component" of a file path.
URL has the appropriate method for that purpose:

```<code>let path = "/Users/user/.../AppName/2017-07-07_21:14:52_0.jpeg"
let imageName = URL(fileURLWithPath: path).lastPathComponent
print(imageName) // 2017-07-07_21:14:52_0.jpeg
</code>```

Title: How to get a substring from a specific character to the end of the string in swift 4?

Body:
To answer your direct question: You can search for the last
occurrence of a string and get the substring from that position:

let path = "/Users/user/.../AppName/2017-07-07_21:14:52_0.jpeg"
if let r = path.range(of: "/", options: .backwards) {
    let imageName = String(path[r.upperBound...])
    print(imageName)  // 2017-07-07_21:14:52_0.jpeg
}

(Code updated for Swift 4 and later.)

But what you really want is the "last path component" of a file path.
URL has the appropriate method for that purpose:

let path = "/Users/user/.../AppName/2017-07-07_21:14:52_0.jpeg"
let imageName = URL(fileURLWithPath: path).lastPathComponent
print(imageName) // 2017-07-07_21:14:52_0.jpeg


问:
Java query code for mongodb query
Can Some one help toconvert this mongo query into java code ?
It works fine in mongo command line ,but I am not able run this with java .
Here is mongo query

```<code>db.booking.aggregate([{
        "$match": {
            "bookingDate": {
                "$ne": null,
                "$gte": new Date("2017-04-01"),
                "$lte": new Date("2018-03-31")
            }
        }
    },
    {
        "$project": {
            "totalAmount": 1,
            "totalPax": 1,
            "month": {
                "$month": {
                    $add: ["$bookingDate", 25200000]
                }
            }

        }
    },
    {
        "$group": {
            "_id": "$month",
            "totalPax": {
                "$sum": "$totalPax"
            },
            "totalAmount": {
                "$sum": "$totalAmount"
            },

        }
    }
])
</code>```

This is what I have tried , but its not working ,

```<code>BasicDBObject match = new BasicDBObject("$match", new BasicDBObject("bookingDate",
    new BasicDBObject("$gte", OperationsUtil.getISODateFromUIDate(startDate)).append("$lte",OperationsUtil.getISODateFromUIDate(endDate)).append("$ne", null)));
BasicDBObject match1 = new BasicDBObject("$match", new BasicDBObject("bookingDeleted",false));
BasicDBList add=new BasicDBList();
add.add(new BasicDBObject("$bookingDate",25200000));
BasicDBObject monthDoc=new BasicDBObject("$add",add);
BasicDBObject project = new BasicDBObject("$project",new BasicDBObject("_id",0).append("totalAmount",1).append("totalPax",1).append("month",new BasicDBObject("$month",monthDoc)));
DBObject group = new BasicDBObject("$group", new BasicDBObject("_id","$month")
.append("totalPaxCount", new BasicDBObject("$sum", "$totalPax")).append("totalAmount",new BasicDBObject("$sum", "$totalAmount")));
DBObject sort = new BasicDBObject("$sort", new BasicDBObject("_id", 1));
AggregationOutput cursor = bookingCollection.aggregate(match,match1,project,group,sort);
</code>```

答:
we were able to convert the above query  solution , here is the code for the above query , just answering so that if someone  come across this kind problem can refer this answer </p>

```<code>BasicDBObject match = new BasicDBObject("$match", new BasicDBObject("bookingDate",
                new BasicDBObject("$gte", OperationsUtil.getISODateFromUIDate(startDate)).append("$lte",OperationsUtil.getISODateFromUIDate(endDate)).append("$ne", null)));
     BasicDBObject match1 = new BasicDBObject("$match", new BasicDBObject("bookingDeleted",false).append("tour.travelStatus",new BasicDBObject("$ne", "Unreceipted")));
     BasicDBList addition=new BasicDBList();
     addition.add("$bookingDate");
     addition.add(OperationsConstant.UTC_TO_IST_MILLISECONDS);
     BasicDBObject monthDoc=new BasicDBObject("$add",addition);
     BasicDBObject project = new BasicDBObject("$project",new BasicDBObject("_id",0).append("totalAmount",1).append("totalPax",1).append("month",new BasicDBObject("$month",monthDoc)));
     DBObject group = new BasicDBObject("$group", new BasicDBObject("_id","$month")
             .append("totalPaxCount", new BasicDBObject("$sum", "$totalPax")).append("totalAmount",new BasicDBObject("$sum", "$totalAmount")));
     DBObject sort = new BasicDBObject("$sort", new BasicDBObject("_id", 1));
     AggregationOutput cursor = bookingCollection.aggregate(match,match1,project,group,sort);
</code>```

Title: Java query code for mongodb query

Body:
Can Some one help toconvert this mongo query into java code ?
It works fine in mongo command line ,but I am not able run this with java .
Here is mongo query

db.booking.aggregate([{
        "$match": {
            "bookingDate": {
                "$ne": null,
                "$gte": new Date("2017-04-01"),
                "$lte": new Date("2018-03-31")
            }
        }
    },
    {
        "$project": {
            "totalAmount": 1,
            "totalPax": 1,
            "month": {
                "$month": {
                    $add: ["$bookingDate", 25200000]
                }
            }

        }
    },
    {
        "$group": {
            "_id": "$month",
            "totalPax": {
                "$sum": "$totalPax"
            },
            "totalAmount": {
                "$sum": "$totalAmount"
            },

        }
    }
])

This is what I have tried , but its not working ,

BasicDBObject match = new BasicDBObject("$match", new BasicDBObject("bookingDate",
    new BasicDBObject("$gte", OperationsUtil.getISODateFromUIDate(startDate)).append("$lte",OperationsUtil.getISODateFromUIDate(endDate)).append("$ne", null)));
BasicDBObject match1 = new BasicDBObject("$match", new BasicDBObject("bookingDeleted",false));
BasicDBList add=new BasicDBList();
add.add(new BasicDBObject("$bookingDate",25200000));
BasicDBObject monthDoc=new BasicDBObject("$add",add);
BasicDBObject project = new BasicDBObject("$project",new BasicDBObject("_id",0).append("totalAmount",1).append("totalPax",1).append("month",new BasicDBObject("$month",monthDoc)));
DBObject group = new BasicDBObject("$group", new BasicDBObject("_id","$month")
.append("totalPaxCount", new BasicDBObject("$sum", "$totalPax")).append("totalAmount",new BasicDBObject("$sum", "$totalAmount")));
DBObject sort = new BasicDBObject("$sort", new BasicDBObject("_id", 1));
AggregationOutput cursor = bookingCollection.aggregate(match,match1,project,group,sort);

Body:
we were able to convert the above query  solution , here is the code for the above query , just answering so that if someone  come across this kind problem can refer this answer

BasicDBObject match = new BasicDBObject("$match", new BasicDBObject("bookingDate",
                new BasicDBObject("$gte", OperationsUtil.getISODateFromUIDate(startDate)).append("$lte",OperationsUtil.getISODateFromUIDate(endDate)).append("$ne", null)));
     BasicDBObject match1 = new BasicDBObject("$match", new BasicDBObject("bookingDeleted",false).append("tour.travelStatus",new BasicDBObject("$ne", "Unreceipted")));
     BasicDBList addition=new BasicDBList();
     addition.add("$bookingDate");
     addition.add(OperationsConstant.UTC_TO_IST_MILLISECONDS);
     BasicDBObject monthDoc=new BasicDBObject("$add",addition);
     BasicDBObject project = new BasicDBObject("$project",new BasicDBObject("_id",0).append("totalAmount",1).append("totalPax",1).append("month",new BasicDBObject("$month",monthDoc)));
     DBObject group = new BasicDBObject("$group", new BasicDBObject("_id","$month")
             .append("totalPaxCount", new BasicDBObject("$sum", "$totalPax")).append("totalAmount",new BasicDBObject("$sum", "$totalAmount")));
     DBObject sort = new BasicDBObject("$sort", new BasicDBObject("_id", 1));
     AggregationOutput cursor = bookingCollection.aggregate(match,match1,project,group,sort);


问:
I need to navigate each and every link in the web page and its sub pages links
I am using selenium driver and using a python script to do this.Here is my code.

```<code>d = webdriver.Chrome()
d.get("http://localhost:8080")
list_links = d.find_elements_by_tag_name('a')

for i in list_links:
    print url
</code>```

Above program is properly giving the out put as

```<code>https://www.w3schools.com/
https://www.ubuntu.com/
None
</code>```

But when I compile below code:

```<code>d = webdriver.Chrome()
d.get("http://localhost:8080")
list_links = d.find_elements_by_tag_name('a')

for i in list_links:
    url=i.get_attribute('href')
    print url
    d.get(url)
</code>```

It navigate to the first link https://www.w3schools.com/ successfully.Then it says:

```<code>Traceback (most recent call last):
File "web_nav.py", line 20, in <module>
url=i.get_attribute('href')
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webelement.py", line 141, in get_attribute
resp = self._execute(Command.GET_ELEMENT_ATTRIBUTE, {'name': name})
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webelement.py", line 493, in _execute
return self._parent.execute(command, params)
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 256, in execute
self.error_handler.check_response(response)
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/errorhandler.py", line 194, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
(Session info: chrome=59.0.3071.115)
(Driver info: chromedriver=2.30.477691
(6ee44a7247c639c0703f291d320bdf05c1531b57),platform=Linux 4.4.0-31-
generic x86_64)
</code>```

Here i am using ubuntu 14.04, language python and i'm using selenium web driver

答:
first get all the urls then navigate to them

```<code>d = webdriver.Chrome()
d.get("http://localhost:8080")
list_links =  d.find_elements_by_tag_name('a')
urls = []
for i in list_links:
    urls.append(i.get_attribute('href'))
for url in urls:
    d.get(url)
</code>```

you could simplify this with a function

```<code>def get_link_urls(url,driver):
    driver.get(url)
    urls = []
    for link in d.find_elements_by_tag_name('a'):
        urls.append(link.get_attribute('href'))
    return urls

urls = get_link_urls("http://localhost:8080")
sub_urls = []
for url in urls:
    sub_urls.extend(get_link_urls(url))
</code>```

Body:
I am using selenium driver and using a python script to do this.Here is my code.

d = webdriver.Chrome()
d.get("http://localhost:8080")
list_links = d.find_elements_by_tag_name('a')

for i in list_links:
    print url

Above program is properly giving the out put as

https://www.w3schools.com/
https://www.ubuntu.com/
None

But when I compile below code:

d = webdriver.Chrome()
d.get("http://localhost:8080")
list_links = d.find_elements_by_tag_name('a')

for i in list_links:
    url=i.get_attribute('href')
    print url
    d.get(url)

It navigate to the first link https://www.w3schools.com/ successfully.Then it says:

Traceback (most recent call last):
File "web_nav.py", line 20, in <module>
url=i.get_attribute('href')
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webelement.py", line 141, in get_attribute
resp = self._execute(Command.GET_ELEMENT_ATTRIBUTE, {'name': name})
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webelement.py", line 493, in _execute
return self._parent.execute(command, params)
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 256, in execute
self.error_handler.check_response(response)
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/errorhandler.py", line 194, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
(Session info: chrome=59.0.3071.115)
(Driver info: chromedriver=2.30.477691
(6ee44a7247c639c0703f291d320bdf05c1531b57),platform=Linux 4.4.0-31-
generic x86_64)

Here i am using ubuntu 14.04, language python and i'm using selenium web driver

Body:
first get all the urls then navigate to them

d = webdriver.Chrome()
d.get("http://localhost:8080")
list_links =  d.find_elements_by_tag_name('a')
urls = []
for i in list_links:
    urls.append(i.get_attribute('href'))
for url in urls:
    d.get(url)

you could simplify this with a function

def get_link_urls(url,driver):
    driver.get(url)
    urls = []
    for link in d.find_elements_by_tag_name('a'):
        urls.append(link.get_attribute('href'))
    return urls

urls = get_link_urls("http://localhost:8080")
sub_urls = []
for url in urls:
    sub_urls.extend(get_link_urls(url))


问:
iPhone Development - Setting UIWebView font
I have to show rich text that i pull from server, so i'm using UIWebView. Now the problem is that i have no control over the font which is used in UIWebView. How can i change the font to use system font (making it consistent with rest of the application)?

I'm doing something like this at the moment:

```<code>myRichTextView = [[UIWebView alloc] initWithFrame:CGRectMake(x, y, width, height)];
myRichTextView.backgroundColor = [UIColor clearColor];
[myRichTextView setScalesPageToFit:NO];
[myRichTextView loadHTMLString:myString baseURL:[NSURL URLWithString:myBaseURL]];
</code>```

Again, need to control the display font. If i can't control the font, please let me know other alternatives to UIWebView.

Thanks

答: Reference a css style sheet in your HTML document or put the style information into the top of the HTML document itself</p>

OwnerDisplayName: Mustafa

Body:
I have to show rich text that i pull from server, so i'm using UIWebView. Now the problem is that i have no control over the font which is used in UIWebView. How can i change the font to use system font (making it consistent with rest of the application)?

I'm doing something like this at the moment:

myRichTextView = [[UIWebView alloc] initWithFrame:CGRectMake(x, y, width, height)];
myRichTextView.backgroundColor = [UIColor clearColor];
[myRichTextView setScalesPageToFit:NO];
[myRichTextView loadHTMLString:myString baseURL:[NSURL URLWithString:myBaseURL]];

Again, need to control the display font. If i can't control the font, please let me know other alternatives to UIWebView.

Thanks

OwnerDisplayName: Michael


问:
How to get Exact Time of a MIDI event
I'm trying to read a MIDI file and I want to determine the exact time of a NoteOn event from it in C#.

I tried to use absolute time, but the output was something like 256632.

What is this number ?
This is the line of my code that returns the time :

```<code>(note as NoteOnEvent).AbsoluteTime
</code>```

答:
Delta-times

Time attached to every event in a MIDI file is an offset from the previous event. This offset is called delta-time.

As said by Hans Passant it is stored in a file before an event in special form called variable-length quantity (VLQ). Yes, standard says that VLQ representations must fit in 32 bits (4 bytes). But, theoretically (and there are some real files on the web), larger numbers are possible, so it is much better if a library which provides MIDI file parsing uses integer type bigger than regular int. long for the AbsoluteTime in NAudio is a good choice.

Absolute time

AbsoluteTime property returns just sum of all preceding delta-times and the current event's one.

Meaning of time

What every delta-time or an absolute one actually means depends on time division of a MIDI file. There are two different types of time division:

Ticks Per Quarter Note

SMPTE Time Division

In first case all times expressed as number of ticks. For example, if division is 96, then a delta-time of 48 defines interval of an eighth-note. As also said by Hans Passant NAudio exposes it as the MidiFile.DeltaTicksPerQuarterNote property

In second case all times expressed as number of subdivisions of a second in a way consistent with SMPTE and MIDI Time Code. In practice it is very very very rare type of time division.

"Understandable" representations of time

I think the most "understandable" format for time is metric time (hours, minutes, seconds). As said by Hans Passant and CL you need to know changes of tempo through a MIDI file to calculate metric time of a MIDi event.

There are some libraries that do this calculation for you. For example, with DryWetMIDI you can get metric time of an event with this code:

```<code>MidiFile midiFile = MidiFile.Read("Some MIDI file.mid");
TempoMap tempoMap = midiFile.GetTempoMap();

MetricTimeSpan timeOf10thEvent = midiFile.GetTimedEvents()
                                         .Skip(9)
                                         .First()
                                         .TimeAs<MetricTimeSpan>(tempoMap);
</code>```

With this library you can also get time as bars, beats (using BarBeatTicksTimeSpan or BarBeatFractionTimeSpan) or a fraction of the whole note's length (using MusicalTimeSpan).

Calculation of musical time uses changes of time signature. Both tempo and time signature changes provided by tempo map of a MIDI file that can be obtained with GetTempoMap extension method for MidiFile.

Title: How to get Exact Time of a MIDI event

Body:
I'm trying to read a MIDI file and I want to determine the exact time of a NoteOn event from it in C#.

I tried to use absolute time, but the output was something like 256632.

What is this number ?
This is the line of my code that returns the time :

(note as NoteOnEvent).AbsoluteTime

Body:
Delta-times

Time attached to every event in a MIDI file is an offset from the previous event. This offset is called delta-time.

As said by Hans Passant it is stored in a file before an event in special form called variable-length quantity (VLQ). Yes, standard says that VLQ representations must fit in 32 bits (4 bytes). But, theoretically (and there are some real files on the web), larger numbers are possible, so it is much better if a library which provides MIDI file parsing uses integer type bigger than regular int. long for the AbsoluteTime in NAudio is a good choice.

Absolute time

AbsoluteTime property returns just sum of all preceding delta-times and the current event's one.

Meaning of time

What every delta-time or an absolute one actually means depends on time division of a MIDI file. There are two different types of time division:

Ticks Per Quarter Note

SMPTE Time Division

In first case all times expressed as number of ticks. For example, if division is 96, then a delta-time of 48 defines interval of an eighth-note. As also said by Hans Passant NAudio exposes it as the MidiFile.DeltaTicksPerQuarterNote property

In second case all times expressed as number of subdivisions of a second in a way consistent with SMPTE and MIDI Time Code. In practice it is very very very rare type of time division.

"Understandable" representations of time

I think the most "understandable" format for time is metric time (hours, minutes, seconds). As said by Hans Passant and CL you need to know changes of tempo through a MIDI file to calculate metric time of a MIDi event.

There are some libraries that do this calculation for you. For example, with DryWetMIDI you can get metric time of an event with this code:

MidiFile midiFile = MidiFile.Read("Some MIDI file.mid");
TempoMap tempoMap = midiFile.GetTempoMap();

MetricTimeSpan timeOf10thEvent = midiFile.GetTimedEvents()
                                         .Skip(9)
                                         .First()
                                         .TimeAs<MetricTimeSpan>(tempoMap);

With this library you can also get time as bars, beats (using BarBeatTicksTimeSpan or BarBeatFractionTimeSpan) or a fraction of the whole note's length (using MusicalTimeSpan).

Calculation of musical time uses changes of time signature. Both tempo and time signature changes provided by tempo map of a MIDI file that can be obtained with GetTempoMap extension method for MidiFile.


问:
How can I keep my model files from being refreshed when doing an "Update Model from Database"?
I have a project that uses Entity Framework Database First style development. I made some changes to various Model files, and now every time I do an "Update Model from Database" on my EDMX file, those changes get wiped out. I see there is a tab for Refresh and it has my model files listed, but there is no way to tell VS to not refresh these files. What should I do here? Thanks.</p>

答: Like you said...its DatabaseFirst... so your models file will update from database(not any where else ...not you) .and you should not do it... because every changes will be lose when you update your model from database again! ...if you are change your model for some reason like adding column or(...) you have to do it from your database not here!...but if you changing it for another reasons like adding validation attributes or.. you have to use partial classes!! not writing directly in your model files.  </p>


问:
Saving data from android app to remote server
I am just a beginner in android app development and that's why I have many doubts. I am building one application where the user enters some data in editText. Now I want to save that data in my database. My database is running on my laptop. How would my app connect to the database? Do I need a web server in between? If yes then which web server is used for Android apps? Basically, i want to know the flow of data from app to the database.</p>

答:
Study more from Udacity.com, its free.

You may use a jdbc Connector to connect to database.

Connect your jdbc connector over local network ip\servername and database connection string


问:
CreateDir throws exception in QB64
I have the following code that sometimes returns an error when trying to create a new directory. Sometimes when that directory doesn't exist, it throws an error and does not create the directory. I would like to know why?

```<code>DECLARE DYNAMIC LIBRARY "kernel32"
    FUNCTION CreateDirectoryA% (F$, X$)
    FUNCTION GetLastError& ()
END DECLARE
F$ = "TEMPX" + CHR$(0) ' new directory to create
x = CreateDirectoryA(F$, CHR$(0))
IF x = 0 THEN
    IF GetLastError = &H3E6 THEN
        PRINT "Invalid access to memory location."
    END IF
END IF
</code>```

This code was written in QB64.

答:
This code forces the creation of a directory when the exception x3E6 happens but does explain why the error happens in the first place:</p>

```<code>DECLARE DYNAMIC LIBRARY "kernel32"
    FUNCTION CreateDirectoryA% (F$, X$)
    FUNCTION GetLastError& ()
END DECLARE
DO
    F$ = "TEMPX" + CHR$(0) ' new directory to create
    x = CreateDirectoryA(F$, CHR$(0))
    IF x THEN ' successful create
        EXIT DO
    END IF
    IF x = 0 THEN
        REM Test for Invalid access to memory location.
        IF GetLastError = &H3E6 THEN
            _DELAY .2
        ELSE
            EXIT DO
        END IF
    END IF
LOOP
</code>```

Title: CreateDir throws exception in QB64

Body:
I have the following code that sometimes returns an error when trying to create a new directory. Sometimes when that directory doesn't exist, it throws an error and does not create the directory. I would like to know why?

DECLARE DYNAMIC LIBRARY "kernel32"
    FUNCTION CreateDirectoryA% (F$, X$)
    FUNCTION GetLastError& ()
END DECLARE
F$ = "TEMPX" + CHR$(0) ' new directory to create
x = CreateDirectoryA(F$, CHR$(0))
IF x = 0 THEN
    IF GetLastError = &H3E6 THEN
        PRINT "Invalid access to memory location."
    END IF
END IF

This code was written in QB64.

Body:
This code forces the creation of a directory when the exception x3E6 happens but does explain why the error happens in the first place:

DECLARE DYNAMIC LIBRARY "kernel32"
    FUNCTION CreateDirectoryA% (F$, X$)
    FUNCTION GetLastError& ()
END DECLARE
DO
    F$ = "TEMPX" + CHR$(0) ' new directory to create
    x = CreateDirectoryA(F$, CHR$(0))
    IF x THEN ' successful create
        EXIT DO
    END IF
    IF x = 0 THEN
        REM Test for Invalid access to memory location.
        IF GetLastError = &H3E6 THEN
            _DELAY .2
        ELSE
            EXIT DO
        END IF
    END IF
LOOP


问:
store variable value between program execution in c#
I have 2 console applications.

Application_B and Application_C. Both applications are collecting data from
Application_A.

Lets say if I run Application_B first and it gets data from Application_A. At the same time if I run Application_C it should  display message that values have been filled, or something like that.

答:
I strongly recommend you reading the Application Domain concept before your development phase. Here is an extract.
Source: https://learn.microsoft.com/en-us/dotnet/framework/app-domains/application-domains

Operating systems and runtime environments typically provide some form
  of isolation between applications. For example, Windows uses processes
  to isolate applications. This isolation is necessary to ensure that
  code running in one application cannot adversely affect other,
  unrelated applications. Application domains provide an isolation
  boundary for security, reliability, and versioning, and for unloading
  assemblies. Application domains are typically created by runtime
  hosts, which are responsible for bootstrapping the common language
  runtime before an application is run.

There are also some solutions for your problem that you can take advantage.
Using a shared repository can be a good solution. This Repository can be a file or a database.


问:
How to fetch particular data from Firebase in Android
I have integrated Google sign-in in my app and i am pushing some data in to fire base including user U-id.I had researched a lot and didn't get anything the problem i am facing that i want to fetch Particular data for eg If User A sign-in and push 5 data and Then User B sign-in and push 3 data.I want a query like if User A sing-in Again it will get his 5 data only and not the data which is pushed by User B.Thanks in Advance :)

By using this it fetch all the data from firebase:

```<code> databaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot data : dataSnapshot.getChildren()) {
                FirebaseModel firebasemodel =
      data.getValue(FirebaseModel.class);
                firebasemodels.add(firebasemodel);
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
</code>```

I have tried all that .child .orderby and .equalTo but did'nt work

My Structure is Like:

My FireBase Structure

答:
You also need a reference to the data, which isn't included in your code block.  So something along the lines of (this should be before this):</p>

```<code>DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("notepad-secure/notepad");
</code>```

Body:
I have integrated Google sign-in in my app and i am pushing some data in to fire base including user U-id.I had researched a lot and didn't get anything the problem i am facing that i want to fetch Particular data for eg If User A sign-in and push 5 data and Then User B sign-in and push 3 data.I want a query like if User A sing-in Again it will get his 5 data only and not the data which is pushed by User B.Thanks in Advance :)

By using this it fetch all the data from firebase:

 databaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot data : dataSnapshot.getChildren()) {
                FirebaseModel firebasemodel =
      data.getValue(FirebaseModel.class);
                firebasemodels.add(firebasemodel);
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

I have tried all that .child .orderby and .equalTo but did'nt work

My Structure is Like:

My FireBase Structure

Body:
You also need a reference to the data, which isn't included in your code block.  So something along the lines of (this should be before this):

DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("notepad-secure/notepad");


问:
Swift - Add an UIView that does not overlap current Storyboard's Views
I am trying to accomplish the following task on my drawing app:

I have designed a custom UIView in a .xib file, consisting of only a 'close' button in the UIView. By default, I do not want my app to load this UIView; I would only like for it to load when I press a button on my app's main view. After the view pops up, I would like to still be able to access the other views on my app, while the pop up is still open. Particularly, I would still like to draw lines on the view I have set up as a 'canvas.' Currently, I have added three files for this custom pop up: a class file inherited from UIView called PopUpView.swift, another class file inherited from UIViewController called PopUpViewController.swift, and the .xib file.

In the main ViewController, I have the following code

```<code>var popUp = popUpClass()
@IBAction func showPopUp (sender: UIButton){
    self.view.addSubview(popUp)
    }
</code>```

However, when I click on it, the view does not show up. I am a little confused about what the flow of the code should be and was wondering if anybody could offer me assistance?

Thank you!

答: An issue I encountered when I started building an app that incorporated drawing was that the canvasView when using the override func draw(_ rect: CGRect) draws the lines in the sublayers, so if you are adding any views to the canvas, you will no longer be able to see what you draw. So if you want to add any subviews, add it to a view that is beneath the canvas view and always make sure the canvas view is on top with a clear background color. </p>

Body:
I am trying to accomplish the following task on my drawing app:

I have designed a custom UIView in a .xib file, consisting of only a 'close' button in the UIView. By default, I do not want my app to load this UIView; I would only like for it to load when I press a button on my app's main view. After the view pops up, I would like to still be able to access the other views on my app, while the pop up is still open. Particularly, I would still like to draw lines on the view I have set up as a 'canvas.' Currently, I have added three files for this custom pop up: a class file inherited from UIView called PopUpView.swift, another class file inherited from UIViewController called PopUpViewController.swift, and the .xib file.

In the main ViewController, I have the following code

var popUp = popUpClass()
@IBAction func showPopUp (sender: UIButton){
    self.view.addSubview(popUp)
    }

However, when I click on it, the view does not show up. I am a little confused about what the flow of the code should be and was wondering if anybody could offer me assistance?

Thank you!


问:
ReferenceError: json is not defined when AJAX call the server method
I want to call the server method through the AJAX call. But when I am click the button and call the AJAX function at that time it shows an error.

Here is my code

```<code><input type="button" id="btn_findsubmit" value="Edit" class="button" />

$(document).on("click", "#btn_findsubmit", function (e) {
    var c = $find("<%=cmbobx_search.ClientID %>");
    $.ajax({
        type: "POST",
        url: "schoolregistration.aspx/GetSchoolName",
        data: json.stringify({ schoolname: c.get_textboxcontrol().value }),
        contenttype: "application/json; charset=utf-8",
        datatype: "json",
        success: OnSuccessGetSchoolName,
        failure: function () {
            alert("error! try again...");
        }
    });
});
</code>```

[WebMethod]
[ScriptMethod]

```<code>public static string GetSchoolName(string schoolName){
   //Here is the code
}
</code>```

Now when I click the button at that time JavaScript button click event is working but the ajax method do not calling the server method GetSchoolName (I know by doing debug mode).

And throws a error that:

ReferenceError: json is not defined

答: It should be JSON.stringify, not json.stringify

Body:
I want to call the server method through the AJAX call. But when I am click the button and call the AJAX function at that time it shows an error.

Here is my code

<input type="button" id="btn_findsubmit" value="Edit" class="button" />

$(document).on("click", "#btn_findsubmit", function (e) {
    var c = $find("<%=cmbobx_search.ClientID %>");
    $.ajax({
        type: "POST",
        url: "schoolregistration.aspx/GetSchoolName",
        data: json.stringify({ schoolname: c.get_textboxcontrol().value }),
        contenttype: "application/json; charset=utf-8",
        datatype: "json",
        success: OnSuccessGetSchoolName,
        failure: function () {
            alert("error! try again...");
        }
    });
});

[WebMethod]
[ScriptMethod]

public static string GetSchoolName(string schoolName){
   //Here is the code
}

Now when I click the button at that time JavaScript button click event is working but the ajax method do not calling the server method GetSchoolName (I know by doing debug mode).

And throws a error that:

ReferenceError: json is not defined


问:
Reading steps for date intervals from HealthKit using Swift
I have this method to read today steps from HealthKit.

```<code>func todaySteps(completion: (Double, NSError?) -> () )
{ // this function gives you all of the steps the user has taken since the beginning of the current day.

    let type = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount) // The type of data we are requesting

    let date = NSDate()
    print(date)
    let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
    let newDate = cal.startOfDayForDate(date)
    print(newDate)
    let predicate = HKQuery.predicateForSamplesWithStartDate(newDate, endDate: NSDate(), options: .None) // Our search predicate which will fetch all steps taken today

    // The actual HealthKit Query which will fetch all of the steps and add them up for us.
    let query = HKSampleQuery(sampleType: type!, predicate: predicate, limit: 0, sortDescriptors: nil) { query, results, error in
        var steps: Double = 0

        if results?.count > 0
        {
            for result in results as! [HKQuantitySample]
            {
                steps += result.quantity.doubleValueForUnit(HKUnit.countUnit())
            }
        }

        completion(steps, error)
    }

    executeQuery(query)
}
</code>```

Now lets say if I want to read total steps of each day from 1/june/2016 to 7/june/2016

How can I do that please guide me thanks

答:
Use this to get steps of multiple dates</p>

```<code>func MultipleDaysStepsAndActivities(_ startDate:Date, completion: @escaping (NSDictionary, [HealthKitManuallActivity], NSError?) -> () ) {

    let calender = NSCalendar.current
    let now = Date()
    _ = calender.component(.year, from: now)

    let type = HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount) // The type of data we are requesting
    let predicate = HKQuery.predicateForSamples(withStart: startDate, end: now, options: HKQueryOptions())

    var interval = DateComponents()
    interval.day = 1

    let query = HKStatisticsCollectionQuery(quantityType: type!, quantitySamplePredicate: predicate, options: [.cumulativeSum], anchorDate: startDate, intervalComponents:interval)

    query.initialResultsHandler = { query, results, error in

        if error != nil {
            print(error as Any)
            return
        }

        var dict:[String:Double] = [:]

        if let myResults = results {
            myResults.enumerateStatistics(from: startDate, to: now) {
                statistics, stop in

                if let quantity = statistics.sumQuantity() {

                    let steps = quantity.doubleValue(for: HKUnit.count())
                    print("Steps = \(steps.rounded())")
                    dict[self.fmt.string(from: statistics.startDate)] = steps.rounded()
                }
            }
        }

    }

    execute(query)

}
</code>```

Body:
I have this method to read today steps from HealthKit.

func todaySteps(completion: (Double, NSError?) -> () )
{ // this function gives you all of the steps the user has taken since the beginning of the current day.

    let type = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount) // The type of data we are requesting

    let date = NSDate()
    print(date)
    let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
    let newDate = cal.startOfDayForDate(date)
    print(newDate)
    let predicate = HKQuery.predicateForSamplesWithStartDate(newDate, endDate: NSDate(), options: .None) // Our search predicate which will fetch all steps taken today

    // The actual HealthKit Query which will fetch all of the steps and add them up for us.
    let query = HKSampleQuery(sampleType: type!, predicate: predicate, limit: 0, sortDescriptors: nil) { query, results, error in
        var steps: Double = 0

        if results?.count > 0
        {
            for result in results as! [HKQuantitySample]
            {
                steps += result.quantity.doubleValueForUnit(HKUnit.countUnit())
            }
        }

        completion(steps, error)
    }

    executeQuery(query)
}

Now lets say if I want to read total steps of each day from 1/june/2016 to 7/june/2016

How can I do that please guide me thanks

Body:
Use this to get steps of multiple dates

func MultipleDaysStepsAndActivities(_ startDate:Date, completion: @escaping (NSDictionary, [HealthKitManuallActivity], NSError?) -> () ) {

    let calender = NSCalendar.current
    let now = Date()
    _ = calender.component(.year, from: now)

    let type = HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount) // The type of data we are requesting
    let predicate = HKQuery.predicateForSamples(withStart: startDate, end: now, options: HKQueryOptions())

    var interval = DateComponents()
    interval.day = 1

    let query = HKStatisticsCollectionQuery(quantityType: type!, quantitySamplePredicate: predicate, options: [.cumulativeSum], anchorDate: startDate, intervalComponents:interval)

    query.initialResultsHandler = { query, results, error in

        if error != nil {
            print(error as Any)
            return
        }

        var dict:[String:Double] = [:]

        if let myResults = results {
            myResults.enumerateStatistics(from: startDate, to: now) {
                statistics, stop in

                if let quantity = statistics.sumQuantity() {

                    let steps = quantity.doubleValue(for: HKUnit.count())
                    print("Steps = \(steps.rounded())")
                    dict[self.fmt.string(from: statistics.startDate)] = steps.rounded()
                }
            }
        }

    }

    execute(query)

}


问:
integration between mvc4 application and mongo db
I am currently working on asp.net mvc4 web application. Part of the application, users can log in and browse the site etc. The data for the site is stored in a sql server database, contains users information etc.

A new feature to the site will be for all users to add comments to particular products shown on the site. As there could be hundreds of thousands of customers and thousands of products, this is alot of data.

So I have started looking at a NoSql option for this data and not store it in the relational sql server database. I have been looking at Mongo Db. My first question, is this a correct approach I am taking?

Next topic, how easily does c#/.net integrate with a mongo database. I havent worked with this before so my knowledge in the area is poor. Ideally, I would be querying (for the want of the correct term) the mongo db for comments based on a particular products identifier. I presume I can write a query style to get this data.

My next question is around the redundancy of a mongo db. With sql server, I have a fail over server if an issue occurs with the main db server. Is there a similar concept with mongo or how does it work? My consideration is for mongo to run on the same server as the sql server database. The data in the mongo db will not be mission critical, but the data in sql server is. My web application will run on multiple servers in a load balanced environment.

Can a mongo db be easily moved to another server? ie. how well can it be scaled out. Even can data from it be copied to another mongo db?

I appreciate my questions are of a beginner standard but I am currently researching the topic so assistance would be great.

答:
try this

MVC Application With MongoDB - Part 1

MVC Application With MongoDB - Part 2

Getting Started With MongoDB in ASP.Net MVC4


问:
How to obtain the icons from add / remove programs Control Panel
I'm trying to do an application that basically emulates the add /remove programs feature of Windows Control Panel. I'm currently using the registry, I don't use
WMI because is SO SLOW and only returns the software installed by a .msi file, There are the keys I'm currently reading:

HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall HKLM\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall HKCU\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall

and i have i think all the software installed but there is a problem with the icons, i dont know how to extract the icons that appear on control panel. Some keys have a DisplayIcon property but some other doesn't. I try two things:

First extract the icon for the Application on the DisplayIcon Key.

Second, Try to identify the C:\Windows\Installer\FOLDER to extract a icon for some file there. But is not perfect, i obtain only about 80% of the icons. I know there is a lot of programs that can do this very well.. for example "SoftwareInformer".

I read about it and i found information about ARPPRODUCTICON and WiX an a Icon Table, but i'm not sure where is that table and is there any way to access to it.

Also i search for an open source application that do this without luck.

答: Not all applications listed in the control panel applet have an "application" icon - some just use the default icon for example, "Microsoft Device Emulator (64 bit) version 3.0 - ENU"</p>


问:
How to retrieve database connection from Magento
One of our customer is in a unfortunate situation, his actual hosting provider is not providing the credentials to access the local files, he only has a Magento login with admin/store-manager rights or something like this.

We need to either export the products into a SQL file or access the database login, we cannot open the relative .xml file as we do not have access to the server files. Any idea on how to dump the database except exporting it as CSV?

答:
Go to admin panel

```<code>System ->Tools -> Backups
</code>```

Click on Database Backup. After Finish the process Click on link available in Download column

Body:
Go to admin panel

System ->Tools -> Backups

Click on Database Backup. After Finish the process Click on link available in Download column