问:
Why is "git pull origin feature-12345 master" the only way to update my pull request branch?
I'm working with a pull request on BitBucket, which has been open for a fairly long time (several weeks, while master continues to progress rapidly), and where I'm not the only person making commits to the PR. I also need to keep the PR in sync with master. Because there are multiple people working on the branch (and because it feels dirty), doing a rebase and then git push --force is not a great option.

The only thing that I've found actually works, in this case, is the following:

```<code>git checkout master
git pull origin master
git checkout -b feature-12345 origin/feature-12345
git pull origin feature-12345 master
git push origin feature-12345
</code>```

The key line above is git pull origin feature-12345 master, which results in a commit with the message:

```<code>Merge branches 'feature-12345' and 'master' of ssh://mybitbucketserver/ABC/xyz into feature-12345
</code>```

After doing this, BitBucket shows a nice "merge" commit in the "commits" list for the PR, instead of flooding the commit history with recent commits from master.

I'm happy that I've worked out how to do this, but my question is: why do I need to use that specific command, to make it merge in this way? If I try (while on the feature-12345 branch):

```<code>git pull origin master
</code>```

And then push, it floods my commit history.

Same if I do this (which I would have thought would be 100% equivalent to the merge part of git pull origin feature-12345 master, but it seems not):

```<code>git merge feature-12345 master
</code>```

What's so special about git pull origin feature-12345 master?

答:
TL;DR: what you want is:

```<code>git fetch origin
</code>```

optionally followed by:

```<code>git checkout master
git merge origin/master   # *do* allow fast-forward here
</code>```

followed by:

```<code>git checkout feature-12345
git merge origin/feature-12345   # or git rebase origin/feature-12345
</code>```

if needed/desired, followed by:

```<code>git merge --no-ff origin/master  # or git merge --no-ff master
</code>```

As ElpieKay points out in a comment, though, you might want to rethink your strategy of merging from the tip commit of master into the feature branch.  It's not really wrong but subsequently merging the feature branch back into the master branch can result in a criss-cross merge, which Git does handle, but can produce surprises.

Description (long)

As Gauthier answered, git pull simply runs git fetch first, then—once that succeeds—git merge (or sometimes a different Git command, if you tell it to).

The tricky part is how git pull runs git merge.  It does not do what most people expect at first.

Git's merge verb merges commits.  The arguments to git merge specify which commit(s) to use as "their" commit(s).  Your commit, the --ours commit in a normal three-way merge, is always HEAD: whatever commit is current when you first run the command.  The way git pull runs its two Git commands, the commit that was current when you ran git pull is still current when git pull runs git merge.

The merge base for an ordinary three-way merge is simple enough; git merge-base will compute it for you.  But you're not doing an ordinary three-way merge.  Instead, you're doing what Git calls an octopus merge.  To find the merge base for this operation, Git uses git merge-base --octopus, giving it the hash ID of the HEAD commit and the hash ID of each of the target commits you're asking to merge.  Git then compares this merge base to each commit-to-be-merged, and combines all the changes.

When you run:

```<code>git pull origin feature-12345 master
</code>```

you tell your Git to connect to a second Git over on origin, and ask it for its feature-12345 and its master, by git pull running:

```<code>git fetch origin feature-12345 master
</code>```

These names resolve to two commit hash IDs (probably different ones, but possibly one single one).  If your Git does not yet have these commits, your Git downloads these commits now.  If your Git already has these commits, your Git need not do anything here.

The next step depends on your Git version.  If your Git is 1.8.4 or newer, your Git "opportunistically updates" your origin/feature-12345 and origin/master now.  Otherwise, it leaves them unchanged.

Last, your git fetch dumps these raw commit hash IDs into the file .git/FETCH_HEAD.  The git fetch step is now complete.

The pull code now moves on to the second Git command: it runs git merge <hash-id-1> <hash-id-2>, where the two hash IDs are extracted from the .git/FETCH_HEAD file.  (It supplies some extra arguments like -m to set the default commit message as well, but these are less important here.)  This is what invokes the octopus merge strategy.

Note, again, that Git is doing this merge by commit hash IDs, not by names!  This is one reason people can have so much trouble reproducing the effect: those hash IDs may, especially if your Git is very old (pre-1.8.4), not have any names at all!

If you just run git fetch origin, though, your Git will load, from origin, all its branches, setting all your own origin/* remote-tracking names to correspond to the commits on origin.  You could then run git merge origin/feature-12345 origin/master to get this same octopus merge.

Actually wanting octopus merges is pretty rare.  But using the octopus merge strategy has a side effect: it inhibits Git from doing a fast-forward operation.  When you run:

```<code>git merge <single-commit-specifier>
</code>```

Git will check to see if your current commit is an ancestor of the specified commit.  If so, Git can do a fast-forward instead of a merge.  If you have not told Git not do do that, it will do that, because it can.

If you want a true merge—to avoid, as you put it, "flooding the commit history"—you can simply tell Git: Don't do that.  The --no-ff flag (note double dash) says to git merge that even if it can, it shouldn't.  If it can't, it won't anyway (in which case the flag is unnecessary but harmless).  If it can, it won't because of the flag: you will get a real merge, rather than a fast-forward not-a-merge-at-all.

Body:
I'm working with a pull request on BitBucket, which has been open for a fairly long time (several weeks, while master continues to progress rapidly), and where I'm not the only person making commits to the PR. I also need to keep the PR in sync with master. Because there are multiple people working on the branch (and because it feels dirty), doing a rebase and then git push --force is not a great option.

The only thing that I've found actually works, in this case, is the following:

git checkout master
git pull origin master
git checkout -b feature-12345 origin/feature-12345
git pull origin feature-12345 master
git push origin feature-12345

The key line above is git pull origin feature-12345 master, which results in a commit with the message:

Merge branches 'feature-12345' and 'master' of ssh://mybitbucketserver/ABC/xyz into feature-12345

After doing this, BitBucket shows a nice "merge" commit in the "commits" list for the PR, instead of flooding the commit history with recent commits from master.

I'm happy that I've worked out how to do this, but my question is: why do I need to use that specific command, to make it merge in this way? If I try (while on the feature-12345 branch):

git pull origin master

And then push, it floods my commit history.

Same if I do this (which I would have thought would be 100% equivalent to the merge part of git pull origin feature-12345 master, but it seems not):

git merge feature-12345 master

What's so special about git pull origin feature-12345 master?

Body:
TL;DR: what you want is:

git fetch origin

optionally followed by:

git checkout master
git merge origin/master   # *do* allow fast-forward here

followed by:

git checkout feature-12345
git merge origin/feature-12345   # or git rebase origin/feature-12345

if needed/desired, followed by:

git merge --no-ff origin/master  # or git merge --no-ff master

As ElpieKay points out in a comment, though, you might want to rethink your strategy of merging from the tip commit of master into the feature branch.  It's not really wrong but subsequently merging the feature branch back into the master branch can result in a criss-cross merge, which Git does handle, but can produce surprises.

Description (long)

As Gauthier answered, git pull simply runs git fetch first, then—once that succeeds—git merge (or sometimes a different Git command, if you tell it to).

The tricky part is how git pull runs git merge.  It does not do what most people expect at first.

Git's merge verb merges commits.  The arguments to git merge specify which commit(s) to use as "their" commit(s).  Your commit, the --ours commit in a normal three-way merge, is always HEAD: whatever commit is current when you first run the command.  The way git pull runs its two Git commands, the commit that was current when you ran git pull is still current when git pull runs git merge.

The merge base for an ordinary three-way merge is simple enough; git merge-base will compute it for you.  But you're not doing an ordinary three-way merge.  Instead, you're doing what Git calls an octopus merge.  To find the merge base for this operation, Git uses git merge-base --octopus, giving it the hash ID of the HEAD commit and the hash ID of each of the target commits you're asking to merge.  Git then compares this merge base to each commit-to-be-merged, and combines all the changes.

When you run:

git pull origin feature-12345 master

you tell your Git to connect to a second Git over on origin, and ask it for its feature-12345 and its master, by git pull running:

git fetch origin feature-12345 master

These names resolve to two commit hash IDs (probably different ones, but possibly one single one).  If your Git does not yet have these commits, your Git downloads these commits now.  If your Git already has these commits, your Git need not do anything here.

The next step depends on your Git version.  If your Git is 1.8.4 or newer, your Git "opportunistically updates" your origin/feature-12345 and origin/master now.  Otherwise, it leaves them unchanged.

Last, your git fetch dumps these raw commit hash IDs into the file .git/FETCH_HEAD.  The git fetch step is now complete.

The pull code now moves on to the second Git command: it runs git merge <hash-id-1> <hash-id-2>, where the two hash IDs are extracted from the .git/FETCH_HEAD file.  (It supplies some extra arguments like -m to set the default commit message as well, but these are less important here.)  This is what invokes the octopus merge strategy.

Note, again, that Git is doing this merge by commit hash IDs, not by names!  This is one reason people can have so much trouble reproducing the effect: those hash IDs may, especially if your Git is very old (pre-1.8.4), not have any names at all!

If you just run git fetch origin, though, your Git will load, from origin, all its branches, setting all your own origin/* remote-tracking names to correspond to the commits on origin.  You could then run git merge origin/feature-12345 origin/master to get this same octopus merge.

Actually wanting octopus merges is pretty rare.  But using the octopus merge strategy has a side effect: it inhibits Git from doing a fast-forward operation.  When you run:

git merge <single-commit-specifier>

Git will check to see if your current commit is an ancestor of the specified commit.  If so, Git can do a fast-forward instead of a merge.  If you have not told Git not do do that, it will do that, because it can.

If you want a true merge—to avoid, as you put it, "flooding the commit history"—you can simply tell Git: Don't do that.  The --no-ff flag (note double dash) says to git merge that even if it can, it shouldn't.  If it can't, it won't anyway (in which case the flag is unnecessary but harmless).  If it can, it won't because of the flag: you will get a real merge, rather than a fast-forward not-a-merge-at-all.


来源: stackexchange

问:
HANA SQL Syntax error
I am trying to translate some code to HANA SQL Script, however I get the following error

"Incorrect syntax near 'is': line 29 col 76".

The "IS NULL" seems to be an issue, however I am not sure where to place it as I am only a beginner in SQL.

```<code>WHERE IS NULL(T2."Manual", '') = 'Y' AND T0."EntryNumber" = :list_of_cols_val_tab_del;
</code>```

Help will be much appreciated.

Thanks,
Katie.

答:
Changed the code to what's below and the SP successfully executed. Thanks. </p>

```<code>WHERE (T2."Manual" = 'Y' or T2."Manual" is NULL) AND T0."EntryNumber" = :list_of_cols_val_tab_del;
</code>```

ContentLicense: CC BY-SA 3.0

Title: HANA SQL Syntax error

Body:
I am trying to translate some code to HANA SQL Script, however I get the following error

"Incorrect syntax near 'is': line 29 col 76".

The "IS NULL" seems to be an issue, however I am not sure where to place it as I am only a beginner in SQL.

WHERE IS NULL(T2."Manual", '') = 'Y' AND T0."EntryNumber" = :list_of_cols_val_tab_del;

Help will be much appreciated.

Thanks,
Katie.

Body:
Changed the code to what's below and the SP successfully executed. Thanks.

WHERE (T2."Manual" = 'Y' or T2."Manual" is NULL) AND T0."EntryNumber" = :list_of_cols_val_tab_del;


问:
How to determine if the user signed in to Firebase with email and password or with google sign in?
I am working on a log in for a web application, and I have made it so the user can sign in manually with their email and password or by using a google sign in. Is there a way to determine which method they used? Preferably by using the Firebase authentication state change function.

```<code>`firebase.auth().onAuthStateChanged(firebaseUser => {....`
</code>```

I know you can tell how they signed in when you go into the Firebase console log but is there a way to determine it using JavaScript code?

When using firebase.auth().currentUser.providerData the following:

答: @mjrdnk's answer is correct, but there is a caveat, a user could have multiple providers linked. So using firebase.auth().currentUser.providerData[0].providerId will always yield the same provider even when another linked provider was used to sign in. The most accurate way to determine the current provider used to sign is by inspecting the ID token's field: firebase.sign_in_provider.

Body:
I am working on a log in for a web application, and I have made it so the user can sign in manually with their email and password or by using a google sign in. Is there a way to determine which method they used? Preferably by using the Firebase authentication state change function.

`firebase.auth().onAuthStateChanged(firebaseUser => {....`

I know you can tell how they signed in when you go into the Firebase console log but is there a way to determine it using JavaScript code?

When using firebase.auth().currentUser.providerData the following:


问:
Change value of a segmented control?
How do i change the value of a segmented control through code?</p>

答:
You can change the segment control value by using property selectedSegmentIndex

For Ex. segmentedControlObject.selectedSegmentIndex=1;

For Tutorial you can refer this

ContentLicense: CC BY-SA 2.5

Title: Change value of a segmented control?


问:
C# How to delete items in the listbox(loaded from textfile)
How do I delete selected item from the listbox. The content of the listbox is from a text File and I use StreamReader to read all content in the textfile and display in the listbox. And If i delete it, will it update the textfile ?

Populate listbox

```<code>        public void Outbound_load()
    {
        Listbox1.Items.Clear();
        using (StreamReader sr = new StreamReader("C:\\Users\\jason\\Desktop\\Outbound.txt"))
        {
            string line;
            // Read and display lines from the file until the end of
            // the file is reached.
            while ((line = sr.ReadLine()) != null)
            {
                Listbox1.Items.Add(line);
            }
            sr.Close();
        }
    }
</code>```

答:
After playing around I found the solution</p>

```<code>     public void Del_in()
    {

        if (Listbox2.SelectedIndex > -1)
        {
            Listbox2.Items.RemoveAt(Listbox2.SelectedIndex);
            using (FileStream fs = new FileStream(filepath, FileMode.Create, FileAccess.Write))
            {
                using (TextWriter tw = new StreamWriter(fs))
                    foreach (string item in Listbox2.Items)
                        tw.WriteLine(item);
            }
        }
    }
</code>```

Body:
How do I delete selected item from the listbox. The content of the listbox is from a text File and I use StreamReader to read all content in the textfile and display in the listbox. And If i delete it, will it update the textfile ?

Populate listbox

        public void Outbound_load()
    {
        Listbox1.Items.Clear();
        using (StreamReader sr = new StreamReader("C:\\Users\\jason\\Desktop\\Outbound.txt"))
        {
            string line;
            // Read and display lines from the file until the end of
            // the file is reached.
            while ((line = sr.ReadLine()) != null)
            {
                Listbox1.Items.Add(line);
            }
            sr.Close();
        }
    }

Body:
After playing around I found the solution

     public void Del_in()
    {

        if (Listbox2.SelectedIndex > -1)
        {
            Listbox2.Items.RemoveAt(Listbox2.SelectedIndex);
            using (FileStream fs = new FileStream(filepath, FileMode.Create, FileAccess.Write))
            {
                using (TextWriter tw = new StreamWriter(fs))
                    foreach (string item in Listbox2.Items)
                        tw.WriteLine(item);
            }
        }
    }


问:
How can one make two instances of this Singleton Class?
This code should be enough for restricting only one instance of singleton class. How can we make two instances of this object?</p>

```<code>class Singleton
{
private:
    Singleton()
    {}
    ~Singleton()
    {}
    static Singleton * ptr;
public:
    static Singleton * CreateObject()
    {
        if (!ptr)
            ptr = new Singleton;
        return ptr;
    }
    static void freeObject()
    {
        if (ptr)
        {
            delete ptr;
            ptr = 0;
        }
    }
};
Singleton * Singleton::ptr = 0;
</code>```

答:
This code should be enough for restricting only one instance of singleton class.

It is not.

How can we make two instances of this object?

With the singleton implementation you gave in your question, it is fairly easy to create a second instance:

```<code>Singleton* s1 = Singleton::CreateObject();
Singleton* s2 = new Singleton(*s1);
</code>```

And enjoy memory leaks.

To fix your singleton, you should respect the rule of five (if you define at least one constructor, define all five of them). Or you could use something else than a singleton.

Body:
This code should be enough for restricting only one instance of singleton class. How can we make two instances of this object?

class Singleton
{
private:
    Singleton()
    {}
    ~Singleton()
    {}
    static Singleton * ptr;
public:
    static Singleton * CreateObject()
    {
        if (!ptr)
            ptr = new Singleton;
        return ptr;
    }
    static void freeObject()
    {
        if (ptr)
        {
            delete ptr;
            ptr = 0;
        }
    }
};
Singleton * Singleton::ptr = 0;

Body:
This code should be enough for restricting only one instance of singleton class.

It is not.

How can we make two instances of this object?

With the singleton implementation you gave in your question, it is fairly easy to create a second instance:

Singleton* s1 = Singleton::CreateObject();
Singleton* s2 = new Singleton(*s1);

And enjoy memory leaks.

To fix your singleton, you should respect the rule of five (if you define at least one constructor, define all five of them). Or you could use something else than a singleton.


问:
not receiving firebase notification from console
i am not receiving notification after sending it through firebase console , i tried sending many notification but received one or two from around 20 notifications, i followed this guide firebase messaging from github
,why am i not receiving notification, my app is installed in one emulator and in one of my phone but when i receive notification which i have sent through notification panel i get them either on phone or emulator never got them on both.

below is the screenshot of my console

答:
Make sure token is generated</p>

```<code>FirebaseInstanceId.getInstance().getToken();
</code>```

Body:
Make sure token is generated

FirebaseInstanceId.getInstance().getToken();


答:
This query will not raise error:

```<code>WHERE IFNULL(T2."Manual", '') = 'Y' AND T0."EntryNumber" = :list_of_cols_val_tab_del;
</code>```

And you should use this instead, the IFNULL function is not necessary in your case:

```<code>WHERE T2."Manual" = 'Y' AND T0."EntryNumber" = :list_of_cols_val_tab_del;
</code>```

Title: HANA SQL Syntax error

Body:
This query will not raise error:

WHERE IFNULL(T2."Manual", '') = 'Y' AND T0."EntryNumber" = :list_of_cols_val_tab_del;

And you should use this instead, the IFNULL function is not necessary in your case:

WHERE T2."Manual" = 'Y' AND T0."EntryNumber" = :list_of_cols_val_tab_del;


问:
creating new object throws copywithzone unrecognized selector error in iOS
I have a simple object that looks like this:

```<code>#import <Foundation/Foundation.h>
#import <Parse/Parse.h>

@class MyUser;

@interface MyCycle : NSObject

@property (nonatomic, copy) NSNumber *myNumber;
@property (nonatomic, strong) MyUser *user;
@property (nonatomic, strong) NSArray *data;

@end
</code>```

Here is the implementation:

```<code>#import "MyCycle.h"

@implementation MyCycle

@end
</code>```

Here is the user object:

```<code>#import <Foundation/Foundation.h>
#import <Parse/Parse.h>

@interface MyUser : NSObject

@property (nonatomic, copy) NSString *usersName;
@property (nonatomic, copy) NSString *gender;
@property (nonatomic, copy) NSString *email;
@property (nonatomic, copy) NSString *password;
@property (nonatomic, copy) NSString *phoneNumber;
@property (nonatomic, strong) UIImage *profileImage;
@property (nonatomic, strong) PFFile *profileImageFile;

@end
</code>```

I allocate this object and populate it with the following:

```<code>MyCycle *cycle = [[MyCycle alloc] init];
        cycle.myNumber = @1;
        cycle.data = [[NSArray alloc]init];
</code>```

I get the following error:

```<code>*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[MyCycle copyWithZone:]: unrecognized selector sent to instance
</code>```

Why is this happening and how can I fix it?

答: It's old question but probably you haven't @synthesized properties 'data', 'myNumber'. In other words you have no setter for those properties.</p>

Body:
I have a simple object that looks like this:

#import <Foundation/Foundation.h>
#import <Parse/Parse.h>

@class MyUser;

@interface MyCycle : NSObject

@property (nonatomic, copy) NSNumber *myNumber;
@property (nonatomic, strong) MyUser *user;
@property (nonatomic, strong) NSArray *data;

@end

Here is the implementation:

#import "MyCycle.h"

@implementation MyCycle

@end

Here is the user object:

#import <Foundation/Foundation.h>
#import <Parse/Parse.h>

@interface MyUser : NSObject

@property (nonatomic, copy) NSString *usersName;
@property (nonatomic, copy) NSString *gender;
@property (nonatomic, copy) NSString *email;
@property (nonatomic, copy) NSString *password;
@property (nonatomic, copy) NSString *phoneNumber;
@property (nonatomic, strong) UIImage *profileImage;
@property (nonatomic, strong) PFFile *profileImageFile;

@end

I allocate this object and populate it with the following:

MyCycle *cycle = [[MyCycle alloc] init];
        cycle.myNumber = @1;
        cycle.data = [[NSArray alloc]init];

I get the following error:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[MyCycle copyWithZone:]: unrecognized selector sent to instance

Why is this happening and how can I fix it?


问:
Django: sqlite3.OperationalError: no such table in python shell
I'm following a django blog tutorial. When I used python manage.py shell and tried following commands in shell

```<code>from mainsite.models import Category, Tag
c = Category(name='category test')
c.save()
</code>```

this error occured:

```<code>sqlite3.OperationalError: no such table: mainsite_category
</code>```

This is my model.py in mainsite folder, which I think is correct:

```<code>from django.db import models
from django.contrib.auth.models import User
class Category(models.Model):
    name = models.CharField(max_length=100)

def __str__(self):
    return self.name
</code>```

I have tried manage.py makemigrations, manage.py migrate and can successfully use manage.py runserver to see the website. So what is wrong here?

Edit: this is my INSTALLED APP in settings.py

```<code>INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'mainsite',
]
</code>```

And my project structure

```<code>|____djangoBlog
| |______init__.py
| |____settings.py
| |____urls.py
| |____wsgi.py
|____mainsite
| |______init__.py
| |____admin.py
| |____apps.py
| |____models.py
| |____tests.py
| |____urls.py
| |____views.py
|____manage.py
|____README.md
|____requirements.txt
|____templates
| |____blog
| | |____index.html
</code>```

Edit: When I run python manage.py makemigrations and python manage.py migrate, the output is as follows:

```<code>No changes detected

Operations to perform:
    Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
    No migrations to apply.
</code>```

答:
It seems like in your models.py you need an indentation at name:

```<code>class Category(models.Model):
    name = models.CharField(max_length=100)
</code>```

Body:
I'm following a django blog tutorial. When I used python manage.py shell and tried following commands in shell

from mainsite.models import Category, Tag
c = Category(name='category test')
c.save()

this error occured:

sqlite3.OperationalError: no such table: mainsite_category

This is my model.py in mainsite folder, which I think is correct:

from django.db import models
from django.contrib.auth.models import User
class Category(models.Model):
    name = models.CharField(max_length=100)

def __str__(self):
    return self.name

I have tried manage.py makemigrations, manage.py migrate and can successfully use manage.py runserver to see the website. So what is wrong here?

Edit: this is my INSTALLED APP in settings.py

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'mainsite',
]

And my project structure

|____djangoBlog
| |______init__.py
| |____settings.py
| |____urls.py
| |____wsgi.py
|____mainsite
| |______init__.py
| |____admin.py
| |____apps.py
| |____models.py
| |____tests.py
| |____urls.py
| |____views.py
|____manage.py
|____README.md
|____requirements.txt
|____templates
| |____blog
| | |____index.html

Edit: When I run python manage.py makemigrations and python manage.py migrate, the output is as follows:

No changes detected

Operations to perform:
    Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
    No migrations to apply.

Body:
It seems like in your models.py you need an indentation at name:

class Category(models.Model):
    name = models.CharField(max_length=100)


问:
Xamarin Forms Orientation on iPad
I have a Universal Xamarin Forms App with a single page wrapped in a NavigationPage:

```<code>Current.MainPage = new NavigationPage(new RootPage()
            {
                BackgroundColor = (Color)Application.Current.Resources["BackgroundColour"]
            })
            {
                BackgroundColor = (Color)Application.Current.Resources["BackgroundColour"],
                BarBackgroundColor = (Color)Application.Current.Resources["BackgroundColour"],
                Padding = NavigationPaddingForPlatfrom()
            };
</code>```

I've also overridden GetSupportedInterfaceOrientations in AppDelegate and set a break point - however the break point is never hit.  When I rotate in the simulator or device, the break point isn't hit.  I've also set the Device Orientation in info.plist to Portrait only, however the App still rotates.

Am I missing some configuration point that's needed to control orientation?

I'm using Xamarin Forms 2.4.0.38779.

The end goal is to force a MasterDetail Page into landscape only.

答:
Have you tried this.</p>

```<code>protected override void OnSizeAllocated(double width, double height)
        {
           base.OnSizeAllocated(width, height);
                if (width != this.width || height != this.height)
                {
                    this.width = width;
                    this.height = height;
                    if (Width > Height)
                    {
                       //your grid
                    }
                   else
                    {
                       //your grid
                    }
                }
         }
</code>```

Title: Xamarin Forms Orientation on iPad

Body:
I have a Universal Xamarin Forms App with a single page wrapped in a NavigationPage:

Current.MainPage = new NavigationPage(new RootPage()
            {
                BackgroundColor = (Color)Application.Current.Resources["BackgroundColour"]
            })
            {
                BackgroundColor = (Color)Application.Current.Resources["BackgroundColour"],
                BarBackgroundColor = (Color)Application.Current.Resources["BackgroundColour"],
                Padding = NavigationPaddingForPlatfrom()
            };

I've also overridden GetSupportedInterfaceOrientations in AppDelegate and set a break point - however the break point is never hit.  When I rotate in the simulator or device, the break point isn't hit.  I've also set the Device Orientation in info.plist to Portrait only, however the App still rotates.

Am I missing some configuration point that's needed to control orientation?

I'm using Xamarin Forms 2.4.0.38779.

The end goal is to force a MasterDetail Page into landscape only.

Body:
Have you tried this.

protected override void OnSizeAllocated(double width, double height)
        {
           base.OnSizeAllocated(width, height);
                if (width != this.width || height != this.height)
                {
                    this.width = width;
                    this.height = height;
                    if (Width > Height)
                    {
                       //your grid
                    }
                   else
                    {
                       //your grid
                    }
                }
         }


问:
How can I edit a non-string data value in a data frame?
Consider a data set with a number of columns.

```<code>> data <- import.csv("data.csv")
> head(data[1])

> Output:

    Sex
1   M
2   M
3   F
4   M
5   I
6   I
</code>```

(Isolating the first column of my data set.) I want to change the F to M in all cases.

So I try the following:

```<code>> for (i in 1:6) {
      if (data[i, 1] == F) {
          data[i, 1] = M)
      }
  }
</code>```

This leaves the data unchanged. So I tried to import the data like so:

```<code>> data <- import.csv("data.csv", stringsAsFactors = FALSE)
</code>```

The loop method works now, but this is not OK because with the F, M, and I as strings I cannot perform the logistic regression that I need to.

Any suggestions on changing F to M but not introducing strings?

答:
Try

Df$column <- ifelse(df$var== "F","M",df$var)

Body:
Consider a data set with a number of columns.

> data <- import.csv("data.csv")
> head(data[1])

> Output:

    Sex
1   M
2   M
3   F
4   M
5   I
6   I

(Isolating the first column of my data set.) I want to change the F to M in all cases.

So I try the following:

> for (i in 1:6) {
      if (data[i, 1] == F) {
          data[i, 1] = M)
      }
  }

This leaves the data unchanged. So I tried to import the data like so:

> data <- import.csv("data.csv", stringsAsFactors = FALSE)

The loop method works now, but this is not OK because with the F, M, and I as strings I cannot perform the logistic regression that I need to.

Any suggestions on changing F to M but not introducing strings?


问:
Xcode's feature similar to Visual Studio's add reference?
I asked about debugging dylib in Xcode in this post. For Visual Studio, I can use the 'Add New Reference' in Property pages to assign a dynamic library project from the project that uses the library. And, I can put all the project in one single solution file, and make the project as 'Startup Project'. I just set breakpoints and run to debug the dynamic library.

Can Xcode do the similar/same thing?

Can Xcode have two or more projects in one something like VS2010's solution file?

Does Xcode provide something like referencing project to debug dynamic library?

答:
Can Xcode have two or more projects in one something like VS2010's solution file?

You can include an Xcode project in another Xcode project. Just use the Add Existing File action to add it. Then you can reference any of the included project's build products.


问:
Vue: Update Component data from Vue instance
I want to update data in a component from my Vue instance. Finding plenty of examples on how to do the opposite, but nothing on this.

Say I have:

```<code>Vue.component('component', {
props: {
    prop: {
        default: null
    }
},
template: '#template',
data: function () {
    return {
        open: false
    };
}
});
</code>```

Now I would like to set open to true from my Vue instance:

```<code>var root = new Vue({
    el: '#root',
    data: {},
    methods: { updateComponentData: function() {//set open to true} } });
</code>```

答:
You should be able to do it with a Child Component Ref.

```
<pre class="lang-js prettyprint-override"><code>var root = new Vue({
  el: '#root',
  data: {},
  methods: {
    updateComponentData: function() {
      this.$refs.component.open = true
    }
  }
});
</code>```

Working example

const Child = Vue.component('child', {
  template: `

Component1

Hello, {{ title }}! {{ open }}

  `,
  data() {
    return {
      title: 'component',
      open: false
    }
  }
});

var root = new Vue({
  el: '#app',
  components: {
    Child
  },
  methods: {
    updateComponentData: function() {
      //console.log('updateComponentData', this.$refs)
      this.$refs.component1.open = true
    }
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js"></script>

<div id="app">
  <h2>Parent</h2>
  <button v-on:click="updateComponentData">Click me true</button>
  <child ref="component1"></child>
</div></code>```

Body:
I want to update data in a component from my Vue instance. Finding plenty of examples on how to do the opposite, but nothing on this.

Say I have:

Vue.component('component', {
props: {
    prop: {
        default: null
    }
},
template: '#template',
data: function () {
    return {
        open: false
    };
}
});

Now I would like to set open to true from my Vue instance:

var root = new Vue({
    el: '#root',
    data: {},
    methods: { updateComponentData: function() {//set open to true} } });

Body:
You should be able to do it with a Child Component Ref.

<script type="text/x-template" id="template" ref="component">
    <div>Hello, {{ name }}!</div>
</script>

var root = new Vue({
  el: '#root',
  data: {},
  methods: {
    updateComponentData: function() {
      this.$refs.component.open = true
    }
  }
});

Working example

const Child = Vue.component('child', {
  template: `
    <div>
      <h2>Component1</h2>
      <div>Hello, {{ title }}! <strong>{{ open }}<strong></div>
    </div>
  `,
  data() {
    return {
      title: 'component',
      open: false
    }
  }
});

var root = new Vue({
  el: '#app',
  components: {
    Child
  },
  methods: {
    updateComponentData: function() {
      //console.log('updateComponentData', this.$refs)
      this.$refs.component1.open = true
    }
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js"></script>

<div id="app">
  <h2>Parent</h2>
  <button v-on:click="updateComponentData">Click me true</button>
  <child ref="component1"></child>
</div>

ContentLicense: CC BY-SA 4.0


问:
How to with enabling horizontal scrolling on webpage
index.html

```<code><div name="MainContent" id="MainContent" class="MainContent">

</div>
</code>```

index.sass

```<code>body, html
    border: none;
    outline: none;
    background-color: #FFF;
    color: #000;
    margin: 0 0 0 0

    #MainContent
        border: none;
        outline: none;
        position: relative;
        background-color: #000;
        color: #FFF;
        margin: -250px 0 0 100px;
        float: left;
        width: 2000px;
        min-width: 2000px;
        max-width: 2000px;
        height: 500px;
        min-height: 500px;
        max-height: 500px;
        top: 50%;
</code>```

Horizontal scrolling is working, however, only by using the bar at the bottom of the page. If i attempt to use the scroll wheel the page will not scroll. Any ideas as to why that is and how to make that work?

答:
To remove your body scroll property, add overflow:hidden to your html or body styles.

```<code>body,html {
   overflow:hidden;
}
</code>```

To make your div scrollable, set its width to 100%, and enable horizontal scrolling by adding overflow-x:auto. Now the width of the div will be 100% to the body , and if the content inside the div has higher width, then the scroll will get enabled.

```<code>#MainContent {
   width:100%; /* you can even set a static width here, which could be less than the body width*/
   overflow-x:auto;
}
</code>```

NB: Please REMOVE the min-width:2000px and max-width:2000px from the #MainContent style

Body:
index.html

index.sass

body, html
    border: none;
    outline: none;
    background-color: #FFF;
    color: #000;
    margin: 0 0 0 0

    #MainContent
        border: none;
        outline: none;
        position: relative;
        background-color: #000;
        color: #FFF;
        margin: -250px 0 0 100px;
        float: left;
        width: 2000px;
        min-width: 2000px;
        max-width: 2000px;
        height: 500px;
        min-height: 500px;
        max-height: 500px;
        top: 50%;

Horizontal scrolling is working, however, only by using the bar at the bottom of the page. If i attempt to use the scroll wheel the page will not scroll. Any ideas as to why that is and how to make that work?

Body:
To remove your body scroll property, add overflow:hidden to your html or body styles.

body,html {
   overflow:hidden;
}

To make your div scrollable, set its width to 100%, and enable horizontal scrolling by adding overflow-x:auto. Now the width of the div will be 100% to the body , and if the content inside the div has higher width, then the scroll will get enabled.

#MainContent {
   width:100%; /* you can even set a static width here, which could be less than the body width*/
   overflow-x:auto;
}

NB: Please REMOVE the min-width:2000px and max-width:2000px from the #MainContent style


问:
Can I use a digital signature in this scenario? With c#
I want to sign an xml document using a private key. And then when my client receives the software for them to be able to verify that the xml document hasnt changed by using a public key.

I want to distribut the same public key amongst all of my customers so that we can issue licenses to them.

Is this possible? I am using c# and .net.

答:
Yes, this is possible.  There are more important questions when putting together a solution.

Do you want this verification to be done automatically by your program?

Do you want to set up your own public key infrastructure?

Does your company already have a public signing certificate?

Depending on the answers, you might not need to write any code.


问:
Symfony 3 Unique constraint error
I am getting the following error while adding a UniqueEntity constraint on the email field of my User entity.

Attempted to load class "Unique" from namespace
  "\Symfony\Component\Validator\Constraints". Did you forget a "use"
  statement for another namespace?

If I remove the validation the error disappears. The contents of my validation.yml file are as followed.

```<code>LB\CoreBundle\Entity\User:
constraints:
    - Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity:
            fields: [email]
            groups: [registration,userEdit]
</code>```

I have tried importing the validation constraint in my User.php file but the error still persists. Any help to get rid of this error is greatly appreciated.

答:
```<code>use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

/**
 * @ORM\Entity
 * @ORM\Table(name="cab_fos_user")
 * @ORM\HasLifecycleCallbacks()
 * @UniqueEntity("email")
 * @ExclusionPolicy("all")
 * @Vich\Uploadable
 */
class User extends BaseUser
</code>```

Title: Symfony 3 Unique constraint error

Body:
I am getting the following error while adding a UniqueEntity constraint on the email field of my User entity.

Attempted to load class "Unique" from namespace
  "\Symfony\Component\Validator\Constraints". Did you forget a "use"
  statement for another namespace?

If I remove the validation the error disappears. The contents of my validation.yml file are as followed.

LB\CoreBundle\Entity\User:
constraints:
    - Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity:
            fields: [email]
            groups: [registration,userEdit]

I have tried importing the validation constraint in my User.php file but the error still persists. Any help to get rid of this error is greatly appreciated.


问:
angularjs password confirmation not display confirmation message
Please help me why im not able to display confirmation message

```<code>angular.module('MyApp')
    .directive('pwCheck', function () {
        return {
            restrict: 'A', // only activate on element attribute
            require: '?ngModel',

            link: function (scope, elem, attr, ngModel) {
                var val2 = "";
                scope.$watch(attr.ngModel, function () {
                    validate();
                })
                attr.$observe('pwCheck', function (val) {
                    validate();
                });
                var validate = function () {
                    var val1 = ngModel.$viewValue;
                    var val2 = attr.pwCheck;
                    ngModel.$setValidity('passwordVerify', val1 === val2);
</code>```

HtmlCode

Here im trying to validate Emp_Password against  Emp_Cpsw    for that i used EmpCpsw  directive.The directive working Good but confirmation message is not popup

```<code><b>EnterPassword</b> :<input type="password" name="Emp_Password" ng-model="psw1" pw-check="{{psw2}}" required />

                <span class="error" ng-show="pwCheck">Password not match</span>
                <b>c_password</b><input type="password" name="Emp_Cpsw" ng-model="psw2" pw-check required pw-check="{{psw1}}" />
                <span class="error" ng-show="pwCheck">Password not match</span>
</code>```

答:
You have added setValidity with name passwordVerify so should use the same name in your view.

```<code>ngModel.$setValidity('passwordVerify', val1 === val2);
</code>```

So, use

```<code><span class="error" ng-show="passwordVerify">Password not match</span>
</code>```

Body:
Please help me why im not able to display confirmation message

angular.module('MyApp')
    .directive('pwCheck', function () {
        return {
            restrict: 'A', // only activate on element attribute
            require: '?ngModel',

            link: function (scope, elem, attr, ngModel) {
                var val2 = "";
                scope.$watch(attr.ngModel, function () {
                    validate();
                })
                attr.$observe('pwCheck', function (val) {
                    validate();
                });
                var validate = function () {
                    var val1 = ngModel.$viewValue;
                    var val2 = attr.pwCheck;
                    ngModel.$setValidity('passwordVerify', val1 === val2);

HtmlCode

Here im trying to validate Emp_Password against  Emp_Cpsw    for that i used EmpCpsw  directive.The directive working Good but confirmation message is not popup

EnterPassword :<input type="password" name="Emp_Password" ng-model="psw1" pw-check="{{psw2}}" required />

                Password not match
                c_password<input type="password" name="Emp_Cpsw" ng-model="psw2" pw-check required pw-check="{{psw1}}" />
                Password not match

Body:
You have added setValidity with name passwordVerify so should use the same name in your view.

ngModel.$setValidity('passwordVerify', val1 === val2);

So, use

<span class="error" ng-show="passwordVerify">Password not match</span>


问:
powershell delete some files older than 90 days, with exceptions
```<code>$timeLimit1 = Get-Date.AddDays(-90)
Get-ChildItem <path> | ? {$_.LastWriteTime -le $timeLimit1 } | Remove-Item
</code>```

So I have the easier part, but I am trying to figure out how to do something a little more complex.

I am setting up a backup deletion routine.  The requirement is to keep the last 90 days of backups, then the final day of each month prior to that for the current year and finally a backup from December 31st for the prior 2 years.

I couldn't find any examples other than just a single check; is it possible to do several checks to automate that.

答:
Just create an array of your "special" dates and add them to your filter.

```<code>$timeLimit1 = Get-Date
$timeLimit1.AddDays(-90)
$specialDates = (Get-Date "31-12-2014"), (Get-Date "31-05-2017") # continue the list
Get-ChildItem <path> | ? {$_.LastWriteTime -le $timeLimit1 -and $specialDates -notcontains $_.LastAccessTime.Date } | Remove-Item
</code>```

I would also make a function to find the "special" dates.

Body:
$timeLimit1 = Get-Date.AddDays(-90)
Get-ChildItem <path> | ? {$_.LastWriteTime -le $timeLimit1 } | Remove-Item

So I have the easier part, but I am trying to figure out how to do something a little more complex.

I am setting up a backup deletion routine.  The requirement is to keep the last 90 days of backups, then the final day of each month prior to that for the current year and finally a backup from December 31st for the prior 2 years.

I couldn't find any examples other than just a single check; is it possible to do several checks to automate that.

Body:
Just create an array of your "special" dates and add them to your filter.

$timeLimit1 = Get-Date
$timeLimit1.AddDays(-90)
$specialDates = (Get-Date "31-12-2014"), (Get-Date "31-05-2017") # continue the list
Get-ChildItem <path> | ? {$_.LastWriteTime -le $timeLimit1 -and $specialDates -notcontains $_.LastAccessTime.Date } | Remove-Item

I would also make a function to find the "special" dates.


问:
Fetching Images from a folder and display them in modal using PHP
Im practicing some new things in Php and I have been trying to do this since past two days. I am counting the images in a given folder and displaying those images on the web-page.
Here's the code on my page.

```<code><?php
require "../_inc/master.inc.php";
require "../webConfig/web.config.php";
?>
<?php
doctype();
head_start("Gallery");
?>
<link rel="stylesheet" type="text/css" href="../lib/css/gallery.css" media="all" />
<?php
head_close();
?>
<?php
disp_head_start();
disp_head_close();
menu();
function countFolder($dir) {
 return (count(scandir($dir)) - 2);
}
$count=countFolder('../lib/media/imgs/uploads/gallery');
?>
<p> </p>
<div class="row" style="background-color:#7D37CE; padding:2%">
<?php for($i=1;$i<=$count;$i++){ ?>
<script>$(document).ready(function(){
    $('[data-toggle="tooltip"]').tooltip();
});</script>
    <div class="panel-group col-xs-12 col-sm-12 col-md-3 col-lg-3">
        <div class="panel panel-default">
            <div class="panel-body">
                <div class="thumb">
                    <a href="#" class="image-responsive" data-toggle="tooltip" title="Click to View">
                    <?php echo $i ?>
                        <img class="image-responsive g_img" data-toggle="modal" data-target="#image" src="../lib/media/imgs/uploads/gallery/<?php echo $i ?>.jpg" height="250px" width="100%" alt="Image" />
                        <?php //$name = $i ?>
                    </a>
                <!--image modal-->
                    <div id="image" class="modal fade" role="dialog">
                    <div class="modal-dialog">
                    <div class="modal-content">
                    <div class="modal-header">
                    <input type="submit" class="close bt" data-dismiss="modal" value="×" />
                    </div>
                    <div class="modal-body">
                    <img src="../lib/media/imgs/uploads/gallery/<?php echo $i ?>.jpg" class="mimg" alt="This image failed to load. Please reload the page." />
                    </div>
                    <div class="modal-footer">
                    <input type="submit" class="close bt" data-dismiss="modal" value="Close" />
                    </div>
                    </div>
                    </div>
                    </div>
                <!--// modal-->
                </div>
            </div>
        </div>
    </div>

<?php }?>

<?php

footer();
?>
</div>
<?php
close();
?>
</code>```

What my code does is it first counts the number of images in a folder and display's the image Thumbnails on the page. Here is the screenshot of the output

When clicked on the image, a modal box opens and shows that image like as shown in the image.

The Images in the folder have been named 1,2,3,4.... and so on.

My problem is that thumbnails are being displayed properly, but on clicking the image(whether first or any), the modal shows only the first image.

Thanks in advance.....

答:
Alternatively, You can dynamically change bootstrap modal body and use only single modal.</p>

```<code><?php
require "../_inc/master.inc.php";
require "../webConfig/web.config.php";
?>
<?php
doctype();
head_start("Gallery");
?>
<link rel="stylesheet" type="text/css" href="../lib/css/gallery.css" media="all" />
<?php
head_close();
?>
<?php
disp_head_start();
disp_head_close();
menu();
function countFolder($dir) {
 return (count(scandir($dir)) - 2);
}
$count=countFolder('../lib/media/imgs/uploads/gallery');
?>
<p> </p>
<div class="row" style="background-color:#7D37CE; padding:2%">
<?php for($i=1;$i<=$count;$i++){ ?>
<script>$(document).ready(function(){
    $('[data-toggle="tooltip"]').tooltip();
});</script>
    <div class="panel-group col-xs-12 col-sm-12 col-md-3 col-lg-3">
        <div class="panel panel-default">
            <div class="panel-body">
                <div class="thumb">
                    <a href="#" class="image-responsive" data-toggle="tooltip" title="Click to View">
                    <?php echo $i ?>
                        <img class="img image-responsive g_img" src="../lib/media/imgs/uploads/gallery/<?php echo $i ?>.jpg"  height="250px" width="100%" alt="Image" />
                        <?php //$name = $i ?>
                    </a>

                </div>
            </div>
        </div>
    </div>

<?php }?>

 <!--image modal-->
    <div id="imageModal" class="modal fade" role="dialog">
    <div class="modal-dialog">
    <div class="modal-content">
    <div class="modal-header">
    <input type="submit" class="close bt" data-dismiss="modal" value="×" />
    </div>
    <div class="modal-body">
    <img id="modalImg" src="../lib/media/imgs/uploads/gallery/<?php echo $i ?>.jpg" class="mimg" alt="This image failed to load. Please reload the page." />
    </div>
    <div class="modal-footer">
    <input type="submit" class="close bt" data-dismiss="modal" value="Close" />
    </div>
    </div>
    </div>
    </div>
<!--// modal-->

<script>
$(function(){
   //change the image on modal
   $('body').live('click','.img',function(){
      var activeSrc = $(this).attr('src');
      $("#modalImg").attr('src',activeSrc);
      $("#imageModal").modal('show');

   });
});
</script>

<?php

footer();
?>
</div>
<?php
close();
?>
</code>```

Body:
Im practicing some new things in Php and I have been trying to do this since past two days. I am counting the images in a given folder and displaying those images on the web-page.
Here's the code on my page.

<?php
require "../_inc/master.inc.php";
require "../webConfig/web.config.php";
?>
<?php
doctype();
head_start("Gallery");
?>
<link rel="stylesheet" type="text/css" href="../lib/css/gallery.css" media="all" />
<?php
head_close();
?>
<?php
disp_head_start();
disp_head_close();
menu();
function countFolder($dir) {
 return (count(scandir($dir)) - 2);
}
$count=countFolder('../lib/media/imgs/uploads/gallery');
?>

<?php for($i=1;$i<=$count;$i++){ ?>

                    <?php echo $i ?>
                        <img class="image-responsive g_img" data-toggle="modal" data-target="#image" src="../lib/media/imgs/uploads/gallery/<?php echo $i ?>.jpg" height="250px" width="100%" alt="Image" />
                        <?php //$name = $i ?>

                    <input type="submit" class="close bt" data-dismiss="modal" value="×" />

                    <img src="../lib/media/imgs/uploads/gallery/<?php echo $i ?>.jpg" class="mimg" alt="This image failed to load. Please reload the page." />

                    <input type="submit" class="close bt" data-dismiss="modal" value="Close" />

<?php }?>

<?php

footer();
?>

<?php
close();
?>

What my code does is it first counts the number of images in a folder and display's the image Thumbnails on the page. Here is the screenshot of the output

When clicked on the image, a modal box opens and shows that image like as shown in the image.

The Images in the folder have been named 1,2,3,4.... and so on.

My problem is that thumbnails are being displayed properly, but on clicking the image(whether first or any), the modal shows only the first image.

Thanks in advance.....

Body:
Alternatively, You can dynamically change bootstrap modal body and use only single modal.

<?php
require "../_inc/master.inc.php";
require "../webConfig/web.config.php";
?>
<?php
doctype();
head_start("Gallery");
?>
<link rel="stylesheet" type="text/css" href="../lib/css/gallery.css" media="all" />
<?php
head_close();
?>
<?php
disp_head_start();
disp_head_close();
menu();
function countFolder($dir) {
 return (count(scandir($dir)) - 2);
}
$count=countFolder('../lib/media/imgs/uploads/gallery');
?>
<p>&nbsp;</p>
<div class="row" style="background-color:#7D37CE; padding:2%">
<?php for($i=1;$i<=$count;$i++){ ?>
<script>$(document).ready(function(){
    $('[data-toggle="tooltip"]').tooltip();
});</script>
    <div class="panel-group col-xs-12 col-sm-12 col-md-3 col-lg-3">
        <div class="panel panel-default">
            <div class="panel-body">
                <div class="thumb">
                    <a href="#" class="image-responsive" data-toggle="tooltip" title="Click to View">
                    <?php echo $i ?>
                        <img class="img image-responsive g_img" src="../lib/media/imgs/uploads/gallery/<?php echo $i ?>.jpg"  height="250px" width="100%" alt="Image" />
                        <?php //$name = $i ?>
                    </a>

                </div>
            </div>
        </div>
    </div>

<?php }?>

 <!--image modal-->
    <div id="imageModal" class="modal fade" role="dialog">
    <div class="modal-dialog">
    <div class="modal-content">
    <div class="modal-header">
    <input type="submit" class="close bt" data-dismiss="modal" value="&times;" />
    </div>
    <div class="modal-body">
    <img id="modalImg" src="../lib/media/imgs/uploads/gallery/<?php echo $i ?>.jpg" class="mimg" alt="This image failed to load. Please reload the page." />
    </div>
    <div class="modal-footer">
    <input type="submit" class="close bt" data-dismiss="modal" value="Close" />
    </div>
    </div>
    </div>
    </div>
<!--// modal-->

<script>
$(function(){
   //change the image on modal
   $('body').live('click','.img',function(){
      var activeSrc = $(this).attr('src');
      $("#modalImg").attr('src',activeSrc);
      $("#imageModal").modal('show');

   });
});
</script>

<?php

footer();
?>
</div>
<?php
close();
?>


问:
How can I reload a page and display a query parameter with PHP + JS?
```<code>function myfun()
{
  var nm=12;
  window.location.href="bkd.php?uid="+nm;
}

<form name="frm" method="GET">
  <input type="text" value="ghf" onclick="myfun();"></input>
  <input type="hidden" value="" name="txtval" id="txtval"></input>
  <?php
    echo $_GET["uid"];
  ?>
</form>
</code>```

I have added JS and HTML on the same page. Wwhen I execute the code I am getting the value in PHP but it also displays

"Undefined index: uid"

答:
The first time you load the page $_GET['uid'] might not be set so you need to check it. You can use array_key_exists() for this.

I would also recommend putting the onclick action on a button rather than the text field.

```<code>function myfun()
{
    var nm=12;
    window.location.href="bkd.php?uid="+nm;
}

<form name="frm" method="GET">
<input type="text" value="ghf"></input>
<input type="hidden" value="" name="txtval" id="txtval"></input>
<input type="button" onclick="myfun();"></input>
<?php
if (array_key_exists("uid", $_GET)) {
    echo $_GET["uid"];
}

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

Body:
function myfun()
{
  var nm=12;
  window.location.href="bkd.php?uid="+nm;
}

<form name="frm" method="GET">
  <input type="text" value="ghf" onclick="myfun();"></input>
  <input type="hidden" value="" name="txtval" id="txtval"></input>
  <?php
    echo $_GET["uid"];
  ?>
</form>

I have added JS and HTML on the same page. Wwhen I execute the code I am getting the value in PHP but it also displays

"Undefined index: uid"

Body:
The first time you load the page $_GET['uid'] might not be set so you need to check it. You can use array_key_exists() for this.

I would also recommend putting the onclick action on a button rather than the text field.

function myfun()
{
    var nm=12;
    window.location.href="bkd.php?uid="+nm;
}

<form name="frm" method="GET">
<input type="text" value="ghf"></input>
<input type="hidden" value="" name="txtval" id="txtval"></input>
<input type="button" onclick="myfun();"></input>
<?php
if (array_key_exists("uid", $_GET)) {
    echo $_GET["uid"];
}

?>
</form>


问:
IntelliJ IDEA doesn't recognise angular 4 html tags
The plugin "AngularJS" is, as far as I know, for Angular < 2 and doesn't support Angular 4.

I have an entire project which builds with ng build and so on, however IDEA doesn't support the HTML tags such as "fxLayout"

It produces the message: "Attribute fxLayout is not allowed here"

How do I configure IntelliJ IDEA to allow Angular4 html tags?

答:
At first AngularJS plugin should be installed via Settings | Plugins | Install JetBrains plugin.

Then it should work automatically as long as you have angular.js in your web module.

AngularJS plugin requires JavaScript support that is not available in Community version


问:
How to add stuff into existing base class in C#?
Say I have a Father class to be inherited by Children classes, later I want to add more stuff into the Father class without modifying the original Father class, please teach me how could I do it.

Let me clarify my question. Any valuables and methods in Father will automatically accessible to all the Children classes, right? For example:

```<code>public class Father
{
    public int a;
    public int b;
    public int c()
    {
        return a+b;
    }
}

public class Child : Father
{
    private int d=a*b+c();
}
</code>```

Now I want to add a boolean e and a method f() to Father so my Child could access it directly, without adding those lines directly in Father or make a new class in between Father and Child. Is that possible? How could I do it?

答: You are looking for Extension Methods. Refer this post for more information.</p>

Body:
Say I have a Father class to be inherited by Children classes, later I want to add more stuff into the Father class without modifying the original Father class, please teach me how could I do it.

Let me clarify my question. Any valuables and methods in Father will automatically accessible to all the Children classes, right? For example:

public class Father
{
    public int a;
    public int b;
    public int c()
    {
        return a+b;
    }
}

public class Child : Father
{
    private int d=a*b+c();
}

Now I want to add a boolean e and a method f() to Father so my Child could access it directly, without adding those lines directly in Father or make a new class in between Father and Child. Is that possible? How could I do it?


问:
Paperclip S3 issue, no method match
Been trying to integrate S3 into my paperclip class.
Did so successfully on my local and a coworker's, but it's not working on production.

Here's my image class's paperclip code:

```<code>has_attached_file :image,
storage: :s3,
:path  => ":imageable_type/:imageable_id/:filename",
s3_credentials: {
      access_key_id: ENV["AWS_KEY"],
      secret_access_key: ENV["AWS_SECRET"],
      bucket: ENV["S3_BUCKET"]
},
s3_region: ENV["S3_REGION"]
</code>```

I'm getting the following error NoMethodError (undefined method 'match' for nil:NilClass):. A quick search shows it to be related to the s3_region not being mentioned.
It works in my development server and they the s3_region is included in my configurations.

I have defined the interpolations and environment variables. The environment variables are working in the rails console so that's not an issue I guess.

Any help would be appreciated

答:
what are you using to deploy to production?

For example, if you use Heroku, you need to mantain separately the env variables in your production server. You can do this via dashboard or the terminal

What are the other heroku environment variables?

https://devcenter.heroku.com/articles/config-vars

If you use AWS then read here

http://docs.aws.amazon.com/lambda/latest/dg/env_variables.html

For docker read here

https://docs.docker.com/compose/link-env-deprecated/

The env variables are defined in files like ~/.bash_profile or ~/.bashrc of every ubuntu server/container you are running

Read more about environment variable and how to configure them

Title: Paperclip S3 issue, no method match

Body:
Been trying to integrate S3 into my paperclip class.
Did so successfully on my local and a coworker's, but it's not working on production.

Here's my image class's paperclip code:

has_attached_file :image,
storage: :s3,
:path  => ":imageable_type/:imageable_id/:filename",
s3_credentials: {
      access_key_id: ENV["AWS_KEY"],
      secret_access_key: ENV["AWS_SECRET"],
      bucket: ENV["S3_BUCKET"]
},
s3_region: ENV["S3_REGION"]

I'm getting the following error NoMethodError (undefined method 'match' for nil:NilClass):. A quick search shows it to be related to the s3_region not being mentioned.
It works in my development server and they the s3_region is included in my configurations.

I have defined the interpolations and environment variables. The environment variables are working in the rails console so that's not an issue I guess.

Any help would be appreciated


问:
Generating Swagger JSON for Spring MVC: Springfox or Enunciate
If you want to generate Swagger UI documantation for your Spring MVC project, basically you have two options: Enunciate and SpringFox.

I dived into the subject but did not find a single opinion which one is better.

From my perspective Enunciate looks preferable since it is completely external to your project. No need to add a special Bean with configuration, no need to reference additional package with annotations and annotate your controllers with them. You simple use JavaDoc with custom tags and it does the job.

Are there any other considerations to take into account?

Thanks.

答:
After using both, I find the following key differences:

Enunciate evaluates annotations at build time, Springfox reads the Spring MVC configuration from the application context (build time vs. runtime)

Enunciate can use Javadocs as part of the documentation (build vs. runtime)

Springfox requires a test to generate a swagger configuration file that can be used for further code generation which does not fit nicely into a standard maven lifecycle. I prefer to use generate-sources / generate-resources for code / doc generation. With springfox I'm stuck with generating after running tests.

Springfox with springfox-swagger-ui is a really simple way to bolt a swagger UI on top of your existing Spring Boot / MVC application. OTOH, using something like ReDoc along with the generated Swagger Spec is nearly as simple but more flexible.

Springfox requires quite some configuration within your application, so your app will have a runtime dependency on Springfox.


问:
Importing library once for a python module
I want to structure imports of my python module/package, namely I have several *.py files in my module. All of them use:

```<code> import numpy as np
</code>```

in some pf them I use:

```<code>import pandas as pd
</code>```

can I set the global import for my python module, and say that it uses numpy as np in all the *.py files of the module.
I tried something in __init__.py but it didn't work as expected. Is it anyhow reasonable to make global imports?

答: No, you cannot do this, it is fundamentally opposed to the way Python works.</p>

Body:
I want to structure imports of my python module/package, namely I have several *.py files in my module. All of them use:

 import numpy as np

in some pf them I use:

import pandas as pd

can I set the global import for my python module, and say that it uses numpy as np in all the *.py files of the module.
I tried something in __init__.py but it didn't work as expected. Is it anyhow reasonable to make global imports?


问:
Getting last part of a string
I have a string in following format

```<code>String s= abc=1,cde=2,efg=3
</code>```

I only want to extract efg.

I tried by Spilting it but not getting 3 in last part for part[3]  it is showing arrays out of bounds exception.  I want to extract as I need to increment last part by 1 every time.

答: If split() results in an array of three elements, the index of the last one is 2 not 3. That could explain the exception. In an array indexes start at 0.</p>

Title: Getting last part of a string

Body:
I have a string in following format

String s= abc=1,cde=2,efg=3

I only want to extract efg.

I tried by Spilting it but not getting 3 in last part for part[3]  it is showing arrays out of bounds exception.  I want to extract as I need to increment last part by 1 every time.


问:
Non-static variable cannot be referenced from a static context?
i'm a n00b in Android Coding, today I wanna try to use the location service.

I set up a simple class and a simple main, just to have longitude and latitude.

But when I try to call the construction for retrive the long and latitude Android Studio pop out the error:

"Error:(33, 16) error: non-static variable latitude cannot be referenced from a static context"

This is my location Class

```<code>public class AppLocationManager implements LocationListener {

    private LocationManager locationManager;
    private String latitude;
    private String longitude;
    private Criteria criteria;
    private String provider;

    public AppLocationManager(Context context) {
        locationManager = (LocationManager) context
                .getSystemService(Context.LOCATION_SERVICE);
        criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        provider = locationManager.getBestProvider(criteria, true);
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,1,0,this);
        setMostRecentLocation(locationManager.getLastKnownLocation(provider));
    }

    private void setMostRecentLocation(Location lastKnownLocation) {

    }

    public String getLatitude() {
        return latitude;
    }

    public String getLongitude() {
        return longitude;
    }

    /*
     * (non-Javadoc)
     *
     * @see
     * android.location.LocationListener#onLocationChanged(android.location.
     * Location)
     */
    @Override
    public void onLocationChanged(Location location) {
        double lon = (double) (location.getLongitude());/// * 1E6);
        double lat = (double) (location.getLatitude());// * 1E6);

//      int lontitue = (int) lon;
//      int latitute = (int) lat;
        latitude = lat + "";
        longitude = lon + "";

    }

    /*
     * (non-Javadoc)
     *
     * @see
     * android.location.LocationListener#onProviderDisabled(java.lang.String)
     */
    @Override
    public void onProviderDisabled(String arg0) {
        // TODO Auto-generated method stub

    }

    /*
     * (non-Javadoc)
     *
     * @see
     * android.location.LocationListener#onProviderEnabled(java.lang.String)
     */
    @Override
    public void onProviderEnabled(String arg0) {
        // TODO Auto-generated method stub

    }

    /*
     * (non-Javadoc)
     *
     * @see android.location.LocationListener#onStatusChanged(java.lang.String,
     * int, android.os.Bundle)
     */
    @Override
    public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
        // TODO Auto-generated method stub

    }

}
</code>```

答:
To access non-static properties and method you will Object of that class. To learn about read this so thread :</p>

```<code> AppLocationManager appLocationManager=new AppLocationManager(context);
String latitude=appLocationManager.getLatitude();
String longitude=appLocationManager.getLongitude();
</code>```

Body:
i'm a n00b in Android Coding, today I wanna try to use the location service.

I set up a simple class and a simple main, just to have longitude and latitude.

But when I try to call the construction for retrive the long and latitude Android Studio pop out the error:

"Error:(33, 16) error: non-static variable latitude cannot be referenced from a static context"

This is my location Class

public class AppLocationManager implements LocationListener {

    private LocationManager locationManager;
    private String latitude;
    private String longitude;
    private Criteria criteria;
    private String provider;

    public AppLocationManager(Context context) {
        locationManager = (LocationManager) context
                .getSystemService(Context.LOCATION_SERVICE);
        criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        provider = locationManager.getBestProvider(criteria, true);
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,1,0,this);
        setMostRecentLocation(locationManager.getLastKnownLocation(provider));
    }

    private void setMostRecentLocation(Location lastKnownLocation) {

    }

    public String getLatitude() {
        return latitude;
    }

    public String getLongitude() {
        return longitude;
    }

    /*
     * (non-Javadoc)
     *
     * @see
     * android.location.LocationListener#onLocationChanged(android.location.
     * Location)
     */
    @Override
    public void onLocationChanged(Location location) {
        double lon = (double) (location.getLongitude());/// * 1E6);
        double lat = (double) (location.getLatitude());// * 1E6);

//      int lontitue = (int) lon;
//      int latitute = (int) lat;
        latitude = lat + "";
        longitude = lon + "";

    }

    /*
     * (non-Javadoc)
     *
     * @see
     * android.location.LocationListener#onProviderDisabled(java.lang.String)
     */
    @Override
    public void onProviderDisabled(String arg0) {
        // TODO Auto-generated method stub

    }

    /*
     * (non-Javadoc)
     *
     * @see
     * android.location.LocationListener#onProviderEnabled(java.lang.String)
     */
    @Override
    public void onProviderEnabled(String arg0) {
        // TODO Auto-generated method stub

    }

    /*
     * (non-Javadoc)
     *
     * @see android.location.LocationListener#onStatusChanged(java.lang.String,
     * int, android.os.Bundle)
     */
    @Override
    public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
        // TODO Auto-generated method stub

    }

}

Body:
To access non-static properties and method you will Object of that class. To learn about read this so thread :

 AppLocationManager appLocationManager=new AppLocationManager(context);
String latitude=appLocationManager.getLatitude();
String longitude=appLocationManager.getLongitude();


问:
http requests in stenciljs
How can I make http requests (GET / POST / PUT / DELETE) in StencilJS?

I tried using axios as follows: Did npm install axios --save and in the stencil component import axios from 'axios';. As soon as I call axios.get(...)I get the following error message:

[ ERROR ]  bundling: node_modules/axios/lib/adapters/http.js, line: 4

A module cannot import itself

L3:  var utils = require('./../utils');

L4:  var settle = require('./../core/settle');

L5:  var buildURL = require('./../helpers/buildURL');

I understand it might have to do with this issue: https://github.com/ionic-team/stencil/issues/98

However, any recommendations on how to get html requests work within a stencil component?

答:
We can use the fetch API. It is browser native and does therefore not need an import. StencilJS also has a polyfill for it, so it works everywhere.

Thanks to @insanicae for pointing me to it.

Example:

```<code>import { Component, State } from '@stencil/core';

@Component({
  tag: 'app-profile',
  styleUrl: 'app-profile.css'
})
export class AppProfile {
  @State() name: string;

  componentWillLoad() {
    fetch('https://api.github.com/users/ErvinLlojku')
      .then((response: Response) => response.json())
      .then(response => {
        this.name = response['name'];
      });
  }

  render() {
    return [
      <ion-header>
        <ion-toolbar color="primary">
          <ion-buttons slot="start">
            <ion-back-button defaultHref="/" />
          </ion-buttons>
          <ion-title>Profile: {this.name}</ion-title>
        </ion-toolbar>
      </ion-header>,

      <ion-content padding>
        <p>My name is {this.name}.</p>

      </ion-content>
    ];
  }
}
</code>```

Consult official docs of fetch for more. https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

Title: http requests in stenciljs

Body:
We can use the fetch API. It is browser native and does therefore not need an import. StencilJS also has a polyfill for it, so it works everywhere.

Thanks to @insanicae for pointing me to it.

Example:

import { Component, State } from '@stencil/core';

@Component({
  tag: 'app-profile',
  styleUrl: 'app-profile.css'
})
export class AppProfile {
  @State() name: string;

  componentWillLoad() {
    fetch('https://api.github.com/users/ErvinLlojku')
      .then((response: Response) => response.json())
      .then(response => {
        this.name = response['name'];
      });
  }

  render() {
    return [
      <ion-header>
        <ion-toolbar color="primary">
          <ion-buttons slot="start">
            <ion-back-button defaultHref="/" />
          </ion-buttons>
          <ion-title>Profile: {this.name}</ion-title>
        </ion-toolbar>
      </ion-header>,

      <ion-content padding>
        <p>My name is {this.name}.</p>

      </ion-content>
    ];
  }
}

Consult official docs of fetch for more. https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API


问:
Get this error : "Uncaught SyntaxError: Unexpected token <" when i call a function trough onclick
i get this error Uncaught SyntaxError: Unexpected token <

When i click on this :

```<code><a href="javascript:void(0);" onclick="newsGenerator({{link}})" class="blog-more">READ MORE</a>
</code>```

This function is refer to this :

```<code>function newsGenerator(contents) {
  var newsSelected = window.open("");
  newsSelected.document.write(contents);
}
</code>```

The {{link}} that you see on the "a href" come from here :

```<code>link: "<html><head><title>MyTitle</title></head><body>test</body></html>",
</code>```

That is built on my template like this :

```<code>template = template.replace("{{link}}", item.link);
</code>```

With the function :

```<code>var html = ""

assets.forEach(buildTemplate);
document.getElementById("list").innerHTML = html;

function buildTemplate(item) {
  var template = document.getElementById("template").innerHTML;
  template = template.replace("{{name}}", item.name);
  template = template.replace("{{date}}", item.date);
  template = template.replace("{{publisher}}", item.publisher);
  template = template.replace("{{link}}", item.link);
  template = template.replace("{{info}}", item.info);
  template = template.replace("{{img}}", item.img);
  html += template;
}
</code>```

答:
You need to wrap link with additional escaped single quotes. Something like this:

link: "\'<title>MyTitle</title>test\'"

Body:
i get this error Uncaught SyntaxError: Unexpected token <

When i click on this :

READ MORE

This function is refer to this :

function newsGenerator(contents) {
  var newsSelected = window.open("");
  newsSelected.document.write(contents);
}

The {{link}} that you see on the "a href" come from here :

link: "<title>MyTitle</title>test",

That is built on my template like this :

template = template.replace("{{link}}", item.link);

With the function :

var html = ""

assets.forEach(buildTemplate);
document.getElementById("list").innerHTML = html;

function buildTemplate(item) {
  var template = document.getElementById("template").innerHTML;
  template = template.replace("{{name}}", item.name);
  template = template.replace("{{date}}", item.date);
  template = template.replace("{{publisher}}", item.publisher);
  template = template.replace("{{link}}", item.link);
  template = template.replace("{{info}}", item.info);
  template = template.replace("{{img}}", item.img);
  html += template;
}

Body:
You need to wrap link with additional escaped single quotes. Something like this:

link: "\'<html><head><title>MyTitle</title></head><body>test</body></html>\'"


问:
Can I use a string as a name in Visual Basic to change an objects properties?
My Idea is not too hard. I have a button, a string called "progname", a TextBox and three Progressbars.

When I enter a number into the TextBox and press the button, the following code run's through.

```<code>Dim progname As String
    progname = "Progressbar" & TextBox1.Text
</code>```

Now I have a string called "progname" with relevant value.For an example "Progressbar2".

What I want to achieve is write something like:

```<code>progname.Value += 1
</code>```

Which can't be done, as "Value" is not a Member of "String". How can I do this?
Overall what I want, is to be able to select one of the three progressbars by typing one of the numbers 1-3 into the TextBox and then change that ones porperties.

答:
Yes you can.

A basic example is this, which searches your form for controls with the name matching your string. It then changes the type to a ProgressBar so you can access all the methods ..

```<code>Dim progbar As ProgressBar = CType(Me.Controls.Find(progName, False)(0), ProgressBar)
progbar.Value += 1
</code>```

Body:
My Idea is not too hard. I have a button, a string called "progname", a TextBox and three Progressbars.

When I enter a number into the TextBox and press the button, the following code run's through.

Dim progname As String
    progname = "Progressbar" & TextBox1.Text

Now I have a string called "progname" with relevant value.For an example "Progressbar2".

What I want to achieve is write something like:

progname.Value += 1

Which can't be done, as "Value" is not a Member of "String". How can I do this?
Overall what I want, is to be able to select one of the three progressbars by typing one of the numbers 1-3 into the TextBox and then change that ones porperties.

Body:
Yes you can.

A basic example is this, which searches your form for controls with the name matching your string. It then changes the type to a ProgressBar so you can access all the methods ..

Dim progbar As ProgressBar = CType(Me.Controls.Find(progName, False)(0), ProgressBar)
progbar.Value += 1


问:
MongoEngine - How to get files from GridFs using ObjectIDs
I have a specific collection of documents when each document holds a file (using GridFS).

I used the aggregate method to retrieve specific documents from that collection.

The aggregate method returned me a list of documents, when each document is represented as a dictionary.

So when I try to get the file from the dict, it returns me an ObjectID Object (and not a file object as returned in the regular querying method).

The question is, how can I get the file object using this ObjectID?

To rephrase it, Is there an easy way to get the actual file object as shown in the documentation using only the ObjectID (without getting involved in the merging of the file chunks in the GridFS)

Thanks.

答:
The solution for this is to use the GridFSProxy object directly and put the file Object ID as the parameter:</p>

```<code>import mongoengine
.
.
file_obj = mongoengine.GridFSProxy(FileID)
</code>```

Body:
The solution for this is to use the GridFSProxy object directly and put the file Object ID as the parameter:

import mongoengine
.
.
file_obj = mongoengine.GridFSProxy(FileID)


问:
how to put background image path from remote web site?
I need grab images from Imgur to My web page background image

```<code> <div style="background-image:url(); width:100%; height:100%;" class="zoom" >
</code>```

My image path is https://imgur.com/a/NbUpX

then how can I put this image to my background image url?

答:
You need to copy the right image path: https://i.imgur.com/QdMWFHZ.jpg

Go to https://imgur.com/a/NbUpX -> right click on image -> Copy image address

After this you need to put it into background-image:url('https://i.imgur.com/QdMWFHZ.jpg');

Here you can find some documentation for background-image using.

Remember to set an height for your div, because in your solution will be 100% of nothing so this can be a solution:

```

Body:
I need grab images from Imgur to My web page background image

My image path is https://imgur.com/a/NbUpX

then how can I put this image to my background image url?

Body:
You need to copy the right image path: https://i.imgur.com/QdMWFHZ.jpg

Go to https://imgur.com/a/NbUpX -> right click on image -> Copy image address

After this you need to put it into background-image:url('https://i.imgur.com/QdMWFHZ.jpg');

Here you can find some documentation for background-image using.

Remember to set an height for your div, because in your solution will be 100% of nothing so this can be a solution:

 <div style="background-image:url('https://i.imgur.com/QdMWFHZ.jpg'); width:100%; height:200px; background-size: contain; background-repeat: no-repeat;" class="zoom" >


问:
Comparing sound files if not completely identical
Is there any way to programatically compare two sound files to determine if they are identical, or nearly identical?  These are not mp3 files and do not have any ID3 or other meta data, but plain wav files.  Comparing the checksum values may not work as they may not be completely identical.</p>

答:
The process for comparing a set of sounds for similarities is called Content Based Audio Indexing, Retrieval, and Fingerprinting in computer science research.

One method of doing this is to:

1) Run several bits of signal processing on each audio file to extract features, such as pitch over time, frequency spectrum, autocorrelation, dynamic range, transients, etc.

2) Put all the features for each audio file into a multi-dimensional array and dump each multi-dimensional array into a database

3) Use optimization techniques (such as gradient descent) to find the best match for a given audio file in your database of multi-dimensional data.

The trick to making this work well is which features

There are several projects that do stuff like this, including MusicBrainz, and EchoNest.

Echonest has one of the simplest APIs I've seen in this space.  Very easy to get started.

P.S.  No I do not work for Echonest, nor do I know anyone who works there.

OwnerDisplayName: Tai Squared

OwnerDisplayName: Nick


问:
Passing a non-associative function to reduce
My program has this line:

```<code>Function<String, Integer> f = (String s) -> s.chars().reduce(0, (a, b) -> 2 * a + b);
</code>```

The function being passed to reduce is not associative. Reduce's documentation says that the function passed must be associative.

How can I rewrite this as an expression which doesn't break reduce's contract?

答:
You can convert this function to an associative function, as explained in this answer at the example of List.hashCode(). The difference lies only in the factor (2vs.31) and the start value (1vs.0).

It can be adapted to your task, which is especially easy when you have a random access input like a String:

```<code>Function<String, Integer> f =
    s -> IntStream.range(0, s.length()).map(i -> s.charAt(i)<<(s.length()-i-1)).sum();
</code>```

This would even run in parallel, but it’s unlikely that you ever encounter such humongous strings that a parallel evaluation provides a benefit. So what remains, is that most people might consider this solution less readable than a simple for loop…

Note that the above solution exhibits a different overflow behavior, i.e. if the String has more than 32 chars, due to the usage of the shift operator rather than multiplying with two.

The fix for this issue makes the solution even more efficient:

```<code>Function<String, Integer> f = s ->
    IntStream.range(Math.max(0, s.length()-32), s.length())
             .map(i -> s.charAt(i)<<(s.length()-i-1)).sum();
</code>```

If the string has more than 32 chars, it only processes the last 32 chars, which is already sufficient to calculate the same result as your original function.

Body:
My program has this line:

Function<String, Integer> f = (String s) -> s.chars().reduce(0, (a, b) -> 2 * a + b);

The function being passed to reduce is not associative. Reduce's documentation says that the function passed must be associative.

How can I rewrite this as an expression which doesn't break reduce's contract?

Body:
You can convert this function to an associative function, as explained in this answer at the example of List.hashCode(). The difference lies only in the factor (2vs.31) and the start value (1vs.0).

It can be adapted to your task, which is especially easy when you have a random access input like a String:

Function<String, Integer> f =
    s -> IntStream.range(0, s.length()).map(i -> s.charAt(i)<<(s.length()-i-1)).sum();

This would even run in parallel, but it’s unlikely that you ever encounter such humongous strings that a parallel evaluation provides a benefit. So what remains, is that most people might consider this solution less readable than a simple for loop…

Note that the above solution exhibits a different overflow behavior, i.e. if the String has more than 32 chars, due to the usage of the shift operator rather than multiplying with two.

The fix for this issue makes the solution even more efficient:

Function<String, Integer> f = s ->
    IntStream.range(Math.max(0, s.length()-32), s.length())
             .map(i -> s.charAt(i)<<(s.length()-i-1)).sum();

If the string has more than 32 chars, it only processes the last 32 chars, which is already sufficient to calculate the same result as your original function.


问:
How to send local notifications even when app is closed
How can I schedule a background task in my xamarin forms app to run, even if the app is closed. The background task has to check something every hour into a database. Based on the result from database I need to send a notification to the user, for instance the message notifications like in whatsapp.

Is this possible?

答:
You can schedule local notification by using LocalNotificationPlugin.

```<code>CrossLocalNotifications.Current.Show("title", "body", 101, DateTime.Now.AddSeconds(5));
</code>```

In case that you want to implement periodical background thread you need to write platform specific code. Follow this article here.

Body:
You can schedule local notification by using LocalNotificationPlugin.

CrossLocalNotifications.Current.Show("title", "body", 101, DateTime.Now.AddSeconds(5));

In case that you want to implement periodical background thread you need to write platform specific code. Follow this article here.


答:
This is the JavaScript you are generating.

```<code>newsGenerator(<html><head><title>MyTitle</title></head><body>test</body></html>)
</code>```

You can't have a < operator immediately after the ( that starts a function call.

It looks like you are trying to pass a string.

String literals must be delimited with quote marks or apostrophes.

(Remember that your HTML onclick attribute value is currently delimited with quote marks).

Title: Get this error : "Uncaught SyntaxError: Unexpected token <" when i call a function trough onclick

Body:
This is the JavaScript you are generating.

newsGenerator(<html><head><title>MyTitle</title></head><body>test</body></html>)

You can't have a < operator immediately after the ( that starts a function call.

It looks like you are trying to pass a string.

String literals must be delimited with quote marks or apostrophes.

(Remember that your HTML onclick attribute value is currently delimited with quote marks).


问:
Apply different class to table tr based on image title
```<code><table id='xhtmlgrid'>
<tbody>
<tr class='bgwhite'>
<td>
<table>
<tbody>
<tr>
<td>
<span>
<img src="./secured_off1.png">
</span>
</td>
<td>
<span>
<img src="./secured_off2.png">
</span>
</td>
<td>
<span>
<img src="./secured_off3.png" title="Locked">
</span>
</td>
<td>
<span>
<img src="./secured_off4.png">
</span>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</code>```

i have code like this,based on image title,i have multiple images in that tr, i want to change the tr class from bgwhite to bggreen,how can i do that,any help appreciated.

so far i'm using this code to find the image title

```<code>$("#xhtml_grid table > tbody > tr").each(function () {
        var hdnLock = $(this).find('td:eq(2)').find('img').attr('title');
        if (hdnLock == 'Locked') {
        }

    });
</code>```

for reference i'm adding the image of html

答:
```<code>$("#xhtml_grid table > tbody > tr").each(function () {
        var hdnLock = $(this).find('td:eq(2)').find('img').attr('title');
        if (hdnLock == 'Locked') {
            $(this).parents('tr').css('background-Color', '#ddff99');
        }
    });
</code>```

Thanks everyone for your support and suggestions, I found a way for my issue, here I'm posting my code that worked for me.

Body:
i have code like this,based on image title,i have multiple images in that tr, i want to change the tr class from bgwhite to bggreen,how can i do that,any help appreciated.

so far i'm using this code to find the image title

$("#xhtml_grid table > tbody > tr").each(function () {
        var hdnLock = $(this).find('td:eq(2)').find('img').attr('title');
        if (hdnLock == 'Locked') {
        }

    });

for reference i'm adding the image of html

Body:
$("#xhtml_grid table > tbody > tr").each(function () {
        var hdnLock = $(this).find('td:eq(2)').find('img').attr('title');
        if (hdnLock == 'Locked') {
            $(this).parents('tr').css('background-Color', '#ddff99');
        }
    });

Thanks everyone for your support and suggestions, I found a way for my issue, here I'm posting my code that worked for me.


问:
biztalk custom pipelinecomponent split messages in send
Is it possible to create a custom pipelinecomponent that splits a message in 2 messages, but in the send port?
I have seen that it is possible in the receive port using the disassembler interface, but can we use this in a send pipeline component?
Can someone give me an example to how to accomplish this?

Thx

答: Typically send ports are made for assembly and not dis-assembly, hence why the interface for a send port component has an assemble aspect to it.  Is sounds like this would be a good opportunity to split the message via filters and use multiple send ports to send out the 2 messages.  I've seen a few folks do this with writing the msgs to the file system, etc. but that screams bad practice.  Think of splitting the messages before the pipeline components are needed. </p>


问:
Make ajax POST and return JSON in Rails
I'm trying to make an AJAX POST request to one of my routes and return some JSON, but I'm running into an issue where the JSON is not being returned and a page is rendering instead like a GET request. Here is my code:

View

```<code><%= form_with url: users_add_skill_path, id: "skills-form", format: 'json' do |f| %>
  <%= f.text_field :skill, placeholder: "Submit your skill" %>
  <%= f.submit "Submit Skill" %>
<% end %>
</code>```

This becomes in HTML:

```<code><form id="skills-form" action="/users/add_skill" accept-charset="UTF-8" data-remote="true" method="post"><input name="utf8" type="hidden" value="✓"><input type="hidden" name="authenticity_token" value="token_hereadnfjahbsdkfjabsd">
    <label for="skill">Skill</label>
    <input placeholder="Submit your skill" type="text" name="skill">

    <input type="submit" name="commit" value="Submit Skill" data-disable-with="Submit Skill">

</form>
</code>```

Routes

```<code>devise_scope :user do
    post '/users/add_skill' => 'users/registrations#add_skill', :defaults =>
{ :format => :json }
end
</code>```

Controller

```<code>class Users::RegistrationsController < Devise::RegistrationsController

respond_to :html, except: [:add_skill]
respond_to :json, only: [:add_skill]

def add_skill
  @user = current_user
  @user.skills.push(params[:skill])

  respond_to do |format|
    if @user.save
      format.json { render json: @user.skills, status: :created, location: @user }
    else
      format.json { render json: @user.errors, status: :unprocessable_entity }
  end
end
</code>```

Javascript

```<code>const skillsForm = document.getElementById("skills-form");
skillsForm.addEventListener('ajax:success', function(res) {
    console.log("added skill");
});
</code>```

The 'skill' is being persisted to the database so I know that the request is being made correctly - and if I remove the :defaults => { :format => :json} from the routes, and change a few other things in the respond_to block (sorry I don't remember exactly what I had changed), the data is persisted the page does not change, so I'm pretty sure the Ajax request is working well, but I don't know how to get the response.

I saw a lot of questions using jQuery ajax() but I'm not using jQuery so I'm not sure what I should be doing. Any help would be greatly appreciated!

答: I actually realized that I had not included rails-ujs in my application.js, and so the request was being made as a GET request and not returning anything. Everything has been solved now, thanks for all your help.

Title: Make ajax POST and return JSON in Rails

Body:
I'm trying to make an AJAX POST request to one of my routes and return some JSON, but I'm running into an issue where the JSON is not being returned and a page is rendering instead like a GET request. Here is my code:

View

<%= form_with url: users_add_skill_path, id: "skills-form", format: 'json' do |f| %>
  <%= f.text_field :skill, placeholder: "Submit your skill" %>
  <%= f.submit "Submit Skill" %>
<% end %>

This becomes in HTML:

<form id="skills-form" action="/users/add_skill" accept-charset="UTF-8" data-remote="true" method="post"><input name="utf8" type="hidden" value="✓"><input type="hidden" name="authenticity_token" value="token_hereadnfjahbsdkfjabsd">
    Skill
    <input placeholder="Submit your skill" type="text" name="skill">

    <input type="submit" name="commit" value="Submit Skill" data-disable-with="Submit Skill">

</form>

Routes

devise_scope :user do
    post '/users/add_skill' => 'users/registrations#add_skill', :defaults =>
{ :format => :json }
end

Controller

class Users::RegistrationsController < Devise::RegistrationsController

respond_to :html, except: [:add_skill]
respond_to :json, only: [:add_skill]

def add_skill
  @user = current_user
  @user.skills.push(params[:skill])

  respond_to do |format|
    if @user.save
      format.json { render json: @user.skills, status: :created, location: @user }
    else
      format.json { render json: @user.errors, status: :unprocessable_entity }
  end
end

Javascript

const skillsForm = document.getElementById("skills-form");
skillsForm.addEventListener('ajax:success', function(res) {
    console.log("added skill");
});

The 'skill' is being persisted to the database so I know that the request is being made correctly - and if I remove the :defaults => { :format => :json} from the routes, and change a few other things in the respond_to block (sorry I don't remember exactly what I had changed), the data is persisted the page does not change, so I'm pretty sure the Ajax request is working well, but I don't know how to get the response.

I saw a lot of questions using jQuery ajax() but I'm not using jQuery so I'm not sure what I should be doing. Any help would be greatly appreciated!