问:
OpaqueToken is not a constructor
I am trying to create a multilingual website using angular2 from the source code https://embed.plnkr.co/BnCRsCfB1ZIMoQ4QT6Lg/ but it is throwing error that

opaqueToken is not a constructor.

Can anyone help me with this?

I have attached my package.json. Please find it below

`

```<code>{

"name": "angular-quickstart",
  "version": "1.0.0",
  "description": "QuickStart package.json from the documentation, supplemented with testing support",
  "scripts": {
    "start": "concurrently \"tsc -w\" \"lite-server\" ",
    "e2e": "tsc && concurrently \"http-server -s\" \"protractor protractor.config.js\" --kill-others --success first",
    "lint": "tslint ./app/**/*.ts -t verbose",
    "lite": "lite-server",
    "pree2e": "webdriver-manager update",
    "test": "tsc && concurrently \"tsc -w\" \"karma start karma.conf.js\"",
    "test-once": "tsc && karma start karma.conf.js --single-run",
    "tsc": "tsc",
    "tsc:w": "tsc -w"
  },
  "keywords": [],
  "author": "",
  "license": "MIT",
  "dependencies": {
    "@angular/common": "~2.4.0",
    "@angular/compiler": "~2.4.0",
    "@angular/core": "~2.4.0",
    "@angular/forms": "~2.4.0",
    "@angular/http": "~2.4.0",
    "@angular/platform-browser": "~2.4.0",
    "@angular/platform-browser-dynamic": "~2.4.0",
    "@angular/router": "~3.4.0",
    "angular-in-memory-web-api": "~0.2.2",
    "core-js": "^2.4.1",
    "reflect-metadata": "^0.1.8",
    "rxjs": "5.0.1",
    "systemjs": "^0.20.19",
    "zone.js": "^0.7.4"
  },
  "devDependencies": {
    "concurrently": "^3.1.0",
    "lite-server": "^2.2.2",
    "typescript": "~2.0.10",
    "canonical-path": "0.0.2",
    "http-server": "^0.9.0",
    "tslint": "^3.15.1",
    "lodash": "^4.16.4",
    "jasmine-core": "~2.4.1",
    "karma": "^1.3.0",
    "karma-chrome-launcher": "^2.0.0",
    "karma-cli": "^1.0.1",
    "karma-jasmine": "^1.0.2",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~4.0.14",
    "rimraf": "^2.5.4",
    "@types/node": "^6.0.46",
    "@types/jasmine": "^2.5.36"
  },
  "repository": {}
}

`
</code>```

答:
You need to add your providers to a module.

This plunker has a good example of how to use: https://plnkr.co/edit/SHfTH9R6JVDwJKnzRFSH?p=preview

e.g.

App module - add providers here so each module can set what they need. The loggerapiconfig is the opaque token so the value can be set.

```<code>import { NgModule, provide } from '@angular/core';
import { BrowserModule }  from '@angular/platform-browser';
import { APP_BASE_HREF } from '@angular/common';

import { AppComponent } from './app.component';
import { EmailModule, apiConfig as emailApiConfig } from './email/index';
import { LoggerModule, apiConfig as loggerApiConfig } from './logger/index';

@NgModule({
  imports: [
    BrowserModule,
    EmailModule,
    LoggerModule,
  ],
  providers: [
    { provide: emailApiConfig, useValue: { apiKey: 'email-key', context: 'registration' } },
    { provide: loggerApiConfig, useValue: { apiKey: 'logger-key' } },
  ],
  declarations: [ AppComponent ],
  bootstrap: [ AppComponent ],
})
export class AppModule {

}
</code>```

Logger Module

```<code>import { NgModule } from '@angular/core';

import { LoggerService } from './logger.service';

@NgModule({
  providers: [ LoggerService ],
})
export class LoggerModule { }
</code>```

Logger Service - injects the opaquetoken with the values set in appmodule

```<code>import { Injectable, Inject, OpaqueToken } from '@angular/core';

import { LoggerConfig } from './logger.config';

export const apiConfig = new OpaqueToken('api-config');

@Injectable()
export class LoggerService {
  constructor(@Inject(apiConfig) public apiConfig: LoggerConfig) { }
}
</code>```

Logger Config

```<code>export type LoggerConfig = {
  apiKey: string
}
</code>```

logger/index

```<code>export { LoggerConfig } from './logger.config';
export { LoggerModule } from './logger.module';
export { apiConfig, LoggerService } from './logger.service';
</code>```

NOTE

OpaqueToken is deprecated in newer versions of Angular. You will need to use the InjectionToken class https://angular.io/api/core/InjectionToken

Title: OpaqueToken is not a constructor

Body:
I am trying to create a multilingual website using angular2 from the source code https://embed.plnkr.co/BnCRsCfB1ZIMoQ4QT6Lg/ but it is throwing error that

opaqueToken is not a constructor.

Can anyone help me with this?

I have attached my package.json. Please find it below

`

{

"name": "angular-quickstart",
  "version": "1.0.0",
  "description": "QuickStart package.json from the documentation, supplemented with testing support",
  "scripts": {
    "start": "concurrently \"tsc -w\" \"lite-server\" ",
    "e2e": "tsc && concurrently \"http-server -s\" \"protractor protractor.config.js\" --kill-others --success first",
    "lint": "tslint ./app/**/*.ts -t verbose",
    "lite": "lite-server",
    "pree2e": "webdriver-manager update",
    "test": "tsc && concurrently \"tsc -w\" \"karma start karma.conf.js\"",
    "test-once": "tsc && karma start karma.conf.js --single-run",
    "tsc": "tsc",
    "tsc:w": "tsc -w"
  },
  "keywords": [],
  "author": "",
  "license": "MIT",
  "dependencies": {
    "@angular/common": "~2.4.0",
    "@angular/compiler": "~2.4.0",
    "@angular/core": "~2.4.0",
    "@angular/forms": "~2.4.0",
    "@angular/http": "~2.4.0",
    "@angular/platform-browser": "~2.4.0",
    "@angular/platform-browser-dynamic": "~2.4.0",
    "@angular/router": "~3.4.0",
    "angular-in-memory-web-api": "~0.2.2",
    "core-js": "^2.4.1",
    "reflect-metadata": "^0.1.8",
    "rxjs": "5.0.1",
    "systemjs": "^0.20.19",
    "zone.js": "^0.7.4"
  },
  "devDependencies": {
    "concurrently": "^3.1.0",
    "lite-server": "^2.2.2",
    "typescript": "~2.0.10",
    "canonical-path": "0.0.2",
    "http-server": "^0.9.0",
    "tslint": "^3.15.1",
    "lodash": "^4.16.4",
    "jasmine-core": "~2.4.1",
    "karma": "^1.3.0",
    "karma-chrome-launcher": "^2.0.0",
    "karma-cli": "^1.0.1",
    "karma-jasmine": "^1.0.2",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~4.0.14",
    "rimraf": "^2.5.4",
    "@types/node": "^6.0.46",
    "@types/jasmine": "^2.5.36"
  },
  "repository": {}
}

`

Body:
You need to add your providers to a module.

This plunker has a good example of how to use: https://plnkr.co/edit/SHfTH9R6JVDwJKnzRFSH?p=preview

e.g.

App module - add providers here so each module can set what they need. The loggerapiconfig is the opaque token so the value can be set.

import { NgModule, provide } from '@angular/core';
import { BrowserModule }  from '@angular/platform-browser';
import { APP_BASE_HREF } from '@angular/common';

import { AppComponent } from './app.component';
import { EmailModule, apiConfig as emailApiConfig } from './email/index';
import { LoggerModule, apiConfig as loggerApiConfig } from './logger/index';

@NgModule({
  imports: [
    BrowserModule,
    EmailModule,
    LoggerModule,
  ],
  providers: [
    { provide: emailApiConfig, useValue: { apiKey: 'email-key', context: 'registration' } },
    { provide: loggerApiConfig, useValue: { apiKey: 'logger-key' } },
  ],
  declarations: [ AppComponent ],
  bootstrap: [ AppComponent ],
})
export class AppModule {

}

Logger Module

import { NgModule } from '@angular/core';

import { LoggerService } from './logger.service';

@NgModule({
  providers: [ LoggerService ],
})
export class LoggerModule { }

Logger Service - injects the opaquetoken with the values set in appmodule

import { Injectable, Inject, OpaqueToken } from '@angular/core';

import { LoggerConfig } from './logger.config';

export const apiConfig = new OpaqueToken('api-config');

@Injectable()
export class LoggerService {
  constructor(@Inject(apiConfig) public apiConfig: LoggerConfig) { }
}

Logger Config

export type LoggerConfig = {
  apiKey: string
}

logger/index

export { LoggerConfig } from './logger.config';
export { LoggerModule } from './logger.module';
export { apiConfig, LoggerService } from './logger.service';

NOTE

OpaqueToken is deprecated in newer versions of Angular. You will need to use the InjectionToken class https://angular.io/api/core/InjectionToken


来源: stackexchange

问:
Hide/Show Data Labels on update
I want to use

```<code>data: {
  labels: true
}
</code>```

in a standard chart, as shown here: http://c3js.org/samples/data_label.html

It is very fine when I use c3.generate function to create a new chart.

Now that the chart is created, I would like to hide/show these labels on update (when I load new data). I don't find how to properly do it.

Thank you

答:
There are no built-in way to toggle data labels.

But you can control its visibility using d3.js (which c3.js is based on):

```<code>d3.select('.c3-chart-texts').style('display', 'none') // or 'block'
</code>```

UPDATE:

If you got multiple charts, you can select corresponding labels either by chart object:

```<code>chart1.internal.selectChart.select('.c3-chart-texts')...
</code>```

or by chart id:

```<code>d3.select('#chart1').select('.c3-chart-texts')...
</code>```

ContentLicense: CC BY-SA 3.0

Title: Hide/Show Data Labels on update

Body:
I want to use

data: {
  labels: true
}

in a standard chart, as shown here: http://c3js.org/samples/data_label.html

It is very fine when I use c3.generate function to create a new chart.

Now that the chart is created, I would like to hide/show these labels on update (when I load new data). I don't find how to properly do it.

Thank you

Body:
There are no built-in way to toggle data labels.

But you can control its visibility using d3.js (which c3.js is based on):

d3.select('.c3-chart-texts').style('display', 'none') // or 'block'

UPDATE:

If you got multiple charts, you can select corresponding labels either by chart object:

chart1.internal.selectChart.select('.c3-chart-texts')...

or by chart id:

d3.select('#chart1').select('.c3-chart-texts')...


问:
Git: Remove all revisions of a file in a repository, and replace with new file
I need to move current and ALL past revisions of a file in my repository, and then replace them with a new file.  Basically, without thinking, I forgot (and continuously forgot) to remove the mysql password for the database connection file, and would like to remove any traces of this.

The simplest fix would be to change the mysql password and from this point on, do not include the password in the file, however, I'd like to just clean up the revision history.

答: Github has a help section dedicated to this issue. I actually used it before and find it very useful.</p>

ContentLicense: CC BY-SA 2.5


问:
Data to save in Yii not working
I tried to save these test data into the database if the record haven't exist yet. But when I try to create new record, it returns fail. I'm not sure what's wrong.

This is the code to check whether the registration id exist or not:

```<code>public static function getEventRegistration($registration_code)
{
    $model = EventRegistration::model()->findByAttributes(array('registration_code'=>$registration_code));
        if($model!==null)
        return $model;
}
</code>```

This is the code to save the new record:

```<code>public function actionEventReg()
{
    $tmps = HUB::getEventRegistration('999881');
    if(empty($tmps)){
        // echo 'record does not exist';

        //create new registration
        $object = new EventRegistration;
        $object->event_code = '206218';
        $object->event_vendor_code = 'bizzabo';
        $object->registration_code = '0123456';
        $object->full_name = 'test rifff';
        $object->first_name = 'test';
        $object->last_name = 'rifff';
        $object->email = 'rifhan@mymagic.my';
        $object->phone = '';
        $object->organization = '';
        $object->gender = '';
        $object->age_group = '';
        $object->where_found = '';
        $object->persona = '';
        $object->paid_fee = '';
        $object->is_attended = '';
        $object->date_registered = '';
        $object->date_payment = '';
        $object->json_original = '';
        $object->date_added = time();
        $object->date_modified = time();

        if($object->save()){
            $success = 'success';
        }else{
            $fail = 'fail';
        }
        //create junk
        $junk = new Junk;
        $junk->code = 'test-getRegistrationNotExist-'.time();
        $junk->content = sprintf('successfully insert data: %s or (%s). With first name is %s and last name is %s', $success, $fail, $object->first_name, $object->last_name);
        $junk->save();
    }else{
        // echo 'record exist';

        //create junk
        $junk = new Junk;
        $junk->code = 'test-getRegistrationExist-'.time();
        $junk->content = sprintf('called on: %s with first name is %s and last name is %s', Yii::app()->params['masterDomain'], $tmps->first_name, $tmps->last_name);
        $junk->save();
    }
}
</code>```

UPDATE:

I change the code like Yupik adviced to dump the error like below :

```<code>public function actionBizzaboCallback()
{
    $junk = new Junk;
    $junk->code = 'bizzabo-bizzaboCallback-'.time();

    $junk->content .= serialize($_POST);

    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        // fetch RAW input
        $json = file_get_contents('php://input');

        // decode json
        $objects = json_decode($json);

        // expecting valid json
        if (json_last_error() !== JSON_ERROR_NONE) {
            die(header('HTTP/1.0 415 Unsupported Media Type'));
        } else {
            // check if registration exist
            $tmps = HUB::getEventRegistrationByID($objects->details->items[0]->ticketId);

                if(empty($tmps)){
                    //1. echo 'record does not exist';

                    //2. create new registration
                    $object = new EventRegistration;
                    $object->event_code = $objects->eventId;
                    $object->event_vendor_code = 'bizzabo';
                    $object->registration_code = $objects->details->items[0]->ticketId;

                    $object->full_name = sprintf('%s %s', $objects->details->items[0]->registrationForm->firstName, $objects->details->items[0]->registrationForm->lastName);

                    $object->first_name = $objects->details->items[0]->registrationForm->firstName;
                    $object->last_name = $objects->details->items[0]->registrationForm->lastName;
                    $object->email = $objects->details->items[0]->registrationForm->email;

                    $object->phone = 'null';
                    // $object->phone = $objects->details->items[0]->registrationForm->mobileNumber;
                    $object->organization = 'null';
                    //$object->organization = $objects->details->items[0]->registrationForm->organisation__instit;

                    $object->gender = 'unknown';
                     if(isset($objects->details->items[0]->registrationForm->gender))
                     {
                        if(stristr($objects->details->items[0]->registrationForm->gender, 'female'))
                        {
                            $gender = 'female';
                        }
                        else
                        {
                            if(stristr($objects->details->items[0]->registrationForm->gender, 'male'))
                            {
                                $gender = 'male';
                            }
                        }
                    }

                    $object->age_group = $objects->details->items[0]->registrationForm->age_group;

                    $object->where_found = $objects->details->items[0]->registrationForm->how_did_you_hear_abo;

                    $object->persona = $objects->details->items[0]->registrationForm->type_of_person;

                    $object->paid_fee = $objects->details->items[0]->registrationForm->ticketPaid;

                    $object->date_registered = $objects->details->items[0]->registrationForm->created;

                    $object->date_payment = $objects->details->items[0]->registrationForm->created;

                    $object->json_original = $json;

                    $object->date_added = time();
                    $object->date_modified = time();

                    if($object->save()){
                        $success = 'success';
                    }else{
                        var_dump($object->getErrors());
                        $fail = 'fail';
                    }

                    //3. create junk
                    $junk = new Junk;
                    $junk->code = 'bizzabo-getBizzaboRegistrationIntoDB-'.time();
                    $junk->content = sprintf('ticket id: %s does not exist. %s into database.', $objects->details->items[0]->ticketId, $fail);

                }else{
                    //1. echo 'record exist';

                    //2. create junk
                    $junk = new Junk;
                    $junk->code = 'bizzabo-getBizzaboRegistrationExisted-'.time();
                    $junk->content = sprintf('ticket id: %s does exist. Did not update into database.',$objects->details->items[0]->ticketId);
                }
            $junk->content .= sprintf('Get error : %s ', $object->getErrors());
        }
    }
    $junk->save();
}
</code>```

But when I try to print $object->getErrors() in junk file, it displayed Array

答:
Code fix

This method:

```<code>public static function getEventRegistration($registration_code)
{
    $model = EventRegistration::model()->findByAttributes(array('registration_code'=>$registration_code));
        if($model!==null)
        return $model;
}
</code>```

You're checking if $model is not null, if that's true, you're returning $model, otherwise nothing, so it's like you're returning null. Change this to:

```<code>public static function getEventRegistration($registration_code)
{
    return EventRegistration::model()->findByAttributes(array('registration_code'=>$registration_code));
}
</code>```

Main problem:

To check what's wrong in your new object, simply put var_dump($object->getErrors());die; in else statement:

```<code>    if($object->save()){
        $success = 'success';
    }else{
        var_dump($object->getErrors());die;
        $fail = 'fail';
    }
</code>```

Then try to save it - if it fails one more time - you will see what's exacly wrong with your validation.

Title: Data to save in Yii not working

Body:
I tried to save these test data into the database if the record haven't exist yet. But when I try to create new record, it returns fail. I'm not sure what's wrong.

This is the code to check whether the registration id exist or not:

public static function getEventRegistration($registration_code)
{
    $model = EventRegistration::model()->findByAttributes(array('registration_code'=>$registration_code));
        if($model!==null)
        return $model;
}

This is the code to save the new record:

public function actionEventReg()
{
    $tmps = HUB::getEventRegistration('999881');
    if(empty($tmps)){
        // echo 'record does not exist';

        //create new registration
        $object = new EventRegistration;
        $object->event_code = '206218';
        $object->event_vendor_code = 'bizzabo';
        $object->registration_code = '0123456';
        $object->full_name = 'test rifff';
        $object->first_name = 'test';
        $object->last_name = 'rifff';
        $object->email = 'rifhan@mymagic.my';
        $object->phone = '';
        $object->organization = '';
        $object->gender = '';
        $object->age_group = '';
        $object->where_found = '';
        $object->persona = '';
        $object->paid_fee = '';
        $object->is_attended = '';
        $object->date_registered = '';
        $object->date_payment = '';
        $object->json_original = '';
        $object->date_added = time();
        $object->date_modified = time();

        if($object->save()){
            $success = 'success';
        }else{
            $fail = 'fail';
        }
        //create junk
        $junk = new Junk;
        $junk->code = 'test-getRegistrationNotExist-'.time();
        $junk->content = sprintf('successfully insert data: %s or (%s). With first name is %s and last name is %s', $success, $fail, $object->first_name, $object->last_name);
        $junk->save();
    }else{
        // echo 'record exist';

        //create junk
        $junk = new Junk;
        $junk->code = 'test-getRegistrationExist-'.time();
        $junk->content = sprintf('called on: %s with first name is %s and last name is %s', Yii::app()->params['masterDomain'], $tmps->first_name, $tmps->last_name);
        $junk->save();
    }
}

UPDATE:

I change the code like Yupik adviced to dump the error like below :

public function actionBizzaboCallback()
{
    $junk = new Junk;
    $junk->code = 'bizzabo-bizzaboCallback-'.time();

    $junk->content .= serialize($_POST);

    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        // fetch RAW input
        $json = file_get_contents('php://input');

        // decode json
        $objects = json_decode($json);

        // expecting valid json
        if (json_last_error() !== JSON_ERROR_NONE) {
            die(header('HTTP/1.0 415 Unsupported Media Type'));
        } else {
            // check if registration exist
            $tmps = HUB::getEventRegistrationByID($objects->details->items[0]->ticketId);

                if(empty($tmps)){
                    //1. echo 'record does not exist';

                    //2. create new registration
                    $object = new EventRegistration;
                    $object->event_code = $objects->eventId;
                    $object->event_vendor_code = 'bizzabo';
                    $object->registration_code = $objects->details->items[0]->ticketId;

                    $object->full_name = sprintf('%s %s', $objects->details->items[0]->registrationForm->firstName, $objects->details->items[0]->registrationForm->lastName);

                    $object->first_name = $objects->details->items[0]->registrationForm->firstName;
                    $object->last_name = $objects->details->items[0]->registrationForm->lastName;
                    $object->email = $objects->details->items[0]->registrationForm->email;

                    $object->phone = 'null';
                    // $object->phone = $objects->details->items[0]->registrationForm->mobileNumber;
                    $object->organization = 'null';
                    //$object->organization = $objects->details->items[0]->registrationForm->organisation__instit;

                    $object->gender = 'unknown';
                     if(isset($objects->details->items[0]->registrationForm->gender))
                     {
                        if(stristr($objects->details->items[0]->registrationForm->gender, 'female'))
                        {
                            $gender = 'female';
                        }
                        else
                        {
                            if(stristr($objects->details->items[0]->registrationForm->gender, 'male'))
                            {
                                $gender = 'male';
                            }
                        }
                    }

                    $object->age_group = $objects->details->items[0]->registrationForm->age_group;

                    $object->where_found = $objects->details->items[0]->registrationForm->how_did_you_hear_abo;

                    $object->persona = $objects->details->items[0]->registrationForm->type_of_person;

                    $object->paid_fee = $objects->details->items[0]->registrationForm->ticketPaid;

                    $object->date_registered = $objects->details->items[0]->registrationForm->created;

                    $object->date_payment = $objects->details->items[0]->registrationForm->created;

                    $object->json_original = $json;

                    $object->date_added = time();
                    $object->date_modified = time();

                    if($object->save()){
                        $success = 'success';
                    }else{
                        var_dump($object->getErrors());
                        $fail = 'fail';
                    }

                    //3. create junk
                    $junk = new Junk;
                    $junk->code = 'bizzabo-getBizzaboRegistrationIntoDB-'.time();
                    $junk->content = sprintf('ticket id: %s does not exist. %s into database.', $objects->details->items[0]->ticketId, $fail);

                }else{
                    //1. echo 'record exist';

                    //2. create junk
                    $junk = new Junk;
                    $junk->code = 'bizzabo-getBizzaboRegistrationExisted-'.time();
                    $junk->content = sprintf('ticket id: %s does exist. Did not update into database.',$objects->details->items[0]->ticketId);
                }
            $junk->content .= sprintf('Get error : %s ', $object->getErrors());
        }
    }
    $junk->save();
}

But when I try to print $object->getErrors() in junk file, it displayed Array

Body:
Code fix

This method:

public static function getEventRegistration($registration_code)
{
    $model = EventRegistration::model()->findByAttributes(array('registration_code'=>$registration_code));
        if($model!==null)
        return $model;
}

You're checking if $model is not null, if that's true, you're returning $model, otherwise nothing, so it's like you're returning null. Change this to:

public static function getEventRegistration($registration_code)
{
    return EventRegistration::model()->findByAttributes(array('registration_code'=>$registration_code));
}

Main problem:

To check what's wrong in your new object, simply put var_dump($object->getErrors());die; in else statement:

    if($object->save()){
        $success = 'success';
    }else{
        var_dump($object->getErrors());die;
        $fail = 'fail';
    }

Then try to save it - if it fails one more time - you will see what's exacly wrong with your validation.


问:
UICollectionView not showing & delegate/datasource methods not being called
I have my data source methods

```<code>- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{

    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{

    return 10;
}

-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{

    LPDiaryCollectionViewCell *cell = (LPDiaryCollectionViewCell*)[collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];

    cell.testLabel.text = @"test";
    return cell;

}
</code>```

The cell is registered

```<code>[self.collectionView registerClass:[LPDiaryCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
</code>```

Datasource, delegate and outlet are connected

But when I run, datasource methods don't get called and view is plain white with no UICollectionView showing.

EDIT: added the uicollectionview programattically instead. It displays but still no cell.

答:
static NSString *identifier = @"Yourcellname";

UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];

Body:
I have my data source methods

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{

    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{

    return 10;
}

-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{

    LPDiaryCollectionViewCell *cell = (LPDiaryCollectionViewCell*)[collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];

    cell.testLabel.text = @"test";
    return cell;

}

The cell is registered

[self.collectionView registerClass:[LPDiaryCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];

Datasource, delegate and outlet are connected

But when I run, datasource methods don't get called and view is plain white with no UICollectionView showing.

EDIT: added the uicollectionview programattically instead. It displays but still no cell.


问:
How can I remove my slash URLs with an .htaccess from localhost XAMPP
For example:

```<code><a href="/example/">example</a>
</code>```

to

```<code><a href="example">example</a>
</code>```

or

<link type="text/css" href="/assets/css/bootstrap.min.css" />

to

<link type="text/css" href="assets/css/bootstrap.min.css" />
enter image description here

my htaccess

```<code>RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+)/$ $1.php
RewriteRule ^([^/]+)/([^/]+)/$ /$1/$2.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/)$
RewriteRule (.*)$ /$1/ [R=301,L]
</code>```

Please help!....

答:
What about this?

RewriteEngine On

RewriteRule ^/(.*)$/ $1 [R=301,L]

RewriteRule ^/(.*)$/ $1/ [R=301,L]

Body:
For example:

example

to

example

or

<link type="text/css" href="/assets/css/bootstrap.min.css" />

to

<link type="text/css" href="assets/css/bootstrap.min.css" />
enter image description here

my htaccess

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+)/$ $1.php
RewriteRule ^([^/]+)/([^/]+)/$ /$1/$2.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/)$
RewriteRule (.*)$ /$1/ [R=301,L]

Please help!....


问:
Do I need to check if keys exist before adding new values to it in multidimensional arrays?
I remember writing code a long time ago like seen below. Where you check each key before adding value to it in multidimensional arrays:

```<code>$transactions = [];

if (!isset($transactions[$account])) {
    $transactions[$account] = [];
}

if (!$transactions[$account]['cards'])) {
    $transactions[$account]['cards'] = [];
}

$transactions[$account]["cards"][] = $card;
</code>```

but recently I noticed that I have started writing this:

```<code>$transactions = [];

$transactions[$account]["cards"][] = $card;
</code>```

and everything seems to work just fine without declaring those arrays beforehand.

答:
Yes, PHP will implicitly create intermediate arrays on assignment (and only on assignment):

If [the array] doesn't exist yet, it will be created, so this is also an
  alternative way to create an array. This practice is however
  discouraged because if [the array] already contains some value (e.g. string
  from request variable) then this value will stay in the place and []
  may actually stand for string access operator. It is always better to
  initialize a variable by a direct assignment.

http://php.net/manual/en/language.types.array.php#language.types.array.syntax.modifying

So, yes, it works and is explicitly supported, as long as you're sure about your array structures and you're not accidentally using [...] to access a string index instead of the array you expected.

Body:
I remember writing code a long time ago like seen below. Where you check each key before adding value to it in multidimensional arrays:

$transactions = [];

if (!isset($transactions[$account])) {
    $transactions[$account] = [];
}

if (!$transactions[$account]['cards'])) {
    $transactions[$account]['cards'] = [];
}

$transactions[$account]["cards"][] = $card;

but recently I noticed that I have started writing this:

$transactions = [];

$transactions[$account]["cards"][] = $card;

and everything seems to work just fine without declaring those arrays beforehand.


问:
How to install pip for Python 3.6 on Ubuntu 16.10?
I'd like to start by pointing out that this question may seem like a duplicate, but it isn't. All the questions I saw here were regarding pip for Python 3 and I'm talking about Python 3.6. The steps used back then don't work for Python 3.6.

I got a clear Ubuntu 16.10 image from the official docker store.

Run apt-get update

Run apt-get install python3.6

Run apt-get install python3-pip

Run pip3 install requests bs4

Run python3.6 script.py

Got ModuleNotFoundError below:

```<code> Traceback (most recent call last):
    File "script.py", line 6, in <module>
     import requests
 ModuleNotFoundError: No module named 'requests'
</code>```

Python's and pip's I have in the machine:

```<code>python3
python3.5
python3.5m
python3.6
python3m
python3-config
python3.5-config
python3.5m-config
python3.6m
python3m-config

pip
pip3
pip3.5
</code>```

答:
This website contains a much cleaner solution, it leaves pip intact as-well and one can easily switch between 3.5 and 3.6 and then whenever 3.7 is released.

http://ubuntuhandbook.org/index.php/2017/07/install-python-3-6-1-in-ubuntu-16-04-lts/

A short summary:

```<code>sudo apt-get install python python-pip python3 python3-pip
sudo add-apt-repository ppa:jonathonf/python-3.6
sudo apt-get update
sudo apt-get install python3.6
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.5 1
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.6 2
</code>```

Then

```<code>$ pip -V
pip 8.1.1 from /usr/lib/python2.7/dist-packages (python 2.7)
$ pip3 -V
pip 8.1.1 from /usr/local/lib/python3.5/dist-packages (python 3.5)
</code>```

Then to select python 3.6 run

```<code>sudo update-alternatives --config python3
</code>```

and select '2'. Then

```<code>$ pip3 -V
pip 8.1.1 from /usr/local/lib/python3.6/dist-packages (python 3.6)
</code>```

To update pip select the desired version and

```<code>pip3 install --upgrade pip

$ pip3 -V
pip 9.0.1 from /usr/local/lib/python3.6/dist-packages (python 3.6)
</code>```

Tested on Ubuntu 16.04.

Body:
I'd like to start by pointing out that this question may seem like a duplicate, but it isn't. All the questions I saw here were regarding pip for Python 3 and I'm talking about Python 3.6. The steps used back then don't work for Python 3.6.

I got a clear Ubuntu 16.10 image from the official docker store.

Run apt-get update

Run apt-get install python3.6

Run apt-get install python3-pip

Run pip3 install requests bs4

Run python3.6 script.py

Got ModuleNotFoundError below:

 Traceback (most recent call last):
    File "script.py", line 6, in <module>
     import requests
 ModuleNotFoundError: No module named 'requests'

Python's and pip's I have in the machine:

python3
python3.5
python3.5m
python3.6
python3m
python3-config
python3.5-config
python3.5m-config
python3.6m
python3m-config

pip
pip3
pip3.5

Body:
This website contains a much cleaner solution, it leaves pip intact as-well and one can easily switch between 3.5 and 3.6 and then whenever 3.7 is released.

http://ubuntuhandbook.org/index.php/2017/07/install-python-3-6-1-in-ubuntu-16-04-lts/

A short summary:

sudo apt-get install python python-pip python3 python3-pip
sudo add-apt-repository ppa:jonathonf/python-3.6
sudo apt-get update
sudo apt-get install python3.6
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.5 1
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.6 2

Then

$ pip -V
pip 8.1.1 from /usr/lib/python2.7/dist-packages (python 2.7)
$ pip3 -V
pip 8.1.1 from /usr/local/lib/python3.5/dist-packages (python 3.5)

Then to select python 3.6 run

sudo update-alternatives --config python3

and select '2'. Then

$ pip3 -V
pip 8.1.1 from /usr/local/lib/python3.6/dist-packages (python 3.6)

To update pip select the desired version and

pip3 install --upgrade pip

$ pip3 -V
pip 9.0.1 from /usr/local/lib/python3.6/dist-packages (python 3.6)

Tested on Ubuntu 16.04.


问:
Cannot return paginated result from service in angular 5
I have the following code which returned paginated result from my service. I just switched to angular 5 and now the code doesn't work anymore

```<code>return this._http.get(
        this.userManagerResourceApiUrl + "GetAllUsers/" + tierID + "/" + countryID + "/" + officeID + "/" + filter
    ).map((res: Response) => {
            paginatedResult.result = res.json();

            if (res.headers.get("Pagination") != null) {
                var paginationHeader: Pagination = this.itemsService.getSerialized<Pagination>(JSON.parse(res.headers.get("Pagination")));
                paginatedResult.pagination = paginationHeader;
            }

            this.totalItems = paginatedResult.pagination.TotalItems;
            return paginatedResult;
        }).catch(this.handleError);
</code>```

I get the following error message

```<code>Type 'Promise<any>' is not assignable to type 'IUser[]'
</code>```

答:
In angular 5,  You don't need to map to json anymore and remove any map(res => res.json()) calls, which are no longer needed.

Things to take care while upgrading your project to angular 5.
 https://onlyforcoder.blogspot.in/2017/11/angular-5-upgrade-your-project-To-Angular5.html

Body:
I have the following code which returned paginated result from my service. I just switched to angular 5 and now the code doesn't work anymore

return this._http.get(
        this.userManagerResourceApiUrl + "GetAllUsers/" + tierID + "/" + countryID + "/" + officeID + "/" + filter
    ).map((res: Response) => {
            paginatedResult.result = res.json();

            if (res.headers.get("Pagination") != null) {
                var paginationHeader: Pagination = this.itemsService.getSerialized<Pagination>(JSON.parse(res.headers.get("Pagination")));
                paginatedResult.pagination = paginationHeader;
            }

            this.totalItems = paginatedResult.pagination.TotalItems;
            return paginatedResult;
        }).catch(this.handleError);

I get the following error message

Type 'Promise<any>' is not assignable to type 'IUser[]'


问:
ClickOnce and IsolatedStorage
The Winform application is release with ClickOnce in our Intranet. We store personal preference for the GUI in the Isolated Storage. All works pretty fine :)

The problem is when we have a new version of the application, we publish... all preferences are lost! User need to setup their preference over and over each version.

Is there a way to freeze the isolation for the whole application instead of the version?

答:
a summary from the other answers:</p>

```<code>IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForAssembly();//for visual studio
if (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed)
{
    isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();//for click once applications
}
</code>```

OwnerDisplayName: Daok

Title: ClickOnce and IsolatedStorage

LastEditorDisplayName: Jon B

Body:
a summary from the other answers:

IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForAssembly();//for visual studio
if (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed)
{
    isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();//for click once applications
}


问:
Capture event of children in parent component React with no markup of own
```<code>var React = require('react');
var {Col} = require('react-bootstrap/lib');

var Segment = require('../util/segment-data');

module.exports = React.createClass({
    displayName: 'MyFilter',
    propTypes: {
        children: React.PropTypes.node,
        component: React.PropTypes.string
    },
    render(){
        return (
            this.props.children
        );
    },
    captureEventHandler(){
        var data = {
            label: e.target.innerText ? e.target.innerText : e.target.textContent
        };
        Segment.track(this.props.component, data);
    }
});
</code>```

Then

```<code><SegmentFilter component={Events.sailing_schedules}>
                        <div onClick={this.handleSort.bind(null, 'departure_date')}>Departure Date <span className='caret'></span></div>
                    </SegmentFilter>
</code>```

My question is that how do I capture click, enter or any event happening in children in the component SegmentFilter?
Is it possible to not specify any DOM element inside render ? So basically I am asking how can I do it without doing the following.

```<code>return (
        <div onClick={this.handleClick}>
            {this.props.children}
        </div>
    );
handleClick(e){
    var data = {
        label: e.target.innerText ? e.target.innerText : e.target.textContent
    };
    Segment.track(this.props.component, data);
}
</code>```

The reason I am avoiding this is because I don't want to specify any html of my wrapper component. Or at worst even if I use the div how can I capture any event of child element inside parent component.

So I am looking to write a global event handler in Segment wrapper which will be called no matter which event fires and not only click in child elements. Let's say it should bubble upto that function handleClick

UPDATE -
I referred this but couldn't find my case.

Example for Bubbling and Capturing in React.js

答:
You can do this my applying onClick prop to all children.

```<code>render() {
  return React.Children.map(this.props.children, child => {
    return React.cloneElement(child, {
      onClick: this.captureEventHandler
    });
  });
}
</code>```

Body:
var React = require('react');
var {Col} = require('react-bootstrap/lib');

var Segment = require('../util/segment-data');

module.exports = React.createClass({
    displayName: 'MyFilter',
    propTypes: {
        children: React.PropTypes.node,
        component: React.PropTypes.string
    },
    render(){
        return (
            this.props.children
        );
    },
    captureEventHandler(){
        var data = {
            label: e.target.innerText ? e.target.innerText : e.target.textContent
        };
        Segment.track(this.props.component, data);
    }
});

Then

<SegmentFilter component={Events.sailing_schedules}>

Departure Date

                    </SegmentFilter>

My question is that how do I capture click, enter or any event happening in children in the component SegmentFilter?
Is it possible to not specify any DOM element inside render ? So basically I am asking how can I do it without doing the following.

return (

            {this.props.children}

    );
handleClick(e){
    var data = {
        label: e.target.innerText ? e.target.innerText : e.target.textContent
    };
    Segment.track(this.props.component, data);
}

The reason I am avoiding this is because I don't want to specify any html of my wrapper component. Or at worst even if I use the div how can I capture any event of child element inside parent component.

So I am looking to write a global event handler in Segment wrapper which will be called no matter which event fires and not only click in child elements. Let's say it should bubble upto that function handleClick

UPDATE -
I referred this but couldn't find my case.

Example for Bubbling and Capturing in React.js

Body:
You can do this my applying onClick prop to all children.

render() {
  return React.Children.map(this.props.children, child => {
    return React.cloneElement(child, {
      onClick: this.captureEventHandler
    });
  });
}


问:
Copy the content of a document file and append it into another keeping it formatted C#
I want to copy the content of a document file to another keeping it formatted. I found a way to copy the whole document to a new one using File.Copy(file, newFile, true); but I need to append the content to another existing one.

答:
Here is a quick code sample that should get you on your way:</p>

```<code>using Word = Microsoft.Office.Interop.Word;

var wdApp = new Word.Application();
var documents = wdApp.Documents;
var doc = documents.Open(newFile);
doc.Content.Collapse(Word.WdCollapseDirection.wdCollapseEnd);
doc.Content.InsertFile(file);
</code>```

Body:
Here is a quick code sample that should get you on your way:

using Word = Microsoft.Office.Interop.Word;

var wdApp = new Word.Application();
var documents = wdApp.Documents;
var doc = documents.Open(newFile);
doc.Content.Collapse(Word.WdCollapseDirection.wdCollapseEnd);
doc.Content.InsertFile(file);


问:
Can't make LiveValidation validMessage empty
i am using the livevalidation plugin, and have just switched from the prototype version to the standalone version, and have noticed a change in behaviour.

When a user enters the correct information in a field, i dont want there to be any acknoldgement, so i set:

```<code>validMessage: ""
</code>```

That worked with the prototype version of the plugin, but with the standalone version, it defaults to the message "Thankyou!"

This is not what i want at all, am i missing something?

答:
Nope, you are not missing anything. It's a bug (?) or simply different behavior between the two versions. In the prototype version, the options are extended (using prototype's Object.extend method) with the default options. Since you declare a validMessage property (albeit set to the empty string) it won't get replaced by the default value. In the standalone version, on the other hand the validMessage option is set with the following code:

```<code>this.validMessage = options.validMessage || 'Thankyou!';
</code>```

In other words, if validMessage is falsy (which the empty string is) set it to the default.

I suppose the workaround is to use " " (single space) as the value for validMessage. Or write to the developers and ask for the different behavior to be fixed.

Body:
i am using the livevalidation plugin, and have just switched from the prototype version to the standalone version, and have noticed a change in behaviour.

When a user enters the correct information in a field, i dont want there to be any acknoldgement, so i set:

validMessage: ""

That worked with the prototype version of the plugin, but with the standalone version, it defaults to the message "Thankyou!"

This is not what i want at all, am i missing something?

Body:
Nope, you are not missing anything. It's a bug (?) or simply different behavior between the two versions. In the prototype version, the options are extended (using prototype's Object.extend method) with the default options. Since you declare a validMessage property (albeit set to the empty string) it won't get replaced by the default value. In the standalone version, on the other hand the validMessage option is set with the following code:

this.validMessage = options.validMessage || 'Thankyou!';

In other words, if validMessage is falsy (which the empty string is) set it to the default.

I suppose the workaround is to use " " (single space) as the value for validMessage. Or write to the developers and ask for the different behavior to be fixed.


问:
Write an empty file with just the UTF-8 BOM
OS: Windows 7 SP1

I created an empty text file in the cmd.exe using the below command:

```<code>echo 2> .gitignore
</code>```

The command redirects std::cerr (empty output in this case) into the .gitignore file. The result file has ANSI encoding, but I need UTF-8. Can I point the necessary encoding (UTF-8) for the > operation?

答:
Create a .bat/.cmd file like:

```<code><nul SET /P "=123"> output.txt
</code>```

Then replace 123 with EF BB BF bytes in your prefered HEX-editor.

To edit this .bat/.cmd file later one shouldn't use Window's Notepad.exe as it converts BOM-bytes to a question mark (?) in the "Save as ASCII" mode (or, in the "Save as UTF-8" mode it adds unneeded BOM to the script file itself).
Instead one can use Notepad++ with a "UTF-8 (witout BOM)" mode.

ContentLicense: CC BY-SA 4.0

Body:
OS: Windows 7 SP1

I created an empty text file in the cmd.exe using the below command:

echo 2> .gitignore

The command redirects std::cerr (empty output in this case) into the .gitignore file. The result file has ANSI encoding, but I need UTF-8. Can I point the necessary encoding (UTF-8) for the > operation?

Body:
Create a .bat/.cmd file like:

<nul SET /P "=123"> output.txt

Then replace 123 with EF BB BF bytes in your prefered HEX-editor.

To edit this .bat/.cmd file later one shouldn't use Window's Notepad.exe as it converts BOM-bytes to a question mark (?) in the "Save as ASCII" mode (or, in the "Save as UTF-8" mode it adds unneeded BOM to the script file itself).
Instead one can use Notepad++ with a "UTF-8 (witout BOM)" mode.


问:
Yii2 Convert Number to words
Is there a way in yii2 to convert a number into words?

For example 101 into "one hundred one".
I didn't find an extension for yii2.
Is there any function?

答:
You can use asSpellout()

```<code>Yii::$app->formatter->asSpellout(101);
</code>```

Make sure you have PHP intl extension installed.

Title: Yii2 Convert Number to words

Body:
You can use asSpellout()

Yii::$app->formatter->asSpellout(101);

Make sure you have PHP intl extension installed.


问:
Fill variable with text of a .txt file at an FTP server in Python
I think my question sounds kinda stupid but I'm pretty new to python programming.

I just want to have a text variable which gets a string from a .txt file at an FTP server.

So in conclusion: There is a .txt File stored at an FTP server and I want to have the content of this file stored in an variable...

This is what I have so far... Can anybody help me? I use Python 3.6.3 :) thanks in advance!

```<code>from ftplib import FTP

ftp = FTP('1bk2t.ddns.net')
ftp.login(user='User', passwd = 'Password')

ftp.cwd('/path/')

filename = 'filename.txt'

ftp.retrbinary("RETR " + filename, open(filename, 'wb').write)
ftp.quit()

var = localfile.read
</code>```

答:
If you want to download a text file contents to memory, without using any temporary file, use FTP.retrlines like:

```<code>contents = ""
def collectLines(s):
    global contents
    contents += s + "\n"

ftp.retrlines("RETR " + filename, collectLines)
</code>```

Or use an array:

```<code>lines = []
ftp.retrlines("RETR " + filename, lines.append)
</code>```

Body:
I think my question sounds kinda stupid but I'm pretty new to python programming.

I just want to have a text variable which gets a string from a .txt file at an FTP server.

So in conclusion: There is a .txt File stored at an FTP server and I want to have the content of this file stored in an variable...

This is what I have so far... Can anybody help me? I use Python 3.6.3 :) thanks in advance!

from ftplib import FTP

ftp = FTP('1bk2t.ddns.net')
ftp.login(user='User', passwd = 'Password')

ftp.cwd('/path/')

filename = 'filename.txt'

ftp.retrbinary("RETR " + filename, open(filename, 'wb').write)
ftp.quit()

var = localfile.read

Body:
If you want to download a text file contents to memory, without using any temporary file, use FTP.retrlines like:

contents = ""
def collectLines(s):
    global contents
    contents += s + "\n"

ftp.retrlines("RETR " + filename, collectLines)

Or use an array:

lines = []
ftp.retrlines("RETR " + filename, lines.append)


问:
Read .txt file from maven project in java using executable file in linux shell
I want to read a .txt file from a java project on click of an executable file in linux based command prompt in a manner as shown below

./xyz inputs.txt

where xyz is the executable file and inputs is the input file. The executable file will launch the main class which is to read the inputs.txt file and proceed.
Please Note: It is compulsory to use the command as shown above

答: So what is your problem? You trying to read it from the terminal or from some IDE?</p>


问:
How to automate updating a trac wiki page?
I have a trac wiki page I'd like to update automatically on a regular basis (say, once an hour) with data fetched by a script.

I can get the script to generate the wiki markup.

How would you then upload that to the trac page? I want to replace the whole body of the page.

I would prefer a solution in python, as the rest of the stack (trac, fetching scripts) also use that. Just a pointer in the right direction should be enough ;)

答: I had a hard time getting the XmlRpcPlugin to work, details in the trac ticket: http://trac-hacks.org/ticket/6035#comment:7</p>


问:
How do i read lines in txt and use them in a method for ruby, exactly as the text is?
```<code>class Test

  def self.take_test( question, options, answer )
    puts question
    options.each_with_index { |option, idx| puts "#{ idx + 1 }: #{ option}" }
    print "Answer: "
    reply = gets.to_i
    if answer == reply
      puts "Correct!"
    else
      puts "Wrong. The answer is: " + answer.to_s
    end
  end
end

file = File.open("Matematik.txt", "r")
</code>```

This is what i tried to do:

```<code>  IO.foreach("Matematik.txt") { |line| Test.take_test(line) }
</code>```

This is how the questions are set up in the file:

'What is 2+2?', [ '2', '3', '4', '5', ], 4

'What is 3+3?', [ '3', '6', '9', ], 6

I get the error: take_test wrong number of arguments given (given 1, expected 3) (ArgumentError)

It seems like it reads the line like 1 argument. Is there a way to read the lines exactly as i stands, and input it like this?:

```<code>#Test.take_test('What is 2+2?', [ '2', '3', '4', '5', ], 4)
</code>```

答:
In theory, yes, with eval("Test.take_test(#{line})"). However, eval is evil, and to be avoided if at all possible.

It would be much easier if you changed your file format so you can deconstruct it easily. (It is not impossible with your format, it's just you have a lot of unnecessary work, when compared to a simpler format.) For example, given lines formatted like CSV:

```<code>"What is 2+2?",2,3,4,5,4
</code>```

it is very easy to do the following:

```<code>require 'csv'

Question = Struct.new(:text, :options, :answer)

questions = CSV.read("Mathematik.csv").map { |text, *options, answer|
  Question.new(text, options, answer.to_i)
}

questions[0].text
# => "What is 3+3?"

questions[0].options
# => ["2", "3", "4", "5"]

questions[0].answer
# => 4
</code>```

Body:
class Test

  def self.take_test( question, options, answer )
    puts question
    options.each_with_index { |option, idx| puts "#{ idx + 1 }: #{ option}" }
    print "Answer: "
    reply = gets.to_i
    if answer == reply
      puts "Correct!"
    else
      puts "Wrong. The answer is: " + answer.to_s
    end
  end
end

file = File.open("Matematik.txt", "r")

This is what i tried to do:

  IO.foreach("Matematik.txt") { |line| Test.take_test(line) }

This is how the questions are set up in the file:

'What is 2+2?', [ '2', '3', '4', '5', ], 4

'What is 3+3?', [ '3', '6', '9', ], 6

I get the error: take_test wrong number of arguments given (given 1, expected 3) (ArgumentError)

It seems like it reads the line like 1 argument. Is there a way to read the lines exactly as i stands, and input it like this?:

#Test.take_test('What is 2+2?', [ '2', '3', '4', '5', ], 4)

Body:
In theory, yes, with eval("Test.take_test(#{line})"). However, eval is evil, and to be avoided if at all possible.

It would be much easier if you changed your file format so you can deconstruct it easily. (It is not impossible with your format, it's just you have a lot of unnecessary work, when compared to a simpler format.) For example, given lines formatted like CSV:

"What is 2+2?",2,3,4,5,4

it is very easy to do the following:

require 'csv'

Question = Struct.new(:text, :options, :answer)

questions = CSV.read("Mathematik.csv").map { |text, *options, answer|
  Question.new(text, options, answer.to_i)
}

questions[0].text
# => "What is 3+3?"

questions[0].options
# => ["2", "3", "4", "5"]

questions[0].answer
# => 4


问:
BeautifulSoup with python
I am trying to learn beautifulsoup to scrap HTML and have a difficult challenge. HTML I am trying to scrap is not well formatted and with lack of knowledge with beautifulsoup I am kind of stuck..

The HTML I am trying to scrap is as below

```<code> *<tr class="unique">
                    <td>S.N.</td>
                    <td><a href="http://www.nepalstock.com/main/todays_price/index/1/stock-name/desc/" class="icon-asc sorter">Traded Companies</a></td>
                    <td class="alnright"><a href="http://www.nepalstock.com/main/todays_price/index/1/transaction/asc/" class="icon-sorter sorter">No. Of Transaction</a></td>
                    <td class="alnright"><a href="http://www.nepalstock.com/main/todays_price/index/1/max-price/asc/" class="icon-sorter sorter">Max Price</a></td>
                    <td class="alnright"><a href="http://www.nepalstock.com/main/todays_price/index/1/min-price/asc/" class="icon-sorter sorter">Min Price</a></td>
                    <td class="alnright"><a href="http://www.nepalstock.com/main/todays_price/index/1/closing-price/asc/" class="icon-sorter sorter">Closing Price</a></td>
                    <td class="alnright"><a href="http://www.nepalstock.com/main/todays_price/index/1/total-share/asc/" class="icon-sorter sorter">Traded Shares</a></td>
                    <td class="alnright"><a href="http://www.nepalstock.com/main/todays_price/index/1/amount/asc/" class="icon-sorter sorter">Amount</a></td>
                    <td class="alnright"><a href="http://www.nepalstock.com/main/todays_price/index/1/previous-closing/asc/" class="icon-sorter sorter">Previous Closing</a></td>
                    <td class="alnright"><a href="http://www.nepalstock.com/main/todays_price/index/1/difference/asc/" class="icon-sorter sorter">Difference Rs.</a></td>
                </tr>
                <tr>
                    <td>1</td>
                    <td>Agriculture Development Bank Limited</td>
                    <td class="alnright">47</td>
                    <td class="alnright">437.00</td>
                    <td class="alnright">426.00</td>
                    <td class="alnright">435.00</td>
                    <td class="alnright">9725.00</td>
                    <td class="alnright">4204614.00</td>
                    <td class="alnright">431.00</td>
                    <td class="alnright">4.00
                        <img src="http://www.nepalstock.com/images/increase.gif">
                    </td>
                </tr>*
</code>```

So the outcome I want to get is the string "Agriculture Development Bank Limited".
Thanks in advance for your help !

答:
Can help you more precisely if you ask it in general what are you looking for. Here is the code which will satisfy your this need.</p>

```<code>from bs4 import BeautifulSoup
html_doc = """
Your HTML code
"""
soup = BeautifulSoup(html_doc, 'html.parser')
soup.find("td", text="Agriculture Development Bank Limited").text
</code>```

Title: BeautifulSoup with python

Body:
I am trying to learn beautifulsoup to scrap HTML and have a difficult challenge. HTML I am trying to scrap is not well formatted and with lack of knowledge with beautifulsoup I am kind of stuck..

The HTML I am trying to scrap is as below

 *

                    S.N.
                    Traded Companies
                    No. Of Transaction
                    Max Price
                    Min Price
                    Closing Price
                    Traded Shares
                    Amount
                    Previous Closing
                    Difference Rs.

                    1
                    Agriculture Development Bank Limited
                    47
                    437.00
                    426.00
                    435.00
                    9725.00
                    4204614.00
                    431.00
                    4.00

*

So the outcome I want to get is the string "Agriculture Development Bank Limited".
Thanks in advance for your help !

Body:
Can help you more precisely if you ask it in general what are you looking for. Here is the code which will satisfy your this need.

from bs4 import BeautifulSoup
html_doc = """
Your HTML code
"""
soup = BeautifulSoup(html_doc, 'html.parser')
soup.find("td", text="Agriculture Development Bank Limited").text


问:
How to assure data consistency between components on front?
How to make sure all components have access to same data ?

Problem

When components change data while others still use an old value.

When component refresh data it's refreshed locally by not for other components.

How to deal with this ? is theire a design pattern explaining how to centralise data source to handle this

答:
The best way to share data between components is to use service.

As per official style guide it is not recommended to perform complex data manipulations inside components:

The component's responsibility is for the presentation and gathering
  of information for the view. It should not care how it gets the data,
  just that it knows who to ask for it. Separating the data services
  moves the logic on how to get it to the data service, and lets the
  component be simpler and more focused on the view.

If you still need to update data on the component level, you would need to do manual change detection checks. OnChanges lifecycle hook method is what you're looking for I believe.


问:
RXJS. Lazy observable
I'm playing around with rxjs trying to understand one concept: reactive programming supposed to be lazy. If no one subscriber is attached to an observable, it shouldn't produce values. Here is my example:

const Rx = require('rxjs')

const state = new Rx.Subject()

const changeStateLazy = (args) =>
    Rx.Observable.of(args)
        // some logic, e.g. REST requests
        .do(val => state.next('new state'))

changeStateLazy(42)

const stateListener = state.subscribe(
    val => console.log('state.next: ', val),
    err => console.log('state.error: ', err),
    () => console.log('state.complete'))
```

How to make the observable (which in function changeStateLazy) lazy, i.e. run some logic... and change the state only if a listener is attached to state subject (in my case it's stateListener)?

答:
Here is how I could manage that.

```<code>const Rx = require('rxjs')

const lazyStateModifier = new Rx.ReplaySubject(1)
    .map(args => {
        console.log('>some logic. args: ', args)
        return {status: 'OK', result: 'new state'}
    })
    .map(res => res.result)

const state = new Rx.Subject().merge(lazyStateModifier)

const changeStateLazy = (args) =>
    lazyStateModifier.next(args)

console.log('>invoke changeStateLazy')
changeStateLazy(42)

console.log('>subscribe')
state.subscribe(
    val => console.log('state.next: ', val),
    err => console.log('state.error: ', err),
    () => console.log('state.complete'))
</code>```

Hope there's a better solution, without merging every lazy observable to the state...

Title: RXJS. Lazy observable

Body:
I'm playing around with rxjs trying to understand one concept: reactive programming supposed to be lazy. If no one subscriber is attached to an observable, it shouldn't produce values. Here is my example:

const Rx = require('rxjs')

const state = new Rx.Subject()

const changeStateLazy = (args) =>
    Rx.Observable.of(args)
        // some logic, e.g. REST requests
        .do(val => state.next('new state'))

changeStateLazy(42)

const stateListener = state.subscribe(
    val => console.log('state.next: ', val),
    err => console.log('state.error: ', err),
    () => console.log('state.complete'))

How to make the observable (which in function changeStateLazy) lazy, i.e. run some logic... and change the state only if a listener is attached to state subject (in my case it's stateListener)?

Body:
Here is how I could manage that.

const Rx = require('rxjs')

const lazyStateModifier = new Rx.ReplaySubject(1)
    .map(args => {
        console.log('>some logic. args: ', args)
        return {status: 'OK', result: 'new state'}
    })
    .map(res => res.result)

const state = new Rx.Subject().merge(lazyStateModifier)

const changeStateLazy = (args) =>
    lazyStateModifier.next(args)

console.log('>invoke changeStateLazy')
changeStateLazy(42)

console.log('>subscribe')
state.subscribe(
    val => console.log('state.next: ', val),
    err => console.log('state.error: ', err),
    () => console.log('state.complete'))

Hope there's a better solution, without merging every lazy observable to the state...


问:
Radio button not selected by default in angular 4
I am trying to make the radio button selected by default in angular 4.

Below is my template code:

```<code> <div class="form-check form-check-inline">
  <label class="form-check-label">  </label>
    <input type="radio" class="form-check-input"
    name="type"
    [(ngModel)]="searchForm.type"
    [value]="['all']"
[checked]='searchForm.type ==='all''
    > All
</div>
</code>```

And I am initializing default value in my component ngOnInit

```<code>export class myComponent{
searchForm:FormVO = new FormVO();

ngOnInit(){
this.searchForm.type='all';
}
}
</code>```

I also tried with constructor initialize, here actually value is setting to searchForm.type as all in both constructor or nginit way.
Issue I am facing is I could not make the radio selected only in template.

These are the ways I tried:

Way 1:

```<code>[checked]="searchForm.type ==='all'"
</code>```

Way 2:

```<code>[checked]="searchForm.type ==='all' ? true : false"
</code>```

way 3:

```<code>[checked]="searchForm.type =='all'"
</code>```

I also read in few sits like through numbers i can make this selected by default. I did not try that way, because I want the solution with string values only.

Thanks in advance.

I request to avoid marking this as duplicate question, as I already tried all the solutions for those questions and nothing worked.

I am using angular cli with angular 4.

答: I solved this problem by adding form tag around input boxes. Please try it and look if it works for you.</p>

Body:
I am trying to make the radio button selected by default in angular 4.

Below is my template code:

    <input type="radio" class="form-check-input"
    name="type"
    [(ngModel)]="searchForm.type"
    [value]="['all']"
[checked]='searchForm.type ==='all''
    > All

And I am initializing default value in my component ngOnInit

export class myComponent{
searchForm:FormVO = new FormVO();

ngOnInit(){
this.searchForm.type='all';
}
}

I also tried with constructor initialize, here actually value is setting to searchForm.type as all in both constructor or nginit way.
Issue I am facing is I could not make the radio selected only in template.

These are the ways I tried:

Way 1:

[checked]="searchForm.type ==='all'"

Way 2:

[checked]="searchForm.type ==='all' ? true : false"

way 3:

[checked]="searchForm.type =='all'"

I also read in few sits like through numbers i can make this selected by default. I did not try that way, because I want the solution with string values only.

Thanks in advance.

I request to avoid marking this as duplicate question, as I already tried all the solutions for those questions and nothing worked.

I am using angular cli with angular 4.


问:
Eclipse JUnit - possible causes of seeing "initializationError" in Eclipse window
I know this question is pretty general but I haven't found any hints on why this error may show up. What are possible causes of seeing initalizationError in Eclipse window? I get no useful information just a long and useless failure trace (not included here).

I am using JUnit 4.11

I have written the following code - just to see if it works:

```<code>package test;

import static org.junit.Assert.*;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

public class SimpleTest {

@BeforeClass
public static void setUpBeforeClass() throws Exception {
}

@AfterClass
public static void tearDownAfterClass() throws Exception {
}

@Test
public void test() {
    assertEquals(15, 15);
}

}
</code>```

Edit: Sorry In Eclipse window it's called actually a "Failure trace":

```<code>java.lang.NoClassDefFoundError: org/hamcrest/SelfDescribing     at
java.lang.ClassLoader.defineClass1(Native Method)   at
java.lang.ClassLoader.defineClass(Unknown Source)   at
java.security.SecureClassLoader.defineClass(Unknown Source)     at
java.net.URLClassLoader.defineClass(Unknown Source)     at
java.net.URLClassLoader.access$100(Unknown Source)  at
java.net.URLClassLoader$1.run(Unknown Source)   at
java.net.URLClassLoader$1.run(Unknown Source)   at
java.security.AccessController.doPrivileged(Native Method)  at
java.net.URLClassLoader.findClass(Unknown Source)   at
java.lang.ClassLoader.loadClass(Unknown Source)     at
sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)  at
java.lang.ClassLoader.loadClass(Unknown Source)     at
org.junit.internal.builders.JUnit4Builder.runnerForClass(JUnit4Builder.java:10)
    at
org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at
org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
    at
org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at
org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:26)
    at
org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.<init>(JUnit4TestReference.java:33)
    at
org.eclipse.jdt.internal.junit4.runner.JUnit4TestClassReference.<init>(JUnit4TestClassReference.java:25)
    at
org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:48)
    at
org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:38)
    at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:452)
    at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: java.lang.ClassNotFoundException:
org.hamcrest.SelfDescribing     at java.net.URLClassLoader$1.run(Unknown
Source)     at java.net.URLClassLoader$1.run(Unknown Source)    at
java.security.AccessController.doPrivileged(Native Method)  at
java.net.URLClassLoader.findClass(Unknown Source)   at
java.lang.ClassLoader.loadClass(Unknown Source)     at
sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)  at
java.lang.ClassLoader.loadClass(Unknown Source)     ... 25 more
</code>```

答: Also make sure you have all @Before-, @After- and whatever-JUnit-annotated methods declared as public. I had mine declared as private which caused the issue.

Body:
I know this question is pretty general but I haven't found any hints on why this error may show up. What are possible causes of seeing initalizationError in Eclipse window? I get no useful information just a long and useless failure trace (not included here).

I am using JUnit 4.11

I have written the following code - just to see if it works:

package test;

import static org.junit.Assert.*;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

public class SimpleTest {

@BeforeClass
public static void setUpBeforeClass() throws Exception {
}

@AfterClass
public static void tearDownAfterClass() throws Exception {
}

@Test
public void test() {
    assertEquals(15, 15);
}

}

Edit: Sorry In Eclipse window it's called actually a "Failure trace":

java.lang.NoClassDefFoundError: org/hamcrest/SelfDescribing     at
java.lang.ClassLoader.defineClass1(Native Method)   at
java.lang.ClassLoader.defineClass(Unknown Source)   at
java.security.SecureClassLoader.defineClass(Unknown Source)     at
java.net.URLClassLoader.defineClass(Unknown Source)     at
java.net.URLClassLoader.access$100(Unknown Source)  at
java.net.URLClassLoader$1.run(Unknown Source)   at
java.net.URLClassLoader$1.run(Unknown Source)   at
java.security.AccessController.doPrivileged(Native Method)  at
java.net.URLClassLoader.findClass(Unknown Source)   at
java.lang.ClassLoader.loadClass(Unknown Source)     at
sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)  at
java.lang.ClassLoader.loadClass(Unknown Source)     at
org.junit.internal.builders.JUnit4Builder.runnerForClass(JUnit4Builder.java:10)
    at
org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at
org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
    at
org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at
org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:26)
    at
org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.<init>(JUnit4TestReference.java:33)
    at
org.eclipse.jdt.internal.junit4.runner.JUnit4TestClassReference.<init>(JUnit4TestClassReference.java:25)
    at
org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:48)
    at
org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:38)
    at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:452)
    at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: java.lang.ClassNotFoundException:
org.hamcrest.SelfDescribing     at java.net.URLClassLoader$1.run(Unknown
Source)     at java.net.URLClassLoader$1.run(Unknown Source)    at
java.security.AccessController.doPrivileged(Native Method)  at
java.net.URLClassLoader.findClass(Unknown Source)   at
java.lang.ClassLoader.loadClass(Unknown Source)     at
sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)  at
java.lang.ClassLoader.loadClass(Unknown Source)     ... 25 more


问:
How to get OR permissions instead of AND in REST framework
It seems that permission classes are ANDed when REST framework checks permissions. That is every permission class needs to return True for permission to be granted. This makes things like "if you are a superuser, you can access anything, but if you are a regular user you need explicit permissions" a bit hard to implement, you cannot just return False, it will fail the whole stack. Is there a way to maybe short-circuit permissions? Something like "if this permission is granted, stop checking?" or some other way to deal with cases like that?</p>

答:
One way would be to add another permission class which combines existing classes the way you want it, e.g.:</p>

```<code>class IsAdmin(BasePermission):
    """Allow access to admins"""
    def has_object_permission(self, request, view, obj):
        return request.user.is_admin()

class IsOwner(BasePermission):
    """Allow access to owners"""
    def has_object_permission(self, request, view, obj):
        request.user.is_owner(obj)

class IsAdminOrOwner(BasePermission):
    """Allow access to admins and owners"""
    def has_object_permission(*args):
        return (IsAdmin.has_object_permission(*args) or
                IsOwner.has_object_permission(*args))
</code>```

Body:
One way would be to add another permission class which combines existing classes the way you want it, e.g.:

class IsAdmin(BasePermission):
    """Allow access to admins"""
    def has_object_permission(self, request, view, obj):
        return request.user.is_admin()

class IsOwner(BasePermission):
    """Allow access to owners"""
    def has_object_permission(self, request, view, obj):
        request.user.is_owner(obj)

class IsAdminOrOwner(BasePermission):
    """Allow access to admins and owners"""
    def has_object_permission(*args):
        return (IsAdmin.has_object_permission(*args) or
                IsOwner.has_object_permission(*args))


问:
Crashes after startActivityForResult in API 27
After updating to API 27 and Support library 27.0.2 suddenly I get a lot of these stack traces in Crashlytics:

```<code>Fatal Exception: java.lang.IllegalArgumentException
    at android.os.Parcel.readException(Parcel.java:1544)
    at android.os.Parcel.readException(Parcel.java:1493)
    at android.app.ActivityManagerProxy.isTopOfTask(ActivityManagerNative.java:5108)
    at android.app.Activity.isTopOfTask(Activity.java:5688)
    at android.app.Activity.startActivityForResult(Activity.java:3973)
    at android.support.v4.app.BaseFragmentActivityApi16.startActivityForResult(Source:54)
    at android.support.v4.app.FragmentActivity.startActivityForResult(Source:67)
</code>```

I call this like:

```<code>ActivityOptions options = ActivityOptions.makeCustomAnimation(activity, R.anim.slide_in_from_right, R.anim.fade_out);
startActivityForResult( intent, REQ_ACTION, options.toBundle());
</code>```

I cannot read the source code as it is not released yet. I even tried to replace and use android-26 code, but it's different.

There is a warning for the above call saying that BaseFragmentActivityApi16.startActivityForResult can only called from the same library group, so I fixed it by using ActivityCompat, but I don't think it will solve the crash problem.

Is this a platform issue or can I fix this?

Edit

```<code>if (Build.VERSION.SDK_INT >= 21) {
    ActivityOptions options = ActivityOptions.makeCustomAnimation(activity, R.anim.slide_in_from_right, R.anim.fade_out);
    startActivityForResult(intent, REQ_ACTION, options.toBundle());
} else {
    ActivityOptions options = ActivityOptions.makeCustomAnimation(activity, R.anim.slide_in_from_right, R.anim.fade_out);
    ActivityCompat.startActivityForResult(this, intent, REQ_ACTION, options.toBundle());
}
</code>```

If I change it to the above according to the link in my comment, Android Studio complaining like above. This might be related to the problem.

答:
Use ActivityOptionsCompat instead of ActivityOptions for below api 21.

ActivityOptionsCompat is a helper class for accessing features in ActivityOptions in a backwards compatible fashion.

```<code>if (Build.VERSION.SDK_INT >= 21) {
  ActivityOptions options = ActivityOptions.makeCustomAnimation(activity,
  R.anim.slide_in_from_right, R.anim.fade_out);
  startActivityForResult(intent, REQ_ACTION, options.toBundle());
  } else {
   ActivityOptionsCompat options = ActivityOptionsCompat
  .makeCustomAnimation(activity,R.anim.slide_in_from_right,R.anim.fade_out);
   ActivityCompat.startActivity(this, intent, options.toBundle());
}
</code>```

Hope this will help you.

Body:
After updating to API 27 and Support library 27.0.2 suddenly I get a lot of these stack traces in Crashlytics:

Fatal Exception: java.lang.IllegalArgumentException
    at android.os.Parcel.readException(Parcel.java:1544)
    at android.os.Parcel.readException(Parcel.java:1493)
    at android.app.ActivityManagerProxy.isTopOfTask(ActivityManagerNative.java:5108)
    at android.app.Activity.isTopOfTask(Activity.java:5688)
    at android.app.Activity.startActivityForResult(Activity.java:3973)
    at android.support.v4.app.BaseFragmentActivityApi16.startActivityForResult(Source:54)
    at android.support.v4.app.FragmentActivity.startActivityForResult(Source:67)

I call this like:

ActivityOptions options = ActivityOptions.makeCustomAnimation(activity, R.anim.slide_in_from_right, R.anim.fade_out);
startActivityForResult( intent, REQ_ACTION, options.toBundle());

I cannot read the source code as it is not released yet. I even tried to replace and use android-26 code, but it's different.

There is a warning for the above call saying that BaseFragmentActivityApi16.startActivityForResult can only called from the same library group, so I fixed it by using ActivityCompat, but I don't think it will solve the crash problem.

Is this a platform issue or can I fix this?

Edit

if (Build.VERSION.SDK_INT >= 21) {
    ActivityOptions options = ActivityOptions.makeCustomAnimation(activity, R.anim.slide_in_from_right, R.anim.fade_out);
    startActivityForResult(intent, REQ_ACTION, options.toBundle());
} else {
    ActivityOptions options = ActivityOptions.makeCustomAnimation(activity, R.anim.slide_in_from_right, R.anim.fade_out);
    ActivityCompat.startActivityForResult(this, intent, REQ_ACTION, options.toBundle());
}

If I change it to the above according to the link in my comment, Android Studio complaining like above. This might be related to the problem.

Body:
Use ActivityOptionsCompat instead of ActivityOptions for below api 21.

ActivityOptionsCompat is a helper class for accessing features in ActivityOptions in a backwards compatible fashion.

if (Build.VERSION.SDK_INT >= 21) {
  ActivityOptions options = ActivityOptions.makeCustomAnimation(activity,
  R.anim.slide_in_from_right, R.anim.fade_out);
  startActivityForResult(intent, REQ_ACTION, options.toBundle());
  } else {
   ActivityOptionsCompat options = ActivityOptionsCompat
  .makeCustomAnimation(activity,R.anim.slide_in_from_right,R.anim.fade_out);
   ActivityCompat.startActivity(this, intent, options.toBundle());
}

Hope this will help you.


问:
Recursively compute difference between consecutive records within each group
Goodmorning StackOverflow,

I have seen answer to similar question, however, they do not consider the group_ID and are not efficient enough to be run on massive datasets.

I am struggling to find a solution to the following task:
within the consecutive elements of each group_ID, recursively compute the difference with the previous element starting from the second to the last element belonging to that group_ID.

Therefore, considering the following sample data:

```<code>data <- data.frame(time = c(1:3, 1:4),
                   group_ID = c(rep(c("1", "2"), c(3, 4))),
                   value = c(0, 400, 2000, 0, 500, 2000, 2120))
</code>```

The expected result of the solution I am trying to find is:

```<code>solution_df <- data.frame(time = c(1:3, 1:4),
                          group_ID = c(rep(c("1", "2"), c(3, 4))),
                          difference = c(NA, 400, 1600, NA, 500, 1500, 120))
</code>```

It is critical to bear in mind the dataset is massive and the solution must be efficient.

I hope the question was clear, otherwise please ask for further details.

答:
You could use data.table for grouping and diff to calculate the differences.

```<code>library(data.table)
setDT(data)
data[, .(time = time,
  difference = c(NA, diff(value))), by = group_ID]

#   group_ID time difference
#1:        1    1         NA
#2:        1    2        400
#3:        1    3       1600
#4:        2    1         NA
#5:        2    2        500
#6:        2    3       1500
#7:        2    4        120
</code>```

I don't know what is supposed to be recursive here.

Body:
Goodmorning StackOverflow,

I have seen answer to similar question, however, they do not consider the group_ID and are not efficient enough to be run on massive datasets.

I am struggling to find a solution to the following task:
within the consecutive elements of each group_ID, recursively compute the difference with the previous element starting from the second to the last element belonging to that group_ID.

Therefore, considering the following sample data:

data <- data.frame(time = c(1:3, 1:4),
                   group_ID = c(rep(c("1", "2"), c(3, 4))),
                   value = c(0, 400, 2000, 0, 500, 2000, 2120))

The expected result of the solution I am trying to find is:

solution_df <- data.frame(time = c(1:3, 1:4),
                          group_ID = c(rep(c("1", "2"), c(3, 4))),
                          difference = c(NA, 400, 1600, NA, 500, 1500, 120))

It is critical to bear in mind the dataset is massive and the solution must be efficient.

I hope the question was clear, otherwise please ask for further details.

Body:
You could use data.table for grouping and diff to calculate the differences.

library(data.table)
setDT(data)
data[, .(time = time,
  difference = c(NA, diff(value))), by = group_ID]

#   group_ID time difference
#1:        1    1         NA
#2:        1    2        400
#3:        1    3       1600
#4:        2    1         NA
#5:        2    2        500
#6:        2    3       1500
#7:        2    4        120

I don't know what is supposed to be recursive here.


问:
Update PyCharm with new DataGrip
JetBrains has just released new DataGrip 2017.3

I have Professional edition of PyCharm. This includes working with databases (as I understood all the features of DataGrip).

Is it possible to update my Pycharm, so that it also includes new DataGrip?
I see only minor update possible for now.

答: You need PyCharm 2017.3 which was released the 29th of November. I don't know why it doesn't show in the Updates dialog.</p>

Title: Update PyCharm with new DataGrip


问:
Set EXIF DateTaken as file CreationTime
I'm trying to fix metadata of my photos using powershell.
I need to set exif DateTaken as file CreationTime

Here is my code:

```<code>[reflection.assembly]::loadfile( "C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Drawing.dll")
echo "--------"
echo ""
$files = Get-ChildItem E:\Photos\*.*
ForEach ($file in $files) {

        #Get Date
    $foo=New-Object -TypeName system.drawing.bitmap -ArgumentList $file.fullname
    $date = $foo.GetPropertyItem(36867).value[0..9]
    $arYear = [Char]$date[0],[Char]$date[1],[Char]$date[2],[Char]$date[3]
    $arMonth = [Char]$date[5],[Char]$date[6]
    $arDay = [Char]$date[8],[Char]$date[9]
    $strYear = [String]::Join('',$arYear)
    $strMonth = [String]::Join('',$arMonth)
    $strDay = [String]::Join('',$arDay)
    $DateTaken = $strDay + "/" + $strMonth + "/" + $strYear

        # Get Time
    $time = $foo.GetPropertyItem(36867).value[11..18]
    $arHour = [Char]$time[0],[Char]$time[1]
    $arMinute = [Char]$time[3],[Char]$time[4]
    $arSecond = [Char]$time[6],[Char]$time[7]
    $strHour = [String]::Join('',$arHour)
    $strMinute = [String]::Join('',$arMinute)
    $strSecond = [String]::Join('',$arSecond)
    $TimeTaken = $strHour + ":" + $strMinute + ":" + $strSecond

        # Link into one date and time
    $FullDate = $DateTaken + " " + $TimeTaken

    echo "File name"
    echo $file.name
    echo ""
    echo "Wrong data"
    echo (Get-Item $file).creationtime.datetime
    echo ""
    echo "Right data"
    echo $FullDate
    echo ""

        #Set DateTaken as CreationTime
    (Get-Item $file).creationtime= $FullDate

    pause
}
</code>```

I got error "cannot access the file because it is being used by another process".
I have no idea how to fix it.

PS. I'm not sure if $FullDate has right syntax, because I couldn't test it

Thanks

答: Have you tried get rid of the $foo object by calling $foo.dispose()?</p>

Title: Set EXIF DateTaken as file CreationTime

Body:
I'm trying to fix metadata of my photos using powershell.
I need to set exif DateTaken as file CreationTime

Here is my code:

[reflection.assembly]::loadfile( "C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Drawing.dll")
echo "--------"
echo ""
$files = Get-ChildItem E:\Photos\*.*
ForEach ($file in $files) {

        #Get Date
    $foo=New-Object -TypeName system.drawing.bitmap -ArgumentList $file.fullname
    $date = $foo.GetPropertyItem(36867).value[0..9]
    $arYear = [Char]$date[0],[Char]$date[1],[Char]$date[2],[Char]$date[3]
    $arMonth = [Char]$date[5],[Char]$date[6]
    $arDay = [Char]$date[8],[Char]$date[9]
    $strYear = [String]::Join('',$arYear)
    $strMonth = [String]::Join('',$arMonth)
    $strDay = [String]::Join('',$arDay)
    $DateTaken = $strDay + "/" + $strMonth + "/" + $strYear

        # Get Time
    $time = $foo.GetPropertyItem(36867).value[11..18]
    $arHour = [Char]$time[0],[Char]$time[1]
    $arMinute = [Char]$time[3],[Char]$time[4]
    $arSecond = [Char]$time[6],[Char]$time[7]
    $strHour = [String]::Join('',$arHour)
    $strMinute = [String]::Join('',$arMinute)
    $strSecond = [String]::Join('',$arSecond)
    $TimeTaken = $strHour + ":" + $strMinute + ":" + $strSecond

        # Link into one date and time
    $FullDate = $DateTaken + " " + $TimeTaken

    echo "File name"
    echo $file.name
    echo ""
    echo "Wrong data"
    echo (Get-Item $file).creationtime.datetime
    echo ""
    echo "Right data"
    echo $FullDate
    echo ""

        #Set DateTaken as CreationTime
    (Get-Item $file).creationtime= $FullDate

    pause
}

I got error "cannot access the file because it is being used by another process".
I have no idea how to fix it.

PS. I'm not sure if $FullDate has right syntax, because I couldn't test it

Thanks


问:
Gradle flyway script to update multiple databases
I have a Gradle script which uses the flyway plugin to create some database tables, and now I need to update the script so that it can work with 2 separate sets of flyway scripts, each of which updates a separate database.

In the single-database version of the script I simply do this:

```<code>flyway {
    url = 'jdbc:edb://localhost:5432/mydb'
    schemas = ['my_schema']
    user = 'my_user'
    password = 'my_pass'
    locations = ['filesystem:src/main/resources/db/flyway/my_db']
}
</code>```

I've been experimenting with declaring a new task to run the scripts for the second db:

```<code>task flywayMigrate2 << {
    ext {
        flyway {
            url = 'jdbc:edb://localhost:5432/mydb2'
            schemas = ['my_schema2']
            user = 'my_user2'
            password = 'my_pass2'
            locations = ['filesystem:src/main/resources/db/flyway/my_db2']
        }
    }
}

flywayMigrate2.finalizedBy flywayMigrate
</code>```

My Gradle skills are poor, but I know this isn't the right way to do it - my understanding is that the ext block overwrites the original flyway configuration, so if I wanted to run flywayMigrate after flywayMigrate2 it would continue to use the second set of config values rather than reverting to the original set.

I can't be the first person to need to do this, but I'm struggling to find a decent approach, can anyone help?

答:
I don't think that you have to define another Gradle task in order to introduce a second Flyway configuration.

According to the documentation you simply can overwrite either using Gradle properties

```<code>gradle -Pflyway.user=myUsr -Pflyway.schemas=schema1,schema2 -Pflyway.placeholders.keyABC=valXYZ
</code>```

or system properties

```<code>gradle -Dflyway.user=myUser -Dflyway.schemas=schema1,schema2 -Dflyway.placeholders.keyABC=valueXYZ
</code>```

or providing an external Flyway config

```<code>gradle -Dflyway.configFiles=path/to/myAlternativeConfig.conf flywayMigrate
</code>```

The Flyway Gradle plugin follows the following configuration order:

System properties

Environment variables

Custom config files

Gradle properties

Flyway configuration section in build.gradle

<user-home>/flyway.conf

Flyway Gradle plugin defaults

Alternatively you could introduce a new task that overwrites the Gradle properties of Flyway.

```<code>task migrate2(FlywayMigrateTask) {

   project.ext['flyway.user']='myUsr'
   project.ext['flyway.password']='mySecretPwd'
   project.ext['flyway.schemas']='schema1,schema2,schema3'
   project.ext['flyway.placeholders.keyABC']='valueXYZ'
   project.ext['flyway.placeholders.otherplaceholder']='value123'

}
</code>```

Body:
I have a Gradle script which uses the flyway plugin to create some database tables, and now I need to update the script so that it can work with 2 separate sets of flyway scripts, each of which updates a separate database.

In the single-database version of the script I simply do this:

flyway {
    url = 'jdbc:edb://localhost:5432/mydb'
    schemas = ['my_schema']
    user = 'my_user'
    password = 'my_pass'
    locations = ['filesystem:src/main/resources/db/flyway/my_db']
}

I've been experimenting with declaring a new task to run the scripts for the second db:

task flywayMigrate2 << {
    ext {
        flyway {
            url = 'jdbc:edb://localhost:5432/mydb2'
            schemas = ['my_schema2']
            user = 'my_user2'
            password = 'my_pass2'
            locations = ['filesystem:src/main/resources/db/flyway/my_db2']
        }
    }
}

flywayMigrate2.finalizedBy flywayMigrate

My Gradle skills are poor, but I know this isn't the right way to do it - my understanding is that the ext block overwrites the original flyway configuration, so if I wanted to run flywayMigrate after flywayMigrate2 it would continue to use the second set of config values rather than reverting to the original set.

I can't be the first person to need to do this, but I'm struggling to find a decent approach, can anyone help?

Body:
I don't think that you have to define another Gradle task in order to introduce a second Flyway configuration.

According to the documentation you simply can overwrite either using Gradle properties

gradle -Pflyway.user=myUsr -Pflyway.schemas=schema1,schema2 -Pflyway.placeholders.keyABC=valXYZ

or system properties

gradle -Dflyway.user=myUser -Dflyway.schemas=schema1,schema2 -Dflyway.placeholders.keyABC=valueXYZ

or providing an external Flyway config

gradle -Dflyway.configFiles=path/to/myAlternativeConfig.conf flywayMigrate

The Flyway Gradle plugin follows the following configuration order:

System properties

Environment variables

Custom config files

Gradle properties

Flyway configuration section in build.gradle

<user-home>/flyway.conf

Flyway Gradle plugin defaults

Alternatively you could introduce a new task that overwrites the Gradle properties of Flyway.

task migrate2(FlywayMigrateTask) {

   project.ext['flyway.user']='myUsr'
   project.ext['flyway.password']='mySecretPwd'
   project.ext['flyway.schemas']='schema1,schema2,schema3'
   project.ext['flyway.placeholders.keyABC']='valueXYZ'
   project.ext['flyway.placeholders.otherplaceholder']='value123'

}