问:
Enable users of a WebRtc app to download webrtc logs via javascript
I've seen the following:

```<code>chrome://webrtc-internals
</code>```

However I'm looking for a way to let users click a button from within the web app to either download or - preferably - POST WebRtc logs to an endpoint baked into the app.  The idea is that I can enable non-technical users to share technical logs with me through the click of a UI button.

How can this be achieved?

Note: This should not be dependent on Chrome; Chromium will also be used as the app will be wrapped up in Electron.

答:
This is what I ended up using (replace knockout with underscore or whatever):

```<code>            connectionReport.signalingState = connection.signalingState;
            connectionReport.stats = [];
            connection.getStats(function (stats) {
                const reportCollection = stats.result();
                ko.utils.arrayForEach(reportCollection, function (innerReport) {
                    const statReport = {};
                    statReport.id = innerReport.id;
                    statReport.type = innerReport.type;
                    const keys = innerReport.names();
                    ko.utils.arrayForEach(keys, function (reportKey) {
                        statReport[reportKey] = innerReport.stat(reportKey);
                    })
                    connectionReport.stats.push(statReport);
                });
                connectionStats.push(connectionReport);
            });
</code>```

UPDATE:

It appears that this getStats mechanism is soon-to-be-deprecated.

Body:
I've seen the following:

chrome://webrtc-internals

However I'm looking for a way to let users click a button from within the web app to either download or - preferably - POST WebRtc logs to an endpoint baked into the app.  The idea is that I can enable non-technical users to share technical logs with me through the click of a UI button.

How can this be achieved?

Note: This should not be dependent on Chrome; Chromium will also be used as the app will be wrapped up in Electron.

Body:
This is what I ended up using (replace knockout with underscore or whatever):

            connectionReport.signalingState = connection.signalingState;
            connectionReport.stats = [];
            connection.getStats(function (stats) {
                const reportCollection = stats.result();
                ko.utils.arrayForEach(reportCollection, function (innerReport) {
                    const statReport = {};
                    statReport.id = innerReport.id;
                    statReport.type = innerReport.type;
                    const keys = innerReport.names();
                    ko.utils.arrayForEach(keys, function (reportKey) {
                        statReport[reportKey] = innerReport.stat(reportKey);
                    })
                    connectionReport.stats.push(statReport);
                });
                connectionStats.push(connectionReport);
            });

UPDATE:

It appears that this getStats mechanism is soon-to-be-deprecated.


来源: stackexchange

问:
Upgrading from MVC Preview 3 to Beta/RC
We have a web app that is using MVC Preview 3. I'm new to the project and relatively new to ASP.NET MVC itself - soon we will be looking to upgrade to either the Beta or RC version.

Are there any major difference between preview 3 and Beta version that would require extensive refactoring?

Any "gotchas"?

From my understanding the RC will be very close to the current Beta... does anyone have a view on this?

Any advice apprecited really.... thanks.

答:
There were quite a few changes between preview 3 to the beta. IIRC the most pain came between preview 3 - preview 4.

One of the biggest gotchas is some of the functionality in the main dlls got placed into a separate dll because they were not going to be fully supported for the first release.

I suggest you brew a large pot of coffee and go and read everything Phil Haack and Scott Gu wrote around that time.

http://haacked.com/archive/2008/07/16/aspnetmvc-codeplex-preview4.aspx

http://weblogs.asp.net/scottgu/archive/2008/07/14/asp-net-mvc-preview-4-release-part-1.aspx

ContentLicense: CC BY-SA 2.5

Title: Upgrading from MVC Preview 3 to Beta/RC

OwnerDisplayName: IainMH


问:
standalone C++ preprocessor
I'm looking for a standalone C++ preprocessor. I'll use with another language, so there's no point in running through a full fledged compiler, but it's a very limited script language, so the #define and #if and other directives will help me a lot.

For example, I'd be writing a file like this:

```<code>#define DEBUG
do some stuff
#ifdef DEBUG
    show a message box or whatever
#endif
do some more stuff
</code>```

答: How about the GNU C preprocessor?</p>

Title: standalone C++ preprocessor

Body:
I'm looking for a standalone C++ preprocessor. I'll use with another language, so there's no point in running through a full fledged compiler, but it's a very limited script language, so the #define and #if and other directives will help me a lot.

For example, I'd be writing a file like this:

#define DEBUG
do some stuff
#ifdef DEBUG
    show a message box or whatever
#endif
do some more stuff

Body: How about the GNU C preprocessor?


问:
App Installation failed after upgrade to XCode 8
My apps will no long install on my devices in my development environment after installing Xcode 8 with the error : App installation failed “A valid provisioning profile for this executable was not found.”

I’ve seen quite a few questions here on the subject and I’ve slowly gone through all the answers but to no avail.  I thought it might have been ios10 but I keep one of my devices at ios9, that one don’t work either.

What I’ve done :

I’ve switched between Xcode automatically handling signing and doing
it manually, setting all the profiles to “Development”.

I’ve deleted all the provisioning profiles and redownloaded them.

I’ve tried going to developer portal, manually regenerating the
provisioning profiles and using them.

When I check the info next to the XCode managed profile, under
“Devices”, my current device is listed.

Turned on and off the Push notification services. (I don’t use push
notifications).

Also disabled push notification services on my App ID in the
development portal.

Removed the provisioning profiles from the devices themselves in the
Devices Window.

Deleted all old certificates in my keychain.

Updated all my cocoa pods.

Restarted countless times and did many of the different steps in
different orders.

I recently had to turn on keychain sharing as my app no longer wanted
to retrieve an access token used for oAuth from the keychain, but
turning that on or off had no effect either.

Other than the recently changed keychain access, I have no other
entitlements.

With the keychain access, I also created an app group in the
development portal and made sure it was set for my keychain group.
No difference

I’ve been stuck on this a day now and it’s really pushing back my next release as I have to test on real devices, the error message is frustratingly vague when everything seems in place, am I missing a log file somewhere that might give me a hint?

答:
Xcode 8.3.3:

Had the same problem.

tried deleting Derived Data, cleaning project, changed dev team back and forth, manually setting the prov profiles, nothing helped.
Fixed it in the end by restarting Xcode :/

ContentLicense: CC BY-SA 3.0


问:
TypeError: Cannot read property 'valid' of undefined
I have the following textarea:

```<code><textarea class="form-control" [(ngModel)]="content" name="content" required>
        </textarea>
</code>```

and the following submit button:

```<code> <button type="submit" class="btn btn-default" [disabled]="content.valid">New comment</button>
</code>```

As I saw in the angular 2 form guide (https://angular.io/docs/ts/latest/guide/forms.html) I can use the x.valid in order to check if it's not empty.

Why do I get TypeError: Cannot read property 'valid' of undefined error?

答:
```<code><div class="form-group">
    <label for="inputEmail" class="col-lg-2 control-label">Email</label>
    <div class="col-lg-10">
        <input type="text" class="form-control" id="name" placeholder="Name" minlength="4" maxlength="24"  [(ngModel)]="name" name="email" #myName="ngModel" required>
            <div *ngIf="myName.errors && (myName.dirty || myName.touched)" class="alert alert-danger">
                <div [hidden]="!myName.errors.required">
                    Name is required
                </div>
                <div [hidden]="!myName.errors.minlength">
                    Name must be at least 4 characters long.
                </div>
                <div [hidden]="!myName.errors.maxlength">
                    Name cannot be more than 24 characters long.
                </div>
            </div>
    </div>
</div>
</code>```

Body:
I have the following textarea:

<textarea class="form-control" [(ngModel)]="content" name="content" required>
        </textarea>

and the following submit button:

 <button type="submit" class="btn btn-default" [disabled]="content.valid">New comment</button>

As I saw in the angular 2 form guide (https://angular.io/docs/ts/latest/guide/forms.html) I can use the x.valid in order to check if it's not empty.

Why do I get TypeError: Cannot read property 'valid' of undefined error?


问:
Dates in R calculating number of days
I'm having data as

```<code>customer_id Last_city    First city       recent_date
1020         Jaipur       Gujarat         20130216
1021         Delhi        Lucknow         20130129
1022         Mumbai       Punjab          20130221
</code>```

and I want to find the number of days from recent date and today (for every record).

答:
difftime function calculates time difference in days, hours, minutes, etc.
First, need to parse the date string into a date representation (e.g. Date or POSIXct) then compare that to the current date/time.

```<code># create dummy data.frame for testing
df <- data.frame("customer_id"=1020, "Last_city"="Jaipur",
    "First_city"="Gujarat", "recent_date"="20130216",
    stringsAsFactors = FALSE)

now <- Sys.Date()
# parse date into date type (Note: %Y=4-digit year, %y=2-digit year)
df$date = as.Date(df$recent_date, format = "%Y%m%d")
# next calculate the difference between recent date and current time
df$diff = as.double(difftime(now, df$date, units = c("days")))

> df
  customer_id Last_city First_city recent_date       date  diff
1        1020    Jaipur    Gujarat    20130216 2013-02-16  1604
</code>```

If wanted the difference in weeks then

```<code>>  as.double(difftime(now, df$date, units = c("weeks")))
[1] 229.1429
</code>```

Title: Dates in R calculating number of days

Body:
I'm having data as

customer_id Last_city    First city       recent_date
1020         Jaipur       Gujarat         20130216
1021         Delhi        Lucknow         20130129
1022         Mumbai       Punjab          20130221

and I want to find the number of days from recent date and today (for every record).

Body:
difftime function calculates time difference in days, hours, minutes, etc.
First, need to parse the date string into a date representation (e.g. Date or POSIXct) then compare that to the current date/time.

# create dummy data.frame for testing
df <- data.frame("customer_id"=1020, "Last_city"="Jaipur",
    "First_city"="Gujarat", "recent_date"="20130216",
    stringsAsFactors = FALSE)

now <- Sys.Date()
# parse date into date type (Note: %Y=4-digit year, %y=2-digit year)
df$date = as.Date(df$recent_date, format = "%Y%m%d")
# next calculate the difference between recent date and current time
df$diff = as.double(difftime(now, df$date, units = c("days")))

> df
  customer_id Last_city First_city recent_date       date  diff
1        1020    Jaipur    Gujarat    20130216 2013-02-16  1604

If wanted the difference in weeks then

>  as.double(difftime(now, df$date, units = c("weeks")))
[1] 229.1429


问:
how can I upgrade my project of laravel 5.0 directly to 5.4?
There is an old project made in laravel 5.0.35 framework by some other developer, now my job is to add some new features to that project but I am familiar with laravel 5.4 so what I think would be good aproach is that I upgrade this project in 5.4 then do my work. But I don't know how to do it.
P.S. I have seen laravel upgrade docs in which they upgrade version by version. Is it possible to upgrade this project directly to laravel 5.4 skipping that version by version upgradation? </p>

答:
in your laravel directory type

```<code>composer update
</code>```

and it will be update your laravel project

there is a composer.json file in root and you can find version of your laravel

```<code>"laravel/framework": "5.4.*",
</code>```

it shows dependencies that you want to upgrade

dont forget to get backup before upgrade

Body:
in your laravel directory type

composer update

and it will be update your laravel project

there is a composer.json file in root and you can find version of your laravel

"laravel/framework": "5.4.*",

it shows dependencies that you want to upgrade

dont forget to get backup before upgrade


问:
Letting superclass's methods be implemented by an inherited class
Say I have this structure for my code:

```<code>public abstract class A{
    public abstract Foo methodX();
    public abstract Bar methodY();
}

public class B extends A {
    public Foo methodX(){
        // stuff
    }
    public Bar methodY(){
        // more stuff
    }
}

public class C extends A {
    public Foo methodX() {
        // stuff
    }
    public Bar methodY(){
        // What to do?
    }
}

public class D extends C {
    public Bar methodY() {
        // do stuff
    }
}

public class F extends C {
    public Bar methodY() {
        // do different stuff
    }
}
</code>```

The reason for me to do this is because I have multiple classes extending A, all have common method methodX() and methodY() and I have multiple classes extending B all have some common properties to B but need to have different ways of doing methodY() and have different equals/hashcode.

So, how do I have it so that B implements the only methodX() but lets C and D implement methodY() without returning null or doing nothing in methodY() for B?

答:
You need to declare class B as abstract

```<code>public abstract class B extends A{
    public Foo medhodX(){
        // stuff
    }
}
</code>```

By declaring class abstract you allow him not to implement all abstract methods (from superclass or implemented interface). So you can implement only one abstract method and force child class to impleent all remaining abstract methods.

Body:
Say I have this structure for my code:

public abstract class A{
    public abstract Foo methodX();
    public abstract Bar methodY();
}

public class B extends A {
    public Foo methodX(){
        // stuff
    }
    public Bar methodY(){
        // more stuff
    }
}

public class C extends A {
    public Foo methodX() {
        // stuff
    }
    public Bar methodY(){
        // What to do?
    }
}

public class D extends C {
    public Bar methodY() {
        // do stuff
    }
}

public class F extends C {
    public Bar methodY() {
        // do different stuff
    }
}

The reason for me to do this is because I have multiple classes extending A, all have common method methodX() and methodY() and I have multiple classes extending B all have some common properties to B but need to have different ways of doing methodY() and have different equals/hashcode.

So, how do I have it so that B implements the only methodX() but lets C and D implement methodY() without returning null or doing nothing in methodY() for B?

Body:
You need to declare class B as abstract

public abstract class B extends A{
    public Foo medhodX(){
        // stuff
    }
}

By declaring class abstract you allow him not to implement all abstract methods (from superclass or implemented interface). So you can implement only one abstract method and force child class to impleent all remaining abstract methods.


问:
Unsigned int to byte
I'm trying to create a custom inputstream. My problem is, the read() method returns an integer from 0-255, but I need to convert it to a byte, decrypt it, and convert it back to an integer. How?

I need something like:

```<code>InputStream in = ...;
OutputStream out = ...;

int unsigned = in.read();
byte signed = unsignedIntToSignedByte(unsigned); // from -128 to 127
... // Editing it here
outputstream.write(signedByteToUnsignedInt(signed)); // from 0 - 255
</code>```

答:
Noting that creating your own encryption is unsafe, and assuming you're doing it "just for fun" and don't think in any way that what you're doing is secure, you really don't need anything special...

```<code>int i = in.read();
byte b = (byte) i;
byte e = encrypt(b);
out.write(e);
</code>```

would be the basic approach, assuming byte encrypt(byte b) method which does the "encryption". Checking for end-of-stream, exception handling, performance considerations (you don't want to perform things 1 byte at a time) etc. have been left out from this example.

Title: Unsigned int to byte

Body:
I'm trying to create a custom inputstream. My problem is, the read() method returns an integer from 0-255, but I need to convert it to a byte, decrypt it, and convert it back to an integer. How?

I need something like:

InputStream in = ...;
OutputStream out = ...;

int unsigned = in.read();
byte signed = unsignedIntToSignedByte(unsigned); // from -128 to 127
... // Editing it here
outputstream.write(signedByteToUnsignedInt(signed)); // from 0 - 255

Body:
Noting that creating your own encryption is unsafe, and assuming you're doing it "just for fun" and don't think in any way that what you're doing is secure, you really don't need anything special...

int i = in.read();
byte b = (byte) i;
byte e = encrypt(b);
out.write(e);

would be the basic approach, assuming byte encrypt(byte b) method which does the "encryption". Checking for end-of-stream, exception handling, performance considerations (you don't want to perform things 1 byte at a time) etc. have been left out from this example.


问:
liferay returns localhost for CAS instead of real hostname
i'm trying to implement CAS in Liferay portal. after setting configurations, when i click on signin button, it redirects me to this url :
https://sso.myuni.ac.com:8443/cas/login?service=https%3A%2F%2Flocalhost%3A8080.
my real hostname is : www.liferay.myuni.com and the port is 8443.
how can i change settings in order to liferay returns real hostname instead of localhost?
i want to liferay returens https://sso.myuni.ac.com:8443/cas/login?service=https%3A%2F%2Fliferay.myuni.com%3A8443

答:
Are you running with an Apache in front of your tomcat (assuming you're using tomcat)? If you do (and if you use mod_proxy to forward the requests), make sure you also include

```<code>ProxyPreserveHost On
</code>```

This will make sure that Tomcat has an idea what the originally requested host name is - otherwise it'll take whatever the Proxyserver sends (when installed on the same server, this is typically localhost).

Read about ProxyPreserveHost

Alternatively, check if you can declare the actual host name in Liferay's configuration, e.g. by searching for localhost in portal.properties (you'll override this in portal-ext.properties)

Edit: As you say you only use tomcat, no Apache: Please state what remote host you're actually seeing instead of the expected (and how you obtain it)

With regards to portal.properties: This is a file that is contained within one of Liferay's jars, and is not meant to be modified (that's why it's not easy to find). However, the HTML version is here, it contains a lot of configuration options. You're overriding by creating a file named portal-ext.properties in ${liferay.home}, containing only those settings that you'd like to change with regards to portal.proerties.

Body:
Are you running with an Apache in front of your tomcat (assuming you're using tomcat)? If you do (and if you use mod_proxy to forward the requests), make sure you also include

ProxyPreserveHost On

This will make sure that Tomcat has an idea what the originally requested host name is - otherwise it'll take whatever the Proxyserver sends (when installed on the same server, this is typically localhost).

Read about ProxyPreserveHost

Alternatively, check if you can declare the actual host name in Liferay's configuration, e.g. by searching for localhost in portal.properties (you'll override this in portal-ext.properties)

Edit: As you say you only use tomcat, no Apache: Please state what remote host you're actually seeing instead of the expected (and how you obtain it)

With regards to portal.properties: This is a file that is contained within one of Liferay's jars, and is not meant to be modified (that's why it's not easy to find). However, the HTML version is here, it contains a lot of configuration options. You're overriding by creating a file named portal-ext.properties in ${liferay.home}, containing only those settings that you'd like to change with regards to portal.proerties.


答:
Ya you can update it but folder structure is changed in laravel 5.4. so you can face problem in it.
Go in composer.json and change the laravel version then
 update composer  with command .</p>

Title: how can I upgrade my project of laravel 5.0 directly to 5.4?

Body:
There is an old project made in laravel 5.0.35 framework by some other developer, now my job is to add some new features to that project but I am familiar with laravel 5.4 so what I think would be good aproach is that I upgrade this project in 5.4 then do my work. But I don't know how to do it.
P.S. I have seen laravel upgrade docs in which they upgrade version by version. Is it possible to upgrade this project directly to laravel 5.4 skipping that version by version upgradation?


问:
Searching unsorted array in perl?
I have an array with... lets say 100 elements. I want to check to see if any of the elements matches a particular string. For example:

@array = ('red','white','blue');

I also want to know if the array contains the string 'white' as one of the elements.
I know how to do this with a foreach loop and comparing each element, but... is there an easier (faster) way than looping through the whole array?

-Thanks

答:
Perl 5.10 and higher, smart match:

```<code>say 'found' if 'white' ~~ @array;
</code>```

For pre-5.10, List::MoreUtils:

```<code>use List::MoreUtils qw{any};
print "found" if any { 'white' eq $_ } @array;
</code>```

These short circuit - if a match is found there is no need to traverse the whole array.

Title: Searching unsorted array in perl?

Body:
Perl 5.10 and higher, smart match:

say 'found' if 'white' ~~ @array;

For pre-5.10, List::MoreUtils:

use List::MoreUtils qw{any};
print "found" if any { 'white' eq $_ } @array;

These short circuit - if a match is found there is no need to traverse the whole array.


问:
Changing or preventing the use of E in Python?
I'm currently trying to write a script that will create a unique ID for a user relying on a number of variables, like birthdate, name, hometown, etc. This creates a very long number that is completely unique to that user, however, to try to make the number even more unique, I want to change a random number in the string. This is what I have so far:

```<code>rand = randint(1,15)
tempid = id / 10**rand
if randint(1,2) == 1:
    tempid = tempid + randint(2,10000)
else:
    tempid = tempid - randint(5,7500)
print(id)
id = tempid * (10**rand)
print(str(id))
</code>```

The code is fairly simple. It makes the number much smaller by dividing it by a large multiple of 10, adds or subtracts a random number, and multiplies it back to it's original length, with some changed numbers in the middle. The only problem is, because it must be an integer to be able to do any math with it, Python shortens it to 1.[something]e+[something]. This isn't helpful at all, becasue now it's not an ID. Is there anyway I can change it back to its original form, where it's just a long string, or perhaps change the code so it never becomes e? Thank you!

答:
Your problem is that id when you print it refers to a large float value, which is then printed in exponential notation. If it were an integer value, no e would be in the printout. The float value comes from your line

```<code>tempid = id / 10**rand
</code>```

which, in Python 3.x, stores a float value in tempid. You later execute

```<code>id = tempid * (10**rand)
</code>```

which multiplies a float by an integer, resulting in a float, and that float is what is printed in the next line

You can avoid this in several ways. You can keep all the calculations in integers by replacing your division line with

```<code>tempid = id // 10**rand
</code>```

That extra slash mark means integer division, so tempid here and id later are integers. However, this may change the resulting values. So a better way is allow tempid to be a float but ensure that id is always an integer, using

```<code>id = int(tempid * (10**rand))
</code>```

This should keep all your values the same and give you the print you want.

That answers your actual question. However, I agree with @user2722968 that if your purpose is to create a unique ID you should use module meant for that purpose, such as uuid. The history of computing shows that randomizing a part of a string to get a random value does poorly, and getting actual random or unique values is difficult to get right. You should do it the way others have shown to work well.

Body:
I'm currently trying to write a script that will create a unique ID for a user relying on a number of variables, like birthdate, name, hometown, etc. This creates a very long number that is completely unique to that user, however, to try to make the number even more unique, I want to change a random number in the string. This is what I have so far:

rand = randint(1,15)
tempid = id / 10**rand
if randint(1,2) == 1:
    tempid = tempid + randint(2,10000)
else:
    tempid = tempid - randint(5,7500)
print(id)
id = tempid * (10**rand)
print(str(id))

The code is fairly simple. It makes the number much smaller by dividing it by a large multiple of 10, adds or subtracts a random number, and multiplies it back to it's original length, with some changed numbers in the middle. The only problem is, because it must be an integer to be able to do any math with it, Python shortens it to 1.[something]e+[something]. This isn't helpful at all, becasue now it's not an ID. Is there anyway I can change it back to its original form, where it's just a long string, or perhaps change the code so it never becomes e? Thank you!

Body:
Your problem is that id when you print it refers to a large float value, which is then printed in exponential notation. If it were an integer value, no e would be in the printout. The float value comes from your line

tempid = id / 10**rand

which, in Python 3.x, stores a float value in tempid. You later execute

id = tempid * (10**rand)

which multiplies a float by an integer, resulting in a float, and that float is what is printed in the next line

You can avoid this in several ways. You can keep all the calculations in integers by replacing your division line with

tempid = id // 10**rand

That extra slash mark means integer division, so tempid here and id later are integers. However, this may change the resulting values. So a better way is allow tempid to be a float but ensure that id is always an integer, using

id = int(tempid * (10**rand))

This should keep all your values the same and give you the print you want.

That answers your actual question. However, I agree with @user2722968 that if your purpose is to create a unique ID you should use module meant for that purpose, such as uuid. The history of computing shows that randomizing a part of a string to get a random value does poorly, and getting actual random or unique values is difficult to get right. You should do it the way others have shown to work well.


问:
How to imitate std::string's find_first_not_of using strspn
I'm trying to create a custom string class similar to std::string.

And I'm having a trouble implementing 'find_first_not_of'.

Here's my test code

```<code>#include <iostream>

class String {

private:

    char *m_data;
    int m_length;

    char *alloc(int size);
    int length() const {return m_length;}
    int size() const {return m_length;}
    const char *c_str() const {return m_data;}

public:

    String(const char *str=0);

    int find_first_not_of(const char *str);
    static const int npos;
};

const int String::npos = -1;

char * String::alloc(int size)
{
    char * str = new char[size+1];
    return str;
}

String::String(const char *str)
{
    if (!str) str = "";
    m_length = static_cast<int>(strlen(str));
    m_data = alloc(m_length);
    strcpy(m_data, str);
}

int String::find_first_not_of(const char *str)
{
    size_t len = strspn(c_str(), str);

    if (len == 0)
        return -1;
    else
        return len;
}

int main(int argc, const char * argv[]) {

    String A = "123";
    std::string B = "123";

    if (A.find_first_not_of("0123456789") == -1)
        std::cout << "A is digit" << std::endl;
    else
        std::cout << "A is not digit" << std::endl;

    if (B.find_first_not_of("0123456789") == -1)
        std::cout << "B is digit" << std::endl;
    else
        std::cout << "B is not digit" << std::endl;
    return 0;
}
</code>```

And this is the result I see if I run the code.

```<code>A is not digit
B is digit
Program ended with exit code: 0
</code>```

Can someone please point me what I'm missing?

Thanks!

答:
You are confusing your String::find_first_not_of with std::string::find_first_not_of. They are different functions that have different functionality.

I really don't understand what String::find_first_not_of needs to do, but here is what each of them returns (one the length of the string and the other one the position):

std::string::find_first_if_not (from here):

The position of the first character that does not match.
  If no such characters are found, the function returns string::npos.

strspn (from here):

The length of the initial portion of str1 containing only characters that appear in str2.
  Therefore, if all of the characters in str1 are in str2, the function returns the length of the entire str1 string, and if the first character in str1 is not in str2, the function returns zero.

So even the inner working of the functions are different.

You should be able to follow based on this info.

Body:
I'm trying to create a custom string class similar to std::string.

And I'm having a trouble implementing 'find_first_not_of'.

Here's my test code

#include <iostream>

class String {

private:

    char *m_data;
    int m_length;

    char *alloc(int size);
    int length() const {return m_length;}
    int size() const {return m_length;}
    const char *c_str() const {return m_data;}

public:

    String(const char *str=0);

    int find_first_not_of(const char *str);
    static const int npos;
};

const int String::npos = -1;

char * String::alloc(int size)
{
    char * str = new char[size+1];
    return str;
}

String::String(const char *str)
{
    if (!str) str = "";
    m_length = static_cast<int>(strlen(str));
    m_data = alloc(m_length);
    strcpy(m_data, str);
}

int String::find_first_not_of(const char *str)
{
    size_t len = strspn(c_str(), str);

    if (len == 0)
        return -1;
    else
        return len;
}

int main(int argc, const char * argv[]) {

    String A = "123";
    std::string B = "123";

    if (A.find_first_not_of("0123456789") == -1)
        std::cout << "A is digit" << std::endl;
    else
        std::cout << "A is not digit" << std::endl;

    if (B.find_first_not_of("0123456789") == -1)
        std::cout << "B is digit" << std::endl;
    else
        std::cout << "B is not digit" << std::endl;
    return 0;
}

And this is the result I see if I run the code.

A is not digit
B is digit
Program ended with exit code: 0

Can someone please point me what I'm missing?

Thanks!


问:
Parallax image fills screen rather than div
I am creating a website as part of a University project and am tying to get a parallax effect on some images. I've been following the tutorial over at W3Schools...

https://www.w3schools.com/howto/howto_css_parallax.asp

My problem is that the images are filling the width of the screen rather than the div, causing them to be hugely zoomed in with the top and bottom cut off. Is there another way of doing this?

答:
If you want to remove the zoom effect and show the parts of the image that are cut off, you can change the background-size property to:</p>

```<code>background-size: contain;
</code>```

Body:
If you want to remove the zoom effect and show the parts of the image that are cut off, you can change the background-size property to:

background-size: contain;


问:
how to send a collection/array to mvc action via ajax
atm I'm trying like this, but no luck, I get null in my Do action</p>

```<code>var arr = [31,17,16];

$.get('<%=Url.Action("Do", "Foo") %>',
       {ids:arr},
       function(d){...});

public ActionResult Do(IEnumerable<int> ids)
{
...
}
</code>```

答:
Try like this:

```<code>$.ajax({
    url: '<%= Url.Action("Do", "Foo") %>',
    data: { ids: [ 31, 17, 16] },
    traditional: true,
    success: function(result) {

    }
});
</code>```

Notice the traditional: true parameter.

Or if you insist on the $.get() function:

```<code>$.get(
    '<%= Url.Action("Do", "Foo") %>',
    $.param({ ids: [31, 17, 16] }, true),
    function (result) {

    }
);
</code>```

Body:
atm I'm trying like this, but no luck, I get null in my Do action

var arr = [31,17,16];

$.get('<%=Url.Action("Do", "Foo") %>',
       {ids:arr},
       function(d){...});

public ActionResult Do(IEnumerable<int> ids)
{
...
}

Body:
Try like this:

$.ajax({
    url: '<%= Url.Action("Do", "Foo") %>',
    data: { ids: [ 31, 17, 16] },
    traditional: true,
    success: function(result) {

    }
});

Notice the traditional: true parameter.

Or if you insist on the $.get() function:

$.get(
    '<%= Url.Action("Do", "Foo") %>',
    $.param({ ids: [31, 17, 16] }, true),
    function (result) {

    }
);


问:
cwrsync rsync: did not see server greeting
Hello I try to rsync with ssh from windows to linux but I have this message:
rsync: did not see server greeting

I tried rsync ssh from linux to linux, it works.
So here is my command on windows:

```<code>C:\Temp\cwRsync_5.5.0_x86_Free\bin>Rsync -av -e "./ssh -i C:\Temp\id_rsa" /cygdrive/c/Temp ouistitis@192.168.1.12::.
Enter passphrase for key 'C:\Temp\id_rsa':
rsync: did not see server greeting
rsync error: error starting client-server protocol (code 5) at main.c(1648) [sender=3.1.2]
</code>```

here is the server auth.log:

```<code>Mar  3 01:00:13 ORDI sshd[16605]: Accepted publickey for ouistX from 192.168.1.15 port 50590 ssh2: RSA a7:XX:b3:XX:8d:XX:4c:5a:87:XX:2a:55:a9:37:54:45
Mar  3 01:00:14 ORDI sshd[16624]: Received disconnect from 192.168.1.15: 11: disconnected by user
</code>```

it seems there is a problem with the client, version problem?

this is the free version of cwrsync.

thx

答:
If you want to rsync over SSH, but you’re getting “did not see server greeting” and “error starting client-server protocol”, make sure the destination is specified with a single colon before filesystem path:

```<code>rsync -avz -e "ssh -i <somekey>" somedir <user>@<host>:somedir
</code>```

Destination with double colon before filesystem path (like <user>@<host>::somedir) makes rsync use its daemon instead of SSH even if you specify an SSH executable with -e flag.

It is stated in rsync manual—you can see the separate section “Access via rsync daemon” using double colon before target filesystem path when the port is unspecified:

```<code>SYNOPSIS
       Local:  rsync [OPTION...] SRC... [DEST]

       Access via remote shell:
         Pull: rsync [OPTION...] [USER@]HOST:SRC... [DEST]
         Push: rsync [OPTION...] SRC... [USER@]HOST:DEST

       Access via rsync daemon:
         Pull: rsync [OPTION...] [USER@]HOST::SRC... [DEST]
               rsync [OPTION...] rsync://[USER@]HOST[:PORT]/SRC... [DEST]
         Push: rsync [OPTION...] SRC... [USER@]HOST::DEST
               rsync [OPTION...] SRC... rsync://[USER@]HOST[:PORT]/DEST
</code>```

I stumbled across this same issue because rsync’s manual doesn’t make it very obvious.

Body:
Hello I try to rsync with ssh from windows to linux but I have this message:
rsync: did not see server greeting

I tried rsync ssh from linux to linux, it works.
So here is my command on windows:

C:\Temp\cwRsync_5.5.0_x86_Free\bin>Rsync -av -e "./ssh -i C:\Temp\id_rsa" /cygdrive/c/Temp ouistitis@192.168.1.12::.
Enter passphrase for key 'C:\Temp\id_rsa':
rsync: did not see server greeting
rsync error: error starting client-server protocol (code 5) at main.c(1648) [sender=3.1.2]

here is the server auth.log:

Mar  3 01:00:13 ORDI sshd[16605]: Accepted publickey for ouistX from 192.168.1.15 port 50590 ssh2: RSA a7:XX:b3:XX:8d:XX:4c:5a:87:XX:2a:55:a9:37:54:45
Mar  3 01:00:14 ORDI sshd[16624]: Received disconnect from 192.168.1.15: 11: disconnected by user

it seems there is a problem with the client, version problem?

this is the free version of cwrsync.

thx

Body:
If you want to rsync over SSH, but you’re getting “did not see server greeting” and “error starting client-server protocol”, make sure the destination is specified with a single colon before filesystem path:

rsync -avz -e "ssh -i <somekey>" somedir <user>@<host>:somedir

Destination with double colon before filesystem path (like <user>@<host>::somedir) makes rsync use its daemon instead of SSH even if you specify an SSH executable with -e flag.

It is stated in rsync manual—you can see the separate section “Access via rsync daemon” using double colon before target filesystem path when the port is unspecified:

SYNOPSIS
       Local:  rsync [OPTION...] SRC... [DEST]

       Access via remote shell:
         Pull: rsync [OPTION...] [USER@]HOST:SRC... [DEST]
         Push: rsync [OPTION...] SRC... [USER@]HOST:DEST

       Access via rsync daemon:
         Pull: rsync [OPTION...] [USER@]HOST::SRC... [DEST]
               rsync [OPTION...] rsync://[USER@]HOST[:PORT]/SRC... [DEST]
         Push: rsync [OPTION...] SRC... [USER@]HOST::DEST
               rsync [OPTION...] SRC... rsync://[USER@]HOST[:PORT]/DEST

I stumbled across this same issue because rsync’s manual doesn’t make it very obvious.

ContentLicense: CC BY-SA 4.0


问:
Rails routing to external site from model column through controller
I'm having an issue in my controller. I'm making url objects with original_url short_url and sanitized_url. I can create and save the links just fine. The issue i'm having is when following the short link back to mysite.com/short_url  it needs to go through the controller show and grab the sanitized url and redirect to that external site.
Can someone help me figure out what's wrong with this code?

I'm getting undefined method 'sanitized_url'

urls_controller.rb - show

```<code>short = params[:short_url]
@url = Url.where("short_url = ? ", short)

redirect_to @url.sanitized_url
</code>```

My routes.

```<code>  root to: 'urls#index'
  get "/:short_url", to: "urls#show"
  get "shortened/:short_url", to: "urls#shortened", as: :shortened
  resources :urls
</code>```

Thank you

答:
undefined method 'sanitized_url'

where returns AR collection. You need to apply sanitized_url on an instance

Below should work

```<code>short = params[:short_url]
@url = Url.where("short_url = ? ", short).first

redirect_to @url.sanitized_url
</code>```

Body:
I'm having an issue in my controller. I'm making url objects with original_url short_url and sanitized_url. I can create and save the links just fine. The issue i'm having is when following the short link back to mysite.com/short_url  it needs to go through the controller show and grab the sanitized url and redirect to that external site.
Can someone help me figure out what's wrong with this code?

I'm getting undefined method 'sanitized_url'

urls_controller.rb - show

short = params[:short_url]
@url = Url.where("short_url = ? ", short)

redirect_to @url.sanitized_url

My routes.

  root to: 'urls#index'
  get "/:short_url", to: "urls#show"
  get "shortened/:short_url", to: "urls#shortened", as: :shortened
  resources :urls

Thank you

Body:
undefined method 'sanitized_url'

where returns AR collection. You need to apply sanitized_url on an instance

Below should work

short = params[:short_url]
@url = Url.where("short_url = ? ", short).first

redirect_to @url.sanitized_url


问:
Reduce execution time of prime number generator
I have to print numbers between two limits n and m, t times.

I created t variable, and two pointers n, m that points to reserved blocks of memory for t integer values.

I use pointers instead of array to do faster operations.

Outer for loop iterates for every test cases and increasing m and n pointers.

Inner for loop prints primes from m[i] to n[i].

Code

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

int is_prime(int);

int main(void) {

    int t;
    int *n = malloc(sizeof(int) * t);
    int *m = malloc(sizeof(int) * t);

    scanf("%d", &t);
    for (int i = 0; i < t; i++, m++, n++) {
        scanf("%d %d", &m[i], &n[i]);
        for (int j = m[i]; j <= n[i]; j++) {
            if (is_prime(j)) {
                printf("%d\n", j);
            }
        }
        if (i < t - 1) printf("\n");
    }

    return 0;
}

int is_prime(int num)
{

    if (num <= 1) return 0;
    if (num % 2 == 0 && num > 2) return 0;

    for(int i = 3; i < num / 2; i+= 2){
         if (num % i == 0)
             return 0;
    }

    return 1;
}
</code>```

Problem: http://www.spoj.com/problems/PRIME1/

Code is correctly compiling on http://ideone.com but I'm giving "time limit exceeded" error when I'm trying submit this code on SPOJ. How can I reduce execution time of this prime number generator?

答:
I know that you are looking for algorithm improvements, but the following technical optimizations might help:

If you are using Visual Studio, you can use alloca instead of malloc, so that n and m go in the stack instead of the heap.

You can also try to rewrite your algorithm using arrays instead of pointers to put n and m in the stack.

If you want to keep using pointers, use the __restrict keyword after the asterisks, which alerts the compiler that you don't make references of the two pointers.

Body:
I have to print numbers between two limits n and m, t times.

I created t variable, and two pointers n, m that points to reserved blocks of memory for t integer values.

I use pointers instead of array to do faster operations.

Outer for loop iterates for every test cases and increasing m and n pointers.

Inner for loop prints primes from m[i] to n[i].

Code

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

int is_prime(int);

int main(void) {

    int t;
    int *n = malloc(sizeof(int) * t);
    int *m = malloc(sizeof(int) * t);

    scanf("%d", &t);
    for (int i = 0; i < t; i++, m++, n++) {
        scanf("%d %d", &m[i], &n[i]);
        for (int j = m[i]; j <= n[i]; j++) {
            if (is_prime(j)) {
                printf("%d\n", j);
            }
        }
        if (i < t - 1) printf("\n");
    }

    return 0;
}

int is_prime(int num)
{

    if (num <= 1) return 0;
    if (num % 2 == 0 && num > 2) return 0;

    for(int i = 3; i < num / 2; i+= 2){
         if (num % i == 0)
             return 0;
    }

    return 1;
}

Problem: http://www.spoj.com/problems/PRIME1/

Code is correctly compiling on http://ideone.com but I'm giving "time limit exceeded" error when I'm trying submit this code on SPOJ. How can I reduce execution time of this prime number generator?


问:
select column names containing string programmatically
Given a data frame like:

```<code>df <- data.frame(z_a = 1:2,
                 z_b = 1:2,
                 y_a = 3:4,
                 y_b = 3:4)
</code>```

I can select columns names that contain a character with:

```<code>library(dplyr)
df %>% select(contains("a"), contains("b"))

  z_a y_a z_b y_b
1   1   3   1   3
2   2   4   2   4
</code>```

NOTE that the column order has changed. Columns containing a come first before columns containing b

I'd like to select column names that contain characters in a vector and that reorders the columns.

```<code>searchfor <- letters[1:2]
</code>```

Using searchfor, I'd like to make the following expression and use it in a select statement:

```<code>E <- quote(contains(searchfor[1]), contains(searchfor[2]))
df %>% select_(E)
</code>```

答:
I don't understand the exact requirement, but is this solution.</p>

```<code>select(df, matches("a|b"))
</code>```

Body:
Given a data frame like:

df <- data.frame(z_a = 1:2,
                 z_b = 1:2,
                 y_a = 3:4,
                 y_b = 3:4)

I can select columns names that contain a character with:

library(dplyr)
df %>% select(contains("a"), contains("b"))

  z_a y_a z_b y_b
1   1   3   1   3
2   2   4   2   4

NOTE that the column order has changed. Columns containing a come first before columns containing b

I'd like to select column names that contain characters in a vector and that reorders the columns.

searchfor <- letters[1:2]

Using searchfor, I'd like to make the following expression and use it in a select statement:

E <- quote(contains(searchfor[1]), contains(searchfor[2]))
df %>% select_(E)

Body:
I don't understand the exact requirement, but is this solution.

select(df, matches("a|b"))


问:
Why is there no **not equal** comparison in DynamoDB queries?
I try to query my table Tinpon with a secondary index yielding a partition-key category and sort-key tinponId. My goal is to exclude items with certain tinponIds. My first thought would be to make a negative compare:

    keyConditionExpression = "category = :category AND tinponId != :tinponId"

but there is only a equal = comparison. Then I tried serval other methods (with sadly do not exist):

    keyConditionExpression = "category = :category NOT tinponId = :tinponId"
    keyConditionExpression = "category = :category AND tinponId <> :tinponId"
    keyConditionExpression = "category = :category AND tinponId < :tinponId AND tinponId > :tinponId"

Following the AWS guide there is no not equal comparisson. Why so?
And is there a way to query DynamoDB excluding a list of ids or is the only option to retrieve a whole bunch of items and filter them later manually?

答:
The KeyConditionExpression doesn't allow not equals for the sort key. However, you can use the "Not Equals i.e. <>" in FilterExpression.

```<code>KeyConditionExpression : 'category = :category',
FilterExpression : 'tinponId  <> :tinponIdVal',
ExpressionAttributeValues : {
    ':category' : 'somevalue',
    ':tinponIdVal' :  'somevalue'
}
</code>```

Body:
The KeyConditionExpression doesn't allow not equals for the sort key. However, you can use the "Not Equals i.e. <>" in FilterExpression.

KeyConditionExpression : 'category = :category',
FilterExpression : 'tinponId  <> :tinponIdVal',
ExpressionAttributeValues : {
    ':category' : 'somevalue',
    ':tinponIdVal' :  'somevalue'
}


问:
How to create a table with left-aligned cells for currency-strings growing from right to left using jspdf-autotable?
I've been trying to modify my table for hours to make it look right, but I just can't find a smart way of doing it.

This is what it looks like: http://imgur.com/a/oK8O1

I want "beløb" and "Restgæld" entries to be left-aligned, but growing from the right ie. looking like this:

```<code>Beløb
100.000,00 Kr.
     10,00 Kr.
    200,00 Kr.
  1.000,00 Kr.
</code>```

Not:

```<code>Beløb
   100.000,00 Kr.
        10,00 Kr.
       200,00 Kr.
     1.000,00 Kr.
</code>```

And defintly not

```<code>Beløb
100.000,00 Kr.
10,00 Kr.
200,00 Kr.
1.000,00 Kr.
</code>```

Also the table must fill the whole width of the page minus margins.

These are my settings:

```<code>doc.autoTable(columns, data, {
    addPageContent: pageContent,
    margin: { top: 200 },
    columnStyles: {
        Beløb: {
            halign: 'right'
        },
        Restgæld: {
            halign: 'right'
        }
    },
    headerStyles: { fillColor: [131, 149, 160] }
});
</code>```

I've tried setting the column widths manually, but that gave me the same problem. I was thinking of right-aligning the data and manually set the column width to exactly the size of the largest number. My problem with this was that the table became too short then. I think a solution would be to add an empty place-holder column that will span for the rest of the page, but I think this method makes the code too complicated for what it is. Is there a smarter way? Maybe some setting that allows you to set spacings between columns?

答: What you want is to set the style columnWidth: 'wrap'; on the columns you want to fit the content. Currently they are set to the default auto which will make them expand if there is space available.

Body:
I've been trying to modify my table for hours to make it look right, but I just can't find a smart way of doing it.

This is what it looks like: http://imgur.com/a/oK8O1

I want "beløb" and "Restgæld" entries to be left-aligned, but growing from the right ie. looking like this:

Beløb
100.000,00 Kr.
     10,00 Kr.
    200,00 Kr.
  1.000,00 Kr.

Not:

Beløb
   100.000,00 Kr.
        10,00 Kr.
       200,00 Kr.
     1.000,00 Kr.

And defintly not

Beløb
100.000,00 Kr.
10,00 Kr.
200,00 Kr.
1.000,00 Kr.

Also the table must fill the whole width of the page minus margins.

These are my settings:

doc.autoTable(columns, data, {
    addPageContent: pageContent,
    margin: { top: 200 },
    columnStyles: {
        Beløb: {
            halign: 'right'
        },
        Restgæld: {
            halign: 'right'
        }
    },
    headerStyles: { fillColor: [131, 149, 160] }
});

I've tried setting the column widths manually, but that gave me the same problem. I was thinking of right-aligning the data and manually set the column width to exactly the size of the largest number. My problem with this was that the table became too short then. I think a solution would be to add an empty place-holder column that will span for the rest of the page, but I think this method makes the code too complicated for what it is. Is there a smarter way? Maybe some setting that allows you to set spacings between columns?


问:
constraint generic type T and K where K extends keyof T and T[K] is boolean?
I can't make following function type checked without using any somewhere.

```<code>export function makeToggleState<T, K extends keyof T>(obj: {new(): T}, prop: K) {
  return (state: T, show: boolean|null = null) => {
    if (show === null) {
      state[prop] = !state[prop]
    } else {
      state[prop] = show
    }
  }
}

class State {
    value = true
}

makeToggleState(State, 'value')
</code>```

I am getting this error:

```<code>Type 'false' is not assignable to type 'T[K]'.
  Type 'false' is not assignable to type 'T[string]'.
(parameter) prop: K extends keyof T
</code>```

What is the best way to tell compiler I want K extends keyof T and T[K] is boolean?

答:
There is no way to have this constraint in makeToggleState declaration, but you can declare it for the function it returns, using intersection of T and mapped type T & {[n in K]: boolean} for its state parameter.

```<code>export function makeToggleState<T, K extends keyof T>(obj: {new(): T}, prop: K) {
    return (state: T & {[n in K]: boolean}, show: boolean|null = null) => {
    if (show === null) {
      state[prop] = !state[prop]
    } else {
      state[prop] = show
    }
  }
}

class State {
    value = true;
    name = 'q';
}

const toggleValue = makeToggleState(State, 'value');

const s = new State();
toggleValue(s)

const toggleName = makeToggleState(State, 'name'); // ok

// but does not compile when you try to use it
toggleName(s);

//Argument of type 'State' is not assignable to parameter of type 'State & { name: boolean; }'.
//  Type 'State' is not assignable to type '{ name: boolean; }'.
//    Types of property 'name' are incompatible.
//      Type 'string' is not assignable to type 'boolean'.
</code>```

Body:
I can't make following function type checked without using any somewhere.

export function makeToggleState<T, K extends keyof T>(obj: {new(): T}, prop: K) {
  return (state: T, show: boolean|null = null) => {
    if (show === null) {
      state[prop] = !state[prop]
    } else {
      state[prop] = show
    }
  }
}

class State {
    value = true
}

makeToggleState(State, 'value')

I am getting this error:

Type 'false' is not assignable to type 'T[K]'.
  Type 'false' is not assignable to type 'T[string]'.
(parameter) prop: K extends keyof T

What is the best way to tell compiler I want K extends keyof T and T[K] is boolean?

Body:
There is no way to have this constraint in makeToggleState declaration, but you can declare it for the function it returns, using intersection of T and mapped type T & {[n in K]: boolean} for its state parameter.

export function makeToggleState<T, K extends keyof T>(obj: {new(): T}, prop: K) {
    return (state: T & {[n in K]: boolean}, show: boolean|null = null) => {
    if (show === null) {
      state[prop] = !state[prop]
    } else {
      state[prop] = show
    }
  }
}

class State {
    value = true;
    name = 'q';
}

const toggleValue = makeToggleState(State, 'value');

const s = new State();
toggleValue(s)

const toggleName = makeToggleState(State, 'name'); // ok

// but does not compile when you try to use it
toggleName(s);

//Argument of type 'State' is not assignable to parameter of type 'State & { name: boolean; }'.
//  Type 'State' is not assignable to type '{ name: boolean; }'.
//    Types of property 'name' are incompatible.
//      Type 'string' is not assignable to type 'boolean'.


问:
Protocol function no working in swift 3
This is a cardCollectionView app, I am trying to delete item with longpress and show a delete button in item. I can delete item already, but my item doesn't reload to an empty place. I found that the problem is because there is a protocol function never working.

Here's my protocol:

```<code>@objc protocol ActionDelegation:class {

func deleteCell(_ indexPath:IndexPath, _ cellView:MyCollectionViewCell)
func hideAllDeleteBtn()
func showAllDeleteBtn()
}
</code>```

The hideAllDeleteBtn() and showAllDeleteBtn() function are working well, but deleteCell(_ indexPath:IndexPath, _ cellView:MyCollectionViewCell) function never works.

```<code>weak var delegation : ActionDelegation!
</code>```

I try to print() here, but never run in this function at all (in MyCollectionViewCell class)

```<code>func animationDidStop(_ theAnimation: CAAnimation!, finished flag: Bool){
    delegation.deleteCell(path, self)
}
</code>```

here is ViewController class

I did cell.delegation = self in one of my function

It should work after I tap delete button with a disspare animation,

```<code>func deleteCell(_ indexPath:IndexPath, _ cellView:MyCollectionViewCell){            print("1")
    myCollectionView.performBatchUpdates({ () -> Void in
        print("2")
        self.cellArray.removeObject(at: indexPath.row)
        self.myCollectionView.deleteItems(at: [indexPath])
        print("3")
    }, completion: {(flag:Bool) in
        print("4")
        self.myCollectionView.reloadData()
        print("5")
    })
}
</code>```

yup...this function is never working, if this is function working then empty place should not be empty.
FYI  the other two protocol functions are working, why only this one can't ?

Edit

This is the animation part, it is in a Animation class which extends NSObject

```<code> class Animation: NSObject {

   func fadeAnimation(view:UIView){
    let animation = CATransition()
    animation.delegate = view as? CAAnimationDelegate
    animation.duration = 0.5
    view.layer.add(animation, forKey: nil)
    view.isHidden = true
}}
</code>```

it will call in MyCollectionViewCell
like below (in MyCollectionViewCell)

```<code>let animation = Animation()

func setAnimation(){

    animation.fadeAnimation(view: self)
}
</code>```

when I delete the item, it can delete and with fade animation

答:
The animationDidStop(_:finished:) is not getting called because you've specified that the first parameter is an optional, but it's not.

By the way, if you specified that MyCollectionViewCell conformed to CAAnimationDelegate (for example, in an extension, like below), the compiler would have warned you about this issue:

It should be:

```<code>extension MyCollectionViewCell: CAAnimationDelegate {
    func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
        ...
    }
}
</code>```

In the future, I might suggest using block-based animation to simplify any delegate-related issues with the animation.

```<code>protocol ActionDelegate: class {
    func deleteCell(_ cell: UICollectionViewCell)
    func hideAllDeleteBtn()
    func showAllDeleteBtn()
}

class MyCollectionViewCell: UICollectionViewCell {
    weak var delegate: ActionDelegate?

    func fadeAndDelete() {
        UIView.animate(withDuration: 0.5, animations: {
            self.alpha = 0
        }, completion: { _ in
            self.delegate?.deleteCell(self)
        })
    }
}
</code>```

Note, I simplified deleteCell(_:) delegate method, because you shouldn't save the IndexPath, but instead calculated it just in time:

```<code>extension ViewController: ActionDelegate {
    func deleteCell(_ cell: UICollectionViewCell) {
        guard let indexPath = myCollectionView.indexPath(for: cell) else { return }

        cellArray.removeObject(at: indexPath.row)   // I might suggest making `cellArray` a Swift array rather than a `NSMutableArray`
        myCollectionView.deleteItems(at: [indexPath])
    }

    func hideAllDeleteBtn() { ... }

    func showAllDeleteBtn() { ... }
}
</code>```

Title: Protocol function no working in swift 3

Body:
This is a cardCollectionView app, I am trying to delete item with longpress and show a delete button in item. I can delete item already, but my item doesn't reload to an empty place. I found that the problem is because there is a protocol function never working.

Here's my protocol:

@objc protocol ActionDelegation:class {

func deleteCell(_ indexPath:IndexPath, _ cellView:MyCollectionViewCell)
func hideAllDeleteBtn()
func showAllDeleteBtn()
}

The hideAllDeleteBtn() and showAllDeleteBtn() function are working well, but deleteCell(_ indexPath:IndexPath, _ cellView:MyCollectionViewCell) function never works.

weak var delegation : ActionDelegation!

I try to print() here, but never run in this function at all (in MyCollectionViewCell class)

func animationDidStop(_ theAnimation: CAAnimation!, finished flag: Bool){
    delegation.deleteCell(path, self)
}

here is ViewController class

I did cell.delegation = self in one of my function

It should work after I tap delete button with a disspare animation,

func deleteCell(_ indexPath:IndexPath, _ cellView:MyCollectionViewCell){            print("1")
    myCollectionView.performBatchUpdates({ () -> Void in
        print("2")
        self.cellArray.removeObject(at: indexPath.row)
        self.myCollectionView.deleteItems(at: [indexPath])
        print("3")
    }, completion: {(flag:Bool) in
        print("4")
        self.myCollectionView.reloadData()
        print("5")
    })
}

yup...this function is never working, if this is function working then empty place should not be empty.
FYI  the other two protocol functions are working, why only this one can't ?

Edit

This is the animation part, it is in a Animation class which extends NSObject

 class Animation: NSObject {

   func fadeAnimation(view:UIView){
    let animation = CATransition()
    animation.delegate = view as? CAAnimationDelegate
    animation.duration = 0.5
    view.layer.add(animation, forKey: nil)
    view.isHidden = true
}}

it will call in MyCollectionViewCell
like below (in MyCollectionViewCell)

let animation = Animation()

func setAnimation(){

    animation.fadeAnimation(view: self)
}

when I delete the item, it can delete and with fade animation

Body:
The animationDidStop(_:finished:) is not getting called because you've specified that the first parameter is an optional, but it's not.

By the way, if you specified that MyCollectionViewCell conformed to CAAnimationDelegate (for example, in an extension, like below), the compiler would have warned you about this issue:

It should be:

extension MyCollectionViewCell: CAAnimationDelegate {
    func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
        ...
    }
}

In the future, I might suggest using block-based animation to simplify any delegate-related issues with the animation.

protocol ActionDelegate: class {
    func deleteCell(_ cell: UICollectionViewCell)
    func hideAllDeleteBtn()
    func showAllDeleteBtn()
}

class MyCollectionViewCell: UICollectionViewCell {
    weak var delegate: ActionDelegate?

    func fadeAndDelete() {
        UIView.animate(withDuration: 0.5, animations: {
            self.alpha = 0
        }, completion: { _ in
            self.delegate?.deleteCell(self)
        })
    }
}

Note, I simplified deleteCell(_:) delegate method, because you shouldn't save the IndexPath, but instead calculated it just in time:

extension ViewController: ActionDelegate {
    func deleteCell(_ cell: UICollectionViewCell) {
        guard let indexPath = myCollectionView.indexPath(for: cell) else { return }

        cellArray.removeObject(at: indexPath.row)   // I might suggest making `cellArray` a Swift array rather than a `NSMutableArray`
        myCollectionView.deleteItems(at: [indexPath])
    }

    func hideAllDeleteBtn() { ... }

    func showAllDeleteBtn() { ... }
}


问:
Angular - How can I mock an HTTP request?
I have a simple code which invokes a real HTTP request :

```<code>@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{person?.id}}</h2>
    </div>
  `,
})
export class App {
  name:string;
  constructor(public http: Http) {
     this.http.get('https://jsonplaceholder.typicode.com/posts/1')
     .map(res => res.json()).subscribe(res => {
        this.person = res;
     },()=>{},()=>console.log('complete'));
  }
}
</code>```

But now I want to mock the request so that it will fetch data from a file containing :

```<code>export arrFakeData:any = {id:1};
</code>```

I don't want to use a service . I want to mock the request.

Some examples shows to use XHRBackend and some shows how to extend the HTTP class,  but they doesn't say how can I force the data to retrieve

I know that I should use

```<code>  providers:[ /*{ provide: XHRBackend, useClass: MockBackend }*/]
</code>```

But I don't know how.

Question:

How can I mock http request and return (for GET) the array from arrFakeData ?

PLUNKER

答: You can just make the http endpoint a JSON file containing whatever data you need. This is exactly how we did it on my last project for Google, and how I do it in my own side projects. We didn't bother mocking up http services and so on, we just pointed at a json file and left everything else the same. </p>

Body:
I have a simple code which invokes a real HTTP request :

@Component({
  selector: 'my-app',
  template: `

Hello {{person?.id}}

  `,
})
export class App {
  name:string;
  constructor(public http: Http) {
     this.http.get('https://jsonplaceholder.typicode.com/posts/1')
     .map(res => res.json()).subscribe(res => {
        this.person = res;
     },()=>{},()=>console.log('complete'));
  }
}

But now I want to mock the request so that it will fetch data from a file containing :

export arrFakeData:any = {id:1};

I don't want to use a service . I want to mock the request.

Some examples shows to use XHRBackend and some shows how to extend the HTTP class,  but they doesn't say how can I force the data to retrieve

I know that I should use

  providers:[ /*{ provide: XHRBackend, useClass: MockBackend }*/]

But I don't know how.

Question:

How can I mock http request and return (for GET) the array from arrFakeData ?

PLUNKER


问:
How to validate if keyword matched is highlighed or not in Ruby and Rails
I am writing a testing script using Ruby and Rails. I have to validate whether proper keyword is highlighted or not. How do i do in rub. For eg. "confidential" is my keyword and want to validate whether it got highlighted or not.</p>

答:
Assuming you highlight your keyword with -tags and have a HighLighter class that does the highlighting:

```<code>assert_contains "<em>confidential</em>", HighLighter.highlight(text)
</code>```

Body:
Assuming you highlight your keyword with <em>-tags and have a HighLighter class that does the highlighting:

assert_contains "<em>confidential</em>", HighLighter.highlight(text)


问:
Read value from Arduino web server
I am trying to write Python code to read a simple temperature value from the local Arduino server.

This is my source page:

```<code><font color=black size=7>Senzorji DS18B20<font color=black size=7><br />
<font color=black size=7>Kurnica: [26.00] °
C
<font color=green size=7><font color=black size=7><br />
<font color=black size=7>Zunaj: [33.13] °
C
<font color=green size=7><font color=black size=7><br />
<font color=black size=7>Garaza: [27.62] °
C
<font color=black size=7><br />
<br />
Senzor DHT11 - Garaza<font color=black size=7><br />
<font color=black size=7>Temperatura v garazi: [24.00] °
C
<font color=green size=7><font color=black size=7><br />
<font color=black size=7>Vlaga v garazi: [17.00] %
<br />
<br />
Senzor DHT11 - Stara kurilnica<font color=black size=7><br />
<font color=black size=7>Temperatura v stari kurilnici: [23.00] °
C
<font color=green size=7><font color=black size=7><br />
<font color=black size=7>Vlaga v stari kurilnici: [14.00] %
<font color=green size=7>
</code>```

I want to read the value in square brackets with Beautiful soup but no luck. I cannot find my case. All examples are more complex; mine is simple but I do not know.

I'm using Raspberry Pi.

With PHP, I wrote simple code. It changed for me and it worked.
This is my PHP code:

```<code>function get_string_between($string, $start, $end){
        $string = " ".$string;
        $ini = strpos($string,$start);
        if ($ini == 0) return "";
        $ini += strlen($start);
        $len = strpos($string,$end,$ini) - $ini;
        return substr($string,$ini,$len);
}

$arduino91 = file_get_contents("http://192.168.5.91/");
$radiator = get_string_between($arduino91, "(povratek): [", "]");
$garaza = get_string_between($arduino91, "Garaza: [", "]");
$garazadht = get_string_between($arduino91, "Temperatura v garazi: [", "]");
$garazavl = get_string_between($arduino91, "Vlaga v garazi: [", "]");
$kurnica = get_string_between($arduino91, "Kurnica: [", "]");

echo "Temperatura v kurilnici: $kuriltemp"."<br>";
echo "Pec: $pec1"."<br>";
</code>```

How would I write such code in Python?

答:
You can extract all values between [..] directly from your html/text using regular expressions, i.e. re.findall().

Assuming you already fetched that page from your Arduino server, perhaps using the requests library:

```<code>import requests
html = requests.get("http://127.0.0.1/").text
# now in html is something like: "<font color=black size=7>...."
</code>```

you can extract those values with:

```<code>import re
values = re.findall('\[([\d.]+)\]', html)
</code>```

For html from your example, values variable will contain:

```<code>['26.00', '33.13', '27.62', '24.00', '17.00', '23.00', '14.00']
</code>```

Now you can say:

```<code>kurnica = values[0]
garaza = values[2]
...
</code>```

Or if you want to extract all values at once, you can use the destructuring assignment, like this:

```<code>kurnica, zunaj, garaza, t_garaza, h_garaza, t_kuril, h_kuril = values
</code>```

Title: Read value from Arduino web server

Body:
I am trying to write Python code to read a simple temperature value from the local Arduino server.

This is my source page:

Senzorji DS18B20

Kurnica: [26.00] °
C

Zunaj: [33.13] °
C

Garaza: [27.62] °
C

Senzor DHT11 - Garaza

Temperatura v garazi: [24.00] °
C

Vlaga v garazi: [17.00] %

Senzor DHT11 - Stara kurilnica

Temperatura v stari kurilnici: [23.00] °
C

Vlaga v stari kurilnici: [14.00] %

I want to read the value in square brackets with Beautiful soup but no luck. I cannot find my case. All examples are more complex; mine is simple but I do not know.

I'm using Raspberry Pi.

With PHP, I wrote simple code. It changed for me and it worked.
This is my PHP code:

function get_string_between($string, $start, $end){
        $string = " ".$string;
        $ini = strpos($string,$start);
        if ($ini == 0) return "";
        $ini += strlen($start);
        $len = strpos($string,$end,$ini) - $ini;
        return substr($string,$ini,$len);
}

$arduino91 = file_get_contents("http://192.168.5.91/");
$radiator = get_string_between($arduino91, "(povratek): [", "]");
$garaza = get_string_between($arduino91, "Garaza: [", "]");
$garazadht = get_string_between($arduino91, "Temperatura v garazi: [", "]");
$garazavl = get_string_between($arduino91, "Vlaga v garazi: [", "]");
$kurnica = get_string_between($arduino91, "Kurnica: [", "]");

echo "Temperatura v kurilnici: $kuriltemp"."
";
echo "Pec: $pec1"."
";

How would I write such code in Python?

Body:
You can extract all values between [..] directly from your html/text using regular expressions, i.e. re.findall().

Assuming you already fetched that page from your Arduino server, perhaps using the requests library:

import requests
html = requests.get("http://127.0.0.1/").text
# now in html is something like: "<font color=black size=7>...."

you can extract those values with:

import re
values = re.findall('\[([\d.]+)\]', html)

For html from your example, values variable will contain:

['26.00', '33.13', '27.62', '24.00', '17.00', '23.00', '14.00']

Now you can say:

kurnica = values[0]
garaza = values[2]
...

Or if you want to extract all values at once, you can use the destructuring assignment, like this:

kurnica, zunaj, garaza, t_garaza, h_garaza, t_kuril, h_kuril = values


问:
Spark Cassandra Streaming
i want to save data from spark streaming to cassandra using scala maven project. this is the code that save data to cassandra table

```<code>import org.apache.maventestsparkproject._
import com.datastax.spark.connector.streaming._
import com.datastax.spark.connector.SomeColumns

import org.apache.spark.SparkConf
import org.apache.spark.streaming._
import org.apache.spark.streaming.kafka._

object SparkCassandra {
    def main(args: Array[String]) {

     val sparkConf = new SparkConf()
         .setAppName("KakfaStreamToCassandra").setMaster("local[*]")
         .set("spark.cassandra.connection.host", "localhost")
         .set("spark.cassandra.connection.port", "9042")

    val topics = "fayssal1,fayssal2"

     val ssc = new StreamingContext(sparkConf, Seconds(5))

     val topicsSet = topics.split(",").toSet
     val kafkaParams = Map[String, String]("metadata.broker.list" -> brokers)
     val messages = KafkaUtils.createDirectStream[String, String, StringDecoder, StringDecoder](ssc, kafkaParams, topicsSet)

     val lines = messages.map(_._2)

     val words = lines.flatMap(_.split(" "))

     val wordCounts = words.map(x => (x, 1L)).reduceByKey(_ + _)

     wordCounts.saveToCassandra(keysspace, table, SomeColumns("word", "count"))

     ssc.awaitTermination()

     ssc.start()
}
}
</code>```

the project is builting successfly, this is my pom.xml

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>org.apache.maventestsparkproject</groupId>
  <artifactId>testmavenapp</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>
  <name>testmavenapp</name>
  <url>http://maven.apache.org</url>

    <properties>
       <scala.version>2.11.8</scala.version>
       <spark.version>1.6.2</spark.version>
       <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
         <groupId>org.scala-lang</groupId>
         <artifactId>scala-library</artifactId>
        <version>${scala.version}</version>
     </dependency>

     <dependency>
         <groupId>org.apache.spark</groupId>
         <artifactId>spark-core_2.11</artifactId>
         <version>${spark.version}</version>
     </dependency>

     <dependency>
         <groupId>org.apache.spark</groupId>
         <artifactId>spark-sql_2.11</artifactId>
         <version>${spark.version}</version>
     </dependency>

    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-streaming_2.10</artifactId>
        <version>1.3.1</version>
    </dependency>

     <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-streaming-kafka_2.11</artifactId>
        <version>${spark.version}</version>
     </dependency>
    <dependency>
        <groupId>com.datastax.spark</groupId>
        <artifactId>spark-cassandra-connector_2.10</artifactId>
        <version>1.0.0-rc4</version>
    </dependency>
    <dependency>
        <groupId>com.datastax.spark</groupId>
        <artifactId>spark-cassandra-connector-java_2.10</artifactId>
        <version>1.0.0-rc4</version>
    </dependency>
    <dependency>
        <groupId>com.datastax.cassandra</groupId>
        <artifactId>cassandra-driver-core</artifactId>
        <version>2.1.5</version>
    </dependency>
     <dependency>
        <groupId>com.datastax.spark</groupId>
        <artifactId>spark-cassandra-connector_2.11</artifactId>
        <version>${spark.version}</version>
     </dependency>
  </dependencies>
</project>
</code>```

but when i run this commande:

```<code>scala -cp /home/darif/TestProject/testmavenapp/target/testmavenapp-1.0-SNAPSHOT.jar /home/darif/TestProject/testmavenapp/src/main/java/org/apache/maventestsparkproject/SparkCassandra.scala
</code>```

i get the following errors look like this:

```<code>home/darif/TestProject/testmavenapp/src/main/java/org/apache/maventestsparkproject/SparkCassandra.scala:1: error: object apache is not a member of package org
import org.apache.maventestsparkproject._
           ^
/home/darif/TestProject/testmavenapp/src/main/java/org/apache/maventestsparkproject/SparkCassandra.scala:2: error: object datastax is not a member of package com
import com.datastax.spark.connector.streaming._
           ^
/home/darif/TestProject/testmavenapp/src/main/java/org/apache/maventestsparkproject/SparkCassandra.scala:3: error: object datastax is not a member of package com
import com.datastax.spark.connector.SomeColumns
           ^
/home/darif/TestProject/testmavenapp/src/main/java/org/apache/maventestsparkproject/SparkCassandra.scala:5: error: object apache is not a member of package org
import org.apache.spark.SparkConf
           ^
/home/darif/TestProject/testmavenapp/src/main/java/org/apache/maventestsparkproject/SparkCassandra.scala:6: error: object apache is not a member of package org
import org.apache.spark.streaming._
           ^
/home/darif/TestProject/testmavenapp/src/main/java/org/apache/maventestsparkproject/SparkCassandra.scala:7: error: object apache is not a member of package org
import org.apache.spark.streaming.kafka._
           ^
/home/darif/TestProject/testmavenapp/src/main/java/org/apache/maventestsparkproject/SparkCassandra.scala:12: error: not found: type SparkConf
     val sparkConf = new SparkConf()
                             ^
/home/darif/TestProject/testmavenapp/src/main/java/org/apache/maventestsparkproject/SparkCassandra.scala:19: error: not found: type StreamingContext
     val ssc = new StreamingContext(sparkConf, Seconds(5))
                       ^
/home/darif/TestProject/testmavenapp/src/main/java/org/apache/maventestsparkproject/SparkCassandra.scala:19: error: not found: value Seconds
     val ssc = new StreamingContext(sparkConf, Seconds(5))
                                                   ^
/home/darif/TestProject/testmavenapp/src/main/java/org/apache/maventestsparkproject/SparkCassandra.scala:22: error: not found: value brokers
     val kafkaParams = Map[String, String]("metadata.broker.list" -> brokers)
                                                                         ^
/home/darif/TestProject/testmavenapp/src/main/java/org/apache/maventestsparkproject/SparkCassandra.scala:23: error: not found: value KafkaUtils
     val messages = KafkaUtils.createDirectStream[String, String, StringDecoder, StringDecoder](ssc, kafkaParams, topicsSet)
                        ^
/home/darif/TestProject/testmavenapp/src/main/java/org/apache/maventestsparkproject/SparkCassandra.scala:23: error: not found: type StringDecoder
     val messages = KafkaUtils.createDirectStream[String, String, StringDecoder, StringDecoder](ssc, kafkaParams, topicsSet)
                                                                      ^
/home/darif/TestProject/testmavenapp/src/main/java/org/apache/maventestsparkproject/SparkCassandra.scala:23: error: not found: type StringDecoder
     val messages = KafkaUtils.createDirectStream[String, String, StringDecoder, StringDecoder](ssc, kafkaParams, topicsSet)
                                                                                ^
13 errors found
</code>```

i am using :

```<code> Scala 2.11.8
 Spark 1.6.2
 Kafka Client APIs 0.8.2.11
 Cassandra 3.9
 Datastax Spark-Cassandra Connector compatible with Spark 1.6.2
</code>```

答:
The classpath for your application has not been set up correctly. It is recommend in various places to use spark-submit as your launcher as it will setup the vast majority of the classpath. Third party dependencies would be set using --packages.

Datastax Example

Spark Documentation

That said you could achieve the same result by custom setting various things in your Spark Conf as well as manually setting the classpath to include all of the Spark, DSE, and Kafka libraries.

Title: Spark Cassandra Streaming

Body:
i want to save data from spark streaming to cassandra using scala maven project. this is the code that save data to cassandra table

import org.apache.maventestsparkproject._
import com.datastax.spark.connector.streaming._
import com.datastax.spark.connector.SomeColumns

import org.apache.spark.SparkConf
import org.apache.spark.streaming._
import org.apache.spark.streaming.kafka._

object SparkCassandra {
    def main(args: Array[String]) {

     val sparkConf = new SparkConf()
         .setAppName("KakfaStreamToCassandra").setMaster("local[*]")
         .set("spark.cassandra.connection.host", "localhost")
         .set("spark.cassandra.connection.port", "9042")

    val topics = "fayssal1,fayssal2"

     val ssc = new StreamingContext(sparkConf, Seconds(5))

     val topicsSet = topics.split(",").toSet
     val kafkaParams = Map[String, String]("metadata.broker.list" -> brokers)
     val messages = KafkaUtils.createDirectStream[String, String, StringDecoder, StringDecoder](ssc, kafkaParams, topicsSet)

     val lines = messages.map(_._2)

     val words = lines.flatMap(_.split(" "))

     val wordCounts = words.map(x => (x, 1L)).reduceByKey(_ + _)

     wordCounts.saveToCassandra(keysspace, table, SomeColumns("word", "count"))

     ssc.awaitTermination()

     ssc.start()
}
}

the project is builting successfly, this is my pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>org.apache.maventestsparkproject</groupId>
  <artifactId>testmavenapp</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>
  <name>testmavenapp</name>
  <url>http://maven.apache.org</url>

    <properties>
       <scala.version>2.11.8</scala.version>
       <spark.version>1.6.2</spark.version>
       <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
         <groupId>org.scala-lang</groupId>
         <artifactId>scala-library</artifactId>
        <version>${scala.version}</version>
     </dependency>

     <dependency>
         <groupId>org.apache.spark</groupId>
         <artifactId>spark-core_2.11</artifactId>
         <version>${spark.version}</version>
     </dependency>

     <dependency>
         <groupId>org.apache.spark</groupId>
         <artifactId>spark-sql_2.11</artifactId>
         <version>${spark.version}</version>
     </dependency>

    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-streaming_2.10</artifactId>
        <version>1.3.1</version>
    </dependency>

     <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-streaming-kafka_2.11</artifactId>
        <version>${spark.version}</version>
     </dependency>
    <dependency>
        <groupId>com.datastax.spark</groupId>
        <artifactId>spark-cassandra-connector_2.10</artifactId>
        <version>1.0.0-rc4</version>
    </dependency>
    <dependency>
        <groupId>com.datastax.spark</groupId>
        <artifactId>spark-cassandra-connector-java_2.10</artifactId>
        <version>1.0.0-rc4</version>
    </dependency>
    <dependency>
        <groupId>com.datastax.cassandra</groupId>
        <artifactId>cassandra-driver-core</artifactId>
        <version>2.1.5</version>
    </dependency>
     <dependency>
        <groupId>com.datastax.spark</groupId>
        <artifactId>spark-cassandra-connector_2.11</artifactId>
        <version>${spark.version}</version>
     </dependency>
  </dependencies>
</project>

but when i run this commande:

scala -cp /home/darif/TestProject/testmavenapp/target/testmavenapp-1.0-SNAPSHOT.jar /home/darif/TestProject/testmavenapp/src/main/java/org/apache/maventestsparkproject/SparkCassandra.scala

i get the following errors look like this:

home/darif/TestProject/testmavenapp/src/main/java/org/apache/maventestsparkproject/SparkCassandra.scala:1: error: object apache is not a member of package org
import org.apache.maventestsparkproject._
           ^
/home/darif/TestProject/testmavenapp/src/main/java/org/apache/maventestsparkproject/SparkCassandra.scala:2: error: object datastax is not a member of package com
import com.datastax.spark.connector.streaming._
           ^
/home/darif/TestProject/testmavenapp/src/main/java/org/apache/maventestsparkproject/SparkCassandra.scala:3: error: object datastax is not a member of package com
import com.datastax.spark.connector.SomeColumns
           ^
/home/darif/TestProject/testmavenapp/src/main/java/org/apache/maventestsparkproject/SparkCassandra.scala:5: error: object apache is not a member of package org
import org.apache.spark.SparkConf
           ^
/home/darif/TestProject/testmavenapp/src/main/java/org/apache/maventestsparkproject/SparkCassandra.scala:6: error: object apache is not a member of package org
import org.apache.spark.streaming._
           ^
/home/darif/TestProject/testmavenapp/src/main/java/org/apache/maventestsparkproject/SparkCassandra.scala:7: error: object apache is not a member of package org
import org.apache.spark.streaming.kafka._
           ^
/home/darif/TestProject/testmavenapp/src/main/java/org/apache/maventestsparkproject/SparkCassandra.scala:12: error: not found: type SparkConf
     val sparkConf = new SparkConf()
                             ^
/home/darif/TestProject/testmavenapp/src/main/java/org/apache/maventestsparkproject/SparkCassandra.scala:19: error: not found: type StreamingContext
     val ssc = new StreamingContext(sparkConf, Seconds(5))
                       ^
/home/darif/TestProject/testmavenapp/src/main/java/org/apache/maventestsparkproject/SparkCassandra.scala:19: error: not found: value Seconds
     val ssc = new StreamingContext(sparkConf, Seconds(5))
                                                   ^
/home/darif/TestProject/testmavenapp/src/main/java/org/apache/maventestsparkproject/SparkCassandra.scala:22: error: not found: value brokers
     val kafkaParams = Map[String, String]("metadata.broker.list" -> brokers)
                                                                         ^
/home/darif/TestProject/testmavenapp/src/main/java/org/apache/maventestsparkproject/SparkCassandra.scala:23: error: not found: value KafkaUtils
     val messages = KafkaUtils.createDirectStream[String, String, StringDecoder, StringDecoder](ssc, kafkaParams, topicsSet)
                        ^
/home/darif/TestProject/testmavenapp/src/main/java/org/apache/maventestsparkproject/SparkCassandra.scala:23: error: not found: type StringDecoder
     val messages = KafkaUtils.createDirectStream[String, String, StringDecoder, StringDecoder](ssc, kafkaParams, topicsSet)
                                                                      ^
/home/darif/TestProject/testmavenapp/src/main/java/org/apache/maventestsparkproject/SparkCassandra.scala:23: error: not found: type StringDecoder
     val messages = KafkaUtils.createDirectStream[String, String, StringDecoder, StringDecoder](ssc, kafkaParams, topicsSet)
                                                                                ^
13 errors found

i am using :

 Scala 2.11.8
 Spark 1.6.2
 Kafka Client APIs 0.8.2.11
 Cassandra 3.9
 Datastax Spark-Cassandra Connector compatible with Spark 1.6.2


问:
How does one yank a function call in vim?
Suppose a line of text reads:

```
$x = ( frobnicate( foo( bar( $x, $y )[ 1 ]))[ 1 ]);
```

The cursor is on the 'f' of 'frobnicate' and I want to yank the text which includes the call to frobnicate.  (That is, everything up to the 3rd closing parenthesis.  I can certainly do:

```
y3f)
```

or do it interactively with

```
vf);;y
```

but neither of these is appealing.  (I don't want to have to count the '3' manually, nor do the repeated find until I hit the end point.)  Is there an easy way to accomplish the move from 'f' to the matching closing paren?  I'm thinking something like the v_i 'inner word' motion command.

答:
y% seems to work.

From help %:

Find the next item in this line after
  or under the cursor and jump to its
  match. inclusive motion. Items can
  be: ([{}]) parenthesis or
  (curly/square) brackets

Body:
Suppose a line of text reads:

$x = ( frobnicate( foo( bar( $x, $y )[ 1 ]))[ 1 ]);

The cursor is on the 'f' of 'frobnicate' and I want to yank the text which includes the call to frobnicate.  (That is, everything up to the 3rd closing parenthesis.  I can certainly do:

y3f)

or do it interactively with

vf);;y

but neither of these is appealing.  (I don't want to have to count the '3' manually, nor do the repeated find until I hit the end point.)  Is there an easy way to accomplish the move from 'f' to the matching closing paren?  I'm thinking something like the v_i 'inner word' motion command.


问:
How do I remove CLion-2016.2.3 completely from Ubuntu 16.04 LTS?
I had installed CLion(2016.2.3) IDE from CLion-2016.2.3.tar.gz file. I accidentally deleted the CLion-2016.2.3.tar.gz file and CLion-2016.2.3 folder(which I got after extracting CLion-2016.2.3.tar.gz). Now CLion isn't working. When I ran dpkg --list from terminal, CLion wasn't present in the output. I want to remove CLion completely(all its files, folders, dependencies, etc.(even the configuration files)). How do I remove it completely?

答:
Run the following command in terminal to find all the directories and files containing clion in their name :-

$ sudo find . -iname "*clion*"

Then delete the directories and files you have found.

To delete directories/files, go to the location of that directory/file in terminal using cd and run the following command :-

$ sudo rm -rf DIRECTORY_NAME/FILE_NAME


答:
There are several ways to improve the primality check for an integer n. Here are a few that you might find useful.

Reduce the number of checks: A well known theorem is giving the fact that if you want to look for factors of n, let say n = a * b, then you can look for a divisor between 1 and sqrt(n). (Proof is quite easy, the main argument being that we have three cases, either a = b = sqrt(n), or we have a < sqrt(n) < b or b < sqrt(n) < a. And, whatever case we fall in, there will be a factor of n between 1 and sqrt(n)).

Use a Sieve of Eratosthenes: This way allows to discard unnecessary candidates which are previously disqualified (see Sieve of Eratosthenes (Wikipedia))

Use probabilistic algorithms: The most efficient way to check for primality nowadays is to use a probabilistic test. It is a bit more complex to implements but it is way more efficient. You can find a few of these techniques here (Wikipedia).

Title: Reduce execution time of prime number generator


问:
Regex exclude word from matches
Does anyone know what am I doing wrong?
I have this sentence:

```<code>hi [user=1234]John Jack[/user] take me home
</code>```

and I need regex which select only John Jack

My regex:

```<code>(\[user=\d\d\d\d](.+?)\[\/user\])(?!(\[user=\d\d\d\d\])|(\[\/user\]))
</code>```

I want exclude [user=1234] and [/user]

This (\[user=\d\d\d\d](.+?)\[\/user\]) selects [user=1234]John Jack[/user] but I want only John Jack

Full example:

hi [user=1234]John Jack[/user] take me home. [user=12] Jonno Ha
  [\user] where you are [differentTag] hm?  [/differentTag]. Peter Im
  here with [user=1]Danny Di [\user]

答:
I assume you no need any java code, otherwise please comment me to delete the answer

to exclude[user=1234] and [/user] you can use:

[^\]\[a-zA-Z=\d\/]

and for matching other parts:

```<code>[a-zA-Z ]*[^\]\[a-zA-Z=\d\/][a-zA-Z]*
</code>```

and for input:

```<code>hi [user=1234]John Jack[/user] take me home. [user=12] Jonno Ha [\user] where you are [differentTag] hm? [/differentTag]. Peter Im here with [user=1]Danny Di [\user]
</code>```

you can use:

```<code>[a-zA-Z ]*[^\]\[a-zA-Z=\d\/\\]+[a-zA-Z ]*
</code>```

It matches all things except all inside []

[a-zA-Z ]*[^\]\[a-zA-Z=\d\/\\]+[a-zA-Z ]*

It excludes:

```<code>[user=1234]
[/user]
[user=12]
[\user]
[differentTag]
[/differentTag]
[user=1]
[\user]
</code>```

and if you want to match only the user name before [/user] or [\user] you cat try:

```<code>[a-zA-Z ]+(?=\[(?:\\|\/)user\])
</code>```

[a-zA-Z ]+(?=\[(?:\\|\/)user\])

it matches:

```<code>John Jack
Jonno Ha
Danny Di
</code>```

and more efficient than above:

```<code>(?<=])[a-zA-Z ]+(?=\[(?:\\|\/))
</code>```

and still matches:

```<code>John Jack
Jonno Ha
Danny Di
</code>```

Title: Regex exclude word from matches

Body:
Does anyone know what am I doing wrong?
I have this sentence:

hi [user=1234]John Jack[/user] take me home

and I need regex which select only John Jack

My regex:

(\[user=\d\d\d\d](.+?)\[\/user\])(?!(\[user=\d\d\d\d\])|(\[\/user\]))

I want exclude [user=1234] and [/user]

This (\[user=\d\d\d\d](.+?)\[\/user\]) selects [user=1234]John Jack[/user] but I want only John Jack

Full example:

hi [user=1234]John Jack[/user] take me home. [user=12] Jonno Ha
  [\user] where you are [differentTag] hm?  [/differentTag]. Peter Im
  here with [user=1]Danny Di [\user]

Body:
I assume you no need any java code, otherwise please comment me to delete the answer

to exclude[user=1234] and [/user] you can use:

[^\]\[a-zA-Z=\d\/]

and for matching other parts:

[a-zA-Z ]*[^\]\[a-zA-Z=\d\/][a-zA-Z]*

and for input:

hi [user=1234]John Jack[/user] take me home. [user=12] Jonno Ha [\user] where you are [differentTag] hm? [/differentTag]. Peter Im here with [user=1]Danny Di [\user]

you can use:

[a-zA-Z ]*[^\]\[a-zA-Z=\d\/\\]+[a-zA-Z ]*

It matches all things except all inside []

[a-zA-Z ]*[^\]\[a-zA-Z=\d\/\\]+[a-zA-Z ]*

It excludes:

[user=1234]
[/user]
[user=12]
[\user]
[differentTag]
[/differentTag]
[user=1]
[\user]

and if you want to match only the user name before [/user] or [\user] you cat try:

[a-zA-Z ]+(?=\[(?:\\|\/)user\])

[a-zA-Z ]+(?=\[(?:\\|\/)user\])

it matches:

John Jack
Jonno Ha
Danny Di

and more efficient than above:

(?<=])[a-zA-Z ]+(?=\[(?:\\|\/))

and still matches:

John Jack
Jonno Ha
Danny Di