问:
Handlebars - Expecting 'OPEN_INVERSE_CHAIN', 'INVERSE', 'OPEN_ENDBLOCK', got 'EOF'
I am trying out handlebars and I am using the following simple template for this:

```<code><html>

<head></head>

<body>

    <h1>{{title}}</h1>
    <p>{{body}}</p>

    {{#each list}}
    <ul>
        <li>{{@index}}. {{this}}</li>
    </ul>
    </br>
    {{{htmlTag}}}

    {{#if user.admin}}
    <button class="launch">Launch Spacecraft</button> {{else}}
    <button class="login"> Log in</button>
    {{/if}}
    {{!-- This is a comment --}}

</body>
</html>
</code>```

My app.js looks like the following:

```<code>require('dotenv').config()
const express = require('express')
const logger= require('morgan')
const path = require('path')

const app = express()

app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'hbs')
app.use(logger(process.env.LOG_ENV))

app.get('/', (req, res) => {
    const titel = "This is a titel"
    const body = "Lorem ipsum dolor sit amen ..."
    const list = ['apple', 'banana', 'vegetable']
    const htmlTag = '<h2>This is an unescaped Heading</h2>'
    const user = {
    admin: true
  }
    res.render('index',{titel, body, list, htmlTag, user})
})

// Start Server
const port = process.env.APP_PORT || 8080
const host = process.env.APP_URL || '0.0.0.0'

app.listen(port, host, () => {
    console.log(`Listening on ${host}:${port}/`)
})

module.exports = app
</code>```

When I render the page, I get the following error:

Error: /home/ubuntu/workspace/src/views/index.hbs: Parse error on line
  20:
      ...}}
      -------------------^
      Expecting 'OPEN_INVERSE_CHAIN', 'INVERSE', 'OPEN_ENDBLOCK', got 'EOF'
          at Object.parseError (/home/ubuntu/workspace/node_modules/handlebars/dist/cjs/handlebars/compiler/parser.js:267:19)
          at Object.parse (/home/ubuntu/workspace/node_modules/handlebars/dist/cjs/handlebars/compiler/parser.js:336:30)
          at HandlebarsEnvironment.parse (/home/ubuntu/workspace/node_modules/handlebars/dist/cjs/handlebars/compiler/base.js:46:43)
          at compileInput (/home/ubuntu/workspace/node_modules/handlebars/dist/cjs/handlebars/compiler/compiler.js:514:19)
          at ret (/home/ubuntu/workspace/node_modules/handlebars/dist/cjs/handlebars/compiler/compiler.js:523:18)
          at /home/ubuntu/workspace/node_modules/hbs/lib/hbs.js:63:19
          at tryToString (fs.js:456:3)
          at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:443:12)

Any suggestion what I am doing wrong within my template?

I appreciate your reply!

答:
Error states:

Expecting (...), got EOF

Where:

(...)  is what it can possibly expect

EOF is End of File

What you are missing is closing {{/each}}:

```<code>{{#each list}}
<ul>
    <li>{{@index}}. {{this}}</li>
</ul>
</br>
{{{htmlTag}}} {{#if user.admin}}
<button class="launch">Launch Spacecraft</button> {{else}}
<button class="login"> Log in</button> {{/if}} {{!-- This is a comment --}}
{{/each}} <!-- HERE -->
</code>```

Body:
I am trying out handlebars and I am using the following simple template for this:

{{title}}

{{body}}

    {{#each list}}

{{@index}}. {{this}}

    {{{htmlTag}}}

    {{#if user.admin}}
    <button class="launch">Launch Spacecraft</button> {{else}}
    <button class="login"> Log in</button>
    {{/if}}
    {{!-- This is a comment --}}

My app.js looks like the following:

require('dotenv').config()
const express = require('express')
const logger= require('morgan')
const path = require('path')

const app = express()

app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'hbs')
app.use(logger(process.env.LOG_ENV))

app.get('/', (req, res) => {
    const titel = "This is a titel"
    const body = "Lorem ipsum dolor sit amen ..."
    const list = ['apple', 'banana', 'vegetable']
    const htmlTag = '
This is an unescaped Heading
'
    const user = {
    admin: true
  }
    res.render('index',{titel, body, list, htmlTag, user})
})

// Start Server
const port = process.env.APP_PORT || 8080
const host = process.env.APP_URL || '0.0.0.0'

app.listen(port, host, () => {
    console.log(`Listening on ${host}:${port}/`)
})

module.exports = app

When I render the page, I get the following error:

Error: /home/ubuntu/workspace/src/views/index.hbs: Parse error on line
  20:
      ...}}
      -------------------^
      Expecting 'OPEN_INVERSE_CHAIN', 'INVERSE', 'OPEN_ENDBLOCK', got 'EOF'
          at Object.parseError (/home/ubuntu/workspace/node_modules/handlebars/dist/cjs/handlebars/compiler/parser.js:267:19)
          at Object.parse (/home/ubuntu/workspace/node_modules/handlebars/dist/cjs/handlebars/compiler/parser.js:336:30)
          at HandlebarsEnvironment.parse (/home/ubuntu/workspace/node_modules/handlebars/dist/cjs/handlebars/compiler/base.js:46:43)
          at compileInput (/home/ubuntu/workspace/node_modules/handlebars/dist/cjs/handlebars/compiler/compiler.js:514:19)
          at ret (/home/ubuntu/workspace/node_modules/handlebars/dist/cjs/handlebars/compiler/compiler.js:523:18)
          at /home/ubuntu/workspace/node_modules/hbs/lib/hbs.js:63:19
          at tryToString (fs.js:456:3)
          at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:443:12)

Any suggestion what I am doing wrong within my template?

I appreciate your reply!

Body:
Error states:

Expecting (...), got EOF

Where:

(...)  is what it can possibly expect

EOF is End of File

What you are missing is closing {{/each}}:

{{#each list}}
<ul>
    <li>{{@index}}. {{this}}</li>
</ul>
</br>
{{{htmlTag}}} {{#if user.admin}}
<button class="launch">Launch Spacecraft</button> {{else}}
<button class="login"> Log in</button> {{/if}} {{!-- This is a comment --}}
{{/each}} <!-- HERE -->


来源: stackexchange

答:
The other answer is partially correct because first would return the first element of the group date generated by the grouping on color.

In the question, the max(count) is always at the first position for that particular color, hence the statement :

```<code>df.groupBy(color).agg(first("date").alias(date),max("count")).show();
</code>```

returns correct results.

If your data was like this :

```<code>df.show
// red with highest count is at the bottom of the group
+-----+----------+-----+
|color|      date|count|
+-----+----------+-----+
|  red|2014-05-02|    1|
|  red|2015-04-02|    1|
|  red|2015-04-26|    1|
|  red|2015-09-26|    2|
|  red|2014-05-26|    5|
| blue|2014-05-26|    3|
| blue|2014-06-02|    1|
|brown|2014-07-31|    2|
|green|2014-08-01|    2|
+-----+----------+-----+
</code>```

The query in question would return the first date in the group which corresponds to count 1 :

```<code>df.groupBy($"color").agg( first($"date").as("date") , max("count").as("count") ).show
+-----+----------+-----+
|color|      date|count|
+-----+----------+-----+
|brown|2014-07-31|    2|
|green|2014-08-01|    2|
| blue|2014-05-26|    3|
|  red|2014-05-02|    5|
+-----+----------+-----+
</code>```

Alternatively, you can use window functions here :

```<code>import org.apache.spark.sql.expression.Window

val window = Window.partitionBy($"color").orderBy($"count".desc)

df.withColumn("rn", row_number over window).where($"rn" === 1 ).drop($"rn").show
+-----+----------+-----+
|color|      date|count|
+-----+----------+-----+
|brown|2014-07-31|    2|
|green|2014-08-01|    2|
| blue|2014-05-26|    3|
|  red|2014-05-26|    5|
+-----+----------+-----+
</code>```

ContentLicense: CC BY-SA 3.0

Title: Max count with related values in spark

Body:
I have a dataset having some colors and counts with related dates.

+-----------+----------+-----+
|      color|      Date|count|
+-----------+----------+-----+
|        red|2014-05-26|    5|
|        red|2014-05-02|    1|
|        red|2015-04-02|    1|
|        red|2015-04-26|    1|
|        red|2015-09-26|    2|
|       blue|2014-05-26|    3|
|       blue|2014-06-02|    1|
|      brown|2014-07-31|    2|
|      green|2014-08-01|    2|
+-----------+----------+-----+

I want max count for each colors with related dates. I am using Spark 2.0.2 with Java 8.

when I used max function then it removed date column and when I put date into groupBy then it gives same table as input dataset.

df.groupBy(color).max("count").show();

+-----------+----------+
|color      |max(count)|
+-----------+----------+
|        red|         5|
|       blue|         3|
|      brown|         2|
|      green|         2|
+-----------+----------+

Expected output:

+-----------+----------+----------+
|color      |      date|max(count)|
+-----------+----------+----------+
|        red|2014-05-26|         5|
|       blue|2014-05-26|         3|
|      brown|2014-07-31|         2|
|      green|2014-08-01|         2|
+-----------+----------+----------+

Body:
The other answer is partially correct because first would return the first element of the group date generated by the grouping on color.

In the question, the max(count) is always at the first position for that particular color, hence the statement :

df.groupBy(color).agg(first("date").alias(date),max("count")).show();

returns correct results.

If your data was like this :

df.show
// red with highest count is at the bottom of the group
+-----+----------+-----+
|color|      date|count|
+-----+----------+-----+
|  red|2014-05-02|    1|
|  red|2015-04-02|    1|
|  red|2015-04-26|    1|
|  red|2015-09-26|    2|
|  red|2014-05-26|    5|
| blue|2014-05-26|    3|
| blue|2014-06-02|    1|
|brown|2014-07-31|    2|
|green|2014-08-01|    2|
+-----+----------+-----+

The query in question would return the first date in the group which corresponds to count 1 :

df.groupBy($"color").agg( first($"date").as("date") , max("count").as("count") ).show
+-----+----------+-----+
|color|      date|count|
+-----+----------+-----+
|brown|2014-07-31|    2|
|green|2014-08-01|    2|
| blue|2014-05-26|    3|
|  red|2014-05-02|    5|
+-----+----------+-----+

Alternatively, you can use window functions here :

import org.apache.spark.sql.expression.Window

val window = Window.partitionBy($"color").orderBy($"count".desc)

df.withColumn("rn", row_number over window).where($"rn" === 1 ).drop($"rn").show
+-----+----------+-----+
|color|      date|count|
+-----+----------+-----+
|brown|2014-07-31|    2|
|green|2014-08-01|    2|
| blue|2014-05-26|    3|
|  red|2014-05-26|    5|
+-----+----------+-----+


问:
Styling Custom Checkbox with Image Not Appearing
I'm trying out HTML and CSS and am relatively new to the entire concept. I'm currently working on styling a custom checkbox using an image I made from Photoshop. I am not able to figure out why my image is not appearing when I set it this way.

HTML

```<code><ul id="myUL" class="ulChecklist">
  <form action="/action_page.php">
    <li><input type="checkbox" name="instruction">
      <label for="Step1">Step 1</label>
    </li>
    <li><input type="checkbox" name="instruction">
      <label for="Step2">Step 2</label>
    </li>
    <li><input type="checkbox" name="instruction">
      <label for="Step3">Step 3</label>
    </li>
  </form>
</ul>
</code>```

CSS

```<code>input[type="checkbox"] {
opacity: 0;
}

input[type="checkbox"] + label {
background: url(check.png) left center no-repeat;
}
</code>```

This is the pre-checked image I want to add.

This is the post-checked image I want to add.

As you can see, it isn't appearing.

Is something wrong with the way I write these codes? I've checked the following Lynda course link: https://www.lynda.com/HTML-tutorials/Styling-radio-buttons-check-boxes-images/612196/646907-4.html

But it isn't working out for me. I would greatly appreciate help from people! Thank you for taking your time to answer a noob's question!

答:
Sorry I am not able to view the Lynda course as I am not a member, but will do my best to answer this.

If I were setting up I would make the following changes to your code:

```<code><ul id="myUL" class="ulChecklist">
  <form action="/action_page.php">
    <li><input type="checkbox" name="instruction">
      <label for="Step1">Step 1</label>
         <img src=“./check.png” class=“checkmark-section”>
    </li>
  </form>
</ul>
</code>```

Then in the CSS I would callout the checkmark-section class and add in the click effect image under the pseudo class of focus < This is the css word for clicked.

For example:

.checkmark-section:focus {
       background: url(./checkmark-active)

}

This will mean that once checkmark-active is clicked, it will swap over to show the depressed check mark image instead. I have not tried this out, but that is how I would expect it to work.

All the best,

Dan

Body:
I'm trying out HTML and CSS and am relatively new to the entire concept. I'm currently working on styling a custom checkbox using an image I made from Photoshop. I am not able to figure out why my image is not appearing when I set it this way.

HTML

  <form action="/action_page.php">

<input type="checkbox" name="instruction">
      Step 1

<input type="checkbox" name="instruction">
      Step 2

<input type="checkbox" name="instruction">
      Step 3

  </form>

CSS

input[type="checkbox"] {
opacity: 0;
}

input[type="checkbox"] + label {
background: url(check.png) left center no-repeat;
}

This is the pre-checked image I want to add.

This is the post-checked image I want to add.

As you can see, it isn't appearing.

Is something wrong with the way I write these codes? I've checked the following Lynda course link: https://www.lynda.com/HTML-tutorials/Styling-radio-buttons-check-boxes-images/612196/646907-4.html

But it isn't working out for me. I would greatly appreciate help from people! Thank you for taking your time to answer a noob's question!

Body:
Sorry I am not able to view the Lynda course as I am not a member, but will do my best to answer this.

If I were setting up I would make the following changes to your code:

<ul id="myUL" class="ulChecklist">
  <form action="/action_page.php">
    <li><input type="checkbox" name="instruction">
      <label for="Step1">Step 1</label>
         <img src=“./check.png” class=“checkmark-section”>
    </li>
  </form>
</ul>

Then in the CSS I would callout the checkmark-section class and add in the click effect image under the pseudo class of focus < This is the css word for clicked.

For example:

.checkmark-section:focus {
       background: url(./checkmark-active)

}

This will mean that once checkmark-active is clicked, it will swap over to show the depressed check mark image instead. I have not tried this out, but that is how I would expect it to work.

All the best,

Dan


问:
Error when run android app - ionic
I have a problem when I run the app... I want to test the location with GPS in my android phone but I can`t, ... it´s only that.

this is my ionic info

```<code>cli packages: (/usr/local/lib/node_modules)

    @ionic/cli-utils  : 1.18.0
    ionic (Ionic CLI) : 3.18.0

global packages:

    cordova (Cordova CLI) : 7.1.0

local packages:

    @ionic/app-scripts : 3.1.2
    Cordova Platforms  : android 6.2.3
    Ionic Framework    : ionic-angular 3.9.2

System:

    Node  : v7.0.0
    npm   : 3.10.8
    OS    : macOS Sierra
    Xcode : Xcode 8.3.2 Build version 8E2002

Environment Variables:

    ANDROID_HOME : not set

Misc:

    backend : pro
</code>```

l

```<code>ionic cordova run android --prod
</code>```

This is the error:

Error:

```<code>./src/app/main.ts
Module not found: Error: Can't resolve './app.module.ngfactory' in '/Users/eliascanaza/Documents/www/ionic/yofood/src/app'
resolve './app.module.ngfactory' in '/Users/eliascanaza/Documents/www/ionic/yofood/src/app'
  using description file: /Users/eliascanaza/Documents/www/ionic/yofood/package.json (relative path: ./src/app)
    Field 'browser' doesn't contain a valid alias configuration
  after using description file: /Users/eliascanaza/Documents/www/ionic/yofood/package.json (relative path: ./src/app)
    using description file: /Users/eliascanaza/Documents/www/ionic/yofood/package.json (relative path: ./src/app/app.module.ngfactory)
      no extension
        Field 'browser' doesn't contain a valid alias configuration
        /Users/eliascanaza/Documents/www/ionic/yofood/src/app/app.module.ngfactory doesn't exist
      .ts
        Field 'browser' doesn't contain a valid alias configuration
        /Users/eliascanaza/Documents/www/ionic/yofood/src/app/app.module.ngfactory.ts doesn't exist
      .js
        Field 'browser' doesn't contain a valid alias configuration
        /Users/eliascanaza/Documents/www/ionic/yofood/src/app/app.module.ngfactory.js doesn't exist
      .json
        Field 'browser' doesn't contain a valid alias configuration
        /Users/eliascanaza/Documents/www/ionic/yofood/src/app/app.module.ngfactory.json doesn't exist
      as directory
        /Users/eliascanaza/Documents/www/ionic/yofood/src/app/app.module.ngfactory doesn't exist
[/Users/eliascanaza/Documents/www/ionic/yofood/src/app/app.module.ngfactory]
[/Users/eliascanaza/Documents/www/ionic/yofood/src/app/app.module.ngfactory.ts]
[/Users/eliascanaza/Documents/www/ionic/yofood/src/app/app.module.ngfactory.js]
[/Users/eliascanaza/Documents/www/ionic/yofood/src/app/app.module.ngfactory.json]
[/Users/eliascanaza/Documents/www/ionic/yofood/src/app/app.module.ngfactory]
 @ ./src/app/main.ts 2:0-60
    at new BuildError (/Users/eliascanaza/Documents/www/ionic/yofood/node_modules/@ionic/app-scripts/dist/util/errors.js:16:28)
    at callback (/Users/eliascanaza/Documents/www/ionic/yofood/node_modules/@ionic/app-scripts/dist/webpack.js:121:28)
    at emitRecords.err (/Users/eliascanaza/Documents/www/ionic/yofood/node_modules/webpack/lib/Compiler.js:269:13)
    at Compiler.emitRecords (/Users/eliascanaza/Documents/www/ionic/yofood/node_modules/webpack/lib/Compiler.js:375:38)
    at emitAssets.err (/Users/eliascanaza/Documents/www/ionic/yofood/node_modules/webpack/lib/Compiler.js:262:10)
    at applyPluginsAsyncSeries1.err (/Users/eliascanaza/Documents/www/ionic/yofood/node_modules/webpack/lib/Compiler.js:368:12)
    at next (/Users/eliascanaza/Documents/www/ionic/yofood/node_modules/tapable/lib/Tapable.js:218:11)
    at Compiler.compiler.plugin (/Users/eliascanaza/Documents/www/ionic/yofood/node_modules/webpack/lib/performance/SizeLimitsPlugin.js:99:4)
    at Compiler.applyPluginsAsyncSeries1 (/Users/eliascanaza/Documents/www/ionic/yofood/node_modules/tapable/lib/Tapable.js:222:13)
    at Compiler.afterEmit (/Users/eliascanaza/Documents/www/ionic/yofood/node_modules/webpack/lib/Compiler.js:365:9)
</code>```

app.module.ts, I want to test the location but I can`t, there is the library for location and the service to call the webservice

```<code>import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';

import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { TestPage } from '../pages/test/test';

import { Geolocation } from '@ionic-native/geolocation';

import { MessageServiceProvider } from '../providers/message-service/message-service';

@NgModule({
  declarations: [
    MyApp,
    HomePage,
    TestPage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage,
    TestPage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler},
    MessageServiceProvider,
    Geolocation
  ]
})
export class AppModule {}
</code>```

So, I need your help ... what is the wrong? thanks a lot!

答:
It says that **Error: Can't resolve './app.module.ngfactory' **

1.check your main.ts file it should have import { AppModule } from './app.module'; not something like app.module.ngfactory.

2.Also make sure your app works without errors first using Ionic Serve and check console for any app specific errors.

Title: Error when run android app - ionic

Body:
I have a problem when I run the app... I want to test the location with GPS in my android phone but I can`t, ... it´s only that.

this is my ionic info

cli packages: (/usr/local/lib/node_modules)

    @ionic/cli-utils  : 1.18.0
    ionic (Ionic CLI) : 3.18.0

global packages:

    cordova (Cordova CLI) : 7.1.0

local packages:

    @ionic/app-scripts : 3.1.2
    Cordova Platforms  : android 6.2.3
    Ionic Framework    : ionic-angular 3.9.2

System:

    Node  : v7.0.0
    npm   : 3.10.8
    OS    : macOS Sierra
    Xcode : Xcode 8.3.2 Build version 8E2002

Environment Variables:

    ANDROID_HOME : not set

Misc:

    backend : pro

l

ionic cordova run android --prod

This is the error:

Error:

./src/app/main.ts
Module not found: Error: Can't resolve './app.module.ngfactory' in '/Users/eliascanaza/Documents/www/ionic/yofood/src/app'
resolve './app.module.ngfactory' in '/Users/eliascanaza/Documents/www/ionic/yofood/src/app'
  using description file: /Users/eliascanaza/Documents/www/ionic/yofood/package.json (relative path: ./src/app)
    Field 'browser' doesn't contain a valid alias configuration
  after using description file: /Users/eliascanaza/Documents/www/ionic/yofood/package.json (relative path: ./src/app)
    using description file: /Users/eliascanaza/Documents/www/ionic/yofood/package.json (relative path: ./src/app/app.module.ngfactory)
      no extension
        Field 'browser' doesn't contain a valid alias configuration
        /Users/eliascanaza/Documents/www/ionic/yofood/src/app/app.module.ngfactory doesn't exist
      .ts
        Field 'browser' doesn't contain a valid alias configuration
        /Users/eliascanaza/Documents/www/ionic/yofood/src/app/app.module.ngfactory.ts doesn't exist
      .js
        Field 'browser' doesn't contain a valid alias configuration
        /Users/eliascanaza/Documents/www/ionic/yofood/src/app/app.module.ngfactory.js doesn't exist
      .json
        Field 'browser' doesn't contain a valid alias configuration
        /Users/eliascanaza/Documents/www/ionic/yofood/src/app/app.module.ngfactory.json doesn't exist
      as directory
        /Users/eliascanaza/Documents/www/ionic/yofood/src/app/app.module.ngfactory doesn't exist
[/Users/eliascanaza/Documents/www/ionic/yofood/src/app/app.module.ngfactory]
[/Users/eliascanaza/Documents/www/ionic/yofood/src/app/app.module.ngfactory.ts]
[/Users/eliascanaza/Documents/www/ionic/yofood/src/app/app.module.ngfactory.js]
[/Users/eliascanaza/Documents/www/ionic/yofood/src/app/app.module.ngfactory.json]
[/Users/eliascanaza/Documents/www/ionic/yofood/src/app/app.module.ngfactory]
 @ ./src/app/main.ts 2:0-60
    at new BuildError (/Users/eliascanaza/Documents/www/ionic/yofood/node_modules/@ionic/app-scripts/dist/util/errors.js:16:28)
    at callback (/Users/eliascanaza/Documents/www/ionic/yofood/node_modules/@ionic/app-scripts/dist/webpack.js:121:28)
    at emitRecords.err (/Users/eliascanaza/Documents/www/ionic/yofood/node_modules/webpack/lib/Compiler.js:269:13)
    at Compiler.emitRecords (/Users/eliascanaza/Documents/www/ionic/yofood/node_modules/webpack/lib/Compiler.js:375:38)
    at emitAssets.err (/Users/eliascanaza/Documents/www/ionic/yofood/node_modules/webpack/lib/Compiler.js:262:10)
    at applyPluginsAsyncSeries1.err (/Users/eliascanaza/Documents/www/ionic/yofood/node_modules/webpack/lib/Compiler.js:368:12)
    at next (/Users/eliascanaza/Documents/www/ionic/yofood/node_modules/tapable/lib/Tapable.js:218:11)
    at Compiler.compiler.plugin (/Users/eliascanaza/Documents/www/ionic/yofood/node_modules/webpack/lib/performance/SizeLimitsPlugin.js:99:4)
    at Compiler.applyPluginsAsyncSeries1 (/Users/eliascanaza/Documents/www/ionic/yofood/node_modules/tapable/lib/Tapable.js:222:13)
    at Compiler.afterEmit (/Users/eliascanaza/Documents/www/ionic/yofood/node_modules/webpack/lib/Compiler.js:365:9)

app.module.ts, I want to test the location but I can`t, there is the library for location and the service to call the webservice

import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';

import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { TestPage } from '../pages/test/test';

import { Geolocation } from '@ionic-native/geolocation';

import { MessageServiceProvider } from '../providers/message-service/message-service';

@NgModule({
  declarations: [
    MyApp,
    HomePage,
    TestPage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage,
    TestPage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler},
    MessageServiceProvider,
    Geolocation
  ]
})
export class AppModule {}

So, I need your help ... what is the wrong? thanks a lot!


问:
How to get the MethodInfo of a Java 8 method reference?
Please have a look at the following code:

```<code>Method methodInfo = MyClass.class.getMethod("myMethod");
</code>```

This works, but the method name is passed as a string, so this will compile even if myMethod does not exist.

On the other hand, Java 8 introduces a method reference feature. It is checked at compile time. It is possible to use this feature to get method info?

```<code>printMethodName(MyClass::myMethod);
</code>```

Full example:

```<code>@FunctionalInterface
private interface Action {

    void invoke();
}

private static class MyClass {

    public static void myMethod() {
    }
}

private static void printMethodName(Action action) {
}

public static void main(String[] args) throws NoSuchMethodException {
    // This works, but method name is passed as a string, so this will compile
    // even if myMethod does not exist
    Method methodInfo = MyClass.class.getMethod("myMethod");

    // Here we pass reference to a method. It is somehow possible to
    // obtain java.lang.reflect.Method for myMethod inside printMethodName?
    printMethodName(MyClass::myMethod);
}
</code>```

In other words I would like to have a code which is the equivalent of the following C# code:

```<code>    private static class InnerClass
    {
        public static void MyMethod()
        {
            Console.WriteLine("Hello");
        }
    }

    static void PrintMethodName(Action action)
    {
        // Can I get java.lang.reflect.Method in the same way?
        MethodInfo methodInfo = action.GetMethodInfo();
    }

    static void Main()
    {
        PrintMethodName(InnerClass.MyMethod);
    }
</code>```

答:
We have published the small library reflection-util that can be used to capture a method name.

Example:

```<code>class MyClass {

    private int value;

    public void myMethod() {
    }

    public int getValue() {
        return value;
    }

}

String methodName = ClassUtils.getMethodName(MyClass.class, MyClass::myMethod);
System.out.println(methodName); // prints "myMethod"

String getterName = ClassUtils.getMethodName(MyClass.class, MyClass::getValue);
System.out.println(getterName); // prints "getValue"
</code>```

Implementation details: A Proxy subclass of MyClass is created with ByteBuddy and a call to the method is captured to retrieve its name.
ClassUtils caches the information such that we do not need to create a new proxy on every invocation.

Please note that this approach is no silver bullet and there are some known cases that don’t work:

It doesn’t work for static methods.

It doesn’t work if the class is final.

We currently do not support all potential method signatures. It should work for methods that do not take an argument such as a getter method.

Body:
Please have a look at the following code:

Method methodInfo = MyClass.class.getMethod("myMethod");

This works, but the method name is passed as a string, so this will compile even if myMethod does not exist.

On the other hand, Java 8 introduces a method reference feature. It is checked at compile time. It is possible to use this feature to get method info?

printMethodName(MyClass::myMethod);

Full example:

@FunctionalInterface
private interface Action {

    void invoke();
}

private static class MyClass {

    public static void myMethod() {
    }
}

private static void printMethodName(Action action) {
}

public static void main(String[] args) throws NoSuchMethodException {
    // This works, but method name is passed as a string, so this will compile
    // even if myMethod does not exist
    Method methodInfo = MyClass.class.getMethod("myMethod");

    // Here we pass reference to a method. It is somehow possible to
    // obtain java.lang.reflect.Method for myMethod inside printMethodName?
    printMethodName(MyClass::myMethod);
}

In other words I would like to have a code which is the equivalent of the following C# code:

    private static class InnerClass
    {
        public static void MyMethod()
        {
            Console.WriteLine("Hello");
        }
    }

    static void PrintMethodName(Action action)
    {
        // Can I get java.lang.reflect.Method in the same way?
        MethodInfo methodInfo = action.GetMethodInfo();
    }

    static void Main()
    {
        PrintMethodName(InnerClass.MyMethod);
    }

Body:
We have published the small library reflection-util that can be used to capture a method name.

Example:

class MyClass {

    private int value;

    public void myMethod() {
    }

    public int getValue() {
        return value;
    }

}

String methodName = ClassUtils.getMethodName(MyClass.class, MyClass::myMethod);
System.out.println(methodName); // prints "myMethod"

String getterName = ClassUtils.getMethodName(MyClass.class, MyClass::getValue);
System.out.println(getterName); // prints "getValue"

Implementation details: A Proxy subclass of MyClass is created with ByteBuddy and a call to the method is captured to retrieve its name.
ClassUtils caches the information such that we do not need to create a new proxy on every invocation.

Please note that this approach is no silver bullet and there are some known cases that don’t work:

It doesn’t work for static methods.

It doesn’t work if the class is final.

We currently do not support all potential method signatures. It should work for methods that do not take an argument such as a getter method.

ContentLicense: CC BY-SA 4.0


问:
Ionic Serve Not Serving
When I run ionic serve, it builds the app but the server isn't run. Here's the trail:

```<code>    Starting app-scripts server: --address 0.0.0.0 --port 8100 --livereload-port 35729
--dev-logger-port 53703 --nobrowser - Ctrl+C to cancel
[17:55:35]  watch started ...
[17:55:35]  build dev started ...
[17:55:36]  clean started ...
[17:55:36]  clean finished in 2 ms
[17:55:36]  copy started ...
[17:55:36]  deeplinks started ...
[17:55:37]  deeplinks finished in 589 ms
[17:55:37]  transpile started ...
[17:55:44]  transpile finished in 7.38 s
[17:55:44]  preprocess started ...
[17:55:44]  copy finished in 8.56 s
[17:55:44]  preprocess finished in 206 ms
[17:55:44]  webpack started ...
</code>```

After webpack started the cli just exits and i see the normal terminal prompt.

Trying out the npm run ionic:serve command instead results into this error:

```<code>TypeError: Cannot read property 'substr' of undefined
</code>```

So far I've re-installed ionic, same result. A bit unsure how to deal with this one...

答:
It turns out that this is caused when creating multiple component classes in one ts file. Splitting those classes each into their own file solves the problem.

Related to this https://github.com/ionic-team/ionic-app-scripts/issues/796

Title: Ionic Serve Not Serving

Body:
When I run ionic serve, it builds the app but the server isn't run. Here's the trail:

    Starting app-scripts server: --address 0.0.0.0 --port 8100 --livereload-port 35729
--dev-logger-port 53703 --nobrowser - Ctrl+C to cancel
[17:55:35]  watch started ...
[17:55:35]  build dev started ...
[17:55:36]  clean started ...
[17:55:36]  clean finished in 2 ms
[17:55:36]  copy started ...
[17:55:36]  deeplinks started ...
[17:55:37]  deeplinks finished in 589 ms
[17:55:37]  transpile started ...
[17:55:44]  transpile finished in 7.38 s
[17:55:44]  preprocess started ...
[17:55:44]  copy finished in 8.56 s
[17:55:44]  preprocess finished in 206 ms
[17:55:44]  webpack started ...

After webpack started the cli just exits and i see the normal terminal prompt.

Trying out the npm run ionic:serve command instead results into this error:

TypeError: Cannot read property 'substr' of undefined

So far I've re-installed ionic, same result. A bit unsure how to deal with this one...


答:
You are on the right path. Just that you need to resize the background image and float it to the left. And one of the most important part is to associate the label with the input checkbox with for and id:

input[type="checkbox"] {
opacity: 0;
}

input[type="checkbox"] + label {
background: url(http://www.iconarchive.com/download/i86039/graphicloads/100-flat-2/check-1.ico) left center no-repeat;
float: left;
padding-left: 25px; /*image width plus extra padding */
background-size: 20px 20px;
}

input[type="checkbox"]:checked + label {
background: url(https://d30y9cdsu7xlg0.cloudfront.net/png/2181-200.png) left center no-repeat;
float: left;
padding-left: 25px; /*image width plus extra padding */
background-size: 20px 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul id="myUL" class="ulChecklist">
  <form action="/action_page.php">
    <li><input id="Step1" type="checkbox" name="instruction">
      <label for="Step1">Step 1</label>
    </li>
    <li><input id="Step2" type="checkbox" name="instruction">
      <label for="Step2">Step 2</label>
    </li>
    <li><input id="Step3" type="checkbox" name="instruction">
      <label for="Step3">Step 3</label>
    </li>
  </form>
</ul></code>```

Title: Styling Custom Checkbox with Image Not Appearing

Body:
You are on the right path. Just that you need to resize the background image and float it to the left. And one of the most important part is to associate the label with the input checkbox with for and id:

input[type="checkbox"] {
opacity: 0;
}

input[type="checkbox"] + label {
background: url(http://www.iconarchive.com/download/i86039/graphicloads/100-flat-2/check-1.ico) left center no-repeat;
float: left;
padding-left: 25px; /*image width plus extra padding */
background-size: 20px 20px;
}

input[type="checkbox"]:checked + label {
background: url(https://d30y9cdsu7xlg0.cloudfront.net/png/2181-200.png) left center no-repeat;
float: left;
padding-left: 25px; /*image width plus extra padding */
background-size: 20px 20px;
}

<ul id="myUL" class="ulChecklist">
  <form action="/action_page.php">
    <li><input id="Step1" type="checkbox" name="instruction">
      <label for="Step1">Step 1</label>
    </li>
    <li><input id="Step2" type="checkbox" name="instruction">
      <label for="Step2">Step 2</label>
    </li>
    <li><input id="Step3" type="checkbox" name="instruction">
      <label for="Step3">Step 3</label>
    </li>
  </form>
</ul>


答:
The code you have provided makes no provision for the background label image when the adjacent sibling pseudo-state is :checked.

You'll need to account for both states, e.g: input[type="checkbox"] & input[type="checkbox"]:checked

```<code>input[type="checkbox"] + label {
background: url(check.png) left center no-repeat;
}

input[type="checkbox"]:checked + label {
background: url(check-alt.png) left center no-repeat;
}
</code>```

Edit

You may also need to declare background size properties.

Body:
The code you have provided makes no provision for the background label image when the adjacent sibling pseudo-state is :checked.

You'll need to account for both states, e.g: input[type="checkbox"] & input[type="checkbox"]:checked

input[type="checkbox"] + label {
background: url(check.png) left center no-repeat;
}

input[type="checkbox"]:checked + label {
background: url(check-alt.png) left center no-repeat;
}

Edit

You may also need to declare background size properties.


问:
How to access file in parent directory using python?
I am trying to access a text file in the parent directory,

Eg : python script is in codeSrc & the text file is in mainFolder.

script path:

```<code>G:\mainFolder\codeSrc\fun.py
</code>```

desired file path:

```<code>G:\mainFolder\foo.txt
</code>```

I am currently using this syntax with python 2.7x,

```<code>import os
filename = os.path.dirname(os.getcwd())+"\\foo.txt"
</code>```

Although this works fine, is there a better (prettier :P) way to do this?

答:
While your example works, it is maybe not the nicest, neither is mine, probably. Anyhow, os.path.dirname() is probably meant for strings where the final part is already a filename. It uses os.path.split(), which provides an empty string if the path end with a slash. So this potentially can go wrong. Moreover, as you are already using os.path, I'd also use it to join paths, which then becomes even platform independent. I'd write

```<code>os.path.join( os.getcwd(), '..', 'foo.txt' )
</code>```

...and concerning the readability of the code, here (as in the post using the environ module) it becomes evident immediately that you go one level up.

Body:
I am trying to access a text file in the parent directory,

Eg : python script is in codeSrc & the text file is in mainFolder.

script path:

G:\mainFolder\codeSrc\fun.py

desired file path:

G:\mainFolder\foo.txt

I am currently using this syntax with python 2.7x,

import os
filename = os.path.dirname(os.getcwd())+"\\foo.txt"

Although this works fine, is there a better (prettier :P) way to do this?

Body:
While your example works, it is maybe not the nicest, neither is mine, probably. Anyhow, os.path.dirname() is probably meant for strings where the final part is already a filename. It uses os.path.split(), which provides an empty string if the path end with a slash. So this potentially can go wrong. Moreover, as you are already using os.path, I'd also use it to join paths, which then becomes even platform independent. I'd write

os.path.join( os.getcwd(), '..', 'foo.txt' )

...and concerning the readability of the code, here (as in the post using the environ module) it becomes evident immediately that you go one level up.


问:
Repeating a value when a previous variable value has occured
I have a data set with the following variables:
1. Group
2. Status (Takes on variables 1-7)

I need to create a flag where the following conditions are met:
-Flag 1=0 when Status <6, else Flag 1= 1 when Status >=6
-Within each group: If Status has reached 6 or higher and goes back down to below 6, the flag 1 must remain as 1.

The desired table would look as follows:

Body:
data.table and cummax do the job:

library(data.table)
dt <- data.table(Group = c(1,2,2,3,3,3,3,4,4),
                 Status = c(1,2,3,7,6,5,4,5,6))
dt[, flag := cummax(Status >= 6), by = Group]
dt

  Group Status flag
1:     1      1    0
2:     2      2    0
3:     2      3    0
4:     3      7    1
5:     3      6    1
6:     3      5    1
7:     3      4    1
8:     4      5    0
9:     4      6    1


问:
How do I limit the number of times a key can pressed before having no response in TKinter?
So I was working on some TKinter GUI code and I wanted to limit the keybind to the space bar so that it could only be pressed twenty times before becoming un-usable. How do I implement this(In general)?</p>

答:
As Bryan mentions in comment, one example would be:

```<code>import tkinter as tk

root = tk.Tk()

c = 0

def space_event(event):
    global c
    if c < 20:
        print(c)
        c += 1

root.bind("<space>", space_event)

root.mainloop()
</code>```

the above code was bugging me as it still runs the event function after 20 is reached, just not doing anything after that. Instead learning from this I'd rather use below code, as this makes the space key no longer binded after c >= 20:

```<code>import tkinter as tk

root = tk.Tk()

c = 0

def space_event(event):
    global c

    print(c)
    c += 1

    if c >= 20:
        root.unbind("<space>")

root.bind("<space>", space_event)

root.mainloop()
</code>```

Body:
As Bryan mentions in comment, one example would be:

import tkinter as tk

root = tk.Tk()

c = 0

def space_event(event):
    global c
    if c < 20:
        print(c)
        c += 1

root.bind("<space>", space_event)

root.mainloop()

the above code was bugging me as it still runs the event function after 20 is reached, just not doing anything after that. Instead learning from this I'd rather use below code, as this makes the space key no longer binded after c >= 20:

import tkinter as tk

root = tk.Tk()

c = 0

def space_event(event):
    global c

    print(c)
    c += 1

    if c >= 20:
        root.unbind("<space>")

root.bind("<space>", space_event)

root.mainloop()


问:
parquet.io.ParquetDecodingException: Can not read value at 0 in block -1 in file
I have saved a remote DB table in Hive using saveAsTable method, now when i try to access the Hive table data using CLI command select * from table_name, It's giving me the error below:

```<code>2016-06-15 10:49:36,866 WARN  [HiveServer2-Handler-Pool: Thread-96]:
thrift.ThriftCLIService (ThriftCLIService.java:FetchResults(681)) -
Error fetching results: org.apache.hive.service.cli.HiveSQLException:
java.io.IOException: parquet.io.ParquetDecodingException: Can not read
value at 0 in block -1 in file hdfs:
</code>```

Any idea what I might be doing wrong here?

答:
It looks like a schema mismatch problem here.
If you set your schema to be not nullable, and create your dataframe with None value, Spark would throw you ValueError: This field is not nullable, but got None error.

[Pyspark]

```<code>from pyspark.sql.functions import * #udf, concat, col, lit, ltrim, rtrim
from pyspark.sql.types import *

schema = ArrayType(StructType([StructField('A', IntegerType(), nullable=False)]))
# It will throw "ValueError".
df = spark.createDataFrame([[[None]],[[2]]],schema=schema)
df.show()
</code>```

But it is not the case if you use udf.

Using the same schema, if you use udf for transformation, it won't throw you ValueError even if your udf return a None. And it is the place where data schema mismatch happens.

For example:

```<code>df = spark.createDataFrame([[[1]],[[2]]], schema=schema)

def throw_none():
    def _throw_none(x):
        if x[0][0] == 1:
            return [['I AM ONE']]
        else:
            return x
    return udf(_throw_none, schema)

# since value col only accept intergerType, it will throw null for
# string "I AM ONE" in the first row. But spark did not throw ValueError
# error this time ! This is where data schema type mismatch happen !
df = df.select(throw_none()(col("value")).name('value'))
df.show()
</code>```

Then, the following parquet write and read will throw you the parquet.io.ParquetDecodingException error.

```<code>df.write.parquet("tmp")
spark.read.parquet("tmp").collect()
</code>```

So be very careful on the null value if you are using udf, return the right data type in your udf. And unless it is unnecessary, please dont set nullable=False in your StructField. Set nullable=True will solve all the problem.

Body:
I have saved a remote DB table in Hive using saveAsTable method, now when i try to access the Hive table data using CLI command select * from table_name, It's giving me the error below:

2016-06-15 10:49:36,866 WARN  [HiveServer2-Handler-Pool: Thread-96]:
thrift.ThriftCLIService (ThriftCLIService.java:FetchResults(681)) -
Error fetching results: org.apache.hive.service.cli.HiveSQLException:
java.io.IOException: parquet.io.ParquetDecodingException: Can not read
value at 0 in block -1 in file hdfs:

Any idea what I might be doing wrong here?

Body:
It looks like a schema mismatch problem here.
If you set your schema to be not nullable, and create your dataframe with None value, Spark would throw you ValueError: This field is not nullable, but got None error.

[Pyspark]

from pyspark.sql.functions import * #udf, concat, col, lit, ltrim, rtrim
from pyspark.sql.types import *

schema = ArrayType(StructType([StructField('A', IntegerType(), nullable=False)]))
# It will throw "ValueError".
df = spark.createDataFrame([[[None]],[[2]]],schema=schema)
df.show()

But it is not the case if you use udf.

Using the same schema, if you use udf for transformation, it won't throw you ValueError even if your udf return a None. And it is the place where data schema mismatch happens.

For example:

df = spark.createDataFrame([[[1]],[[2]]], schema=schema)

def throw_none():
    def _throw_none(x):
        if x[0][0] == 1:
            return [['I AM ONE']]
        else:
            return x
    return udf(_throw_none, schema)

# since value col only accept intergerType, it will throw null for
# string "I AM ONE" in the first row. But spark did not throw ValueError
# error this time ! This is where data schema type mismatch happen !
df = df.select(throw_none()(col("value")).name('value'))
df.show()

Then, the following parquet write and read will throw you the parquet.io.ParquetDecodingException error.

df.write.parquet("tmp")
spark.read.parquet("tmp").collect()

So be very careful on the null value if you are using udf, return the right data type in your udf. And unless it is unnecessary, please dont set nullable=False in your StructField. Set nullable=True will solve all the problem.


问:
Notifying child components which is active one
Is there a better way to do the following? The following is spinning the CPU in Chrome (as per Javascript profiler).

```<code><div *ngFor="let item of items">
    <itemComp [item]="item" [active]="item == service.activeItem"></itemComp>
</div>
</code>```

Is there a way for each of the itemComp components to subscribe for a notification when they become active?

For ex., once they are rendered, let's say the user clicks on any of the items to mark as active. Only one item can be active any time. and say, I want to just change the background color of the active item to highlight it. In this case the current active item becomes inactive and a new item becomes active. How do I propagate this change?

答:
Is there a way for each of the itemComp components to subscribe for a notification when they become active?

Do you mean when they get rendered the first time? If itemComp is your component, you can implement one of angulars lifecycle-hooks like ngOnInit and run your code there.

Edit: You could add a click event to each item with a function that:

```<code><div *ngFor="let item of items">
    <itemComp [item]="item" [active]="item == service.activeItem" (click)="activateItem(item)"></itemComp>
</div>
</code>```

makes all items inactive

makes the clicked item active

Body:
Is there a better way to do the following? The following is spinning the CPU in Chrome (as per Javascript profiler).

    <itemComp [item]="item" [active]="item == service.activeItem"></itemComp>

Is there a way for each of the itemComp components to subscribe for a notification when they become active?

For ex., once they are rendered, let's say the user clicks on any of the items to mark as active. Only one item can be active any time. and say, I want to just change the background color of the active item to highlight it. In this case the current active item becomes inactive and a new item becomes active. How do I propagate this change?

Body:
Is there a way for each of the itemComp components to subscribe for a notification when they become active?

Do you mean when they get rendered the first time? If itemComp is your component, you can implement one of angulars lifecycle-hooks like ngOnInit and run your code there.

Edit: You could add a click event to each item with a function that:

<div *ngFor="let item of items">
    <itemComp [item]="item" [active]="item == service.activeItem" (click)="activateItem(item)"></itemComp>
</div>

makes all items inactive

makes the clicked item active


问:
Laravel DB log time metrics
In Laravel there is an option to enable db query logging. In array it returns query, bindings and time. Question is is time in microseconds?</p>

答: For view all metrics query I use this lib  barryvdh/laravel-debugbar in Dev mode.</p>

Title: Laravel DB log time metrics


问:
how to call sinon stub yieldsTo a function depending on arguments
I am using sinonjs to test my ajax application.

```<code>sinon.stub($, 'ajax').yieldsTo('success',
{
    msgtype: 'success',
    state: 'loggedin'
});
</code>```

My problem is: Based on URL in AJAX I want to send arguments differently. How can I achieve that?

If url to $.ajax is: /login then argument to 'success' should be  {state: 'loggedin'}

If url to $.ajax is: /getemail then argument to 'success' should be  {email: 'test@test.com'}

------------EDIT--------------

my ajax arguments are
{url: '/login', type: "POST", data: request_data, success: function(data){}}

ajaxStub.withArgs({url:'/login'}) is not working.

答:
You can use withArgs with sinon.match.
For example:

```<code>ajaxStub = sinon.stub(jQuery, 'ajax');
ajaxStub.withArgs(sinon.match({ url: 'https://some_url'})).yieldsToAsync('success', responseData);
</code>```

Body:
I am using sinonjs to test my ajax application.

sinon.stub($, 'ajax').yieldsTo('success',
{
    msgtype: 'success',
    state: 'loggedin'
});

My problem is: Based on URL in AJAX I want to send arguments differently. How can I achieve that?

If url to $.ajax is: /login then argument to 'success' should be  {state: 'loggedin'}

If url to $.ajax is: /getemail then argument to 'success' should be  {email: 'test@test.com'}

------------EDIT--------------

my ajax arguments are
{url: '/login', type: "POST", data: request_data, success: function(data){}}

ajaxStub.withArgs({url:'/login'}) is not working.

Body:
You can use withArgs with sinon.match.
For example:

ajaxStub = sinon.stub(jQuery, 'ajax');
ajaxStub.withArgs(sinon.match({ url: 'https://some_url'})).yieldsToAsync('success', responseData);


问:
want to separate frontend and backend user in yii2
as there is only user table in yii2 advanced. so user can login to both frontend and backend with same credential . we want saperate it out.

so I created frontuser table ,with same structure as of user table.
then created its model using gii model generator

made it as common model/user.

here is frontend/model/frontuser

```<code><?php

namespace frontend\models;

use Yii;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;

/**
 * This is the model class for table "frontuser".
 *
 * @property integer $id
 * @property string $username
 * @property string $auth_key
 * @property string $password_hash
 * @property string $password_reset_token
 * @property string $email
 * @property integer $status
 * @property integer $created_at
 * @property integer $updated_at
 */
//class Frontuser extends \yii\db\ActiveRecord
class Frontuser extends ActiveRecord implements IdentityInterface
{
    /**
     * @inheritdoc
     */
    const STATUS_DELETED = 0;
    const STATUS_ACTIVE = 10;
    public static function tableName()
    {
       return '{{%frontuser}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
       return [
            ['status', 'default', 'value' => self::STATUS_ACTIVE],
            ['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]],
        ];
    }

    /**
     *  inheritdoc
     */
    public static function findIdentity($id)
    {
        return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
    }

    /**
     * @inheritdoc
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
    }

    /**
     * Finds user by username
     *
     * @param string $username
     * @return static|null
     */
    public static function findByUsername($username)
    {
        return static::findOne(['username' => $username, 'status' => self::STATUS_ACTIVE]);
    }

    /**
     * Finds user by password reset token
     *
     * @param string $token password reset token
     * @return static|null
     */
    public static function findByPasswordResetToken($token)
    {
        if (!static::isPasswordResetTokenValid($token)) {
            return null;
        }

        return static::findOne([
            'password_reset_token' => $token,
            'status' => self::STATUS_ACTIVE,
        ]);
    }

    /**
     * Finds out if password reset token is valid
     *
     * @param string $token password reset token
     * @return bool
     */
    public static function isPasswordResetTokenValid($token)
    {
        if (empty($token)) {
            return false;
        }

        $timestamp = (int) substr($token, strrpos($token, '_') + 1);
        $expire = Yii::$app->params['user.passwordResetTokenExpire'];
        return $timestamp + $expire >= time();
    }

    /**
     * @inheritdoc
     */
    public function getId()
    {
        return $this->getPrimaryKey();
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey()
    {
        return $this->auth_key;
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
    }

    /**
     * Validates password
     *
     * @param string $password password to validate
     * @return bool if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        return Yii::$app->security->validatePassword($password, $this->password_hash);
    }

    /**
     * Generates password hash from password and sets it to the model
     *
     * @param string $password
     */
    public function setPassword($password)
    {
        $this->password_hash = Yii::$app->security->generatePasswordHash($password);
    }

    /**
     * Generates "remember me" authentication key
     */
    public function generateAuthKey()
    {
        $this->auth_key = Yii::$app->security->generateRandomString();
    }

    /**
     * Generates new password reset token
     */
    public function generatePasswordResetToken()
    {
        $this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
    }

    /**
     * Removes password reset token
     */
    public function removePasswordResetToken()
    {
        $this->password_reset_token = null;
    }
}
</code>```

and in frontend/config/main.php

```<code><?php
$params = array_merge(
    require(__DIR__ . '/../../common/config/params.php'),
    require(__DIR__ . '/../../common/config/params-local.php'),
    require(__DIR__ . '/params.php'),
    require(__DIR__ . '/params-local.php')
);

return [
    'id' => 'app-frontend',
    'basePath' => dirname(__DIR__),
    'bootstrap' => ['log'],
    'controllerNamespace' => 'frontend\controllers',
    'components' => [
        'request' => [
            'csrfParam' => '_csrf-frontend',
        ],
        // 'user' => [
        //     'identityClass' => 'common\models\User',
        //     'enableAutoLogin' => true,
        //     'identityCookie' => ['name' => '_identity-frontend', 'httpOnly' => true],
        // ],
        'user' => [
                'class' => 'yii\web\User', // basic class
                'identityClass' => 'frontend\models\Frontuser', // your admin model
                'enableAutoLogin' => true,
                'loginUrl' => '/admin/frontend/login',
            ],
        'session' => [
            // this is the name of the session cookie used for login on the frontend
            'name' => 'advanced-frontend',
        ],
        'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],
                ],
            ],
        ],
        'authManager' => [
            'class' => 'yii\rbac\DbManager', // or use 'yii\rbac\DbManager'
            'defaultRoles'=> ['guest'],
            ],
        'errorHandler' => [
            'errorAction' => 'site/error',
        ],
        /*
        'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'rules' => [
            ],
        ],
        */
    ],
    'params' => $params,
];
</code>```

but still ,I sign up ,entry goes in user table ..
I want to use user table for backend user
and frontuser table for frontend user
how to do it?

答: You should check what form model is used in sign up action. Probably it is frontend\models\SignupForm. And SignupForm uses common\models\User as user model. You should change it to frontend\models\Frontuser. So check login, logout, signup, reset password actions. Change model to frontend\models\Frontuser everyware in frontend.

Body:
as there is only user table in yii2 advanced. so user can login to both frontend and backend with same credential . we want saperate it out.

so I created frontuser table ,with same structure as of user table.
then created its model using gii model generator

made it as common model/user.

here is frontend/model/frontuser

<?php

namespace frontend\models;

use Yii;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;

/**
 * This is the model class for table "frontuser".
 *
 * @property integer $id
 * @property string $username
 * @property string $auth_key
 * @property string $password_hash
 * @property string $password_reset_token
 * @property string $email
 * @property integer $status
 * @property integer $created_at
 * @property integer $updated_at
 */
//class Frontuser extends \yii\db\ActiveRecord
class Frontuser extends ActiveRecord implements IdentityInterface
{
    /**
     * @inheritdoc
     */
    const STATUS_DELETED = 0;
    const STATUS_ACTIVE = 10;
    public static function tableName()
    {
       return '{{%frontuser}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
       return [
            ['status', 'default', 'value' => self::STATUS_ACTIVE],
            ['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]],
        ];
    }

    /**
     *  inheritdoc
     */
    public static function findIdentity($id)
    {
        return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
    }

    /**
     * @inheritdoc
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
    }

    /**
     * Finds user by username
     *
     * @param string $username
     * @return static|null
     */
    public static function findByUsername($username)
    {
        return static::findOne(['username' => $username, 'status' => self::STATUS_ACTIVE]);
    }

    /**
     * Finds user by password reset token
     *
     * @param string $token password reset token
     * @return static|null
     */
    public static function findByPasswordResetToken($token)
    {
        if (!static::isPasswordResetTokenValid($token)) {
            return null;
        }

        return static::findOne([
            'password_reset_token' => $token,
            'status' => self::STATUS_ACTIVE,
        ]);
    }

    /**
     * Finds out if password reset token is valid
     *
     * @param string $token password reset token
     * @return bool
     */
    public static function isPasswordResetTokenValid($token)
    {
        if (empty($token)) {
            return false;
        }

        $timestamp = (int) substr($token, strrpos($token, '_') + 1);
        $expire = Yii::$app->params['user.passwordResetTokenExpire'];
        return $timestamp + $expire >= time();
    }

    /**
     * @inheritdoc
     */
    public function getId()
    {
        return $this->getPrimaryKey();
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey()
    {
        return $this->auth_key;
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
    }

    /**
     * Validates password
     *
     * @param string $password password to validate
     * @return bool if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        return Yii::$app->security->validatePassword($password, $this->password_hash);
    }

    /**
     * Generates password hash from password and sets it to the model
     *
     * @param string $password
     */
    public function setPassword($password)
    {
        $this->password_hash = Yii::$app->security->generatePasswordHash($password);
    }

    /**
     * Generates "remember me" authentication key
     */
    public function generateAuthKey()
    {
        $this->auth_key = Yii::$app->security->generateRandomString();
    }

    /**
     * Generates new password reset token
     */
    public function generatePasswordResetToken()
    {
        $this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
    }

    /**
     * Removes password reset token
     */
    public function removePasswordResetToken()
    {
        $this->password_reset_token = null;
    }
}

and in frontend/config/main.php

<?php
$params = array_merge(
    require(__DIR__ . '/../../common/config/params.php'),
    require(__DIR__ . '/../../common/config/params-local.php'),
    require(__DIR__ . '/params.php'),
    require(__DIR__ . '/params-local.php')
);

return [
    'id' => 'app-frontend',
    'basePath' => dirname(__DIR__),
    'bootstrap' => ['log'],
    'controllerNamespace' => 'frontend\controllers',
    'components' => [
        'request' => [
            'csrfParam' => '_csrf-frontend',
        ],
        // 'user' => [
        //     'identityClass' => 'common\models\User',
        //     'enableAutoLogin' => true,
        //     'identityCookie' => ['name' => '_identity-frontend', 'httpOnly' => true],
        // ],
        'user' => [
                'class' => 'yii\web\User', // basic class
                'identityClass' => 'frontend\models\Frontuser', // your admin model
                'enableAutoLogin' => true,
                'loginUrl' => '/admin/frontend/login',
            ],
        'session' => [
            // this is the name of the session cookie used for login on the frontend
            'name' => 'advanced-frontend',
        ],
        'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],
                ],
            ],
        ],
        'authManager' => [
            'class' => 'yii\rbac\DbManager', // or use 'yii\rbac\DbManager'
            'defaultRoles'=> ['guest'],
            ],
        'errorHandler' => [
            'errorAction' => 'site/error',
        ],
        /*
        'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'rules' => [
            ],
        ],
        */
    ],
    'params' => $params,
];

but still ,I sign up ,entry goes in user table ..
I want to use user table for backend user
and frontuser table for frontend user
how to do it?


问:
Appbar not hiding when recyclerview scrolled
I am trying to hide appbar when user scrolled recyclerview layout code as per follows:

```<code> <?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:fitsSystemWindows="true"
    android:layout_height="match_parent">
    <android.support.design.widget.AppBarLayout
        android:id="@+id/my_appbar_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">
            <include
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                layout="@layout/plp_header_card_view"
                app:layout_scrollFlags="scroll|enterAlways" />
        </LinearLayout>
    </android.support.design.widget.AppBarLayout>
    <android.support.v7.widget.RecyclerView
        android:id="@+id/item_list_recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:scrollbars="none" />
</android.support.design.widget.CoordinatorLayout>
</code>```

I want to hide appbar when this screen intialize & show appbar when user scroll the recyclerview. Please help me to do this one.

答:
Apply app:layout_scrollFlags="scroll|enterAlways" on LinearLayout work hide action recycleview scroll.

But you question is hide appbar when this screen intialize & show appbar when user scroll the recyclerview

My suggestion as belowit will help you to achieved target

1. Hide and show toolbar on scroll

2. you can use CollapsingToolbar

Body:
I am trying to hide appbar when user scrolled recyclerview layout code as per follows:

 <?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:fitsSystemWindows="true"
    android:layout_height="match_parent">
    <android.support.design.widget.AppBarLayout
        android:id="@+id/my_appbar_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">
            <include
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                layout="@layout/plp_header_card_view"
                app:layout_scrollFlags="scroll|enterAlways" />
        </LinearLayout>
    </android.support.design.widget.AppBarLayout>
    <android.support.v7.widget.RecyclerView
        android:id="@+id/item_list_recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:scrollbars="none" />
</android.support.design.widget.CoordinatorLayout>

I want to hide appbar when this screen intialize & show appbar when user scroll the recyclerview. Please help me to do this one.


问:
Need help on volume mount issue with kubernetes
I have RBAC enabled kubernetes cluster created using
kops version 1.8.0-beta.1, I am trying to run a nginx pod which should attach pre-created EBS volume and pod should start. But getting issue as not authorized even though i am a admin user. Any help would be highly appreciated.

```<code>kubectl version Client Version: version.Info{Major:"1", Minor:"8", GitVersion:"v1.8.3", GitCommit:"f0efb3cb883751c5ffdbe6d515f3cb4fbe7b7acd", GitTreeState:"clean", BuildDate:"2017-11-09T07:27:47Z", GoVersion:"go1.9.2", Compiler:"gc", Platform:"darwin/amd64"}
Server Version: version.Info{Major:"1", Minor:"8", GitVersion:"v1.8.3", GitCommit:"f0efb3cb883751c5ffdbe6d515f3cb4fbe7b7acd", GitTreeState:"clean", BuildDate:"2017-11-08T18:27:48Z", GoVersion:"go1.8.3", Compiler:"gc", Platform:"linux/amd64"}

namespace:default
</code>```

cat test-ebs.yml

```<code>apiVersion: v1
kind: Pod
metadata:
  name: test-ebs
spec:
  containers:
  - image: nginx
    name: nginx
    volumeMounts:
    - mountPath: /test-ebs
      name: test-volume
  volumes:
  - name: test-volume
    awsElasticBlockStore:
      volumeID: <vol-IDhere>
      fsType: ext4
</code>```

I am getting the below error:

```<code>Warning  FailedMount            8m               attachdetach                                        AttachVolume.Attach failed for volume "test-volume" : Error attaching EBS volume "<vol-ID>" to instance "<i-instanceID>": "UnauthorizedOperation: You are not authorized to perform this operation
</code>```

答:
In kops 1.8.0-beta.1, master node requires you to tag the AWS volume with:

KubernetesCluster: <clustername-here>

If you have created the k8s cluster using kops like so:

kops create cluster --name=k8s.yourdomain.com [other-args-here]

your tag on the EBS volume needs to be

KubernetesCluster: k8s.yourdomain.com

And the policy on master would contain a block which would contain:

```<code>{
  "Sid": "kopsK8sEC2MasterPermsTaggedResources",
  "Effect": "Allow",
  "Action": [
    "ec2:AttachVolume",
    "ec2:AuthorizeSecurityGroupIngress",
    "ec2:DeleteRoute",
    "ec2:DeleteSecurityGroup",
    "ec2:DeleteVolume",
    "ec2:DetachVolume",
    "ec2:RevokeSecurityGroupIngress"
  ],
  "Resource": [
    "*"
  ],
  "Condition": {
    "StringEquals": {
      "ec2:ResourceTag/KubernetesCluster": "k8s.yourdomain.com"
    }
  }
}
</code>```

The condition indicates that master-policy has privilege to only attach volumes which contain the right tag.

Body:
I have RBAC enabled kubernetes cluster created using
kops version 1.8.0-beta.1, I am trying to run a nginx pod which should attach pre-created EBS volume and pod should start. But getting issue as not authorized even though i am a admin user. Any help would be highly appreciated.

kubectl version Client Version: version.Info{Major:"1", Minor:"8", GitVersion:"v1.8.3", GitCommit:"f0efb3cb883751c5ffdbe6d515f3cb4fbe7b7acd", GitTreeState:"clean", BuildDate:"2017-11-09T07:27:47Z", GoVersion:"go1.9.2", Compiler:"gc", Platform:"darwin/amd64"}
Server Version: version.Info{Major:"1", Minor:"8", GitVersion:"v1.8.3", GitCommit:"f0efb3cb883751c5ffdbe6d515f3cb4fbe7b7acd", GitTreeState:"clean", BuildDate:"2017-11-08T18:27:48Z", GoVersion:"go1.8.3", Compiler:"gc", Platform:"linux/amd64"}

namespace:default

cat test-ebs.yml

apiVersion: v1
kind: Pod
metadata:
  name: test-ebs
spec:
  containers:
  - image: nginx
    name: nginx
    volumeMounts:
    - mountPath: /test-ebs
      name: test-volume
  volumes:
  - name: test-volume
    awsElasticBlockStore:
      volumeID: <vol-IDhere>
      fsType: ext4

I am getting the below error:

Warning  FailedMount            8m               attachdetach                                        AttachVolume.Attach failed for volume "test-volume" : Error attaching EBS volume "<vol-ID>" to instance "": "UnauthorizedOperation: You are not authorized to perform this operation

Body:
In kops 1.8.0-beta.1, master node requires you to tag the AWS volume with:

KubernetesCluster: <clustername-here>

If you have created the k8s cluster using kops like so:

kops create cluster --name=k8s.yourdomain.com [other-args-here]

your tag on the EBS volume needs to be

KubernetesCluster: k8s.yourdomain.com

And the policy on master would contain a block which would contain:

{
  "Sid": "kopsK8sEC2MasterPermsTaggedResources",
  "Effect": "Allow",
  "Action": [
    "ec2:AttachVolume",
    "ec2:AuthorizeSecurityGroupIngress",
    "ec2:DeleteRoute",
    "ec2:DeleteSecurityGroup",
    "ec2:DeleteVolume",
    "ec2:DetachVolume",
    "ec2:RevokeSecurityGroupIngress"
  ],
  "Resource": [
    "*"
  ],
  "Condition": {
    "StringEquals": {
      "ec2:ResourceTag/KubernetesCluster": "k8s.yourdomain.com"
    }
  }
}

The condition indicates that master-policy has privilege to only attach volumes which contain the right tag.


问:
Database Password Decryption in UWP
I'm a beginner at Universal Windows Platform. I am using Php My admin for my database using web services. Now I'm struck at login. In database, The password is in Bcrypted or Hashed. I don't know how to decrypt it in C# or UWP. </p>

答:
```<code>private string Decrypt(string cipherText)
{
    string EncryptionKey = "MAKV2SPBNI99212";
    byte[] cipherBytes = Convert.FromBase64String(cipherText);
    using (Aes encryptor = Aes.Create())
    {
        Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
        encryptor.Key = pdb.GetBytes(32);
        encryptor.IV = pdb.GetBytes(16);
        using (MemoryStream ms = new MemoryStream())
        {
            using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
            {
                cs.Write(cipherBytes, 0, cipherBytes.Length);
                cs.Close();
            }
            cipherText = Encoding.Unicode.GetString(ms.ToArray());
        }
    }
    return cipherText;
}
</code>```

Title: Database Password Decryption in UWP


问:
How to use react-redux to store a token and use it on multiple axios request?
I am building an app using react native that requires me to do multiple get request on same API with token.

Let say the url is like this

Token URL = https://test.co/v1/tokens, API URL 1 = https://test.co/v1/students and API URL 2 = https://test.co/v1/cars

First of all, to fetch the data from either API URLs, I wrote it like this

Example for students_actions.js

```<code>import axios from 'axios';
import { FETCH_STUDENT } from './types';

const TOKEN_URL = '...'
const STUDENT_URL = '...'

export const fetchStudent = (callback) => async (dispatch) => {
    axios.post(TOKEN_URL, {
        email: 'email',
        password: 'password',
        role: 'user'
    })
    .then((response) => {
        const accessToken = response.data.token;
        //console.log(accessToken);
        axios.get(STUDENT_URL, {
            headers: { 'Authorization': 'Bearer '.concat(accessToken) }
        })
        .then((studentResponse) => {
            dispatch({ type: FETCH_STUDENT, payload: studentResponse.data });
            callback();
        })
        .catch((e) => {
            console.log(e);
        });
    })
    .catch((error) => {
        console.log(error);
    });
};
</code>```

Example for students_reducers.js

```<code>import { FETCH_STUDENT } from '../actions/types';

const INITIAL_STATE = {
    data: []
};

export default function (state = INITIAL_STATE, action) {
    switch (action.type) {
        case FETCH_STUDENT:
            return action.payload;
        default:
            return state;
    }
}
</code>```

and call it inside render function like this

```<code>//some code
import { connect } from 'react-redux';

import * as actions from '../actions';

onButtonPressProfile = () => {
    this.props.fetchStudent(() => {
        this.props.navigation.navigate('Profile');
    });
}
class StudentProfile extends Component {
    render() {
        return(
            <View><Text>{this.props.students.name}</Text></View>
        );
    }
}

function mapStateToProps({ students }) {
    return { students: students.data };
}

export default connect(mapStateToProps, actions)(StudentProfile);
</code>```

While this is all running without any problem I feel like students_actions.js can be further simplify by writing the code for retrieving the token in other file and call the value back inside students_actions.js for GET request.

The reason is so I do not have to request token everytime I want to access either students or cars. Lets say, I did request one time and I can use the same token for like 24 hours to access the API. Once it expired, then I have to do another request for token to access the API again.

I already wrote the code for token_actions.js together with token_reducer.js. Below are the two codes.

token_actions.js

```<code>//import library
// this code works
const TOKEN_URL = apiConfig.url + 'tokens';
const auth = {
    email: 'email',
    password: 'password',
    role: 'user'
};

export const fetchToken = () => async (dispatch, getState) => {
        axios.post(TOKEN_URL, auth)
        .then((response) => {

            dispatch({ type: FETCH_TOKEN, payload: response.data.token });
        })
        .catch((error) => {
            console.log(error);
        });
};
</code>```

token_reducer.js

```<code>import {
    FETCH_TOKEN
} from '../actions/types';

const INITIAL_STATE = {
    data: []
};

export default function (state = INITIAL_STATE, action) {
    switch (action.type) {
        case FETCH_TOKEN:
            return action.payload;
        default:
            return state;
}
</code>```

}

students_actions.js

```<code>axios.get(STUDENT_URL, { headers: {
                           'Authorization': 'Bearer '.concat(here is the value from token_actions)}})
</code>```

And now I am stuck at how should I call/import the payload from token_actions.js into students_actions.js? Should I use mapStateToProps or is there any other way to do this?

Right now, this app does not have any authentication function yet. It is basically an app that shows the data fetched from API.

I wrote this app mainly based on examples I found online and for this case I found this example but seems not really what I want to achieve.

I do not really quite understand javascript so I will be really glad if anyone could pointed out any link related to this case or maybe same questions here on Stackoverflow and also maybe some suggestions.

Thank you.

答:
I the logical thing to do would be to create something like an AuthReducer where you store your token and your refresh token. This is an example of my basic AuthReducer:

```<code>export const INITIAL_STATE = {
  oAuthToken: '',
  refreshToken: '',
};

export default AuthReducer = (state = INITIAL_STATE, action) => {
  switch (action.type) {
    case REFRESH_OAUTH_DATA:
      const { oAuthToken, refreshToken } = action.payload;
      return { ...state, oAuthToken, refreshToken };

    case LOGOUT:
      return INITIAL_STATE;

    case LOGIN_FETCH_SUCCESS:
      const { oAuthToken, refreshToken } = action.payload;
      return { ...state, oAuthToken, refreshToken };

    default:
      return state;
  }
};
</code>```

Now you can get your token in your actions using the getState method doing something like:

```<code>export const fetchStudent = (callback) => async (dispatch, getState) => {
    const token = getState().AuthReducer.oAuthToken;
    ....
};
</code>```

Remember that if you are using ES6 you might also want to use await:

```<code>export const fetchStudent = (callback) => async (dispatch, getState) => {
    try {
        const accessToken = getState().AuthReducer.oAuthToken;

        let response = await axios.get(STUDENT_URL, {
            headers: { 'Authorization': 'Bearer '.concat(accessToken) }
         })

         dispatch({ type: FETCH_STUDENT, payload: response.data });
         callback();
    } catch(e) {
        console.log(e);
    }
};
</code>```

This way your code is way easier to read and maintain.

Body:
I am building an app using react native that requires me to do multiple get request on same API with token.

Let say the url is like this

Token URL = https://test.co/v1/tokens, API URL 1 = https://test.co/v1/students and API URL 2 = https://test.co/v1/cars

First of all, to fetch the data from either API URLs, I wrote it like this

Example for students_actions.js

import axios from 'axios';
import { FETCH_STUDENT } from './types';

const TOKEN_URL = '...'
const STUDENT_URL = '...'

export const fetchStudent = (callback) => async (dispatch) => {
    axios.post(TOKEN_URL, {
        email: 'email',
        password: 'password',
        role: 'user'
    })
    .then((response) => {
        const accessToken = response.data.token;
        //console.log(accessToken);
        axios.get(STUDENT_URL, {
            headers: { 'Authorization': 'Bearer '.concat(accessToken) }
        })
        .then((studentResponse) => {
            dispatch({ type: FETCH_STUDENT, payload: studentResponse.data });
            callback();
        })
        .catch((e) => {
            console.log(e);
        });
    })
    .catch((error) => {
        console.log(error);
    });
};

Example for students_reducers.js

import { FETCH_STUDENT } from '../actions/types';

const INITIAL_STATE = {
    data: []
};

export default function (state = INITIAL_STATE, action) {
    switch (action.type) {
        case FETCH_STUDENT:
            return action.payload;
        default:
            return state;
    }
}

and call it inside render function like this

//some code
import { connect } from 'react-redux';

import * as actions from '../actions';

onButtonPressProfile = () => {
    this.props.fetchStudent(() => {
        this.props.navigation.navigate('Profile');
    });
}
class StudentProfile extends Component {
    render() {
        return(
            <View><Text>{this.props.students.name}</Text></View>
        );
    }
}

function mapStateToProps({ students }) {
    return { students: students.data };
}

export default connect(mapStateToProps, actions)(StudentProfile);

While this is all running without any problem I feel like students_actions.js can be further simplify by writing the code for retrieving the token in other file and call the value back inside students_actions.js for GET request.

The reason is so I do not have to request token everytime I want to access either students or cars. Lets say, I did request one time and I can use the same token for like 24 hours to access the API. Once it expired, then I have to do another request for token to access the API again.

I already wrote the code for token_actions.js together with token_reducer.js. Below are the two codes.

token_actions.js

//import library
// this code works
const TOKEN_URL = apiConfig.url + 'tokens';
const auth = {
    email: 'email',
    password: 'password',
    role: 'user'
};

export const fetchToken = () => async (dispatch, getState) => {
        axios.post(TOKEN_URL, auth)
        .then((response) => {

            dispatch({ type: FETCH_TOKEN, payload: response.data.token });
        })
        .catch((error) => {
            console.log(error);
        });
};

token_reducer.js

import {
    FETCH_TOKEN
} from '../actions/types';

const INITIAL_STATE = {
    data: []
};

export default function (state = INITIAL_STATE, action) {
    switch (action.type) {
        case FETCH_TOKEN:
            return action.payload;
        default:
            return state;
}

}

students_actions.js

axios.get(STUDENT_URL, { headers: {
                           'Authorization': 'Bearer '.concat(here is the value from token_actions)}})

And now I am stuck at how should I call/import the payload from token_actions.js into students_actions.js? Should I use mapStateToProps or is there any other way to do this?

Right now, this app does not have any authentication function yet. It is basically an app that shows the data fetched from API.

I wrote this app mainly based on examples I found online and for this case I found this example but seems not really what I want to achieve.

I do not really quite understand javascript so I will be really glad if anyone could pointed out any link related to this case or maybe same questions here on Stackoverflow and also maybe some suggestions.

Thank you.

Body:
I the logical thing to do would be to create something like an AuthReducer where you store your token and your refresh token. This is an example of my basic AuthReducer:

export const INITIAL_STATE = {
  oAuthToken: '',
  refreshToken: '',
};

export default AuthReducer = (state = INITIAL_STATE, action) => {
  switch (action.type) {
    case REFRESH_OAUTH_DATA:
      const { oAuthToken, refreshToken } = action.payload;
      return { ...state, oAuthToken, refreshToken };

    case LOGOUT:
      return INITIAL_STATE;

    case LOGIN_FETCH_SUCCESS:
      const { oAuthToken, refreshToken } = action.payload;
      return { ...state, oAuthToken, refreshToken };

    default:
      return state;
  }
};

Now you can get your token in your actions using the getState method doing something like:

export const fetchStudent = (callback) => async (dispatch, getState) => {
    const token = getState().AuthReducer.oAuthToken;
    ....
};

Remember that if you are using ES6 you might also want to use await:

export const fetchStudent = (callback) => async (dispatch, getState) => {
    try {
        const accessToken = getState().AuthReducer.oAuthToken;

        let response = await axios.get(STUDENT_URL, {
            headers: { 'Authorization': 'Bearer '.concat(accessToken) }
         })

         dispatch({ type: FETCH_STUDENT, payload: response.data });
         callback();
    } catch(e) {
        console.log(e);
    }
};

This way your code is way easier to read and maintain.


问:
c# Best Method to create a log file
I'm writing a tool that's going to be check the health of workstations across a network, and will fix according to the issues it finds. I want to create a log file as the app is running through its tasks / checks on each machine. I just want to get this working on a single machine for now, but in time it will be scanning 100+ machines in one go (Threaded out).

What is the best way to create a log file?

I was thinking of using a List<string> to build up the log file in memory and then output it to a file once it had finished.

I'm just thinking there may be a better way of doing this?

答: I found the SimpleLogger from heiswayi on GitHub good.</p>

Title: c# Best Method to create a log file


问:
UICollectionView cellForItemAtIndexPath called many times
I am developing an app with an UICollectionView gallery. I have subclassed a UICollectionViewFlowLayout and I've enabled pageEnabled property.

My gallery works very good with images but I also have comments of every image that I download from the service every time I change the picture using the picture code. When I change from one image to next or the picture before, I change a property value and in its custom setter I call a method to download those comments.

The problem is when I go ahead to next picture the cellForItemAtIndexPath method is called 3 times, firs time with the next image information(What I need), second time with the image where I am and third time with the next image information again(What I need). If this image does not have too many comments this happens very quickly so nobody gets notice. But, when I am changing to the next image but I change my mind in the middle of the next image and get back to the image where I am. I get wrong image comments for the image where I am.

Everything happens if I go back in the gallery.

How can I manage this? Is possible to know if the cell is completely displayed? If I could know when the cell is completely displayed I could call the webService method and download that information.

Thanks in advance

答: I faced the same problem. Just go to Storyboard. Choose your CollectionView then go to -> Attribute Inspector-> Uncheck the prefetching Enable property. Solved the problem.


问:
custom spinner not showing drop down options
I have created a custom spinner with the following background. Now my issue is I can not use the drop down arrow (drop down arrow don't show options). Any help please?</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:left="50dip">
        <shape xmlns:android="http://schemas.android.com/apk/res/android">
            <solid android:color="@color/colorGreen"/>
            <stroke android:width="0.5dp" android:color="@color/colorGreen" />
            <corners android:topRightRadius="@dimen/x30" android:bottomRightRadius="@dimen/x30"/>
            <padding android:left="0dp" android:top="0dip" android:right="0dip" android:bottom="0dip" />
        </shape>
    </item>
    <item android:right="50dip">
        <shape xmlns:android="http://schemas.android.com/apk/res/android">
            <solid android:color="@color/colorWhite"/>
            <stroke android:width="0.5dp" android:color="@color/colorGreen" />
            <corners android:topLeftRadius="@dimen/x30" android:bottomLeftRadius="@dimen/x30" ></corners>
            <padding android:left="0dip" android:top="0dip" android:right="0dp" android:bottom="0dip" />
        </shape>
    </item>
    <item
        android:bottom="@dimen/x20"
        android:top="@dimen/x20"
        android:right="@dimen/x20">
        <bitmap android:src="@drawable/drop_down"
            android:gravity="center|right" />
    </item>

</layer-list>
</code>```

答:
```<code>this is my custom spinner background  spinnerbg.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <layer-list>
            <item>
                <shape>
                    <gradient android:angle="90"
                        android:endColor="@color/spinner"
                        android:startColor="@color/spinner"
                        android:type="linear" />

                    <corners android:radius="0dp" />

                </shape>
            </item>
            <item>
                <bitmap android:gravity="bottom|right"
                    android:src="@drawable/dropdown" />

            </item>
        </layer-list>
    </item>

</selector>

    Inside my style.xml i have done like this

     <style name="spinner_style" >
            <item name="android:background">@drawable/spinnerbg</item>
            <item name="android:layout_marginBottom">10dp</item>
            <item name="android:paddingLeft">8dp</item>
            <item name="android:paddingTop">5dp</item>
            <item name="android:paddingBottom">5dp</item>
        </style>
</code>```

you can try this one it is working fine for me

Body:
I have created a custom spinner with the following background. Now my issue is I can not use the drop down arrow (drop down arrow don't show options). Any help please?

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:left="50dip">
        <shape xmlns:android="http://schemas.android.com/apk/res/android">
            <solid android:color="@color/colorGreen"/>
            <stroke android:width="0.5dp" android:color="@color/colorGreen" />
            <corners android:topRightRadius="@dimen/x30" android:bottomRightRadius="@dimen/x30"/>
            <padding android:left="0dp" android:top="0dip" android:right="0dip" android:bottom="0dip" />
        </shape>
    </item>
    <item android:right="50dip">
        <shape xmlns:android="http://schemas.android.com/apk/res/android">
            <solid android:color="@color/colorWhite"/>
            <stroke android:width="0.5dp" android:color="@color/colorGreen" />
            <corners android:topLeftRadius="@dimen/x30" android:bottomLeftRadius="@dimen/x30" ></corners>
            <padding android:left="0dip" android:top="0dip" android:right="0dp" android:bottom="0dip" />
        </shape>
    </item>
    <item
        android:bottom="@dimen/x20"
        android:top="@dimen/x20"
        android:right="@dimen/x20">
        <bitmap android:src="@drawable/drop_down"
            android:gravity="center|right" />
    </item>

</layer-list>

Body:
this is my custom spinner background  spinnerbg.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <layer-list>
            <item>
                <shape>
                    <gradient android:angle="90"
                        android:endColor="@color/spinner"
                        android:startColor="@color/spinner"
                        android:type="linear" />

                    <corners android:radius="0dp" />

                </shape>
            </item>
            <item>
                <bitmap android:gravity="bottom|right"
                    android:src="@drawable/dropdown" />

            </item>
        </layer-list>
    </item>

</selector>

    Inside my style.xml i have done like this

     <style name="spinner_style" >
            <item name="android:background">@drawable/spinnerbg</item>
            <item name="android:layout_marginBottom">10dp</item>
            <item name="android:paddingLeft">8dp</item>
            <item name="android:paddingTop">5dp</item>
            <item name="android:paddingBottom">5dp</item>
        </style>

you can try this one it is working fine for me


问:
Angular4 deletes entry from database but I have to reload page to see the results
After I press delete button, the message gets deleted from database but I have to refresh the page to see the message disappear from page.

dashboard.component.html

```<code><h2 *ngIf="user"> Hello, {{user.username}} </h2>
<a [routerLink]="['/']">Log Out</a>

<form (submit)="createMessage()">
<label>Message</label>
<input type="text" name="message" [(ngModel)]="message.message">
<input type="submit" value="create new message">
</form>

<div *ngFor="let message of messages">
<h1>{{message.userId.username}}</h1>
<h3>{{message.message}}</h3>
<h2 *ngIf="user.username === message.userId.username">
<form (submit) = "delete(message._id)">
    <button type="submit" name="" value="">DeleteOne</button>
</form>
</h2>
<hr>
</div>
</code>```

dashboard.component.ts

```<code>export class DashboardComponent implements OnInit {
messages: Message[] =[];
user: User;
message: Message = new Message();
currentId;

constructor(public _user: UserService, public _router:Router,private
_route: ActivatedRoute, private _message: MessageService) {
this.user = _user.currentUser;
this._route.params.subscribe((param)=>{
console.log("task details url id is: ", param.id);
this.currentId = param.id;
})
}

delete(val) {
console.log("delete method!", val);
 this._message.delete({id: val})
 .then((data)=>{
})
</code>```

答:
The reason why your message is not removed from the UI is because your messages array is not updated. In order to do this you have 2 options:

Remove the element manually from the messages array.

Once the delete() function is resolved (inside the then or the subscribe) make another call to the backend to retrieve the current status of the messages and assign it to the messages array.

Body:
After I press delete button, the message gets deleted from database but I have to refresh the page to see the message disappear from page.

dashboard.component.html

 Hello, {{user.username}}

Log Out

<form (submit)="createMessage()">
Message
<input type="text" name="message" [(ngModel)]="message.message">
<input type="submit" value="create new message">
</form>

{{message.userId.username}}

{{message.message}}

<form (submit) = "delete(message._id)">
    <button type="submit" name="" value="">DeleteOne</button>
</form>

dashboard.component.ts

export class DashboardComponent implements OnInit {
messages: Message[] =[];
user: User;
message: Message = new Message();
currentId;

constructor(public _user: UserService, public _router:Router,private
_route: ActivatedRoute, private _message: MessageService) {
this.user = _user.currentUser;
this._route.params.subscribe((param)=>{
console.log("task details url id is: ", param.id);
this.currentId = param.id;
})
}

delete(val) {
console.log("delete method!", val);
 this._message.delete({id: val})
 .then((data)=>{
})


问:
django rest framework: prefetch an initial data in serializer
I know that django has select_related and prefetch_related that can be used when querying items from database to increase its performance, and it can be used in pair with django rest framework's nested serializer.

However, the problem come when I want to use the serializer to create my model
for example:

```<code>class CompanySerializer(serializer.serializers):
    employee_set = serializers.JSONField()
    class Meta:
        model = Company
        fields = ('id', 'employee_set')
    def create(self, validated_data):
        employee_set = validated_data.pop('employee_set')
        for employee in employee_set:
            serializer = EmployeeSerializer(data=employee)
            serializer.is_valid(raise_exception=True)
            serializer.save()

class EmployeeSerializer(serializer.serializers):
    card = serializers.PrimaryKeyRelatedField(queryset=Card.objects.all())
    class Meta:
        model = Employee
        fields = ('id', 'name', 'card')
    def validate(self, obj):
        if card.employee_set.all().count() > 3:
            raise serializers.ValidationError({'_error': 'invalid})
        return data
</code>```

For example, I want to create a company with multiple employee like:

request.POST:

```<code>{
    employee_set: [
        { name: 'tim', card: 1 },
        { name: 'bob', card: 1 },
        { name: 'jimmy', card: 2},
    ]
}
</code>```

then I can use CompanySerializer(request.POST), right?

However, when I am saving this serializer, the EmployeeSerializer will iterate over each employee and query employee.card_set, which result in a lot of sql queries. Is there any way to do it similar like prefetch_related?

thanks

答:
As the question is too open, I'll give the directions.

Django ORM allows you to create several instances at once using bulk_create.

Also note that you should not call another serializer from a serializer's create/update, as shown in the documentation

Body:
I know that django has select_related and prefetch_related that can be used when querying items from database to increase its performance, and it can be used in pair with django rest framework's nested serializer.

However, the problem come when I want to use the serializer to create my model
for example:

class CompanySerializer(serializer.serializers):
    employee_set = serializers.JSONField()
    class Meta:
        model = Company
        fields = ('id', 'employee_set')
    def create(self, validated_data):
        employee_set = validated_data.pop('employee_set')
        for employee in employee_set:
            serializer = EmployeeSerializer(data=employee)
            serializer.is_valid(raise_exception=True)
            serializer.save()

class EmployeeSerializer(serializer.serializers):
    card = serializers.PrimaryKeyRelatedField(queryset=Card.objects.all())
    class Meta:
        model = Employee
        fields = ('id', 'name', 'card')
    def validate(self, obj):
        if card.employee_set.all().count() > 3:
            raise serializers.ValidationError({'_error': 'invalid})
        return data

For example, I want to create a company with multiple employee like:

request.POST:

{
    employee_set: [
        { name: 'tim', card: 1 },
        { name: 'bob', card: 1 },
        { name: 'jimmy', card: 2},
    ]
}

then I can use CompanySerializer(request.POST), right?

However, when I am saving this serializer, the EmployeeSerializer will iterate over each employee and query employee.card_set, which result in a lot of sql queries. Is there any way to do it similar like prefetch_related?

thanks