问:
Adjust a UIButton's highlight glow radius size on touch
Background:

The UIButton control has a property “Shows Touch On Highlight” that can be set in the Storyboard. When this option is checked, and the UIButton is touched, a white glow is visible on the UIButton text.

Question:

How can I adjust the radius size of the UIButton glow when touched?

答:
Using code from my previous answer Need a Glowing Animation around a button I had been working, adding some customizations in order to solve your answer and here is the results, If you set animateAllways = false this custom button will behave as you need

```<code>//
//  GlowingButton.swift
//  NavigationButtonRotateQuestion
//
//  Created by Reinier Melian on 01/07/2017.
//  Copyright © 2017 Pruebas. All rights reserved.
//

import UIKit

@IBDesignable
class GlowingButton: UIButton {

    @IBInspectable var animDuration : CGFloat = 3
    @IBInspectable var cornerRadius : CGFloat = 5
    @IBInspectable var maxGlowSize : CGFloat = 10
    @IBInspectable var minGlowSize : CGFloat = 0
    @IBInspectable var glowColor : UIColor = nil ?? UIColor.red
    @IBInspectable var animateAllways : Bool = false
    fileprivate var animating : Bool = false

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        self.contentScaleFactor = UIScreen.main.scale
        self.layer.masksToBounds = false

        if(self.animateAllways){
            self.setupButtonForContinueAnimation()
            self.startAnimation()
        }else{
            self.setupButton()
        }
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

        if(!self.animateAllways){
        let layerAnimation = CABasicAnimation(keyPath: "shadowRadius")
        layerAnimation.fromValue = minGlowSize
        layerAnimation.toValue = maxGlowSize
        layerAnimation.isAdditive = false
        layerAnimation.duration = CFTimeInterval(animDuration/2)
        layerAnimation.fillMode = kCAFillModeForwards
        layerAnimation.isRemovedOnCompletion = false
        self.layer.add(layerAnimation, forKey: "addGlowing")
        }
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {

    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {

        if(!self.animateAllways){
        let layerAnimation = CABasicAnimation(keyPath: "shadowRadius")
        layerAnimation.fromValue = maxGlowSize
        layerAnimation.toValue = minGlowSize
        layerAnimation.isAdditive = false
        layerAnimation.duration = CFTimeInterval(animDuration/2)
        layerAnimation.fillMode = kCAFillModeForwards
        layerAnimation.isRemovedOnCompletion = false
        self.layer.add(layerAnimation, forKey: "removeGlowing")
        }
    }

    override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {

        if(!self.animateAllways){
        let layerAnimation = CABasicAnimation(keyPath: "shadowRadius")
        layerAnimation.fromValue = maxGlowSize
        layerAnimation.toValue = minGlowSize
        layerAnimation.isAdditive = false
        layerAnimation.duration = CFTimeInterval(animDuration/2)
        layerAnimation.fillMode = kCAFillModeForwards
        layerAnimation.isRemovedOnCompletion = false
        self.layer.add(layerAnimation, forKey: "removeGlowing")
        }
    }

    func setupButton()
    {
        self.layer.cornerRadius = cornerRadius
        self.layer.shadowPath = CGPath(roundedRect: self.bounds, cornerWidth: cornerRadius, cornerHeight: cornerRadius, transform: nil)
        self.layer.shadowRadius = 0
        self.layer.shadowColor = self.glowColor.cgColor
        self.layer.shadowOffset = CGSize.zero
        self.layer.shadowOpacity = 1
    }

    func setupButtonForContinueAnimation()
    {
        self.setupButton()
        self.layer.shadowRadius = maxGlowSize
    }

    func startAnimation()
    {
        let layerAnimation = CABasicAnimation(keyPath: "shadowRadius")
        layerAnimation.fromValue = maxGlowSize
        layerAnimation.toValue = minGlowSize
        layerAnimation.autoreverses = true
        layerAnimation.isAdditive = false
        layerAnimation.duration = CFTimeInterval(animDuration/2)
        layerAnimation.fillMode = kCAFillModeForwards
        layerAnimation.isRemovedOnCompletion = false
        layerAnimation.repeatCount = .infinity
        self.layer.add(layerAnimation, forKey: "glowingAnimation")

    }

}
</code>```

Hope this helps you

Body:
Using code from my previous answer Need a Glowing Animation around a button I had been working, adding some customizations in order to solve your answer and here is the results, If you set animateAllways = false this custom button will behave as you need

//
//  GlowingButton.swift
//  NavigationButtonRotateQuestion
//
//  Created by Reinier Melian on 01/07/2017.
//  Copyright © 2017 Pruebas. All rights reserved.
//

import UIKit

@IBDesignable
class GlowingButton: UIButton {

    @IBInspectable var animDuration : CGFloat = 3
    @IBInspectable var cornerRadius : CGFloat = 5
    @IBInspectable var maxGlowSize : CGFloat = 10
    @IBInspectable var minGlowSize : CGFloat = 0
    @IBInspectable var glowColor : UIColor = nil ?? UIColor.red
    @IBInspectable var animateAllways : Bool = false
    fileprivate var animating : Bool = false

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        self.contentScaleFactor = UIScreen.main.scale
        self.layer.masksToBounds = false

        if(self.animateAllways){
            self.setupButtonForContinueAnimation()
            self.startAnimation()
        }else{
            self.setupButton()
        }
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

        if(!self.animateAllways){
        let layerAnimation = CABasicAnimation(keyPath: "shadowRadius")
        layerAnimation.fromValue = minGlowSize
        layerAnimation.toValue = maxGlowSize
        layerAnimation.isAdditive = false
        layerAnimation.duration = CFTimeInterval(animDuration/2)
        layerAnimation.fillMode = kCAFillModeForwards
        layerAnimation.isRemovedOnCompletion = false
        self.layer.add(layerAnimation, forKey: "addGlowing")
        }
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {

    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {

        if(!self.animateAllways){
        let layerAnimation = CABasicAnimation(keyPath: "shadowRadius")
        layerAnimation.fromValue = maxGlowSize
        layerAnimation.toValue = minGlowSize
        layerAnimation.isAdditive = false
        layerAnimation.duration = CFTimeInterval(animDuration/2)
        layerAnimation.fillMode = kCAFillModeForwards
        layerAnimation.isRemovedOnCompletion = false
        self.layer.add(layerAnimation, forKey: "removeGlowing")
        }
    }

    override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {

        if(!self.animateAllways){
        let layerAnimation = CABasicAnimation(keyPath: "shadowRadius")
        layerAnimation.fromValue = maxGlowSize
        layerAnimation.toValue = minGlowSize
        layerAnimation.isAdditive = false
        layerAnimation.duration = CFTimeInterval(animDuration/2)
        layerAnimation.fillMode = kCAFillModeForwards
        layerAnimation.isRemovedOnCompletion = false
        self.layer.add(layerAnimation, forKey: "removeGlowing")
        }
    }

    func setupButton()
    {
        self.layer.cornerRadius = cornerRadius
        self.layer.shadowPath = CGPath(roundedRect: self.bounds, cornerWidth: cornerRadius, cornerHeight: cornerRadius, transform: nil)
        self.layer.shadowRadius = 0
        self.layer.shadowColor = self.glowColor.cgColor
        self.layer.shadowOffset = CGSize.zero
        self.layer.shadowOpacity = 1
    }

    func setupButtonForContinueAnimation()
    {
        self.setupButton()
        self.layer.shadowRadius = maxGlowSize
    }

    func startAnimation()
    {
        let layerAnimation = CABasicAnimation(keyPath: "shadowRadius")
        layerAnimation.fromValue = maxGlowSize
        layerAnimation.toValue = minGlowSize
        layerAnimation.autoreverses = true
        layerAnimation.isAdditive = false
        layerAnimation.duration = CFTimeInterval(animDuration/2)
        layerAnimation.fillMode = kCAFillModeForwards
        layerAnimation.isRemovedOnCompletion = false
        layerAnimation.repeatCount = .infinity
        self.layer.add(layerAnimation, forKey: "glowingAnimation")

    }

}

Hope this helps you


来源: stackexchange

问:
My ReSharper Gutter Icons for Unit Tests aren't showing
I've installed ReSharper 4.1 and Gallio 3.0.5, but I don't get the gutter icons for unit tests.  The tests seem to run fine in the Test Explorer, but I don't have icons next to the tests in code.  What could be causing this?  I previously had the MbUnit 2.4 ReSharper plugin installed, but it should be uninstalled now.</p>

答:
I did this to get them to show up again.  Maybe it was an overkill.

Uninstall ReSharper

Uninstall Gallio

Delete %appdata%\JetBrains folder

Install ReSharper

Start Visual Studio

Close Visual Studio

Install Gallio

Start Visual Studio

I think the key was deleting the %appdata%\JetBrains folder, because there could have been some old plugin files in there.

OwnerDisplayName: Lance Fisher

ContentLicense: CC BY-SA 2.5


问:
PHP: $_FILES - Why should i restrict specific file types?
Today I was surfing around in the internet about how to upload files onto my webserver with a php formular, and somehow everybody only allows specific file typs (and restricts all others). For somebody who wants to upload a picture, it is not nice to see that the webpage does not except that file type. What´s the problem with other file types (for example, directly from w3schools.com: only JPG, JPEG, PNG & GIF are allowed).

Thankx in advance,

VicStudio

答:
Suppose you want to upload Profile Picture and the user is trying to upload doc file.
and vice versa. Then File format limitation can be good for your form for your security.</p>

ContentLicense: CC BY-SA 3.0


问:
Database design for upvote/downvote in discussion forum?
I have a webite where there is a discussion forum. All questions have unique ID and answers have also unique ID with a foreign key referencing to question ID.

I have a user logged in. Using ajax, I can send the data(upvote/downvote,QID/AID, username).But there are few problems.

Whenever user logs back in, I want that when he opens a question, his previous upvotes and downvotes should be displayed.

A user cannot upvote/downvote a same question multiple times. Like if he upvoted a question to +1, he can only downvote it, not upvote it again.

Solution according to me. I am thinking of maintaining a table where username is the primary key and another attribute is a list of all the upvotes and downvotes he has done. Example:

```<code>(username, array)
(baqir, up_A001 up_A050 down_Q011 up_Q123)
</code>```

Whenever the user logs in, I take this array and make sure all the previous upvotes and downvotes of the user are as it is. If there is a new vote,I add it to the array.

Is there any better solution?

P.S. Not necceassary but my current database structure.

```<code>class Question(models.Model):
    QID = models.CharField( default="",max_length=1000, primary_key=True)
    title = models.CharField(max_length=30, default="")
    description = models.CharField(max_length=1055, default="")
    date = models.DateTimeField(default=datetime.now, blank=True)
    username = models.CharField(max_length=6, default="")
    votes = models.IntegerField(default=0)
    approved = models.BooleanField(default=False)

    def __str__(self):
        return self.title

class Answer(models.Model):
    AID = models.CharField(max_length=1000, default="", primary_key=True)
    QID = models.ForeignKey(Question,on_delete=None)
    description = models.CharField(max_length=1055, default="")
    date = models.DateTimeField(default=datetime.now, blank=True)
    username = models.CharField(max_length=6, default="")
    votes = models.IntegerField(default=0)
    approved = models.BooleanField(default=False)

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

I am using Django. And I basically want whatever stackoverflow has implemented for their voting of questions and answers.

答:
What array people, what are you talking about? You make another table per Q/A or per user, or a table where you just link two things, i.e. user and Q/A and its votes where keys can be repeated (no primary keys for this table).
Any array-like thing is loss of time and energy and it is against good DB design rules anyway.

Example of table keeping votes:

```<code>Table votes:
    UID | QID | AID | VOTE
</code>```

So you connect each user with each question or answer he/she voted. QID or AID can be NULL. When you come to some question, you just check whether table votes has anything to say about it and answers tied to it. If current QID and UID match and you get result, you just act accordingly.

This has a potential of being slow if you have a lot of users, but essentially will work nice.

Second solution is to tie your question/answer with another table keeping in only users that did something (up/down voted it). This will make DB look messier but when your user comes to given Q and its answers you just check whether this table has something to say aboutsaid visitor or not. If I am not clear enough I repeat, new table per each Q and/or A.

You can apply same technique in reverse, i.e. connect user to a table that holds all Q/A that the user voted, which will perhaps be the best way of keeping order and efficiency. So each time the user comes to any Q page you check if he/she have any history for that Q.

No arrays, no nonsense. Just one extra request to check status for currently viewed Q/A.

Body:
I have a webite where there is a discussion forum. All questions have unique ID and answers have also unique ID with a foreign key referencing to question ID.

I have a user logged in. Using ajax, I can send the data(upvote/downvote,QID/AID, username).But there are few problems.

Whenever user logs back in, I want that when he opens a question, his previous upvotes and downvotes should be displayed.

A user cannot upvote/downvote a same question multiple times. Like if he upvoted a question to +1, he can only downvote it, not upvote it again.

Solution according to me. I am thinking of maintaining a table where username is the primary key and another attribute is a list of all the upvotes and downvotes he has done. Example:

(username, array)
(baqir, up_A001 up_A050 down_Q011 up_Q123)

Whenever the user logs in, I take this array and make sure all the previous upvotes and downvotes of the user are as it is. If there is a new vote,I add it to the array.

Is there any better solution?

P.S. Not necceassary but my current database structure.

class Question(models.Model):
    QID = models.CharField( default="",max_length=1000, primary_key=True)
    title = models.CharField(max_length=30, default="")
    description = models.CharField(max_length=1055, default="")
    date = models.DateTimeField(default=datetime.now, blank=True)
    username = models.CharField(max_length=6, default="")
    votes = models.IntegerField(default=0)
    approved = models.BooleanField(default=False)

    def __str__(self):
        return self.title

class Answer(models.Model):
    AID = models.CharField(max_length=1000, default="", primary_key=True)
    QID = models.ForeignKey(Question,on_delete=None)
    description = models.CharField(max_length=1055, default="")
    date = models.DateTimeField(default=datetime.now, blank=True)
    username = models.CharField(max_length=6, default="")
    votes = models.IntegerField(default=0)
    approved = models.BooleanField(default=False)

    def __str__(self):
        return self.AID

I am using Django. And I basically want whatever stackoverflow has implemented for their voting of questions and answers.

Body:
What array people, what are you talking about? You make another table per Q/A or per user, or a table where you just link two things, i.e. user and Q/A and its votes where keys can be repeated (no primary keys for this table).
Any array-like thing is loss of time and energy and it is against good DB design rules anyway.

Example of table keeping votes:

Table votes:
    UID | QID | AID | VOTE

So you connect each user with each question or answer he/she voted. QID or AID can be NULL. When you come to some question, you just check whether table votes has anything to say about it and answers tied to it. If current QID and UID match and you get result, you just act accordingly.

This has a potential of being slow if you have a lot of users, but essentially will work nice.

Second solution is to tie your question/answer with another table keeping in only users that did something (up/down voted it). This will make DB look messier but when your user comes to given Q and its answers you just check whether this table has something to say aboutsaid visitor or not. If I am not clear enough I repeat, new table per each Q and/or A.

You can apply same technique in reverse, i.e. connect user to a table that holds all Q/A that the user voted, which will perhaps be the best way of keeping order and efficiency. So each time the user comes to any Q page you check if he/she have any history for that Q.

No arrays, no nonsense. Just one extra request to check status for currently viewed Q/A.


问:
How can I make substitutions only within the scope of certain LaTeX command arguments?
The below Latex is written in one line, but it could have been over several.

The problem is # in caption commands have to be escaped, so the question is how to do this only within captions?

Or does there exist a Perl/Ruby module that can find the closing } in such a complicated case?

\caption{\small{Et elliptisk område i planen er afgrænset af en ellipse som er niveaukurven $\mathcal{K }_{0}(f)$ for andengradspolynomiet $f(x,y) = 2\cdot x^{2} + 2\cdot y^{2} + 2\cdot x\cdot y -8\cdot x -10 \cdot y + 13$. Se opgave \ref{exercEllipseLevel}  og  eksempel \href{./20-Keglesnit.pdf#evncount.20.1}{ 20.1} i eNote \ref{tn20}.}} \label{figEllipseLevel}

答:
This can be done in Perl using two substitutions: the first to find the \caption elements, end the second to replace all hash symbols # within the elements found

It is convenient to use Regexp::Common::balanced to match the required balanced sequence of braces

The output of this program shows the string before and after editing. It's not the best test data as there is only a single instance of a hash symbol, and none outside the \caption element, but it does show that it works with the example data

```<code>use strict;
use warnings 'all';
use feature 'say';

use Regexp::Common 'balanced';

my $latex = <<'END';
\caption{\small{Et elliptisk område i planen er afgrænset af en ellipse som er niveaukurven $\mathcal{K }_{0}(f)$ for andengradspolynomiet $f(x,y) = 2\cdot x^{2} + 2\cdot y^{2} + 2\cdot x\cdot y -8\cdot x -10 \cdot y + 13$. Se opgave \ref{exercEllipseLevel}  og  eksempel \href{./20-Keglesnit.pdf#evncount.20.1}{ 20.1} i eNote \ref{tn20}.}} \label{figEllipseLevel}
END

say $latex;

$latex =~ s{ ( \\caption $RE{balanced}{-parens=>'{}'} ) }{
    $1 =~ s/#/\\#/gr;
}xeg;

say $latex;
</code>```

output

```<code>\caption{\small{Et elliptisk område i planen er afgrænset af en ellipse som er niveaukurven $\mathcal{K }_{0}(f)$ for andengradspolynomiet $f(x,y) = 2\cdot x^{2} + 2\cdot y^{2} + 2\cdot x\cdot y -8\cdot x -10 \cdot y + 13$. Se opgave \ref{exercEllipseLevel}  og  eksempel \href{./20-Keglesnit.pdf#evncount.20.1}{ 20.1} i eNote \ref{tn20}.}} \label{figEllipseLevel}

\caption{\small{Et elliptisk område i planen er afgrænset af en ellipse som er niveaukurven $\mathcal{K }_{0}(f)$ for andengradspolynomiet $f(x,y) = 2\cdot x^{2} + 2\cdot y^{2} + 2\cdot x\cdot y -8\cdot x -10 \cdot y + 13$. Se opgave \ref{exercEllipseLevel}  og  eksempel \href{./20-Keglesnit.pdf\#evncount.20.1}{ 20.1} i eNote \ref{tn20}.}} \label{figEllipseLevel}
</code>```

Body:
This can be done in Perl using two substitutions: the first to find the \caption elements, end the second to replace all hash symbols # within the elements found

It is convenient to use Regexp::Common::balanced to match the required balanced sequence of braces

The output of this program shows the string before and after editing. It's not the best test data as there is only a single instance of a hash symbol, and none outside the \caption element, but it does show that it works with the example data

use strict;
use warnings 'all';
use feature 'say';

use Regexp::Common 'balanced';

my $latex = <<'END';
\caption{\small{Et elliptisk område i planen er afgrænset af en ellipse som er niveaukurven $\mathcal{K }_{0}(f)$ for andengradspolynomiet $f(x,y) = 2\cdot x^{2} + 2\cdot y^{2} + 2\cdot x\cdot y -8\cdot x -10 \cdot y + 13$. Se opgave \ref{exercEllipseLevel}  og  eksempel \href{./20-Keglesnit.pdf#evncount.20.1}{ 20.1} i eNote \ref{tn20}.}} \label{figEllipseLevel}
END

say $latex;

$latex =~ s{ ( \\caption $RE{balanced}{-parens=>'{}'} ) }{
    $1 =~ s/#/\\#/gr;
}xeg;

say $latex;

output

\caption{\small{Et elliptisk område i planen er afgrænset af en ellipse som er niveaukurven $\mathcal{K }_{0}(f)$ for andengradspolynomiet $f(x,y) = 2\cdot x^{2} + 2\cdot y^{2} + 2\cdot x\cdot y -8\cdot x -10 \cdot y + 13$. Se opgave \ref{exercEllipseLevel}  og  eksempel \href{./20-Keglesnit.pdf#evncount.20.1}{ 20.1} i eNote \ref{tn20}.}} \label{figEllipseLevel}

\caption{\small{Et elliptisk område i planen er afgrænset af en ellipse som er niveaukurven $\mathcal{K }_{0}(f)$ for andengradspolynomiet $f(x,y) = 2\cdot x^{2} + 2\cdot y^{2} + 2\cdot x\cdot y -8\cdot x -10 \cdot y + 13$. Se opgave \ref{exercEllipseLevel}  og  eksempel \href{./20-Keglesnit.pdf\#evncount.20.1}{ 20.1} i eNote \ref{tn20}.}} \label{figEllipseLevel}


问:
how to convert list of psp objects to linnet
Using shapefiles vignette of spatstat, I was able to create a list of psp objects such that each feature of shapefile is a element in this psp list with the attributes as marks. To be specific, I used section 3.2.4 in the vignette as follows

```<code>> x<- readShapeSpatial("includes/roadshapefile.shp")
> out <- lapply(x@lines, function(z) { lapply(z@Lines, as.psp) })
> dat <- x@data
> for(i in seq(nrow(dat)))
+ out[[i]] <- lapply(out[[i]], "marks<-", value=dat[i, , drop=FALSE])
> roadlist <- do.call("c", out)
</code>```

Now i would like to create a whole network linnet from this list of psp objects. Is there a direct function or do I need to loop through each of the psp object to make each one a linnet and then somehow combine it to a complete network? as.linnet would not take this list of psp as a valid input because its class is a plain list.

I feel I am missing some small step. Could someone guide me please.

Once I have a linnet I want to create a point pattern using linfun and access these attributes (marks) to do a non-homogenous intensity of points.

Thanks

答: This is resolved it seems,  in latest version 1.37 I am able to preserve attributes. Thank you.</p>

Body:
Using shapefiles vignette of spatstat, I was able to create a list of psp objects such that each feature of shapefile is a element in this psp list with the attributes as marks. To be specific, I used section 3.2.4 in the vignette as follows

> x<- readShapeSpatial("includes/roadshapefile.shp")
> out <- lapply(x@lines, function(z) { lapply(z@Lines, as.psp) })
> dat <- x@data
> for(i in seq(nrow(dat)))
+ out[[i]] <- lapply(out[[i]], "marks<-", value=dat[i, , drop=FALSE])
> roadlist <- do.call("c", out)

Now i would like to create a whole network linnet from this list of psp objects. Is there a direct function or do I need to loop through each of the psp object to make each one a linnet and then somehow combine it to a complete network? as.linnet would not take this list of psp as a valid input because its class is a plain list.

I feel I am missing some small step. Could someone guide me please.

Once I have a linnet I want to create a point pattern using linfun and access these attributes (marks) to do a non-homogenous intensity of points.

Thanks


问:
Git: replace all commits authors without changing history
I want to replace all of the commits authors names and emails before pushing changes into another repository. I'll need to make more changes and push them as well with replaced authors. But at the same time i want to preserve original authors in first repo.

I have found a lot of similar questions, but all of them suggesting solutions that are rewriting history. This will make it problematic to make more commits later on.

答: I don't think that's even possible. A commit message hash includes the author along with other parameters, so there's no way you can keep the same commit and change its author. Rewriting history is the only option. You can, however, make changes only in the second repository and not the first one.</p>


问:
Deleteing an image in run time
I am trying to delete an image with the method:
(the file path is correct by 100%)

```<code>if(File.Exists(filePath))
   File.Delete(filePath);
</code>```

and I am getting the following exception :

An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll

Additional information: The process cannot access the file 'C:\visual_programming\yad2\yad2\bin\Debug\images\1.jpg' because it is being used by another process.

答:
It's telling you exactly what's wrong; another process is currently accessing the file.

See here for some suggestions as to how you can identify that process.

Title: Deleteing an image in run time

Body:
I am trying to delete an image with the method:
(the file path is correct by 100%)

if(File.Exists(filePath))
   File.Delete(filePath);

and I am getting the following exception :

An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll

Additional information: The process cannot access the file 'C:\visual_programming\yad2\yad2\bin\Debug\images\1.jpg' because it is being used by another process.


问:
How to represent len('') in a form different to the standard integer - Python
I'm making a hangman game in python. I want to display the amount of characters in the word, but instead of it producing the integer as the amount of characters, I would like it instead to be '_'(one for every character.)</p>

```<code>word = input('Please enter a word for your opponent:')
print(len(word) as '_') #Instead of an integer
</code>```

答:
Basically what Kenny Ostrom has suggested in the comment above, just answering it here so this question can be marked complete:

Strings in Python can be repeated n times by using the following syntax:

```<code>s = 'hello'
n = 3
p = s * n # p is equal to "hellohellohello"
</code>```

So what you're looking for is:

```<code>print(len(word) * '_')
</code>```

Body:
I'm making a hangman game in python. I want to display the amount of characters in the word, but instead of it producing the integer as the amount of characters, I would like it instead to be '_'(one for every character.)

word = input('Please enter a word for your opponent:')
print(len(word) as '_') #Instead of an integer

Body:
Basically what Kenny Ostrom has suggested in the comment above, just answering it here so this question can be marked complete:

Strings in Python can be repeated n times by using the following syntax:

s = 'hello'
n = 3
p = s * n # p is equal to "hellohellohello"

So what you're looking for is:

print(len(word) * '_')


问:
How to add an on click event in server side for an Image control in C#/ASP.NET
I have added an image from toolbox in VS2008, and noticed that there isn't an onclick event in server side.

How do I add one on?

答:
Use the ImageButton control:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.imagebutton.aspx</p>


答:
In the most simpliest form, this is probably what you're looking for.

```<code>print('_'*len('Foo'))
</code>```

What's happening in this instance? Well breaking it down step by step looks like this

```<code>'_'*len('Foo')
'_'*3
'___'
</code>```

There's some steps here, but the core concept is that some operators work on strings

You should take some time out of your day and learn about some operators and comparsions that can be used with strings. Here's the offical Documentation for python 3

https://docs.python.org/3/library/stdtypes.html#string-formatting

If that's too much of an eyesore, youtube is great too.

Title: How to represent len('') in a form different to the standard integer - Python

Body:
In the most simpliest form, this is probably what you're looking for.

print('_'*len('Foo'))

What's happening in this instance? Well breaking it down step by step looks like this

'_'*len('Foo')
'_'*3
'___'

There's some steps here, but the core concept is that some operators work on strings

You should take some time out of your day and learn about some operators and comparsions that can be used with strings. Here's the offical Documentation for python 3

https://docs.python.org/3/library/stdtypes.html#string-formatting

If that's too much of an eyesore, youtube is great too.


问:
Using && in if () operator
A friend of mine wrote me some code (and unfortunately he's un accessible right now) and I'm trying to understand it.

```<code>const people = [
  {name: 'morgan', group: 3},
  {name: 'courtney', group: 1},
  {name: 'brian', group: 1},
  {name: 'dog', group: 2}
]

const partitionedPeople = sortedPeople.reduce(
  (parts, person) => {
    const part = parts[0]

    if (part && person.group === part.group) {
      console.log('found part.group')
    } else {
      console.log('did not find part.group')
    }
    return parts;
  },
  []
);
</code>```

What I don't understand is if (part && person.group === part.group) {}

If I change it to if (person.group === part.group) {} I get an error.

Because through the first iteration, part is undefined (first item in an empty list) and I'm asking it to find .group of undefined, which makes sense.

However, when adding in (part && person.group === part.group) it works just fine.

What is part && person.group doing so that the function works?

答:
The && operator works like this:

if the first operand is truthy, it returns the second operand

if the first operand is falsy, it returns the first operand

Here, if part is undefined (which is falsy), the expression evaluates to undefined (because the first operand is returned). undefined is falsy, so the if body is not executed.

If part is defined and truthy, then and only then does && evaluate the second operand, which compares person.group with part.group and returns the result of the comparison.

In JavaScript, everything is truthy except for false, 0, "", null, undefined, and NaN.

Title: Using && in if () operator

Body:
A friend of mine wrote me some code (and unfortunately he's un accessible right now) and I'm trying to understand it.

const people = [
  {name: 'morgan', group: 3},
  {name: 'courtney', group: 1},
  {name: 'brian', group: 1},
  {name: 'dog', group: 2}
]

const partitionedPeople = sortedPeople.reduce(
  (parts, person) => {
    const part = parts[0]

    if (part && person.group === part.group) {
      console.log('found part.group')
    } else {
      console.log('did not find part.group')
    }
    return parts;
  },
  []
);

What I don't understand is if (part && person.group === part.group) {}

If I change it to if (person.group === part.group) {} I get an error.

Because through the first iteration, part is undefined (first item in an empty list) and I'm asking it to find .group of undefined, which makes sense.

However, when adding in (part && person.group === part.group) it works just fine.

What is part && person.group doing so that the function works?


问:
How to type memory instructions/opcodes properly for writing/modifying memory address while debugging kernel in GDB
Assume I have disassembly of 4 instructions starting from address 0x809fff00:

```<code>(gdb) disas /r 0x809fff00, +0x10
Dump of assembler code from 0x809fff00 to 0x809fff10:
   0x809fff00:  00 35 0c 00 sll a2,t4,0x14
   0x809fff04:  00 00 00 00 nop
   0x809fff08:  00 00 00 00 nop
   0x809fff0c:  00 00 00 00 nop
</code>```

and I want to modify the address 0x809fff00 with the opcodes 01 02 03 04 with little endian. How should i do it?

For instance in C, i would do like:
address 0x809fff00 = "\x04\x03\x02\01"

How to do it with set command in GDB?

答:
Since you already know the opcodes, it's pretty simple. You just use set to set whatever bytes you want at that address. The only trick is that you want to set 4 bytes at a time, so you'll need to instruct set to treat the address as a pointer to a DWORD. You can do this with a C-style cast:

```<code>set *(unsigned int*)0x809fff10 = 0x04030201
</code>```

(This, obviously, assumes that an unsigned int is a 4-byte type on your platform. If it isn't, change it as appropriate.)

Body:
Assume I have disassembly of 4 instructions starting from address 0x809fff00:

(gdb) disas /r 0x809fff00, +0x10
Dump of assembler code from 0x809fff00 to 0x809fff10:
   0x809fff00:  00 35 0c 00 sll a2,t4,0x14
   0x809fff04:  00 00 00 00 nop
   0x809fff08:  00 00 00 00 nop
   0x809fff0c:  00 00 00 00 nop

and I want to modify the address 0x809fff00 with the opcodes 01 02 03 04 with little endian. How should i do it?

For instance in C, i would do like:
address 0x809fff00 = "\x04\x03\x02\01"

How to do it with set command in GDB?

Body:
Since you already know the opcodes, it's pretty simple. You just use set to set whatever bytes you want at that address. The only trick is that you want to set 4 bytes at a time, so you'll need to instruct set to treat the address as a pointer to a DWORD. You can do this with a C-style cast:

set *(unsigned int*)0x809fff10 = 0x04030201

(This, obviously, assumes that an unsigned int is a 4-byte type on your platform. If it isn't, change it as appropriate.)


答:
meshgrid is creating nine points, not nine patches.

Look at the output. You've got one point at (2, 0.6), one at (2, 0.7), etc.

Title: Heatmap with matplotlib

Body:
I have a set of 3-tuples, each 3-tuple consists of (var1, var2, result).
Example of a list of 9 3-tuples:

<type 'list'>:
[(4, 0.7, 0.8530612244898, 0.016579670213527985),
 (4, 0.6, 0.8730158730157779, 0.011562402525241757),
 (6, 0.8, 0.8378684807257778, 0.018175985875060037),
 (4, 0.8, 0.8605442176870833, 0.015586992159716321),
 (2, 0.8, 0.8537414965986667, 0.0034013605443334316),
 (2, 0.7, 0.843537414966, 0.006802721088333352),
 (6, 0.6, 0.8480725623582223, 0.01696896774039503),
 (2, 0.6, 0.84693877551025, 0.010204081632749995),
 (6, 0.7, 0.8577097505669444, 0.019873637350220318)]

Now I'd like to create a heatmap out of this.
Var1 can be values [2,4,6] and Var2 can be [0.6, 0.7, 0.8]. There's a total of 9 results.

This is the code I use to plot a heatmap:

    # list of 3-tuples to 3 lists: x, y and weights
    # x (var1) = [2,4,6]
    # y (var2) = [0.6, 0.7, 0.8]
    # weights (res) = [....] (9 values)

    x, y = np.meshgrid(x, y)
    intensity = np.array(weights)

    plt.pcolormesh(x, y, intensity)
    plt.colorbar()  # need a colorbar to show the intensity scale
    plt.show()

Which leads to this graph:

What I find weird is that there's only 4 sections, but I expected there to be 9 (3x3). Can someone shed some light on what I did wrong here?


答:
The if statement can be rewritten like this:

```<code>if (part) {
  if (person.group === part.group) {
    //...
  }
}
</code>```

The part before the && checks to make sure part exists (not undefined, or null, or 0, etc.)

The part after the && checks for equality between person.group and part.group

Title: Using && in if () operator

Body:
The if statement can be rewritten like this:

if (part) {
  if (person.group === part.group) {
    //...
  }
}

The part before the && checks to make sure part exists (not undefined, or null, or 0, etc.)

The part after the && checks for equality between person.group and part.group


问:
Get the one value from array if it repeated again and again
```<code> <?php print_r($disease); ?>

  Array ( [0] => Array ( [disease_name] => magraines ) [1] => Array (
[disease_name] => magraines ) [2] => Array ( [disease_name] => magraines )
[3] => Array ( [disease_name] => magraines ) [4] => Array ( [disease_name]
=> magraines ) [5] => Array ( [disease_name] => brain cancer ) [6] => Array
( [disease_name] => brain cancer ) )
</code>```

I want to get one value magraines and brain cancer...not again and again

```<code><?php foreach ($disease as $get_disease)
{
  echo $get_disease['disease_name'];
}
?>
</code>```

Here is the text:

magrainesmagrainesmagrainesmagrainesmagraines

I want just get one magraines and braincancer.

答:
You can use php array_unique function

According to documentation

array_unique — Removes duplicate values from an array

Updated

According to documentation:

array_unique() is not intended to work on multi dimensional arrays.

But you can use the below code:

Code

```<code>$unique_disease = array_map("unserialize", array_unique(array_map("serialize", $disease)));

foreach ($unique_disease as $get_disease)
{
    echo $get_disease['disease_name'];
}
</code>```

Body:
 <?php print_r($disease); ?>

  Array ( [0] => Array ( [disease_name] => magraines ) [1] => Array (
[disease_name] => magraines ) [2] => Array ( [disease_name] => magraines )
[3] => Array ( [disease_name] => magraines ) [4] => Array ( [disease_name]
=> magraines ) [5] => Array ( [disease_name] => brain cancer ) [6] => Array
( [disease_name] => brain cancer ) )

I want to get one value magraines and brain cancer...not again and again

<?php foreach ($disease as $get_disease)
{
  echo $get_disease['disease_name'];
}
?>

Here is the text:

magrainesmagrainesmagrainesmagrainesmagraines

I want just get one magraines and braincancer.

Body:
You can use php array_unique function

According to documentation

array_unique — Removes duplicate values from an array

Updated

According to documentation:

array_unique() is not intended to work on multi dimensional arrays.

But you can use the below code:

Code

$unique_disease = array_map("unserialize", array_unique(array_map("serialize", $disease)));

foreach ($unique_disease as $get_disease)
{
    echo $get_disease['disease_name'];
}


问:
needed any running example for ng-sidebar implementation
I am new to angular2 i want to create sidebar using ng-sidebar ,
But the documentation they had given in readme.MD doc is quite confusing .I am not able to implement in my already build application.
If somebody have any implement experience in ng-sidebar please let me know how to call that component in my application?
I am very much confused about forRoot method.</p>

答:
Setup:

Run npm install --save ng-sidebar

In your app.module.ts, add following:

```<code>import { SidebarModule } from 'ng-sidebar';
</code>```

Add SidebarModule.forRoot() inside imports: [] in @NgModule, should look like something like below:

```<code>@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, SidebarModule.forRoot()],
  bootstrap: [AppComponent],
})
</code>```

In app.component.html add:

```<code><ng-sidebar-container>

  <ng-sidebar [(opened)]="_opened">
    <p>Sidebar contents</p>
  </ng-sidebar>

  <div ng-sidebar-content>
    <button (click)="_toggleSidebar()">Toggle sidebar</button>
  </div>

</ng-sidebar-container>
</code>```

In app.component.ts add:

```<code>private _opened: boolean = false;

private _toggleSidebar() {
  this._opened = !this._opened;
}
</code>```

Working demo

Code of working demo/Example of calling ng-sidebar in component

Body:
Setup:

Run npm install --save ng-sidebar

In your app.module.ts, add following:

import { SidebarModule } from 'ng-sidebar';

Add SidebarModule.forRoot() inside imports: [] in @NgModule, should look like something like below:

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, SidebarModule.forRoot()],
  bootstrap: [AppComponent],
})

In app.component.html add:

<ng-sidebar-container>

  <ng-sidebar [(opened)]="_opened">
    <p>Sidebar contents</p>
  </ng-sidebar>

  <div ng-sidebar-content>
    <button (click)="_toggleSidebar()">Toggle sidebar</button>
  </div>

</ng-sidebar-container>

In app.component.ts add:

private _opened: boolean = false;

private _toggleSidebar() {
  this._opened = !this._opened;
}

Working demo

Code of working demo/Example of calling ng-sidebar in component


问:
Android Studio: Gradle 'project_name' project refresh failed
I recently downloaded and installed the latest version of Android Studio Bundle 2.3.3. I get a Gradle 'project_name' project refresh failed error {Error:Could not download jsr305.jar (com.google.code.findbugs:jsr305:2.0.1): No cached version available for offline mode} every time I load up the IDE. I have a constant internet connection and I even have downloaded jsr305.jar and placed it in the gradle directory in the Android Studio program files, but the problem still persist. I have not yet started coding or developing the layout yet.Screenshot of the error</p>

答:
when you update android studio it update every thing but forget to update Gradle path you can change your gradle path from menu File > OtherSetting  search for gradle and from that window opened for you change it.select new gradle from myComputer > C: >Users > Current User > .Gradle >wrapper > dist > folder you must select version gradle-3.3-all and here you go every thing ok rebuild your project

do not forget to update   classpath 'com.android.tools.build:gradle:2.2.2' in project gradle file to   classpath 'com.android.tools.build:gradle:3.3.3'


问:
Adding post-install radio option to do nothing when installer has finished
Some time back I had this question. Some of that code is repeated here:

procedure RebuildRunList;
var
  RunEntries: array of TRunEntry;
  I: Integer;
begin
  { Save run list ... }
  SetArrayLength(RunEntries, WizardForm.RunList.Items.Count);
  for I := 0 to WizardForm.RunList.Items.Count - 1 do
  begin
    RunEntries[I].Caption := WizardForm.RunList.ItemCaption[I];
    RunEntries[I].Checked := WizardForm.RunList.Checked[I];
    RunEntries[I].Object := WizardForm.RunList.ItemObject[I];
  end;

  { ... clear it ... }
  WizardForm.RunList.Items.Clear;

  { ... and re-create }
  for I := 0 to GetArrayLength(RunEntries) - 1 do
  begin
    { the first two entries are radio buttons }
    if (I = 0) or (I = 1) then
    begin
      WizardForm.RunList.AddRadioButton(
        RunEntries[I].Caption, '', 0, RunEntries[I].Checked, True, RunEntries[I].Object);
    end
      else
    begin
      WizardForm.RunList.AddCheckBox(
        RunEntries[I].Caption, '', 0, RunEntries[I].Checked, True, True, True,
        RunEntries[I].Object);
    end;
  end;
end;

procedure CurPageChanged(CurPageID: Integer);
begin
  if CurPageID = wpFinished then
  begin
    { Only now is the RunList populated. }
    { Two entries are on 64-bit systems only. }
    if IsWin64 then RebuildRunList;
  end;
end;
```

I would like to know how I can make a enhancement to the radio choices. The drawback at the moment is that the user is forced to start one or the other application. I would like to add another radio option for simply closing down the installer. Ideally it would use a Inno Setup supplied message so that I do not have to ask for translations. (See this question).

Can this be done?

答:
The easiest solution is to add a no-op entry to the RunList:

```<code>[Run]
...
Filename: "{cmd}"; Parameters: "/C exit"; Description: "Exit setup";  \
    Flags: nowait postinstall runasoriginaluser unchecked skipifsilent runhidden; \
    Check: IsWin64
</code>```

And turn it to a radio button:

    { the first three entries are radio buttons }
    if (I = 0) or (I = 1) or (I = 2) then
```

Body:
Some time back I had this question. Some of that code is repeated here:

procedure RebuildRunList;
var
  RunEntries: array of TRunEntry;
  I: Integer;
begin
  { Save run list ... }
  SetArrayLength(RunEntries, WizardForm.RunList.Items.Count);
  for I := 0 to WizardForm.RunList.Items.Count - 1 do
  begin
    RunEntries[I].Caption := WizardForm.RunList.ItemCaption[I];
    RunEntries[I].Checked := WizardForm.RunList.Checked[I];
    RunEntries[I].Object := WizardForm.RunList.ItemObject[I];
  end;

  { ... clear it ... }
  WizardForm.RunList.Items.Clear;

  { ... and re-create }
  for I := 0 to GetArrayLength(RunEntries) - 1 do
  begin
    { the first two entries are radio buttons }
    if (I = 0) or (I = 1) then
    begin
      WizardForm.RunList.AddRadioButton(
        RunEntries[I].Caption, '', 0, RunEntries[I].Checked, True, RunEntries[I].Object);
    end
      else
    begin
      WizardForm.RunList.AddCheckBox(
        RunEntries[I].Caption, '', 0, RunEntries[I].Checked, True, True, True,
        RunEntries[I].Object);
    end;
  end;
end;

procedure CurPageChanged(CurPageID: Integer);
begin
  if CurPageID = wpFinished then
  begin
    { Only now is the RunList populated. }
    { Two entries are on 64-bit systems only. }
    if IsWin64 then RebuildRunList;
  end;
end;

I would like to know how I can make a enhancement to the radio choices. The drawback at the moment is that the user is forced to start one or the other application. I would like to add another radio option for simply closing down the installer. Ideally it would use a Inno Setup supplied message so that I do not have to ask for translations. (See this question).

Can this be done?

Body:
The easiest solution is to add a no-op entry to the RunList:

[Run]
...
Filename: "{cmd}"; Parameters: "/C exit"; Description: "Exit setup";  \
    Flags: nowait postinstall runasoriginaluser unchecked skipifsilent runhidden; \
    Check: IsWin64

And turn it to a radio button:

    { the first three entries are radio buttons }
    if (I = 0) or (I = 1) or (I = 2) then


问:
How to use elisp to let user pick a date from calendar?
Just learn to write an interactive function in elisp:

If called with prefix, open calendar and get the date which is picked by user.

I try to do something like this:

```<code>(calendar)
(org-get-date-from-calendar)
</code>```

It return today straight away instead of let user to pick a date.

答:
I tried

```<code>(org-read-date)
</code>```

And that worked for me

Body:
Just learn to write an interactive function in elisp:

If called with prefix, open calendar and get the date which is picked by user.

I try to do something like this:

(calendar)
(org-get-date-from-calendar)

It return today straight away instead of let user to pick a date.

Body:
I tried

(org-read-date)

And that worked for me


问:
How to get reference of custom ids in values/ids.xml
I'm using anko in recyclerView adapter for creating viewholder's view. I have done this successfully but don't know how to refer it using kotlin synthetic by view id (I want to get it without findViewById)

value/ids.xml

```<code><resources>
<item name="txv1" type="id"/>
<item name="txv2" type="id"/>
</code>```

My Anko getView Codes:

```<code>private fun getView(context: Context): View{
        return with(context){
            linearLayout {
                lparams(width = matchParent, height = wrapContent)
                padding = dip(10)
                orientation = android.widget.LinearLayout.HORIZONTAL

                //Task Number
                textView {
                    id = R.id.txv1
                    text = "TextView 22"
                    textSize = 16f
                    typeface = Typeface.MONOSPACE
                    padding =dip(5)
                }.lparams(){
                    weight = 1f
                }

                //Task Name
                textView {
                    id = R.id.txv2
                    text= "TextView 33"
                    textSize = 16f
                    typeface = android.graphics.Typeface.DEFAULT_BOLD
                    padding =dip(5)
                }
            }
        }
    }
</code>```

I'm assigning custom ids from ids.xml but how to get it without findViewById

Thanks

答:
After researching a lot I came to conclusion that direct reference by id of anko created views are not possible right now.

The workaround is to use -

```<code>val txv1 = findViewById(R.id.txv1) as TextView
</code>```

OR

Declare a variable to hold reference of view created inside anko method.

Code is given below -

```<code>    var txv1: TextView? = null

    private fun getView(context: Context): View{
        return with(context){
            linearLayout {
                txv1 = textView {
                    text = "TextView"
                }
            }
        }
    }
</code>```

Hope this will help others. Thanks

Body:
I'm using anko in recyclerView adapter for creating viewholder's view. I have done this successfully but don't know how to refer it using kotlin synthetic by view id (I want to get it without findViewById)

value/ids.xml

<resources>
<item name="txv1" type="id"/>
<item name="txv2" type="id"/>

My Anko getView Codes:

private fun getView(context: Context): View{
        return with(context){
            linearLayout {
                lparams(width = matchParent, height = wrapContent)
                padding = dip(10)
                orientation = android.widget.LinearLayout.HORIZONTAL

                //Task Number
                textView {
                    id = R.id.txv1
                    text = "TextView 22"
                    textSize = 16f
                    typeface = Typeface.MONOSPACE
                    padding =dip(5)
                }.lparams(){
                    weight = 1f
                }

                //Task Name
                textView {
                    id = R.id.txv2
                    text= "TextView 33"
                    textSize = 16f
                    typeface = android.graphics.Typeface.DEFAULT_BOLD
                    padding =dip(5)
                }
            }
        }
    }

I'm assigning custom ids from ids.xml but how to get it without findViewById

Thanks

Body:
After researching a lot I came to conclusion that direct reference by id of anko created views are not possible right now.

The workaround is to use -

val txv1 = findViewById(R.id.txv1) as TextView

OR

Declare a variable to hold reference of view created inside anko method.

Code is given below -

    var txv1: TextView? = null

    private fun getView(context: Context): View{
        return with(context){
            linearLayout {
                txv1 = textView {
                    text = "TextView"
                }
            }
        }
    }

Hope this will help others. Thanks


答:
If the value of left expression of && is falsy, it returns the value of left expression, otherwise it returns the value of right expression.

So, when part is undefined, (part && person.group === part.group) returns part (which is undefined) immediately.

Title: Using && in if () operator


问:
returning Completable after realm async transaction execution
i'm using realm 3.4 and rx java2. What i want to accomplish is to return a Completable after inserting data into realm.

```<code>public Completable insertSamplesRx(final List<Sample> sampleList) {
    realm.executeTransactionAsync(new Realm.Transaction() {
        @Override
        public void execute(Realm realm) {
            for(Sample s : sampleList) {
                realm.insertOrUpdate(sampleList);
            }
        }
    }, new Realm.Transaction.OnSuccess() {
        @Override
        public void onSuccess() {
            Completable.complete();
        }
    }, new Realm.Transaction.OnError() {
        @Override
        public void onError(Throwable error) {
            Completable.error(error);
        }
    });
}
</code>```

This code obviously doesn't compile because a return is missing. How i can return the completable result here?

Thanks

答:
It is important to remember that Rx objects do not generally do anything until subscribe is called.

You should look into Completable.create to see how to convert an "action" into a Completable that can complete or cause an error.

Body:
i'm using realm 3.4 and rx java2. What i want to accomplish is to return a Completable after inserting data into realm.

public Completable insertSamplesRx(final List<Sample> sampleList) {
    realm.executeTransactionAsync(new Realm.Transaction() {
        @Override
        public void execute(Realm realm) {
            for(Sample s : sampleList) {
                realm.insertOrUpdate(sampleList);
            }
        }
    }, new Realm.Transaction.OnSuccess() {
        @Override
        public void onSuccess() {
            Completable.complete();
        }
    }, new Realm.Transaction.OnError() {
        @Override
        public void onError(Throwable error) {
            Completable.error(error);
        }
    });
}

This code obviously doesn't compile because a return is missing. How i can return the completable result here?

Thanks


问:
can't open new activity when click on cardview but It shows toast only
I am using cardview for displaying items in gridview. I want to open a new activity but as per my code its shows the toast about the item position. I am not getting where i am making mistake so please help me. Help would be appreciate, thanks in advance.

DataModel.class

```<code>public class DataModel {

    public String text;
    public int drawable;
    public String color;

    public DataModel(String t, int d, String c )
    {
        text=t;
        drawable=d;
        color=c;
    }
}
</code>```

RecyclerViewAdapter.class

```<code>public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {

    ArrayList<DataModel> mValues;
    Context mContext;
    protected ItemListener mListener;

    public RecyclerViewAdapter(Context context, ArrayList<DataModel> values, ItemListener itemListener) {

        mValues = values;
        mContext = context;
        mListener=itemListener;
    }

    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        public TextView textView;
        public ImageView imageView;
        public RelativeLayout relativeLayout;
        DataModel item;

        public ViewHolder(View v) {

            super(v);

            v.setOnClickListener(this);
            textView = (TextView) v.findViewById(R.id.textView);
            imageView = (ImageView) v.findViewById(R.id.imageView);
            relativeLayout = (RelativeLayout) v.findViewById(R.id.relativeLayout);

        }

        public void setData(DataModel item) {
            this.item = item;

            textView.setText(item.text);
            imageView.setImageResource(item.drawable);
            relativeLayout.setBackgroundColor(Color.parseColor(item.color));

        }

        @Override
        public void onClick(View view) {
            if (mListener != null) {
                mListener.onItemClick(item);
            }
        }
    }

    @Override
    public RecyclerViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(mContext).inflate(R.layout.recycler_view_item, parent, false);

        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder Vholder, int position) {
        Vholder.setData(mValues.get(position));

    }

    @Override
    public int getItemCount() {

        return mValues.size();
    }

    public interface ItemListener {
        void onItemClick(DataModel item);
    }

}
</code>```

MainActivity class

```<code>public class MainActivity extends AppCompatActivity implements RecyclerViewAdapter.ItemListener {

        RecyclerView recyclerView;
        ArrayList<DataModel> arrayList;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
            arrayList = new ArrayList<>();
            arrayList.add(new DataModel("Item 1", R.drawable.downtoearth, "#FFFFFF"));
            arrayList.add(new DataModel("Item 2", R.drawable.beer, "#3E51B1"));
            arrayList.add(new DataModel("Item 3", R.drawable.ferrari, "#673BB7"));
            arrayList.add(new DataModel("Item 4", R.drawable.jetpack_joyride, "#4BAA50"));
            arrayList.add(new DataModel("Item 5", R.drawable.three_d, "#F94336"));
            arrayList.add(new DataModel("Item 6", R.drawable.terraria, "#0A9B88"));

            RecyclerViewAdapter adapter = new RecyclerViewAdapter(this, arrayList, this);
            recyclerView.setAdapter(adapter);

            /**
             AutoFitGridLayoutManager that auto fits the cells by the column width defined.
             **/

            AutoFitGridLayoutManager layoutManager = new AutoFitGridLayoutManager(this, 300);
            recyclerView.setLayoutManager(layoutManager);

            /**
             Simple GridLayoutManager that spans two columns
             **/
            GridLayoutManager manager = new GridLayoutManager(this, 2, GridLayoutManager.VERTICAL, false);
            recyclerView.setLayoutManager(manager);
        }

        @Override
        public void onItemClick(DataModel item) {

        //here toast is
        Toast.makeText(getApplicationContext(), item.text + " is clicked",
             Toast.LENGTH_SHORT).show();

        }
    }
</code>```

after edit i am getting error in the intent.putExtra command

@Override
    public void onItemClick(DataModel item) {

```<code>    Intent intent = new Intent(MainActivity.this, Yojana.class);
    intent.putExtra("dataitem", item);
    startActivity(intent);

}
</code>```

Yojana.class

public class Yojana extends AppCompatActivity {

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_yojana);
    getIntent().getParcelableExtra("dataitem");

}
</code>```

logcaterror :

```<code>    Error:(56, 15) error: no suitable method found for
    putExtra(String,DataModel)
    method Intent.putExtra(String,boolean) is not applicable
    (argument mismatch; DataModel cannot be converted to boolean)
    method Intent.putExtra(String,byte) is not applicable
    (argument mismatch; DataModel cannot be converted to byte)
    method Intent.putExtra(String,char) is not applicable
    (argument mismatch; DataModel cannot be converted to char)
    method Intent.putExtra(String,short) is not applicable
    (argument mismatch; DataModel cannot be converted to short)
    method Intent.putExtra(String,int) is not applicable
    (argument mismatch; DataModel cannot be converted to int)
    method Intent.putExtra(String,long) is not applicable
    (argument mismatch; DataModel cannot be converted to long)
    method Intent.putExtra(String,float) is not applicable
    (argument mismatch; DataModel cannot be converted to float)
    method Intent.putExtra(String,double) is not applicable
    (argument mismatch; DataModel cannot be converted to double)
    method Intent.putExtra(String,String) is not applicable
    (argument mismatch; DataModel cannot be converted to String)
    method Intent.putExtra(String,CharSequence) is not applicable
    (argument mismatch; DataModel cannot be converted to CharSequence)
    method Intent.putExtra(String,Parcelable) is not applicable
    (argument mismatch; DataModel cannot be converted to Parcelable)
    method Intent.putExtra(String,Parcelable[]) is not applicable
    (argument mismatch; DataModel cannot be converted to Parcelable[])
    method Intent.putExtra(String,Serializable) is not applicable
   (argument mismatch; DataModel cannot be converted to Serializable)
   method Intent.putExtra(String,boolean[]) is not applicable
   (argument mismatch; DataModel cannot be converted to boolean[])
   method Intent.putExtra(String,double[]) is not applicable
   (argument mismatch; DataModel cannot be converted to double[])
   method Intent.putExtra(String,String[]) is not applicable
   (argument mismatch; DataModel cannot be converted to String[])
   method Intent.putExtra(String,CharSequence[]) is not applicable
   (argument mismatch; DataModel cannot be converted to CharSequence[])
   method Intent.putExtra(String,Bundle) is not applicable
   (argument mismatch; DataModel cannot be converted to Bundle)
</code>```

答:
this opens a new activity .but how to open different activities by clicking on different cardviews ?

@Override
    public void onItemClick(DataModel item) {

```<code>        Intent intent = new Intent(MainActivity.this, Yojana.class);
        intent.putExtra("dataitem", String.valueOf(item));
        startActivity(intent);

}
</code>```

Yojana.class

public class Yojana extends AppCompatActivity {

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_yojana);
     getIntent().getExtras().getString("dataitem");

}
</code>```

Body:
I am using cardview for displaying items in gridview. I want to open a new activity but as per my code its shows the toast about the item position. I am not getting where i am making mistake so please help me. Help would be appreciate, thanks in advance.

DataModel.class

public class DataModel {

    public String text;
    public int drawable;
    public String color;

    public DataModel(String t, int d, String c )
    {
        text=t;
        drawable=d;
        color=c;
    }
}

RecyclerViewAdapter.class

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {

    ArrayList<DataModel> mValues;
    Context mContext;
    protected ItemListener mListener;

    public RecyclerViewAdapter(Context context, ArrayList<DataModel> values, ItemListener itemListener) {

        mValues = values;
        mContext = context;
        mListener=itemListener;
    }

    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        public TextView textView;
        public ImageView imageView;
        public RelativeLayout relativeLayout;
        DataModel item;

        public ViewHolder(View v) {

            super(v);

            v.setOnClickListener(this);
            textView = (TextView) v.findViewById(R.id.textView);
            imageView = (ImageView) v.findViewById(R.id.imageView);
            relativeLayout = (RelativeLayout) v.findViewById(R.id.relativeLayout);

        }

        public void setData(DataModel item) {
            this.item = item;

            textView.setText(item.text);
            imageView.setImageResource(item.drawable);
            relativeLayout.setBackgroundColor(Color.parseColor(item.color));

        }

        @Override
        public void onClick(View view) {
            if (mListener != null) {
                mListener.onItemClick(item);
            }
        }
    }

    @Override
    public RecyclerViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(mContext).inflate(R.layout.recycler_view_item, parent, false);

        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder Vholder, int position) {
        Vholder.setData(mValues.get(position));

    }

    @Override
    public int getItemCount() {

        return mValues.size();
    }

    public interface ItemListener {
        void onItemClick(DataModel item);
    }

}

MainActivity class

public class MainActivity extends AppCompatActivity implements RecyclerViewAdapter.ItemListener {

        RecyclerView recyclerView;
        ArrayList<DataModel> arrayList;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
            arrayList = new ArrayList<>();
            arrayList.add(new DataModel("Item 1", R.drawable.downtoearth, "#FFFFFF"));
            arrayList.add(new DataModel("Item 2", R.drawable.beer, "#3E51B1"));
            arrayList.add(new DataModel("Item 3", R.drawable.ferrari, "#673BB7"));
            arrayList.add(new DataModel("Item 4", R.drawable.jetpack_joyride, "#4BAA50"));
            arrayList.add(new DataModel("Item 5", R.drawable.three_d, "#F94336"));
            arrayList.add(new DataModel("Item 6", R.drawable.terraria, "#0A9B88"));

            RecyclerViewAdapter adapter = new RecyclerViewAdapter(this, arrayList, this);
            recyclerView.setAdapter(adapter);

            /**
             AutoFitGridLayoutManager that auto fits the cells by the column width defined.
             **/

            AutoFitGridLayoutManager layoutManager = new AutoFitGridLayoutManager(this, 300);
            recyclerView.setLayoutManager(layoutManager);

            /**
             Simple GridLayoutManager that spans two columns
             **/
            GridLayoutManager manager = new GridLayoutManager(this, 2, GridLayoutManager.VERTICAL, false);
            recyclerView.setLayoutManager(manager);
        }

        @Override
        public void onItemClick(DataModel item) {

        //here toast is
        Toast.makeText(getApplicationContext(), item.text + " is clicked",
             Toast.LENGTH_SHORT).show();

        }
    }

after edit i am getting error in the intent.putExtra command

@Override
    public void onItemClick(DataModel item) {

    Intent intent = new Intent(MainActivity.this, Yojana.class);
    intent.putExtra("dataitem", item);
    startActivity(intent);

}

Yojana.class

public class Yojana extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_yojana);
    getIntent().getParcelableExtra("dataitem");

}

logcaterror :

    Error:(56, 15) error: no suitable method found for
    putExtra(String,DataModel)
    method Intent.putExtra(String,boolean) is not applicable
    (argument mismatch; DataModel cannot be converted to boolean)
    method Intent.putExtra(String,byte) is not applicable
    (argument mismatch; DataModel cannot be converted to byte)
    method Intent.putExtra(String,char) is not applicable
    (argument mismatch; DataModel cannot be converted to char)
    method Intent.putExtra(String,short) is not applicable
    (argument mismatch; DataModel cannot be converted to short)
    method Intent.putExtra(String,int) is not applicable
    (argument mismatch; DataModel cannot be converted to int)
    method Intent.putExtra(String,long) is not applicable
    (argument mismatch; DataModel cannot be converted to long)
    method Intent.putExtra(String,float) is not applicable
    (argument mismatch; DataModel cannot be converted to float)
    method Intent.putExtra(String,double) is not applicable
    (argument mismatch; DataModel cannot be converted to double)
    method Intent.putExtra(String,String) is not applicable
    (argument mismatch; DataModel cannot be converted to String)
    method Intent.putExtra(String,CharSequence) is not applicable
    (argument mismatch; DataModel cannot be converted to CharSequence)
    method Intent.putExtra(String,Parcelable) is not applicable
    (argument mismatch; DataModel cannot be converted to Parcelable)
    method Intent.putExtra(String,Parcelable[]) is not applicable
    (argument mismatch; DataModel cannot be converted to Parcelable[])
    method Intent.putExtra(String,Serializable) is not applicable
   (argument mismatch; DataModel cannot be converted to Serializable)
   method Intent.putExtra(String,boolean[]) is not applicable
   (argument mismatch; DataModel cannot be converted to boolean[])
   method Intent.putExtra(String,double[]) is not applicable
   (argument mismatch; DataModel cannot be converted to double[])
   method Intent.putExtra(String,String[]) is not applicable
   (argument mismatch; DataModel cannot be converted to String[])
   method Intent.putExtra(String,CharSequence[]) is not applicable
   (argument mismatch; DataModel cannot be converted to CharSequence[])
   method Intent.putExtra(String,Bundle) is not applicable
   (argument mismatch; DataModel cannot be converted to Bundle)

Body:
this opens a new activity .but how to open different activities by clicking on different cardviews ?

@Override
    public void onItemClick(DataModel item) {

        Intent intent = new Intent(MainActivity.this, Yojana.class);
        intent.putExtra("dataitem", String.valueOf(item));
        startActivity(intent);

}

Yojana.class

public class Yojana extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_yojana);
     getIntent().getExtras().getString("dataitem");

}


问:
Meteor multiple servers to one database collection (local)
I have a meteor project that does several external API calls on different setInterval() timers and pushes the data to MongoDB.

I want to split the calls to several "micro-services" , different instances running API calls on their own server.

All the data is stored in one single collection

I've found this solution export MONGO_URL=mongodb://localhost:3001/meteor meteor run but it just gives me errors

How can i connect two meteor server instances to connect to the same collection on the default localhost:3001 database?

```<code>npm ERR! Windows_NT 6.1.7601
npm ERR! argv "C:\\nodejs\\node.exe"
"C:\\Users\\Nico\\AppData\\Roaming\\npm\\node_modules\\npm\\bin\\npm-cli.js" "run" "meteor"
npm ERR! node v6.9.2
npm ERR! npm  v4.0.2
npm ERR! code ELIFECYCLE
npm ERR! crypto@ meteor: `export MONGO_URL=mongodb://localhost:3001/meteor meteor run`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the crypto@ meteor script 'export MONGO_URL=mongodb://localhost:3001/meteor meteor'.
</code>```

答:
Meteor does not start up MongoDB itself when providing a MONGO_URL environment variable.

We need to set MONGO_URL to 27017 port instead of 3001

Body:
I have a meteor project that does several external API calls on different setInterval() timers and pushes the data to MongoDB.

I want to split the calls to several "micro-services" , different instances running API calls on their own server.

All the data is stored in one single collection

I've found this solution export MONGO_URL=mongodb://localhost:3001/meteor meteor run but it just gives me errors

How can i connect two meteor server instances to connect to the same collection on the default localhost:3001 database?

npm ERR! Windows_NT 6.1.7601
npm ERR! argv "C:\\nodejs\\node.exe"
"C:\\Users\\Nico\\AppData\\Roaming\\npm\\node_modules\\npm\\bin\\npm-cli.js" "run" "meteor"
npm ERR! node v6.9.2
npm ERR! npm  v4.0.2
npm ERR! code ELIFECYCLE
npm ERR! crypto@ meteor: `export MONGO_URL=mongodb://localhost:3001/meteor meteor run`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the crypto@ meteor script 'export MONGO_URL=mongodb://localhost:3001/meteor meteor'.


问:
PHP Slimframework CORS
I'm in a bit trouble with this CORS thing. Angular 4 is running on localhost:4200, while Slimframework is running on localhost:8080.

My front-end HTTP request:

```<code>....
createPartner(partner: Partner): Observable<Partner> {
    let headers = new Headers({ 'Content-Type' : 'application/json'});
    let options = new RequestOptions({ headers: headers });

    return this.http.post(this.regUrl, partner, options)
           .map((res: Response) => {
              return res.json();
           })
           .catch(this.handleError);
  }
....
</code>```

My middleware:

```<code>....
$app->add(function($request, $response, $next) {
$route = $request->getAttribute("route");

$methods = [];

if (!empty($route)) {
    $pattern = $route->getPattern();

    foreach ($this->router->getRoutes() as $route) {
        if ($pattern === $route->getPattern()) {
            $methods = array_merge_recursive($methods, $route->getMethods());
        }
    }
} else {
    $methods[] = $request->getMethod();
}

$response = $next($request, $response);

return $response->withHeader("Access-Control-Allow-Methods", implode(",", $methods));
});
</code>```

I added "determineRouteBeforeAppMiddleware" => true, to my settings array.

The browser's (chrome) console says:

XMLHttpRequest cannot load http://lvh.me/api/partner. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

What did I do wrong, guys? :/

Edit:

Forgot the 8080 port of the backend URI, now that I added, the new error is:

```<code>OPTIONS http://lvh.me:8080/api/partner net::ERR_CONNECTION_REFUSED
</code>```

答:
Add the following to your htaccess to allow cors,

```<code><IfModule mod_rewrite.c>

  Header add Access-Control-Allow-Origin "*"

  Header add Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"

  Header add Access-Control-Allow-Headers: "Content-Type"

  RewriteEngine on

  RewriteBase /

</IfModule>
</code>```

Source: https://gist.github.com/maxparm/3105526

Title: PHP Slimframework CORS

Body:
I'm in a bit trouble with this CORS thing. Angular 4 is running on localhost:4200, while Slimframework is running on localhost:8080.

My front-end HTTP request:

....
createPartner(partner: Partner): Observable<Partner> {
    let headers = new Headers({ 'Content-Type' : 'application/json'});
    let options = new RequestOptions({ headers: headers });

    return this.http.post(this.regUrl, partner, options)
           .map((res: Response) => {
              return res.json();
           })
           .catch(this.handleError);
  }
....

My middleware:

....
$app->add(function($request, $response, $next) {
$route = $request->getAttribute("route");

$methods = [];

if (!empty($route)) {
    $pattern = $route->getPattern();

    foreach ($this->router->getRoutes() as $route) {
        if ($pattern === $route->getPattern()) {
            $methods = array_merge_recursive($methods, $route->getMethods());
        }
    }
} else {
    $methods[] = $request->getMethod();
}

$response = $next($request, $response);

return $response->withHeader("Access-Control-Allow-Methods", implode(",", $methods));
});

I added "determineRouteBeforeAppMiddleware" => true, to my settings array.

The browser's (chrome) console says:

XMLHttpRequest cannot load http://lvh.me/api/partner. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

What did I do wrong, guys? :/

Edit:

Forgot the 8080 port of the backend URI, now that I added, the new error is:

OPTIONS http://lvh.me:8080/api/partner net::ERR_CONNECTION_REFUSED

Body:
Add the following to your htaccess to allow cors,

<IfModule mod_rewrite.c>

  Header add Access-Control-Allow-Origin "*"

  Header add Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"

  Header add Access-Control-Allow-Headers: "Content-Type"

  RewriteEngine on

  RewriteBase /

</IfModule>

Source: https://gist.github.com/maxparm/3105526


问:
I've added Microdata to web page HTML, but it shows up on publishing from CMS
As explained in searchengineland.com, I've added the following navigation markup but it shows up on publishing the site above the header. I want it to show up like the attached image in Google search results:

I'm using Sandvox for Mac to publish the site. Where should I add the Microdata HTML?

I tried to put it inside this code and it just prints on the published page:

.....

Our Advantage

Travel Experts

Destinations

Cruises

Interests

Hotels

Travel Resources

```

答:
Your screenshot of the Google Search result shows two features:

a search field that searches the result site

links to other pages of the site

You can provide structured data markup to get the first feature (Sitelinks Searchbox), you can’t provide structured data markup to get the second feature (sitelinks).

Schema.org’s SiteNavigationElement type doesn’t seem to get used by Google Search for any of their result features. I recommend not to use SiteNavigationElement at all.

If you want to use SiteNavigationElement anyway, note that you are not using it correctly: you can only markup the whole navigation, not single navigation links. So the url and name properties of SiteNavigationElement are for the URL and the name of the navigation itself (and a navigation typically doesn’t have these). So it would be:

Our Advantage

Travel Experts

Destinations

```

(Note that Schema.org URIs should be specified without the www subdomain.)

Body:
Your screenshot of the Google Search result shows two features:

a search field that searches the result site

links to other pages of the site

You can provide structured data markup to get the first feature (Sitelinks Searchbox), you can’t provide structured data markup to get the second feature (sitelinks).

Schema.org’s SiteNavigationElement type doesn’t seem to get used by Google Search for any of their result features. I recommend not to use SiteNavigationElement at all.

If you want to use SiteNavigationElement anyway, note that you are not using it correctly: you can only markup the whole navigation, not single navigation links. So the url and name properties of SiteNavigationElement are for the URL and the name of the navigation itself (and a navigation typically doesn’t have these). So it would be:

<ul itemscope itemtype="http://schema.org/SiteNavigationElement">
  <li><a href="http://www.travelstore.com/our-advantage">Our Advantage</a></li>
  <li><a href="http://www.travelstore.com/our-travel-experts">Travel Experts</a></li>
  <li><a href="http://www.travelstore.com/destinations">Destinations</a></li>
</ul>

(Note that Schema.org URIs should be specified without the www subdomain.)


问:
time_zone_select sort selection to display us time zones first
I'm trying to use the Time_zone_select method rails provides for form builders. This is awesome but I'd like to provide a little better UX. Is it possible to list the US timezones first instead of all the options all combined alphabetically?

```<code> <%= form.time_zone_select :time_zone, nil, class: "form-input" %>
</code>```

答:
Yes, you can use the priority_zones option (second argument, which you are setting as nil), which receives an array of ActiveSupport::TimeZone objects.

For US zones you can use ActiveSupport::TimeZone.us_zones, for example:

```<code><%= form.time_zone_select :time_zone, ActiveSupport::TimeZone.us_zones, class: "form-input" %>
</code>```

How can I set a default value?

Just add default option, for example:

```<code><%= form.time_zone_select :time_zone, ActiveSupport::TimeZone.us_zones, default: "Pacific Time (US & Canada)", class: "form-input" %>
</code>```

You can read more about time_zone_select here.

Body:
I'm trying to use the Time_zone_select method rails provides for form builders. This is awesome but I'd like to provide a little better UX. Is it possible to list the US timezones first instead of all the options all combined alphabetically?

 <%= form.time_zone_select :time_zone, nil, class: "form-input" %>

Body:
Yes, you can use the priority_zones option (second argument, which you are setting as nil), which receives an array of ActiveSupport::TimeZone objects.

For US zones you can use ActiveSupport::TimeZone.us_zones, for example:

<%= form.time_zone_select :time_zone, ActiveSupport::TimeZone.us_zones, class: "form-input" %>

How can I set a default value?

Just add default option, for example:

<%= form.time_zone_select :time_zone, ActiveSupport::TimeZone.us_zones, default: "Pacific Time (US & Canada)", class: "form-input" %>

You can read more about time_zone_select here.


问:
How can i add color label of each edge in networkx in python
My networkx graph

In my directed networkx graph , i have drawn edges color based on weight. I am able to add them as labels in my graph but it is appearing twice. How can i add edges label with different color only once along with directions

```<code>`elarge=[(u,v) for (u,v,d) in G.edges(data=True) if d['weight'] >0.10]
emed=[(u,v) for (u,v,d) in G.edges(data=True) if d['weight'] >0.05 and d['weight'] <0.10]
esmall=[(u,v) for (u,v,d) in G.edges(data=True) if d['weight'] <0.05]

# red_patch = mpatches.Patch(color='red', label= "Probablity < 0.05")
# plt.legend(handles=[red_patch])

# blue_patch = mpatches.Patch(color='blue', label='Probablity > 0.10')
# plt.legend(handles=[blue_patch])

# green_patch = mpatches.Patch(color='green',label='Probablity > 0.15 and Probablity < 0.10')
# plt.legend(handles=[green_patch])

pos=nx.spring_layout(G) # positions for all nodes
edge_labels = nx.get_edge_attributes(G,'weight')

# nodes
nx.draw_networkx_nodes(G,pos,node_size=4000,node_color= "grey")

# edges

nx.draw_networkx_edges(G,pos,edgelist=elarge,
                    width=2,alpha = 0.6,edge_color = "b",label = "Probablity > 0.10",arrows=True)
nx.draw_networkx_edges(G,pos,edgelist=esmall,
                    width=3,alpha=0.6,edge_color='r',label = "Probablity < 0.05",arrows=True)
nx.draw_networkx_edges(G,pos,edgelist=emed,
                    width=3,alpha=0.6,edge_color='g',label = "'Probablity > 0.15 and Probablity < 0.10'",arrows=True)

# labels
nx.draw_networkx_edge_labels(G, pos, labels = edge_labels,arrows=False)
nx.draw_networkx_labels(G,pos,labels1,font_size=12,font_family='sans-serif')
plt.legend(numpoints = 1)
plt.axis('on')
plt.show()
</code>```

答:
To me, this looks like a bug in networkx (still present in 1.11).  Looking at the source code for draw_networkx_edges, it creates the edges, and then it creates the arrowheads as thicker lines.

After creating the edges, there is the command edge_collection.set_label(label), which sets the labels for the edges.  But after creating the arrowheads it also has arrow_collection.set_label(label).  So both the edge and the arrowhead end up labelled in the legend (this is why you'll see that in your legend the labels appear with two associated widths).

I believe it would be enough to go to the networkx code on your computer and simply comment out arrow_collection.set_label(label).  Another alternative would be to draw the edge without the arrowheads and give it a label, and then redraw it (using the same color) with an arrowhead but no label.

I've submitted a bug report on this, as I can't think of any reason why one would want a separate label for the arrowhead.

Body:
My networkx graph

In my directed networkx graph , i have drawn edges color based on weight. I am able to add them as labels in my graph but it is appearing twice. How can i add edges label with different color only once along with directions

`elarge=[(u,v) for (u,v,d) in G.edges(data=True) if d['weight'] >0.10]
emed=[(u,v) for (u,v,d) in G.edges(data=True) if d['weight'] >0.05 and d['weight'] <0.10]
esmall=[(u,v) for (u,v,d) in G.edges(data=True) if d['weight'] <0.05]

# red_patch = mpatches.Patch(color='red', label= "Probablity < 0.05")
# plt.legend(handles=[red_patch])

# blue_patch = mpatches.Patch(color='blue', label='Probablity > 0.10')
# plt.legend(handles=[blue_patch])

# green_patch = mpatches.Patch(color='green',label='Probablity > 0.15 and Probablity < 0.10')
# plt.legend(handles=[green_patch])

pos=nx.spring_layout(G) # positions for all nodes
edge_labels = nx.get_edge_attributes(G,'weight')

# nodes
nx.draw_networkx_nodes(G,pos,node_size=4000,node_color= "grey")

# edges

nx.draw_networkx_edges(G,pos,edgelist=elarge,
                    width=2,alpha = 0.6,edge_color = "b",label = "Probablity > 0.10",arrows=True)
nx.draw_networkx_edges(G,pos,edgelist=esmall,
                    width=3,alpha=0.6,edge_color='r',label = "Probablity < 0.05",arrows=True)
nx.draw_networkx_edges(G,pos,edgelist=emed,
                    width=3,alpha=0.6,edge_color='g',label = "'Probablity > 0.15 and Probablity < 0.10'",arrows=True)

# labels
nx.draw_networkx_edge_labels(G, pos, labels = edge_labels,arrows=False)
nx.draw_networkx_labels(G,pos,labels1,font_size=12,font_family='sans-serif')
plt.legend(numpoints = 1)
plt.axis('on')
plt.show()