问:
need to drop pin at two places... current location and events locations
I need help on this .... drop the pins.

current location.... pin drop.... with blue....
Event location :locations latitude:53.373812...longitude 4.890951 with red pin.

I did like this:

```<code>@interface AddressAnnotation : NSObject<MKAnnotation> {
    CLLocationCoordinate2D coordinate;

    NSString *mTitle;
    NSString *mSubTitle;

//  CLLocationManager *locationManager;
//  CLLocation *currentLocation;
}
@end
@interface MapViewController : UIViewController <CLLocationManagerDelegate>  {

    IBOutlet MKMapView *mapView;
    AddressAnnotation *addAnnotation;
    NSString *address;
    CLLocationManager *locationManager;
    CLLocation *currentLocation;
}
+(MapViewController *)sharedInstance;
-(void)start;
-(void)stop;
-(BOOL)locationKnown;
@property(nonatomic,retain)CLLocation *currentLocation;
@property(nonatomic,retain)NSString *address;
-(CLLocationCoordinate2D) addressLocation;
-(void)showAddress;

@end
</code>```

//Implementation file.

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

@implementation AddressAnnotation
@synthesize coordinate;
//@synthesize currentLocation;

- (NSString *)subtitle{
    //return @"Sub Title";
    return @"Event";
}
- (NSString *)title{
    //return @"Title";
    return @"Location ";
}

-(id)initWithCoordinate:(CLLocationCoordinate2D) c{
    coordinate=c;
    //NSLog(@"%f,%f",c.latitude,c.longitude);
    return self;
}

@end

@implementation MapViewController
@synthesize address;
@synthesize currentLocation;

static MapViewController *sharedInstance;

+(MapViewController *)sharedInstance{
    @synchronized (self)
    {
        if (!sharedInstance)
            [[MapViewController alloc]init];
        }
    return sharedInstance;
}
+(id)alloc{
    @synchronized(self){
        NSAssert(sharedInstance==nil,"Attempted to allocate a second instance of a singleton LocationController.");
        sharedInstance = [super alloc];
    }
    return sharedInstance;
}
-(id)init{
    if(self==[super init]){
        self.currentLocation=[[CLLocation alloc]init];
        locationManager=[[CLLocationManager alloc]init];
        locationManager.delegate=self;
        [self start];
    }
    return self;
}
-(void)start{
    NSLog(@"Start");
    [locationManager startUpdatingLocation];
}
-(void)stop{
    [locationManager stopUpdatingLocation];
}
-(BOOL)locationKnown{
    if (round(currentLocation.speed)==-1)
        return NO;
        else return YES;

}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    if (abs([newLocation.timestamp timeIntervalSinceDate:[NSDate date]])<120){
        self.currentLocation=newLocation;
    }
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    UIAlertView *alert;
    alert=[[UIAlertView alloc]initWithTitle:@"Error" message:[error description] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
    [alert release];
}
        // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"Map-View";
    [self addressLocation];
    [self showAddress];
    NSLog(@"address is %@",address);

}

-(void)showAddress{

    MKCoordinateRegion region;
    MKCoordinateSpan span;
    span.latitudeDelta=0.2;
    span.longitudeDelta=0.2;

    CLLocationCoordinate2D location = [self addressLocation];
    region.span=span;
    region.center=location;

    if(addAnnotation != nil) {
        [mapView removeAnnotation:addAnnotation];
        [addAnnotation release];
        addAnnotation = nil;
    }

    addAnnotation = [[AddressAnnotation alloc] initWithCoordinate:location];
    [mapView addAnnotation:addAnnotation];

    [mapView setRegion:region animated:TRUE];
    [mapView regionThatFits:region];

}

-(CLLocationCoordinate2D) addressLocation {

    NSString *urlString = [NSString stringWithFormat:@"http://maps.google.com/maps/geo?q=%@&output=csv",

   [address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

    NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString]];
    NSArray *listItems = [locationString componentsSeparatedByString:@","];

    double latitude = 0.0;
    double longitude = 0.0;

    if([listItems count] >= 4 && [[listItems objectAtIndex:0] isEqualToString:@"200"]) {
        latitude = [[listItems objectAtIndex:2] doubleValue];
        longitude = [[listItems objectAtIndex:3] doubleValue];
    }
    else {
        //Show error
    }
    CLLocationCoordinate2D location;
    location.latitude = latitude;
    location.longitude = longitude;

    return location;
}

- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>) annotation{

    MKPinAnnotationView *annView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"currentloc"];
    annView.pinColor = MKPinAnnotationColorRed;
    annView.animatesDrop=YES;
    annView.canShowCallout = YES;
    annView.calloutOffset = CGPointMake(-5, 5);
    return annView;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Overriden to allow any orientation.
    return YES;
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];

    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)dealloc {
    [address release];
    [super dealloc];
}

@end
</code>```

Please help me out...

thanks in adavance.

答:
Showing user current location is simple.

```<code>-(void)start{
    NSLog(@"Start");
     mapView.showsUserLocation=YES; //This will show the current location as blue dot in your mapview
    [locationManager startUpdatingLocation];
}
-(void)stop{
     mapView.showsUserLocation=NO;
    [locationManager stopUpdatingLocation];
}
</code>```

In your viewForAnnotation Delegate

```<code>- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {
if (annotation == mapView.userLocation)
{
    // This code will execute when the current location is called.
    return nil;
}
else
{
    MKPinAnnotationView *annView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"currentloc"];
    annView.pinColor = MKPinAnnotationColorRed;
    annView.animatesDrop=YES;
    annView.canShowCallout = YES;
    annView.calloutOffset = CGPointMake(-5, 5);
    return annView;
}
</code>```

Body:
I need help on this .... drop the pins.

current location.... pin drop.... with blue....
Event location :locations latitude:53.373812...longitude 4.890951 with red pin.

I did like this:

@interface AddressAnnotation : NSObject<MKAnnotation> {
    CLLocationCoordinate2D coordinate;

    NSString *mTitle;
    NSString *mSubTitle;

//  CLLocationManager *locationManager;
//  CLLocation *currentLocation;
}
@end
@interface MapViewController : UIViewController <CLLocationManagerDelegate>  {

    IBOutlet MKMapView *mapView;
    AddressAnnotation *addAnnotation;
    NSString *address;
    CLLocationManager *locationManager;
    CLLocation *currentLocation;
}
+(MapViewController *)sharedInstance;
-(void)start;
-(void)stop;
-(BOOL)locationKnown;
@property(nonatomic,retain)CLLocation *currentLocation;
@property(nonatomic,retain)NSString *address;
-(CLLocationCoordinate2D) addressLocation;
-(void)showAddress;

@end

//Implementation file.

#import "MapViewController.h"

@implementation AddressAnnotation
@synthesize coordinate;
//@synthesize currentLocation;

- (NSString *)subtitle{
    //return @"Sub Title";
    return @"Event";
}
- (NSString *)title{
    //return @"Title";
    return @"Location ";
}

-(id)initWithCoordinate:(CLLocationCoordinate2D) c{
    coordinate=c;
    //NSLog(@"%f,%f",c.latitude,c.longitude);
    return self;
}

@end

@implementation MapViewController
@synthesize address;
@synthesize currentLocation;

static MapViewController *sharedInstance;

+(MapViewController *)sharedInstance{
    @synchronized (self)
    {
        if (!sharedInstance)
            [[MapViewController alloc]init];
        }
    return sharedInstance;
}
+(id)alloc{
    @synchronized(self){
        NSAssert(sharedInstance==nil,"Attempted to allocate a second instance of a singleton LocationController.");
        sharedInstance = [super alloc];
    }
    return sharedInstance;
}
-(id)init{
    if(self==[super init]){
        self.currentLocation=[[CLLocation alloc]init];
        locationManager=[[CLLocationManager alloc]init];
        locationManager.delegate=self;
        [self start];
    }
    return self;
}
-(void)start{
    NSLog(@"Start");
    [locationManager startUpdatingLocation];
}
-(void)stop{
    [locationManager stopUpdatingLocation];
}
-(BOOL)locationKnown{
    if (round(currentLocation.speed)==-1)
        return NO;
        else return YES;

}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    if (abs([newLocation.timestamp timeIntervalSinceDate:[NSDate date]])<120){
        self.currentLocation=newLocation;
    }
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    UIAlertView *alert;
    alert=[[UIAlertView alloc]initWithTitle:@"Error" message:[error description] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
    [alert release];
}
        // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"Map-View";
    [self addressLocation];
    [self showAddress];
    NSLog(@"address is %@",address);

}

-(void)showAddress{

    MKCoordinateRegion region;
    MKCoordinateSpan span;
    span.latitudeDelta=0.2;
    span.longitudeDelta=0.2;

    CLLocationCoordinate2D location = [self addressLocation];
    region.span=span;
    region.center=location;

    if(addAnnotation != nil) {
        [mapView removeAnnotation:addAnnotation];
        [addAnnotation release];
        addAnnotation = nil;
    }

    addAnnotation = [[AddressAnnotation alloc] initWithCoordinate:location];
    [mapView addAnnotation:addAnnotation];

    [mapView setRegion:region animated:TRUE];
    [mapView regionThatFits:region];

}

-(CLLocationCoordinate2D) addressLocation {

    NSString *urlString = [NSString stringWithFormat:@"http://maps.google.com/maps/geo?q=%@&output=csv",

   [address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

    NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString]];
    NSArray *listItems = [locationString componentsSeparatedByString:@","];

    double latitude = 0.0;
    double longitude = 0.0;

    if([listItems count] >= 4 && [[listItems objectAtIndex:0] isEqualToString:@"200"]) {
        latitude = [[listItems objectAtIndex:2] doubleValue];
        longitude = [[listItems objectAtIndex:3] doubleValue];
    }
    else {
        //Show error
    }
    CLLocationCoordinate2D location;
    location.latitude = latitude;
    location.longitude = longitude;

    return location;
}

- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>) annotation{

    MKPinAnnotationView *annView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"currentloc"];
    annView.pinColor = MKPinAnnotationColorRed;
    annView.animatesDrop=YES;
    annView.canShowCallout = YES;
    annView.calloutOffset = CGPointMake(-5, 5);
    return annView;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Overriden to allow any orientation.
    return YES;
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];

    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)dealloc {
    [address release];
    [super dealloc];
}

@end

Please help me out...

thanks in adavance.

Body:
Showing user current location is simple.

-(void)start{
    NSLog(@"Start");
     mapView.showsUserLocation=YES; //This will show the current location as blue dot in your mapview
    [locationManager startUpdatingLocation];
}
-(void)stop{
     mapView.showsUserLocation=NO;
    [locationManager stopUpdatingLocation];
}

In your viewForAnnotation Delegate

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {
if (annotation == mapView.userLocation)
{
    // This code will execute when the current location is called.
    return nil;
}
else
{
    MKPinAnnotationView *annView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"currentloc"];
    annView.pinColor = MKPinAnnotationColorRed;
    annView.animatesDrop=YES;
    annView.canShowCallout = YES;
    annView.calloutOffset = CGPointMake(-5, 5);
    return annView;
}


来源: stackexchange

问:
Angular 2 Field Masking
I want to mask a field for example:  having phone number of 10 digit (123-123-1234) I need to mask in such a way that (xxx-xxx-1234). Also While submit the page I need to send original variable (123-123-1234) to service.

Any help would be greatly appreciated.

Thanks.

答:
You could post some code, we're not supposed to guess it.

Anyway, you could create an object like this

```<code>let phoneBundle = {
    realPhone: '123-123-1234',
    displayPhone: 'xxx-xxx-' + this.phoneBundle.realPhone.substr(-1, 4)
};
</code>```

ContentLicense: CC BY-SA 3.0

Title: Angular 2 Field Masking

Body:
You could post some code, we're not supposed to guess it.

Anyway, you could create an object like this

let phoneBundle = {
    realPhone: '123-123-1234',
    displayPhone: 'xxx-xxx-' + this.phoneBundle.realPhone.substr(-1, 4)
};


答:
It's a good example to use Angular's pipe:

Create a pipe: mask.pipe.ts:

```<code>import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: 'mask' })
export class MaskPipe implements PipeTransform {
    transform(phrase: string) {
        let toBeReplaced = phrase.slice(0, 7);
        return phrase.replace(toBeReplaced, "xxx-xxx");
    }
}
</code>```

Put the pipe in declarations of your module:

```<code>import { MaskPipe } from "./mask.pipe";
@NgModule({
    declarations: [ MaskPipe ]
    // ...
})
</code>```

Use the pipe in your template:

// Component's class:

```<code>export class AppComponent  {
    number: string = "123-123-1234";
}
</code>```

// Component's template:

```<code><h1> {{ number | mask }}</h1>
</code>```

The value of number doesn't change, only the displayed value change

Title: Angular 2 Field Masking

Body:
I want to mask a field for example:  having phone number of 10 digit (123-123-1234) I need to mask in such a way that (xxx-xxx-1234). Also While submit the page I need to send original variable (123-123-1234) to service.

Any help would be greatly appreciated.

Thanks.

Body:
It's a good example to use Angular's pipe:

Create a pipe: mask.pipe.ts:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: 'mask' })
export class MaskPipe implements PipeTransform {
    transform(phrase: string) {
        let toBeReplaced = phrase.slice(0, 7);
        return phrase.replace(toBeReplaced, "xxx-xxx");
    }
}

Put the pipe in declarations of your module:

import { MaskPipe } from "./mask.pipe";
@NgModule({
    declarations: [ MaskPipe ]
    // ...
})

Use the pipe in your template:

// Component's class:

export class AppComponent  {
    number: string = "123-123-1234";
}

// Component's template:

<h1> {{ number | mask }}</h1>

The value of number doesn't change, only the displayed value change


问:
Composer doesn't upgrade Symfony from 3.2 to 3.3
I'm trying to upgrade my project to latest Symfony.

The 3.1 to 3.2 was flawless.

Now it's been a hour I'm trying to upgrade to 3.3 and I still do'nt have a clue why it doesn't happen.

The strangest part is I don't have any error message when running the composer update command, but the symfony version doesn't change. I checked on the debug bar and with the bin/console --version command, still 3.2.10.

```<code>bin/console --version
Symfony 3.2.10 (kernel: app, env: dev, debug: true)
</code>```

My composer.json is, I suppose, correctly specified :

```<code>"require" : {
        "php" : ">=7.0",
        "symfony/symfony" : "3.3.*",
        "doctrine/orm" : "^2.5",
        "doctrine/doctrine-bundle" : "^1.6",
        "doctrine/doctrine-cache-bundle" : "^1.2",
        "symfony/swiftmailer-bundle" : "^2.3",
        "symfony/monolog-bundle" : "^2.8",
        "symfony/polyfill-apcu" : "^1.0",
        "sensio/distribution-bundle" : "^5.0",
        "sensio/framework-extra-bundle" : "^3.0.2",
        "incenteev/composer-parameter-handler" : "^2.0",
        "symfony/assetic-bundle" : "^2",
        "friendsofsymfony/user-bundle" : "~2.0",
        "knplabs/knp-menu-bundle" : "^2.0",
        "egeloen/ckeditor-bundle" : "^4.0",
        "twig/twig" : "@stable",
        "twig/extensions" : "^1.4",
        "stof/doctrine-extensions-bundle" : "^1.2",
        "friendsofsymfony/jsrouting-bundle" : "^1.6",
        "yavin/symfony-form-tree" : "~1.0",
        "cnerta/breadcrumb-bundle" : "2.1.*",
        "symfony/security-acl" : "^v3",
        "petrepatrasc/google-map-bundle" : "^2.3",
        "debril/rss-atom-bundle" : "^3.0",
        "beberlei/DoctrineExtensions" : "^1.0",
        "symfony/http-kernel" : "~3.0",
        "tilleuls/ovh-bundle" : "1.0.*",
        "st/flagiconcss-bundle" : "~1.0",
        "th3mouk/yahoo-weather-api" : "^1.0",
        "jms/serializer-bundle" : "^1.2"
    },
</code>```

Here is the console output :

```<code>composer update
Loading composer repositories with package information
Updating dependencies (including require-dev)
Nothing to install or update
Generating autoload files
> Incenteev\ParameterHandler\ScriptHandler::buildParameters
Updating the "app/config/parameters.yml" file
> Sensio\Bundle\DistributionBundle\Composer\ScriptHandler::buildBootstrap
> Sensio\Bundle\DistributionBundle\Composer\ScriptHandler::clearCache

 // Clearing the cache for the dev environment with debug

// And the rest is usual assetic and cache clear stuff
</code>```

I also tried to upgrade just symfony/symfony, no difference.

Does anyone have a clue ?

Thank you for your time and your help.

答:
The problem is probably that one of your dependencies requires the lower version.

You can use:

```<code>composer why symfony/symfony 3.2.*
</code>```

to find out which dependency it is. Then you probably have to update that dependency first.

To make sure everything works you should do this one by one using:

```<code>composer require dependency/dep ?
</code>```

Where ? is the new version constraint. Then run your tests and then do the same with symfony:

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

OP's edit :

The problem was due to Eclipse not writing the composer.json file to disk anymore, don't ask me why.

However, I mark this answer as the solution because the composer why command is what pushed me in the right direction.

Body:
I'm trying to upgrade my project to latest Symfony.

The 3.1 to 3.2 was flawless.

Now it's been a hour I'm trying to upgrade to 3.3 and I still do'nt have a clue why it doesn't happen.

The strangest part is I don't have any error message when running the composer update command, but the symfony version doesn't change. I checked on the debug bar and with the bin/console --version command, still 3.2.10.

bin/console --version
Symfony 3.2.10 (kernel: app, env: dev, debug: true)

My composer.json is, I suppose, correctly specified :

"require" : {
        "php" : ">=7.0",
        "symfony/symfony" : "3.3.*",
        "doctrine/orm" : "^2.5",
        "doctrine/doctrine-bundle" : "^1.6",
        "doctrine/doctrine-cache-bundle" : "^1.2",
        "symfony/swiftmailer-bundle" : "^2.3",
        "symfony/monolog-bundle" : "^2.8",
        "symfony/polyfill-apcu" : "^1.0",
        "sensio/distribution-bundle" : "^5.0",
        "sensio/framework-extra-bundle" : "^3.0.2",
        "incenteev/composer-parameter-handler" : "^2.0",
        "symfony/assetic-bundle" : "^2",
        "friendsofsymfony/user-bundle" : "~2.0",
        "knplabs/knp-menu-bundle" : "^2.0",
        "egeloen/ckeditor-bundle" : "^4.0",
        "twig/twig" : "@stable",
        "twig/extensions" : "^1.4",
        "stof/doctrine-extensions-bundle" : "^1.2",
        "friendsofsymfony/jsrouting-bundle" : "^1.6",
        "yavin/symfony-form-tree" : "~1.0",
        "cnerta/breadcrumb-bundle" : "2.1.*",
        "symfony/security-acl" : "^v3",
        "petrepatrasc/google-map-bundle" : "^2.3",
        "debril/rss-atom-bundle" : "^3.0",
        "beberlei/DoctrineExtensions" : "^1.0",
        "symfony/http-kernel" : "~3.0",
        "tilleuls/ovh-bundle" : "1.0.*",
        "st/flagiconcss-bundle" : "~1.0",
        "th3mouk/yahoo-weather-api" : "^1.0",
        "jms/serializer-bundle" : "^1.2"
    },

Here is the console output :

composer update
Loading composer repositories with package information
Updating dependencies (including require-dev)
Nothing to install or update
Generating autoload files
> Incenteev\ParameterHandler\ScriptHandler::buildParameters
Updating the "app/config/parameters.yml" file
> Sensio\Bundle\DistributionBundle\Composer\ScriptHandler::buildBootstrap
> Sensio\Bundle\DistributionBundle\Composer\ScriptHandler::clearCache

 // Clearing the cache for the dev environment with debug

// And the rest is usual assetic and cache clear stuff

I also tried to upgrade just symfony/symfony, no difference.

Does anyone have a clue ?

Thank you for your time and your help.

Body:
The problem is probably that one of your dependencies requires the lower version.

You can use:

composer why symfony/symfony 3.2.*

to find out which dependency it is. Then you probably have to update that dependency first.

To make sure everything works you should do this one by one using:

composer require dependency/dep ?

Where ? is the new version constraint. Then run your tests and then do the same with symfony:

composer update symfony/symfony

OP's edit :

The problem was due to Eclipse not writing the composer.json file to disk anymore, don't ask me why.

However, I mark this answer as the solution because the composer why command is what pushed me in the right direction.


问:
Powershell: Adding element to hashtable failed
```<code>PS C:\Users\Hind> $b=@{}
PS C:\Users\Hind> $b+={k="a";v="b"}
A hash table can only be added to another hash table.
At line:1 char:1
+ $b+={k="a";v="b"}
+ ~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : AddHashTableToNonHashTable
</code>```

<p>Why did it fail? How can I add one element to a hashtable successfully? </p>

答:
Initialising the hashtable should be with round bracket instead of curly brackets</p>

```<code>$b=@()
$b+=@{k="a";v="b"}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
PS C:\Users\Hind> $b=@{}
PS C:\Users\Hind> $b+={k="a";v="b"}
A hash table can only be added to another hash table.
At line:1 char:1
+ $b+={k="a";v="b"}
+ ~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : AddHashTableToNonHashTable

Why did it fail? How can I add one element to a hashtable successfully?

Body:
Initialising the hashtable should be with round bracket instead of curly brackets

$b=@()
$b+=@{k="a";v="b"}


问:
forward variable to php script on button click
I have this HTML button:

```<code><form action="testscript.php" name ="more" method="get">
  <input type="submit" value="More Details">
</form>
</code>```

Which when clicked runs this PHP script:

```<code><?php echo 'button pushed: ';
echo $buttonvalue;
?>
</code>```

My question is, how to I assign a value to the button so that when its clicked it will forward its value ($buttonvalue) to the PHP script

For example when the button is clicked i want it to run the script and the result should be button pushed: blue

How do i assign "blue" to the button?

答:
you can try this

HTML :

```<code><form action="testscript.php" name ="more" method="get">
    <input type="hidden" name="buttonvalue" value="Some Value">
    <input type="submit" value="More Details">
</form>
</code>```

PHP :

```<code><?php
echo 'button pushed: ';
echo !empty($_GET['buttonvalue']) ? $_GET['buttonvalue'] : '';
?>
</code>```

Body:
I have this HTML button:

<form action="testscript.php" name ="more" method="get">
  <input type="submit" value="More Details">
</form>

Which when clicked runs this PHP script:

<?php echo 'button pushed: ';
echo $buttonvalue;
?>

My question is, how to I assign a value to the button so that when its clicked it will forward its value ($buttonvalue) to the PHP script

For example when the button is clicked i want it to run the script and the result should be button pushed: blue

How do i assign "blue" to the button?

Body:
you can try this

HTML :

<form action="testscript.php" name ="more" method="get">
    <input type="hidden" name="buttonvalue" value="Some Value">
    <input type="submit" value="More Details">
</form>

PHP :

<?php
echo 'button pushed: ';
echo !empty($_GET['buttonvalue']) ? $_GET['buttonvalue'] : '';
?>


问:
queueCapacity usage for SocketInitiator (QuickFIX/J)
I recently started using the QuickFIX/J library to communicate and send real-time reporting messages to an APA (Approved Publication Arrangement) service using the FIX Protocol.

One of the parameters in the SocketInitiator constructor is queueCapacity but unfortunately there isn't much information in the documentation about its usage. For what I can see it is used to determine the size of an internal queue for the SocketInitiator to process messages asynchronously. The default value is set to 10000 if not provided via the constructor.

I was wondering if there are any guidelines on what value should be used here, whether 10000 is "good enough" and what will happen if the queue capacity max size is reached.

答:
The queue used in the implementation of SingleThreadedEventHandlingStrategy in 1.6.3 is a java.util.concurrent.LinkedBlockingQueue.

The constructor used is public LinkedBlockingQueue(int capacity) which creates a queue of fixed width. If the maximum capacity is reached and a SessionMessageEvent instance is put on the queue, the thread putting on the event blocks until space becomes available in the queue (i.e. until the events in the queue have been processed).

I would venture a guess and say that 10000 is enough for 99.9% of the cases where QuickFIX/J is used.


问:
How should a list be represented in XML?
In XML, how should a list be represented?

With an enclosing list entity:

```<code><person>
    <firstname>Joe</firstname>
    <lastname>Bloggs</lastname>

    <children>
        <child .../>
        <child .../>
        <child .../>
        <child .../>
        <child .../>
    </children>
</person>
</code>```

Or without:

```<code><person>
    <firstname>Joe</firstname>
    <lastname>Bloggs</lastname>

    <child .../>
    <child .../>
    <child .../>
    <child .../>
    <child .../>
</person>
</code>```

答: I would enclose it in an entity to distinguish it from the other elements.</p>

OwnerDisplayName: Mat

ContentLicense: CC BY-SA 2.5

Body:
In XML, how should a list be represented?

With an enclosing list entity:

<person>
    <firstname>Joe</firstname>
    <lastname>Bloggs</lastname>

    <children>
        <child .../>
        <child .../>
        <child .../>
        <child .../>
        <child .../>
    </children>
</person>

Or without:

<person>
    <firstname>Joe</firstname>
    <lastname>Bloggs</lastname>

    <child .../>
    <child .../>
    <child .../>
    <child .../>
    <child .../>
</person>

OwnerDisplayName: Daniel

LastEditorDisplayName: Daniel


问:
Regular expression: if three letters are included
I've got a number of word:
hello, poison, world, search, echo ...
And I've got some letters e, h, o
Now I need to find all words that includes this letters. Like search, echo for e, h, o

I can search this way:

```<code>words = %w[hello poison world search echo]
matched = words.select do |w|
  %w[e,h,o].all?{ |l| w =~ /#{l}/ }
end
</code>```

The problem is that if letters are o, o, o, or l, b, l this search will return true for words like open or boil, but I need to search words that includes three of o or two of l and one b

upd:

```<code>leters = "abc"
words.select{ |w| w.count(letters) >= 3 }
</code>```

upd 2

Bad solution, example:

```<code>"lllllll".count("lua") #=> 5
</code>```

答:
Consider modifying the word (so that it becomes smaller with each check).</p>

```<code>words = %w(fooo for find o ooo)
matched = words.select do |orig|
  # note: str.gsub! returns nil if nothing was replaced
  w = orig.clone
  %w(o o o).all?{ |l| w.gsub!(/^(.*)(#{l})(.*)$/, '\1\3') }
end
</code>```

Body:
I've got a number of word:
hello, poison, world, search, echo ...
And I've got some letters e, h, o
Now I need to find all words that includes this letters. Like search, echo for e, h, o

I can search this way:

words = %w[hello poison world search echo]
matched = words.select do |w|
  %w[e,h,o].all?{ |l| w =~ /#{l}/ }
end

The problem is that if letters are o, o, o, or l, b, l this search will return true for words like open or boil, but I need to search words that includes three of o or two of l and one b

upd:

leters = "abc"
words.select{ |w| w.count(letters) >= 3 }

upd 2

Bad solution, example:

"lllllll".count("lua") #=> 5

Body:
Consider modifying the word (so that it becomes smaller with each check).

words = %w(fooo for find o ooo)
matched = words.select do |orig|
  # note: str.gsub! returns nil if nothing was replaced
  w = orig.clone
  %w(o o o).all?{ |l| w.gsub!(/^(.*)(#{l})(.*)$/, '\1\3') }
end


问:
How to attach files(*.html/*.xml) to TFS Test reults
I have a test suite with 20 unit tests. I run them through a build definition and at the end publish the results(.trx).Through my test code I generate a folder with each test case, each of which has an .html file and if test case fails a snapshot of the desktop (20 test cases  generates 20 folders each of which contains html file). These folders are created locally in the machines where the tests have been run.I wanted to know if I can attach these folders/files to the test results which I publish through my build definition??</p>

答:
When you complete a test the test results (.trx) is generated, So you cannot attach any other files to the test results anymore.

Update:

If you just want to attach the files to the test run/result, you can try to use the REST API

eg:

```<code>POST https://fabrikam-fiber-inc.visualstudio.com/DefaultCollection/Fabrikam/_apis/test/runs/49/results/100000/attachments?api-version=2.0-preview
Content-Type: application/json
{
  "stream": "VXNlciB0ZXh0IGNvbnRlbnQgdG8gdXBsb2FkLg==",
  "fileName": "textAsFileAttachment.txt",
  "comment": "Test attachment upload",
  "attachmentType": "GeneralAttachment"
}
</code>```

Update2 :

Each test (including the automation test) will has a test run ID when running it. the next time to run the same test will be another run ID, it's unique. So, if you want to attach the files to the specific test run, you need to get the test run ID first, the {run} means the specific test run ID.

You can use the REST API to get the test run list (you can get the test run ID from the list), eg:

```<code>GET http://wxv-xin-12r2:8080/tfs/DefaultCollection/2017ScrumProjectFromVS/_apis/test/runs/
</code>```

Body:
When you complete a test the test results (.trx) is generated, So you cannot attach any other files to the test results anymore.

Update:

If you just want to attach the files to the test run/result, you can try to use the REST API

eg:

POST https://fabrikam-fiber-inc.visualstudio.com/DefaultCollection/Fabrikam/_apis/test/runs/49/results/100000/attachments?api-version=2.0-preview
Content-Type: application/json
{
  "stream": "VXNlciB0ZXh0IGNvbnRlbnQgdG8gdXBsb2FkLg==",
  "fileName": "textAsFileAttachment.txt",
  "comment": "Test attachment upload",
  "attachmentType": "GeneralAttachment"
}

Update2 :

Each test (including the automation test) will has a test run ID when running it. the next time to run the same test will be another run ID, it's unique. So, if you want to attach the files to the specific test run, you need to get the test run ID first, the {run} means the specific test run ID.

You can use the REST API to get the test run list (you can get the test run ID from the list), eg:

GET http://wxv-xin-12r2:8080/tfs/DefaultCollection/2017ScrumProjectFromVS/_apis/test/runs/


问:
Binding to collection that exist in other collection
I have ListBox that has binding to the collection (Publishers), every publisher has a name and collection of authors in it, every author has a name. So how can I provide binding to author's name?

```<code><TextBlock Text="{Binding name}" Grid.Column="1" Grid.Row="1"></TextBlock>
<TextBlock Text="{Binding city}" Grid.Column="1" Grid.Row="0"></TextBlock>
</code>```

It is binding to a publisher's name and city.

答:
An author would be an element in a collection which is part of a publisher.

So there is no way for WPF to 'know' which author's name to display: there are multiple.

Instead of a textblock, an ItemsControl could be used that binds its ItemsCollection to the collection of authors in the current publisher.

Body:
I have ListBox that has binding to the collection (Publishers), every publisher has a name and collection of authors in it, every author has a name. So how can I provide binding to author's name?

<TextBlock Text="{Binding name}" Grid.Column="1" Grid.Row="1"></TextBlock>
<TextBlock Text="{Binding city}" Grid.Column="1" Grid.Row="0"></TextBlock>

It is binding to a publisher's name and city.


问:
count where different is more than 2 days
Hi i have this code that I would like to get the total of log that is closed.

(A) More than 2 days.
  (B) Less than 2 days.

```<code>for($m=1; $m<=12; ++$m) {

   $next_year = $cur_year + 1;
   $monthName=date('M', mktime(0, 0, 0, $m, 1)).'';
   $monthNumber  = date('m', mktime(0, 0, 0, $m, 1));
   $monthName  = date('F', mktime(0, 0, 0, $m, 1));
   $currentMonthText = date('Y-m-d', mktime(0, 0, 0, $m, 1));
   $nextMonthText    = date('Y-m-d', mktime(0, 0, 0, $m + 1, 1));

   $result= $DB->query("SELECT * FROM ".$DB->prefix("calldesk_log")."
   WHERE MONTH(date_open)='$monthNumber' AND date_open >=  '$currentMonthText'
   AND date_open <  '$nextMonthText' AND status='Closed'") or die(mysql_error());

    while($row = $DB->fetchArray($result))
    {
       $id_report=$row['id_report)'];
       $date_open=$row['date_open'];
       $date_close=$row['date_close'];
       $diff = abs(strtotime($date_open) - strtotime($date_close));
       $min = floor($diff / (60*60*24));
    }
}
</code>```

Any help will be appreciated.

答:
If its only a matter of days differences, let MYSQL do the job using DATE_ADD() Function, you will thus avoid classical date mistakes which are obvious in your actual code (leap years, year change, etc...)

Here are some examples depending on what you want to do , which is unclear...

Logs that are between 2 days in the past and 2 days in the future (if that's possible but this what you do in your code)

```<code>SELECT *
FROM ".$DB->prefix("calldesk_log")."
WHERE date_open BETWEEN DATE_ADD(curdate(), INTERVAL -2 DAY)
                    AND DATE_ADD(curdate(), INTERVAL  2 DAY)
  AND status='Closed'
</code>```

Logs that are between current date and 2 days in the future

```<code>SELECT *
FROM ".$DB->prefix("calldesk_log")."
WHERE date_open BETWEEN curdate()
                    AND DATE_ADD(curdate(), INTERVAL  2 DAY)
  AND status='Closed'
</code>```

Logs that are between 2 days in the past and current date

```<code>SELECT *
FROM ".$DB->prefix("calldesk_log")."
WHERE date_open BETWEEN DATE_ADD(curdate(), INTERVAL  -2 DAY)
                    AND curdate()
  AND status='Closed'
</code>```

If you want to count months instead of days, just change the INTERVAL:

```<code>DATE_ADD(curdate(), INTERVAL  -2 MONTH)
</code>```

If you want to take the time into account, use NOW() instead of curdate():

```<code>DATE_ADD(NOW(), INTERVAL  -2 DAY)
</code>```

That's it, you can do all this in pure SQL and let MySQL do the job for you.

Body:
Hi i have this code that I would like to get the total of log that is closed.

(A) More than 2 days.
  (B) Less than 2 days.

for($m=1; $m<=12; ++$m) {

   $next_year = $cur_year + 1;
   $monthName=date('M', mktime(0, 0, 0, $m, 1)).'';
   $monthNumber  = date('m', mktime(0, 0, 0, $m, 1));
   $monthName  = date('F', mktime(0, 0, 0, $m, 1));
   $currentMonthText = date('Y-m-d', mktime(0, 0, 0, $m, 1));
   $nextMonthText    = date('Y-m-d', mktime(0, 0, 0, $m + 1, 1));

   $result= $DB->query("SELECT * FROM ".$DB->prefix("calldesk_log")."
   WHERE MONTH(date_open)='$monthNumber' AND date_open >=  '$currentMonthText'
   AND date_open <  '$nextMonthText' AND status='Closed'") or die(mysql_error());

    while($row = $DB->fetchArray($result))
    {
       $id_report=$row['id_report)'];
       $date_open=$row['date_open'];
       $date_close=$row['date_close'];
       $diff = abs(strtotime($date_open) - strtotime($date_close));
       $min = floor($diff / (60*60*24));
    }
}

Any help will be appreciated.

Body:
If its only a matter of days differences, let MYSQL do the job using DATE_ADD() Function, you will thus avoid classical date mistakes which are obvious in your actual code (leap years, year change, etc...)

Here are some examples depending on what you want to do , which is unclear...

Logs that are between 2 days in the past and 2 days in the future (if that's possible but this what you do in your code)

SELECT *
FROM ".$DB->prefix("calldesk_log")."
WHERE date_open BETWEEN DATE_ADD(curdate(), INTERVAL -2 DAY)
                    AND DATE_ADD(curdate(), INTERVAL  2 DAY)
  AND status='Closed'

Logs that are between current date and 2 days in the future

SELECT *
FROM ".$DB->prefix("calldesk_log")."
WHERE date_open BETWEEN curdate()
                    AND DATE_ADD(curdate(), INTERVAL  2 DAY)
  AND status='Closed'

Logs that are between 2 days in the past and current date

SELECT *
FROM ".$DB->prefix("calldesk_log")."
WHERE date_open BETWEEN DATE_ADD(curdate(), INTERVAL  -2 DAY)
                    AND curdate()
  AND status='Closed'

If you want to count months instead of days, just change the INTERVAL:

DATE_ADD(curdate(), INTERVAL  -2 MONTH)

If you want to take the time into account, use NOW() instead of curdate():

DATE_ADD(NOW(), INTERVAL  -2 DAY)

That's it, you can do all this in pure SQL and let MySQL do the job for you.


问:
Using JavaScript to perform a GET request without AJAX
Out of curiosity, I'm wondering about the best (easiest, fastest, shortest, etc; make your pick) way to perform a GET request in JavaScript without using AJAX or any external libraries.

It must work cross-browser and it's not allowed to distort the hosting web page visually or affect it's functionality in any way.

I don't care about headers in the request, just the url-part. I also don't care about the result of the request. I just want the server to do something as a side effect when it receives this request, so firing it is all that matters. If your solution requires the servers to return something in particular, that's ok as well.

I'll post my own suggestion as a possible answer, but I would love it if someone could find a better way!

答:
I would go with Pekka idea and use hidden iframe, the advantage is that no further parsing will be done: for image, the browser will try to parse the result as image, for dynamically creating script tag the browser will try to parse the results as JavaScript code.. iframe is "hit and run", the browser doesn't care what's in there.

Changing your own solution a bit:

```<code>function GET(url) {
    var oFrame = document.getElementById("MyAjaxFrame");
    if (!oFrame) {
        oFrame = document.createElement("iframe");
        oFrame.style.display = "none";
        oFrame.id = "MyAjaxFrame";
        document.body.appendChild(oFrame);
    }
    oFrame.src = url;
}
</code>```

Body:
I would go with Pekka idea and use hidden iframe, the advantage is that no further parsing will be done: for image, the browser will try to parse the result as image, for dynamically creating script tag the browser will try to parse the results as JavaScript code.. iframe is "hit and run", the browser doesn't care what's in there.

Changing your own solution a bit:

function GET(url) {
    var oFrame = document.getElementById("MyAjaxFrame");
    if (!oFrame) {
        oFrame = document.createElement("iframe");
        oFrame.style.display = "none";
        oFrame.id = "MyAjaxFrame";
        document.body.appendChild(oFrame);
    }
    oFrame.src = url;
}


问:
How to perform NSUndoManager on NSMutableArray which contains Images?(Objective - C)
I'm creating an iOS App in which user can add effects to images. After applying that effect I've one done button which saves the current effect and allows user to add next effect on already applied effect, so user can apply more effects on other effects. If user won't press Done button then he switches between effects but with "Done" button he can apply effect on effect(Hope you get it!). Now I've two extra buttons named Undo & Redo. I'm saving all applied effects in an array when user clicks on done button.

Now I want to undo applied effects when undo button is clicked. And visa versa redo operation when redo button is clicked.

I know for that purpose I've to use NSUndoManager but I don't know from where I should start means I don't know how to use NSUndoManager with Array which contains Images?

答:
Well, I've done this by different way!! besides using NSUndoManager I've just used 2 Arrays and done code with them.

```<code>- (IBAction)onUndoClicked:(id)sender {
 if ([arrUndo lastObject] == nil) {
        NSLog(@"EMPTY");
    }
    else
    {
        [arrRedo addObject:[arrUndo lastObject]];
        NSLog(@"ArrAdd %@", [arrUndo description]);

        [arrUndo removeLastObject];
        for (UIImage *obj in arrUndo) {
            if ([arrUndo lastObject] == obj) {

                _imgClicked.image =  obj;
            }
        }
    }}

- (IBAction)onRedoClicked:(id)sender {

    if ([arrRedo lastObject] == nil) {
        NSLog(@"EMPTY");
    }
    else
    {
        [arrEffectImages addObject:[arrRedo lastObject]];
        for (UIImage *obj in arrRedo) {
            if ([arrRedo lastObject] == obj) {
                _imgClicked.image =  obj;
            }
        }
    }}
</code>```

Body:
Well, I've done this by different way!! besides using NSUndoManager I've just used 2 Arrays and done code with them.

- (IBAction)onUndoClicked:(id)sender {
 if ([arrUndo lastObject] == nil) {
        NSLog(@"EMPTY");
    }
    else
    {
        [arrRedo addObject:[arrUndo lastObject]];
        NSLog(@"ArrAdd %@", [arrUndo description]);

        [arrUndo removeLastObject];
        for (UIImage *obj in arrUndo) {
            if ([arrUndo lastObject] == obj) {

                _imgClicked.image =  obj;
            }
        }
    }}

- (IBAction)onRedoClicked:(id)sender {

    if ([arrRedo lastObject] == nil) {
        NSLog(@"EMPTY");
    }
    else
    {
        [arrEffectImages addObject:[arrRedo lastObject]];
        for (UIImage *obj in arrRedo) {
            if ([arrRedo lastObject] == obj) {
                _imgClicked.image =  obj;
            }
        }
    }}


问:
How delete data from other table - WordPress
I am trying to delete data from another table using before_delete_post. However, my script does not work. My before_delete_post is at the top of the code. The effect I would like to get when deleting a post would be to delete the data from another table(wp_used_cars) with the same id.</p>

```<code>add_action( 'before_delete_post', 'my_func' );
function my_func( $postid ){

    global $post_type;
    if ( $post_type != 'my_custom_post_type' ) return;

    $post_type->query( $wpdb->prepare( 'DELETE FROM wp_used_cars WHERE post_id = %d', $postid ) );
}

// -------------------------------------------------------------------------
// add custom posts --------------------------------------------------------

// add uzywane custom post and set custom capabilities
$uzywane = new CustomPost('uzywane');
$uzywane->make('Uzywane', 'Uzywane', 'Uzywane', array(
    'capabilities' => array(
        'edit_post'             => 'edit_used_car',
        'read_post'             => 'read_used_car',
        'delete_post'           => 'delete_used_car',
        'edit_posts'            => 'edit_used_cars',
        'edit_others_posts'     => 'edit_others_used_cars',
        'publish_posts'         => 'publish_used_cars',
        'read_private_posts'    => 'read_private_used_cars',
    ),
));

// add this custom capabilities to admin
$role = get_role( 'administrator' );
$role->add_cap( 'edit_used_car', true );
$role->add_cap( 'read_used_car', true );
$role->add_cap( 'delete_used_car', true );
$role->add_cap( 'edit_used_cars', true );
$role->add_cap( 'edit_others_used_cars', true );
$role->add_cap( 'publish_used_cars', true );
$role->add_cap( 'read_private_used_cars', true );

// if role uzywane don't exists add it and set capabilities to edit uzywane
if( ! role_exists( 'uzywane' ) ) {
    add_role(
        'uzywane',
        __( 'Używane' ),
        array(
            'read'                  => true,
            'edit_used_car'         => true,
            'read_used_car'         => true,
            'delete_used_car'       => true,
            'edit_used_cars'        => true,
            'edit_others_used_cars' => true,
            'publish_used_cars'     => true,
            'read_private_used_cars'=> true,
            'unfiltered_upload'     => true,
            'upload_files'          => true,
            'edit_posts'            => true,
        )
    );
}

// if user has role uzywane than remove links from admin panel
$user = wp_get_current_user();
if ( in_array( 'uzywane', (array) $user->roles ) ) {
    function remove_links() {
        echo '<style>.menu-icon-post, .menu-icon-promo_posts, .menu-icon-serwis, .menu-icon-nowe, .menu-icon-silniki, .menu-icon-comments, #toplevel_page_wpcf7, .menu-icon-tools, #wp-admin-bar-new-content, #wp-admin-bar-wpseo-menu, #wp-admin-bar-comments, .update-nag {display: none;}</style>';
    }
    add_action('admin_head', 'remove_links');
}

// if role uzywane don't exists add it and set capabilities to edit uzywane
if( ! role_exists( 'uzywane-admin' ) ) {
    add_role(
        'uzywane-admin',
        __( 'Używane-admin' ),
        array(
            'read'                  => true,
            'edit_used_car'         => true,
            'read_used_car'         => true,
            'delete_used_car'       => true,
            'edit_used_cars'        => true,
            'edit_others_used_cars' => true,
            'publish_used_cars'     => true,
            'read_private_used_cars'=> true,
            'unfiltered_upload'     => true,
            'upload_files'          => true,
            'edit_posts'            => true,
            'edit_others_posts'     => true,
            'manage_options'        => true,
        )
    );
}

// if user has role uzywane than remove links from admin panel
$user = wp_get_current_user();
if ( in_array( 'uzywane-admin', (array) $user->roles ) ) {
    function remove_links() {
        echo '<style> #toplevel_page_revslider, #toplevel_page_revslider, #menu-settings, #toplevel_page_wpseo_dashboard, #toplevel_page_edit-post_type-search-filter-widget, #toplevel_page_easy-responsive-tabs, .menu-icon-post, .menu-icon-promo_posts, .menu-icon-serwis, .menu-icon-nowe, .menu-icon-silniki, .menu-icon-comments, #toplevel_page_wpcf7, .menu-icon-tools, #wp-admin-bar-new-content, #wp-admin-bar-wpseo-menu, #wp-admin-bar-comments, .update-nag, #toplevel_page_edit-post_type-acf-field-group .wp-submenu li, #menu-appearance, .acf-columns-2 .wp-list-table.widefat tr, #acf-field-group-locations, #mymetabox_revslider_0, #acf-field-group-options {display: none;} .wp-list-table.widefat tr#post-456 {display: block };</style>';
    }
    add_action('admin_head', 'remove_links');
}

function cat_for_used_cars() {

    $labels = array(
        'name'                       => _x( 'Kategorie samochodów', 'Taxonomy General Name', 'text_domain' ),
        'singular_name'              => _x( 'Kategoria samochodów', 'Taxonomy Singular Name', 'text_domain' ),
        'menu_name'                  => __( 'Kategoria samochodów', 'text_domain' ),
        'all_items'                  => __( 'Wszystkie samochodów', 'text_domain' ),
        'parent_item'                => __( 'Parent Item', 'text_domain' ),
        'parent_item_colon'          => __( 'Parent Item:', 'text_domain' ),
        'new_item_name'              => __( 'Nazwa', 'text_domain' ),
        'add_new_item'               => __( 'Dodaj', 'text_domain' ),
        'edit_item'                  => __( 'Edycja', 'text_domain' ),
        'update_item'                => __( 'Update Item', 'text_domain' ),
        'view_item'                  => __( 'View Item', 'text_domain' ),
        'separate_items_with_commas' => __( 'Separate items with commas', 'text_domain' ),
        'add_or_remove_items'        => __( 'Add or remove items', 'text_domain' ),
        'choose_from_most_used'      => __( 'Choose from the most used', 'text_domain' ),
        'popular_items'              => __( 'Popular Items', 'text_domain' ),
        'search_items'               => __( 'Search Items', 'text_domain' ),
        'not_found'                  => __( 'Not Found', 'text_domain' ),
        'no_terms'                   => __( 'No items', 'text_domain' ),
        'items_list'                 => __( 'Items list', 'text_domain' ),
        'items_list_navigation'      => __( 'Items list navigation', 'text_domain' ),
    );
    $args = array(
        'labels'                     => $labels,
        'hierarchical'               => true,
        'public'                     => true,
        'show_ui'                    => true,
        'show_in_menu'               => true,
        'show_admin_column'          => true,
        'show_in_nav_menus'          => false,
        'show_tagcloud'              => false,
        'rewrite'                    => false,
    );
    register_taxonomy( 'usedcars', array( 'uzywane' ), $args );

}
add_action( 'init', 'cat_for_used_cars', 0 );
</code>```

答:
Try Below code :

```<code>add_action( 'before_delete_post', 'my_func' );
function my_func( $postid )
{
    global $post_type;
    if ( $post_type != 'uzywane' )
        return;

    global $wpdb;
    $prefix = $wpdb->prefix;
    $tbl = $prefix.'used_cars';
    $used_cars_count = $wpdb->get_var( "SELECT COUNT(*) FROM $tbl where post_id = ". $postid );
    if($used_cars_count > 0)
    {
        $wpdb->delete( $tbl, array( 'post_id' => $postid ) );
    }
}
</code>```

Hope this will help you!

Body:
I am trying to delete data from another table using before_delete_post. However, my script does not work. My before_delete_post is at the top of the code. The effect I would like to get when deleting a post would be to delete the data from another table(wp_used_cars) with the same id.

add_action( 'before_delete_post', 'my_func' );
function my_func( $postid ){

    global $post_type;
    if ( $post_type != 'my_custom_post_type' ) return;

    $post_type->query( $wpdb->prepare( 'DELETE FROM wp_used_cars WHERE post_id = %d', $postid ) );
}

// -------------------------------------------------------------------------
// add custom posts --------------------------------------------------------

// add uzywane custom post and set custom capabilities
$uzywane = new CustomPost('uzywane');
$uzywane->make('Uzywane', 'Uzywane', 'Uzywane', array(
    'capabilities' => array(
        'edit_post'             => 'edit_used_car',
        'read_post'             => 'read_used_car',
        'delete_post'           => 'delete_used_car',
        'edit_posts'            => 'edit_used_cars',
        'edit_others_posts'     => 'edit_others_used_cars',
        'publish_posts'         => 'publish_used_cars',
        'read_private_posts'    => 'read_private_used_cars',
    ),
));

// add this custom capabilities to admin
$role = get_role( 'administrator' );
$role->add_cap( 'edit_used_car', true );
$role->add_cap( 'read_used_car', true );
$role->add_cap( 'delete_used_car', true );
$role->add_cap( 'edit_used_cars', true );
$role->add_cap( 'edit_others_used_cars', true );
$role->add_cap( 'publish_used_cars', true );
$role->add_cap( 'read_private_used_cars', true );

// if role uzywane don't exists add it and set capabilities to edit uzywane
if( ! role_exists( 'uzywane' ) ) {
    add_role(
        'uzywane',
        __( 'Używane' ),
        array(
            'read'                  => true,
            'edit_used_car'         => true,
            'read_used_car'         => true,
            'delete_used_car'       => true,
            'edit_used_cars'        => true,
            'edit_others_used_cars' => true,
            'publish_used_cars'     => true,
            'read_private_used_cars'=> true,
            'unfiltered_upload'     => true,
            'upload_files'          => true,
            'edit_posts'            => true,
        )
    );
}

// if user has role uzywane than remove links from admin panel
$user = wp_get_current_user();
if ( in_array( 'uzywane', (array) $user->roles ) ) {
    function remove_links() {
        echo '';
    }
    add_action('admin_head', 'remove_links');
}

// if role uzywane don't exists add it and set capabilities to edit uzywane
if( ! role_exists( 'uzywane-admin' ) ) {
    add_role(
        'uzywane-admin',
        __( 'Używane-admin' ),
        array(
            'read'                  => true,
            'edit_used_car'         => true,
            'read_used_car'         => true,
            'delete_used_car'       => true,
            'edit_used_cars'        => true,
            'edit_others_used_cars' => true,
            'publish_used_cars'     => true,
            'read_private_used_cars'=> true,
            'unfiltered_upload'     => true,
            'upload_files'          => true,
            'edit_posts'            => true,
            'edit_others_posts'     => true,
            'manage_options'        => true,
        )
    );
}

// if user has role uzywane than remove links from admin panel
$user = wp_get_current_user();
if ( in_array( 'uzywane-admin', (array) $user->roles ) ) {
    function remove_links() {
        echo '';
    }
    add_action('admin_head', 'remove_links');
}

function cat_for_used_cars() {

    $labels = array(
        'name'                       => _x( 'Kategorie samochodów', 'Taxonomy General Name', 'text_domain' ),
        'singular_name'              => _x( 'Kategoria samochodów', 'Taxonomy Singular Name', 'text_domain' ),
        'menu_name'                  => __( 'Kategoria samochodów', 'text_domain' ),
        'all_items'                  => __( 'Wszystkie samochodów', 'text_domain' ),
        'parent_item'                => __( 'Parent Item', 'text_domain' ),
        'parent_item_colon'          => __( 'Parent Item:', 'text_domain' ),
        'new_item_name'              => __( 'Nazwa', 'text_domain' ),
        'add_new_item'               => __( 'Dodaj', 'text_domain' ),
        'edit_item'                  => __( 'Edycja', 'text_domain' ),
        'update_item'                => __( 'Update Item', 'text_domain' ),
        'view_item'                  => __( 'View Item', 'text_domain' ),
        'separate_items_with_commas' => __( 'Separate items with commas', 'text_domain' ),
        'add_or_remove_items'        => __( 'Add or remove items', 'text_domain' ),
        'choose_from_most_used'      => __( 'Choose from the most used', 'text_domain' ),
        'popular_items'              => __( 'Popular Items', 'text_domain' ),
        'search_items'               => __( 'Search Items', 'text_domain' ),
        'not_found'                  => __( 'Not Found', 'text_domain' ),
        'no_terms'                   => __( 'No items', 'text_domain' ),
        'items_list'                 => __( 'Items list', 'text_domain' ),
        'items_list_navigation'      => __( 'Items list navigation', 'text_domain' ),
    );
    $args = array(
        'labels'                     => $labels,
        'hierarchical'               => true,
        'public'                     => true,
        'show_ui'                    => true,
        'show_in_menu'               => true,
        'show_admin_column'          => true,
        'show_in_nav_menus'          => false,
        'show_tagcloud'              => false,
        'rewrite'                    => false,
    );
    register_taxonomy( 'usedcars', array( 'uzywane' ), $args );

}
add_action( 'init', 'cat_for_used_cars', 0 );

Body:
Try Below code :

add_action( 'before_delete_post', 'my_func' );
function my_func( $postid )
{
    global $post_type;
    if ( $post_type != 'uzywane' )
        return;

    global $wpdb;
    $prefix = $wpdb->prefix;
    $tbl = $prefix.'used_cars';
    $used_cars_count = $wpdb->get_var( "SELECT COUNT(*) FROM $tbl where post_id = ". $postid );
    if($used_cars_count > 0)
    {
        $wpdb->delete( $tbl, array( 'post_id' => $postid ) );
    }
}

Hope this will help you!


问:
InvalidDataAccessApiUsageException: No Persistent Entity information found for the class com.mongodb.BasicDBList
I am trying to insert an array of json objects into mongodb. I pass the array with a POST request, using Spring

My object

```<code>@Document(collection = "Users")
public class User {
  private String name;
  private String number;
//constructors, getters, setters
}
</code>```

My spring controller

```<code>@RestController
public class UserController {

  @RequestMapping(value="/postUser", method = RequestMethod.POST)
  public void postUser(@RequestBody BasicDBList users){
    ApplicationContext ctx =
      new AnnotationConfigApplicationContext(SpringMongoConfig.class);
    MongoOperations mongoOperation =
      (MongoOperations) ctx.getBean("mongoTemplate");
    mongoOperation.insert(users);
  }
}
</code>```

This is my json

```<code>[
    {
        "name" : "a",
        "number" : "1"
    },
    {
        "name" : "c",
        "number" : "3"
    }
]
</code>```

What I get in return is

```<code>{
    "timestamp": 1499161260902,
    "status": 500,
    "error": "Internal Server Error",
    "exception": "org.springframework.dao.InvalidDataAccessApiUsageException",
    "message": "No Persistent Entity information found for the class com.mongodb.BasicDBList",
    "path": "/postUser"
}
</code>```

There is no problem if I do

```<code>public void postUser(@RequestBody User users)
</code>```

and insert a single user. Why doesn't it work?

答:
When you add @RequestBody before the parameter, HttpMessageConvertor will try to convert json string to the specified type - BasicDBList. The json string may not match BasicDBList, so the conversion failed. You can use this:

```<code>public void postUser(@RequestBody List<User> users)
</code>```

Body:
I am trying to insert an array of json objects into mongodb. I pass the array with a POST request, using Spring

My object

@Document(collection = "Users")
public class User {
  private String name;
  private String number;
//constructors, getters, setters
}

My spring controller

@RestController
public class UserController {

  @RequestMapping(value="/postUser", method = RequestMethod.POST)
  public void postUser(@RequestBody BasicDBList users){
    ApplicationContext ctx =
      new AnnotationConfigApplicationContext(SpringMongoConfig.class);
    MongoOperations mongoOperation =
      (MongoOperations) ctx.getBean("mongoTemplate");
    mongoOperation.insert(users);
  }
}

This is my json

[
    {
        "name" : "a",
        "number" : "1"
    },
    {
        "name" : "c",
        "number" : "3"
    }
]

What I get in return is

{
    "timestamp": 1499161260902,
    "status": 500,
    "error": "Internal Server Error",
    "exception": "org.springframework.dao.InvalidDataAccessApiUsageException",
    "message": "No Persistent Entity information found for the class com.mongodb.BasicDBList",
    "path": "/postUser"
}

There is no problem if I do

public void postUser(@RequestBody User users)

and insert a single user. Why doesn't it work?

Body:
When you add @RequestBody before the parameter, HttpMessageConvertor will try to convert json string to the specified type - BasicDBList. The json string may not match BasicDBList, so the conversion failed. You can use this:

public void postUser(@RequestBody List<User> users)


问:
grep invert match on two files
I have two text files containing one column each, for example -

File_A       File_B

1              1

2              2

3              8

If I do grep -f File_A File_B > File_C, I get File_C containing 1 and 2. I want to know how to use grep -v on two files so that I can get the non-matching values, 3 and 8 in the above example.

Thanks.

答:
With GNU diff command (to compare files line by line):

```<code>diff --suppress-common-lines -y f1 f2 | column -t
</code>```

The output (left column contain lines from f1, right column - from f2):

```<code>3  |  8
</code>```

-y, --side-by-side - output in two columns

Title: grep invert match on two files

Body:
With GNU diff command (to compare files line by line):

diff --suppress-common-lines -y f1 f2 | column -t

The output (left column contain lines from f1, right column - from f2):

3  |  8

-y, --side-by-side - output in two columns


答:
Use anchor tag with 'btn' class. And pass value to next page with id.

Page 1.

```<code> <a class="btn btn-primary" href="next-page.php?id=value">Click me</a>
</code>```

Page 2.

```<code> $buttonvalue = $_GET['id'];
echo $buttonvalue;
</code>```

Title: forward variable to php script on button click

Body:
Use anchor tag with 'btn' class. And pass value to next page with id.

Page 1.

 <a class="btn btn-primary" href="next-page.php?id=value">Click me</a>

Page 2.

 $buttonvalue = $_GET['id'];
echo $buttonvalue;


问:
Using a table-alias in Kohana queries?
I'm trying to run a simple query with $this->db in Kohana, but am running into some syntax issues when I try to use an alias for a table within my query:

```<code>$result = $this->db
  ->select("ci.chapter_id, ci.book_id, ci.chapter_heading, ci.chapter_number")
  ->from("chapter_info ci")
  ->where(array("ci.chapter_number" => $chapter, "ci.book_id" => $book))
  ->get();
</code>```

It seems to me that this should work just fine. I'm stating that "chapter_info" ought to be known as "ci," yet this isn't taking for some reason. The error is pretty straight-forward:

```<code>There was an SQL error: Table 'gb_data.chapter_info ci' doesn't exist -
SELECT `ci`.`chapter_id`, `ci`.`book_id`, `ci`.`chapter_heading`,
       `ci`.`chapter_number`
FROM (`chapter_info ci`)
WHERE `ci`.`chapter_number` = 1
  AND `ci`.`book_id` = 1
</code>```

If I use the full table name, rather than an alias, I get the expected results without error. This requires me to write much more verbose queries, which isn't ideal.

Is there some way to use shorter names for tables within Kohana's query-builder?

答:
In Kohana 3 it is simply enough:

```<code>->from( array('table_name', 'alias') )
</code>```

and this will create the query that contains:

```<code>FROM 'table_name' AS 'alias'
</code>```

I have tested it and it works. Good luck.

Title: Using a table-alias in Kohana queries?

Body:
I'm trying to run a simple query with $this->db in Kohana, but am running into some syntax issues when I try to use an alias for a table within my query:

$result = $this->db
  ->select("ci.chapter_id, ci.book_id, ci.chapter_heading, ci.chapter_number")
  ->from("chapter_info ci")
  ->where(array("ci.chapter_number" => $chapter, "ci.book_id" => $book))
  ->get();

It seems to me that this should work just fine. I'm stating that "chapter_info" ought to be known as "ci," yet this isn't taking for some reason. The error is pretty straight-forward:

There was an SQL error: Table 'gb_data.chapter_info ci' doesn't exist -
SELECT `ci`.`chapter_id`, `ci`.`book_id`, `ci`.`chapter_heading`,
       `ci`.`chapter_number`
FROM (`chapter_info ci`)
WHERE `ci`.`chapter_number` = 1
  AND `ci`.`book_id` = 1

If I use the full table name, rather than an alias, I get the expected results without error. This requires me to write much more verbose queries, which isn't ideal.

Is there some way to use shorter names for tables within Kohana's query-builder?

Body:
In Kohana 3 it is simply enough:

->from( array('table_name', 'alias') )

and this will create the query that contains:

FROM 'table_name' AS 'alias'

I have tested it and it works. Good luck.


问:
Convert a list of minutes into lists of minutes, hours, days and months in python
I have a list of big numbers in minutes and I would like to convert or get from this four lists of minutes, hours, days and months. Lke for example:

```<code>Minutes
21601
30
0
90000
</code>```

Resulting lists:

```<code>Minutes  Hours  Days  Months
1        0      15    0
30       0      0     0
0        0      0     0
0        12     2     2
</code>```

Assumptions will be that a month has exactly 30 days. Also I know i showed them here as columns for simplicity but those will be lists.

Cheers,

答:
You could use a timedelta object together with a datetime.

Example:

```<code>from datetime import timedelta, datetime

def convert_from_minutes(minutes):
    td = timedelta(minutes=minutes)
    dt = datetime(1,1,1)
    result = dt + td
    return {
        "days": result.day-1,
        "hours": result.hour,
        "minutes": result.minute,
        "seconds": result.second
    }

ans = convert_from_minutes(21601)
ans["days"]     # gives 15
ans["hours"]    # gives 0
ans["minutes"]  # gives 1
ans["seconds"]  # gives 0
</code>```

Body:
I have a list of big numbers in minutes and I would like to convert or get from this four lists of minutes, hours, days and months. Lke for example:

Minutes
21601
30
0
90000

Resulting lists:

Minutes  Hours  Days  Months
1        0      15    0
30       0      0     0
0        0      0     0
0        12     2     2

Assumptions will be that a month has exactly 30 days. Also I know i showed them here as columns for simplicity but those will be lists.

Cheers,

Body:
You could use a timedelta object together with a datetime.

Example:

from datetime import timedelta, datetime

def convert_from_minutes(minutes):
    td = timedelta(minutes=minutes)
    dt = datetime(1,1,1)
    result = dt + td
    return {
        "days": result.day-1,
        "hours": result.hour,
        "minutes": result.minute,
        "seconds": result.second
    }

ans = convert_from_minutes(21601)
ans["days"]     # gives 15
ans["hours"]    # gives 0
ans["minutes"]  # gives 1
ans["seconds"]  # gives 0


问:
Excel Formula to Find Duplicate Value
I have an excel file with three columns (C,D,E) and one more (F) for finding all duplicate value. How can i use excel formula to get expected result (column F).

So the above columns should look like this:

Thank you in advance!

答:
Try this formula in D2 cell and this is one way to get the output.

=IF(ISERROR(MATCH($A2,$B:$B,0)*MATCH($A2,$C:$C,0)),"",$A2)

Title: Excel Formula to Find Duplicate Value


问:
Seperate GC log file for each Java VM on a Oracle Application Server
We have an Oracle AS 10.1.3.4 running 1 application on multiple JVMs. We have set up garbage collection logging using the -Xloggc parameter.

However, the gc logging of both JVMs is sent to the same log file. We'd like to get this logging in different log files. Anyone got an idea how to do this?

答:
Why don't you put something unique in your filename? Is there any parameter you pass into the JVMs that you can use to differentiate between them?

You could use hostname and a timestamp but it is not very nice:

```<code>-Xloggc:/path/to/gc-$HOSTNAME-$(date +%Y%m%d-%H%M%S%N).log
</code>```

Body:
Why don't you put something unique in your filename? Is there any parameter you pass into the JVMs that you can use to differentiate between them?

You could use hostname and a timestamp but it is not very nice:

-Xloggc:/path/to/gc-$HOSTNAME-$(date +%Y%m%d-%H%M%S%N).log


问:
How to draw/Form circle with two points?
I need to draw a circle and i have only two points.Now i need to find center point and radius of the circle?  You can form the circle in clock wise direction.

Thanks in advance

答:
Here is a Brute Force approach to the problem.

EDIT

Added a max iterations limit to cut off calculations if the line between the two points is almost straight along x (meaning a radius would be nearing Infinity)

Also animations, because that makes everything better :)

var canvas = document.body.appendChild(document.createElement("canvas"));
var ctx = canvas.getContext("2d");
canvas.width = 1000;
canvas.height = 1000;
var points = [
    { x: parseInt(prompt("x1", "110")), y: parseInt(prompt("y1", "120")), r: 5 },
    { x: parseInt(prompt("x2", "110")), y: parseInt(prompt("y2", "60")), r: 5 },
];
function calculateRemainingPoint(points, x, precision, maxIteration) {
    if (x === void 0) { x = 0; }
    if (precision === void 0) { precision = 0.001; }
    if (maxIteration === void 0) { maxIteration = 100000; }
    var newPoint = {
        x: x,
        y: (points[0].y + points[1].y) / 2,
        r: 50
    };
    var d0 = distance(points[0].x, points[0].y, x, newPoint.y);
    var d1 = distance(points[1].x, points[1].y, x, newPoint.y);
    var iteration = 0;
    //Bruteforce approach
    while (Math.abs(d0 - d1) > precision && iteration < maxIteration) {
        var oldDiff = Math.abs(d0 - d1);
        var oldY = newPoint.y;
        iteration++;
        newPoint.y += oldDiff / 10;
        d0 = distance(points[0].x, points[0].y, x, newPoint.y);
        d1 = distance(points[1].x, points[1].y, x, newPoint.y);
        var diff_1 = Math.abs(d0 - d1);
        if (diff_1 > oldDiff) {
            newPoint.y = oldY - oldDiff / 10;
            d0 = distance(points[0].x, points[0].y, x, newPoint.y);
            d1 = distance(points[1].x, points[1].y, x, newPoint.y);
        }
    }
    var diff = (points[0].x + points[1].x) / points[0].x;
    newPoint.r = d0;
    return newPoint;
}
points.push(calculateRemainingPoint(points));
function distance(x1, y1, x2, y2) {
    var a = x1 - x2;
    var b = y1 - y2;
    return Math.sqrt(a * a + b * b);
}
function draw() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.beginPath();
    ctx.moveTo(-canvas.width, canvas.height / 2);
    ctx.lineTo(canvas.width, canvas.height / 2);
    ctx.stroke();
    ctx.closePath();
    ctx.beginPath();
    ctx.moveTo(canvas.width / 2, -canvas.height);
    ctx.lineTo(canvas.width / 2, canvas.height);
    ctx.stroke();
    ctx.closePath();
    for (var pointIndex = 0; pointIndex < points.length; pointIndex++) {
        var point = points[pointIndex];
        ctx.beginPath();
        ctx.arc(point.x + canvas.width / 2, canvas.height / 2 - point.y, point.r, 0, Math.PI * 2);
        ctx.arc(point.x + canvas.width / 2, canvas.height / 2 - point.y, 2, 0, Math.PI * 2);
        ctx.stroke();
        ctx.closePath();
    }
}
setInterval(function () {
    points = points.slice(0, 2);
    points[Math.floor(Math.random() * points.length) % points.length][Math.random() > 0.5 ? 'x' : 'y'] = Math.random() * canvas.width - canvas.width / 2;
    setTimeout(function () {
        points.push(calculateRemainingPoint(points));
        requestAnimationFrame(draw);
    }, 1000 / 60);
}, 1000);
draw();```


问:
Putting two async subscriptions in one Angular *ngIf statement
I have the following in my component template:

...

Within the above div I would like to use the async pipe to subscribe to another observable only once, and use it just like user above throughout the template. So for instance, would something like this be possible:

<ng-template *ngIf="language$ | async as language>

All template code that would use both {{user}} and {{language}} would go in between

</ng-template>```

Or can this even be combined in one statement?

答:
You can use object as variable:

    {{userLanguage.language}} and {{userLanguage.user}}

```

Plunker Example

See also

How to declare a variable in a template in Angular2

Body:
I have the following in my component template:

...

Within the above div I would like to use the async pipe to subscribe to another observable only once, and use it just like user above throughout the template. So for instance, would something like this be possible:

<ng-template *ngIf="language$ | async as language>

All template code that would use both {{user}} and {{language}} would go in between

</ng-template>

Or can this even be combined in one statement?

Body:
You can use object as variable:

<div *ngIf="{ language: language$ | async, user: user$ | async } as userLanguage">
    <b>{{userLanguage.language}}</b> and <b>{{userLanguage.user}}</b>
</div>

Plunker Example

See also

How to declare a variable in a template in Angular2


问:
How to change maven repository folder in windows?
In windows, maven downloads everything in the C:\Documents And Settings\MyUser\.m2 folder (or C:\Users\MyUser\.m2). There exists some way to change the folder that it uses? Specially I want to set it to download anywhere BUT in the Documents And Settings/Users folder.

答:
Look at your settings.xml in ${maven.home}/conf or, preferrably, ${user.home}/.m2/settings.xml (see this for details about the settings.xml). You can add (or uncomment) the following section:

```<code>  <!-- localRepository
  | The path to the local repository maven will use to store artifacts.
  |
  | Default: ~/.m2/repository
  -->
 <localRepository>/path/to/local/repo</localRepository>

</code>```

as suggested by the commented out section already there by default. There, you should be able to change the path to achieve what you want.

Body:
Look at your settings.xml in ${maven.home}/conf or, preferrably, ${user.home}/.m2/settings.xml (see this for details about the settings.xml). You can add (or uncomment) the following section:

  <!-- localRepository
  | The path to the local repository maven will use to store artifacts.
  |
  | Default: ~/.m2/repository
  -->
 <localRepository>/path/to/local/repo</localRepository>

as suggested by the commented out section already there by default. There, you should be able to change the path to achieve what you want.


问:
INT to decimal JavaScript
I'm looking for method to achieve the following:

```<code>var exampleIntOne = 170;
var exampleIntTwo = 1700;
var exampleIntThree = 17000;
var exampleIntFour = 170000;
</code>```

I would like to be able to convert the above to the following expected result:

```<code>1.70
17.00
170.00
1700.00
</code>```

I have tried: exampleIntOne.toFixed(2); but this turns that example into: 170.00

答:
function convertNum(num){
   var numStr=num.toString();
   numStr=numStr.slice(0,-2);
   var newValue=numStr+'.'+'00';
   return newValue;
}
console.log(convertNum(17000));```

Title: INT to decimal JavaScript

Body:
I'm looking for method to achieve the following:

var exampleIntOne = 170;
var exampleIntTwo = 1700;
var exampleIntThree = 17000;
var exampleIntFour = 170000;

I would like to be able to convert the above to the following expected result:

1.70
17.00
170.00
1700.00

I have tried: exampleIntOne.toFixed(2); but this turns that example into: 170.00


问:
Path for logs is not writable
When I'm running codecept run on the first try after bootstrap, I'm running into this error,

[Codeception\Exception\Configuration]
Path for logs is not writable. Please, set appropriate access mode for log path.

Thanks!

答:
For me, _log file was already there but I was still getting the same error.

My problem was solved when I used SUDO with my execution command.

Title: Path for logs is not writable


答:
You can wrap the division/remainder operations into one using the builtin function divmod:

```<code>rem, minutes = zip(*(divmod(x, 60) for x in list_minutes))
rem, hours = zip(*(divmod(x, 24) for x in rem))
months, days = zip(*(divmod(x, 30) for x in rem))
</code>```

Of course, you can use the datetime.timedelta function to get a timedelta from  your minutes, however, this would still require some extra math ops to get the months and hours.

Title: Convert a list of minutes into lists of minutes, hours, days and months in python

Body:
You can wrap the division/remainder operations into one using the builtin function divmod:

rem, minutes = zip(*(divmod(x, 60) for x in list_minutes))
rem, hours = zip(*(divmod(x, 24) for x in rem))
months, days = zip(*(divmod(x, 30) for x in rem))

Of course, you can use the datetime.timedelta function to get a timedelta from  your minutes, however, this would still require some extra math ops to get the months and hours.


问:
forward variable to php script on button click
I have this HTML button:

```<code><form action="testscript.php" name ="more" method="get">
  <input type="submit" value="More Details">
</form>
</code>```

Which when clicked runs this PHP script:

```<code><?php echo 'button pushed: ';
echo $buttonvalue;
?>
</code>```

My question is, how to I assign a value to the button so that when its clicked it will forward its value ($buttonvalue) to the PHP script

For example when the button is clicked i want it to run the script and the result should be button pushed: blue

How do i assign "blue" to the button?

答:
```<code><form action="testscript.php" name ="more" method="get">
  <input type="hidden" name="getDataName" value="123">
  <input type="submit" value="More Details">
</form>
</code>```

PHP script:

```<code><?php
   $buttonvalue= isset ($_GET['getDataName']) ? $_GET['getDataName'] : '';
   if(!empty($buttonvalue)){
    echo 'button pushed: ';
    echo $buttonvalue;
   }else{
    echo 'button not pushed: ';
   }
?>
</code>```

Body:
I have this HTML button:

<form action="testscript.php" name ="more" method="get">
  <input type="submit" value="More Details">
</form>

Which when clicked runs this PHP script:

<?php echo 'button pushed: ';
echo $buttonvalue;
?>

My question is, how to I assign a value to the button so that when its clicked it will forward its value ($buttonvalue) to the PHP script

For example when the button is clicked i want it to run the script and the result should be button pushed: blue

How do i assign "blue" to the button?

Body:
<form action="testscript.php" name ="more" method="get">
  <input type="hidden" name="getDataName" value="123">
  <input type="submit" value="More Details">
</form>

PHP script:

<?php
   $buttonvalue= isset ($_GET['getDataName']) ? $_GET['getDataName'] : '';
   if(!empty($buttonvalue)){
    echo 'button pushed: ';
    echo $buttonvalue;
   }else{
    echo 'button not pushed: ';
   }
?>


问:
PHP REDIS NODE.JS multiple publisher/subscriber
I want to create a privatechat.

Explanation:

Imagine you are User_1 you open a list of users[User_2, User_3 ...etc], every element has  a button after clicking on one specific button I want to start a chatwindow with the specific user. (Server-side Laravel Project port: 8000) to use Websockets effectivly I'm running a node.js server, too(port 3000). To transmit data from php to node.js I'm using redis Pub/Sub, ChatController.php:

```<code>class ChatController extends Controller
{

   public function toChat($ForeignUserId)
   {
    $fid = (int) $ForeignUserId;
    $uid = (int) Sentinel::getUser()->id;

    $CollectionName1 = $fid . "collection" . $uid;
    $CollectionName2 = $uid . "collection" . $fid;
    $roomName = $uid . "room" . $fid;

    $res = DB::table('chats')
              ->where('collection_name', '=', $CollectionName1)
              ->orWhere('collection_name', '=', $CollectionName2)
              ->take(1)
              ->get();

    if(count($res) == 1)
    {
      $redis = Redis::connection();
      //$redis->publish('chat-channel', json_encode([['idone' => $uid], ['idtwo' => $fid]]));
      $redis->publish('chat-channel', json_encode(['idone' => $uid, 'idtwo' => $fid, 'IOroom' => $res[0]->room_name, 'collection' => $res[0]->collection_name]));
    }
    else
    {
      $date = date('Y-m-d H:m:s');
      DB::table('chats')->insert(['collection_name' => $CollectionName2, 'room_name' => $roomName, 'sender' => $uid, 'receiver' => $fid, 'created_at' => $date]);

      //$client = new MongoDB\Client;
      $client = new Mongo;
      $companydb = $client->chat;
      $result1 = $companydb->createCollection($CollectionName2);

      $redis = Redis::connection();
      //$redis->publish('chat-channel', json_encode([['idone' => $uid], ['idtwo' => $fid]]));
      $redis->publish('chat-channel', json_encode(['idone' => $uid, 'idtwo' => $fid, 'IOroom' => $roomName, 'collection' => $CollectionName2]));
    }
    //return view('chat');
    $url = "http://localhost:3000";
    return Redirect::to($url);
   }
}
</code>```

Node.js File (server.js port:3000) receiving data:

```<code>var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var mongoClientInstance = require('mongodb').MongoClient;
var redis = require('redis');
var php_listener = redis.createClient();

   app.get('/', function(req, res){
        res.sendFile(__dirname + '/index.html');
   });

php_listener.subscribe('chat-channel');

php_listener.on('message', function(channel, message){
   var purchase_data = JSON.parse(message);
   let colName = purchase_data.collection;
   let roomName = purchase_data.IOroom;

   let data = [];
   data.push(purchase_data.idone);
   data.push(purchase_data.idtwo);
   data.push(purchase_data.collection);
   data.push(purchase_data.IOroom);

   http.listen(process.env.PORT || 3000);
   console.log('Server running...');

   io.on('connection', function(socket){
       socket.join(roomName);
       io.sockets.in(roomName).emit('roomChat', data);
   });
});
</code>```

My problem is following: I'm User_1 clicking on button2 (so open Chat with User_2, get all information: websocket_room (I'm calling it IOroom), mongodb_collection etc...)

Now lets pretend I'm User_3 (using other browser) and clicking on button 4 (to chat with user_4) I'm joining the websocket_room and still getting all information from User_1 (from which button he clicked)(websocket_room, mongodbcollection, etc...) Console.log result as User_3:

```<code> (4) [2, 1, "2collection1", "2room1"]
 (4) [4, 3, "4collection3", "4room3"]
</code>```

What I'm missing? What do I have forgotten?

答:
Theoretical-Solution:
 AMQP-Server, and add session's on the node.js server. Now I know how to setup a Chat-Server. I figured it out by myself...</p>

Body:
I want to create a privatechat.

Explanation:

Imagine you are User_1 you open a list of users[User_2, User_3 ...etc], every element has  a button after clicking on one specific button I want to start a chatwindow with the specific user. (Server-side Laravel Project port: 8000) to use Websockets effectivly I'm running a node.js server, too(port 3000). To transmit data from php to node.js I'm using redis Pub/Sub, ChatController.php:

class ChatController extends Controller
{

   public function toChat($ForeignUserId)
   {
    $fid = (int) $ForeignUserId;
    $uid = (int) Sentinel::getUser()->id;

    $CollectionName1 = $fid . "collection" . $uid;
    $CollectionName2 = $uid . "collection" . $fid;
    $roomName = $uid . "room" . $fid;

    $res = DB::table('chats')
              ->where('collection_name', '=', $CollectionName1)
              ->orWhere('collection_name', '=', $CollectionName2)
              ->take(1)
              ->get();

    if(count($res) == 1)
    {
      $redis = Redis::connection();
      //$redis->publish('chat-channel', json_encode([['idone' => $uid], ['idtwo' => $fid]]));
      $redis->publish('chat-channel', json_encode(['idone' => $uid, 'idtwo' => $fid, 'IOroom' => $res[0]->room_name, 'collection' => $res[0]->collection_name]));
    }
    else
    {
      $date = date('Y-m-d H:m:s');
      DB::table('chats')->insert(['collection_name' => $CollectionName2, 'room_name' => $roomName, 'sender' => $uid, 'receiver' => $fid, 'created_at' => $date]);

      //$client = new MongoDB\Client;
      $client = new Mongo;
      $companydb = $client->chat;
      $result1 = $companydb->createCollection($CollectionName2);

      $redis = Redis::connection();
      //$redis->publish('chat-channel', json_encode([['idone' => $uid], ['idtwo' => $fid]]));
      $redis->publish('chat-channel', json_encode(['idone' => $uid, 'idtwo' => $fid, 'IOroom' => $roomName, 'collection' => $CollectionName2]));
    }
    //return view('chat');
    $url = "http://localhost:3000";
    return Redirect::to($url);
   }
}

Node.js File (server.js port:3000) receiving data:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var mongoClientInstance = require('mongodb').MongoClient;
var redis = require('redis');
var php_listener = redis.createClient();

   app.get('/', function(req, res){
        res.sendFile(__dirname + '/index.html');
   });

php_listener.subscribe('chat-channel');

php_listener.on('message', function(channel, message){
   var purchase_data = JSON.parse(message);
   let colName = purchase_data.collection;
   let roomName = purchase_data.IOroom;

   let data = [];
   data.push(purchase_data.idone);
   data.push(purchase_data.idtwo);
   data.push(purchase_data.collection);
   data.push(purchase_data.IOroom);

   http.listen(process.env.PORT || 3000);
   console.log('Server running...');

   io.on('connection', function(socket){
       socket.join(roomName);
       io.sockets.in(roomName).emit('roomChat', data);
   });
});

My problem is following: I'm User_1 clicking on button2 (so open Chat with User_2, get all information: websocket_room (I'm calling it IOroom), mongodb_collection etc...)

Now lets pretend I'm User_3 (using other browser) and clicking on button 4 (to chat with user_4) I'm joining the websocket_room and still getting all information from User_1 (from which button he clicked)(websocket_room, mongodbcollection, etc...) Console.log result as User_3:

 (4) [2, 1, "2collection1", "2room1"]
 (4) [4, 3, "4collection3", "4room3"]

What I'm missing? What do I have forgotten?


问:
Flex Row space between wrapped items
What is the most dynamic way of having any amount of rows with any amount of items with a set margin between all the items? Right now the only thing that works for me is to wrap each item in a wrapper set the flex basis to the wrapper and the margin to the child. The issues with this is I loose the ability to have each row the same height of the tallest content in the row.

Case 1: Only margin bottom

https://jsfiddle.net/6oaney4e/6/

This works well because the content keep the height of the tallest item on each row

html

```<code><div class="wrapper">
  <div class="item">
  text
  </div>
  <div class="item">
  text
  <br>
  line2
  </div>
  <div class="item">
  text
  </div>
  <div class="item">
  text
  </div>
</div>
</code>```

css

```<code>.wrapper{
  display: flex;
  flex-flow: row wrap;
  margin: -10px;
  padding: 10px;
  background: green;
}
.item{
  flex: 0 0 50%;
  background: orange;
  margin-bottom: 10px;
}
</code>```

Case 2: All around margin

https://jsfiddle.net/6oaney4e/7/

Here for some reason the rows break I'm guessing that's because the row cant fit the items in with the extra margin on the side.

html same as CASE 1

css

```<code>.wrapper{
  display: flex;
  flex-flow: row wrap;
  margin: -10px;
  padding: 10px;
  background: green;
}
.item{
  flex: 0 0 50%;
  background: orange;
  margin: 10px;
}
</code>```

Case 3: Wrapping items and adding margin to the inner item

https://jsfiddle.net/6oaney4e/8/

That worked but now the items on each row arent really aware of each other and cant have the same height.

html

```<code><div class="wrapper">
  <div class="item-wrap">
  <div class="item">
  text
  </div>
  </div>
  <div class="item-wrap">
  <div class="item">
  text
  <br>
  line2
  </div>
  </div>
  <div class="item-wrap">
  <div class="item">
  text
  </div>
  </div>
  <div class="item-wrap">
  <div class="item">
  text
  </div>
  </div>
</div>
</code>```

css

```<code>.wrapper{
  display: flex;
  flex-flow: row wrap;
  margin: -10px;
  padding: 10px;
  background: green;
}
.item-wrap{
  flex: 0 0 50%;
}
.item{
  background: orange;
  margin: 10px;
}
</code>```

Is there a way to keep the HTML as in CASE 1 (without the div.item-wrap), have the items on each row the same height as in CASE 1 and have the spacing work like in CASE 3?

答:
Ideally, you do want to use rows and make the .item-wrap divs flex-parents too.

.wrapper {
  display: flex;
  flex-flow: row wrap;
  margin: -10px;
  padding: 10px;
  background: green;
}

.item-wrap {
  flex: 0 0 50%;
  display: flex;
}

.item {
  background: orange;
  margin: 10px;
  flex: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <div class="item-wrap">
    <div class="item">
      text
    </div>
  </div>
  <div class="item-wrap">
    <div class="item">
      text
      <br> line2
    </div>
  </div>
  <div class="item-wrap">
    <div class="item">
      text
      <br> line2
      <br> line3
    </div>
  </div>
  <div class="item-wrap">
    <div class="item">
      text
    </div>
  </div>
</div></code>```

However if you must retain the existing structure, you'll need to use calc to adjust the flex-basis. Something like this:

.wrapper {
  display: flex;
  flex-flow: row wrap;
  background: green;
  justify-content: space-between;
}

.item {
  flex-grow:0;
  flex-shrink:0;
  flex-basis:calc(50% - 10px); /* separate properties for IE11 upport */
  background: orange;
  margin: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <div class="item">
    text
  </div>
  <div class="item">
    text
    <br> line2
  </div>
  <div class="item">
    text
    <br> line2
    <br> line3
  </div>
  <div class="item">
    text
  </div>
</div></code>```

Title: Flex Row space between wrapped items

Body:
What is the most dynamic way of having any amount of rows with any amount of items with a set margin between all the items? Right now the only thing that works for me is to wrap each item in a wrapper set the flex basis to the wrapper and the margin to the child. The issues with this is I loose the ability to have each row the same height of the tallest content in the row.

Case 1: Only margin bottom

https://jsfiddle.net/6oaney4e/6/

This works well because the content keep the height of the tallest item on each row

html

  text

  text

  line2

  text

  text

css

.wrapper{
  display: flex;
  flex-flow: row wrap;
  margin: -10px;
  padding: 10px;
  background: green;
}
.item{
  flex: 0 0 50%;
  background: orange;
  margin-bottom: 10px;
}

Case 2: All around margin

https://jsfiddle.net/6oaney4e/7/

Here for some reason the rows break I'm guessing that's because the row cant fit the items in with the extra margin on the side.

html same as CASE 1

css

.wrapper{
  display: flex;
  flex-flow: row wrap;
  margin: -10px;
  padding: 10px;
  background: green;
}
.item{
  flex: 0 0 50%;
  background: orange;
  margin: 10px;
}

Case 3: Wrapping items and adding margin to the inner item

https://jsfiddle.net/6oaney4e/8/

That worked but now the items on each row arent really aware of each other and cant have the same height.

html

  text

  text

  line2

  text

  text

css

.wrapper{
  display: flex;
  flex-flow: row wrap;
  margin: -10px;
  padding: 10px;
  background: green;
}
.item-wrap{
  flex: 0 0 50%;
}
.item{
  background: orange;
  margin: 10px;
}

Is there a way to keep the HTML as in CASE 1 (without the div.item-wrap), have the items on each row the same height as in CASE 1 and have the spacing work like in CASE 3?

Body:
Ideally, you do want to use rows and make the .item-wrap divs flex-parents too.

.wrapper {
  display: flex;
  flex-flow: row wrap;
  margin: -10px;
  padding: 10px;
  background: green;
}

.item-wrap {
  flex: 0 0 50%;
  display: flex;
}

.item {
  background: orange;
  margin: 10px;
  flex: 1;
}

<div class="wrapper">
  <div class="item-wrap">
    <div class="item">
      text
    </div>
  </div>
  <div class="item-wrap">
    <div class="item">
      text
      <br> line2
    </div>
  </div>
  <div class="item-wrap">
    <div class="item">
      text
      <br> line2
      <br> line3
    </div>
  </div>
  <div class="item-wrap">
    <div class="item">
      text
    </div>
  </div>
</div>

However if you must retain the existing structure, you'll need to use calc to adjust the flex-basis. Something like this:

.wrapper {
  display: flex;
  flex-flow: row wrap;
  background: green;
  justify-content: space-between;
}

.item {
  flex-grow:0;
  flex-shrink:0;
  flex-basis:calc(50% - 10px); /* separate properties for IE11 upport */
  background: orange;
  margin: 5px;
}

<div class="wrapper">
  <div class="item">
    text
  </div>
  <div class="item">
    text
    <br> line2
  </div>
  <div class="item">
    text
    <br> line2
    <br> line3
  </div>
  <div class="item">
    text
  </div>
</div>


问:
Angular 2 cannot read property using Interface
I've got some troubles with interface, when I try to use my function, console throws an error: error_handler.js:55 EXCEPTION: Error in package:355:100:20 caused by: Cannot read property 'registerStudent' of undefined
it's my interface:

```<code>export interface StorageInterface{
registerStudent(obj: StudentRegistrationDTO);}
</code>```

ApiStorage:

```<code>import { StorageInterface } from './storage.interface';

export class ApiStorage implements StorageInterface{
registerStudent(obj){
        console.log('after');
        }
}
</code>```

My DTO:

```<code>import { ApiStorage} from '../api.storage';
export class StudentRegistrationDTO{
private apiStorage: ApiStorage;
constructor(
    private firstName: string
){}
registerStudentDTO(){
            console.log('before');
            this.apiStorage.registerStudent(this);
    }
</code>```

and my component file:

```<code>import { StudentRegistrationDTO } from '../storage/dto/registration.student.dto';
export class StudentRegisterComponent {
sRDTO: StudentRegistrationDTO;
 send(){
        this.sRDTO = new StudentRegistrationDTO(
            this.service.first_name)

    this.sRDTO.registerStudentDTO();
        }
}
</code>```

Do you know maybe what's going on here ? Why does it throw error?
Console print "before" and then throw error.

答:
It's because you didn't instantiate your apiStorage varaible. Try this for your DTO :

```<code>import { ApiStorage} from '../api.storage';
export class StudentRegistrationDTO{
private apiStorage: ApiStorage;
constructor(
    private firstName: string
){
    this.apiStorage = new ApiStorage(/* any object that suits your constructor */);
}
registerStudentDTO(){
            console.log('before');
            this.apiStorage.registerStudent(this);
    }
</code>```

Body:
I've got some troubles with interface, when I try to use my function, console throws an error: error_handler.js:55 EXCEPTION: Error in package:355:100:20 caused by: Cannot read property 'registerStudent' of undefined
it's my interface:

export interface StorageInterface{
registerStudent(obj: StudentRegistrationDTO);}

ApiStorage:

import { StorageInterface } from './storage.interface';

export class ApiStorage implements StorageInterface{
registerStudent(obj){
        console.log('after');
        }
}

My DTO:

import { ApiStorage} from '../api.storage';
export class StudentRegistrationDTO{
private apiStorage: ApiStorage;
constructor(
    private firstName: string
){}
registerStudentDTO(){
            console.log('before');
            this.apiStorage.registerStudent(this);
    }

and my component file:

import { StudentRegistrationDTO } from '../storage/dto/registration.student.dto';
export class StudentRegisterComponent {
sRDTO: StudentRegistrationDTO;
 send(){
        this.sRDTO = new StudentRegistrationDTO(
            this.service.first_name)

    this.sRDTO.registerStudentDTO();
        }
}

Do you know maybe what's going on here ? Why does it throw error?
Console print "before" and then throw error.

Body:
It's because you didn't instantiate your apiStorage varaible. Try this for your DTO :

import { ApiStorage} from '../api.storage';
export class StudentRegistrationDTO{
private apiStorage: ApiStorage;
constructor(
    private firstName: string
){
    this.apiStorage = new ApiStorage(/* any object that suits your constructor */);
}
registerStudentDTO(){
            console.log('before');
            this.apiStorage.registerStudent(this);
    }