问:
How to overcome the effect of navigation bar
In my application i want to hide the navigation bar when i m going to previous view and i m hiding navigation bar in viewwiilldisaapper method but the effect is remaining mean it gives the white screen at the time of pop..

so can any one tell me the solution for it.

Thanks to all.

答:
I think it happen due to customize navigation bar. Is this right?
If you have customize navigation bar then you need to resize your upcoming
view. It doesn't matter how would you hide it. </p>


来源: stackexchange

问:
Add Number of days column to Date Column in same dataframe for Spark Scala App
I have a dataframe df of columns ("id", "current_date", "days") and I am trying to add the the "days" to "current_date" and create a new dataframe with new column called "new_date" using spark scala function date_add()

```<code>val newDF = df.withColumn("new_Date", date_add(df("current_date"), df("days").cast("Int")))
</code>```

But looks like the function date_add only accepts Int values and not columns. How can get the desired output in such case? Are there any alternative functions i can use to get the desired output?

spark version: 1.6.0
scala version: 2.10.6

答:
A small custom udf can be used to make this date arithmetic possible.

```<code>import org.apache.spark.sql.functions.udf
import java.util.concurrent.TimeUnit
import java.util.Date
import java.text.SimpleDateFormat

val date_add = udf((x: String, y: Int) => {
    val sdf = new SimpleDateFormat("yyyy-MM-dd")
    val result = new Date(sdf.parse(x).getTime() + TimeUnit.DAYS.toMillis(y))
  sdf.format(result)
} )
</code>```

Usage:

```<code>scala> val df = Seq((1, "2017-01-01", 10), (2, "2017-01-01", 20)).toDF("id", "current_date", "days")
df: org.apache.spark.sql.DataFrame = [id: int, current_date: string, days: int]

scala> df.withColumn("new_Date", date_add($"current_date", $"days")).show()
+---+------------+----+----------+
| id|current_date|days|  new_Date|
+---+------------+----+----------+
|  1|  2017-01-01|  10|2017-01-11|
|  2|  2017-01-01|  20|2017-01-21|
+---+------------+----+----------+
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a dataframe df of columns ("id", "current_date", "days") and I am trying to add the the "days" to "current_date" and create a new dataframe with new column called "new_date" using spark scala function date_add()

val newDF = df.withColumn("new_Date", date_add(df("current_date"), df("days").cast("Int")))

But looks like the function date_add only accepts Int values and not columns. How can get the desired output in such case? Are there any alternative functions i can use to get the desired output?

spark version: 1.6.0
scala version: 2.10.6

Body:
A small custom udf can be used to make this date arithmetic possible.

import org.apache.spark.sql.functions.udf
import java.util.concurrent.TimeUnit
import java.util.Date
import java.text.SimpleDateFormat

val date_add = udf((x: String, y: Int) => {
    val sdf = new SimpleDateFormat("yyyy-MM-dd")
    val result = new Date(sdf.parse(x).getTime() + TimeUnit.DAYS.toMillis(y))
  sdf.format(result)
} )

Usage:

scala> val df = Seq((1, "2017-01-01", 10), (2, "2017-01-01", 20)).toDF("id", "current_date", "days")
df: org.apache.spark.sql.DataFrame = [id: int, current_date: string, days: int]

scala> df.withColumn("new_Date", date_add($"current_date", $"days")).show()
+---+------------+----+----------+
| id|current_date|days|  new_Date|
+---+------------+----+----------+
|  1|  2017-01-01|  10|2017-01-11|
|  2|  2017-01-01|  20|2017-01-21|
+---+------------+----+----------+


问:
sapply() returns 'logical(0)' when x value is 0 in R
I am trying to make a small script to get rid of extreme values in a large dataset, but when my value is "0" my function returns "logical(0)" instead of NA.

```<code>#Getting rid of extreme values
test=NULL
test$value<-runif(200,13.90,14.10)
test$date<-seq(1,200,1)
test$value[125]<-15
test$value[175]<-0

plot(test$date, test$value)

averagei=NULL
averagetot=NULL
for (i in 1:length(test$value)) {
  averagei<-mean(test$value[i-15:i+15])
  averagetot=c(averagetot,averagei)

}

t<-sapply(test$value, function(x) ifelse(x - averagetot[x]>0.5, "NA", x))
t[175]
[[1]]
logical(0)
</code>```

Why does this happen? I can of course get rid of the 0 before but it drives me crazy that I cannot understand why this happens or fix it.

EDIT: Thanks to Marius comment I fixed it using a for loop, might not be the most efficient but it does the job. Someone has a solution in a sapply loop but I could not make it work in my case: Row/column counter in 'apply' functions

```<code>test=NULL
test$value<-runif(200,13.90,14.10)
test$date<-seq(1,200,1)
test$value[125]<-15
test$value[175]<-0

plot(test$date, test$value)

a=NULL
atot=NULL
for (i in 1:length(test$value)){
  a<-ifelse(abs(test$value[i] - averagetot[i])>0.5, "NA", test$value[i])
  atot=c(atot,as.numeric(a))
    }

atot[175]
length(atot)
</code>```

答:
The problem seems to be in the

```<code>averagei<-mean(test$value[i-15:i+15])
</code>```

It should be

```<code>averagei<-mean(test$value[(i-15):(i+15)])
</code>```

Body:
I am trying to make a small script to get rid of extreme values in a large dataset, but when my value is "0" my function returns "logical(0)" instead of NA.

#Getting rid of extreme values
test=NULL
test$value<-runif(200,13.90,14.10)
test$date<-seq(1,200,1)
test$value[125]<-15
test$value[175]<-0

plot(test$date, test$value)

averagei=NULL
averagetot=NULL
for (i in 1:length(test$value)) {
  averagei<-mean(test$value[i-15:i+15])
  averagetot=c(averagetot,averagei)

}

t<-sapply(test$value, function(x) ifelse(x - averagetot[x]>0.5, "NA", x))
t[175]
[[1]]
logical(0)

Why does this happen? I can of course get rid of the 0 before but it drives me crazy that I cannot understand why this happens or fix it.

EDIT: Thanks to Marius comment I fixed it using a for loop, might not be the most efficient but it does the job. Someone has a solution in a sapply loop but I could not make it work in my case: Row/column counter in 'apply' functions

test=NULL
test$value<-runif(200,13.90,14.10)
test$date<-seq(1,200,1)
test$value[125]<-15
test$value[175]<-0

plot(test$date, test$value)

a=NULL
atot=NULL
for (i in 1:length(test$value)){
  a<-ifelse(abs(test$value[i] - averagetot[i])>0.5, "NA", test$value[i])
  atot=c(atot,as.numeric(a))
    }

atot[175]
length(atot)

Body:
The problem seems to be in the

averagei<-mean(test$value[i-15:i+15])

It should be

averagei<-mean(test$value[(i-15):(i+15)])


问:
How do I make an image in PDF open its link in new pop-up window?
I am embedding a PDF in an HTML. There are some images with links in PDF. I want to make those link open in a pop-up window/ new window rather than a new/ the same tab on click.</p>

答: You provide a link on PDF in such a way that the link which is to be opened in pop-up should be a parameter. Write a jquery/js script to access that param and open a pop-up window or boostrap modal to show the link in it. I hope this helps. </p>


问:
returning sum of relationships propertys on path on neo4j?
I need to get the sum of properties of the relationships, from the returned list of a function like the next one

```<code>MATCH path=((house:Building {country: 'usa'})-[*]-(shelf:Building {country: 'mexico'}))
RETURN path;
</code>```

The relationships can have differents names, but the propertys have the same keys(and different values), for example:

```<code>MERGE (house)-[:NAME1{num: '5'}]->(cabin)
MERGE (cabin)-[:NAME2{num: '10'}]->(shop)
MERGE (shop)-[:NAME1{num: '5'}]->(foo)
MERGE (foo)-[:NAME3{num: '30'}]->(shelf)
</code>```

I need a query, applying the previous requirements, returning the sum of all relationship's properties.

How can I do it?

答:
You can use the REDUCE function to calculate the total:

```<code>MATCH path=((house:Building {country: 'usa'})-[rels*]-(shelf:Building {country: 'mexico'}))
RETURN path, REDUCE(s = 0, r IN rels | s + TOINTEGER(r.num)) AS total;
</code>```

NOTE: Ideally, you should store integer values for the num property (instead of strings), so that you will not have to pay a performance penalty for converting all the string values to integers every time you need to use the numeric values. After you do that, you can remove the call to the TOINTEGER function.

Body:
I need to get the sum of properties of the relationships, from the returned list of a function like the next one

MATCH path=((house:Building {country: 'usa'})-[*]-(shelf:Building {country: 'mexico'}))
RETURN path;

The relationships can have differents names, but the propertys have the same keys(and different values), for example:

MERGE (house)-[:NAME1{num: '5'}]->(cabin)
MERGE (cabin)-[:NAME2{num: '10'}]->(shop)
MERGE (shop)-[:NAME1{num: '5'}]->(foo)
MERGE (foo)-[:NAME3{num: '30'}]->(shelf)

I need a query, applying the previous requirements, returning the sum of all relationship's properties.

How can I do it?

Body:
You can use the REDUCE function to calculate the total:

MATCH path=((house:Building {country: 'usa'})-[rels*]-(shelf:Building {country: 'mexico'}))
RETURN path, REDUCE(s = 0, r IN rels | s + TOINTEGER(r.num)) AS total;

NOTE: Ideally, you should store integer values for the num property (instead of strings), so that you will not have to pay a performance penalty for converting all the string values to integers every time you need to use the numeric values. After you do that, you can remove the call to the TOINTEGER function.

ContentLicense: CC BY-SA 4.0


问:
C# Error when initialize a variable in a different public class
I am trying to initialize 2 different variables in a public class but when I initialize the second one, it gets the property (Name in this example) of the first one. After I set the name of the second one. The first variable changes its name property to the second name.
For example, when I execute the code:

```<code>    //Initialization and set of first var
    findLineToolA.Name = "findLineToolA";
    findLineToolB = null;
    //After findLineToolB = new CatFindLineTool();
    findLineToolA.Name = "findLineToolA";
    findLineToolB.Name = "findLineToolA";

    //After findLineToolB.Name = "findLineToolB";
    findLineToolA.Name = "findLineToolB";
    findLineToolB.Name = "findLineToolB";

    public class CatFindLineTool
    {
            private static string _name;

            public string Name
            {
                set
                {
                    _name = value;
                }
                get
                {
                    return _name;
                }
            }
    }
public class CatFindCornerTool
{
    public CatFindLineTool findLineToolA;
    public CatFindLineTool findLineToolB;
    public CatFindCornerTool()
    {
     findLineToolA = new CatFindLineTool();
     findLineToolA.Name = "findLineToolA";
     findLineToolB = new CatFindLineTool();
     findLineToolB.Name = "findLineToolB";
    }
   }
</code>```

I hope someone can help me to figure out why the properties mix up when initialize multiple variables. I guess it is because there is an important concept about C# class that I am ignoring.
Thanks in advance.

答:
You have declared the _name field to be static. This makes it a 'global' or 'shared' entity across all instances of the class - hence changes to one instance will affect all instances.

Just remove the static keyword and your code should work as intended.

Body:
I am trying to initialize 2 different variables in a public class but when I initialize the second one, it gets the property (Name in this example) of the first one. After I set the name of the second one. The first variable changes its name property to the second name.
For example, when I execute the code:

    //Initialization and set of first var
    findLineToolA.Name = "findLineToolA";
    findLineToolB = null;
    //After findLineToolB = new CatFindLineTool();
    findLineToolA.Name = "findLineToolA";
    findLineToolB.Name = "findLineToolA";

    //After findLineToolB.Name = "findLineToolB";
    findLineToolA.Name = "findLineToolB";
    findLineToolB.Name = "findLineToolB";

    public class CatFindLineTool
    {
            private static string _name;

            public string Name
            {
                set
                {
                    _name = value;
                }
                get
                {
                    return _name;
                }
            }
    }
public class CatFindCornerTool
{
    public CatFindLineTool findLineToolA;
    public CatFindLineTool findLineToolB;
    public CatFindCornerTool()
    {
     findLineToolA = new CatFindLineTool();
     findLineToolA.Name = "findLineToolA";
     findLineToolB = new CatFindLineTool();
     findLineToolB.Name = "findLineToolB";
    }
   }

I hope someone can help me to figure out why the properties mix up when initialize multiple variables. I guess it is because there is an important concept about C# class that I am ignoring.
Thanks in advance.


问:
Beginner error Python and Atom
Having trouble with Python code in Atom. I'm using 'Learn Python The Hard Way' to practice some coding. When I enter this code into Atom, there is no error but it just won't run (yes, I have Script installed and it works fine for other things). There is a little egg timer in the bottom of Atom but nothing else gives me any indication of what I may be doing wrong.

```<code>print "How old are you?",
age = raw_input()
print "How tall are you?",
height = raw_input()
print "How much do you weigh?",
weight = raw_input()

print "So, you're %r old, %r tall and %r heavy." % (
    age, height, weight)
</code>```

When I type like this

```<code>print "How old are you?",
print "How tall are you?",
print "How much do you weigh?",

print "So, you're %r old, %r tall and %r heavy." % (
    age, height, weight)
</code>```

The code runs, but with an error just saying that age is not defined and that makes sense because the code isn't complete. Does that just show that there is no problem with the editor but with the code? So please help. I'm new to this.

答:
The script package does not handle collecting input. If your script requires input (as your first script does), then it will just sit and wait.

Your second script doesn't expect any input, so it runs (but then, as you see, it has an error due to age not being defined).

The author of the script package has suggested (here and here) that Hydrogen may be an alternative if you need to handle input.

Title: Beginner error Python and Atom

Body:
Having trouble with Python code in Atom. I'm using 'Learn Python The Hard Way' to practice some coding. When I enter this code into Atom, there is no error but it just won't run (yes, I have Script installed and it works fine for other things). There is a little egg timer in the bottom of Atom but nothing else gives me any indication of what I may be doing wrong.

print "How old are you?",
age = raw_input()
print "How tall are you?",
height = raw_input()
print "How much do you weigh?",
weight = raw_input()

print "So, you're %r old, %r tall and %r heavy." % (
    age, height, weight)

When I type like this

print "How old are you?",
print "How tall are you?",
print "How much do you weigh?",

print "So, you're %r old, %r tall and %r heavy." % (
    age, height, weight)

The code runs, but with an error just saying that age is not defined and that makes sense because the code isn't complete. Does that just show that there is no problem with the editor but with the code? So please help. I'm new to this.


问:
How to determine by reflection if a Method returns 'void'
I have a java.lang.reflect.Method object and I would like to know if it's return type is void.

I've checked the Javadocs and there is a getReturnType() method that returns a Class object. The thing is that they don't say what would be the return type if the method is void.

Thanks!

答:
```<code>method.getReturnType()==void.class     √

method.getReturnType()==Void.Type      √

method.getReturnType()==Void.class     X
</code>```

ContentLicense: CC BY-SA 2.5


问:
E/Surface﹕ getSlotFromBufferLocked: unknown buffer: 0xab7519c0
I have a problem with my app. No inserts the data in mysql, the app does not have errors and orange single message log is:

```<code> E / Surface: getSlotFromBufferLocked: unknown buffer: 0xab7519c0
</code>```

I hope you can help me.

Thank you

答:
Check your unused XML.

I had this problem too when I deleted .java but forgot remove .xml files.

Body:
I have a problem with my app. No inserts the data in mysql, the app does not have errors and orange single message log is:

 E / Surface: getSlotFromBufferLocked: unknown buffer: 0xab7519c0

I hope you can help me.

Thank you


问:
Where to put CSS3 media queries?
I am having a philosophical debate with myself over the best place to put media queries within style sheets.  I am attempting to structure my CSS modularly (like OOCSS or SMACSS, etc). Given that context, I see two choices:

Put all media queries together in a separate stylesheet or section of the main stylesheet.

Put media queries below their base counterparts. For example, if I have a module called "news-item", I could put any necessary media query styles right below the definition of that module.

I am leaning towards the latter, but it would mean I'd have many more separate media queries (separate ones for each logical block of CSS requiring a responsive adjustment).

Any thoughts on this?

答:
May be you can try css variables, which is native support reuse your css!

:root {
  --main-color: #F06D06;
}

.main-header {
  color: var(--main-color);
}
.main-footer {
  background-color: var(--main-color);
}```

https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_variables

https://developers.google.com/web/updates/2016/02/css-variables-why-should-you-care

https://css-tricks.com/difference-between-types-of-css-variables/

Title: Where to put CSS3 media queries?

Body:
May be you can try css variables, which is native support reuse your css!

:root {
  --main-color: #F06D06;
}

.main-header {
  color: var(--main-color);
}
.main-footer {
  background-color: var(--main-color);
}

https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_variables

https://developers.google.com/web/updates/2016/02/css-variables-why-should-you-care

https://css-tricks.com/difference-between-types-of-css-variables/


问:
How to ensure that a logged in employee can only view his sales record but Admin can view all?
I'm learning asp.net, I have created simple web application for storing sales record using a form, employee record, I'm wondering how I can make sure no employee can view sales data of any other employee and make changes to them but Admin or employee manager can view all of their records?

using a simple Model for now:

```<code>{
public ApplicationUser Employee{ get; set; }
public int EmpId { get; set; }
public int Id { get; set; }
public string Po { get; set; }
public long So { get; set; }
}
</code>```

答:
You can use Entity Framework queries to only get the sales records of the currently logged in employee. If the user is in an Admin role, then you will query for all of the sales records.

This question may provide more assistance.

Body:
I'm learning asp.net, I have created simple web application for storing sales record using a form, employee record, I'm wondering how I can make sure no employee can view sales data of any other employee and make changes to them but Admin or employee manager can view all of their records?

using a simple Model for now:

{
public ApplicationUser Employee{ get; set; }
public int EmpId { get; set; }
public int Id { get; set; }
public string Po { get; set; }
public long So { get; set; }
}


问:
Perl code to find an array element in a sentence and then to look either side of the match for another string to be matched from a different array
I have 2 arrays in which one of the array consists of words which I consider as trigger words while the second array is a list of names. I want to find sentences in a file which have the trigger word and then look both right and left and find the matches using the array name.

I am kind of confused about how to go about solving this problem.

```<code>my @strings = (
    'SPARC is an activator of SPARCL1.',
    'SPARCL1 and SPARC regulate the expression of TGFB1.',
    'SPARCL1 and SPARC are used in signal transduction.',
    'SPARCL1 and ADAMTS4 have been found to upregulated by MMP3 and MMP3 are downregulated by SMAD3.',
);

my @trigs = ( "activator", "regulate", "upregulated" , "downregulated" );
my @genes = ( "SPARC", "SPARCL1", "ADAMTS4", "MMP3", "SMAD3", "TGFB1" );
</code>```

Desired output:

```<code>SPARC is an activator of SPARCL1
SPARC regulate the expression of TGFB1
ADAMTS4 have been found to upregulated by MMP3
MMP3 are downregulated by SMAD3
</code>```

答:
```<code>my $trig_re = join '|', map quotemeta, @trigs;
$trig_re = qr/\b(?:$trig_re)/;

my $gene_re = join '|', map quotemeta, @genes;
$gene_re = qr/\b(?:$gene_re)\b/;

my $re = qr/
   (
      $gene_re
      (?:(?!$gene_re|$trig_re).)*
      $trig_re
      (?:(?!$gene_re|$trig_re).)*
      $gene_re
   )
/sx;

for my $string (@strings) {
   say $1 while $string =~ /$re/g;
}
</code>```

Output:

SPARC is an activator of SPARCL1
SPARC regulate the expression of TGFB1
ADAMTS4 have been found to upregulated by MMP3
MMP3 are downregulated by SMAD3
```

Body:
I have 2 arrays in which one of the array consists of words which I consider as trigger words while the second array is a list of names. I want to find sentences in a file which have the trigger word and then look both right and left and find the matches using the array name.

I am kind of confused about how to go about solving this problem.

my @strings = (
    'SPARC is an activator of SPARCL1.',
    'SPARCL1 and SPARC regulate the expression of TGFB1.',
    'SPARCL1 and SPARC are used in signal transduction.',
    'SPARCL1 and ADAMTS4 have been found to upregulated by MMP3 and MMP3 are downregulated by SMAD3.',
);

my @trigs = ( "activator", "regulate", "upregulated" , "downregulated" );
my @genes = ( "SPARC", "SPARCL1", "ADAMTS4", "MMP3", "SMAD3", "TGFB1" );

Desired output:

SPARC is an activator of SPARCL1
SPARC regulate the expression of TGFB1
ADAMTS4 have been found to upregulated by MMP3
MMP3 are downregulated by SMAD3

Body:
my $trig_re = join '|', map quotemeta, @trigs;
$trig_re = qr/\b(?:$trig_re)/;

my $gene_re = join '|', map quotemeta, @genes;
$gene_re = qr/\b(?:$gene_re)\b/;

my $re = qr/
   (
      $gene_re
      (?:(?!$gene_re|$trig_re).)*
      $trig_re
      (?:(?!$gene_re|$trig_re).)*
      $gene_re
   )
/sx;

for my $string (@strings) {
   say $1 while $string =~ /$re/g;
}

Output:

SPARC is an activator of SPARCL1
SPARC regulate the expression of TGFB1
ADAMTS4 have been found to upregulated by MMP3
MMP3 are downregulated by SMAD3


问:
Sprite appearing in node count but not visible
Im attempting to create a constantly moving background by cycling 2 sprites. Running my code shows that the sprites have been added in the correct positions in the correct size. Yet the sprites aren't visible on screen. Why is this the case? My code below</p>

```<code>import SpriteKit
import GameplayKit
import CoreMotion

class GameScene: SKScene, SKPhysicsContactDelegate{

    var ship = SKSpriteNode()
    var actionMoveRight = SKAction()
    var actionMoveLeft = SKAction()
    let shipCategory = 0x1 << 1
    let obstacleCategory = 0x1 << 2
    let backgroundVelocity : CGFloat = 3.0
    var motionManager = CMMotionManager()
    var background = SKSpriteNode.init(imageNamed: "background")

    override func didMove(to view: SKView) {
        // Making self delegate of physics world)
        self.anchorPoint = CGPoint.init(x: 0.5, y: 0.5)
        self.physicsWorld.gravity = CGVector.zero
        self.physicsWorld.contactDelegate = self
        createBG()
        addShip()
    }

    override func update(_ currentTime: CFTimeInterval) {
        moveBG()
    }

    func createBG(){
        for i in 0...2{
            background = SKSpriteNode.init(imageNamed: "background")
            background.name = "background"
            background.size = CGSize.init(width: (self.scene?.size.width)!, height: (self.scene?.size.height)!)
            background.anchorPoint = self.anchorPoint
            background.position = CGPoint.init(x: CGFloat(i) * background.size.width, y: (-(self.frame.size.height/2)))
            background.zPosition = 0
            self.addChild(background)
        }
    }

    func moveBG(){
        self.enumerateChildNodes(withName: "background", using: ({
            (node, error) in

            node.position.x -= 10
            if node.position.x < (self.scene?.size.width)!{
                node.position.x += (self.scene?.size.width)! * 2
            }
        }))
    }

    func addShip() {
        // Initializing spaceship node
        ship = SKSpriteNode(imageNamed: "Spaceship")
        ship.setScale(0.2)
        ship.isHidden = false
        ship.zRotation = CGFloat(0)
        // Adding SpriteKit physics body for collision detection
        ship.physicsBody = SKPhysicsBody(rectangleOf: ship.size)
        ship.physicsBody?.categoryBitMask = UInt32(shipCategory)
        ship.physicsBody?.isDynamic = true
        ship.physicsBody?.contactTestBitMask = UInt32(obstacleCategory)
        ship.physicsBody?.collisionBitMask = 0
        ship.name = "ship"
        ship.position = CGPoint.init(x: 0, y: (-(self.frame.size.height/2)) + ship.size.height/2)
        ship.zPosition = 1
        self.addChild(ship)
        actionMoveRight = SKAction.moveBy(x: 5, y: 0, duration: 0.2) //9
        actionMoveLeft = SKAction.moveBy(x: -5  , y: 0, duration: 0.2) //10
        if motionManager.isAccelerometerAvailable == true {
            motionManager.startAccelerometerUpdates(to: OperationQueue.current!, withHandler:{
                data, error in
                if (data!.acceleration.y) < -0.05 {
                    self.ship.run(self.actionMoveLeft)
                }

                else if data!.acceleration.y > 0.05 {
                    self.ship.run(self.actionMoveRight)
                }

            })

        }
    }
}
</code>```

答:
I assume that the background node size is just the same as the image size.  I also assume that the scene size is the same as the image size.  If that's the case, try the following.</p>

```<code>let backTexture = SKTexture(imageNamed: "background")
let background = SKSpriteNode(texture: backTexture)
//background.size = CGSize.init(width: (self.scene?.size.width)!, height: (self.scene?.size.height)!)
//background.anchorPoint = self.anchorPoint
background.position = CGPoint(x: CGFloat(i) * background.size.width, y: 0))
</code>```

Body:
Im attempting to create a constantly moving background by cycling 2 sprites. Running my code shows that the sprites have been added in the correct positions in the correct size. Yet the sprites aren't visible on screen. Why is this the case? My code below

import SpriteKit
import GameplayKit
import CoreMotion

class GameScene: SKScene, SKPhysicsContactDelegate{

    var ship = SKSpriteNode()
    var actionMoveRight = SKAction()
    var actionMoveLeft = SKAction()
    let shipCategory = 0x1 << 1
    let obstacleCategory = 0x1 << 2
    let backgroundVelocity : CGFloat = 3.0
    var motionManager = CMMotionManager()
    var background = SKSpriteNode.init(imageNamed: "background")

    override func didMove(to view: SKView) {
        // Making self delegate of physics world)
        self.anchorPoint = CGPoint.init(x: 0.5, y: 0.5)
        self.physicsWorld.gravity = CGVector.zero
        self.physicsWorld.contactDelegate = self
        createBG()
        addShip()
    }

    override func update(_ currentTime: CFTimeInterval) {
        moveBG()
    }

    func createBG(){
        for i in 0...2{
            background = SKSpriteNode.init(imageNamed: "background")
            background.name = "background"
            background.size = CGSize.init(width: (self.scene?.size.width)!, height: (self.scene?.size.height)!)
            background.anchorPoint = self.anchorPoint
            background.position = CGPoint.init(x: CGFloat(i) * background.size.width, y: (-(self.frame.size.height/2)))
            background.zPosition = 0
            self.addChild(background)
        }
    }

    func moveBG(){
        self.enumerateChildNodes(withName: "background", using: ({
            (node, error) in

            node.position.x -= 10
            if node.position.x < (self.scene?.size.width)!{
                node.position.x += (self.scene?.size.width)! * 2
            }
        }))
    }

    func addShip() {
        // Initializing spaceship node
        ship = SKSpriteNode(imageNamed: "Spaceship")
        ship.setScale(0.2)
        ship.isHidden = false
        ship.zRotation = CGFloat(0)
        // Adding SpriteKit physics body for collision detection
        ship.physicsBody = SKPhysicsBody(rectangleOf: ship.size)
        ship.physicsBody?.categoryBitMask = UInt32(shipCategory)
        ship.physicsBody?.isDynamic = true
        ship.physicsBody?.contactTestBitMask = UInt32(obstacleCategory)
        ship.physicsBody?.collisionBitMask = 0
        ship.name = "ship"
        ship.position = CGPoint.init(x: 0, y: (-(self.frame.size.height/2)) + ship.size.height/2)
        ship.zPosition = 1
        self.addChild(ship)
        actionMoveRight = SKAction.moveBy(x: 5, y: 0, duration: 0.2) //9
        actionMoveLeft = SKAction.moveBy(x: -5  , y: 0, duration: 0.2) //10
        if motionManager.isAccelerometerAvailable == true {
            motionManager.startAccelerometerUpdates(to: OperationQueue.current!, withHandler:{
                data, error in
                if (data!.acceleration.y) < -0.05 {
                    self.ship.run(self.actionMoveLeft)
                }

                else if data!.acceleration.y > 0.05 {
                    self.ship.run(self.actionMoveRight)
                }

            })

        }
    }
}

Body:
I assume that the background node size is just the same as the image size.  I also assume that the scene size is the same as the image size.  If that's the case, try the following.

let backTexture = SKTexture(imageNamed: "background")
let background = SKSpriteNode(texture: backTexture)
//background.size = CGSize.init(width: (self.scene?.size.width)!, height: (self.scene?.size.height)!)
//background.anchorPoint = self.anchorPoint
background.position = CGPoint(x: CGFloat(i) * background.size.width, y: 0))


问:
I'm trying to write a recursive static method with a helper in order to reverse a string. Why am I getting "stack overflow?"
So as the title says, I want to write a static method in Java that takes a String (like "hello!") and reverses it using a helper recursive method. However, I get stack overflow errors. My code is:

```<code>  public static String reverse2(String text){
    return reverseHelp(text, "", text.length()-1);
  }

  public static String reverseHelp(String text, String newString, int index) {
    if(index <= 0){
      return newString;
    }
    else
    {
      index = text.length()-1;
      return newString = text.charAt(index) + reverseHelp(text, newString, index - 1);
    }

  }
</code>```

What I'm trying to do is append the last character to the new string. How can I get this to work?

答:
The reason why your solution did not work out because your methods are static but your variable String text is behaving local & therefore text.length() - 1
would give the same value each time resulting in stack overflow.

If you make your text variable as static class member & use  it

OR even better if you make

int len = text.length()

as static member and use len in place of text.length()
your code will work.

Body:
So as the title says, I want to write a static method in Java that takes a String (like "hello!") and reverses it using a helper recursive method. However, I get stack overflow errors. My code is:

  public static String reverse2(String text){
    return reverseHelp(text, "", text.length()-1);
  }

  public static String reverseHelp(String text, String newString, int index) {
    if(index <= 0){
      return newString;
    }
    else
    {
      index = text.length()-1;
      return newString = text.charAt(index) + reverseHelp(text, newString, index - 1);
    }

  }

What I'm trying to do is append the last character to the new string. How can I get this to work?


问:
MySQL : search multiple columns with a single statement
I have a MySQL(5.7) table like this.

```<code>+--------+--------------+--------+-------+----------+--------+
| Field  | Type         | Null   | Key   | Default  | Extra  |
|--------+--------------+--------+-------+----------+--------|
| colA   | varchar(50)  | NO     | PRI   | <null>   |        |
| colB   | int(11)      | YES    |       | <null>   |        |
| colC   | int(11)      | YES    |       | <null>   |        |
| colD   | int(11)      | YES    |       | <null>   |        |
| colE   | int(11)      | YES    |       | <null>   |        |
| colF   | int(11)      | YES    |       | <null>   |        |
| colG   | int(11)      | YES    |       | <null>   |        |
| colH   | int(11)      | YES    |       | <null>   |        |
| colI   | int(11)      | YES    |       | <null>   |        |
| colJ   | int(11)      | YES    |       | <null>   |        |
| colK   | int(11)      | YES    |       | <null>   |        |
| colL   | int(11)      | YES    |       | <null>   |        |
| colM   | int(11)      | YES    |       | <null>   |        |
</code>```

I would like to search all the colB, colC, ..., colM mod 100 is 1 or 2. I know I can do this with this.

```<code>SELECT * FROM MYTABLE WHERE
(mod(colB, 100) = 1 OR mod(colB, 100) = 2) AND
(mod(colC, 100) = 1 OR mod(colC, 100) = 2) AND
(mod(colD, 100) = 1 OR mod(colD, 100) = 2) AND
                 :
(mod(colM, 100) = 1 OR mod(colM, 100) = 2)
</code>```

This SQL is very long and inefficient. Can I do this more smart?

答:
You can do it like below:

```<code>SELECT * FROM MYTABLE WHERE
where mod(colB, 100) in (1, 2) AND
colB = colC AND colB = colD AND colB = colE ... etc
</code>```

Since you already check colB, as long as colB and other column is equals its means it should match with your first filter.

Body:
I have a MySQL(5.7) table like this.

+--------+--------------+--------+-------+----------+--------+
| Field  | Type         | Null   | Key   | Default  | Extra  |
|--------+--------------+--------+-------+----------+--------|
| colA   | varchar(50)  | NO     | PRI   | <null>   |        |
| colB   | int(11)      | YES    |       | <null>   |        |
| colC   | int(11)      | YES    |       | <null>   |        |
| colD   | int(11)      | YES    |       | <null>   |        |
| colE   | int(11)      | YES    |       | <null>   |        |
| colF   | int(11)      | YES    |       | <null>   |        |
| colG   | int(11)      | YES    |       | <null>   |        |
| colH   | int(11)      | YES    |       | <null>   |        |
| colI   | int(11)      | YES    |       | <null>   |        |
| colJ   | int(11)      | YES    |       | <null>   |        |
| colK   | int(11)      | YES    |       | <null>   |        |
| colL   | int(11)      | YES    |       | <null>   |        |
| colM   | int(11)      | YES    |       | <null>   |        |

I would like to search all the colB, colC, ..., colM mod 100 is 1 or 2. I know I can do this with this.

SELECT * FROM MYTABLE WHERE
(mod(colB, 100) = 1 OR mod(colB, 100) = 2) AND
(mod(colC, 100) = 1 OR mod(colC, 100) = 2) AND
(mod(colD, 100) = 1 OR mod(colD, 100) = 2) AND
                 :
(mod(colM, 100) = 1 OR mod(colM, 100) = 2)

This SQL is very long and inefficient. Can I do this more smart?

Body:
You can do it like below:

SELECT * FROM MYTABLE WHERE
where mod(colB, 100) in (1, 2) AND
colB = colC AND colB = colD AND colB = colE ... etc

Since you already check colB, as long as colB and other column is equals its means it should match with your first filter.


问:
Unregister service from unity
I'm using Unity within my application. For one integration test, we want to change one of the service registered to the application(because it would require some hardware).

So, I'm able to Register the new "mock" type, but I'm unable to remove the other implementation registered for this interface.

Also to mention, currently we register a "list" of this interface(it's some kind of driver) and we would like to remove all the others instance.

Any idea how I could do this?

答:
I'm assuming you are not using Container.IsRegistered in your tests (which is not always a valid assumption).

A similar approach to @Tipx answer is to re-register but provide an InjectionMember that will clear all of the policies associated with the type.  This has the benefit that, since the policy configuration has been removed, Unity should work as if the types were never registered (even though they will appear in the Registrations list).

Here's the InjectionMember ClearAllPolicies which clears the policies:

```<code>public class ClearAllPolicies : InjectionMember
{
    public override void AddPolicies(Type serviceType, Type implementationType, string name, IPolicyList policies)
    {
        var serviceTypeBuildKey = new NamedTypeBuildKey(serviceType, name);
        policies.Clear<IBuildKeyMappingPolicy>(serviceTypeBuildKey);

        var buildKey = new NamedTypeBuildKey(implementationType, name);

        policies.Clear<IBuildKeyMappingPolicy>(buildKey);
        policies.Clear<IConstructorSelectorPolicy>(buildKey);
        policies.Clear<IBuildPlanCreatorPolicy>(buildKey);
        policies.Clear<IBuildPlanPolicy>(buildKey);
        policies.Clear<IMethodSelectorPolicy>(buildKey);
        policies.Clear<IPropertySelectorPolicy>(buildKey);
        policies.Clear<ILifetimeFactoryPolicy>(buildKey);
        policies.Clear<ILifetimePolicy>(buildKey);
        policies.Clear<IBuilderPolicy>(buildKey);

        DependencyResolverTrackerPolicy.RemoveResolvers(policies, buildKey);
    }
}
</code>```

Here's an example where 3 ILogger named implementations are registered and a list of ILoggers is resolved.  Then the polices are cleared for the loggers and a check is done to ensure that ILogger can't be resolved:

```<code>IUnityContainer container = new UnityContainer();

container.RegisterType<ILogger, MyLogger>("Logger1");
container.RegisterType<ILogger, MyLogger>("Logger2");
container.RegisterType<ILogger, MyLogger>("Logger3");

// Resolve list of all loggers
var loggers = container.Resolve<ILogger[]>();

// Remove Policies for all ILoggers using ClearAllPolicies
foreach (var registration in container.Registrations
                                      .Where(r => r.RegisteredType == typeof(ILogger)))
{
    container.RegisterType(
       registration.RegisteredType,
       registration.MappedToType,
       registration.Name,
       new ClearAllPolicies());
}

// Ensure that when we try to resolve an ILogger or list of ILogger's that
// an exception is thrown
Assert.Throws<ResolutionFailedException>(() => container.Resolve<ILogger>("Logger1"));
Assert.Throws<ResolutionFailedException>(() => container.Resolve<ILogger>("Logger2"));
Assert.Throws<ResolutionFailedException>(() => container.Resolve<ILogger>("Logger3"));
Assert.Throws<ResolutionFailedException>(() => container.Resolve<ILogger[]>());
</code>```

Caveats & Warnings

Do not use this in production code -- I would only use this for testing purposes

It's possible that this does not capture all of the applicable policies and is not complete or does not work for every edge case (e.g. Interception or other esoteric scenarios)

Title: Unregister service from unity

Body:
I'm assuming you are not using Container.IsRegistered in your tests (which is not always a valid assumption).

A similar approach to @Tipx answer is to re-register but provide an InjectionMember that will clear all of the policies associated with the type.  This has the benefit that, since the policy configuration has been removed, Unity should work as if the types were never registered (even though they will appear in the Registrations list).

Here's the InjectionMember ClearAllPolicies which clears the policies:

public class ClearAllPolicies : InjectionMember
{
    public override void AddPolicies(Type serviceType, Type implementationType, string name, IPolicyList policies)
    {
        var serviceTypeBuildKey = new NamedTypeBuildKey(serviceType, name);
        policies.Clear<IBuildKeyMappingPolicy>(serviceTypeBuildKey);

        var buildKey = new NamedTypeBuildKey(implementationType, name);

        policies.Clear<IBuildKeyMappingPolicy>(buildKey);
        policies.Clear<IConstructorSelectorPolicy>(buildKey);
        policies.Clear<IBuildPlanCreatorPolicy>(buildKey);
        policies.Clear<IBuildPlanPolicy>(buildKey);
        policies.Clear<IMethodSelectorPolicy>(buildKey);
        policies.Clear<IPropertySelectorPolicy>(buildKey);
        policies.Clear<ILifetimeFactoryPolicy>(buildKey);
        policies.Clear<ILifetimePolicy>(buildKey);
        policies.Clear<IBuilderPolicy>(buildKey);

        DependencyResolverTrackerPolicy.RemoveResolvers(policies, buildKey);
    }
}

Here's an example where 3 ILogger named implementations are registered and a list of ILoggers is resolved.  Then the polices are cleared for the loggers and a check is done to ensure that ILogger can't be resolved:

IUnityContainer container = new UnityContainer();

container.RegisterType<ILogger, MyLogger>("Logger1");
container.RegisterType<ILogger, MyLogger>("Logger2");
container.RegisterType<ILogger, MyLogger>("Logger3");

// Resolve list of all loggers
var loggers = container.Resolve<ILogger[]>();

// Remove Policies for all ILoggers using ClearAllPolicies
foreach (var registration in container.Registrations
                                      .Where(r => r.RegisteredType == typeof(ILogger)))
{
    container.RegisterType(
       registration.RegisteredType,
       registration.MappedToType,
       registration.Name,
       new ClearAllPolicies());
}

// Ensure that when we try to resolve an ILogger or list of ILogger's that
// an exception is thrown
Assert.Throws<ResolutionFailedException>(() => container.Resolve<ILogger>("Logger1"));
Assert.Throws<ResolutionFailedException>(() => container.Resolve<ILogger>("Logger2"));
Assert.Throws<ResolutionFailedException>(() => container.Resolve<ILogger>("Logger3"));
Assert.Throws<ResolutionFailedException>(() => container.Resolve<ILogger[]>());

Caveats & Warnings

Do not use this in production code -- I would only use this for testing purposes

It's possible that this does not capture all of the applicable policies and is not complete or does not work for every edge case (e.g. Interception or other esoteric scenarios)


问:
unique column value per row
I find it best to use an example, so here we go:

Say I have a table with chores and a table with a weekly schedule like this:

```<code>CHORES:
|----+---------------+----------+-------|
| id |      name     |   type   | hours |
|----+---------------+----------+-------|
| 1  | clean kitchen | cleaning |   4   |
|----+---------------+----------+-------|
| 2  | clean toilet  | cleaning |   3   |
etc

SCHEDULE:
|------+---------------+---------------+-----|
| week |     monday    |    tuesday    | etc |
|------+---------------+---------------+-----|
|   1  | clean kitchen | clean toilet  | etc |
|------+---------------+---------------+-----|
|   2  | clean toilet  | clean kitchen | etc |
etc
</code>```

I want  to make sure that for one week, you can't have duplicate cells, so this wouldn't be allowed:

```<code>SCHEDULE:
|------+---------------+--------------+-----|
| week |     monday    |   tuesday    | etc |
|------+---------------+--------------+-----|
|   1  | clean toilet  | clean toilet | etc |

etc
</code>```

What would I have to do  in my models.py to get this behaviour?

答:
Try django unique-together in model meta option.
https://docs.djangoproject.com/en/1.11/ref/models/options/#unique-together</p>

Title: unique column value per row

Body:
I find it best to use an example, so here we go:

Say I have a table with chores and a table with a weekly schedule like this:

CHORES:
|----+---------------+----------+-------|
| id |      name     |   type   | hours |
|----+---------------+----------+-------|
| 1  | clean kitchen | cleaning |   4   |
|----+---------------+----------+-------|
| 2  | clean toilet  | cleaning |   3   |
etc

SCHEDULE:
|------+---------------+---------------+-----|
| week |     monday    |    tuesday    | etc |
|------+---------------+---------------+-----|
|   1  | clean kitchen | clean toilet  | etc |
|------+---------------+---------------+-----|
|   2  | clean toilet  | clean kitchen | etc |
etc

I want  to make sure that for one week, you can't have duplicate cells, so this wouldn't be allowed:

SCHEDULE:
|------+---------------+--------------+-----|
| week |     monday    |   tuesday    | etc |
|------+---------------+--------------+-----|
|   1  | clean toilet  | clean toilet | etc |

etc

What would I have to do  in my models.py to get this behaviour?


问:
Python ValueError: Invalid literal for int () with base 10
I keep getting this error in line 87: " words[w][0]+=(int(word[0]))
ValueError: invalid literal for int() with base 10: ''"

I can't seem to figure out what the issue is any help would be appreciated.

```<code>#get a word from the user to analyze
word=str.lower(input("Enter a word to test: "))

#open up all of the movie reviews
file=open("movie_reviews.txt","r")

alldata=str.lower(file.read())

file.close()

#create accumulators
total=0
numreviews=0

#split data into a list
splitreviews=alldata.split("\n")

#iterate over each review
for review in splitreviews:

    #further split the review into individual words

    words=review.split(" ")

    if word in words:

        total+=int(words[0])

        numreviews+=1
#determine average and if positive or negative or not enough info
if numreviews==0:
    print(word,"appears",numreviews,"times")
    print("There is no average score for reviews containing the word",word)
    print("Cannot determine if this word is positive or negative")
else:
    print(word,"appears",numreviews,"times")
    print("Total score was:",total)
    print("Average score for this word is:",total/numreviews)

    if total/numreviews>=2:
        print("This is a POSITIVE word!")
    else:
        print("This is a NEGATIVE word!")

#set up an empty dictionary to hold all words
words={}

#import time
import time

t=time.time()
print("Initializing sentiment database")

#open up all of movie reviews
file=open("movie_reviews.txt","r")

alldata=str.lower(file.read())

file.close()

splitreviews=alldata.split("\n")

total=0
for review in splitreviews:

    word=review.split(" ")

    #examine every word in this review
    #add it to the sentiment dictionary if necessary
    #or update it if it already exists
    for w in word:

        if w not in words:
            #add it to the dictionary!
            words[w]=[int(word[0]),1]
            total+=1

        else:
            #update the word using the new review
            words[w][1]+=1
            words[w][0]+=(str(word[0]))

#all done

print("Sentiment database initialization complete")
print("Total unique words analyzed:",total)
print("Analysis took",time.time()-t,"seconds to complete")

phrase=str.lower(input("Enter a phrase to test: "))

phraseparts=phrase.split(" ")

totalaverage=0
num=0

#iterate over each element of phrase pulling info from dictionary
for p in phraseparts:
    if p not in words:
        print("*",p,"does not appear in any movie reviews")
    else:
        num+=1
        print("*",p,"appears",words[p][1],"times with an average score of",words[p][0]/words[p][1])
        totalaverage+=words[p][0]/words[p][1]

if num==0:
    print("Not enough words to determine sentiment.")

#determine average if words in the phrace appear in the dictionary
else:
    print("Average score for this phrase is: ",totalaverage/num)

#determine if it's a positive or negative word
    if totalaverage/num>=2:
        print("This is a POSITIVE phrase")
    else:
        print("This is a NEGATIVE phrase")
</code>```

For reference the file moviereviews.txt looks like this:

```<code>1 A series of escapades demonstrating the adage that what is good for the goose is also good for the gander , some of which occasionally amuses but none of which amounts to much of a story .
4 This quiet , introspective and entertaining independent is worth seeking .
1 Even fans of Ismail Merchant 's work , I suspect , would have a hard time sitting through this one .
3 A positively thrilling combination of ethnography and all the intrigue , betrayal , deceit and murder of a Shakespearean tragedy or a juicy soap opera .
1 Aggressive self-glorification and a manipulative whitewash .
4 A comedy-drama of nearly epic proportions rooted in a sincere performance by the title character undergoing midlife crisis .
1 Narratively , Trouble Every Day is a plodding mess .
3 The Importance of Being Earnest , so thick with wit it plays like a reading from Bartlett 's Familiar Quotations
1 But it does n't leave you with much .
1 You could hate it for the same reason .
</code>```

答:
It may be a bit hard to help you with the information I have so here is a working example of what I think you are trying to do.

```<code>string = "This movie sucks so badly, it is the worst thing I have seen in my entire life"

score = 0

positive = ["good", "best", "happy", "happiest", "amazing", "perfect"]
negative = ["bad", "worst", "sad", "saddest", "stupid", "disgusting"]

words = string.split(" ")

for i in words:
    if any(i in item for item in positive):
        score += 1

    if any(i in item for item in negative):
        score -= 1

if score == 0:
    print("Not enough words to determine sentiment")

if score > 0:
    print("Happy with a score of:", score)
else:
    print("Sad with a score of:", score)
</code>```

I know this question is very old but other people may need this.

Body:
I keep getting this error in line 87: " words[w][0]+=(int(word[0]))
ValueError: invalid literal for int() with base 10: ''"

I can't seem to figure out what the issue is any help would be appreciated.

#get a word from the user to analyze
word=str.lower(input("Enter a word to test: "))

#open up all of the movie reviews
file=open("movie_reviews.txt","r")

alldata=str.lower(file.read())

file.close()

#create accumulators
total=0
numreviews=0

#split data into a list
splitreviews=alldata.split("\n")

#iterate over each review
for review in splitreviews:

    #further split the review into individual words

    words=review.split(" ")

    if word in words:

        total+=int(words[0])

        numreviews+=1
#determine average and if positive or negative or not enough info
if numreviews==0:
    print(word,"appears",numreviews,"times")
    print("There is no average score for reviews containing the word",word)
    print("Cannot determine if this word is positive or negative")
else:
    print(word,"appears",numreviews,"times")
    print("Total score was:",total)
    print("Average score for this word is:",total/numreviews)

    if total/numreviews>=2:
        print("This is a POSITIVE word!")
    else:
        print("This is a NEGATIVE word!")

#set up an empty dictionary to hold all words
words={}

#import time
import time

t=time.time()
print("Initializing sentiment database")

#open up all of movie reviews
file=open("movie_reviews.txt","r")

alldata=str.lower(file.read())

file.close()

splitreviews=alldata.split("\n")

total=0
for review in splitreviews:

    word=review.split(" ")

    #examine every word in this review
    #add it to the sentiment dictionary if necessary
    #or update it if it already exists
    for w in word:

        if w not in words:
            #add it to the dictionary!
            words[w]=[int(word[0]),1]
            total+=1

        else:
            #update the word using the new review
            words[w][1]+=1
            words[w][0]+=(str(word[0]))

#all done

print("Sentiment database initialization complete")
print("Total unique words analyzed:",total)
print("Analysis took",time.time()-t,"seconds to complete")

phrase=str.lower(input("Enter a phrase to test: "))

phraseparts=phrase.split(" ")

totalaverage=0
num=0

#iterate over each element of phrase pulling info from dictionary
for p in phraseparts:
    if p not in words:
        print("*",p,"does not appear in any movie reviews")
    else:
        num+=1
        print("*",p,"appears",words[p][1],"times with an average score of",words[p][0]/words[p][1])
        totalaverage+=words[p][0]/words[p][1]

if num==0:
    print("Not enough words to determine sentiment.")

#determine average if words in the phrace appear in the dictionary
else:
    print("Average score for this phrase is: ",totalaverage/num)

#determine if it's a positive or negative word
    if totalaverage/num>=2:
        print("This is a POSITIVE phrase")
    else:
        print("This is a NEGATIVE phrase")

For reference the file moviereviews.txt looks like this:

1 A series of escapades demonstrating the adage that what is good for the goose is also good for the gander , some of which occasionally amuses but none of which amounts to much of a story .
4 This quiet , introspective and entertaining independent is worth seeking .
1 Even fans of Ismail Merchant 's work , I suspect , would have a hard time sitting through this one .
3 A positively thrilling combination of ethnography and all the intrigue , betrayal , deceit and murder of a Shakespearean tragedy or a juicy soap opera .
1 Aggressive self-glorification and a manipulative whitewash .
4 A comedy-drama of nearly epic proportions rooted in a sincere performance by the title character undergoing midlife crisis .
1 Narratively , Trouble Every Day is a plodding mess .
3 The Importance of Being Earnest , so thick with wit it plays like a reading from Bartlett 's Familiar Quotations
1 But it does n't leave you with much .
1 You could hate it for the same reason .

Body:
It may be a bit hard to help you with the information I have so here is a working example of what I think you are trying to do.

string = "This movie sucks so badly, it is the worst thing I have seen in my entire life"

score = 0

positive = ["good", "best", "happy", "happiest", "amazing", "perfect"]
negative = ["bad", "worst", "sad", "saddest", "stupid", "disgusting"]

words = string.split(" ")

for i in words:
    if any(i in item for item in positive):
        score += 1

    if any(i in item for item in negative):
        score -= 1

if score == 0:
    print("Not enough words to determine sentiment")

if score > 0:
    print("Happy with a score of:", score)
else:
    print("Sad with a score of:", score)

I know this question is very old but other people may need this.


问:
Joining table into 4 columns
I've a problem to show 4 different columns from different table, for more detail, let see in the below :

Table personal (tbl_personal)

```<code>+---+-----+------------+
|ID |Name |Skill       |
+---+-----+------------+
| 1 | Nia | Accountant |
| 2 | Tia | Banking    |
| 3 | Ria | Technicall |
| 4 | Dia | Admin      |
+---+-----+------------+
</code>```

Table master (tbl_master)

```<code>+---+---------+---------+
|ID |Employee1|Employee2|
+---+---------+---------+
| 1 | 1       | 2       |
| 2 | 2       | 1       |
| 3 | 3       | 4       |
+---+---------+---------+
</code>```

I want to show into web page from tbl_master above in codeigniter like this :

```<code>+---+-------+-----------+-------+-----------+
|ID |Name 1 |Skill 1    |Name 2 |Skill 2    |
+---+-------+-----------+-------+-----------+
| 1 | Nia   | Accountant| Tia   | Banking   |
| 2 | Tia   | Banking   | Nia   | Accountant|
| 3 | Ria   | Technicall| Dia   | Admin     |
+---+---------+---------+-------+-----------+
</code>```

Please advice if any suggestion for me to join from tbl_personal with tbl_master,

Thanks for your support...

答:
you need to join two time personal table. like below </p>

```<code>select tp1.name name1,tp1.skill skill1,tp2.name name2,tp2.skill skill2
from tbl_master tm
join tbl_personal tp1
on tm.Employee1 =tp1.ID
join tbl_personal tp2
on tm.Employee2 =tp2.ID
</code>```

Title: Joining table into 4 columns

Body:
I've a problem to show 4 different columns from different table, for more detail, let see in the below :

Table personal (tbl_personal)

+---+-----+------------+
|ID |Name |Skill       |
+---+-----+------------+
| 1 | Nia | Accountant |
| 2 | Tia | Banking    |
| 3 | Ria | Technicall |
| 4 | Dia | Admin      |
+---+-----+------------+

Table master (tbl_master)

+---+---------+---------+
|ID |Employee1|Employee2|
+---+---------+---------+
| 1 | 1       | 2       |
| 2 | 2       | 1       |
| 3 | 3       | 4       |
+---+---------+---------+

I want to show into web page from tbl_master above in codeigniter like this :

+---+-------+-----------+-------+-----------+
|ID |Name 1 |Skill 1    |Name 2 |Skill 2    |
+---+-------+-----------+-------+-----------+
| 1 | Nia   | Accountant| Tia   | Banking   |
| 2 | Tia   | Banking   | Nia   | Accountant|
| 3 | Ria   | Technicall| Dia   | Admin     |
+---+---------+---------+-------+-----------+

Please advice if any suggestion for me to join from tbl_personal with tbl_master,

Thanks for your support...

Body:
you need to join two time personal table. like below

select tp1.name name1,tp1.skill skill1,tp2.name name2,tp2.skill skill2
from tbl_master tm
join tbl_personal tp1
on tm.Employee1 =tp1.ID
join tbl_personal tp2
on tm.Employee2 =tp2.ID


问:
document.removeEventListner not removing event in reactjs
uI have react component, I use componentDidMount lifecycle hook to bind mousedown event to document. When mouse down event triggering I bind two more events mousemove and mouseup to document also I remove those events at mouseup event.

My problem is when mouseup event triggering it suppose to remove mousemove and mouseup but its not working. Instead each time I click the page mouseup triggering multiple times like: 1, 3, 6, 10, 15... it's multiplying.

When componentWillUnmount also not removing event from document.

```<code>import React, { Component } from 'react'

class SandBox extends Component{
    componentDidMount(){
        document.addEventListener('mousedown', this.mouseDown.bind(this))
    }

    //mouseDown
    mouseDown(){
        document.addEventListener('mouseup', this.mouseUp.bind(this))
        document.addEventListener('mousemove', this.mouseMove.bind(this))
    }

    //mouseUp
    mouseUp(){
        // this is not removing the events from document
        document.removeEventListener('mouseup', this.mouseUp, false)
        document.removeEventListener('mousemove', this.mouseMove, false)
        // this triggers 1,3,6,10,15 times
        console.log('mose up')
    }

    moseMove(){
        // mosemoveCodes
    }

}
</code>```

答:
When you bind on function it will make new function and you cant reference old this.whatever thats why removeEventlistener cannot find your function. you can fix this with using es6 class constructor.

```<code>class YourComponent extends Component {
   constructor(props){
     super(props)
     //bind and reference your methods here
     this.mouseDown = this.mouseDown.bind(this)
     this.mouseUp = this.mouseUp.bind(this)
     this.mouseMove = this.mouseMove.bind(this)
     // now its pointing corectcly
   }
   // lifecycle
   componentDidMount(){
     document.addEventListener('mousedown', this.mouseDown.bind(this))
   }
   //mouseDown
   mouseDown(){
     document.addEventListener('mouseup', this.mouseUp)
     document.addEventListener('mousemove', this.mouseMove)
   }

   //mouseUp
   mouseUp(){
     // this is will work
     document.removeEventListener('mouseup', this.mouseUp, false)
     document.removeEventListener('mousemove', this.mouseMove, false)

     console.log('mouse up')
   }
    // unmount
   componentWillUnmount(){
     // this is will work
     document.removeEventListener('mousedown', this.mouseDown, false)
   }
}
</code>```

Body:
uI have react component, I use componentDidMount lifecycle hook to bind mousedown event to document. When mouse down event triggering I bind two more events mousemove and mouseup to document also I remove those events at mouseup event.

My problem is when mouseup event triggering it suppose to remove mousemove and mouseup but its not working. Instead each time I click the page mouseup triggering multiple times like: 1, 3, 6, 10, 15... it's multiplying.

When componentWillUnmount also not removing event from document.

import React, { Component } from 'react'

class SandBox extends Component{
    componentDidMount(){
        document.addEventListener('mousedown', this.mouseDown.bind(this))
    }

    //mouseDown
    mouseDown(){
        document.addEventListener('mouseup', this.mouseUp.bind(this))
        document.addEventListener('mousemove', this.mouseMove.bind(this))
    }

    //mouseUp
    mouseUp(){
        // this is not removing the events from document
        document.removeEventListener('mouseup', this.mouseUp, false)
        document.removeEventListener('mousemove', this.mouseMove, false)
        // this triggers 1,3,6,10,15 times
        console.log('mose up')
    }

    moseMove(){
        // mosemoveCodes
    }

}

Body:
When you bind on function it will make new function and you cant reference old this.whatever thats why removeEventlistener cannot find your function. you can fix this with using es6 class constructor.

class YourComponent extends Component {
   constructor(props){
     super(props)
     //bind and reference your methods here
     this.mouseDown = this.mouseDown.bind(this)
     this.mouseUp = this.mouseUp.bind(this)
     this.mouseMove = this.mouseMove.bind(this)
     // now its pointing corectcly
   }
   // lifecycle
   componentDidMount(){
     document.addEventListener('mousedown', this.mouseDown.bind(this))
   }
   //mouseDown
   mouseDown(){
     document.addEventListener('mouseup', this.mouseUp)
     document.addEventListener('mousemove', this.mouseMove)
   }

   //mouseUp
   mouseUp(){
     // this is will work
     document.removeEventListener('mouseup', this.mouseUp, false)
     document.removeEventListener('mousemove', this.mouseMove, false)

     console.log('mouse up')
   }
    // unmount
   componentWillUnmount(){
     // this is will work
     document.removeEventListener('mousedown', this.mouseDown, false)
   }
}


问:
c# classification inside datatable
I don't know exactly what is the correct term/way to explain my question but i hope someone get my idea

My datatable are required to classify few type of sources (ex in image) and i need to calculate them according to the type.. is there any way i can perform this?

Thank you so much for your reply

Here's what i've tried so far

```<code>  for (int l = 0; l < my_datatable.Rows.Count; l++)
        {

            data_source = my_datatable.Rows[l][3].ToString();

            if (data_source.Contains("Cross Site Scripting"))
            {
                my_datatable.Rows[l][3] = "2";
            }
            else if (data_source.Contains("SQL Injection"))
            {
                my_datatable.Rows[l][3] = "3";
            }
            else if (data_source.Contains("Unicode Attack"))
            {
                my_datatable.Rows[l][3] = "4";
            }
            else if (data_source.Contains("Proxy Attack"))
            {
                my_datatable.Rows[l][3] = "5";
            }
            else
            {
                my_datatable.Rows[l][3] = "1";
            }
</code>```

current output

expected output

Code for CSV part

```<code>        string[] raw_text =
        System.IO.File.ReadAllLines("C:\\dummylog3.csv"); //Placement of the
        .CSV Files
        string[] data_col = null;
        int x = 0;

        foreach (string text_line in raw_text)
        {
            //MessageBox.Show(text_line);
            data_col = text_line.Split(' ');

            if (x == 0)
            {
                for (int i = 0; i <= data_col.Count() - 1; i++)
                {
                    my_datatable.Columns.Add(data_col[i]);
                }

                x++;
            }
            else
            {

                my_datatable.Rows.Add(data_col);
            }

            my_datagridview.DataSource = my_datatable;
            this.Controls.Add(my_datagridview);
        }
</code>```

答:
Make sure your project has a reference to System.Data.DataSetExtensions.dll, if not then add it. You will need this to call 'CopyToDataTable` extension method.

Create a table for your summarized data. We will just use this to create new rows for the summary table. But the data will not be stored here. See next point:

```<code>var summary = new DataTable();
summary.Columns.Add("Code");
summary.Columns.Add("Source Type");
summary.Columns.Add("Number Of Hits", typeof(int));
</code>```

Using Linq, the code below will group the results by the Code and Source Type and then find the count of them. It will finally copy the data to a DataTable:

```<code>var result =
    table.AsEnumerable()
    .GroupBy(x => new { Code = x["Code"], SourceType = x["Source Type"] })
    .Select(x => summary.Rows.Add(x.Key.Code, x.Key.SourceType, x.Count()))
    .CopyToDataTable();
</code>```

Title: c# classification inside datatable

Body:
I don't know exactly what is the correct term/way to explain my question but i hope someone get my idea

My datatable are required to classify few type of sources (ex in image) and i need to calculate them according to the type.. is there any way i can perform this?

Thank you so much for your reply

Here's what i've tried so far

  for (int l = 0; l < my_datatable.Rows.Count; l++)
        {

            data_source = my_datatable.Rows[l][3].ToString();

            if (data_source.Contains("Cross Site Scripting"))
            {
                my_datatable.Rows[l][3] = "2";
            }
            else if (data_source.Contains("SQL Injection"))
            {
                my_datatable.Rows[l][3] = "3";
            }
            else if (data_source.Contains("Unicode Attack"))
            {
                my_datatable.Rows[l][3] = "4";
            }
            else if (data_source.Contains("Proxy Attack"))
            {
                my_datatable.Rows[l][3] = "5";
            }
            else
            {
                my_datatable.Rows[l][3] = "1";
            }

current output

expected output

Code for CSV part

        string[] raw_text =
        System.IO.File.ReadAllLines("C:\\dummylog3.csv"); //Placement of the
        .CSV Files
        string[] data_col = null;
        int x = 0;

        foreach (string text_line in raw_text)
        {
            //MessageBox.Show(text_line);
            data_col = text_line.Split(' ');

            if (x == 0)
            {
                for (int i = 0; i <= data_col.Count() - 1; i++)
                {
                    my_datatable.Columns.Add(data_col[i]);
                }

                x++;
            }
            else
            {

                my_datatable.Rows.Add(data_col);
            }

            my_datagridview.DataSource = my_datatable;
            this.Controls.Add(my_datagridview);
        }

Body:
Make sure your project has a reference to System.Data.DataSetExtensions.dll, if not then add it. You will need this to call 'CopyToDataTable` extension method.

Create a table for your summarized data. We will just use this to create new rows for the summary table. But the data will not be stored here. See next point:

var summary = new DataTable();
summary.Columns.Add("Code");
summary.Columns.Add("Source Type");
summary.Columns.Add("Number Of Hits", typeof(int));

Using Linq, the code below will group the results by the Code and Source Type and then find the count of them. It will finally copy the data to a DataTable:

var result =
    table.AsEnumerable()
    .GroupBy(x => new { Code = x["Code"], SourceType = x["Source Type"] })
    .Select(x => summary.Rows.Add(x.Key.Code, x.Key.SourceType, x.Count()))
    .CopyToDataTable();


问:
Use onmousedown to get the ID of the element you just mousedowned on?
Is this possible?

I am attempting to write a function for onmousedown that will return the ID of the element you just clicked for later use in recreating that element in a different div.

答:
Pls insert this code to your javascript.</p>

```<code>document.getElementById("article").onmouseup(handMu);
</code>```

Body:
Pls insert this code to your javascript.

document.getElementById("article").onmouseup(handMu);


问:
Will conditionals that are always false be removed by compiler in C#
Say I have the following code snippet in c#

```<code>static const bool DO_PERFORMANCE_CODE = false;

if (DO_PERFORMANCE_CODE)
{
   // performance monitoring code goes here
}
</code>```

Will that code get removed by the compiler? This is the functionality I'd like. Basically I want to mimic the conditional compilation stuff in C#, but I want more configurations other than Release and Debug. If there is a better way of doing this, I'd be open to hearing it.

答:
When you  build in "debug" the preprocessor variable DEBUG is defined. So, you can do this:

```<code>public void MyFunc()
{
//do release stuff
#if DEBUG
//do performance testing
#endif
//finish release stuff
}
</code>```

and it will be ignored by the compiler when you switch to Release mode.

Alternatively,  you can define your own preprocessor variable if you don't want to test in debug mode, making sure to "#define PERFORMANCE_TESTING" when you want to test, and commenting it out when you don't.

```<code>#define PERFORMANCE_TESTING

    public void MyFunc()
    {
    //do release stuff
    #if PERFORMANCE_TESTING
    //do performance testing
    #endif
    //finish release stuff
    }
</code>```

OwnerDisplayName: WindyCityEagle

Body:
Say I have the following code snippet in c#

static const bool DO_PERFORMANCE_CODE = false;

if (DO_PERFORMANCE_CODE)
{
   // performance monitoring code goes here
}

Will that code get removed by the compiler? This is the functionality I'd like. Basically I want to mimic the conditional compilation stuff in C#, but I want more configurations other than Release and Debug. If there is a better way of doing this, I'd be open to hearing it.

LastEditorDisplayName: Dana

Body:
When you  build in "debug" the preprocessor variable DEBUG is defined. So, you can do this:

public void MyFunc()
{
//do release stuff
#if DEBUG
//do performance testing
#endif
//finish release stuff
}

and it will be ignored by the compiler when you switch to Release mode.

Alternatively,  you can define your own preprocessor variable if you don't want to test in debug mode, making sure to "#define PERFORMANCE_TESTING" when you want to test, and commenting it out when you don't.

#define PERFORMANCE_TESTING

    public void MyFunc()
    {
    //do release stuff
    #if PERFORMANCE_TESTING
    //do performance testing
    #endif
    //finish release stuff
    }


问:
Regex to match any url in img tag
I need a regular expression that can match any url in img src tag

URL can vary from "/images/temp.jpg" or "temp1.jpg" or even "http://www.example.com/temp.jpg?i=123" or anything

I have written following code:

```<code>preg_match_all('/(href|src)\s*=\s*"([^\s]+\/\/[^\/]+.\/[^\s]+\.(jpg|jpeg|png|gif|bmp))/ixu'
</code>```

but it's not matching many urls including those with query string like ?i=12345

Anyone have idea how to achieve this?

Thanks

答:
You can use

```<code><img [^>]*src="([^"]+)"
</code>```

and take the first capturing group.

EDIT: By the way this assumes that you would not start a tag without properly closing it. Perhaps better is

```<code><img [^>]*src="([^"]+)"[^>]*>
</code>```

EDIT 2: It is unclear what you are trying to achieve, and I get the feeling I am wasting my time trying to help you. In your edit, you wrote that you tried:

```<code>preg_match_all('/(href|src)\s*=\s*"([^\s]+\/\/[^\/]+.\/[^\s]+\.(jpg|jpeg|png|gif|bmp))/ixu'
</code>```

Why is there no mention of img? Why do you include href, when img tags do not take the href attribute? It seems as though you are more interested in checking whether something is a valid image URL than in matching some URL that is specified inside an img tag. Note that the regex I provided does not check the validity of the URL; it just goes based on the fact that whatever appears in quotes in the src attribute is expected to be a valid URL. I did it this way because it is a practical assumption in many situations, and you weren't specific about what you really want. I will not update further if you can't ask a better question.

Title: Regex to match any url in img tag

Body:
I need a regular expression that can match any url in img src tag

URL can vary from "/images/temp.jpg" or "temp1.jpg" or even "http://www.example.com/temp.jpg?i=123" or anything

I have written following code:

preg_match_all('/(href|src)\s*=\s*"([^\s]+\/\/[^\/]+.\/[^\s]+\.(jpg|jpeg|png|gif|bmp))/ixu'

but it's not matching many urls including those with query string like ?i=12345

Anyone have idea how to achieve this?

Thanks

Body:
You can use

<img [^>]*src="([^"]+)"

and take the first capturing group.

EDIT: By the way this assumes that you would not start a tag without properly closing it. Perhaps better is

<img [^>]*src="([^"]+)"[^>]*>

EDIT 2: It is unclear what you are trying to achieve, and I get the feeling I am wasting my time trying to help you. In your edit, you wrote that you tried:

preg_match_all('/(href|src)\s*=\s*"([^\s]+\/\/[^\/]+.\/[^\s]+\.(jpg|jpeg|png|gif|bmp))/ixu'

Why is there no mention of img? Why do you include href, when img tags do not take the href attribute? It seems as though you are more interested in checking whether something is a valid image URL than in matching some URL that is specified inside an img tag. Note that the regex I provided does not check the validity of the URL; it just goes based on the fact that whatever appears in quotes in the src attribute is expected to be a valid URL. I did it this way because it is a practical assumption in many situations, and you weren't specific about what you really want. I will not update further if you can't ask a better question.


问:
CSS Resizing failure when browser window is scaled vertically
I am trying to create a simple login page, and after learning about CSS3 flexbox some time ago I redid the page using this new concept. So now, my page looks like this:

which is what I wanted...until I tried to resize the browser. Then, I got this (when I simply decreased the height of the browser window without decreasing the width):

and this (when I decreased both the height and the width of the browser window to a minimum):

This confused me since I read on other stackoverflow answers that I do not have to have media queries yet to create a responsive web design (which I do intend to do, later on), but just CSS by specifying the max-width in terms of percentages.

Here's my code:

HTML:

```<code><div class="center">
    <!-- Logo -->
    <img id="logo" src="assets/logowshadow.png" alt="cueclick logo">

    <!-- Login element -->
    <form class="login" action="/action_page.js" method="post">
        <p>Enter <i>your</i> secret key</p>
        <div id="password">
            <img id ="eye" src="assets/eye2.png" alt="eye">
            <input type="password" name="secret-key" placeholder="ilovecueclick" autofocus autocomplete="off"/>
        </div>
    </form>
</div>
</code>```

CSS:

```<code>/* -- Background image -- */
body {
    background-image: url(assets/wood.png);
    background-repeat: no-repeat;
    background-size: cover;
    background-attachment: fixed;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 100vh;
}

/* -- Center element -- */
.center {
    max-width: 60%;
    max-height: 80%;
    width: 30%;
    height: 40%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    background-color: rgba(255, 255, 255, 0.7);
    border-radius: 15%;
    box-shadow: 2px 2px 4px 3px #505050;
    position: absolute;
    z-index: 1;
}

/* -- Logo style -- */
#logo {
    position: relative;
    z-index: 2;
    max-width: 100%;
    height: auto;
}

/* -- Form styles -- */
form.login {
    max-width: 100%;
    height: auto;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    position: relative;
    z-index: 2;
}

#password {
    display: flex;
    flex-direction: row;
    align-items: center;
    margin-bottom: 5%;
}

/* -- Show password -- */
#eye {
    height: auto;
    max-width: 15%;
    margin-right: 3%;
}

/* -- Login element -- */
form.login p {
    font-family: Palatino, "Palatino Linotype", "Palatino LT STD", "Book Antiqua", Georgia, serif;
    font-size: 2vw;
    max-width: 100%;
    height: auto;
    line-height: 2%;
}

form.login input[type=password] {
    max-width: 100%;
    width: 100%;
    height: auto;
}
</code>```

To explain what this code is doing further:
- body has a full-size background image that scales with the browser window
- 'center' is essentially the translucent white rectangle above the background
- the logo and the form log-in elements overlap the white rectangle

I have also created three flex containers for their flex items (to deal with the troublesome issue of centering):
1) body is the flex container, and the flex item is the center element
2) center is the flex container, and the logo and the form input section (ie. the paragraph + eye + input field) are the flex items
3) the 'password' div is the flex container (in-line), and the eye and login field are the flex items

I am really unsure where the issue lies, since there seems to be some scaling achieved with the current code...

The full HTML can be found here: https://pastebin.com/6tS6SXi3, and the full CSS can be found here: https://pastebin.com/6M11HnJE

Thanks in advance!

EDIT:

After experimenting further, it turns out that I simply had to let the height of the center class be auto...

Accepted the answer for its simplicity even though it does not use flex-box like I would have wanted it to

答:
Construct your form wrapper with HTML and CSS instead of using an image, which is very hard to control when screen size changes.

Sample:
https://codepen.io/anon/pen/NgPGoQ

```<code>.login {
  width: 300px;
}

@media screen and (max-width: 768px) {
  .login {
    width: 80%;
  }
}
</code>```

Set a default width for your wrapper and add media queries for the screen sizes that you would like a custom width.

Body:
I am trying to create a simple login page, and after learning about CSS3 flexbox some time ago I redid the page using this new concept. So now, my page looks like this:

which is what I wanted...until I tried to resize the browser. Then, I got this (when I simply decreased the height of the browser window without decreasing the width):

and this (when I decreased both the height and the width of the browser window to a minimum):

This confused me since I read on other stackoverflow answers that I do not have to have media queries yet to create a responsive web design (which I do intend to do, later on), but just CSS by specifying the max-width in terms of percentages.

Here's my code:

HTML:

    <form class="login" action="/action_page.js" method="post">

Enter your secret key

            <input type="password" name="secret-key" placeholder="ilovecueclick" autofocus autocomplete="off"/>

    </form>

CSS:

/* -- Background image -- */
body {
    background-image: url(assets/wood.png);
    background-repeat: no-repeat;
    background-size: cover;
    background-attachment: fixed;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 100vh;
}

/* -- Center element -- */
.center {
    max-width: 60%;
    max-height: 80%;
    width: 30%;
    height: 40%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    background-color: rgba(255, 255, 255, 0.7);
    border-radius: 15%;
    box-shadow: 2px 2px 4px 3px #505050;
    position: absolute;
    z-index: 1;
}

/* -- Logo style -- */
#logo {
    position: relative;
    z-index: 2;
    max-width: 100%;
    height: auto;
}

/* -- Form styles -- */
form.login {
    max-width: 100%;
    height: auto;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    position: relative;
    z-index: 2;
}

#password {
    display: flex;
    flex-direction: row;
    align-items: center;
    margin-bottom: 5%;
}

/* -- Show password -- */
#eye {
    height: auto;
    max-width: 15%;
    margin-right: 3%;
}

/* -- Login element -- */
form.login p {
    font-family: Palatino, "Palatino Linotype", "Palatino LT STD", "Book Antiqua", Georgia, serif;
    font-size: 2vw;
    max-width: 100%;
    height: auto;
    line-height: 2%;
}

form.login input[type=password] {
    max-width: 100%;
    width: 100%;
    height: auto;
}

To explain what this code is doing further:
- body has a full-size background image that scales with the browser window
- 'center' is essentially the translucent white rectangle above the background
- the logo and the form log-in elements overlap the white rectangle

I have also created three flex containers for their flex items (to deal with the troublesome issue of centering):
1) body is the flex container, and the flex item is the center element
2) center is the flex container, and the logo and the form input section (ie. the paragraph + eye + input field) are the flex items
3) the 'password' div is the flex container (in-line), and the eye and login field are the flex items

I am really unsure where the issue lies, since there seems to be some scaling achieved with the current code...

The full HTML can be found here: https://pastebin.com/6tS6SXi3, and the full CSS can be found here: https://pastebin.com/6M11HnJE

Thanks in advance!

EDIT:

After experimenting further, it turns out that I simply had to let the height of the center class be auto...

Accepted the answer for its simplicity even though it does not use flex-box like I would have wanted it to

Body:
Construct your form wrapper with HTML and CSS instead of using an image, which is very hard to control when screen size changes.

Sample:
https://codepen.io/anon/pen/NgPGoQ

.login {
  width: 300px;
}

@media screen and (max-width: 768px) {
  .login {
    width: 80%;
  }
}

Set a default width for your wrapper and add media queries for the screen sizes that you would like a custom width.


问:
Node JS: variable usage between modules
I have two modules to represent my problem/confusion:

f2.js:

```<code>var user;

var getName = function(userName) {
    user = userName;
    return user;
};

module.exports.getName = getName;
module.exports.user = user;
</code>```

f1.js:

```<code>var userName = require('./f2.js');
console.log(userName.getName("myName"));

// I need below to return "myName" too - how?
console.log(userName.user);
</code>```

When I run f1.js, I get these:

```<code>myName
undefined
</code>```

What am I missing in terms of scoping or perhaps asynchronous coding? Logically, I know getName function will always run in front so how can I read 'user' variable in other modules as set with that pre-run function? I eventually want to expand this with express and use it as site login

答:
try this

```<code>userName.getName(username){
console.log(username);
});
</code>```

if async's the problem then

f2.js

```<code>var user;

var getName = function(userName,callback) {
    user = userName;
    callback(user);
};

module.exports.getName = getName;
module.exports.user = user;
</code>```

f1.js

```<code>var userName = require('./f2.js');
    userName.getName(username, function(uname) {
    console.log(uname);
});
</code>```

Hope this helps.

Title: Node JS: variable usage between modules

Body:
I have two modules to represent my problem/confusion:

f2.js:

var user;

var getName = function(userName) {
    user = userName;
    return user;
};

module.exports.getName = getName;
module.exports.user = user;

f1.js:

var userName = require('./f2.js');
console.log(userName.getName("myName"));

// I need below to return "myName" too - how?
console.log(userName.user);

When I run f1.js, I get these:

myName
undefined

What am I missing in terms of scoping or perhaps asynchronous coding? Logically, I know getName function will always run in front so how can I read 'user' variable in other modules as set with that pre-run function? I eventually want to expand this with express and use it as site login

Body:
try this

userName.getName(username){
console.log(username);
});

if async's the problem then

f2.js

var user;

var getName = function(userName,callback) {
    user = userName;
    callback(user);
};

module.exports.getName = getName;
module.exports.user = user;

f1.js

var userName = require('./f2.js');
    userName.getName(username, function(uname) {
    console.log(uname);
});

Hope this helps.


问:
Setting the text in the textfield isn't working
I am trying to get the textfield to store a persons name but it keeps appearing as blank, what I currently have is as follows.

In my FXML file I have this label and textfield

```<code><Label layoutX="156.0" layoutY="82.0" prefHeight="17.0" prefWidth="42.0" text="Name:" />

<TextField fx:id="nameTf" text="${controller.customer.name}" layoutX="204.0" layoutY="78.0" />
</code>```

inside my controller for this FXML I have.

```<code>public class ServeController {

@FXML private TextField nameTf;
@FXML private TextField phoneTf;

private String getName() { return nameTf.getText(); }
private double getPhone () { return Double.parseDouble (phoneTf.getText());
}

public void setName(String name) {
    nameTf.setText(name);
}

private void setPhone(String phone) {
    nameTf.setText(phone);
}

@FXML private void initialize() {
}

}
</code>```

and I call the setter from another Controller to set the name like so.

```<code>ServeController serve = new ServeController();

@FXML private void serveCustomer (ActionEvent event) throws Exception {
    serve.setName(customers.get(namelistview.getSelectionModel().getSelectedIndex()).getName());
</code>```

customers is a ObservableList, the getName() function returns the name as a string (I have tested this and it works).

答:
The main issue was as James pointed out, the fact that I was calling the setter on a object instead of the actual controller, by inserting the following code

```<code>ServeController controller = fxmlLoader.getController();
</code>```

instead of

```<code>ServeController serve = new ServeController();
</code>```

and calling the setters by referencing controller, everything seemed to work fine.

Thanks for your help James :)

Body:
I am trying to get the textfield to store a persons name but it keeps appearing as blank, what I currently have is as follows.

In my FXML file I have this label and textfield

<TextField fx:id="nameTf" text="${controller.customer.name}" layoutX="204.0" layoutY="78.0" />

inside my controller for this FXML I have.

public class ServeController {

@FXML private TextField nameTf;
@FXML private TextField phoneTf;

private String getName() { return nameTf.getText(); }
private double getPhone () { return Double.parseDouble (phoneTf.getText());
}

public void setName(String name) {
    nameTf.setText(name);
}

private void setPhone(String phone) {
    nameTf.setText(phone);
}

@FXML private void initialize() {
}

}

and I call the setter from another Controller to set the name like so.

ServeController serve = new ServeController();

@FXML private void serveCustomer (ActionEvent event) throws Exception {
    serve.setName(customers.get(namelistview.getSelectionModel().getSelectedIndex()).getName());

customers is a ObservableList, the getName() function returns the name as a string (I have tested this and it works).

Body:
The main issue was as James pointed out, the fact that I was calling the setter on a object instead of the actual controller, by inserting the following code

ServeController controller = fxmlLoader.getController();

instead of

ServeController serve = new ServeController();

and calling the setters by referencing controller, everything seemed to work fine.

Thanks for your help James :)


答:
This is a workaround. It'll get you what you're looking for, but it's not really satisfying.

In f2.js:

```<code>var getName = function(userName, user) {
    user = userName;
    return user;
};

module.exports.getName = getName;
</code>```

In f1.js:

```<code>var userName = require('./f2.js');
var user;
console.log(userName.getName("myName", user));

console.log(user);
</code>```

Title: Node JS: variable usage between modules

Body:
This is a workaround. It'll get you what you're looking for, but it's not really satisfying.

In f2.js:

var getName = function(userName, user) {
    user = userName;
    return user;
};

module.exports.getName = getName;

In f1.js:

var userName = require('./f2.js');
var user;
console.log(userName.getName("myName", user));

console.log(user);


答:
You can attach the name into an instance of User function like so:

function createUser() {
  this.name = '';
  return {
    user : this.user,
    getName: function(userName) {
        this.user = userName;
        return this.user;
    },
  }
}

var newUser = createUser();

module.exports.getName = newUser.getName;
module.exports.user = newUser.user;```
</div>
</div>
</p>

<p>This assumes that you only have one instance of <code>User</code> though. Otherwise you might want to export the whole function instead and use it like so:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// exports createUser function instead
module.exports.createUser = createUser;

// in other files
var createUser = require('../path/createUser.js');

var bobby = createUser();
bobby.getName('bobby'); // will return 'bobby'

console.log(bobby.user); // will also return 'bobby'</code>```

Title: Node JS: variable usage between modules

Body:
You can attach the name into an instance of User function like so:

function createUser() {
  this.name = '';
  return {
    user : this.user,
    getName: function(userName) {
        this.user = userName;
        return this.user;
    },
  }
}

var newUser = createUser();

module.exports.getName = newUser.getName;
module.exports.user = newUser.user;

This assumes that you only have one instance of User though. Otherwise you might want to export the whole function instead and use it like so:

// exports createUser function instead
module.exports.createUser = createUser;

// in other files
var createUser = require('../path/createUser.js');

var bobby = createUser();
bobby.getName('bobby'); // will return 'bobby'

console.log(bobby.user); // will also return 'bobby'


问:
Swift Bond compile error in NSObject+KVO.swift file
I have installed Bond 6.2.6 with CocoaPods.
While building my project, an error has appeared in the file:

```<code><my_proj>\Pods\Bond\Sources\Bond\Shared\NSObject+KVO.swift
</code>```

The error:

```<code>.../NSObject+KVO.swift:239:81: Cannot convert value of type '(_, _) -> UnownedUnsafe<NSObject>' to expected argument type '(_, UnownedUnsafe<NSObject>) -> _'
</code>```

Source code:

```<code>deallocationDisposable.otherDisposable = object._willDeallocate.reduce(nil, {$1}).observeNext { object in
  if self.observing {
    object?.unbox.removeObserver(self, forKeyPath: self.keyPath, context: &self.context)
  }
}
</code>```

Commenting it gave me the ability to build my project. But it's probably not the best practice...

答: I have updated Xcode to the latest (8.3.2). Now it works.</p>

Body:
I have installed Bond 6.2.6 with CocoaPods.
While building my project, an error has appeared in the file:

<my_proj>\Pods\Bond\Sources\Bond\Shared\NSObject+KVO.swift

The error:

.../NSObject+KVO.swift:239:81: Cannot convert value of type '(_, _) -> UnownedUnsafe<NSObject>' to expected argument type '(_, UnownedUnsafe<NSObject>) -> _'

Source code:

deallocationDisposable.otherDisposable = object._willDeallocate.reduce(nil, {$1}).observeNext { object in
  if self.observing {
    object?.unbox.removeObserver(self, forKeyPath: self.keyPath, context: &self.context)
  }
}

Commenting it gave me the ability to build my project. But it's probably not the best practice...


问:
SQL Server full text search - only works with full string?
I've setup a full text index on a table, there's a column containing the type (always .txt) and a text column with is just a long string in binary. The only way I can get a result with the below query is if the string matches the whole contents of the indexed field.

```<code>SELECT [Pages].[Id]
FROM [Pages]
WHERE CONTAINS([Text], '"this is a test"')
</code>```

The above returns the one record that has the binary for "this is a test".

```<code>SELECT [Pages].[Id]
FROM [Pages]
WHERE CONTAINS([Text], '"test"')
</code>```

The above returns nothing, even though I would expect it to return the record is my previous example.

Any ideas on why this could be happening?

答:
Please try the below

```<code>SELECT [Pages].[Id]
FROM [Pages]
WHERE CONTAINS([Text], '*test*')
</code>```

If you are still having issues with the query then please update the stats of full text index and check.

https://learn.microsoft.com/en-us/sql/relational-databases/search/populate-full-text-indexes

Body:
I've setup a full text index on a table, there's a column containing the type (always .txt) and a text column with is just a long string in binary. The only way I can get a result with the below query is if the string matches the whole contents of the indexed field.

SELECT [Pages].[Id]
FROM [Pages]
WHERE CONTAINS([Text], '"this is a test"')

The above returns the one record that has the binary for "this is a test".

SELECT [Pages].[Id]
FROM [Pages]
WHERE CONTAINS([Text], '"test"')

The above returns nothing, even though I would expect it to return the record is my previous example.

Any ideas on why this could be happening?

Body:
Please try the below

SELECT [Pages].[Id]
FROM [Pages]
WHERE CONTAINS([Text], '*test*')

If you are still having issues with the query then please update the stats of full text index and check.

https://learn.microsoft.com/en-us/sql/relational-databases/search/populate-full-text-indexes