问:
SQL - CONCAT with an IF statement returning 1583 error
Is there a limitation with the CONCAT function so that it cannot handle an IF statement?  I have this query, that works if it is not a part of a CONCAT but as soon as I put it inside a CONCAT function it gives this error: #1583 - Incorrect parameters in the call to native function 'CONCAT'

```<code>SELECT CONCAT((IF(DAYOFYEAR(`deathdatetr`) and DAYOFYEAR(`birthdatetr`),TO_DAYS(`deathdatetr`) - TO_DAYS(`birthdatetr`),(YEAR(`deathdatetr`) - YEAR(`birthdatetr`)) * 365))/365.25 as totaldays, " years old") from tng_people order by totaldays limit 1;
</code>```

This query should return the oldest person in the database (age in years). The table I am querying contains among other things, birth- and deathdates in the format "1860-07-30".

Can someone help me figure this out?

答:
I figured it out, thanks to help from @Gordon.  Apparently CONCAT() cannot handle what I THINK is called Aliasing, so once I removed that from the CONCAT() (the "...as total_days"), my query worked fine.

```<code>SELECT CONCAT ("A", FLOOR((to_days(`deathdatetr`) - to_days(`birthdatetr`))/365.25) ) from tng_people order by (to_days(`deathdatetr`) - to_days(`birthdatetr`)) DESC limit 1
</code>```

Thanks for the help!

Body:
Is there a limitation with the CONCAT function so that it cannot handle an IF statement?  I have this query, that works if it is not a part of a CONCAT but as soon as I put it inside a CONCAT function it gives this error: #1583 - Incorrect parameters in the call to native function 'CONCAT'

SELECT CONCAT((IF(DAYOFYEAR(`deathdatetr`) and DAYOFYEAR(`birthdatetr`),TO_DAYS(`deathdatetr`) - TO_DAYS(`birthdatetr`),(YEAR(`deathdatetr`) - YEAR(`birthdatetr`)) * 365))/365.25 as totaldays, " years old") from tng_people order by totaldays limit 1;

This query should return the oldest person in the database (age in years). The table I am querying contains among other things, birth- and deathdates in the format "1860-07-30".

Can someone help me figure this out?

Body:
I figured it out, thanks to help from @Gordon.  Apparently CONCAT() cannot handle what I THINK is called Aliasing, so once I removed that from the CONCAT() (the "...as total_days"), my query worked fine.

SELECT CONCAT ("A", FLOOR((to_days(`deathdatetr`) - to_days(`birthdatetr`))/365.25) ) from tng_people order by (to_days(`deathdatetr`) - to_days(`birthdatetr`)) DESC limit 1

Thanks for the help!


来源: stackexchange

问:
ussp-push from python not working
I would like to write a python script that sends a file to my android phone.
I will run the script from my phone via ssh.
I tried the following codes but none of them was working. I did not get any errors, but when I try to test it I do not get anything on my phone via Bluetooth.

```<code>from subprocess import call

call(['ussp-push', '0C:D6:xx:xx:xx:xx@1x', '/home/pi/alfred.jpg', 'ana.jpg'])
</code>```

***************************************************************

```<code>from subprocess import Popen, PIPE

process = Popen(['ussp-push', '0C:D6:xx:xx:xx:xx@1x', '/home/pi/alfred.jpg' 'ana.jpg'], stdout=PIPE, stderr=PIPE)
stdout, stderr = process.communicate()
</code>```

Does anyone see what the problem could be? Thanks in advance.

答:
```<code>output = check_output(['ussp-push', '0C:D6:xx:xx:xx:xx@1x', '/home/pi/alfred.jpg' 'ana.jpg'], stderr=STDOUT)
</code>```

check_output returns subprocess' stdout and also checks its exit code. So it raises an exception on any error in a subprocess.

ContentLicense: CC BY-SA 3.0

Title: ussp-push from python not working

Body:
I would like to write a python script that sends a file to my android phone.
I will run the script from my phone via ssh.
I tried the following codes but none of them was working. I did not get any errors, but when I try to test it I do not get anything on my phone via Bluetooth.

from subprocess import call

call(['ussp-push', '0C:D6:xx:xx:xx:xx@1x', '/home/pi/alfred.jpg', 'ana.jpg'])

***************************************************************

from subprocess import Popen, PIPE

process = Popen(['ussp-push', '0C:D6:xx:xx:xx:xx@1x', '/home/pi/alfred.jpg' 'ana.jpg'], stdout=PIPE, stderr=PIPE)
stdout, stderr = process.communicate()

Does anyone see what the problem could be? Thanks in advance.

Body:
output = check_output(['ussp-push', '0C:D6:xx:xx:xx:xx@1x', '/home/pi/alfred.jpg' 'ana.jpg'], stderr=STDOUT)

check_output returns subprocess' stdout and also checks its exit code. So it raises an exception on any error in a subprocess.


问:
Removing the last child node DOM
I'm trying to create a page with two different sides, and to that end I have set up in two different divs with IDs of leftSide and rightSide.

Firstly, I add an image node to leftSide five times.

Then, I clone leftSide to the rightSide div, and I want to remove the last image from rightSide so that, in total, I have five images on the left and four images on the right.

However, my code just deletes all five images on the left side, not just the last one:

```<code>function createSmile() {

    for (var i = 0; i < 5; i++) {
        var newImg = document.createElement("img");
        newImg.src = "smile.png";
        var imgPart = document.getElementById("leftSide");
        imgPart.appendChild(newImg);
    }

    document.getElementById("rightSide").appendChild(document.getElementById("leftSide").cloneNode(true));

    document.getElementById("rightSide").removeChild(document.getElementById("rightSide").lastChild);
}
</code>```

答:
This happened because rightSide has only one child which is the clone of leftSide. So you are removing child but what you haveto do is remove grandchild.

Consider using this:

```<code>document.getElementById("rightSide").removeChild(document.getElementById("rightSide").children[0].lastChild);
</code>```

Hope that works
It would also be better if you look at the source code of your html from Google Chrome to understand what javascript produced

Title: Removing the last child node DOM

Body:
I'm trying to create a page with two different sides, and to that end I have set up in two different divs with IDs of leftSide and rightSide.

Firstly, I add an image node to leftSide five times.

Then, I clone leftSide to the rightSide div, and I want to remove the last image from rightSide so that, in total, I have five images on the left and four images on the right.

However, my code just deletes all five images on the left side, not just the last one:

function createSmile() {

    for (var i = 0; i < 5; i++) {
        var newImg = document.createElement("img");
        newImg.src = "smile.png";
        var imgPart = document.getElementById("leftSide");
        imgPart.appendChild(newImg);
    }

    document.getElementById("rightSide").appendChild(document.getElementById("leftSide").cloneNode(true));

    document.getElementById("rightSide").removeChild(document.getElementById("rightSide").lastChild);
}

Body:
This happened because rightSide has only one child which is the clone of leftSide. So you are removing child but what you haveto do is remove grandchild.

Consider using this:

document.getElementById("rightSide").removeChild(document.getElementById("rightSide").children[0].lastChild);

Hope that works
It would also be better if you look at the source code of your html from Google Chrome to understand what javascript produced


问:
replace line in a file C++
I'm trying to find a way to replace a line, containing a string, in a file with a new line.

If the string is not present in the file, then append it to the file.

Can someone give a sample code?

EDIT : is there anyway if the line that i need to replace is at the end of the file?

答:
To replace the last two lines in your file:

Use fopen() to open the file

Get the current file position with fgetpos()

Store always the last two file position and read line by line

When you've reached the end of the file: The lower position is where you have to position to with fseek()

Now you can fprintf() your new lines to the file and close it with fclose() afterwards.

ContentLicense: CC BY-SA 2.5

Title: replace line in a file C++


问:
How to wait until an image is fully loaded in Java
The Java image API assumes asynchronous loading. Various methods take an ImageObserver as a parameter which might get informed once the image is completely loaded.

On the other hand some types of images (e.g. BufferedImages) don't use the ImageObserver and will never call it.

So how would code look that waits until an image is fully loaded?

I'd like to have a method like

```<code>public void waitUntilLoaded(Image img){
    ...
}
</code>```

Which guarantees that the image is completely loaded when it returns.

答: Another alternative I found is to wait until img.getWidth() returns a value different from -1. You can do this in a cleaner way by using Threads and while loops.

Body:
The Java image API assumes asynchronous loading. Various methods take an ImageObserver as a parameter which might get informed once the image is completely loaded.

On the other hand some types of images (e.g. BufferedImages) don't use the ImageObserver and will never call it.

So how would code look that waits until an image is fully loaded?

I'd like to have a method like

public void waitUntilLoaded(Image img){
    ...
}

Which guarantees that the image is completely loaded when it returns.


问:
Is there a way to prevent rails to precompile assets on production?
I have a lot of assets in my project. The precompile task in the server is very slow and exhaust the host (CPU utilization 100%, high average latency).

My idea is to precompile all assets in my localhost and send to GIT (master) all files already precompiled.

In the deploy action (cap production deploy), avoid the precompile task and in the server, prevent any precompile task.

The server uses the already precompiled files sended via capistrano, available in GIT.

Is it possible? If yes, how to do?
If no, there's another solution to avoid server precomile assets?

Below my configs:

Gemfile

```<code>gem 'capistrano-rails', group: :development
gem 'capistrano-faster-assets', '~> 1.0', group: :development
</code>```

Capfile

```<code>require 'capistrano/setup'
require 'capistrano/deploy'
require 'capistrano/rails'
require 'capistrano/faster_assets'

# Load custom tasks from `lib/capistrano/tasks` if you have any defined
Dir.glob('lib/capistrano/tasks/*.rake').each { |r| import r }
</code>```

config/environments/production.rb

```<code>config.assets.js_compressor = :uglifier
config.assets.css_compressor = :sass
config.assets.compile = true
config.assets.digest = true
other assets configs in this file is commented
</code>```

Environment info

```<code>OS: Ubuntu 14.04.2 LTS (GNU/Linux 3.13.0-48-generic x86_64)
ruby -v: ruby 2.2.2p95 (2015-04-13 revision 50295) [x86_64-linux]
rails -v: 4.2.3
nginx -v: nginx/1.8.0
passenger -v: 5.0.10
</code>```

If you need more information, tell me on the comments.

答:
Short answer:

Replace

```<code>require 'capistrano/rails'
</code>```

with

```<code>require 'capistrano/rails/migrations'
require 'capistrano/bundler'
</code>```

Why this works:

When you require capistrano/rails, you are really including the following (source):

```<code>require 'capistrano/bundler'
require 'capistrano/rails/assets'
require 'capistrano/rails/migrations'
</code>```

Each of these can be included separately to get just those pieces of functionality. Per the docs: https://github.com/capistrano/rails#usage

Body:
I have a lot of assets in my project. The precompile task in the server is very slow and exhaust the host (CPU utilization 100%, high average latency).

My idea is to precompile all assets in my localhost and send to GIT (master) all files already precompiled.

In the deploy action (cap production deploy), avoid the precompile task and in the server, prevent any precompile task.

The server uses the already precompiled files sended via capistrano, available in GIT.

Is it possible? If yes, how to do?
If no, there's another solution to avoid server precomile assets?

Below my configs:

Gemfile

gem 'capistrano-rails', group: :development
gem 'capistrano-faster-assets', '~> 1.0', group: :development

Capfile

require 'capistrano/setup'
require 'capistrano/deploy'
require 'capistrano/rails'
require 'capistrano/faster_assets'

# Load custom tasks from `lib/capistrano/tasks` if you have any defined
Dir.glob('lib/capistrano/tasks/*.rake').each { |r| import r }

config/environments/production.rb

config.assets.js_compressor = :uglifier
config.assets.css_compressor = :sass
config.assets.compile = true
config.assets.digest = true
other assets configs in this file is commented

Environment info

OS: Ubuntu 14.04.2 LTS (GNU/Linux 3.13.0-48-generic x86_64)
ruby -v: ruby 2.2.2p95 (2015-04-13 revision 50295) [x86_64-linux]
rails -v: 4.2.3
nginx -v: nginx/1.8.0
passenger -v: 5.0.10

If you need more information, tell me on the comments.

Body:
Short answer:

Replace

require 'capistrano/rails'

with

require 'capistrano/rails/migrations'
require 'capistrano/bundler'

Why this works:

When you require capistrano/rails, you are really including the following (source):

require 'capistrano/bundler'
require 'capistrano/rails/assets'
require 'capistrano/rails/migrations'

Each of these can be included separately to get just those pieces of functionality. Per the docs: https://github.com/capistrano/rails#usage


问:
Classification with Keras Autoencoders
I'm trying to take a vanilla autoencoder using Keras (with a Tensorflow backend) and stop it when the loss value converges to a specific value. After the last epoch, I want to use a sigmoid function to perform classification. Would you know how to go about doing this (or at least point me in the right direction)? </p>

<p>The below code is quite similar to the vanilla autoencoder at http://wiseodd.github.io/techblog/2016/12/03/autoencoders/. (I'm using my own data, but feel free to use the MNIST example in the link to demonstrate what you are talking about.) </p>

```<code>NUM_ROWS = len(x_train)
NUM_COLS = len(x_train[0])

inputs = Input(shape=(NUM_COLS, ))
h = Dense(64, activation='sigmoid')(inputs)
outputs = Dense(NUM_COLS)(h)

# trying to add last sigmoid layer
outputs = Dense(1)
outputs = Activation('sigmoid')

model = Model(input=inputs, output=outputs)

model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
model.fit(x_train, y_train,
    batch_size=batch,
    epochs=epochs,
    validation_data=(x_test, y_test))
</code>```

答:
I have an interpretation of what you are aiming at, however, you don't seem to have a very clear image yourself.
I guess you can clarify if you prepare the necessary dataset yourself.

One possible solution would be as below:

```<code>NUM_ROWS = len(x_train)
NUM_COLS = len(x_train[0])

inputs = Input(shape=(NUM_COLS, ))
h = Dense(64, activation='sigmoid')(inputs)
outputs = Dense(NUM_COLS)(h)

model = Model(input=inputs, output=outputs)

model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
model.fit(x_train, x_train,
    batch_size=batch,
    epochs=epochs,
    validation_data=(x_test, y_test))

h.trainable=False

# trying to add last sigmoid layer
outputs = Dense(1)(h)
outputs = Activation('sigmoid')

model2.fit(x_train, y_train,
    batch_size=batch,
    epochs=epochs,
    validation_data=(x_test, y_test))
</code>```

Title: Classification with Keras Autoencoders

Body:
I'm trying to take a vanilla autoencoder using Keras (with a Tensorflow backend) and stop it when the loss value converges to a specific value. After the last epoch, I want to use a sigmoid function to perform classification. Would you know how to go about doing this (or at least point me in the right direction)?

The below code is quite similar to the vanilla autoencoder at http://wiseodd.github.io/techblog/2016/12/03/autoencoders/. (I'm using my own data, but feel free to use the MNIST example in the link to demonstrate what you are talking about.)

NUM_ROWS = len(x_train)
NUM_COLS = len(x_train[0])

inputs = Input(shape=(NUM_COLS, ))
h = Dense(64, activation='sigmoid')(inputs)
outputs = Dense(NUM_COLS)(h)

# trying to add last sigmoid layer
outputs = Dense(1)
outputs = Activation('sigmoid')

model = Model(input=inputs, output=outputs)

model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
model.fit(x_train, y_train,
    batch_size=batch,
    epochs=epochs,
    validation_data=(x_test, y_test))

Body:
I have an interpretation of what you are aiming at, however, you don't seem to have a very clear image yourself.
I guess you can clarify if you prepare the necessary dataset yourself.

One possible solution would be as below:

NUM_ROWS = len(x_train)
NUM_COLS = len(x_train[0])

inputs = Input(shape=(NUM_COLS, ))
h = Dense(64, activation='sigmoid')(inputs)
outputs = Dense(NUM_COLS)(h)

model = Model(input=inputs, output=outputs)

model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
model.fit(x_train, x_train,
    batch_size=batch,
    epochs=epochs,
    validation_data=(x_test, y_test))

h.trainable=False

# trying to add last sigmoid layer
outputs = Dense(1)(h)
outputs = Activation('sigmoid')

model2.fit(x_train, y_train,
    batch_size=batch,
    epochs=epochs,
    validation_data=(x_test, y_test))


问:
How to properly use enum in column mapping
Let's say we have 2 entities (User and Profile):

```<code>User {
    ID INT NOT NULL,
    STATUS CHAR(5) NOT NULL
}
Profile {
    ID INT NOT NULL,
    STATUS CHAR(5) NOT NULL
}
</code>```

I would map my entities like:

```<code>public class User {
    @Id private Integer id;
    private Status status;
}
public class Profile {
    @Id private Integer id;
    private Status status;
}
public enum Status {
    ACTIVE, INACTIVE, BLOCKED, SUSPENDED, PENDING;
}
@Converter( autoApply = true )
public class StatusConverter implements AttributeConverter<Status,String> {
    // Converter methods omitted for brevity
}
</code>```

Since it works, I believe everything is alright until now.
Some status are equivalent in many entities, like ACTIVE, but there's some status that aren't equals to another entity status. For example a user can have the status BLOCKED, but we never have a blocked Profile (but we have a INACTIVE one).

Now I have some questions I would like your help:

Should I create one enum per entity (like UserStatus and ProfileStatus) so each one have it's own set of "status"? If yes, where should I place the enum? Inside the User entity (User.Status) or some specific package (com.example.enums.UserStatusEnum)?

Should I map it like a table Status { ID INT NOT NULL, CODE CHAR(5) } and let the application manage it? Or even create a new column (ENTITY CHAR(5)) to specify which entity that status corresponds to?

Change the enum to have one attribute to specify it's entities?

I don't see clearly what path I should follow. Do you have another suggestion?

Please, have in mind that there can be more entities, each one with a different set of Status. But these status don't change often, so I don't really believe I need a table on my database.

答:
Design the entities from the application side only. Then design a matching database schema to persist them - so the database is totally subordinate to the application.

Avoid "reusing" entities like status. Perhaps today the statuses of different entities align, but tomorrow they won't. Also, some entities may only be allowed to have a subset of statuses. You'll quickly descend into a mess. And to save what? A few rows and a couple of tiny tables. Not worth it.

Create separate enums, eg UserStatus. Ignore the fact that some status values are shared between entities.

Body:
Let's say we have 2 entities (User and Profile):

User {
    ID INT NOT NULL,
    STATUS CHAR(5) NOT NULL
}
Profile {
    ID INT NOT NULL,
    STATUS CHAR(5) NOT NULL
}

I would map my entities like:

public class User {
    @Id private Integer id;
    private Status status;
}
public class Profile {
    @Id private Integer id;
    private Status status;
}
public enum Status {
    ACTIVE, INACTIVE, BLOCKED, SUSPENDED, PENDING;
}
@Converter( autoApply = true )
public class StatusConverter implements AttributeConverter<Status,String> {
    // Converter methods omitted for brevity
}

Since it works, I believe everything is alright until now.
Some status are equivalent in many entities, like ACTIVE, but there's some status that aren't equals to another entity status. For example a user can have the status BLOCKED, but we never have a blocked Profile (but we have a INACTIVE one).

Now I have some questions I would like your help:

Should I create one enum per entity (like UserStatus and ProfileStatus) so each one have it's own set of "status"? If yes, where should I place the enum? Inside the User entity (User.Status) or some specific package (com.example.enums.UserStatusEnum)?

Should I map it like a table Status { ID INT NOT NULL, CODE CHAR(5) } and let the application manage it? Or even create a new column (ENTITY CHAR(5)) to specify which entity that status corresponds to?

Change the enum to have one attribute to specify it's entities?

I don't see clearly what path I should follow. Do you have another suggestion?

Please, have in mind that there can be more entities, each one with a different set of Status. But these status don't change often, so I don't really believe I need a table on my database.


答:
You clone #leftSide into #rightSide, so #rightSide has only one children. and then you delete last from only one children.

Solution is here

```<code>function createSmile() {

    for (var i = 0; i < 5; i++) {
        var newImg = document.createElement("img");
        newImg.src = "smile.png";

        leftSide.appendChild(newImg);
        rightSide.appendChild(newImg.cloneNode(true));
    }

    //Here you clone WHOLE <div id="leftSide"></div> into <div id="rightSide"></div>
    //document.getElementById("rightSide").appendChild(document.getElementById("leftSide").cloneNode(true));

    rightSide.removeChild(rightSide.lastChild);

}
</code>```

Title: Removing the last child node DOM

Body:
You clone #leftSide into #rightSide, so #rightSide has only one children. and then you delete last from only one children.

Solution is here

function createSmile() {

    for (var i = 0; i < 5; i++) {
        var newImg = document.createElement("img");
        newImg.src = "smile.png";

        leftSide.appendChild(newImg);
        rightSide.appendChild(newImg.cloneNode(true));
    }

    //Here you clone WHOLE <div id="leftSide"></div> into <div id="rightSide"></div>
    //document.getElementById("rightSide").appendChild(document.getElementById("leftSide").cloneNode(true));

    rightSide.removeChild(rightSide.lastChild);

}


问:
convert letters into numbers (A=1; B=2...) c++
I was trying to make letters into numbers in c++. When I write in console  it should count modulo and type out if ship is coming (i did all, but can't make letters into numbers :/ )

This what should happen: ABC a = 1; b=2; c=3    1*2*3=6....

So I need to write a word and it should be separated into letters and converted into numbers like that.

I am just learning and I don't know much :)

My current code:

```<code>int shipnum, groupnum, moduleship, modulegroup;

cout << "type ship number "; cin >> shipnum;
cout << "type group number "; cin >> groupnum;

/*shipnum dabar 5... (5 mod 2)
groupnum dabar 3... (3 mod 2)
*/

moduleship = shipnum % 47;        //skaiciuojam moduli...
modulegroup = groupnum % 47;

if (moduleship == modulegroup) {
 cout << "YES ship is coming for you :)";
 }

else if (moduleship != modulegroup) {             //  "!=" reiskia "nelygu"
    cout << "SORRY, NO ship for you :(";
}

return 0;
</code>```

Body:
I was trying to make letters into numbers in c++. When I write in console  it should count modulo and type out if ship is coming (i did all, but can't make letters into numbers :/ )

This what should happen: ABC a = 1; b=2; c=3    1*2*3=6....

So I need to write a word and it should be separated into letters and converted into numbers like that.

I am just learning and I don't know much :)

My current code:

int shipnum, groupnum, moduleship, modulegroup;

cout << "type ship number "; cin >> shipnum;
cout << "type group number "; cin >> groupnum;

/*shipnum dabar 5... (5 mod 2)
groupnum dabar 3... (3 mod 2)
*/

moduleship = shipnum % 47;        //skaiciuojam moduli...
modulegroup = groupnum % 47;

if (moduleship == modulegroup) {
 cout << "YES ship is coming for you :)";
 }

else if (moduleship != modulegroup) {             //  "!=" reiskia "nelygu"
    cout << "SORRY, NO ship for you :(";
}

return 0;

Body:
"convert letters into numbers (A=1; B=2…)"

 string a{"ABC"};

    int a0 = a[0]; // 65
    int a1 = a[1]; // 66
    int a2 = a[2]; // 67
    .....

want to wrap A = 1, B = 2...

a0 = a0 - (65 - 1);
a1 = a1 - (65 - 1);
....


问:
How can I code my own custom splash screen for Linux?

This is NOT a question on plain old boring customization; I actually want to create an program, you know, with source code, etc...

I'm thinking about programming my own media centre interface, and I figured it'd look better if I coded my own splash screen for when the OS is loading.

Note: The media centre interface will be run in X, but this question is regarding what will happen before the X server loads.

Simply, I'd like to make a splash screen application to hide the linux kernel boot messages. Is there a way I can program some animation in to this like some sort of animated progress bar for example? I assume that I won't be able to code any 2D/3D graphics (as that'd require X to be running, right?), so how would I go about generating that?

I'd prefer to do this in C++, but C is also an option.

Note: I'm not looking to use any existing "themes" or anything like that, just interested in the programming side of things.

Update:

Some suggestions have been to use standard images (.bmp, .jpeg, etc), I am not interested in loading images in to an existing application. But obviously I may want to load images in to the boot screen application that I will make.

I'm not tied to a Linux distro, so this can be for anything, although Debian or a Debian-based distro would be nice.

I like the suggestion about loading the X server early and running a loading screen from there, however is there not a more direct approach? Surely you can make a program which hides the boot messages and shows a custom program? Obviously this would be very low level programming, but that's what I'm looking for...

Also, I'm not interested in altering the boot loader (LILO, GRUB, etc).

Update 2:

So far good suggestions have been looking at the source code for applications like splashy and fbsplash. Can anyone better this suggestion?

答:
If all you want to do is have a nice clean boot sequence with your own splash and absolutely no boot messaging you can do the following:

First, silence grub, boot messaging, and console cursor:

```<code>GRUB_CMDLINE_LINUX_DEFAULT = quiet fastboot splash vt.cur_default=1 loglevel=0
GRUB_TIMEOUT               = 0
</code>```

This will very quickly and silently (fade to black) bring you to your login screen, where you can place a splash. Your distro may show it's own splash briefly, which you can change if you like.

This yeilds a professional clean boot sequence, without all the usual linux warts and wrinkles. (Like OSX and Windows).

I personally use Ubunutu with LXDE, and have a clean splashy boot in under 3 seconds, even on older hardware.

OwnerDisplayName: Nick Bolton

LastEditorDisplayName: Nick Bolton

Body:
If all you want to do is have a nice clean boot sequence with your own splash and absolutely no boot messaging you can do the following:

First, silence grub, boot messaging, and console cursor:

GRUB_CMDLINE_LINUX_DEFAULT = quiet fastboot splash vt.cur_default=1 loglevel=0
GRUB_TIMEOUT               = 0

This will very quickly and silently (fade to black) bring you to your login screen, where you can place a splash. Your distro may show it's own splash briefly, which you can change if you like.

This yeilds a professional clean boot sequence, without all the usual linux warts and wrinkles. (Like OSX and Windows).

I personally use Ubunutu with LXDE, and have a clean splashy boot in under 3 seconds, even on older hardware.


问:
pip inatall python's libraries via pip
I am trying to instal xlrd, panda  for my python version 3.6

I am using window 10. By way of input:

```<code>pip install xlrd
</code>```

from my window command.
I cannot proceed install and I have the following in return:

'pip' is not recognized as an internal or external command, operable
  program or batch file.

Does anyonw know why and how can I get round it. I am the sole user of this PC so I am not sure what can go wrong.

Thanks

答:
Usually, pip comes with Python 3.6 version (while installing you have option to select pip to install)

If you have already installed. You can see if pip is installed in this path

C:..\Python\Scripts\

If so, then you have to add this to PATH Environment Variables

That will solve your problem!

Title: pip inatall python's libraries via pip

Body:
I am trying to instal xlrd, panda  for my python version 3.6

I am using window 10. By way of input:

pip install xlrd

from my window command.
I cannot proceed install and I have the following in return:

'pip' is not recognized as an internal or external command, operable
  program or batch file.

Does anyonw know why and how can I get round it. I am the sole user of this PC so I am not sure what can go wrong.

Thanks


问:
Someone ran 'pod update' and now my app crashes with podfile.lock issue
We have gone through all the steps a million times:

```<code>$ sudo gem install cocoapods
$ rm -rf Bizzy\ Books.xcworkspace
$ pod install
</code>```

Deleting derived data... changing build settings...

NOTHING is working! And all because one guy ran "pod update" and then didn't know what to do after that!

This is the error code:

PhaseScriptExecution [CP]\ Check\ Pods\ Manifest.lock
  /Users/Owner/Library/Developer/Xcode/DerivedData/Bizzy_Books-ajpeiroanshownarpormfcnuuvik/Build/Intermediates/Bizzy\
  Books.build/Debug-iphoneos/Bizzy\
  Books.build/Script-76499205B9A6D7551C8D0832.sh
      cd "/Users/Owner/Desktop/Bizzy Books"
      /bin/sh -c \"/Users/Owner/Library/Developer/Xcode/DerivedData/Bizzy_Books-ajpeiroanshownarpormfcnuuvik/Build/Intermediates/Bizzy\
  Books.build/Debug-iphoneos/Bizzy\
  Books.build/Script-76499205B9A6D7551C8D0832.sh\"

diff: /Podfile.lock: No such file or directory error: The sandbox is
  not in sync with the Podfile.lock. Run 'pod install' or update your
  CocoaPods installation.

I am looking for somebody that knows what they are doing on this!

Plus, people are blaming me for having "old code" which is only like a week or two since the last pod install in which I had no problems. And there are no errors shown with the code, only with the podfile.lock issue.

And people are downloading from Github and saying it works fine therefore I have no problem, which doesn't help me, because when I pull from Github, it makes no difference, showing the same error!

Here is the github repository:
https://github.com/caldwbr/Bizzy-Books-iOS

答:
Well I finally got it working.

I opened the folder for my app and deleted Bizzy Books.workspace, Podfile, Podfile.lock, and the Pods folder, and emptied the trashcan. (Fairly important, if you don't want to see a slew of red untracked files hanging around after you do 'git status')

Then I navigated inside terminal to this same folder and ran:

```<code>git fetch --all

git reset --hard origin/master
</code>```

Then I tested, and it worked!

I had been doing "git fetch --all" followed by "git pull --hard origin master," but I needed to do "git fetch --all" followed by "git reset --hard origin/master" and MAKE SURE NOT to do any "pod install" or "pod update"! That is the command that is giving me grief!

So thankful this is fixed!!!

There must be some incompatibility with a newer version of on of the pods in my podfile that just isn't working, hence I have to go back to the older version of that pod (not of cocoapods itself I don't think). Or there may be an issue with podfile.lock being funky as when you run 'pod update' or 'pod install' it generates a new podfile.lock file.

Body:
We have gone through all the steps a million times:

$ sudo gem install cocoapods
$ rm -rf Bizzy\ Books.xcworkspace
$ pod install

Deleting derived data... changing build settings...

NOTHING is working! And all because one guy ran "pod update" and then didn't know what to do after that!

This is the error code:

PhaseScriptExecution [CP]\ Check\ Pods\ Manifest.lock
  /Users/Owner/Library/Developer/Xcode/DerivedData/Bizzy_Books-ajpeiroanshownarpormfcnuuvik/Build/Intermediates/Bizzy\
  Books.build/Debug-iphoneos/Bizzy\
  Books.build/Script-76499205B9A6D7551C8D0832.sh
      cd "/Users/Owner/Desktop/Bizzy Books"
      /bin/sh -c \"/Users/Owner/Library/Developer/Xcode/DerivedData/Bizzy_Books-ajpeiroanshownarpormfcnuuvik/Build/Intermediates/Bizzy\
  Books.build/Debug-iphoneos/Bizzy\
  Books.build/Script-76499205B9A6D7551C8D0832.sh\"

diff: /Podfile.lock: No such file or directory error: The sandbox is
  not in sync with the Podfile.lock. Run 'pod install' or update your
  CocoaPods installation.

I am looking for somebody that knows what they are doing on this!

Plus, people are blaming me for having "old code" which is only like a week or two since the last pod install in which I had no problems. And there are no errors shown with the code, only with the podfile.lock issue.

And people are downloading from Github and saying it works fine therefore I have no problem, which doesn't help me, because when I pull from Github, it makes no difference, showing the same error!

Here is the github repository:
https://github.com/caldwbr/Bizzy-Books-iOS

Body:
Well I finally got it working.

I opened the folder for my app and deleted Bizzy Books.workspace, Podfile, Podfile.lock, and the Pods folder, and emptied the trashcan. (Fairly important, if you don't want to see a slew of red untracked files hanging around after you do 'git status')

Then I navigated inside terminal to this same folder and ran:

git fetch --all

git reset --hard origin/master

Then I tested, and it worked!

I had been doing "git fetch --all" followed by "git pull --hard origin master," but I needed to do "git fetch --all" followed by "git reset --hard origin/master" and MAKE SURE NOT to do any "pod install" or "pod update"! That is the command that is giving me grief!

So thankful this is fixed!!!

There must be some incompatibility with a newer version of on of the pods in my podfile that just isn't working, hence I have to go back to the older version of that pod (not of cocoapods itself I don't think). Or there may be an issue with podfile.lock being funky as when you run 'pod update' or 'pod install' it generates a new podfile.lock file.


问:
Scope Issue (NodeJS - "request" package)
I'm having an issue with the scope of a variable. I need to be able to access "userLocation" outside of "request". The request package can be found at https://github.com/request/request Here's my code below:

```<code>var request = require('request');
var userLocation = "";
request('http://ipinfo.io', function(error, res, body) {
    var ipDetails   = JSON.parse(body);
    userLocation    = ipDetails.loc;
});
console.log(userLocation);
</code>```

When I try to output the "userLocation" variable, it prints an empty string instead of the details from the request package.

答:
It's not a scope issue. The nature of NodeJS is asynchronous, meaning that console.log(userLocation) will not wait your request to be completed before it executes. That's why promises and callback functions exist.

If you want to print userLocation, move it inside the callback function like so:

```<code>var request = require('request');
var userLocation = "";
request('http://ipinfo.io', function(error, res, body) {
    var ipDetails = JSON.parse(body);
    var userLocation = ipDetails.loc;
    console.log(userLocation);
});
</code>```

Take a look at this awesome tutorial if you wish to learn more.

Body:
I'm having an issue with the scope of a variable. I need to be able to access "userLocation" outside of "request". The request package can be found at https://github.com/request/request Here's my code below:

var request = require('request');
var userLocation = "";
request('http://ipinfo.io', function(error, res, body) {
    var ipDetails   = JSON.parse(body);
    userLocation    = ipDetails.loc;
});
console.log(userLocation);

When I try to output the "userLocation" variable, it prints an empty string instead of the details from the request package.

Body:
It's not a scope issue. The nature of NodeJS is asynchronous, meaning that console.log(userLocation) will not wait your request to be completed before it executes. That's why promises and callback functions exist.

If you want to print userLocation, move it inside the callback function like so:

var request = require('request');
var userLocation = "";
request('http://ipinfo.io', function(error, res, body) {
    var ipDetails = JSON.parse(body);
    var userLocation = ipDetails.loc;
    console.log(userLocation);
});

Take a look at this awesome tutorial if you wish to learn more.


问:
Sort program not working, not sure why

void sort(int values[], int n)
{
    int smallestSpot = 0;
    for (long long i = 0; i < n ; i++)
    {
        int smallest = values[i];
        for(long long j = i; j < n - i ; j++) //find the smallest int in array
        {
            if(values[j] < smallest)
            {
                smallestSpot = j;
                smallest = values[j];
            }
        }
        values[smallestSpot] = values[i];
        values[i] = smallest;
    }
    return;
}
```

My sorting algorithm overwrites what the first number is, and I can't find out why, please help. Thanks.

答:
Thanks for COLDSPEED and GAURANG VYAS by perform that changes we reachs to working version of code.

Code

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

void sort(int values[], int n){

    int smallestSpot = 0;

    for (long long i = 0; i < n ; i++){

        int smallest = values[i];
        smallestSpot = i;

        for(long long j = i+1; j < n  ; j++){ //find the smallest      int in array
            if(values[j] < smallest){
                smallestSpot = j;
                smallest = values[j];
            }
        }

            values[smallestSpot] = values[i];
            values[i] = smallest;
    }
}

int main(void){

    int arr[5] = {8,1,9,10,2};
    sort(arr,5);
    for(int i=0;i<5;i++){
        printf("%d\n",arr[i]);
    }

    return 0;
}
</code>```

Before try to coding trace your algorithm with pen and paper.
We have many sorting algorithms i suggest to see this link and gain a visual understanding about sorting problems and way of solving them.

Edit

Show output

Title: Sort program not working, not sure why

Body:
void sort(int values[], int n)
{
    int smallestSpot = 0;
    for (long long i = 0; i < n ; i++)
    {
        int smallest = values[i];
        for(long long j = i; j < n - i ; j++) //find the smallest int in array
        {
            if(values[j] < smallest)
            {
                smallestSpot = j;
                smallest = values[j];
            }
        }
        values[smallestSpot] = values[i];
        values[i] = smallest;
    }
    return;
}

My sorting algorithm overwrites what the first number is, and I can't find out why, please help. Thanks.

Body:
Thanks for COLDSPEED and GAURANG VYAS by perform that changes we reachs to working version of code.

Code

#include <stdio.h>

void sort(int values[], int n){

    int smallestSpot = 0;

    for (long long i = 0; i < n ; i++){

        int smallest = values[i];
        smallestSpot = i;

        for(long long j = i+1; j < n  ; j++){ //find the smallest      int in array
            if(values[j] < smallest){
                smallestSpot = j;
                smallest = values[j];
            }
        }

            values[smallestSpot] = values[i];
            values[i] = smallest;
    }
}

int main(void){

    int arr[5] = {8,1,9,10,2};
    sort(arr,5);
    for(int i=0;i<5;i++){
        printf("%d\n",arr[i]);
    }

    return 0;
}

Before try to coding trace your algorithm with pen and paper.
We have many sorting algorithms i suggest to see this link and gain a visual understanding about sorting problems and way of solving them.

Edit

Show output

ContentLicense: CC BY-SA 4.0


问:
Get the value from callback function and set to parent function
I am new to Nodejs and javascript and working on nodejs api code. I am using GandiAPI to check domainAvaliablity(Project related requirement)    and have created a get request method (checkDomainAvaliablity) like this.

```<code>  exports.checkDomainAvaliablity = function (req, res) {
  gandiApi.methodCall('domain.available', [gandiapikey, [domain]], callback)
  };
</code>```

And I have a callback function which have 2 parameters(which I can not change).
I am able to get the value succesfully in my callback function.
Now I want to return "value" from callback and want to set in "res"  paramameter of checkDomainAvaliablity function(Parent function) (something like res.json(task)) .

```<code> var callback = function (error, value) {

   console.dir(value)
   if (value[domain] == 'pending') {
   console.log('result is not yet ready')
   setTimeout(function () {
   gandiApi.methodCall('domain.available', [gandiapikey, [domain]],
   callback)
   }, 700)
   }
   else {
    console.dir(value)
   }

   // I want to return "value" from here and want to set in "res"  paramameter of checkDomainAvaliablity function (Parent function).
 }
</code>```

Note: Use of callbackfuncion is neccessary.

答:
Thanks @trincot. Putting the callback function inside the parent function works fine.

exports.checkDomainAvaliablity = function (req, res) {
  domain = req.params.domainAvaliablity
  var callback = function (error, value) {
    console.log("logging" + value + error)
    if (value[domain] == 'pending') {
      console.log('result is not yet ready')
      setTimeout(function () {
        gandiApi.methodCall('domain.available', [gandiapikey, [domain]],
          callback)
      }, 700)
    }
    else {
      res.send(value);
      console.dir(value)
    }

  }

  gandiApi.methodCall('domain.available', [gandiapikey, [domain]], callback)

};```

Body:
I am new to Nodejs and javascript and working on nodejs api code. I am using GandiAPI to check domainAvaliablity(Project related requirement)    and have created a get request method (checkDomainAvaliablity) like this.

  exports.checkDomainAvaliablity = function (req, res) {
  gandiApi.methodCall('domain.available', [gandiapikey, [domain]], callback)
  };

And I have a callback function which have 2 parameters(which I can not change).
I am able to get the value succesfully in my callback function.
Now I want to return "value" from callback and want to set in "res"  paramameter of checkDomainAvaliablity function(Parent function) (something like res.json(task)) .

 var callback = function (error, value) {

   console.dir(value)
   if (value[domain] == 'pending') {
   console.log('result is not yet ready')
   setTimeout(function () {
   gandiApi.methodCall('domain.available', [gandiapikey, [domain]],
   callback)
   }, 700)
   }
   else {
    console.dir(value)
   }

   // I want to return "value" from here and want to set in "res"  paramameter of checkDomainAvaliablity function (Parent function).
 }

Note: Use of callbackfuncion is neccessary.


问:
Push local changes to my live hosting
I want to know what is the recommended workflow with git.

I have a local environment on xampp, I make some changes, update my local git, push the updated files to my github repo and then upload the files via ftp.
I want that when I push the files to my github repo, my live website (bluehost server) will get the updated files too, without using ftp.
Here my current workflow:

changes on my localhost

commit to my local repo (git bash)

push to github repo

upload the files via ftp to my bluehost server

How can I improve my workflow?

I  heard SSH but I have no idea what it means and how to use it, SSH is the best way?

Thanks.

答: For this i use sourcetre and bitbucket. Bitbucket have pipeline (deployment tool) feature.</p>

Title: Push local changes to my live hosting


问:
Crash when restoring purchases in swift
I'm running into some confusing behavior with my in-app purchases restore feature. Currently, I have the restore feature linked to a button, it seems to crash when I activate it multiple times. For example, if I hit it, restore, navigate to another view, then back to hit the restore again it will crash.

Can anyone check my code and see if I'm missing something staring me in the face?

```<code>import SpriteKit
import StoreKit

class PurchaseView: SKScene, SKPaymentTransactionObserver, SKProductsRequestDelegate{

var instructLabel = SKLabelNode()
var priceLabel = SKLabelNode()

var saleBadgeIcon = SKSpriteNode()
var backIcon = SKSpriteNode()
var restoreIcon = SKSpriteNode()

var blueDiceDemo = SKSpriteNode()
var redDiceDemo = SKSpriteNode()
var greenDiceDemo = SKSpriteNode()
var grayDiceDemo = SKSpriteNode()

var bluePID: String = "dice.blue.add"
var redPID: String = "dice.red.add"
var greenPID: String = "dice.green.add"
var grayPID: String = "dice.gray.add"

private var request : SKProductsRequest!
private var products : [SKProduct] = []

private var blueDicePurchased : Bool = false
private var redDicePurchased : Bool = false
private var greenDicePurchased : Bool = false
private var grayDicePurchased : Bool = false

override func didMoveToView(view: SKView) {
    // In-App Purchase
    initInAppPurchases()

    /*
    checkAndActivateGreenColor()
    checkAndActivateRedColor()
    checkAndActivateGrayColor()
    checkAndActivateBlueColor()
    */

    createInstructionLabel()
    createBackIcon()
    createRestoreIcon()
    createBlueDicePurchase()
    createRedDicePurchase()
    createGreenDicePurchase()
    createGrayDicePurchase()

    checkAndActivateDiceColor(bluePID)
    checkAndActivateDiceColor(redPID)
    checkAndActivateDiceColor(greenPID)
    checkAndActivateDiceColor(grayPID)
}

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    for touch in touches {
        let location = touch.locationInNode(self)
        let node = nodeAtPoint(location)

        if (node == backIcon) {
            let gameScene = GameScene(size: self.size)
            let transition = SKTransition.doorsCloseVerticalWithDuration(0.5)
            gameScene.scaleMode = SKSceneScaleMode.ResizeFill
            gameScene.backgroundColor = SKColor.whiteColor()
            self.scene!.view?.presentScene(gameScene, transition: transition)
        } else if (node == restoreIcon) {
            print("restore my purchases")

            let alert = UIAlertController(title: "Restore Purchases", message: "", preferredStyle: UIAlertControllerStyle.Alert)

            alert.addAction(UIAlertAction(title: "Restore", style: UIAlertActionStyle.Default) { _ in
                self.restorePurchasedProducts()
                })

            alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Default) { _ in

                })

            // Show the alert
            self.view?.window?.rootViewController?.presentViewController(alert, animated: true, completion: nil)

            //restorePurchasedProducts()
        } else if (node == blueDiceDemo) {
            print("buy blue")
            if (!blueDicePurchased) {
                inAppPurchase(blueDicePurchased, pid: bluePID)
            }
        } else if (node == redDiceDemo) {
            print("buy red")
            if (!redDicePurchased) {
                inAppPurchase(redDicePurchased, pid: redPID)
            }
        } else if (node == greenDiceDemo) {
            print("buy green")
            if (!greenDicePurchased) {
                inAppPurchase(greenDicePurchased, pid: greenPID)
            }
        } else if (node == grayDiceDemo) {
            print("buy gray")
            if (!grayDicePurchased) {
                inAppPurchase(grayDicePurchased, pid: grayPID)
            }
        }
    }
}

func createBlueDicePurchase() {
    blueDiceDemo = SKSpriteNode(imageNamed: "dice1_blue")
    blueDiceDemo.setScale(0.6)
    blueDiceDemo.position = CGPoint(x: CGRectGetMidX(self.frame) + blueDiceDemo.size.width * 2, y: CGRectGetMidY(self.frame))
    addChild(blueDiceDemo)

    createSaleBadge(blueDiceDemo)
}

func createGrayDicePurchase() {
    grayDiceDemo = SKSpriteNode(imageNamed: "dice1_gray")
    grayDiceDemo.setScale(0.6)
    grayDiceDemo.position = CGPoint(x: CGRectGetMidX(self.frame), y: CGRectGetMidY(self.frame))
    addChild(grayDiceDemo)

    createSaleBadge(grayDiceDemo)
}

func createRedDicePurchase() {
    redDiceDemo = SKSpriteNode(imageNamed: "dice1_red")
    redDiceDemo.setScale(0.6)
    redDiceDemo.position = CGPoint(x: CGRectGetMidX(self.frame) - blueDiceDemo.size.width * 2, y: CGRectGetMidY(self.frame))
    addChild(redDiceDemo)

    createSaleBadge(redDiceDemo)
}

func createGreenDicePurchase() {
    greenDiceDemo = SKSpriteNode(imageNamed: "dice1_green")
    greenDiceDemo.setScale(0.6)
    greenDiceDemo.position = CGPoint(x: CGRectGetMidX(self.frame), y: CGRectGetMidY(self.frame) - blueDiceDemo.size.height * 1.5)
    addChild(greenDiceDemo)

    createSaleBadge(greenDiceDemo)
}

func createInstructionLabel() {
    instructLabel = SKLabelNode(fontNamed: "Helvetica")
    instructLabel.text = "Click item to purchase!"
    instructLabel.fontSize = 24
    instructLabel.fontColor = SKColor.blackColor()
    instructLabel.position = CGPoint(x: CGRectGetMidX(self.frame), y: CGRectGetMaxY(self.frame) - 50)
    addChild(instructLabel)
}

func createPurchasedLabel(node: SKSpriteNode) {
    let purchasedLabel = SKLabelNode(fontNamed: "Helvetica")
    purchasedLabel.text = "purchased"
    purchasedLabel.fontSize = 30
    purchasedLabel.zPosition = 2
    purchasedLabel.fontColor = SKColor.blackColor()
    purchasedLabel.position = CGPoint(x: 0, y: -7.5)
    node.addChild(purchasedLabel)
}

func createRestoreIcon() {
    restoreIcon = SKSpriteNode(imageNamed: "download")
    restoreIcon.setScale(0.4)
    restoreIcon.position = CGPoint(x: CGRectGetMinX(self.frame) + 30, y: CGRectGetMinY(self.frame) + 30)
    addChild(restoreIcon)
}

func createBackIcon() {
    backIcon = SKSpriteNode(imageNamed: "remove")
    backIcon.setScale(0.5)
    backIcon.position = CGPoint(x: CGRectGetMaxX(self.frame) - 30, y: CGRectGetMinY(self.frame) + 30)
    addChild(backIcon)
}

func createSaleBadge(node: SKSpriteNode) {
    saleBadgeIcon = SKSpriteNode(imageNamed: "badge")
    saleBadgeIcon.setScale(0.4)
    saleBadgeIcon.zPosition = 2
    saleBadgeIcon.position = CGPoint(x: node.size.width/2, y: node.size.height/2)
    node.addChild(saleBadgeIcon)
}

func inAppPurchase(dicePurchased: Bool, pid: String) {
    let alert = UIAlertController(title: "In-App Purchases", message: "", preferredStyle: UIAlertControllerStyle.Alert)

    // Add an alert action for each available product
    for (var i = 0; i < products.count; i++) {
        let currentProduct = products[i]
        if (currentProduct.productIdentifier == pid && !dicePurchased) {
            // Get the localized price
            let numberFormatter = NSNumberFormatter()
            numberFormatter.numberStyle = .CurrencyStyle
            numberFormatter.locale = currentProduct.priceLocale
            // Add the alert action
            alert.addAction(UIAlertAction(title: currentProduct.localizedTitle + " " + numberFormatter.stringFromNumber(currentProduct.price)!, style: UIAlertActionStyle.Default)  { _ in
                // Perform the purchase
                self.buyProduct(currentProduct)
            })

            alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Default) { _ in

                })

            // Show the alert
            self.view?.window?.rootViewController?.presentViewController(alert, animated: true, completion: nil)
        }
    }
}

//Initializes the App Purchases
func initInAppPurchases() {
    SKPaymentQueue.defaultQueue().addTransactionObserver(self)
    // Get the list of possible purchases
    if self.request == nil {
        self.request = SKProductsRequest(productIdentifiers: Set(["dice.green.add", "dice.blue.add", "dice.gray.add","dice.red.add"]))
        self.request.delegate = self
        self.request.start()
    }
}

// Request a purchase
func buyProduct(product: SKProduct) {
    let payment = SKPayment(product: product)
    SKPaymentQueue.defaultQueue().addPayment(payment)
}

// Restore purchases
func restorePurchasedProducts() {
    SKPaymentQueue.defaultQueue().restoreCompletedTransactions()
}

// StoreKit protocoll method. Called when the AppStore responds
func productsRequest(request: SKProductsRequest, didReceiveResponse response: SKProductsResponse) {
    self.products = response.products
    self.request = nil
}

// StoreKit protocoll method. Called when an error happens in the communication with the AppStore
func request(request: SKRequest, didFailWithError error: NSError) {
    print(error)
    self.request = nil
}

// StoreKit protocoll method. Called after the purchase
func paymentQueue(queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
    for transaction in transactions {
        switch (transaction.transactionState) {
        case .Purchased:
            if transaction.payment.productIdentifier ==  "dice.green.add" {
                handleDiceColorPurchase(greenPID)
                print("buying green")
            } else if transaction.payment.productIdentifier ==  "dice.blue.add" {
                handleDiceColorPurchase(bluePID)
                print("buying blue")
            } else if transaction.payment.productIdentifier ==  "dice.red.add" {
                handleDiceColorPurchase(redPID)
                print("buying red")
            } else if transaction.payment.productIdentifier ==  "dice.gray.add" {
                handleDiceColorPurchase(grayPID)
                print("buying gray")
            } else {
                print("Error: Invalid Product ID")
            }
            queue.finishTransaction(transaction)
        case .Restored:
            if transaction.payment.productIdentifier ==  "dice.green.add" {
                handleDiceColorPurchase(greenPID)
                print("restoring green")
            } else if transaction.payment.productIdentifier ==  "dice.blue.add" {
                handleDiceColorPurchase(bluePID)
                print("restoring blue")
            } else if transaction.payment.productIdentifier ==  "dice.red.add" {
                handleDiceColorPurchase(redPID)
                print("restoring red")
            } else if transaction.payment.productIdentifier ==  "dice.gray.add" {
                handleDiceColorPurchase(grayPID)
                print("restoring gray")
            } else {
                print("Error: Invalid Product ID")
            }
            queue.finishTransaction(transaction)
        case .Failed:
            print("Payment Error: \(transaction.error)")
            queue.finishTransaction(transaction)
        default:
            print("Transaction State: \(transaction.transactionState)")
        }
    }
}

// Called after the purchase to provide the colored dice feature
func handleDiceColorPurchase(pid: String){
    switch(pid) {
        case greenPID:
            greenDicePurchased = true
            greenDiceDemo.alpha = 0.25
            greenDiceDemo.removeAllChildren()
            createPurchasedLabel(greenDiceDemo)
        case redPID:
            redDicePurchased = true
            redDiceDemo.alpha = 0.25
            redDiceDemo.removeAllChildren()
            createPurchasedLabel(redDiceDemo)
        case grayPID:
            grayDicePurchased = true
            grayDiceDemo.alpha = 0.25
            grayDiceDemo.removeAllChildren()
            createPurchasedLabel(grayDiceDemo)
        case bluePID:
            blueDicePurchased = true
            blueDiceDemo.alpha = 0.25
            blueDiceDemo.removeAllChildren()
            createPurchasedLabel(blueDiceDemo)
        default:
            print("No action taken, incorrect PID")
    }

    checkAndActivateDiceColor(pid)
    // persist the purchase locally
    NSUserDefaults.standardUserDefaults().setBool(true, forKey: pid)
}

func checkAndActivateDiceColor(pid: String){
    if NSUserDefaults.standardUserDefaults().boolForKey(pid) {
        switch(pid) {
            case greenPID:
                greenDicePurchased = true
                greenDiceDemo.alpha = 0.25
                greenDiceDemo.removeAllChildren()
                createPurchasedLabel(greenDiceDemo)
            case redPID:
                redDicePurchased = true
                redDiceDemo.alpha = 0.25
                redDiceDemo.removeAllChildren()
                createPurchasedLabel(redDiceDemo)
            case grayPID:
                grayDicePurchased = true
                grayDiceDemo.alpha = 0.25
                grayDiceDemo.removeAllChildren()
                createPurchasedLabel(grayDiceDemo)
            case bluePID:
                blueDicePurchased = true
                blueDiceDemo.alpha = 0.25
                blueDiceDemo.removeAllChildren()
                createPurchasedLabel(blueDiceDemo)
            default:
                print("No action taken, incorrect PID")
        }
    }
}
</code>```

}

When it crashes, there isn't much info that I can decipher. I get an error

stating EXC_BAD_ACCESS (code=1, address=0xc)

on my AppDelegate class and something highlighted green stating Enqueued from

com.apple.root.default-qos.overcommit(Thread 4)

Any help is appreciated!

答:
Thanks!, Worked for me too!!!
The crash mentioned was happening for me too. The answer above is quite complete, however, with just the last comment it solved the Crash problem.

The code I used in Objective-C:

```<code>- (void) viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
    [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
}
</code>```

Title: Crash when restoring purchases in swift

Body:
I'm running into some confusing behavior with my in-app purchases restore feature. Currently, I have the restore feature linked to a button, it seems to crash when I activate it multiple times. For example, if I hit it, restore, navigate to another view, then back to hit the restore again it will crash.

Can anyone check my code and see if I'm missing something staring me in the face?

import SpriteKit
import StoreKit

class PurchaseView: SKScene, SKPaymentTransactionObserver, SKProductsRequestDelegate{

var instructLabel = SKLabelNode()
var priceLabel = SKLabelNode()

var saleBadgeIcon = SKSpriteNode()
var backIcon = SKSpriteNode()
var restoreIcon = SKSpriteNode()

var blueDiceDemo = SKSpriteNode()
var redDiceDemo = SKSpriteNode()
var greenDiceDemo = SKSpriteNode()
var grayDiceDemo = SKSpriteNode()

var bluePID: String = "dice.blue.add"
var redPID: String = "dice.red.add"
var greenPID: String = "dice.green.add"
var grayPID: String = "dice.gray.add"

private var request : SKProductsRequest!
private var products : [SKProduct] = []

private var blueDicePurchased : Bool = false
private var redDicePurchased : Bool = false
private var greenDicePurchased : Bool = false
private var grayDicePurchased : Bool = false

override func didMoveToView(view: SKView) {
    // In-App Purchase
    initInAppPurchases()

    /*
    checkAndActivateGreenColor()
    checkAndActivateRedColor()
    checkAndActivateGrayColor()
    checkAndActivateBlueColor()
    */

    createInstructionLabel()
    createBackIcon()
    createRestoreIcon()
    createBlueDicePurchase()
    createRedDicePurchase()
    createGreenDicePurchase()
    createGrayDicePurchase()

    checkAndActivateDiceColor(bluePID)
    checkAndActivateDiceColor(redPID)
    checkAndActivateDiceColor(greenPID)
    checkAndActivateDiceColor(grayPID)
}

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    for touch in touches {
        let location = touch.locationInNode(self)
        let node = nodeAtPoint(location)

        if (node == backIcon) {
            let gameScene = GameScene(size: self.size)
            let transition = SKTransition.doorsCloseVerticalWithDuration(0.5)
            gameScene.scaleMode = SKSceneScaleMode.ResizeFill
            gameScene.backgroundColor = SKColor.whiteColor()
            self.scene!.view?.presentScene(gameScene, transition: transition)
        } else if (node == restoreIcon) {
            print("restore my purchases")

            let alert = UIAlertController(title: "Restore Purchases", message: "", preferredStyle: UIAlertControllerStyle.Alert)

            alert.addAction(UIAlertAction(title: "Restore", style: UIAlertActionStyle.Default) { _ in
                self.restorePurchasedProducts()
                })

            alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Default) { _ in

                })

            // Show the alert
            self.view?.window?.rootViewController?.presentViewController(alert, animated: true, completion: nil)

            //restorePurchasedProducts()
        } else if (node == blueDiceDemo) {
            print("buy blue")
            if (!blueDicePurchased) {
                inAppPurchase(blueDicePurchased, pid: bluePID)
            }
        } else if (node == redDiceDemo) {
            print("buy red")
            if (!redDicePurchased) {
                inAppPurchase(redDicePurchased, pid: redPID)
            }
        } else if (node == greenDiceDemo) {
            print("buy green")
            if (!greenDicePurchased) {
                inAppPurchase(greenDicePurchased, pid: greenPID)
            }
        } else if (node == grayDiceDemo) {
            print("buy gray")
            if (!grayDicePurchased) {
                inAppPurchase(grayDicePurchased, pid: grayPID)
            }
        }
    }
}

func createBlueDicePurchase() {
    blueDiceDemo = SKSpriteNode(imageNamed: "dice1_blue")
    blueDiceDemo.setScale(0.6)
    blueDiceDemo.position = CGPoint(x: CGRectGetMidX(self.frame) + blueDiceDemo.size.width * 2, y: CGRectGetMidY(self.frame))
    addChild(blueDiceDemo)

    createSaleBadge(blueDiceDemo)
}

func createGrayDicePurchase() {
    grayDiceDemo = SKSpriteNode(imageNamed: "dice1_gray")
    grayDiceDemo.setScale(0.6)
    grayDiceDemo.position = CGPoint(x: CGRectGetMidX(self.frame), y: CGRectGetMidY(self.frame))
    addChild(grayDiceDemo)

    createSaleBadge(grayDiceDemo)
}

func createRedDicePurchase() {
    redDiceDemo = SKSpriteNode(imageNamed: "dice1_red")
    redDiceDemo.setScale(0.6)
    redDiceDemo.position = CGPoint(x: CGRectGetMidX(self.frame) - blueDiceDemo.size.width * 2, y: CGRectGetMidY(self.frame))
    addChild(redDiceDemo)

    createSaleBadge(redDiceDemo)
}

func createGreenDicePurchase() {
    greenDiceDemo = SKSpriteNode(imageNamed: "dice1_green")
    greenDiceDemo.setScale(0.6)
    greenDiceDemo.position = CGPoint(x: CGRectGetMidX(self.frame), y: CGRectGetMidY(self.frame) - blueDiceDemo.size.height * 1.5)
    addChild(greenDiceDemo)

    createSaleBadge(greenDiceDemo)
}

func createInstructionLabel() {
    instructLabel = SKLabelNode(fontNamed: "Helvetica")
    instructLabel.text = "Click item to purchase!"
    instructLabel.fontSize = 24
    instructLabel.fontColor = SKColor.blackColor()
    instructLabel.position = CGPoint(x: CGRectGetMidX(self.frame), y: CGRectGetMaxY(self.frame) - 50)
    addChild(instructLabel)
}

func createPurchasedLabel(node: SKSpriteNode) {
    let purchasedLabel = SKLabelNode(fontNamed: "Helvetica")
    purchasedLabel.text = "purchased"
    purchasedLabel.fontSize = 30
    purchasedLabel.zPosition = 2
    purchasedLabel.fontColor = SKColor.blackColor()
    purchasedLabel.position = CGPoint(x: 0, y: -7.5)
    node.addChild(purchasedLabel)
}

func createRestoreIcon() {
    restoreIcon = SKSpriteNode(imageNamed: "download")
    restoreIcon.setScale(0.4)
    restoreIcon.position = CGPoint(x: CGRectGetMinX(self.frame) + 30, y: CGRectGetMinY(self.frame) + 30)
    addChild(restoreIcon)
}

func createBackIcon() {
    backIcon = SKSpriteNode(imageNamed: "remove")
    backIcon.setScale(0.5)
    backIcon.position = CGPoint(x: CGRectGetMaxX(self.frame) - 30, y: CGRectGetMinY(self.frame) + 30)
    addChild(backIcon)
}

func createSaleBadge(node: SKSpriteNode) {
    saleBadgeIcon = SKSpriteNode(imageNamed: "badge")
    saleBadgeIcon.setScale(0.4)
    saleBadgeIcon.zPosition = 2
    saleBadgeIcon.position = CGPoint(x: node.size.width/2, y: node.size.height/2)
    node.addChild(saleBadgeIcon)
}

func inAppPurchase(dicePurchased: Bool, pid: String) {
    let alert = UIAlertController(title: "In-App Purchases", message: "", preferredStyle: UIAlertControllerStyle.Alert)

    // Add an alert action for each available product
    for (var i = 0; i < products.count; i++) {
        let currentProduct = products[i]
        if (currentProduct.productIdentifier == pid && !dicePurchased) {
            // Get the localized price
            let numberFormatter = NSNumberFormatter()
            numberFormatter.numberStyle = .CurrencyStyle
            numberFormatter.locale = currentProduct.priceLocale
            // Add the alert action
            alert.addAction(UIAlertAction(title: currentProduct.localizedTitle + " " + numberFormatter.stringFromNumber(currentProduct.price)!, style: UIAlertActionStyle.Default)  { _ in
                // Perform the purchase
                self.buyProduct(currentProduct)
            })

            alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Default) { _ in

                })

            // Show the alert
            self.view?.window?.rootViewController?.presentViewController(alert, animated: true, completion: nil)
        }
    }
}

//Initializes the App Purchases
func initInAppPurchases() {
    SKPaymentQueue.defaultQueue().addTransactionObserver(self)
    // Get the list of possible purchases
    if self.request == nil {
        self.request = SKProductsRequest(productIdentifiers: Set(["dice.green.add", "dice.blue.add", "dice.gray.add","dice.red.add"]))
        self.request.delegate = self
        self.request.start()
    }
}

// Request a purchase
func buyProduct(product: SKProduct) {
    let payment = SKPayment(product: product)
    SKPaymentQueue.defaultQueue().addPayment(payment)
}

// Restore purchases
func restorePurchasedProducts() {
    SKPaymentQueue.defaultQueue().restoreCompletedTransactions()
}

// StoreKit protocoll method. Called when the AppStore responds
func productsRequest(request: SKProductsRequest, didReceiveResponse response: SKProductsResponse) {
    self.products = response.products
    self.request = nil
}

// StoreKit protocoll method. Called when an error happens in the communication with the AppStore
func request(request: SKRequest, didFailWithError error: NSError) {
    print(error)
    self.request = nil
}

// StoreKit protocoll method. Called after the purchase
func paymentQueue(queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
    for transaction in transactions {
        switch (transaction.transactionState) {
        case .Purchased:
            if transaction.payment.productIdentifier ==  "dice.green.add" {
                handleDiceColorPurchase(greenPID)
                print("buying green")
            } else if transaction.payment.productIdentifier ==  "dice.blue.add" {
                handleDiceColorPurchase(bluePID)
                print("buying blue")
            } else if transaction.payment.productIdentifier ==  "dice.red.add" {
                handleDiceColorPurchase(redPID)
                print("buying red")
            } else if transaction.payment.productIdentifier ==  "dice.gray.add" {
                handleDiceColorPurchase(grayPID)
                print("buying gray")
            } else {
                print("Error: Invalid Product ID")
            }
            queue.finishTransaction(transaction)
        case .Restored:
            if transaction.payment.productIdentifier ==  "dice.green.add" {
                handleDiceColorPurchase(greenPID)
                print("restoring green")
            } else if transaction.payment.productIdentifier ==  "dice.blue.add" {
                handleDiceColorPurchase(bluePID)
                print("restoring blue")
            } else if transaction.payment.productIdentifier ==  "dice.red.add" {
                handleDiceColorPurchase(redPID)
                print("restoring red")
            } else if transaction.payment.productIdentifier ==  "dice.gray.add" {
                handleDiceColorPurchase(grayPID)
                print("restoring gray")
            } else {
                print("Error: Invalid Product ID")
            }
            queue.finishTransaction(transaction)
        case .Failed:
            print("Payment Error: \(transaction.error)")
            queue.finishTransaction(transaction)
        default:
            print("Transaction State: \(transaction.transactionState)")
        }
    }
}

// Called after the purchase to provide the colored dice feature
func handleDiceColorPurchase(pid: String){
    switch(pid) {
        case greenPID:
            greenDicePurchased = true
            greenDiceDemo.alpha = 0.25
            greenDiceDemo.removeAllChildren()
            createPurchasedLabel(greenDiceDemo)
        case redPID:
            redDicePurchased = true
            redDiceDemo.alpha = 0.25
            redDiceDemo.removeAllChildren()
            createPurchasedLabel(redDiceDemo)
        case grayPID:
            grayDicePurchased = true
            grayDiceDemo.alpha = 0.25
            grayDiceDemo.removeAllChildren()
            createPurchasedLabel(grayDiceDemo)
        case bluePID:
            blueDicePurchased = true
            blueDiceDemo.alpha = 0.25
            blueDiceDemo.removeAllChildren()
            createPurchasedLabel(blueDiceDemo)
        default:
            print("No action taken, incorrect PID")
    }

    checkAndActivateDiceColor(pid)
    // persist the purchase locally
    NSUserDefaults.standardUserDefaults().setBool(true, forKey: pid)
}

func checkAndActivateDiceColor(pid: String){
    if NSUserDefaults.standardUserDefaults().boolForKey(pid) {
        switch(pid) {
            case greenPID:
                greenDicePurchased = true
                greenDiceDemo.alpha = 0.25
                greenDiceDemo.removeAllChildren()
                createPurchasedLabel(greenDiceDemo)
            case redPID:
                redDicePurchased = true
                redDiceDemo.alpha = 0.25
                redDiceDemo.removeAllChildren()
                createPurchasedLabel(redDiceDemo)
            case grayPID:
                grayDicePurchased = true
                grayDiceDemo.alpha = 0.25
                grayDiceDemo.removeAllChildren()
                createPurchasedLabel(grayDiceDemo)
            case bluePID:
                blueDicePurchased = true
                blueDiceDemo.alpha = 0.25
                blueDiceDemo.removeAllChildren()
                createPurchasedLabel(blueDiceDemo)
            default:
                print("No action taken, incorrect PID")
        }
    }
}

}

When it crashes, there isn't much info that I can decipher. I get an error

stating EXC_BAD_ACCESS (code=1, address=0xc)

on my AppDelegate class and something highlighted green stating Enqueued from

com.apple.root.default-qos.overcommit(Thread 4)

Any help is appreciated!

Body:
Thanks!, Worked for me too!!!
The crash mentioned was happening for me too. The answer above is quite complete, however, with just the last comment it solved the Crash problem.

The code I used in Objective-C:

- (void) viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
    [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
}


问:
PHP Mail Function
Is it possible to send a mail in PHP without any external packages or tools? If so, is there

any requirement to configure the php.ini file?

Its as follows:

```<code>$to = $row->EMail_ID;
$subject = "Reset your password";
$body = "Hi ".$row->Username.", \n\t\t\tA request to reset your  password was received from you. \n\n\n";
$headers = "From: admin@admin.com\r\n"."X-Mailer: php/";
mail($to, $subject, $body, $headers);
</code>```

The error i get:

```<code>Warning: mail() [function.mail]: Failed to connect to mailserver at "localhost" port 25,
verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set() in F:\wamp\www\pwd.php on line 20
</code>```

答: Sounds like you don't have sendmail (or one of its alternatives, like postfix or courier) installed.</p>

Title: PHP Mail Function

Body:
Is it possible to send a mail in PHP without any external packages or tools? If so, is there

any requirement to configure the php.ini file?

Its as follows:

$to = $row->EMail_ID;
$subject = "Reset your password";
$body = "Hi ".$row->Username.", \n\t\t\tA request to reset your  password was received from you. \n\n\n";
$headers = "From: admin@admin.com\r\n"."X-Mailer: php/";
mail($to, $subject, $body, $headers);

The error i get:

Warning: mail() [function.mail]: Failed to connect to mailserver at "localhost" port 25,
verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set() in F:\wamp\www\pwd.php on line 20


问:
cannot use a return statement in a function that uses observables
so I just learned that I cannot use a return statement in a function that uses a an async operation, or perhaps I can but I am using it incorrectly. My thought is that I should just subscribe to the obseravable in the place I want to use the data I am grabbing, instead of just calling the function in that place and using the return statement.

Here is my code what would be the better way of doing things so I don't have to use the return statement, or better yet, how can I still use the return statement. Please note I want to use observables, not promises, I no longer see the value in promises.

Thank you.

```<code>getService(url) {
    var value: any[] = [];
    this.http.get(url)
      .map(
        (response: Response) => {
          const data = response.json()
            .subscribe(
              (mappedData: any[]) => value = mappedData,
              (error) => console.log(error)
            )
              }
      );
    return value;
  }
</code>```

答:
we can return the value of the json object this way.

```<code>getService(url) {
 var value: any[] = [];
 var subscription = this.http.get(url)
                    .map(response => response.json() )
                    .subscribe(
                         mappedData => value = mappedData.data,
                         (error) => console.log(error)
                    );
 return value;  }
</code>```

transform the response from the http.get() to json object using .map()

then .subscribe() to the output of the .map() which is the transformed json object

Finally set the value from subscribed data.. return the value

Please go through the angular documentation for better understanding.

Body:
so I just learned that I cannot use a return statement in a function that uses a an async operation, or perhaps I can but I am using it incorrectly. My thought is that I should just subscribe to the obseravable in the place I want to use the data I am grabbing, instead of just calling the function in that place and using the return statement.

Here is my code what would be the better way of doing things so I don't have to use the return statement, or better yet, how can I still use the return statement. Please note I want to use observables, not promises, I no longer see the value in promises.

Thank you.

getService(url) {
    var value: any[] = [];
    this.http.get(url)
      .map(
        (response: Response) => {
          const data = response.json()
            .subscribe(
              (mappedData: any[]) => value = mappedData,
              (error) => console.log(error)
            )
              }
      );
    return value;
  }

Body:
we can return the value of the json object this way.

getService(url) {
 var value: any[] = [];
 var subscription = this.http.get(url)
                    .map(response => response.json() )
                    .subscribe(
                         mappedData => value = mappedData.data,
                         (error) => console.log(error)
                    );
 return value;  }

transform the response from the http.get() to json object using .map()

then .subscribe() to the output of the .map() which is the transformed json object

Finally set the value from subscribed data.. return the value

Please go through the angular documentation for better understanding.


问:
ImportError: No module named django.core.wsgi for uwsgi
I'm using uwsgi for my Django(version =1.4) project, but there's an error if I run

```<code>uwsgi --ini django.ini
</code>```

```
from django.core.wsgi import get_wsgi_application
    ImportError: No module named django.core.wsgi
```

but I could import django.core.wsgi as follows:

```<code>>>> import django.core.wsgi
</code>```

the django.ini file:

```
[uwsgi]
chdir=/path/to/my/app
module=app.wsgi:application
master=True
vacuum=True
max-requests=5000
socket=127.0.0.1:9000
```

wsgi.py

```<code>import os

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings")

# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
</code>```

答: If you installed gunicorn on both sudo apt-get install gunicorn and (venv) pip install gunicorn, use sudo apt-get remove gunicorn and restart your virtual environment. This way, it worked for me.

Body:
I'm using uwsgi for my Django(version =1.4) project, but there's an error if I run

uwsgi --ini django.ini

from django.core.wsgi import get_wsgi_application
    ImportError: No module named django.core.wsgi

but I could import django.core.wsgi as follows:

>>> import django.core.wsgi

the django.ini file:

[uwsgi]
chdir=/path/to/my/app
module=app.wsgi:application
master=True
vacuum=True
max-requests=5000
socket=127.0.0.1:9000

wsgi.py

import os

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings")

# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()


问:
How do I fine-tune regex syntax to parse a tricky dirty text?
I have an OCR'ed .txt file that is a volume with data about book reviews (It's a Book Review Index). I'm attempting to separate authors, titles, and review data. I've been able to cleanly separate authors, but still can't separate titles from review data cleanly. Here is a sample of the .txt file:

MA, Chi-Hua - Huan Chiu Hsin Ying BL - v70 - Jl 1 ’74 - pi 183 c MA, Ching-Hsien - Pei Niang Niang Ti Ku Shih
  BL - v77 - Ja 1 ’81 - p630 MA, Hsin-Teh - Chinese Women In The Great Leap Forward
  Choice - v20 - N ’82 - p396 MA, Huan • The Overall Survey Of The Ocean’s Shores 1433
  Choice - v8 - 0 ’71 - pl074 MA, Huan • Ying-Yai Sheng-Lan AHR - v76 - D ’71 - pl578 GJ - vl37 - Je ’71 - p213 JAS - v31 - N ’71 - pl81 TLS - Je 16 ’72 - p681 MA, Laurence J C - Commercial Development And Urban Change In Sung China 960-1279
  JAS - v31 - Ag ’72 - p928 Pac A - v45 - Summer ’72 - p285 MA, Laurence J C - The Environment JAS - v42 - N ’82 - pl39 MA, Laurence J C - Urban Development In Modern China
  Choice - vl9 - Ja ’82 - p696 JAS - v42 - N 82 - pl39 MA, Nancy Chih - Cook Chinese AB - v45 - My 25 ’70 - pl786 PW - vl97 - Mr 23 ’70 - p38 MA, Nancy Chih • Don’t Lick The Chopsticks CSM - v66 - Ja 10 ’74 - pF2 LJ - v99 - Mr 15 ’74 - p757 MA, Nancy Chih - Mrs. Ma’s Japanese Cooking
  VQR - v58 - Spring ’82 - p68 MA, Tsu Sheng - Microscale Manipulations In Chemistry
  Choice-vl3-N ’76 -pi 164 MA, Tsu Sheng - Organic Functional Group Analysis By Gas Chromatography Choice - vl3 - F ’77 - pl624 r MA, Wei-Yi - A Bibliography Of Chinese-Language Materials On The People's Communes ARBA - vl5 - '84 - p320
  Pac A - v56 - Winter ’83 - p796 MA, Wook - Seoul Ro Kanun Kil BL - v78 - 0 15 '81 - p294 y MA, Y W - Traditional Chinese Stories ANQ - vl8 - 0 ’79 - p30 BF - v4 - Ap 40 '79 - p575 Choice -vl5-Ja ’79 -pl528 HR-v32-Spring'79-pl23 JAS - v38 - Ag '79 - p773 Kliatt - vl3 • Winter '79 - p26 WIT - v53 - Summer '79 - p555 MA, Yun • Shih Ching T'ao Hsing BL - v68 - Ap 1 '72 - p651 MA BRICALL, Josep - Politica Economica De La Generalitat 1936-1939. Vol. 1 WP - v25 - O '72 - pl55 MA COY, Ramelle • Short-Time Compensation
  Choice - v21 - Jl '84 - pl648 Econ Bks - vll - S ’84 - p62 c MA De - The Cowherd And The Weaving Maid
  Cur R - v20 - S '81 -p325 c MA De - Crickets
  Cur R - v20 - S '81 - p325 c MA De - School-Master Dongguo Cur R - v20 - S '81 - p325 c MA De - Thrice Borrowing The Plantain Fan CurR- v20-S ’81 -p325 c MA De - The Wonderful Gourds Cur R - v20 - S '81 - p325 MAACK, Berthold - Preussen JMH - v55 - Mr '83 - p71 r MAACK, Mary N - Libraries In Senegal ARBA - vl3 - '82 - pi53 CRL - v45 - Mr '84-pl52 JAL - v7 - S '81 - p244 JLH - vl9 - Spring ’84 - p315 LJ - vl07 - My 1 ’82 - p865 LQ - v52 - Ap '82-pl75 MAACK, Reinhard • Kontinentaldrift Und Geologie Des Sudatlantischen Ozeans GJ - vl36 - Mr '70 - pl38 MAAG, Russell C - Observe And Understand The Sun
  S&T - v54 - S ’77 - p221 MAAG, Victor - Hiob
  Rel St Rev - vlO - Ap '84 - pi 75 MAAILMA Katettu Poyta

And here is a cleaner version, to see better what I'm trying to separate:

MA, Chi-Hua - Huan Chiu Hsin Ying BL - v70 - Jl 1 ’74 - pi 183 c
  MA, Ching-Hsien - Pei Niang Niang Ti Ku Shih BL - v77 - Ja 1 ’81 - p630
  MA, Hsin-Teh - Chinese Women In The Great Leap Forward Choice - v20 - N ’82 - p396
  MA, Huan • The Overall Survey Of The Ocean’s Shores 1433 Choice - v8 - 0 ’71 - pl074
  MA, Huan • Ying-Yai Sheng-Lan AHR - v76 - D ’71 - pl578 GJ - vl37 - Je ’71 - p213 JAS - v31 - N ’71 - pl81 TLS - Je 16 ’72 - p681
  MA, Laurence J C - Commercial Development And Urban Change In Sung China 960-1279 JAS - v31 - Ag ’72 - p928 Pac A - v45 - Summer ’72 - p285
  MA, Laurence J C - The Environment JAS - v42 - N ’82 - pl39
  MA, Laurence J C - Urban Development In Modern China Choice - vl9 - Ja ’82 - p696 JAS - v42 - N 82 - pl39
  MA, Nancy Chih - Cook Chinese AB - v45 - My 25 ’70 - pl786 PW - vl97 - Mr 23 ’70 - p38
  MA, Nancy Chih • Don’t Lick The Chopsticks CSM - v66 - Ja 10 ’74 - pF2 LJ - v99 - Mr 15 ’74 - p757
  MA, Nancy Chih - Mrs. Ma’s Japanese Cooking VQR - v58 - Spring ’82 - p68
  MA, Tsu Sheng - Microscale Manipulations In Chemistry Choice-vl3-N ’76 -pi 164
  MA, Tsu Sheng - Organic Functional Group Analysis By Gas Chromatography Choice - vl3 - F ’77 - pl624 r
  MA, Wei-Yi - A Bibliography Of Chinese-Language Materials On The People's Communes ARBA - vl5 - '84 - p320 Pac A - v56 - Winter ’83 - p796
  MA, Wook - Seoul Ro Kanun Kil BL - v78 - 0 15 '81 - p294 y
  MA, Y W - Traditional Chinese Stories ANQ - vl8 - 0 ’79 - p30 BF - v4 - Ap 40 '79 - p575 Choice -vl5-Ja ’79 -pl528 HR-v32-Spring'79-pl23 JAS - v38 - Ag '79 - p773 Kliatt - vl3 • Winter '79 - p26 WIT - v53 -  Summer '79 - p555
  MA, Yun • Shih Ching T'ao Hsing BL - v68 - Ap 1 '72 - p651
  MA BRICALL, Josep - Politica Economica De La Generalitat 1936-1939. Vol. 1 WP - v25 - O '72 - pl55
  MA COY, Ramelle • Short-Time Compensation Choice - v21 - Jl '84 - pl648 Econ Bks - vll - S ’84 - p62 c
  MA De - The Cowherd And The Weaving Maid Cur R - v20 - S '81 -p325 c
  MA De - Crickets Cur R - v20 - S '81 - p325 c
  MA De - School-Master Dongguo Cur R - v20 - S '81 - p325 c
  MA De - Thrice Borrowing The Plantain Fan CurR- v20-S ’81 -p325 c
  MA De - The Wonderful Gourds Cur R - v20 - S '81 - p325
  MAACK, Berthold - Preussen JMH - v55 - Mr '83 - p71 r

And here's my code:

```<code># read in review volume .txt file
import pandas as pd
import numpy as np
import re

file = '/Users/sinykin/Dropbox/US_LIT_PRODUCTION_DATA/REVIEWS_DATA/BOOK_REVIEWS_INDEX_TEXTS/1965_1984_Vol_5_M-P.txt'

with open(file) as f:
    content = f.readlines()
    content = [x.strip() for x in content]
    content = " ".join(content)

# Get all authors
pattern = r"[A-Z\-]{2,}[\,]+\s[A-Za-z\s\,\(\)\.]+\s[\-\*\•\.\■ ]{1}"
authors = re.findall(pattern, content)

# Now replace all found authors with XXX_XXX
if re.search(pattern, content):
    r = re.compile(pattern)
    content2 = r.sub(r'XXX_XXX', content)

# Now get all the content for each author
content3 = content2.split('XXX_XXX')
bib = content3[1:]

# Now separate reviews from titles
pattern2 = r"\s+(?:([A-Z][a-z][a-z]((?!\s+-|\s+Choice\s*-).)*?\w)(?:\s+-
\s*|\s+(?=Choice\s*-)|\s*$))"
bib2 = "".join(bib)
titles = re.findall(pattern2, bib2)
print (titles[:1000])
</code>```

It's the regex code in pattern2 that I'm struggling with. For example, it currently gives me this, for what should be titles:

[('The Overall Survey Of The Ocean\xe2\x80\x99s Shores 1433', '3'),

  ('Ying-Yai Sheng-Lan AHR', 'H'),

  ('Commercial Development And Urban Change In Sung China 960-1279 JAS', 'A'),

  ('Pac A', ' '),

  ('Summer \xe2\x80\x9972', '7'),

  ('The Environment JAS', 'A'),

  ('Urban Development In Modern China', 'n'),

  ('Cook Chinese AB', 'A'),

  ('Don\xe2\x80\x99t Lick The Chopsticks CSM', 'S'),

  ('Mrs. Ma\xe2\x80\x99s Japanese Cooking VQR', 'Q'),
  ('Spring \xe2\x80\x9982', '8'),

  ('Microscale Manipulations In Chemistry', 'r')

As you can see, I'm getting extra data beyond the end of the titles, esp capital letters that mark abbreviation for reviews.

Can you help me refine my regex to capture just the titles?

答:
Question: ... refine my regex to capture just the titles?

Split content2 on these Patterns to get a List of Books:

```<code>books = []
for c in re.split('(XXX_XXX|MA, | MA, | MA )', content2):
    if c and not c in ['MA, ', ' MA, ', ' MA ', 'XXX_XXX']:
        books.append(c.strip())
</code>```

Loop books to extract the title:

```<code>reObj = re.compile(r'(.+?)(( [A-Z\&]{1,4})?| Choice| Cur ?R) ?- ?[’v][l]?(\d{1,2}|O )')
for book in books:
    match = reObj.match(book)
    if match:
        title = match.groups()[0]
        print('{}'.format(title))
    else:
        print('FAIL:{}'.format(book))
</code>```

Output:

```<code>Chi-Hua - Huan Chiu Hsin Ying
Ching-Hsien - Pei Niang Niang Ti Ku Shih
Hsin-Teh - Chinese Women In The Great Leap Forward
The Overall Survey Of The Ocean’s Shores 1433
Ying-Yai Sheng-Lan
Commercial Development And Urban Change In Sung China 960-1279
The Environment
Urban Development In Modern China
Cook Chinese
Don’t Lick The Chopsticks
... (omitted for brevity)
</code>```

Tested with Python:3.4.2 - re:2.2.1

Body:
I have an OCR'ed .txt file that is a volume with data about book reviews (It's a Book Review Index). I'm attempting to separate authors, titles, and review data. I've been able to cleanly separate authors, but still can't separate titles from review data cleanly. Here is a sample of the .txt file:

MA, Chi-Hua - Huan Chiu Hsin Ying BL - v70 - Jl 1 ’74 - pi 183 c MA, Ching-Hsien - Pei Niang Niang Ti Ku Shih
  BL - v77 - Ja 1 ’81 - p630 MA, Hsin-Teh - Chinese Women In The Great Leap Forward
  Choice - v20 - N ’82 - p396 MA, Huan • The Overall Survey Of The Ocean’s Shores 1433
  Choice - v8 - 0 ’71 - pl074 MA, Huan • Ying-Yai Sheng-Lan AHR - v76 - D ’71 - pl578 GJ - vl37 - Je ’71 - p213 JAS - v31 - N ’71 - pl81 TLS - Je 16 ’72 - p681 MA, Laurence J C - Commercial Development And Urban Change In Sung China 960-1279
  JAS - v31 - Ag ’72 - p928 Pac A - v45 - Summer ’72 - p285 MA, Laurence J C - The Environment JAS - v42 - N ’82 - pl39 MA, Laurence J C - Urban Development In Modern China
  Choice - vl9 - Ja ’82 - p696 JAS - v42 - N 82 - pl39 MA, Nancy Chih - Cook Chinese AB - v45 - My 25 ’70 - pl786 PW - vl97 - Mr 23 ’70 - p38 MA, Nancy Chih • Don’t Lick The Chopsticks CSM - v66 - Ja 10 ’74 - pF2 LJ - v99 - Mr 15 ’74 - p757 MA, Nancy Chih - Mrs. Ma’s Japanese Cooking
  VQR - v58 - Spring ’82 - p68 MA, Tsu Sheng - Microscale Manipulations In Chemistry
  Choice-vl3-N ’76 -pi 164 MA, Tsu Sheng - Organic Functional Group Analysis By Gas Chromatography Choice - vl3 - F ’77 - pl624 r MA, Wei-Yi - A Bibliography Of Chinese-Language Materials On The People's Communes ARBA - vl5 - '84 - p320
  Pac A - v56 - Winter ’83 - p796 MA, Wook - Seoul Ro Kanun Kil BL - v78 - 0 15 '81 - p294 y MA, Y W - Traditional Chinese Stories ANQ - vl8 - 0 ’79 - p30 BF - v4 - Ap 40 '79 - p575 Choice -vl5-Ja ’79 -pl528 HR-v32-Spring'79-pl23 JAS - v38 - Ag '79 - p773 Kliatt - vl3 • Winter '79 - p26 WIT - v53 - Summer '79 - p555 MA, Yun • Shih Ching T'ao Hsing BL - v68 - Ap 1 '72 - p651 MA BRICALL, Josep - Politica Economica De La Generalitat 1936-1939. Vol. 1 WP - v25 - O '72 - pl55 MA COY, Ramelle • Short-Time Compensation
  Choice - v21 - Jl '84 - pl648 Econ Bks - vll - S ’84 - p62 c MA De - The Cowherd And The Weaving Maid
  Cur R - v20 - S '81 -p325 c MA De - Crickets
  Cur R - v20 - S '81 - p325 c MA De - School-Master Dongguo Cur R - v20 - S '81 - p325 c MA De - Thrice Borrowing The Plantain Fan CurR- v20-S ’81 -p325 c MA De - The Wonderful Gourds Cur R - v20 - S '81 - p325 MAACK, Berthold - Preussen JMH - v55 - Mr '83 - p71 r MAACK, Mary N - Libraries In Senegal ARBA - vl3 - '82 - pi53 CRL - v45 - Mr '84-pl52 JAL - v7 - S '81 - p244 JLH - vl9 - Spring ’84 - p315 LJ - vl07 - My 1 ’82 - p865 LQ - v52 - Ap '82-pl75 MAACK, Reinhard • Kontinentaldrift Und Geologie Des Sudatlantischen Ozeans GJ - vl36 - Mr '70 - pl38 MAAG, Russell C - Observe And Understand The Sun
  S&T - v54 - S ’77 - p221 MAAG, Victor - Hiob
  Rel St Rev - vlO - Ap '84 - pi 75 MAAILMA Katettu Poyta

And here is a cleaner version, to see better what I'm trying to separate:

MA, Chi-Hua - Huan Chiu Hsin Ying BL - v70 - Jl 1 ’74 - pi 183 c
  MA, Ching-Hsien - Pei Niang Niang Ti Ku Shih BL - v77 - Ja 1 ’81 - p630
  MA, Hsin-Teh - Chinese Women In The Great Leap Forward Choice - v20 - N ’82 - p396
  MA, Huan • The Overall Survey Of The Ocean’s Shores 1433 Choice - v8 - 0 ’71 - pl074
  MA, Huan • Ying-Yai Sheng-Lan AHR - v76 - D ’71 - pl578 GJ - vl37 - Je ’71 - p213 JAS - v31 - N ’71 - pl81 TLS - Je 16 ’72 - p681
  MA, Laurence J C - Commercial Development And Urban Change In Sung China 960-1279 JAS - v31 - Ag ’72 - p928 Pac A - v45 - Summer ’72 - p285
  MA, Laurence J C - The Environment JAS - v42 - N ’82 - pl39
  MA, Laurence J C - Urban Development In Modern China Choice - vl9 - Ja ’82 - p696 JAS - v42 - N 82 - pl39
  MA, Nancy Chih - Cook Chinese AB - v45 - My 25 ’70 - pl786 PW - vl97 - Mr 23 ’70 - p38
  MA, Nancy Chih • Don’t Lick The Chopsticks CSM - v66 - Ja 10 ’74 - pF2 LJ - v99 - Mr 15 ’74 - p757
  MA, Nancy Chih - Mrs. Ma’s Japanese Cooking VQR - v58 - Spring ’82 - p68
  MA, Tsu Sheng - Microscale Manipulations In Chemistry Choice-vl3-N ’76 -pi 164
  MA, Tsu Sheng - Organic Functional Group Analysis By Gas Chromatography Choice - vl3 - F ’77 - pl624 r
  MA, Wei-Yi - A Bibliography Of Chinese-Language Materials On The People's Communes ARBA - vl5 - '84 - p320 Pac A - v56 - Winter ’83 - p796
  MA, Wook - Seoul Ro Kanun Kil BL - v78 - 0 15 '81 - p294 y
  MA, Y W - Traditional Chinese Stories ANQ - vl8 - 0 ’79 - p30 BF - v4 - Ap 40 '79 - p575 Choice -vl5-Ja ’79 -pl528 HR-v32-Spring'79-pl23 JAS - v38 - Ag '79 - p773 Kliatt - vl3 • Winter '79 - p26 WIT - v53 -  Summer '79 - p555
  MA, Yun • Shih Ching T'ao Hsing BL - v68 - Ap 1 '72 - p651
  MA BRICALL, Josep - Politica Economica De La Generalitat 1936-1939. Vol. 1 WP - v25 - O '72 - pl55
  MA COY, Ramelle • Short-Time Compensation Choice - v21 - Jl '84 - pl648 Econ Bks - vll - S ’84 - p62 c
  MA De - The Cowherd And The Weaving Maid Cur R - v20 - S '81 -p325 c
  MA De - Crickets Cur R - v20 - S '81 - p325 c
  MA De - School-Master Dongguo Cur R - v20 - S '81 - p325 c
  MA De - Thrice Borrowing The Plantain Fan CurR- v20-S ’81 -p325 c
  MA De - The Wonderful Gourds Cur R - v20 - S '81 - p325
  MAACK, Berthold - Preussen JMH - v55 - Mr '83 - p71 r

And here's my code:

# read in review volume .txt file
import pandas as pd
import numpy as np
import re

file = '/Users/sinykin/Dropbox/US_LIT_PRODUCTION_DATA/REVIEWS_DATA/BOOK_REVIEWS_INDEX_TEXTS/1965_1984_Vol_5_M-P.txt'

with open(file) as f:
    content = f.readlines()
    content = [x.strip() for x in content]
    content = " ".join(content)

# Get all authors
pattern = r"[A-Z\-]{2,}[\,]+\s[A-Za-z\s\,\(\)\.]+\s[\-\*\•\.\■ ]{1}"
authors = re.findall(pattern, content)

# Now replace all found authors with XXX_XXX
if re.search(pattern, content):
    r = re.compile(pattern)
    content2 = r.sub(r'XXX_XXX', content)

# Now get all the content for each author
content3 = content2.split('XXX_XXX')
bib = content3[1:]

# Now separate reviews from titles
pattern2 = r"\s+(?:([A-Z][a-z][a-z]((?!\s+-|\s+Choice\s*-).)*?\w)(?:\s+-
\s*|\s+(?=Choice\s*-)|\s*$))"
bib2 = "".join(bib)
titles = re.findall(pattern2, bib2)
print (titles[:1000])

It's the regex code in pattern2 that I'm struggling with. For example, it currently gives me this, for what should be titles:

[('The Overall Survey Of The Ocean\xe2\x80\x99s Shores 1433', '3'),

  ('Ying-Yai Sheng-Lan AHR', 'H'),

  ('Commercial Development And Urban Change In Sung China 960-1279 JAS', 'A'),

  ('Pac A', ' '),

  ('Summer \xe2\x80\x9972', '7'),

  ('The Environment JAS', 'A'),

  ('Urban Development In Modern China', 'n'),

  ('Cook Chinese AB', 'A'),

  ('Don\xe2\x80\x99t Lick The Chopsticks CSM', 'S'),

  ('Mrs. Ma\xe2\x80\x99s Japanese Cooking VQR', 'Q'),
  ('Spring \xe2\x80\x9982', '8'),

  ('Microscale Manipulations In Chemistry', 'r')

As you can see, I'm getting extra data beyond the end of the titles, esp capital letters that mark abbreviation for reviews.

Can you help me refine my regex to capture just the titles?

Body:
Question: ... refine my regex to capture just the titles?

Split content2 on these Patterns to get a List of Books:

books = []
for c in re.split('(XXX_XXX|MA, | MA, | MA )', content2):
    if c and not c in ['MA, ', ' MA, ', ' MA ', 'XXX_XXX']:
        books.append(c.strip())

Loop books to extract the title:

reObj = re.compile(r'(.+?)(( [A-Z\&]{1,4})?| Choice| Cur ?R) ?- ?[’v][l]?(\d{1,2}|O )')
for book in books:
    match = reObj.match(book)
    if match:
        title = match.groups()[0]
        print('{}'.format(title))
    else:
        print('FAIL:{}'.format(book))

Output:

Chi-Hua - Huan Chiu Hsin Ying
Ching-Hsien - Pei Niang Niang Ti Ku Shih
Hsin-Teh - Chinese Women In The Great Leap Forward
The Overall Survey Of The Ocean’s Shores 1433
Ying-Yai Sheng-Lan
Commercial Development And Urban Change In Sung China 960-1279
The Environment
Urban Development In Modern China
Cook Chinese
Don’t Lick The Chopsticks
... (omitted for brevity)

Tested with Python:3.4.2 - re:2.2.1


问:
how can I open a video from dailymotion with mpmovieplayercontroller
I want to open a video from dailymotion with mpmovieplayercontroller. I have tried Dailymotion SDK but it seems that it just embeds a video to a uiwebview. I wonder if there is a dailymotion parser to get the video link just like hcyoutubeparser or ytvvimeoextractor.</p>

答:
the last answer is a great starting point, but doesn't work anymore, needed to update due to Javascript/JSON Syntax changes:

```<code>-(NSDictionary*)getInfoForDailyMotionVideo:(NSString*)videoId{
    NSString *urlString = [NSString stringWithFormat:@"http://www.dailymotion.com/embed/video/%@", videoId];
    NSURL *URL = [NSURL URLWithString:urlString];
    NSData * data = [[NSData alloc] initWithContentsOfURL:URL];
    NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSString *str;

    NSRange startRange = [html rangeOfString:@"var config = {"];
    str = [html substringFromIndex:startRange.location];
    NSRange endRange = [str rangeOfString:@"{"];
    str = [str substringFromIndex:endRange.location];
    endRange = [str rangeOfString:@"}};"];
    NSString *jsonString = [str substringToIndex:endRange.location+1];
    jsonString = [jsonString stringByAppendingString:@"}"];
    NSError *jsonError;
    NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:0 error:&jsonError];
    return result;
}
</code>```

This now works and returns all relevant values for AVPlayer etc...

Have fun!

Body:
the last answer is a great starting point, but doesn't work anymore, needed to update due to Javascript/JSON Syntax changes:

-(NSDictionary*)getInfoForDailyMotionVideo:(NSString*)videoId{
    NSString *urlString = [NSString stringWithFormat:@"http://www.dailymotion.com/embed/video/%@", videoId];
    NSURL *URL = [NSURL URLWithString:urlString];
    NSData * data = [[NSData alloc] initWithContentsOfURL:URL];
    NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSString *str;

    NSRange startRange = [html rangeOfString:@"var config = {"];
    str = [html substringFromIndex:startRange.location];
    NSRange endRange = [str rangeOfString:@"{"];
    str = [str substringFromIndex:endRange.location];
    endRange = [str rangeOfString:@"}};"];
    NSString *jsonString = [str substringToIndex:endRange.location+1];
    jsonString = [jsonString stringByAppendingString:@"}"];
    NSError *jsonError;
    NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:0 error:&jsonError];
    return result;
}

This now works and returns all relevant values for AVPlayer etc...

Have fun!