问:
Make button move around the screen and record finger gesture accuracy

I am trying to make an app in which the user has to follow a dot dragging his finger across the screen. Each time the dot is reached by the user, it moves to the next point (there are 5 equidistant points in total, with specific coordinates).

The length of the path traced by the finger is recorded between every two dots, stored into and array and the value is eventually averaged, to assess the accuracy of the user (comparing his own path to the ideal, shortest one).

```<code>-(IBAction)button1Clicked:(UIButton *)sender {
    CGRect buttonFrame = sender.frame;

    int dotX = arc4random() % (int)(1000 - buttonFrame.size.width);
    int dotY = arc4random() % (int)(self.view.frame.size.height - buttonFrame.size.height);

    buttonFrame.origin.x = dotX;
    buttonFrame.origin.y = dotY;
    [sender setFrame:buttonFrame];
    NSLog(@"x = %f, y = %f", self.button1.frame.origin.x, self.button1.frame.origin.y);
}
</code>```

I've tried to add the buttons programmatically using several buttons stored in an array, but also directly from the storyboard, and I still haven't figured out which would be the best way for the app to do what it's meant to.

My coding knowledge being still very poor, I've only managed to make an app with a dot shaped button that has to be clicked (touch down inside) in order for it to move around the screen, and when the user presses it it moves to a random point on the screen of my iPad. Instead would like the button to move around a specific path, a set number of times until the code stops running and the results are averaged (I will probably need to put some code inside a "for" loop for that), and the gesture should be touch drag inside rather than touch down.
It would be great if anyone could help me out giving me some hints!

答:
I think you should only need to add one button. Create an array of NSMutableDictionary, which contains values for each point that you want the user to navigate to, this includes, x and y coordinates, minimum distance between this coordinate and the last coordinate, and the actual distance travelled between this coordinate and the last coordinate. The following setup should work for you but it is untested:

Storing your coordinate sets:
The way you store your coordinate sets depends on how many sets of coordinates you have, and how many coordinates are in each. If you only have a few sets of coordinates, you could get away with writing them in the code like I have here. If you have a lot of coordinate sets, you will most likely want to create a file which you will store in your bundle, and access it where needed, there are many SO questions related to this process already.

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

@interface ViewController (){
    NSMutableArray *values;
    NSInteger buttonCount;
    __weak IBOutlet UIButton *button;
    BOOL hasStarted;
}

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    UIGestureRecognizer *gestureRecognizer = [[UIGestureRecognizer alloc] init];
    [gestureRecognizer setEnabled:YES];
    [gestureRecognizer setDelegate:self];
    [self.view addGestureRecognizer:gestureRecognizer];

    button.hidden = true;

    buttonCount = 0;
    values = [[NSMutableArray alloc]init];
    [self generateValuesArrayWithCoordiantes];
}

-(void)generateValuesArrayWithCoordiantes{
    // for every number between 0 and 20, create an nsdictionary with your desired values for x and y
    CGPoint lastCoord = CGPointZero;
    // you need to have your set of coordinates stored somewhere, so that they can put into the button values dictionary
    // here is an array of dictionary, with an x and y number for each array value, you will require 20 rows, one for each set of coords

    NSArray *coords = @[@{@"x":@317, @"y":@100},
                        @{@"x":@200, @"y":@250},
                        @{@"x":@120, @"y":@400},
                        @{@"x":@80, @"y":@380}];

    for (int i = 0; i<20; i++) {
        NSMutableDictionary *buttonValues = [[NSMutableDictionary alloc]init];

        // get the required coords from your coords array
        NSDictionary *currentCoord = [coords objectAtIndex:i];
        [buttonValues setValue:[currentCoord valueForKey:@"x"] forKey:@"x"];
        [buttonValues setValue:[currentCoord valueForKey:@"y"] forKey:@"y"];

        // set the distance travelled to 0. this will be updated as your view detects touches moved
        [buttonValues setValue:[NSNumber numberWithInt:0] forKey:@"distanceTravelled"];

        if (i>0) {
            // calculate the minimum distance required to get from this point to the previous point. not required for the first point
            CGFloat minDistance = [self distanceBetween:CGPointMake([[currentCoord valueForKey:@"x"]floatValue], [[currentCoord valueForKey:@"y"]floatValue]) and:lastCoord];
            [buttonValues setValue:[NSNumber numberWithFloat:minDistance] forKey:@"minDistance"];
        }
        lastCoord = CGPointMake([[currentCoord valueForKey:@"x"]floatValue], [[currentCoord valueForKey:@"y"]floatValue]);
        [values addObject:buttonValues];
    }
}

-(IBAction)button1Clicked:(UIButton *)sender {
    if (!hasStarted) {
        NSLog(@"It Has Begun");
        hasStarted = true;
    }
    buttonCount = buttonCount + 1;
    if (buttonCount == 20){
        // The button has been clicked 20 times, compare the minDistance of the dictionaries, to the actualDistance of the dictionaries
        NSLog(@"We are done");
        return;
    }
    //get the last frame of the button
    CGRect lastFrame = sender.frame;

    NSMutableDictionary *nextButtonValues = [values objectAtIndex:buttonCount];

    CGRect nextFrame = CGRectMake([[nextButtonValues valueForKey:@"x"]floatValue], [[nextButtonValues valueForKey:@"y"]floatValue], lastFrame.size.width, lastFrame.size.height);

    [sender setFrame:nextFrame];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    button.hidden = false;
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    // get this and last touch location and the distance moved between them
    UITouch *touch = [touches anyObject];
    CGPoint touchLocation = [touch locationInView:self.view];
    CGPoint lastLocation = [touch previousLocationInView:self.view];
    CGFloat distanceMoved = [self distanceBetween:touchLocation and:lastLocation];

    //NSLog(@"MOVED %.2f", distanceMoved);

    // get the current course from values, and update the distanceTravelled to include the distance moved
    NSMutableDictionary *currentCourse = [values objectAtIndex:buttonCount];
    CGFloat courseTravelled = [[currentCourse valueForKey:@"distanceTravelled"]floatValue];
    [currentCourse setValue:[NSNumber numberWithFloat:courseTravelled + distanceMoved] forKey:@"distanceTravelled"];

    // detect if the touch is inside the button frame
    for (UITouch *t in touches) {
        CGPoint touchPoint = [t locationInView:self.view];

        CGPoint testPoint = [self.view convertPoint:touchPoint toView:button];
        if ([button pointInside:testPoint withEvent:event]) {
            [self button1Clicked:button];
            return;
        }
    }
}

-(CGFloat)distanceBetween:(CGPoint)point1 and:(CGPoint)point2{
    CGFloat xDist = (point1.x - point2.x);
    CGFloat yDist = (point1.y - point2.y);
    return sqrt((xDist * xDist) + (yDist * yDist));
}

@end
</code>```

When the view detects the initial touch, the button will be unhidden, and the game will begin

Body:
I am trying to make an app in which the user has to follow a dot dragging his finger across the screen. Each time the dot is reached by the user, it moves to the next point (there are 5 equidistant points in total, with specific coordinates).

The length of the path traced by the finger is recorded between every two dots, stored into and array and the value is eventually averaged, to assess the accuracy of the user (comparing his own path to the ideal, shortest one).

-(IBAction)button1Clicked:(UIButton *)sender {
    CGRect buttonFrame = sender.frame;

    int dotX = arc4random() % (int)(1000 - buttonFrame.size.width);
    int dotY = arc4random() % (int)(self.view.frame.size.height - buttonFrame.size.height);

    buttonFrame.origin.x = dotX;
    buttonFrame.origin.y = dotY;
    [sender setFrame:buttonFrame];
    NSLog(@"x = %f, y = %f", self.button1.frame.origin.x, self.button1.frame.origin.y);
}

I've tried to add the buttons programmatically using several buttons stored in an array, but also directly from the storyboard, and I still haven't figured out which would be the best way for the app to do what it's meant to.

My coding knowledge being still very poor, I've only managed to make an app with a dot shaped button that has to be clicked (touch down inside) in order for it to move around the screen, and when the user presses it it moves to a random point on the screen of my iPad. Instead would like the button to move around a specific path, a set number of times until the code stops running and the results are averaged (I will probably need to put some code inside a "for" loop for that), and the gesture should be touch drag inside rather than touch down.
It would be great if anyone could help me out giving me some hints!

Body:
I think you should only need to add one button. Create an array of NSMutableDictionary, which contains values for each point that you want the user to navigate to, this includes, x and y coordinates, minimum distance between this coordinate and the last coordinate, and the actual distance travelled between this coordinate and the last coordinate. The following setup should work for you but it is untested:

Storing your coordinate sets:
The way you store your coordinate sets depends on how many sets of coordinates you have, and how many coordinates are in each. If you only have a few sets of coordinates, you could get away with writing them in the code like I have here. If you have a lot of coordinate sets, you will most likely want to create a file which you will store in your bundle, and access it where needed, there are many SO questions related to this process already.

#import "ViewController.h"

@interface ViewController (){
    NSMutableArray *values;
    NSInteger buttonCount;
    __weak IBOutlet UIButton *button;
    BOOL hasStarted;
}

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    UIGestureRecognizer *gestureRecognizer = [[UIGestureRecognizer alloc] init];
    [gestureRecognizer setEnabled:YES];
    [gestureRecognizer setDelegate:self];
    [self.view addGestureRecognizer:gestureRecognizer];

    button.hidden = true;

    buttonCount = 0;
    values = [[NSMutableArray alloc]init];
    [self generateValuesArrayWithCoordiantes];
}

-(void)generateValuesArrayWithCoordiantes{
    // for every number between 0 and 20, create an nsdictionary with your desired values for x and y
    CGPoint lastCoord = CGPointZero;
    // you need to have your set of coordinates stored somewhere, so that they can put into the button values dictionary
    // here is an array of dictionary, with an x and y number for each array value, you will require 20 rows, one for each set of coords

    NSArray *coords = @[@{@"x":@317, @"y":@100},
                        @{@"x":@200, @"y":@250},
                        @{@"x":@120, @"y":@400},
                        @{@"x":@80, @"y":@380}];

    for (int i = 0; i<20; i++) {
        NSMutableDictionary *buttonValues = [[NSMutableDictionary alloc]init];

        // get the required coords from your coords array
        NSDictionary *currentCoord = [coords objectAtIndex:i];
        [buttonValues setValue:[currentCoord valueForKey:@"x"] forKey:@"x"];
        [buttonValues setValue:[currentCoord valueForKey:@"y"] forKey:@"y"];

        // set the distance travelled to 0. this will be updated as your view detects touches moved
        [buttonValues setValue:[NSNumber numberWithInt:0] forKey:@"distanceTravelled"];

        if (i>0) {
            // calculate the minimum distance required to get from this point to the previous point. not required for the first point
            CGFloat minDistance = [self distanceBetween:CGPointMake([[currentCoord valueForKey:@"x"]floatValue], [[currentCoord valueForKey:@"y"]floatValue]) and:lastCoord];
            [buttonValues setValue:[NSNumber numberWithFloat:minDistance] forKey:@"minDistance"];
        }
        lastCoord = CGPointMake([[currentCoord valueForKey:@"x"]floatValue], [[currentCoord valueForKey:@"y"]floatValue]);
        [values addObject:buttonValues];
    }
}

-(IBAction)button1Clicked:(UIButton *)sender {
    if (!hasStarted) {
        NSLog(@"It Has Begun");
        hasStarted = true;
    }
    buttonCount = buttonCount + 1;
    if (buttonCount == 20){
        // The button has been clicked 20 times, compare the minDistance of the dictionaries, to the actualDistance of the dictionaries
        NSLog(@"We are done");
        return;
    }
    //get the last frame of the button
    CGRect lastFrame = sender.frame;

    NSMutableDictionary *nextButtonValues = [values objectAtIndex:buttonCount];

    CGRect nextFrame = CGRectMake([[nextButtonValues valueForKey:@"x"]floatValue], [[nextButtonValues valueForKey:@"y"]floatValue], lastFrame.size.width, lastFrame.size.height);

    [sender setFrame:nextFrame];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    button.hidden = false;
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    // get this and last touch location and the distance moved between them
    UITouch *touch = [touches anyObject];
    CGPoint touchLocation = [touch locationInView:self.view];
    CGPoint lastLocation = [touch previousLocationInView:self.view];
    CGFloat distanceMoved = [self distanceBetween:touchLocation and:lastLocation];

    //NSLog(@"MOVED %.2f", distanceMoved);

    // get the current course from values, and update the distanceTravelled to include the distance moved
    NSMutableDictionary *currentCourse = [values objectAtIndex:buttonCount];
    CGFloat courseTravelled = [[currentCourse valueForKey:@"distanceTravelled"]floatValue];
    [currentCourse setValue:[NSNumber numberWithFloat:courseTravelled + distanceMoved] forKey:@"distanceTravelled"];

    // detect if the touch is inside the button frame
    for (UITouch *t in touches) {
        CGPoint touchPoint = [t locationInView:self.view];

        CGPoint testPoint = [self.view convertPoint:touchPoint toView:button];
        if ([button pointInside:testPoint withEvent:event]) {
            [self button1Clicked:button];
            return;
        }
    }
}

-(CGFloat)distanceBetween:(CGPoint)point1 and:(CGPoint)point2{
    CGFloat xDist = (point1.x - point2.x);
    CGFloat yDist = (point1.y - point2.y);
    return sqrt((xDist * xDist) + (yDist * yDist));
}

@end

When the view detects the initial touch, the button will be unhidden, and the game will begin


来源: stackexchange

问:
How to use sed to create new txt file without specific words
I have a text file that contains $string . How would I use sed to create a new txt file without all occurrences of $string ?</p>

答:
You can use the following sed command that will replace all the occurrences of your string variable by the the empty string ''  and by redirecting the output to a new output_file.

```<code>sed "s/$string//g" input_file > output_file
</code>```

or you can use the following sed command:

```<code>sed -i.bkp "s/$string//g" file
</code>```

to work directly inside the file passed as parameter, -i.bkp option will create backup file automatically with an extension .bkp, (in the above example file.bkp), if no need of backup, use just -i

Last but not least, your $string variable should not contain any slash / if there are any you should escape all of them using \. You can create a function to perform this task.

ContentLicense: CC BY-SA 3.0

Body:
You can use the following sed command that will replace all the occurrences of your string variable by the the empty string ''  and by redirecting the output to a new output_file.

sed "s/$string//g" input_file > output_file

or you can use the following sed command:

sed -i.bkp "s/$string//g" file

to work directly inside the file passed as parameter, -i.bkp option will create backup file automatically with an extension .bkp, (in the above example file.bkp), if no need of backup, use just -i

Last but not least, your $string variable should not contain any slash / if there are any you should escape all of them using \. You can create a function to perform this task.


问:
Function output displaying nothing, Python
I am trying to create a program in Python 3 that turns the DNA codon into an amino acid, however, after inputing the code, I get no error messages, but the function does not display anything after I run the code and type in the DNA code. Ex: ATTGTTTCT, should display ILE VAL SER, I am not getting the ILE VAL SER. Any help would be greatly appreciated.</p>

```<code>DNA_sequence = input("Enter your DNA sequence below: \n")
DNA = DNA_sequence.upper()
DNA_to_codons = ([DNA[start:start + 3]] for start in range(0, len(DNA), 3))

print('The amino acid chain of your DNA sequence is as follows: \n')
for i in DNA_to_codons:
    if(i=="ATG"): print("MET", end = ' ')
    if(i=="TGA" or i=="TAA" or i=="TAG"): print("END", end = ' ')
    if(i=="TTT" or i=="TTC"): print("PHE", end = ' ')
    if(i=="TTA" or i=="TTG" or i=="CTT" or i=="CTC" or i=="CTA" or i=="CTG"): print("LEU", end = ' ')
    if(i=="ATT" or i=="ATC" or i=="ATA"): print("ILE", end = ' ')
    if(i=="GTT" or i=="GTC" or i =="GTA" or i=="GTG"): print("VAL", end = ' ')
    if(i=="TCT" or i=="TCC" or i=="TCA" or i=="TCG"): print("SER", end = ' ')
    if(i=="CCT" or i=="CCC" or i=="CCA" or i=="CCG"): print("PRO", end = ' ')
    if(i=="ACT" or i=="ACC" or i=="ACA" or i=="ACG"): print("THR", end = ' ')
    if(i=="GCT" or i=="GCC" or i=="GCA" or i=="GCG"): print("ALA", end = ' ')
    if(i=="TAT" or i=="TAC"): print("TYR", end = ' ')
    if(i=="CAT" or i=="CAC"): print("HIS", end = ' ')
    if(i=="CAA" or i=="CAG"): print("GLN", end = ' ')
    if(i=="AAT" or i=="AAC"): print("ASN", end = ' ')
    if(i=="AAA" or i=="AAG"): print("LYS", end = ' ')
    if(i=="GAT" or i =="GAC"): print("ASP", end = ' ')
</code>```

答:
On your third line of code, change

```<code>DNA_to_codons = ([DNA[start:start + 3]] for start in range(0, len(DNA), 3))
</code>```

to

```<code>DNA_to_codons = (DNA[start:start + 3] for start in range(0, len(DNA), 3))
</code>```

Each element in DNA_to_codons was being yield as a list instead of a string, making DNA_to_codons a generator containing lists in your original code, hence the comparisons didn't work as a list (i.e. ["ATT"]) was being compared to a string (i.e. "ATT").

Body:
I am trying to create a program in Python 3 that turns the DNA codon into an amino acid, however, after inputing the code, I get no error messages, but the function does not display anything after I run the code and type in the DNA code. Ex: ATTGTTTCT, should display ILE VAL SER, I am not getting the ILE VAL SER. Any help would be greatly appreciated.

DNA_sequence = input("Enter your DNA sequence below: \n")
DNA = DNA_sequence.upper()
DNA_to_codons = ([DNA[start:start + 3]] for start in range(0, len(DNA), 3))

print('The amino acid chain of your DNA sequence is as follows: \n')
for i in DNA_to_codons:
    if(i=="ATG"): print("MET", end = ' ')
    if(i=="TGA" or i=="TAA" or i=="TAG"): print("END", end = ' ')
    if(i=="TTT" or i=="TTC"): print("PHE", end = ' ')
    if(i=="TTA" or i=="TTG" or i=="CTT" or i=="CTC" or i=="CTA" or i=="CTG"): print("LEU", end = ' ')
    if(i=="ATT" or i=="ATC" or i=="ATA"): print("ILE", end = ' ')
    if(i=="GTT" or i=="GTC" or i =="GTA" or i=="GTG"): print("VAL", end = ' ')
    if(i=="TCT" or i=="TCC" or i=="TCA" or i=="TCG"): print("SER", end = ' ')
    if(i=="CCT" or i=="CCC" or i=="CCA" or i=="CCG"): print("PRO", end = ' ')
    if(i=="ACT" or i=="ACC" or i=="ACA" or i=="ACG"): print("THR", end = ' ')
    if(i=="GCT" or i=="GCC" or i=="GCA" or i=="GCG"): print("ALA", end = ' ')
    if(i=="TAT" or i=="TAC"): print("TYR", end = ' ')
    if(i=="CAT" or i=="CAC"): print("HIS", end = ' ')
    if(i=="CAA" or i=="CAG"): print("GLN", end = ' ')
    if(i=="AAT" or i=="AAC"): print("ASN", end = ' ')
    if(i=="AAA" or i=="AAG"): print("LYS", end = ' ')
    if(i=="GAT" or i =="GAC"): print("ASP", end = ' ')

Body:
On your third line of code, change

DNA_to_codons = ([DNA[start:start + 3]] for start in range(0, len(DNA), 3))

to

DNA_to_codons = (DNA[start:start + 3] for start in range(0, len(DNA), 3))

Each element in DNA_to_codons was being yield as a list instead of a string, making DNA_to_codons a generator containing lists in your original code, hence the comparisons didn't work as a list (i.e. ["ATT"]) was being compared to a string (i.e. "ATT").


问:
Can I roll back a JTA transcation after I commit it?
I have a JTA transcation which I commit.  Can I roll it back after I commit?  If yes, how? I have following situation.

I have a backend layer which updated 3 DBs.  I have used JTA user transcation for it.  If update in any DB fails all updates to 3 DBs are rolled back using utx.rollback

Now I have a layer on top of backend layer which updates some other DB.  Now I want that step 1 and step 2 should both succeed or both fail, so I want to roll back JTA transcation of step 1 in case step 2 fails.

It's difficult for me to put code of step 2 into 1 as we are using some existing APIs to update DB in step 2.

答:
I think that the answer is that you cannot do anything like this using JTA, or other RDBMs.

Transactions are either committed, or they are rolled back.  Once successfully committed they cannot be rolled back.

The only possible "out" might be to try and use nested transactions, and rollback the outer transaction.  But that probably isn't going to work:

Not all JTA implementations support nested transactions.

Even if they did, there is no guarantee that the outer transaction will successfully commit.  And that could leave you with the "other" DB committed and the JTA transaction rolled back.

It sound like you are going to have to rethink your persistence APIs.

ContentLicense: CC BY-SA 2.5


问:
Access Denied Connecting to MySQL with PHP
I know there are a lot of threads asking this question already, but I have been at this for hours and am at wits end.  I am attempting to connect to a MySQL database that I am running of my MacBook with the following PHP:

```<code><?php
DEFINE('DB_USER', 'webuser');
DEFINE('DB_PASSWORD', 'thispassword');
DEFINE('DB_HOST', '127.0.0.1:3306');
DEFINE('DB_NAME', 'learning_accounts');

$dbc = @mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
OR die('Error connecting: ' .
mysqli_connect_error()
);

?>
</code>```

That returns the following error:

```<code>Error connecting: Access denied for user 'webuser'@'localhost' (using password: YES)
</code>```

I can connect fine through the terminal, even trying to connect with PHP and root does not work.  I am new to both PHP and MySQL so any guidance and insight would be appreciated!

I have tried tons of solutions such as granting privileges, flushing privileges, creating new users, using PDO, nothing has been working - please help!

Thanks so much, I hate learning new languages because then I'm a lost fish when it comes to debugging at first!

Update

I have a password set for my root account, but changing the DB_PASSWORD variable to '' changes the error to: Error connecting: Unknown database 'learning_accounts'

Update 2
I have fixed the issue, check my answer to see how, if you are having this problem then I hope you found this thread quickly!

Zach L

答:
As @DontPanic suggested in his comment get rid off the 3306 from 127.0.0.1:3306.

If you're using XAMPP, WAMP or EasyPHP the MySQL password isn't set by-default. Hence you should use

```<code>DEFINE('DB_USER', 'root'); // default user name
DEFINE('DB_PASSWORD', ''); // empty password just open single quote and close
</code>```

Body:
I know there are a lot of threads asking this question already, but I have been at this for hours and am at wits end.  I am attempting to connect to a MySQL database that I am running of my MacBook with the following PHP:

<?php
DEFINE('DB_USER', 'webuser');
DEFINE('DB_PASSWORD', 'thispassword');
DEFINE('DB_HOST', '127.0.0.1:3306');
DEFINE('DB_NAME', 'learning_accounts');

$dbc = @mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
OR die('Error connecting: ' .
mysqli_connect_error()
);

?>

That returns the following error:

Error connecting: Access denied for user 'webuser'@'localhost' (using password: YES)

I can connect fine through the terminal, even trying to connect with PHP and root does not work.  I am new to both PHP and MySQL so any guidance and insight would be appreciated!

I have tried tons of solutions such as granting privileges, flushing privileges, creating new users, using PDO, nothing has been working - please help!

Thanks so much, I hate learning new languages because then I'm a lost fish when it comes to debugging at first!

Update

I have a password set for my root account, but changing the DB_PASSWORD variable to '' changes the error to: Error connecting: Unknown database 'learning_accounts'

Update 2
I have fixed the issue, check my answer to see how, if you are having this problem then I hope you found this thread quickly!

Zach L

Body:
As @DontPanic suggested in his comment get rid off the 3306 from 127.0.0.1:3306.

If you're using XAMPP, WAMP or EasyPHP the MySQL password isn't set by-default. Hence you should use

DEFINE('DB_USER', 'root'); // default user name
DEFINE('DB_PASSWORD', ''); // empty password just open single quote and close


问:
java walkFileTree to mimic chmod -R 755 does not work
I want to ensure correct permissions in a directory tree (0755 for directories and 644 for files). Here is my class:

```<code>package NRF_Utils;

import java.io.IOException;
import java.nio.file.FileVisitResult;
import static java.nio.file.FileVisitResult.*;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Set;
import java.util.logging.Logger;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;

public class DirectoryTreeOperations {
    private static final Logger log = Logger.getLogger("spv." + DirectoryTreeOperations.class.getName());

    public static boolean setPermissions(String root, String directoryPermissions, String filePermissions) {
        boolean result = true;
        //declaring the path to delete
        final Path path = Paths.get(root);
        final Set<PosixFilePermission> dirPermissions = PosixFilePermissions.fromString(directoryPermissions);
        final Set<PosixFilePermission> filPermissions = PosixFilePermissions.fromString(filePermissions);

        try {
            Files.walkFileTree(path, new FileVisitor<Path>() {

                @Override
                public FileVisitResult preVisitDirectory(Path dir,
                        BasicFileAttributes attrs) throws IOException {
                    System.out.println("setting dir permission on " + dir);
                    Files.setPosixFilePermissions(dir, dirPermissions);
                    return CONTINUE;
                }

                @Override
                public FileVisitResult visitFile(Path file,
                        BasicFileAttributes attrs) throws IOException {
                    System.out.println("setting file permission on " + file);
                    Files.setPosixFilePermissions(file, filPermissions);
                    return CONTINUE;
                }

                @Override
                public FileVisitResult visitFileFailed(Path file, IOException exc)
                        throws IOException {
                    log.severe("visitFileFailed failed on " + file + " : " + exc);
                    return CONTINUE;
                }

                @Override
                public FileVisitResult postVisitDirectory(Path dir,
                        IOException exc) throws IOException {
                    return CONTINUE;
                }

            });
        } catch (IOException e) {
            log.severe("setPermissions failed " + e);
            result = false;
        }
        return result;
    }

    // TODO remove and provide a proper unit test
    public static void main(String [] arg) {
        System.out.println ("setPermissions returned: " + setPermissions("/tmp/x", "rwxr-xr-x", "rw-r--r--"));
    }
}
</code>```

To perform test, I have done:

```<code>mkdir -p /tmp/x/y/z;touch /tmp/x/y/z/f;chmod 000 /tmp/x/y/z
</code>```

The output is:

```<code>setting dir permission on /tmp/x
setting dir permission on /tmp/x/y
setPermissions returned: true
nov. 26, 2017 2:45:00 PM NRF_Utils.DirectoryTreeOperations$1 visitFileFailed
GRAVE: visitFileFailed failed on /tmp/x/y/z : java.nio.file.AccessDeniedException: /tmp/x/y/z
</code>```

It seems java does not want to explore the directory tree because the permissions are wrong, but my aim was to explore the directory tree to fix permissions. Is the API crazy ?

答:
The only issue with walkFileTree is that it doesn't call preVisitDirectory() on directories it doesn't have permission to search.  You can work around that by fixing the permissions just ahead of where walkFileTree is looking.
 I.e., by manually scanning the direct children of any directory handed to preVisitDirectoy() and applying permissions there (rather than in visitFile):

```<code>            @Override
            public FileVisitResult preVisitDirectory(Path dir,
                    BasicFileAttributes attrs) throws IOException {
                for(File f : new File(dir.toUri()).listFiles()) { //iterate over the contents of the directory
                    System.out.println("setting dir permission on " + f);
                    Files.setPosixFilePermissions(dir.resolve(f.getName()), dirPermissions);
                }

                //System.out.println("setting dir permission on " + dir);
                //Files.setPosixFilePermissions(dir, dirPermissions);
                return CONTINUE;
            }
</code>```

Then you can comment out visitFile()'s body:

```<code>            @Override
            public FileVisitResult visitFile(Path file,
                    BasicFileAttributes attrs) throws IOException {
            //    System.out.println("setting file permission on " + file);
            //    Files.setPosixFilePermissions(file, filPermissions);
                return CONTINUE;
            }
</code>```

Since we're now applying permissions one layer below where the walk has made it to, we need an additional call just inside the try block:

```<code>        System.out.println("setting dir permission on " + path); //in case the initial path needs fixing
        Files.setPosixFilePermissions(path, dirPermissions);
</code>```

Here's the whole thing together (well, I took off your package declaration for convenience):

```<code>import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import static java.nio.file.FileVisitResult.*;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Set;
import java.util.logging.Logger;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;

public class DirectoryTreeOperations {
    private static final Logger log = Logger.getLogger("spv." + DirectoryTreeOperations.class.getName());

    public static boolean setPermissions(String root, String directoryPermissions, String filePermissions) {
        boolean result = true;
        //declaring the path to delete
        final Path path = Paths.get(root);
        final Set<PosixFilePermission> dirPermissions = PosixFilePermissions.fromString(directoryPermissions);
        final Set<PosixFilePermission> filPermissions = PosixFilePermissions.fromString(filePermissions);

        try {
            System.out.println("setting dir permission on " + path); //in case the initial path needs fixing
            Files.setPosixFilePermissions(path, dirPermissions);

            Files.walkFileTree(path, new FileVisitor<Path>() {
                @Override
                public FileVisitResult preVisitDirectory(Path dir,
                        BasicFileAttributes attrs) throws IOException {
                    for(File f : new File(dir.toUri()).listFiles()) { //iterate over the contents of the directory
                        System.out.println("setting dir permission on " + f);
                        Files.setPosixFilePermissions(dir.resolve(f.getName()), dirPermissions);
                    }

                    //System.out.println("setting dir permission on " + dir);
                    //Files.setPosixFilePermissions(dir, dirPermissions);
                    return CONTINUE;
                }

                @Override
                public FileVisitResult visitFile(Path file,
                        BasicFileAttributes attrs) throws IOException {
                //    System.out.println("setting file permission on " + file);
                //    Files.setPosixFilePermissions(file, filPermissions);
                    return CONTINUE;
                }

                @Override
                public FileVisitResult visitFileFailed(Path file, IOException exc)
                        throws IOException {
                    log.severe("visitFileFailed failed on " + file + " : " + exc);
                    return CONTINUE;
                }

                @Override
                public FileVisitResult postVisitDirectory(Path dir,
                        IOException exc) throws IOException {
                    return CONTINUE;
                }

            });
        } catch (IOException e) {
            log.severe("setPermissions failed " + e);
            result = false;
        }
        return result;
    }

    // TODO remove and provide a proper unit test
    public static void main(String [] arg) {
        System.out.println ("setPermissions returned: " + setPermissions("/tmp/x", "rwxr-xr-x", "rw-r--r--"));
    }
}
</code>```

When run on the example case:

```<code>$ mkdir -p /tmp/x/y/z;touch /tmp/x/y/z/f;chmod 000 /tmp/x/y/z
$ find /tmp/x
/tmp/x
/tmp/x/y
/tmp/x/y/z
find: â/tmp/x/y/zâ: Permission denied
$ java DirectoryTreeOperations
setting dir permission on /tmp/x
setting dir permission on /tmp/x/y
setting dir permission on /tmp/x/y/z
setting dir permission on /tmp/x/y/z/f
setPermissions returned: true
$ find /tmp/x
/tmp/x
/tmp/x/y
/tmp/x/y/z
/tmp/x/y/z/f
</code>```

Body:
I want to ensure correct permissions in a directory tree (0755 for directories and 644 for files). Here is my class:

package NRF_Utils;

import java.io.IOException;
import java.nio.file.FileVisitResult;
import static java.nio.file.FileVisitResult.*;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Set;
import java.util.logging.Logger;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;

public class DirectoryTreeOperations {
    private static final Logger log = Logger.getLogger("spv." + DirectoryTreeOperations.class.getName());

    public static boolean setPermissions(String root, String directoryPermissions, String filePermissions) {
        boolean result = true;
        //declaring the path to delete
        final Path path = Paths.get(root);
        final Set<PosixFilePermission> dirPermissions = PosixFilePermissions.fromString(directoryPermissions);
        final Set<PosixFilePermission> filPermissions = PosixFilePermissions.fromString(filePermissions);

        try {
            Files.walkFileTree(path, new FileVisitor<Path>() {

                @Override
                public FileVisitResult preVisitDirectory(Path dir,
                        BasicFileAttributes attrs) throws IOException {
                    System.out.println("setting dir permission on " + dir);
                    Files.setPosixFilePermissions(dir, dirPermissions);
                    return CONTINUE;
                }

                @Override
                public FileVisitResult visitFile(Path file,
                        BasicFileAttributes attrs) throws IOException {
                    System.out.println("setting file permission on " + file);
                    Files.setPosixFilePermissions(file, filPermissions);
                    return CONTINUE;
                }

                @Override
                public FileVisitResult visitFileFailed(Path file, IOException exc)
                        throws IOException {
                    log.severe("visitFileFailed failed on " + file + " : " + exc);
                    return CONTINUE;
                }

                @Override
                public FileVisitResult postVisitDirectory(Path dir,
                        IOException exc) throws IOException {
                    return CONTINUE;
                }

            });
        } catch (IOException e) {
            log.severe("setPermissions failed " + e);
            result = false;
        }
        return result;
    }

    // TODO remove and provide a proper unit test
    public static void main(String [] arg) {
        System.out.println ("setPermissions returned: " + setPermissions("/tmp/x", "rwxr-xr-x", "rw-r--r--"));
    }
}

To perform test, I have done:

mkdir -p /tmp/x/y/z;touch /tmp/x/y/z/f;chmod 000 /tmp/x/y/z

The output is:

setting dir permission on /tmp/x
setting dir permission on /tmp/x/y
setPermissions returned: true
nov. 26, 2017 2:45:00 PM NRF_Utils.DirectoryTreeOperations$1 visitFileFailed
GRAVE: visitFileFailed failed on /tmp/x/y/z : java.nio.file.AccessDeniedException: /tmp/x/y/z

It seems java does not want to explore the directory tree because the permissions are wrong, but my aim was to explore the directory tree to fix permissions. Is the API crazy ?

Body:
The only issue with walkFileTree is that it doesn't call preVisitDirectory() on directories it doesn't have permission to search.  You can work around that by fixing the permissions just ahead of where walkFileTree is looking.
 I.e., by manually scanning the direct children of any directory handed to preVisitDirectoy() and applying permissions there (rather than in visitFile):

            @Override
            public FileVisitResult preVisitDirectory(Path dir,
                    BasicFileAttributes attrs) throws IOException {
                for(File f : new File(dir.toUri()).listFiles()) { //iterate over the contents of the directory
                    System.out.println("setting dir permission on " + f);
                    Files.setPosixFilePermissions(dir.resolve(f.getName()), dirPermissions);
                }

                //System.out.println("setting dir permission on " + dir);
                //Files.setPosixFilePermissions(dir, dirPermissions);
                return CONTINUE;
            }

Then you can comment out visitFile()'s body:

            @Override
            public FileVisitResult visitFile(Path file,
                    BasicFileAttributes attrs) throws IOException {
            //    System.out.println("setting file permission on " + file);
            //    Files.setPosixFilePermissions(file, filPermissions);
                return CONTINUE;
            }

Since we're now applying permissions one layer below where the walk has made it to, we need an additional call just inside the try block:

        System.out.println("setting dir permission on " + path); //in case the initial path needs fixing
        Files.setPosixFilePermissions(path, dirPermissions);

Here's the whole thing together (well, I took off your package declaration for convenience):

import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import static java.nio.file.FileVisitResult.*;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Set;
import java.util.logging.Logger;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;

public class DirectoryTreeOperations {
    private static final Logger log = Logger.getLogger("spv." + DirectoryTreeOperations.class.getName());

    public static boolean setPermissions(String root, String directoryPermissions, String filePermissions) {
        boolean result = true;
        //declaring the path to delete
        final Path path = Paths.get(root);
        final Set<PosixFilePermission> dirPermissions = PosixFilePermissions.fromString(directoryPermissions);
        final Set<PosixFilePermission> filPermissions = PosixFilePermissions.fromString(filePermissions);

        try {
            System.out.println("setting dir permission on " + path); //in case the initial path needs fixing
            Files.setPosixFilePermissions(path, dirPermissions);

            Files.walkFileTree(path, new FileVisitor<Path>() {
                @Override
                public FileVisitResult preVisitDirectory(Path dir,
                        BasicFileAttributes attrs) throws IOException {
                    for(File f : new File(dir.toUri()).listFiles()) { //iterate over the contents of the directory
                        System.out.println("setting dir permission on " + f);
                        Files.setPosixFilePermissions(dir.resolve(f.getName()), dirPermissions);
                    }

                    //System.out.println("setting dir permission on " + dir);
                    //Files.setPosixFilePermissions(dir, dirPermissions);
                    return CONTINUE;
                }

                @Override
                public FileVisitResult visitFile(Path file,
                        BasicFileAttributes attrs) throws IOException {
                //    System.out.println("setting file permission on " + file);
                //    Files.setPosixFilePermissions(file, filPermissions);
                    return CONTINUE;
                }

                @Override
                public FileVisitResult visitFileFailed(Path file, IOException exc)
                        throws IOException {
                    log.severe("visitFileFailed failed on " + file + " : " + exc);
                    return CONTINUE;
                }

                @Override
                public FileVisitResult postVisitDirectory(Path dir,
                        IOException exc) throws IOException {
                    return CONTINUE;
                }

            });
        } catch (IOException e) {
            log.severe("setPermissions failed " + e);
            result = false;
        }
        return result;
    }

    // TODO remove and provide a proper unit test
    public static void main(String [] arg) {
        System.out.println ("setPermissions returned: " + setPermissions("/tmp/x", "rwxr-xr-x", "rw-r--r--"));
    }
}

When run on the example case:

$ mkdir -p /tmp/x/y/z;touch /tmp/x/y/z/f;chmod 000 /tmp/x/y/z
$ find /tmp/x
/tmp/x
/tmp/x/y
/tmp/x/y/z
find: â/tmp/x/y/zâ: Permission denied
$ java DirectoryTreeOperations
setting dir permission on /tmp/x
setting dir permission on /tmp/x/y
setting dir permission on /tmp/x/y/z
setting dir permission on /tmp/x/y/z/f
setPermissions returned: true
$ find /tmp/x
/tmp/x
/tmp/x/y
/tmp/x/y/z
/tmp/x/y/z/f


问:
How do I get correct date and time from Tweepy?
I'm trying to analyze political tweets.

When I run this code:

```<code>import tweepy
from tweepy import OAuthHandler
import datetime

consumer_key    = '...'
consumer_secret = '...'
access_token    = '...'
access_secret   = '...'

auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)

api = tweepy.API(auth)

username = "VP"
startDate = datetime.datetime(2017, 12, 1, 0, 0, 0)
endDate =   datetime.datetime(2017, 12, 2, 0, 0, 0)

tweets = []
tmpTweets = api.user_timeline(username)
for tweet in tmpTweets:
    if tweet.created_at < endDate and tweet.created_at > startDate:
        tweets.append(tweet)

while (tmpTweets[-1].created_at > startDate):
    print("Last Tweet @", tmpTweets[-1].created_at, "...fetching more")
    tmpTweets = api.user_timeline(username, max_id = tmpTweets[-1].id)
    for tweet in tmpTweets:
        if tweet.created_at < endDate and tweet.created_at > startDate:
            tweets.append(tweet)

for tweet in tweets:
    print(tweet.created_at)
</code>```

I get this:

```<code>Last Tweet @ 2017-12-02 13:52:36 ...fetching more
2017-12-01 21:06:35
2017-12-01 12:29:27
2017-12-01 12:27:36
2017-12-01 00:50:17
2017-12-01 00:47:42
2017-12-01 00:25:32
</code>```

But this is wrong. VP tweeted 3 times on Dec 1. These timestamps appear to be ahead by 4 hours. How do I fix this for Eastern Time?

答:
Timezones..

.created_at is in UTC (+0000) while your startDate and endDate are local datetime objects.

One way to approach is to convert the created_at to local and then compare:

```<code>created_date_local = datetime_from_utc_to_local(tweet.created_at)
if endDate > created_date_local > startDate:
    # ...
</code>```

where datetime_from_utc_to_local is defined as:

```<code>def datetime_from_utc_to_local(utc_datetime):
    now_timestamp = time.time()
    offset = datetime.datetime.fromtimestamp(now_timestamp) - datetime.datetime.utcfromtimestamp(now_timestamp)
    return utc_datetime + offset
</code>```

This is just one way to do it, not necessarily the best.

Prints 3 tweets only, as desired:

```<code>Last Tweet @ 2017-12-02 13:52:36 ...fetching more
2017-12-01 21:06:35
2017-12-01 12:29:27
2017-12-01 12:27:36
</code>```

Body:
I'm trying to analyze political tweets.

When I run this code:

import tweepy
from tweepy import OAuthHandler
import datetime

consumer_key    = '...'
consumer_secret = '...'
access_token    = '...'
access_secret   = '...'

auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)

api = tweepy.API(auth)

username = "VP"
startDate = datetime.datetime(2017, 12, 1, 0, 0, 0)
endDate =   datetime.datetime(2017, 12, 2, 0, 0, 0)

tweets = []
tmpTweets = api.user_timeline(username)
for tweet in tmpTweets:
    if tweet.created_at < endDate and tweet.created_at > startDate:
        tweets.append(tweet)

while (tmpTweets[-1].created_at > startDate):
    print("Last Tweet @", tmpTweets[-1].created_at, "...fetching more")
    tmpTweets = api.user_timeline(username, max_id = tmpTweets[-1].id)
    for tweet in tmpTweets:
        if tweet.created_at < endDate and tweet.created_at > startDate:
            tweets.append(tweet)

for tweet in tweets:
    print(tweet.created_at)

I get this:

Last Tweet @ 2017-12-02 13:52:36 ...fetching more
2017-12-01 21:06:35
2017-12-01 12:29:27
2017-12-01 12:27:36
2017-12-01 00:50:17
2017-12-01 00:47:42
2017-12-01 00:25:32

But this is wrong. VP tweeted 3 times on Dec 1. These timestamps appear to be ahead by 4 hours. How do I fix this for Eastern Time?

Body:
Timezones..

.created_at is in UTC (+0000) while your startDate and endDate are local datetime objects.

One way to approach is to convert the created_at to local and then compare:

created_date_local = datetime_from_utc_to_local(tweet.created_at)
if endDate > created_date_local > startDate:
    # ...

where datetime_from_utc_to_local is defined as:

def datetime_from_utc_to_local(utc_datetime):
    now_timestamp = time.time()
    offset = datetime.datetime.fromtimestamp(now_timestamp) - datetime.datetime.utcfromtimestamp(now_timestamp)
    return utc_datetime + offset

This is just one way to do it, not necessarily the best.

Prints 3 tweets only, as desired:

Last Tweet @ 2017-12-02 13:52:36 ...fetching more
2017-12-01 21:06:35
2017-12-01 12:29:27
2017-12-01 12:27:36


问:
open webview inside a linked list view in android
In my android application i would like to use linked list view wherein i would like to open a webview on click of initial list view.
Is it possible to open a webview inside a listview in android??

Please share your valuable suggestions.

Thanks in advance :)

答:
Webview w = (Webview) findwiewbyid...
w.loadUrl(''http://yourlink.com'')
but you need to create a method to retrieve the link in your listview
parent.getItemAtPosition(position) something like this.</p>


问:
Replacing View using ng-view in angularjs
When the view change its replace the previous view in ng-view. but its not changing. it showing the template data which is "context".

var app = angular.module("myapp", ["ngRoute"]);

app.service('datapass', function () {

    this.name = "name";

});

app.config(function ($routeProvider) {

    $routeProvider
    .when("/name", {

        template: 'Context',
        controller: 'front_controller'
    })
    .when("/detail", {
        template: 'My Name is Awais Saleem',
        controller: 'main_controller'
    })
    .otherwise("/name");

});

app.controller("front_controller", function ($scope, datapass,$location) {
    $scope.url = datapass.name;
    $scope.changeView = function () {

        $scope.url = datapass.name = (datapass.name == "name") ? "detail" : "name";

    };

});

app.controller("main_controller", function ($scope, datapass,$location) {
    $scope.url = datapass.name;

    $scope.changeView = function () {

        $scope.url = datapass.name = (datapass.name == "name") ? "detail" : "name";

    };

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.js"></script>

<body ng-app="myapp">

        <div ng-view></div>

</body></code>```

When i click on the "context" then it should show the other page data, like "My Name is Awais Saleem" and i click on "My name is..." then it show the "Context".
Basically i want to replace the previous view.

答:
The reason it is not working is because $scope.url is only recognized in its controller, and since you don't have any controller in the HTML page, it doesn't know what that means.

A quick and dirty solution would be to add it to the $rootScope, but a better solution would be to add a parent state with a controller, and then all the states will have that functionality also.

Body:
When the view change its replace the previous view in ng-view. but its not changing. it showing the template data which is "context".

var app = angular.module("myapp", ["ngRoute"]);

app.service('datapass', function () {

    this.name = "name";

});

app.config(function ($routeProvider) {

    $routeProvider
    .when("/name", {

        template: 'Context',
        controller: 'front_controller'
    })
    .when("/detail", {
        template: 'My Name is Awais Saleem',
        controller: 'main_controller'
    })
    .otherwise("/name");

});

app.controller("front_controller", function ($scope, datapass,$location) {
    $scope.url = datapass.name;
    $scope.changeView = function () {

        $scope.url = datapass.name = (datapass.name == "name") ? "detail" : "name";

    };

});

app.controller("main_controller", function ($scope, datapass,$location) {
    $scope.url = datapass.name;

    $scope.changeView = function () {

        $scope.url = datapass.name = (datapass.name == "name") ? "detail" : "name";

    };

});

When i click on the "context" then it should show the other page data, like "My Name is Awais Saleem" and i click on "My name is..." then it show the "Context".
Basically i want to replace the previous view.


问:
Comparing integer in int array to a user provided integer
I have a two dimensional array, gridArray[5][7], populated with numbers (only the last row is populated with anything other than 0). I'm taking user input for a column and color, converting the color to a number representation, and then checking it against the rows in the array. If it's in the column the user enters, it should print "Your guess was correct". Instead, it seems to print "Your guess was incorrect", even if the guess was correct. I checked the boolean values, and it's returning false when it should be returning true. I can't figure out why. Here's my code:

```<code>public static void main(String[] args) {
        int[][] gridArray = new int[7][5];

        gridPop(gridArray);

        playFunc(gridArray);

    }

public static void playFunc(int[][] gridArray) {
    char colorGuess = 'N';
    int columnGuess = -1;
    String columnString = "a column to guess";
    boolean correctIncorrectGuess = false;

    System.out.println("Please enter a color to guess (R/B/P/Y/G)");
        colorGuess = charCheck();
            System.out.println("Please enter a column to guess");
            System.out.println("The column # must be between 1 and 5");
                columnGuess = intChecker(columnString);
                    correctIncorrectGuess = checkHat(gridArray, charReturn(colorGuess), columnGuess);
            System.out.println("Your guess was " + boolCorrectString(correctIncorrectGuess));
}

public static boolean checkHat(int[][] gridArray, int color, int column){
    boolean guess = false;
    for (int i = 0; i < gridArray.length; i++) {
        if (gridArray[i][column] == color) {
            guess = true;
        } else {
            guess = false;
        }
    }
    return guess;
}

public static int intChecker(String object) {
    boolean correctInput = false;
    int userInput = 0;

    while (!correctInput) {
        try {
            userInput = scanner.nextInt();
            correctInput = true;
        } catch(InputMismatchException e) {
            System.out.println("I'm sorry, that doesn't seem to be a number");
            System.out.println("Please enter " +object);
            scanner.next();
        }
    }

    return userInput;
}

public static String boolCorrectString(boolean toString) {
    String correctInc = "";
        if (toString) {
            correctInc = "correct";
        } else {
            correctInc = "incorrect";
        }
        return correctInc;
}

public static int charReturn(char color) {
    int colorToInt = -1;
        if (color == 'G') {
            colorToInt =  1;
        } else if (color == 'R') {
            colorToInt =  2;
        } else if (color == 'B') {
            colorToInt =  3;
        } else if (color == 'P') {
            colorToInt =  4;
        } else if (color == 'Y') {
            colorToInt =  5;
        } else if (color == 'g') {
            colorToInt =  1;
        } else if (color == 'r') {
            colorToInt =  2;
        } else if (color == 'b') {
            colorToInt =  3;
        } else if (color == 'p') {
            colorToInt =  4;
        } else if (color == 'y') {
            colorToInt =  5;
        }
return colorToInt;
}

    public static char charCheck() {
        char userInput = 'N';

        userInput =  scanner.next().charAt(0);
            while((userInput != 'G') && (userInput != 'Y') && (userInput != 'B')
            && (userInput != 'R') && (userInput != 'P') && (userInput != 'g') &&
            (userInput != 'y') && (userInput != 'b') && (userInput != 'r') && (userInput != 'p')) {
                System.out.println("Please enter R/B/P/Y/G");
                    userInput =  scanner.next().charAt(0);
            }
            return userInput;
    }
</code>```

I did some testing, and it's gathering the right numbers for the column, the representation of the color, etc. It seems that even when gridArray[i][column] should be the same as the guessed color, the boolean is being returned as false (I tested and it isnt printing incorrectly -- it's actually finding false when it should be true). Why isn't the code comparing the gridArray entry and the color guess correctly? Where does the code break down?

EDIT:
Gridpop method

```<code>public static void gridPop(int[][] gridArray) {
    for (int i=0; i < gridArray[6].length; i++) {
        int randomNum = ThreadLocalRandom.current().nextInt(1, 6);
            gridArray[6][i] = randomNum;
    }
    for (int i=5; i >= 0; i--) {
        for (int j=0; j < gridArray[i].length; j++) {
            gridArray[i][j] = 0;
        }
    }
}
</code>```

EDIT: I'm actually very very dumb. It was an off by one error, as it was checking at the user entered column, not the user entered column -1

答:
Your problem lies within the checkHat() method. When the matching element is first found, you set the boolean guess to true; however, when the next value checked is not equal to color guess is set back to false. Something like this should work:</p>

```<code>public static boolean checkHat(int[][] gridArray, int color, int column){
    for (int i = 0; i < gridArray.length; i++) {
        if (gridArray[i][column] == color) {
            return true;
        }
    }
    return false;
}
</code>```

Body:
I have a two dimensional array, gridArray[5][7], populated with numbers (only the last row is populated with anything other than 0). I'm taking user input for a column and color, converting the color to a number representation, and then checking it against the rows in the array. If it's in the column the user enters, it should print "Your guess was correct". Instead, it seems to print "Your guess was incorrect", even if the guess was correct. I checked the boolean values, and it's returning false when it should be returning true. I can't figure out why. Here's my code:

public static void main(String[] args) {
        int[][] gridArray = new int[7][5];

        gridPop(gridArray);

        playFunc(gridArray);

    }

public static void playFunc(int[][] gridArray) {
    char colorGuess = 'N';
    int columnGuess = -1;
    String columnString = "a column to guess";
    boolean correctIncorrectGuess = false;

    System.out.println("Please enter a color to guess (R/B/P/Y/G)");
        colorGuess = charCheck();
            System.out.println("Please enter a column to guess");
            System.out.println("The column # must be between 1 and 5");
                columnGuess = intChecker(columnString);
                    correctIncorrectGuess = checkHat(gridArray, charReturn(colorGuess), columnGuess);
            System.out.println("Your guess was " + boolCorrectString(correctIncorrectGuess));
}

public static boolean checkHat(int[][] gridArray, int color, int column){
    boolean guess = false;
    for (int i = 0; i < gridArray.length; i++) {
        if (gridArray[i][column] == color) {
            guess = true;
        } else {
            guess = false;
        }
    }
    return guess;
}

public static int intChecker(String object) {
    boolean correctInput = false;
    int userInput = 0;

    while (!correctInput) {
        try {
            userInput = scanner.nextInt();
            correctInput = true;
        } catch(InputMismatchException e) {
            System.out.println("I'm sorry, that doesn't seem to be a number");
            System.out.println("Please enter " +object);
            scanner.next();
        }
    }

    return userInput;
}

public static String boolCorrectString(boolean toString) {
    String correctInc = "";
        if (toString) {
            correctInc = "correct";
        } else {
            correctInc = "incorrect";
        }
        return correctInc;
}

public static int charReturn(char color) {
    int colorToInt = -1;
        if (color == 'G') {
            colorToInt =  1;
        } else if (color == 'R') {
            colorToInt =  2;
        } else if (color == 'B') {
            colorToInt =  3;
        } else if (color == 'P') {
            colorToInt =  4;
        } else if (color == 'Y') {
            colorToInt =  5;
        } else if (color == 'g') {
            colorToInt =  1;
        } else if (color == 'r') {
            colorToInt =  2;
        } else if (color == 'b') {
            colorToInt =  3;
        } else if (color == 'p') {
            colorToInt =  4;
        } else if (color == 'y') {
            colorToInt =  5;
        }
return colorToInt;
}

    public static char charCheck() {
        char userInput = 'N';

        userInput =  scanner.next().charAt(0);
            while((userInput != 'G') && (userInput != 'Y') && (userInput != 'B')
            && (userInput != 'R') && (userInput != 'P') && (userInput != 'g') &&
            (userInput != 'y') && (userInput != 'b') && (userInput != 'r') && (userInput != 'p')) {
                System.out.println("Please enter R/B/P/Y/G");
                    userInput =  scanner.next().charAt(0);
            }
            return userInput;
    }

I did some testing, and it's gathering the right numbers for the column, the representation of the color, etc. It seems that even when gridArray[i][column] should be the same as the guessed color, the boolean is being returned as false (I tested and it isnt printing incorrectly -- it's actually finding false when it should be true). Why isn't the code comparing the gridArray entry and the color guess correctly? Where does the code break down?

EDIT:
Gridpop method

public static void gridPop(int[][] gridArray) {
    for (int i=0; i < gridArray[6].length; i++) {
        int randomNum = ThreadLocalRandom.current().nextInt(1, 6);
            gridArray[6][i] = randomNum;
    }
    for (int i=5; i >= 0; i--) {
        for (int j=0; j < gridArray[i].length; j++) {
            gridArray[i][j] = 0;
        }
    }
}

EDIT: I'm actually very very dumb. It was an off by one error, as it was checking at the user entered column, not the user entered column -1

Body:
Your problem lies within the checkHat() method. When the matching element is first found, you set the boolean guess to true; however, when the next value checked is not equal to color guess is set back to false. Something like this should work:

public static boolean checkHat(int[][] gridArray, int color, int column){
    for (int i = 0; i < gridArray.length; i++) {
        if (gridArray[i][column] == color) {
            return true;
        }
    }
    return false;
}


问:
Rails form_with change submit text
I'm creating a new form using form_with helper and as you know is detecting if you are on a new record page or a edit page ([following the CRUD example from rails guide][1], i render the form as a partial to reuse the form) changing the text on the submit button depending where i call the form.

```<code><%= form_with model: @article, local: true do |form| %>
   <p>
       <%= form.label :title %>
       <%= form.text_field :title %>
   </p>
   <p>
       <%= form.submit %>
   </p>
<% end %>
</code>```

But i want to the text on the form submit helpers for translating purpose, but I don't know if is possible to preserve the Create/Update recognition functionality and if there are some helper or class where I can configure those labels.

答:
Dont mess up your form with conditions.Put those conditions in helper classes

form.rb

..
<%= form.submit frm_action %>
..

And your helper method like this

helper.rb

```<code>def frm_action
  if @article.id.present?
    "Create"
  else
    "Update"
  end
end
</code>```

Title: Rails form_with change submit text

Body:
I'm creating a new form using form_with helper and as you know is detecting if you are on a new record page or a edit page ([following the CRUD example from rails guide][1], i render the form as a partial to reuse the form) changing the text on the submit button depending where i call the form.

<%= form_with model: @article, local: true do |form| %>

       <%= form.label :title %>
       <%= form.text_field :title %>

       <%= form.submit %>

<% end %>

But i want to the text on the form submit helpers for translating purpose, but I don't know if is possible to preserve the Create/Update recognition functionality and if there are some helper or class where I can configure those labels.

Body:
Dont mess up your form with conditions.Put those conditions in helper classes

form.rb

..
<%= form.submit frm_action %>
..

And your helper method like this

helper.rb

def frm_action
  if @article.id.present?
    "Create"
  else
    "Update"
  end
end


问:
Why is that my $wpdb->delete value is FALSE, And won't execute properly?
I'm going to delete a row in a table using the $wpdb object

here's my code:

```<code>function delete_variation($variation_ID){
    $where = array(
            'ID' => $variation_ID,
            'post_type' => 'product_variation'
        );
    $table_name = 'wp-posts';
    $wpdb->delete( $table_name , $where);
}
</code>```

every arguments are fine, I've got results.. But the

```<code>$wpdb->delete( $table_name , $where);
</code>```

returned FALSE and won't execute?

no errors has been found, everything seems okay, just that it returned FALSE.

Thanks!

答:
try modifying your function as below :

```<code>function delete_variation($variation_ID){
    global $wpdb;
    $where = array(
            'ID' => $variation_ID,
            'post_type' => 'product_variation'
        );
    $table_name = $wpdb->prefix.'posts'; // IDEAL WAY FOR TABLE PREFIX
    $wpdb->delete( $table_name , $where);
}
</code>```

Hope this will help you!

Body:
I'm going to delete a row in a table using the $wpdb object

here's my code:

function delete_variation($variation_ID){
    $where = array(
            'ID' => $variation_ID,
            'post_type' => 'product_variation'
        );
    $table_name = 'wp-posts';
    $wpdb->delete( $table_name , $where);
}

every arguments are fine, I've got results.. But the

$wpdb->delete( $table_name , $where);

returned FALSE and won't execute?

no errors has been found, everything seems okay, just that it returned FALSE.

Thanks!

Body:
try modifying your function as below :

function delete_variation($variation_ID){
    global $wpdb;
    $where = array(
            'ID' => $variation_ID,
            'post_type' => 'product_variation'
        );
    $table_name = $wpdb->prefix.'posts'; // IDEAL WAY FOR TABLE PREFIX
    $wpdb->delete( $table_name , $where);
}

Hope this will help you!


答: You can't rollback a transaction after it is committed. </p>

Title: Can I roll back a JTA transcation after I commit it?

Body:
I have a JTA transcation which I commit.  Can I roll it back after I commit?  If yes, how? I have following situation.

I have a backend layer which updated 3 DBs.  I have used JTA user transcation for it.  If update in any DB fails all updates to 3 DBs are rolled back using utx.rollback

Now I have a layer on top of backend layer which updates some other DB.  Now I want that step 1 and step 2 should both succeed or both fail, so I want to roll back JTA transcation of step 1 in case step 2 fails.

It's difficult for me to put code of step 2 into 1 as we are using some existing APIs to update DB in step 2.


问:
XMP metadata for "how this was created?"
I want to add metadata to plain text and binary files. These files tend to be derived from a canonical source on the internet (which might get updated etc). For example, I might do something like curl $URL | obscure_magical_filter_that_took_me_ages > file.txt

If possible, I want to do this in a vaguely standard way. XMP would appear to be a good standard, with exiftool being a good command-line tool for interacting with this.

I can create sidecar files like so:

```<code>exiftool -Creator="Joe Creator" -xmp -o test.xmp
</code>```

The issue is that there doesn't seem to be a metadata field for "how was this made?". What should I use?

Exiftool's documentation has a good list of fields.
Out of these, OriginatingProgram seems like the best match: Is this a good thing to use?

Where can I put metadata for "How was this command created"*.

Links

This page lists some metadata standards

The PROV metadata standard looks interesting

An alternative approach uses something like a Makefile for this provenance information.

答:
There really isn't a specific tag along these lines that I can think of, so you can either re-purpose a tag or create your own tag.

One thing to take into account is how are you going to access the info in the sidecar files.  OriginatingProgram is an ACDSee specific file and is unlikely to be read by most programs that would read sidecar files.  Additionally, it sounds like it would likely be overwritten if ACDSee ever changed data in that sidecar file.

If you're setting up you're own system to read and processes sidecar files, then creating your own tag might be the way to go.  Exiftool's example config file has info on doing so and more help can be found on the exiftool forums.  But such a tag will probably not be visible to most software.

Re-purposing a more common tag that you might be a convenient strategy.  If you have no plans on using a tag like Title or Description, then those are easy and well supported tags.  Otherwise you could look to re-purpose a different tag that may not be relevant to the file, such as City, State or Country.  Instructions might also be a good choice, as I believe it's intended purpose is for restrictions or right usages, which wouldn't really apply to a non-image or video file.

Personally, I tend to place miscellaneous info that is still important to the file in HierarchicalSubject.  You can set it apart from other keywords in it's own hierarchy and it's still available and easy to see with most software.

ContentLicense: CC BY-SA 4.0

Body:
I want to add metadata to plain text and binary files. These files tend to be derived from a canonical source on the internet (which might get updated etc). For example, I might do something like curl $URL | obscure_magical_filter_that_took_me_ages > file.txt

If possible, I want to do this in a vaguely standard way. XMP would appear to be a good standard, with exiftool being a good command-line tool for interacting with this.

I can create sidecar files like so:

exiftool -Creator="Joe Creator" -xmp -o test.xmp

The issue is that there doesn't seem to be a metadata field for "how was this made?". What should I use?

Exiftool's documentation has a good list of fields.
Out of these, OriginatingProgram seems like the best match: Is this a good thing to use?

Where can I put metadata for "How was this command created"*.

Links

This page lists some metadata standards

The PROV metadata standard looks interesting

An alternative approach uses something like a Makefile for this provenance information.


问:
Actions must be plain objects. Use custom middleware for async actions.how to solve this
In my react redux app error like this (Uncaught Error: Actions must be plain objects. Use custom middleware for async actions.) is showing every thing which is important to run this app are successfully installed so do not need to worry about that it google it several time but nothing happen anybody have an idea to solve this your effort will be appreciated in this case and thanks in advance

this is my action index.js

```<code>export function CounterActions(){
    return {
        type: "Add"
    }
}
</code>```

this is my reducer counterApp.js

```<code>    const initialState = {
        counter: 0
    }

    function counterApp(state, action) {
        if (typeof state === "undefined"){
            return initialState;
        }

        switch (action.type) {
            case "Add":
                return Object.assign( {}, state, { counter: state.counter + 1 } );
            default:
                return state;
        }
    }

export default counterApp;
</code>```

this is my store store.js

```<code>import { createStore } from 'redux';

import counterApp from './reducers/counterApp';

let store  = createStore(counterApp);

export default store;
</code>```

and this is my component app.jsx

```<code>    import React, { Component } from 'react';
    import { connect } from 'react-redux';
    import { CounterActions } from '../actions/index';

    class App extends Component{
        constructor(props){
            super(props);
        }
        click(){
            this.props.testClick();
        }

        render(){
            return(
                <div>
                    <h1>React Redux</h1>
                    <h2>Counter: {this.props.counter}</h2>
                    <button onClick={this.click.bind(this)}>Count ++ </button>
                </div>
            )
        }
    }

    const mapDispatchToProps = (dispatch) => {
        return {
            testClick: () => dispatch(CounterActions("Add"))
        }
    }

    const mapStateToProps = (state) => {
        return state;
    }

export default connect(mapDispatchToProps, mapStateToProps)(App);
</code>```

答:
The order in which you pass arguments to connect is incorrect. Reverse the order of arguments and it should be fine.

```<code>export default connect(mapStateToProps, mapDispatchToProps)(App);
</code>```

The syntax of connect is as follows:

```<code>connect([mapStateToProps], [mapDispatchToProps], [mergeProps], [options])
</code>```

Body:
In my react redux app error like this (Uncaught Error: Actions must be plain objects. Use custom middleware for async actions.) is showing every thing which is important to run this app are successfully installed so do not need to worry about that it google it several time but nothing happen anybody have an idea to solve this your effort will be appreciated in this case and thanks in advance

this is my action index.js

export function CounterActions(){
    return {
        type: "Add"
    }
}

this is my reducer counterApp.js

    const initialState = {
        counter: 0
    }

    function counterApp(state, action) {
        if (typeof state === "undefined"){
            return initialState;
        }

        switch (action.type) {
            case "Add":
                return Object.assign( {}, state, { counter: state.counter + 1 } );
            default:
                return state;
        }
    }

export default counterApp;

this is my store store.js

import { createStore } from 'redux';

import counterApp from './reducers/counterApp';

let store  = createStore(counterApp);

export default store;

and this is my component app.jsx

    import React, { Component } from 'react';
    import { connect } from 'react-redux';
    import { CounterActions } from '../actions/index';

    class App extends Component{
        constructor(props){
            super(props);
        }
        click(){
            this.props.testClick();
        }

        render(){
            return(

React Redux

Counter: {this.props.counter}

                    <button onClick={this.click.bind(this)}>Count ++ </button>

            )
        }
    }

    const mapDispatchToProps = (dispatch) => {
        return {
            testClick: () => dispatch(CounterActions("Add"))
        }
    }

    const mapStateToProps = (state) => {
        return state;
    }

export default connect(mapDispatchToProps, mapStateToProps)(App);

Body:
The order in which you pass arguments to connect is incorrect. Reverse the order of arguments and it should be fine.

export default connect(mapStateToProps, mapDispatchToProps)(App);

The syntax of connect is as follows:

connect([mapStateToProps], [mapDispatchToProps], [mergeProps], [options])


问:
MVC Custom Attribute - Client-side Validation - Warning: No message defined for 'field'
I tried to create a custom data annotation validation attribute (NameValidationAttribute) in MVC 5 project using VS2013. I was able to successfully add the client side validation and the error message for custom validation is getting displayed as soon as the focus leaves the textbox. However, the standard attributes like [Required] and [Range] validators are now not showing proper error messages, says 'Warning: No message defined for 'field' ' (See below screenshot).

Question:
- Why the standard validation error messages are showing as "Warning: No message defined for UnitsInStock"? What am I missing?

Below is my custom client validation script:

I included following scripts in EditProducts page.

Please note that the error messages for UnitPrice, UnitsInStock and ReorderLevel fields are defined with Range validation attribute (see below).

FYI, I tried to change the order of the scripts in ProductEdit page but still its showing the same message.

Please advise!

答:
jQuery unobtrusive need data-msg for default validate message.
This is how to apply dynamic error message from your model to Html

```<code>  $.validator.unobtrusive.adapters.add("requireif", function (options) {
        $('#' + options.element.id).attr("data-msg", options.message);
        // Add rule ...
    });
</code>```

You can change default warning message.

```<code> $.validator.addMethod("requireif", function (value, element, pair) {
        // validate logic
        return true/false;
 }, "YOUR DEFAULT MESSAGE HERE");
</code>```

Or

```<code>  @Html.TextBoxFor(m => m.Property1, new { Class = "form-control", data_msg = "YOUR DEFAULT MESSAGE HERE" })
</code>```

Or if you can put it directly to your Html like this.

```<code><input class="form-control" data-msg="YOUR DEFAULT MESSAGE HERE"/>
</code>```

Body:
jQuery unobtrusive need data-msg for default validate message.
This is how to apply dynamic error message from your model to Html

  $.validator.unobtrusive.adapters.add("requireif", function (options) {
        $('#' + options.element.id).attr("data-msg", options.message);
        // Add rule ...
    });

You can change default warning message.

 $.validator.addMethod("requireif", function (value, element, pair) {
        // validate logic
        return true/false;
 }, "YOUR DEFAULT MESSAGE HERE");

Or

  @Html.TextBoxFor(m => m.Property1, new { Class = "form-control", data_msg = "YOUR DEFAULT MESSAGE HERE" })

Or if you can put it directly to your Html like this.

<input class="form-control" data-msg="YOUR DEFAULT MESSAGE HERE"/>


问:
yii redirect with array
```<code>$this->redirect(array($redirect, 'error' => $error, 'msg' => $msg, 'details' => $details));
</code>```

How can we pass array as a parameter?
I have tried during redirection.

Returning:

Error 400 Your request is invalid.

Any help would be appreciated.

答: After a lots of tries I have found that , the array what I was passing is an associative array and passing with GET method, so while redirection if we seen in URL, associative array passing with every internal element of $details array, and same parameters are not listed at destination method, so the result will not found such a method.

Title: yii redirect with array

Body:
$this->redirect(array($redirect, 'error' => $error, 'msg' => $msg, 'details' => $details));

How can we pass array as a parameter?
I have tried during redirection.

Returning:

Error 400 Your request is invalid.

Any help would be appreciated.


问:
How to write two ampersand for JavaScript in WordPress?
I use WordPress 3.0.1 and install Exec-PHP plugin. I edit the code in admin panel- pages - html cede. I want to add some JavaScript in a custom page.

When the code use two ampersand, it occupy wrong. && become && How to solve this problem?

```<code>for(i=0;i<3;i++)
{
   var l=a.length;
   //alert(l);
   var iNum=parseInt(Math.random()*l);
   //alert(iNum);

   b[i]=a[iNum];
   if(iNum==0&&iNum+1!=l){a.shift();}else if(iNum+1==l){a.pop()}else{a.splice(iNum,1)}
   //alert(b[i]);
   document.write(b[i]);
}
</code>```

答:
Are you passing a script in through the content area? Why is this being parsed and escaped by WordPress?

If you are passing it into the content area, WordPress is escaping those characters.  Otherwise, people could use SQL injection to inject a XSS onto your page (e.g. running some Javascript on https://malicious.site/whatever.js).

This might not work, but try just switching to Text rather than Visual in the editor. I think that might be the issue. If you switch to Text, I bet you will see the coded ampersands in the HTML.

Body:
I use WordPress 3.0.1 and install Exec-PHP plugin. I edit the code in admin panel- pages - html cede. I want to add some JavaScript in a custom page.

When the code use two ampersand, it occupy wrong. && become && How to solve this problem?

for(i=0;i<3;i++)
{
   var l=a.length;
   //alert(l);
   var iNum=parseInt(Math.random()*l);
   //alert(iNum);

   b[i]=a[iNum];
   if(iNum==0&&iNum+1!=l){a.shift();}else if(iNum+1==l){a.pop()}else{a.splice(iNum,1)}
   //alert(b[i]);
   document.write(b[i]);
}


问:
Bootstrap button doesn't open
I'm not able to figure out why my boostrap button doesn't open.

I've seen previous questions with Jquery order being the issue, but I think this is not my problem here. Right?

I'm following the examples from the bootstrap official website.

Could someone help me please?

My code

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">

    T!
    <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#main-navbar" aria-controls="main-navbar" aria-expanded="false" aria-label="Toggle navigation">

                    </button>

TEST1(current)

TEST2

TEST3

```

答:
Don't use (#) while assigning id.
That's what the problem is.

Remove # from

```<code><div class="collapse navbar-collapse" id="#main-navbar">
</code>```

And everything will start working.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">

    T!
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#main-navbar" aria-controls="main-navbar" aria-expanded="false" aria-label="Toggle navigation">

  </button>

TEST1(current)

TEST2

TEST3

```

Title: Bootstrap button doesn't open

Body:
Don't use (#) while assigning id.
That's what the problem is.

Remove # from

<div class="collapse navbar-collapse" id="#main-navbar">

And everything will start working.

<!-- Bootstrap CSS-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
<div class="container-fluid">
  <hr id="hr-nav">
  <nav class="navbar navbar-expand-lg navbar-dark bg-dark" role="navigation">
    <a class="navbar-brand" href="#">T!</a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#main-navbar" aria-controls="main-navbar" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
    <div class="collapse navbar-collapse" id="main-navbar">
      <ul class="navbar-nav mr-auto navbar-center">
        <li class="nav-item active"><a class="nav-link" href="#">TEST1<span class="sr-only">(current)</span></a></li>
        <li><a class="nav-link" href="#">TEST2</a></li>
        <li><a class="nav-link" href="#">TEST3</a></li>
      </ul>
    </div>
  </nav>
  <hr id="hr-nav">
</div>


问:
How good is Apache POI word support?
On the web page, it looks like there is no current development in the old style .doc.

Is it good enough to create complex documents?

Can it read all .docs without crashing?

What features do (not) work?

I am not currently interested in the XML based formats, as I don't control the client side.

The excel support seems to be much better.

答:
If you are looking for programmatically reading or writing doc files, I believe you're better of with remoting OpenOffice or StarOffice. We've done this at a former company, even though it's a pretty heavy solution, it worked quite well. OpenOffice has (right after Word) a very good doc-Support. For remoting it's a lot better than Word itself. At said company we (earlier) used to remotecontrol Word with frequent problems because Word (on saving a document) insisted on displaying a warning dialog from time to time. Bad idea on a server deep down in some datacenter with nobody close to it.

As this was a Java shop, the very good OpenOffice support for Java came in handy. In fact, they even used to bundle the commercial version StarOffice and had some very good contacts at and help from Sun.

Disclaimer: As andHapp and alepuzio said, POI is very good in Excel support and I'm using it with big success. Last time I've seen the doc support, I didn't dare using it in production (for customers). I haven't looked at doc support for at least two years.

OwnerDisplayName: Stephan Eggermont

Title: How good is Apache POI word support?

LastEditorDisplayName: warren

OwnerDisplayName: Olaf


问:
Error Stream was not readble
I wrote the code below and I got an error (Stream was not readble) while execute this line SR = New StreamReader(FS) why and how to fix it

the code :

```<code>Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim FS As FileStream
    Dim SR As StreamReader
    Dim SW As StreamWriter
    Dim FS_Out As FileStream
    FS = New FileStream("C:\Temp\My Picture.JPG", System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write)
    SR = New StreamReader(FS)
    FS_Out = New FileStream("C:\Temp\My Picture Out.JPG", FileMode.Create, FileAccess.ReadWrite)
    SW = New StreamWriter(FS_Out)

    Dim alltext As String
    FS.Seek(0, SeekOrigin.Begin)
    alltext = SR.ReadToEnd()

    'SW.Write (Buffer)

    SR.Close()
    FS.Close()

End Sub
</code>```

答: It appear you mismatch the mode on FS, it should be FileAccess.ReadWrite.

Title: Error Stream was not readble

Body:
I wrote the code below and I got an error (Stream was not readble) while execute this line SR = New StreamReader(FS) why and how to fix it

the code :

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim FS As FileStream
    Dim SR As StreamReader
    Dim SW As StreamWriter
    Dim FS_Out As FileStream
    FS = New FileStream("C:\Temp\My Picture.JPG", System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write)
    SR = New StreamReader(FS)
    FS_Out = New FileStream("C:\Temp\My Picture Out.JPG", FileMode.Create, FileAccess.ReadWrite)
    SW = New StreamWriter(FS_Out)

    Dim alltext As String
    FS.Seek(0, SeekOrigin.Begin)
    alltext = SR.ReadToEnd()

    'SW.Write (Buffer)

    SR.Close()
    FS.Close()

End Sub


问:
update web.config custom values in asp.net
I want to update some values in the web,config through c# code. Here below I am giving the config file which I have,

<configuration>
 <applicationSettings>
    <ProjectName.Properties.Settings>
       <setting name="Employees" serializeAs="Xml">
        <value>
          <ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
            <string>000001;PSWD;DId\Emp1;Password</string>
          </ArrayOfString>
        </value>
      </setting>
    </ProjectName.Properties.Settings>
  </applicationSettings>
</configuration>```

Here in this, based on the employee(DId\Emp1) I want to update the password through c# code.

答:
You can just read file and save back. </p>

```<code>string password = "pass";
//phycial path of the web config file.
string str =File.ReadAllText(".\web.config");
str = str.replace("000001;PSWD;DId\Emp1;Password","000001;PSWD;DId\Emp1;"& password);
 File.WriteAllText(".\web.config", str);
</code>```

Body:
I want to update some values in the web,config through c# code. Here below I am giving the config file which I have,

<configuration>
 <applicationSettings>
    <ProjectName.Properties.Settings>
       <setting name="Employees" serializeAs="Xml">
        <value>
          <ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
            <string>000001;PSWD;DId\Emp1;Password</string>
          </ArrayOfString>
        </value>
      </setting>
    </ProjectName.Properties.Settings>
  </applicationSettings>
</configuration>

Here in this, based on the employee(DId\Emp1) I want to update the password through c# code.

Body:
You can just read file and save back.

string password = "pass";
//phycial path of the web config file.
string str =File.ReadAllText(".\web.config");
str = str.replace("000001;PSWD;DId\Emp1;Password","000001;PSWD;DId\Emp1;"& password);
 File.WriteAllText(".\web.config", str);