问:
React-native switch navigation the component for route must be a React component
I'm building an app in react-native. I'm trying to set initial route name dynamically in my navigation with switchNavigator. Here is my code :

Navigation.js

```<code>import { createStackNavigator, createAppContainer, createSwitchNavigator } from 'react-navigation'
import homeDisconnect from '../screens/homeDisconnect.js'
import Login from '../screens/Login'
import Register from '../screens/Register'
import Home from '../screens/Home'
import AuthLoading from '../screens/AuthLoading'

const AppStack = createStackNavigator(
  {
    Home: {
      screen: Home,
      navigationOptions: {
        headerTitle: 'Accueil',
        headerLeft: null,
        gesturesEnabled: false
      }
    }
  }
)

const AuthStack = createStackNavigator(
  {
    homeDisconnect: {
      screen: homeDisconnect,
      navigationOptions: {
        headerTitle: null,
        headerLeft: null,
        header: null
      }
    },
    Login: {
      screen: Login,
      navigationOptions: {
        headerTitle: 'S\'identifier',
        headerLeft: null
      }
    },
    Register: {
      screen: Register,
      navigationOptions: {
        headerTitle: 'S\'inscrire'
      }
    }
  },
  {
    headerLayoutPreset: 'center',
    initialRouteName: 'homeDisconnect'
  }
)

export default createAppContainer(createSwitchNavigator(
  {
    AuthLoading: AuthLoading,
    AppStack: AppStack,
    AuthStack: AuthStack,
  }
));

</code>```

AuthLoading.js

```<code>
import React, { Component } from 'react'
import {ActivityIndicator, StatusBar, StyleSheet, View} from 'react-native'

import {AppStack, AuthStack} from '../navigation/StackNavigation'

import { connect } from 'react-redux'

class AuthLoading extends Component {
  constructor() {
    super();
  }

    componentDidMount(){
      this._bootstrapAsync()
    }

  _bootstrapAsync = async () => {
    console.log(this.props)
    const userToken = this.props.token

    this.props.navigation.navigate(userToken ? 'App' : 'Auth');
  };
  render() {
    return (
      <View style={styles.container}>
        <ActivityIndicator />
        <StatusBar barStyle="default" />
      </View>
    );
  }
}

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

export default connect(mapStateToProps)(AuthLoading);

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
});

</code>```

App.js

```<code>import {AuthLoading} from './src/screens/AuthLoading'

export default class App extends Component {
  render() {
    return (
      <View>
        <AuthLoading></AuthLoading>
      </View>
    )
  }
}
</code>```

--> import {AppStack, AuthStack} from '../navigation/StackNavigation', is it not possible to do that, that way ? I'm getting that error :

The component for route 'AuthLoading' must be a React component.

What am I doing wrong ?

答:
SwitchNavigator knows to navigate between screen/stack in the same SwitchNavigator, so i recommended to navigate in this way:

```<code>userToken ?
this.props.navigation.navigate('AppStack') : this.props.navigation.navigate('AuthLoading')
</code>```

and you don't need this import so remove it:

```<code>import {AppStack, AuthStack} from '../navigation/StackNavigation'
</code>```

Navigation.js:

```<code> export default MainNavigator = createSwitchNavigator(
  {
    AuthLoading: AuthLoading,
    AppStack: AppStack,
    AuthStack: AuthStack,
  }
});
</code>```

Now change your code in App.js :

```<code>import MainNavigator  from './src/screens/AuthLoading'

export default class App extends Component {
  render() {
    return (
      <View>
        <MainNavigator />
      </View>
    )
  }
}
</code>```

Body:
I'm building an app in react-native. I'm trying to set initial route name dynamically in my navigation with switchNavigator. Here is my code :

Navigation.js

import { createStackNavigator, createAppContainer, createSwitchNavigator } from 'react-navigation'
import homeDisconnect from '../screens/homeDisconnect.js'
import Login from '../screens/Login'
import Register from '../screens/Register'
import Home from '../screens/Home'
import AuthLoading from '../screens/AuthLoading'

const AppStack = createStackNavigator(
  {
    Home: {
      screen: Home,
      navigationOptions: {
        headerTitle: 'Accueil',
        headerLeft: null,
        gesturesEnabled: false
      }
    }
  }
)

const AuthStack = createStackNavigator(
  {
    homeDisconnect: {
      screen: homeDisconnect,
      navigationOptions: {
        headerTitle: null,
        headerLeft: null,
        header: null
      }
    },
    Login: {
      screen: Login,
      navigationOptions: {
        headerTitle: 'S\'identifier',
        headerLeft: null
      }
    },
    Register: {
      screen: Register,
      navigationOptions: {
        headerTitle: 'S\'inscrire'
      }
    }
  },
  {
    headerLayoutPreset: 'center',
    initialRouteName: 'homeDisconnect'
  }
)

export default createAppContainer(createSwitchNavigator(
  {
    AuthLoading: AuthLoading,
    AppStack: AppStack,
    AuthStack: AuthStack,
  }
));

AuthLoading.js

import React, { Component } from 'react'
import {ActivityIndicator, StatusBar, StyleSheet, View} from 'react-native'

import {AppStack, AuthStack} from '../navigation/StackNavigation'

import { connect } from 'react-redux'

class AuthLoading extends Component {
  constructor() {
    super();
  }

    componentDidMount(){
      this._bootstrapAsync()
    }

  _bootstrapAsync = async () => {
    console.log(this.props)
    const userToken = this.props.token

    this.props.navigation.navigate(userToken ? 'App' : 'Auth');
  };
  render() {
    return (
      <View style={styles.container}>
        <ActivityIndicator />
        <StatusBar barStyle="default" />
      </View>
    );
  }
}

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

export default connect(mapStateToProps)(AuthLoading);

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
});

App.js

import {AuthLoading} from './src/screens/AuthLoading'

export default class App extends Component {
  render() {
    return (
      <View>
        <AuthLoading></AuthLoading>
      </View>
    )
  }
}

--> import {AppStack, AuthStack} from '../navigation/StackNavigation', is it not possible to do that, that way ? I'm getting that error :

The component for route 'AuthLoading' must be a React component.

What am I doing wrong ?

Body:
SwitchNavigator knows to navigate between screen/stack in the same SwitchNavigator, so i recommended to navigate in this way:

userToken ?
this.props.navigation.navigate('AppStack') : this.props.navigation.navigate('AuthLoading')

and you don't need this import so remove it:

import {AppStack, AuthStack} from '../navigation/StackNavigation'

Navigation.js:

 export default MainNavigator = createSwitchNavigator(
  {
    AuthLoading: AuthLoading,
    AppStack: AppStack,
    AuthStack: AuthStack,
  }
});

Now change your code in App.js :

import MainNavigator  from './src/screens/AuthLoading'

export default class App extends Component {
  render() {
    return (
      <View>
        <MainNavigator />
      </View>
    )
  }
}


来源: stackexchange

问:
How to compare two arabic string in oracle?
I have two strings:

```<code>a = 'على';
b = 'علي';
</code>```

or

```<code>a = 'محمد';
b ='محــــــــــمد';
</code>```

or

```<code>a= 'بُنْ'
b='بن'

</code>```

```<code>a= 'يسرا'
b='يسرى'

</code>```

and I already have data in database

What I have tried so far:

How can I compare them and return true?
i cant collect all cases

答:
You can either use the comparision operator = or Oracle's SQL function DECODE in order to compare values.

```<code>select case when 'على' = 'علي' then 'same' else 'different' end from dual;

select decode('على' ,'علي', 'same', 'different') from dual;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have two strings:

a = 'على';
b = 'علي';

or

a = 'محمد';
b ='محــــــــــمد';

or

a= 'بُنْ'
b='بن'

a= 'يسرا'
b='يسرى'

and I already have data in database

What I have tried so far:

How can I compare them and return true?
i cant collect all cases

Body:
You can either use the comparision operator = or Oracle's SQL function DECODE in order to compare values.

select case when 'على' = 'علي' then 'same' else 'different' end from dual;

select decode('على' ,'علي', 'same', 'different') from dual;


问:
How to get function from function type?
Suppose I have hold of the concrete type of a normal, named Julia function, F = typeof(f).  Is it possible to get back f from F?  I assume this should work in principle, since F is a singleton type.

答:
You can go with Core.Compiler.singleton_type function which returns the instance field for a concrete DataType. I think this function is used for the same objective as yours (not only for this objective) in Core.Compiler during compilation. This is probably considered "more internal" than directly accessing instance field.

```<code>julia> Core.Compiler.singleton_type(typeof(sum))
sum (generic function with 13 methods)
</code>```

Title: How to get function from function type?

Body:
You can go with Core.Compiler.singleton_type function which returns the instance field for a concrete DataType. I think this function is used for the same objective as yours (not only for this objective) in Core.Compiler during compilation. This is probably considered "more internal" than directly accessing instance field.

julia> Core.Compiler.singleton_type(typeof(sum))
sum (generic function with 13 methods)


问:
Using Express and Spring boot dual backend for Single react Project
I have a react frontend project and I am using mongo DB as my database. I want to implement rest api with both spring boot and express JS. It means some of the api calls should done by spring boot and others should done by express js. Is there any option to do this?</p>

答:
I don't see why not. You will have two separate servers running - one NodeJS + ExpressJS, and the other would be Spring Boot. Your client does not need to know what the implementation of these servers are (i.e. Spring Boot, ExpressJS, Java, Python, whatever). The client will just need the URL of the endpoint that is being served by your servers.

This is the beauty of REST - de-coupled client and server.


问:
case class inheriting another class/trait
I want to have a case class extend a trait

Here are my requirements:

I need to use a case class for the child. This is a hard requirement because of scopt (https://github.com/scopt/scopt)

The parent needs to be a trait. Apologies for not being clear about it earlier

I want the attributes of the parent trait to be accessible to the child, and preferrably not have to specify them again when declaring the child case class. For example, if the parent trait is: trait ParentParams { var name: String = "Al" } then the child should not be case class ChildParams(id: String = "whatever", override val name: String = Parent.defaultName) extends Parent. I would prefer to have it as case class Child(id: String) extends Parent. However, when I try the second approach, I am not able to access the name field when I try to do a .copy() on a case class object. As a workaround I can mutate the value of the name attribute through childObj.name = "newName"

I should (hard requirement) be able to override the attribute values that the child object inherited from the parent. Right now this is possible because I have declared the parent attributes as a var instead of a val. However, ideally I would like to make it immutable and use the copy method for changing values instead.

This is what I have right now, but am unable to use the .copy() method to change the value of an inherited attribute.

```<code>package abcd.wxyz

import org.scalatest.{FlatSpec, Matchers}

trait ParentTrait {
  var name: String = "name"
}

case class TestParams(param1: String = "123") extends ParentTrait

class TestParamsSpec extends FlatSpec with Matchers {
  "TestParams" should "be able to access it's inherited attributes and modify them" in {

    val testParams = TestParams()
    testParams.name = "newName1"
    testParams.param1 should equal("123")
    testParams.name should equal("newName1")

    val modifiedTestParams = testParams.copy(name = "newName2") // cannot resolve symbol name
    modifiedTestParams.name should equal("newName2")

  }
}
</code>```

I get a "Cannot resolve symbol name" on .copy(name = "newName2") for the code above.

The reason behind having this inheritance is to have a function which accepts a Child object and expects it to have a "name" attribute defined. For example, consider a function which will append "Mr." or "Mrs." given a Child object having a name attribute.

Overall background of what is happening:
I am filling a config with command line input values (into a case class) using scopt. If no value is provided, a default is used for that attribute. By attribute I mean the data member inside the case class.
I have a function (let's call it dbReader) which accepts an object of the case class and uses it to establish a connection and read from a database. There are many different parameter case classes in my project and I want each of these parameters to implement a common DatabaseConnectionParameters trait so that the function dbReader can work regardless of which parameter case class is passed to it.

答:
```<code>case class Child(id: String = "55", override val name: String = super.name) extends Parent
</code>```

Does not work, but

```<code> case class Child(id: String = "55", override val name: String) extends Parent(name)
</code>```

does ...

You have to provide a constructor parameter to Parent to be able instantiate it.

Body:
I want to have a case class extend a trait

Here are my requirements:

I need to use a case class for the child. This is a hard requirement because of scopt (https://github.com/scopt/scopt)

The parent needs to be a trait. Apologies for not being clear about it earlier

I want the attributes of the parent trait to be accessible to the child, and preferrably not have to specify them again when declaring the child case class. For example, if the parent trait is: trait ParentParams { var name: String = "Al" } then the child should not be case class ChildParams(id: String = "whatever", override val name: String = Parent.defaultName) extends Parent. I would prefer to have it as case class Child(id: String) extends Parent. However, when I try the second approach, I am not able to access the name field when I try to do a .copy() on a case class object. As a workaround I can mutate the value of the name attribute through childObj.name = "newName"

I should (hard requirement) be able to override the attribute values that the child object inherited from the parent. Right now this is possible because I have declared the parent attributes as a var instead of a val. However, ideally I would like to make it immutable and use the copy method for changing values instead.

This is what I have right now, but am unable to use the .copy() method to change the value of an inherited attribute.

package abcd.wxyz

import org.scalatest.{FlatSpec, Matchers}

trait ParentTrait {
  var name: String = "name"
}

case class TestParams(param1: String = "123") extends ParentTrait

class TestParamsSpec extends FlatSpec with Matchers {
  "TestParams" should "be able to access it's inherited attributes and modify them" in {

    val testParams = TestParams()
    testParams.name = "newName1"
    testParams.param1 should equal("123")
    testParams.name should equal("newName1")

    val modifiedTestParams = testParams.copy(name = "newName2") // cannot resolve symbol name
    modifiedTestParams.name should equal("newName2")

  }
}

I get a "Cannot resolve symbol name" on .copy(name = "newName2") for the code above.

The reason behind having this inheritance is to have a function which accepts a Child object and expects it to have a "name" attribute defined. For example, consider a function which will append "Mr." or "Mrs." given a Child object having a name attribute.

Overall background of what is happening:
I am filling a config with command line input values (into a case class) using scopt. If no value is provided, a default is used for that attribute. By attribute I mean the data member inside the case class.
I have a function (let's call it dbReader) which accepts an object of the case class and uses it to establish a connection and read from a database. There are many different parameter case classes in my project and I want each of these parameters to implement a common DatabaseConnectionParameters trait so that the function dbReader can work regardless of which parameter case class is passed to it.

Body:
case class Child(id: String = "55", override val name: String = super.name) extends Parent

Does not work, but

 case class Child(id: String = "55", override val name: String) extends Parent(name)

does ...

You have to provide a constructor parameter to Parent to be able instantiate it.


问:
Rails 5 nested form with modal bootstrap and Cocoon gem
I'm trying to create a bootstrap modal nested form with cocoon gem. My project follows the simple example on main page (https://github.com/nathanvda/cocoon). I have a main model Project that has many Tasks

I'm trying to create a new recored Task with bootstrap modal inside Project.

I tried make it in so many different ways that a I can't tell whats going wrong or types of error I had.

Anyone could provide an example of a modal with a Cocoon form for a model Taks?

答:
I assume that your intention is that the modal asks for a confirmation by the user.

Dig a little deeper into the readme of the gem because what you want do might require you do craft a significant amount of frontend developing.

cocoon fires specific events when the link to add association button is clicked (before and after insert/remove). You should hook into the cocoon:before-insert event.

The guide provides a simplified example for this in the section Canceling a callback

See https://github.com/nathanvda/cocoon#canceling-a-callback


问:
Automated builds in monotouch
I am currently trying to implement a one-click build solution (without having to start the monodevelop IDE) for my monotouch projects, where i could specify provisioning profiles and code signing certificates. I searched popular build tools like nant, ant and maven, but none seems to support monotouch. Has anyone tried something similar ?</p>

答:
I've gotten it work with Jenkins (aka Hudson).

You basically setup a Jenkins server, and setup your Mac as a "slave" build server.  (I used a JNLP slave).

From there you can run any command line you want in the build, so you merely have to run mdtool with some arguments, like so:

```<code>/Applications/MonoDevelop.app/Contents/MacOS/mdtool -v build "--configuration:Release|iPhone" "Path/To/YourSolution.sln"
</code>```

One thing to worry about is that to sign an iOS app, the slave process must run under your user.  So you can't really create a Mac daemon for it, you'll have to run the slave process in startup for your user and minimize it, which is kind of annoying.

ContentLicense: CC BY-SA 3.0

Title: Automated builds in monotouch

Body:
I've gotten it work with Jenkins (aka Hudson).

You basically setup a Jenkins server, and setup your Mac as a "slave" build server.  (I used a JNLP slave).

From there you can run any command line you want in the build, so you merely have to run mdtool with some arguments, like so:

/Applications/MonoDevelop.app/Contents/MacOS/mdtool -v build "--configuration:Release|iPhone" "Path/To/YourSolution.sln"

One thing to worry about is that to sign an iOS app, the slave process must run under your user.  So you can't really create a Mac daemon for it, you'll have to run the slave process in startup for your user and minimize it, which is kind of annoying.


问:
Should i make multiple models for my migration with different tables
I have a migration with multiple tables in it: Status, Status_project, Status_task. Can i call them all with just my Status model that was created with migration command ? ```php artisan make:model Status -m```

I am reading at several places that i have to make a model for each table, but is there no other way? Except DB::table('statuses'). Because of my relations i don't prefer multiple models

Example:

```<code>  Schema::create('statuses', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name')->unique();
        $table->string('display_name')->nullable();
        $table->string('description')->nullable();
        $table->timestamps();
    });

    Schema::create('status_task', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('user_id')->nullable();
        $table->unsignedBigInteger('task_id');
        $table->unsignedBigInteger('status_id');

        $table->foreign('user_id')->references('id')->on('users')
            ->onUpdate('cascade')->onDelete('cascade');
        $table->foreign('task_id')->references('id')->on('ongoing_tasks')
            ->onUpdate('cascade')->onDelete('cascade');
        $table->foreign('status_id')->references('id')->on('statuses')
            ->onUpdate('cascade')->onDelete('cascade');

    });

    Schema::create('status_project', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('user_id')->nullable();
        $table->string('project_id');
        $table->unsignedBigInteger('status_id');

        $table->foreign('user_id')->references('id')->on('users')
            ->onUpdate('cascade')->onDelete('cascade');
        $table->foreign('project_id')->references('id')->on('ongoing_projects')
            ->onUpdate('cascade')->onDelete('cascade');
        $table->foreign('status_id')->references('id')->on('statuses')
            ->onUpdate('cascade')->onDelete('cascade');

    });

    DB::commit();
</code>```

答: If you plan on using Eloquent to build your queries, you need to create a model for each table. If you are using the query builder, no need to create a model for each table.</p>

Body:
I have a migration with multiple tables in it: Status, Status_project, Status_task. Can i call them all with just my Status model that was created with migration command ?
php artisan make:model Status -m

I am reading at several places that i have to make a model for each table, but is there no other way? Except DB::table('statuses'). Because of my relations i don't prefer multiple models

Example:

  Schema::create('statuses', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name')->unique();
        $table->string('display_name')->nullable();
        $table->string('description')->nullable();
        $table->timestamps();
    });

    Schema::create('status_task', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('user_id')->nullable();
        $table->unsignedBigInteger('task_id');
        $table->unsignedBigInteger('status_id');

        $table->foreign('user_id')->references('id')->on('users')
            ->onUpdate('cascade')->onDelete('cascade');
        $table->foreign('task_id')->references('id')->on('ongoing_tasks')
            ->onUpdate('cascade')->onDelete('cascade');
        $table->foreign('status_id')->references('id')->on('statuses')
            ->onUpdate('cascade')->onDelete('cascade');

    });

    Schema::create('status_project', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('user_id')->nullable();
        $table->string('project_id');
        $table->unsignedBigInteger('status_id');

        $table->foreign('user_id')->references('id')->on('users')
            ->onUpdate('cascade')->onDelete('cascade');
        $table->foreign('project_id')->references('id')->on('ongoing_projects')
            ->onUpdate('cascade')->onDelete('cascade');
        $table->foreign('status_id')->references('id')->on('statuses')
            ->onUpdate('cascade')->onDelete('cascade');

    });

    DB::commit();


问:
cassandra how to select token for compound primary key
I want to get the token for a row of my table whose primary key looks like this:

PRIMARY KEY ((C1, C2), C3)

I tried selecting with the following

SELECT token((C1, C2), C3) from myTable

but get an error
SyntaxException: line 1:12 no viable alternative at input '('

what is the proper syntax for this type of query

答:
Token could be called only on the partition key part of the primary key. In your case it will be</p>

```<code>select token(C1, C2) from myTable;
</code>```

Body:
Token could be called only on the partition key part of the primary key. In your case it will be

select token(C1, C2) from myTable;


问:
WPF FlowDocument Table - AutoFit option?
I want a table to logically size the columns according to the contents. Is this possible in WPF?

alt text http://img43.imageshack.us/img43/2640/flowdocument.jpg

Here is the code I'm working with:

```<code><Window x:Class="FlowDocument.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <Window.Resources>
        <Style TargetType="{x:Type TableCell}">
            <Setter Property="BorderBrush" Value="Gray" />
            <Setter Property="BorderThickness" Value="3" />

        </Style>
        <Style TargetType="{x:Type Paragraph}">
            <Setter Property="Padding" Value="2, 2, 2, 2" />
        </Style>
    </Window.Resources>
    <Grid>
        <FlowDocumentScrollViewer>
            <FlowDocument>
                <Table>
                    <Table.Columns>
                        <TableColumn Background="LightBlue" />
                        <TableColumn Background="Coral" />
                    </Table.Columns>
                    <TableRowGroup>
                        <TableRow>
                            <TableCell>
                                <Paragraph>This is a long piece of text</Paragraph>
                            </TableCell>
                            <TableCell>
                                <Paragraph>This isn't</Paragraph>
                            </TableCell>
                        </TableRow>
                        <TableRow>
                            <TableCell>
                                <Paragraph>This is a another long piece of text. The column should be wider than the other one!</Paragraph>
                            </TableCell>
                            <TableCell>
                                <Paragraph>Ditto</Paragraph>
                            </TableCell>
                        </TableRow>
                    </TableRowGroup>
                </Table>
            </FlowDocument>
        </FlowDocumentScrollViewer>
    </Grid>
</Window>
</code>```

答:
Actually, Microsoft recommends to use a Grid instead of table for this purpose:
learn.microsoft.com: Table vs Grid

Alas, Grid does not support simple grid lines out of the box. Microsoft says the Grid.ShowGridLines is only for design purposes and draws rather ugly dashed lines. Micrsoft wants you to draw Gridlines yourself. How lazy is that from Microsoft ?

Here is some sample code how this can be done:

```<code><FlowDocumentScrollViewer>
  <FlowDocument>
    <BlockUIContainer>
      <Grid HorizontalAlignment="Left" RenderOptions.EdgeMode="Aliased" UseLayoutRounding="True">
        <Grid.ColumnDefinitions>
          <ColumnDefinition/>
          <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
          <RowDefinition/>
          <RowDefinition/>
        </Grid.RowDefinitions>
        <Grid.Resources>
          <Style TargetType="Border">
            <Setter Property="BorderBrush" Value="Black"/>
            <Setter Property="Padding" Value="2,0,3,0"/>
          </Style>

        </Grid.Resources>
        <Border Grid.Row="0" Grid.Column="0" BorderThickness="1,1,1,1">
          <TextBlock Text="AAA"/>
        </Border>
        <Border Grid.Row="0" Grid.Column="1" BorderThickness="0,1,1,1">
          <TextBlock Text="BBB"/>
        </Border>
        <Border Grid.Row="1" Grid.Column="0" BorderThickness="1,0,1,1">
          <TextBlock Text="CCC"/>
        </Border>
        <Border Grid.Row="1" Grid.Column="2" BorderThickness="0,0,1,1">
          <TextBlock Text="QgQ"/>
        </Border>
      </Grid>
    </BlockUIContainer>
  </FlowDocument>
</FlowDocumentScrollViewer>
</code>```

The main idea is to set each TextBox inside a Border and to decide for each Border which side needs a borderline.

To get precise 1 pixel line, one must set Grid.RenderOptions.EdgeMode="Aliased" and Grid.UseLayoutRounding="True".

ContentLicense: CC BY-SA 2.5

Body:
I want a table to logically size the columns according to the contents. Is this possible in WPF?

alt text http://img43.imageshack.us/img43/2640/flowdocument.jpg

Here is the code I'm working with:

<Window x:Class="FlowDocument.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <Window.Resources>

    </Window.Resources>
    <Grid>
        <FlowDocumentScrollViewer>
            <FlowDocument>

                        <TableColumn Background="LightBlue" />
                        <TableColumn Background="Coral" />

                    <TableRowGroup>
                        <TableRow>
                            <TableCell>
                                <Paragraph>This is a long piece of text</Paragraph>
                            </TableCell>
                            <TableCell>
                                <Paragraph>This isn't</Paragraph>
                            </TableCell>
                        </TableRow>
                        <TableRow>
                            <TableCell>
                                <Paragraph>This is a another long piece of text. The column should be wider than the other one!</Paragraph>
                            </TableCell>
                            <TableCell>
                                <Paragraph>Ditto</Paragraph>
                            </TableCell>
                        </TableRow>
                    </TableRowGroup>

            </FlowDocument>
        </FlowDocumentScrollViewer>
    </Grid>
</Window>

Body:
Actually, Microsoft recommends to use a Grid instead of table for this purpose:
learn.microsoft.com: Table vs Grid

Alas, Grid does not support simple grid lines out of the box. Microsoft says the Grid.ShowGridLines is only for design purposes and draws rather ugly dashed lines. Micrsoft wants you to draw Gridlines yourself. How lazy is that from Microsoft ?

Here is some sample code how this can be done:

<FlowDocumentScrollViewer>
  <FlowDocument>
    <BlockUIContainer>
      <Grid HorizontalAlignment="Left" RenderOptions.EdgeMode="Aliased" UseLayoutRounding="True">
        <Grid.ColumnDefinitions>
          <ColumnDefinition/>
          <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
          <RowDefinition/>
          <RowDefinition/>
        </Grid.RowDefinitions>
        <Grid.Resources>
          <Style TargetType="Border">
            <Setter Property="BorderBrush" Value="Black"/>
            <Setter Property="Padding" Value="2,0,3,0"/>
          </Style>

        </Grid.Resources>
        <Border Grid.Row="0" Grid.Column="0" BorderThickness="1,1,1,1">
          <TextBlock Text="AAA"/>
        </Border>
        <Border Grid.Row="0" Grid.Column="1" BorderThickness="0,1,1,1">
          <TextBlock Text="BBB"/>
        </Border>
        <Border Grid.Row="1" Grid.Column="0" BorderThickness="1,0,1,1">
          <TextBlock Text="CCC"/>
        </Border>
        <Border Grid.Row="1" Grid.Column="2" BorderThickness="0,0,1,1">
          <TextBlock Text="QgQ"/>
        </Border>
      </Grid>
    </BlockUIContainer>
  </FlowDocument>
</FlowDocumentScrollViewer>

The main idea is to set each TextBox inside a Border and to decide for each Border which side needs a borderline.

To get precise 1 pixel line, one must set Grid.RenderOptions.EdgeMode="Aliased" and Grid.UseLayoutRounding="True".


问:
How to select rows for some employees, but no rows for others
I have a table EMP that contains emplyee name and insurance plan selections.  There are multiple rows for employees because they can choose a new plan each year.  There are no null values allowed in any field.

How do I select all rows for employees that have a Plan of A or B, but no rows for any employee with a Plan of C?

EMP Table

```<code>Name    | Date   |  Plan |
John    | 1/2018 |  A    |
John    | 1/2017 |  B    |
Alice   | 1/2018 |  C    |
Bob     | 1/2018 |  A    |
Bob     | 1/2017 |  C    |
Bob     | 1/2016 |  B    |
Dave    | 1/2018 |  B    |
Dave    | 1/2017 |  B    |
</code>```

The results should be:

```<code>John    1/2018  A
John    1/2017  B
Dave    1/2018  B
Dave    1/2017  B
</code>```

In other words, I want to select anyone with Plan A or B, but ignore all rows for anyone who ever had plan C.

答:
```<code>SELECT *
FROM EMP
WHERE Name IN ( SELECT Name
                FROM EMP
                GROUP BY Name
                HAVING COUNT( CASE WHEN Plan IN ('A','B') THEN 1 END) > 0
                   AND COUNT( CASE WHEN Plan = 'C' THEN 1 END) = 0
              )
</code>```

Body:
I have a table EMP that contains emplyee name and insurance plan selections.  There are multiple rows for employees because they can choose a new plan each year.  There are no null values allowed in any field.

How do I select all rows for employees that have a Plan of A or B, but no rows for any employee with a Plan of C?

EMP Table

Name    | Date   |  Plan |
John    | 1/2018 |  A    |
John    | 1/2017 |  B    |
Alice   | 1/2018 |  C    |
Bob     | 1/2018 |  A    |
Bob     | 1/2017 |  C    |
Bob     | 1/2016 |  B    |
Dave    | 1/2018 |  B    |
Dave    | 1/2017 |  B    |

The results should be:

John    1/2018  A
John    1/2017  B
Dave    1/2018  B
Dave    1/2017  B

In other words, I want to select anyone with Plan A or B, but ignore all rows for anyone who ever had plan C.


问:
Flutter WebView plugin unable to play some YouTube videos
The webview_flutter plugin is unable to play some YouTube embed videos that do work if played from within a web app. The videos display "Video unavailable". Playing YouTube videos inline in a Flutter app has been an issue for at least a year.

https://github.com/flutter/flutter/issues/13756

I have tried various Flutter plugins to play YouTube video inline but either they only support Android or don't work with YouTube.

I have tried using HTML string (YouTube iframe) directly inside WebView plugin but the video is unavailable. Loading HTML from a webserver allows for some videos to be played which otherwise didn't directly in the flutter app e.g. Some music videos display "Video unavailable. This video contains content from Vevo, who has blocked it from display on the website or application".

But if I launch the same video using the YouTube iframe API (see code) from a web application, it works without any errors i.e. the embed is not disabled but these videos don't play in Flutter app. I have also read similar issues with playing YouTube videos in Android where suggestion was to use a WebChromeClient, that is unavailable in Flutter.

Flutter app that displays a YouTube video inside WebView plugin.

```<code>import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

// Use IP instead of localhost to access local webserver
const _youTubeUrl = 'http://localhost:8080';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'YouTube Video',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'YouTube Video'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  final String title;

  MyHomePage({Key key, this.title}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  WebViewController _controller;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Column(
        children: <Widget>[
          Expanded(
            child: WebView(
              initialUrl: '$_youTubeUrl/videos/IyFZznAk69U',
              javascriptMode: JavascriptMode.unrestricted,
              onWebViewCreated: (WebViewController controller) =>
                  _controller = controller,
            ),
          ),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.play_arrow),
        onPressed: () async {
          await _controller.evaluateJavascript('player.loadVideoById("d_m5csmrf7I")');
        },
      ),
    );
  }
}
</code>```

Node.js server side code that returns index.html via express routing

```<code>const path = require("path");
const express = require("express");

const server = express();

// Define route
api.get("/", (req, res) =>
  res.sendFile(path.join(__dirname + "/index.html"))
);

const port = process.env.PORT || 8080;

server.listen(port, () => console.log(`Server listening on ${port}`));

process.on("exit", () => console.log("Server exited"));
</code>```

index.html file that uses YouTube iframe API served to the Flutter app

```<code><!DOCTYPE html>
<html>

<head>
    <style>
        #player {
            position: relative;
            padding-top: 56.25%;
            min-width: 240px;
            height: 0;
        }

        iframe {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
        }
    </style>
    <script>
        var player;

        function onYouTubeIframeAPIReady() {
            player = new YT.Player("yt", {
                videoId: "IyFZznAk69U",
                playerVars: {
                    autoplay: 1
                }
            });
        }
    </script>
    <script src="https://www.youtube.com/iframe_api" async></script>
</head>

<body>
    <div id="player">
        <div id="yt"></div>
    </div>
</body>

</html>
</code>```

答:
UPDATE: This plugin seems better (mentioned on the jira issue url) but not official from the Flutter team

https://github.com/hoanglm4/flutter_youtube_view

Body:
The webview_flutter plugin is unable to play some YouTube embed videos that do work if played from within a web app. The videos display "Video unavailable". Playing YouTube videos inline in a Flutter app has been an issue for at least a year.

https://github.com/flutter/flutter/issues/13756

I have tried various Flutter plugins to play YouTube video inline but either they only support Android or don't work with YouTube.

I have tried using HTML string (YouTube iframe) directly inside WebView plugin but the video is unavailable. Loading HTML from a webserver allows for some videos to be played which otherwise didn't directly in the flutter app e.g. Some music videos display "Video unavailable. This video contains content from Vevo, who has blocked it from display on the website or application".

But if I launch the same video using the YouTube iframe API (see code) from a web application, it works without any errors i.e. the embed is not disabled but these videos don't play in Flutter app. I have also read similar issues with playing YouTube videos in Android where suggestion was to use a WebChromeClient, that is unavailable in Flutter.

Flutter app that displays a YouTube video inside WebView plugin.

import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

// Use IP instead of localhost to access local webserver
const _youTubeUrl = 'http://localhost:8080';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'YouTube Video',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'YouTube Video'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  final String title;

  MyHomePage({Key key, this.title}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  WebViewController _controller;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Column(
        children: <Widget>[
          Expanded(
            child: WebView(
              initialUrl: '$_youTubeUrl/videos/IyFZznAk69U',
              javascriptMode: JavascriptMode.unrestricted,
              onWebViewCreated: (WebViewController controller) =>
                  _controller = controller,
            ),
          ),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.play_arrow),
        onPressed: () async {
          await _controller.evaluateJavascript('player.loadVideoById("d_m5csmrf7I")');
        },
      ),
    );
  }
}

Node.js server side code that returns index.html via express routing

const path = require("path");
const express = require("express");

const server = express();

// Define route
api.get("/", (req, res) =>
  res.sendFile(path.join(__dirname + "/index.html"))
);

const port = process.env.PORT || 8080;

server.listen(port, () => console.log(`Server listening on ${port}`));

process.on("exit", () => console.log("Server exited"));

index.html file that uses YouTube iframe API served to the Flutter app

<!DOCTYPE html>


问:
Making small components on runtime
I am having a problem working with JQuery DataTable. I had to use that plugin since I had no other choice allowed due to my project requirements.

So the problem is that, I am adding rows to DataTable and in the row there's a column with button HTML tag. Now I want to bind an on click handler to the button.

```<code>dt.Rows.Add({
   column_1_data,
   column_2_data,
   "<button @click='itsVueTime'>MyButton</button>"
});
</code>```

Here dt is the DataTable's instance. Now the problem is @click won't work. I understand that its not being rendered by Vue thats why its not working.

Is there a way to bind click event in this condition?

答:
Without knowing more context, I would recommend this way of doing it

In your component with the method you want to use, you can expose the component like this. (I use mounted, but you can use other lifecycle methods too like created)

  mounted() {
    window.app = this;
  }
```

<p>then you can use</p>

<pre class="lang-html prettyprint-override"><code><button onclick="app.holler()">Say Hello</button>
</code>```

you can also expose just the function you want to use like so

  mounted() {
    window.itsVueTime = this.itsVueTime;
  }
```

Title: Making small components on runtime

Body:
I am having a problem working with JQuery DataTable. I had to use that plugin since I had no other choice allowed due to my project requirements.

So the problem is that, I am adding rows to DataTable and in the row there's a column with button HTML tag. Now I want to bind an on click handler to the button.

dt.Rows.Add({
   column_1_data,
   column_2_data,
   "<button @click='itsVueTime'>MyButton</button>"
});

Here dt is the DataTable's instance. Now the problem is @click won't work. I understand that its not being rendered by Vue thats why its not working.

Is there a way to bind click event in this condition?

Body:
Without knowing more context, I would recommend this way of doing it

In your component with the method you want to use, you can expose the component like this. (I use mounted, but you can use other lifecycle methods too like created)

  mounted() {
    window.app = this;
  }

then you can use

<button onclick="app.holler()">Say Hello</button>

you can also expose just the function you want to use like so

  mounted() {
    window.itsVueTime = this.itsVueTime;
  }


问:
Problem with sending encoding polylines with json via ajax to the server
Im trying to send encoded polylines of google maps to the server with ajax to save them in the database. Im sending them through JSON and decode them at the server side. The problem is when the polyline gets too long the json_decode() function won't decode the json string anymore. Im making my ajax call with post and i've tried several things already like escaping the polylines etc. but nothing will work!

Working JSON example:

```<code>{"title":"a",
 "type":"custom",
 "POIS":["46","43"],
 "polylines":[{
    "points": "oot|H_bgd@rI{HjGkFz@_Ad@w@@eAxD~ClBpAxC`Ax@pAjAbCj@zA|@h@VqAr@wAdBeB|C}Bd@KfY}A",
    "levels": "PEFEFGEFFEEFGEFEFEP"
 }]
}
</code>```

Not working JSON example:

```<code>{"title":"a",
 "type":"custom",
  "POIS":["46","43"],
  "polylines":[{
     "points": "uip|Hc|nd@v@GXoC`TwJV?VPvAhElAxF^bHtHd@zDd@Hj@]jf@KpC@v@F^VOx@HK`De@~EsAdHaEzPyDpMw\zaAqCvJo@tCmDjLyDtNkKvZmD`MmDfNuDnMuA~D_BpDiEhHcF|GxAzEfHhOORvChGjBrEJHnHxOzC~EtDzCpAnBdAzBpc@|hAjJvU`IxPbGdLn@|AJFb@rApAlHF|@fAjGF|AGvGDvCv@rGhA|Fr@fCjA`DfAbCHM`AOzAn@jBzEvBrEbCxCtAnAtAp@|InCf@Dz@Kn@BlDn@`@`@fApCfAqATOh@AxAvAHjA`@E`@L`@b@hGxI|EvF~CmMHInGfF|@bBdCjGvElKrBjGz@bD`@bBjAnGnAdLXjFJpCDtLSlIiBj`@g@tOCjLBdBLnDh@tE`@d@|A|FhA~Fl@pE~CtI`FbMX`@\LZ@`@WbEuFrD_HxBhBrDnBlGfCjFnAX\B`@Gb@sArEE|@g@zDe@`H@x@F\pAdFCv@QZn@lA",
     "levels": "PFFEGEEFFEGEEEFFEFEGEEFFEEEFEEEFEFEGEEFEEEFFFEFEFEEEFEEEFEEFFEFEGEFFEFEFEFEEEFEFEEFFFEEFEFEFFEEGEEEFEEFEFEFEFEGEFEFEEGEEFEGEFEEGEEFEEFEEFEFP"
  }]
}
</code>```

答:
You need to escape certain characters in your points property.

A quick look through your encoded polyline shows you have the character sequence "DpMw\zaA" roughly a fifth of the way into the String.

Backslashes should be escaped with a backslash. So this should look like "DpMw\\zaA"

You should also escape double quotes in your JSON as the property points is constructed with a starting and ending double quote.

Body:
Im trying to send encoded polylines of google maps to the server with ajax to save them in the database. Im sending them through JSON and decode them at the server side. The problem is when the polyline gets too long the json_decode() function won't decode the json string anymore. Im making my ajax call with post and i've tried several things already like escaping the polylines etc. but nothing will work!

Working JSON example:

{"title":"a",
 "type":"custom",
 "POIS":["46","43"],
 "polylines":[{
    "points": "oot|H_bgd@rI{HjGkFz@_Ad@w@@eAxD~ClBpAxC`Ax@pAjAbCj@zA|@h@VqAr@wAdBeB|C}Bd@KfY}A",
    "levels": "PEFEFGEFFEEFGEFEFEP"
 }]
}

Not working JSON example:

{"title":"a",
 "type":"custom",
  "POIS":["46","43"],
  "polylines":[{
     "points": "uip|Hc|nd@v@GXoC`TwJV?VPvAhElAxF^bHtHd@zDd@Hj@]jf@KpC@v@F^VOx@HK`De@~EsAdHaEzPyDpMw\zaAqCvJo@tCmDjLyDtNkKvZmD`MmDfNuDnMuA~D_BpDiEhHcF|GxAzEfHhOORvChGjBrEJHnHxOzC~EtDzCpAnBdAzBpc@|hAjJvU`IxPbGdLn@|AJFb@rApAlHF|@fAjGF|AGvGDvCv@rGhA|Fr@fCjA`DfAbCHM`AOzAn@jBzEvBrEbCxCtAnAtAp@|InCf@Dz@Kn@BlDn@`@`@fApCfAqATOh@AxAvAHjA`@E`@L`@b@hGxI|EvF~CmMHInGfF|@bBdCjGvElKrBjGz@bD`@bBjAnGnAdLXjFJpCDtLSlIiBj`@g@tOCjLBdBLnDh@tE`@d@|A|FhA~Fl@pE~CtI`FbMX`@\LZ@`@WbEuFrD_HxBhBrDnBlGfCjFnAX\B`@Gb@sArEE|@g@zDe@`H@x@F\pAdFCv@QZn@lA",
     "levels": "PFFEGEEFFEGEEEFFEFEGEEFFEEEFEEEFEFEGEEFEEEFFFEFEFEEEFEEEFEEFFEFEGEFFEFEFEFEEEFEFEEFFFEEFEFEFFEEGEEEFEEFEFEFEFEGEFEFEEGEEFEGEFEEGEEFEEFEEFEFP"
  }]
}


问:
JavaScript: Use forEach to see if array contains a specific number value
I have the code below. I am purposefully trying to use forEach in this instance.  </p>

```<code>function check(arr, el) {

  arr.forEach((element) => {

    console.log(element)

    if (element === el) {

       return true
    }
  })
}

check([1, 2, 3, 4, 5], 3)
</code>```

<p>I am expecting the code to return true because the el value of 3 is in the array.  But instead it returns undefined.  What am I doing wrong?  </p>

答:
Cannot use return inside a forEach statement.

NOTE: This answer is only because you need to use forEach.
Ordinarily you would always use some().

function check(arr, el) {
  let found = false;
  arr.forEach((element) => {
    console.log(element)
    if (element === el) {
      found = true;
    }
  });
  return found;
}

console.log( check([1, 2, 3, 4, 5], 3));```

Body:
I have the code below. I am purposefully trying to use forEach in this instance.

function check(arr, el) {

  arr.forEach((element) => {

    console.log(element)

    if (element === el) {

       return true
    }
  })
}

check([1, 2, 3, 4, 5], 3)

I am expecting the code to return true because the el value of 3 is in the array.  But instead it returns undefined.  What am I doing wrong?


答:
You can use not exists:

```<code>select e.*
from emp e
where plan in ('A', 'B') and
      not exists (select 1
                  from emp e2
                  where e2.name = e.name and e2.plan = 'C'
                 );
</code>```

Title: How to select rows for some employees, but no rows for others

Body:
You can use not exists:

select e.*
from emp e
where plan in ('A', 'B') and
      not exists (select 1
                  from emp e2
                  where e2.name = e.name and e2.plan = 'C'
                 );


问:
Secure Connection from Unity to Database
At the moment Unity connects to my database using the WWW class which then uses PHP to connect to my database. All the information from PHP to the database is encrypted, however, the connection between Unity and PHP is not encrypted allowing for a hacker to interrupt. Has anyone tried encrypting the connection from Unity to PHP before? If so, how would I go about it.

Thanks!

答: You need to secure your internet endpoint, best way is using HTTPS. Get a certificate for free using let's encrypt. </p>


问:
TABLEAU Calculating a Running DISTINCT COUNT on usernames for last 3 months
Issue:

Need to show RUNNING DISTINCT users per 3-month interval^^. (See goal table as reference). However, “COUNTD” does not help even after table calculation or “WINDOW_COUNT” or “WINDOW_SUM” function.

^^RUNNING DISTINCT user means DISTINCT users in a period of time (Jan - Mar, Feb – Apr, etc.). The COUNTD option only COUNT DISTINCT users in a window. This process should go over 3-month window to find the DISTINCT users.

Original Table

Date    Username
1/1/2016    A
1/1/2016    B
1/2/2016    C
2/1/2016    A
2/1/2016    B
2/2/2016    B
3/1/2016    B
3/1/2016    C
3/2/2016    D
4/1/2016    A
4/1/2016    C
4/2/2016    D
4/3/2016    F
5/1/2016    D
5/2/2016    F
6/1/2016    D
6/2/2016    F
6/3/2016    G
6/4/2016    H

Goal Table

Tried Methods:

Step-by-step:
Tried to distribute the problem into steps, but due to columnar nature of tableau, I cannot successfully run COUNT or SUM (any aggregate command) on the LAST STEP of the solution.

STEP 0 Raw Data

This tables show the structure Data, as it is in the original table.

STEP 1 COUNT usernames by MONTH

The table show the count of users by month. You will notice because user B had 2 entries he is counted twice. In the next step we use DISTINCT COUNT to fix this issue.

STEP 2  DISTINCT COUNT by MONTH

Now we can see who all were present in a month, next step would be to see running DISTINCT COUNT by MONTH for 3 months

STEP 3 RUNNING DISTINCT COUNT for 3 months

Now we can see the SUM of DISTINCT COUNT of usernames for running 3 months. If you turn the MONTH INTERVAL to 1 from 3, you can see STEP 2 table.

LAST STEP Issue Step

GOAL: Need the GRAND TOTAL to be the SUM of MONTH column.

Request:

I want to calculate the SUM of '1' by MONTH. However, I am using WINDOW function and aggregating the data that gave me an Error.

WHAT I NEED

Jan    Feb     March    April    May   Jun
  3      3        4        5       5     6

WHAT I GOT

Jan    Feb    March      April    May    Jun
  1       1       1          1       1      1

My Output after tried methods:  Attached twbx file. DISTINCT_count_running_v1

HELP taken:

https://community.tableau.com/thread/119179 ; Tried this method but stuck at last step

https://community.tableau.com/thread/122852 ; Used some parts of this solution

答: The way I approached the problem was identifying the minimum login date for each user and then using that date to count the distinct number of users. For example, I have data in this format. I created a calculated field called Min User Login Date as { FIXED [User]:MIN([Date])} and then did a CNTD(USER) on Min User Login Date to get the unique user count by date. If you want running total, then you can do quick table calculation on Running Total on CNTD(USER) field.</p>


问:
how to create reviews using polymorphic associations
I have three models that can all have a Review and each review must belong to a User. I am using polymorphic associations :as => :reviewable but I am not sure where I should put the logic for creating a review for each model. I would assume that the CRUD for each review should be handled by the reviews_controller (or nested attributes? in the other controllers?), but then how do I associate the review with each model ?

I couldn't find any examples of model/view/controller on google, maybe that would help a lot in clearing out things.

Thanks,
Cezar

答:
Since it's an update to the model, it's easier to go through the model's controller. Plus then there is no mistaking which model the review belongs to.

Take a look at what acts_as_commentable does. It might be easier to repurpose than to roll your own.

http://github.com/jackdempsey/acts_as_commentable/tree/master

OwnerDisplayName: Cezar

LastEditorDisplayName: Gamecat

OwnerDisplayName: Sarah Mei


问:
How do I implement a infinite list in Flex (hero)
I'm new to Flex/ActionScript (.NET/Java has been my main playground so far).
I'm trying to build a Flex app that has a list that is meant to look and behave like an infinite list (of items - which can be any object). The idea is that the user should be able to scroll up or down and never reach the end of the list in either direction.

An example would be a list of numbers. Scrolling up will show negative numbers; scrolling down will show positive ones. Now, my list is a simple Flex Spark list (using Flex Hero).
It is bound to a data provider that is an ArrayList.

My initial idea was to listen to the scroll event and add/remove items as needed. However, in the current build of Flex Hero, there is a bug that doesn't raise scroll events for vertical scrollbars sometimes (http://bugs.adobe.com/jira/browse/SDK-26533).

So, I'm using the workaround suggested in the link above (i.e listening to the  propertyChanged event of the list's scroller's viewport. The event though only gives me the current verticalScrollPosition.

And it looks like the default spark list supports smooth scrolling and raises the event many times before the list scrolling comes to a standstill (it is a nice visual effect).

Now, I need to :

Figure out whether it is scrolling up or down (how do I do that?)

Figure out which items are visible. I can get this from:

list.dataGroup.getItemIndicesInView()

Add/remove items as needed, so that the user can scroll up and down forever, never reaching the end of the list in either direction.

I've tried the following code but it doesn't work. (comments in code).

Any Flex experts out there? Please help.

```<code>        import mx.collections.ArrayList;
        import mx.core.INavigatorContent;
        import mx.events.FlexEvent;
        import mx.events.PropertyChangeEvent;

        var listData:ArrayList;
        var firstItemInView:int = 0;
        var lastItemInView:int = 0;
        var count = 0;

                    //gets the currently visible item indices (first and last)
        private function getVisibleIndices():Vector.<int> {
            var ind:Vector.<int> = new Vector.<int>(2, true);
            ind[0] = firstItemInView;
            ind[1] = lastItemInView;
            return ind;
        }

        protected function view_creationCompleteHandler(event:FlexEvent):void {

                            //create an initialise list data
            listData = new ArrayList();
            for(var i:int = 0; i < 6; i++){
                listData.addItemAt(i, i);
            }
            infiniteList.dataProvider = listData;

            updateIndices();

            infiniteList.scroller.viewport.addEventListener(PropertyChangeEvent.PROPERTY_CHANGE, infiniteList_VerticalScroll_PropertyChanged);
        }

                    //get the indices visible from the list's data group
        private function getNewIndices():Vector.<int> {
            var indices:Vector.<int> = new Vector.<int>(2, true);
            var indicesInView:Vector.<int> = infiniteList.dataGroup.getItemIndicesInView();
            if (indicesInView.length > 0){
                indices[0] = indicesInView[0];
            }
            if (indicesInView.length > 1){
                indices[1] = indicesInView[indicesInView.length - 1];
            }
            return indices;
        }

        private function updateIndices():void {
            var indices:Vector.<int> = getNewIndices();
            if (indices.length > 0){
                firstItemInView = indices[0];
                if (indices.length > 1){
                    lastItemInView = indices[1];
                }
            }
        }

        protected function leftCalendar_VerticalScroll_PropertyChanged(event:PropertyChangeEvent):void {

            switch (event.property){
                case "verticalScrollPosition":

                    var indices:Vector.<int> = getNewIndices();
                    var oldIndices:Vector.<int> = getVisibleIndices();

                    var newNum:Number;

                    if (indices[1] - indices[0] == 2 && (oldIndices[0] != indices[0] && oldIndices[1] != indices[1])){
                        //a new item is in view. did we scroll up or down?
                        if (oldIndices[0] < indices[0]){
                            count++;
                            trace(count + " up : old[" + oldIndices[0] + "," + oldIndices[1] + "], new[" + indices[0] + "," + indices[1] + "]");
                            //newNum = Number(listData.getItemAt(listData.length - 1)) + 1;
                            //trace("new number to add: " + newNum);
                            //trace("todo remove: " + listData.getItemAt(0));
                            fixItems({ addAt : "top", removeAt : "bottom", newValue : newNum});

                        } else {
                            trace("down : old[" + oldIndices[0] + "," + oldIndices[1] + "], new[" + indices[0] + "," + indices[1] + "]");
                            fixItems({ addAt : "bottom", removeAt : "top", newValue : newNum});
                        }

                        //update indices:
                        updateIndices();
                        var newOnes = getVisibleIndices(); //seems to be getting the new ones, but the next occurance of this event handler doesn't pick up the new values! why?
                        trace(count + " current[" + newOnes[0] + ", " + newOnes[1] + "]");
                    }

                    break;
            }
        }

        protected function fixItems(data:Object):void {
            var item:Object;

            //add a new item
            if (data.addAt == "top"){
                listData.addItemAt(data.newValue, 0);
            } else {
                listData.addItem(data.newValue);
            }

            //remove one of the existing ones
            if (data.removeAt == "top"){
                item = listData.getItemAt(0);
                trace("removing " + item);
                listData.removeItemAt(0);
            } else {
                item = listData.getItemAt(listData.length - 1);
                trace("removing " + item);
                listData.removeItemAt(listData.length - 1);
            }
            updateIndices();
        }
</code>```

答: You can't use a List.  You'll have to create your own custom component for this from scratch.  All components that I know of in Flex uses a finite dataProvider to display information.  If you want infinite, you'll need to create your own component that can handle a range (or none whatsoever) and display it appropriately and scroll it.  Be sure to clean any items that are not displayed anymore (or reuse them) because that would be a severe memory leak.</p>

Body:
I'm new to Flex/ActionScript (.NET/Java has been my main playground so far).
I'm trying to build a Flex app that has a list that is meant to look and behave like an infinite list (of items - which can be any object). The idea is that the user should be able to scroll up or down and never reach the end of the list in either direction.

An example would be a list of numbers. Scrolling up will show negative numbers; scrolling down will show positive ones. Now, my list is a simple Flex Spark list (using Flex Hero).
It is bound to a data provider that is an ArrayList.

My initial idea was to listen to the scroll event and add/remove items as needed. However, in the current build of Flex Hero, there is a bug that doesn't raise scroll events for vertical scrollbars sometimes (http://bugs.adobe.com/jira/browse/SDK-26533).

So, I'm using the workaround suggested in the link above (i.e listening to the  propertyChanged event of the list's scroller's viewport. The event though only gives me the current verticalScrollPosition.

And it looks like the default spark list supports smooth scrolling and raises the event many times before the list scrolling comes to a standstill (it is a nice visual effect).

Now, I need to :

Figure out whether it is scrolling up or down (how do I do that?)

Figure out which items are visible. I can get this from:

list.dataGroup.getItemIndicesInView()

Add/remove items as needed, so that the user can scroll up and down forever, never reaching the end of the list in either direction.

I've tried the following code but it doesn't work. (comments in code).

Any Flex experts out there? Please help.

        import mx.collections.ArrayList;
        import mx.core.INavigatorContent;
        import mx.events.FlexEvent;
        import mx.events.PropertyChangeEvent;

        var listData:ArrayList;
        var firstItemInView:int = 0;
        var lastItemInView:int = 0;
        var count = 0;

                    //gets the currently visible item indices (first and last)
        private function getVisibleIndices():Vector.<int> {
            var ind:Vector.<int> = new Vector.<int>(2, true);
            ind[0] = firstItemInView;
            ind[1] = lastItemInView;
            return ind;
        }

        protected function view_creationCompleteHandler(event:FlexEvent):void {

                            //create an initialise list data
            listData = new ArrayList();
            for(var i:int = 0; i < 6; i++){
                listData.addItemAt(i, i);
            }
            infiniteList.dataProvider = listData;

            updateIndices();

            infiniteList.scroller.viewport.addEventListener(PropertyChangeEvent.PROPERTY_CHANGE, infiniteList_VerticalScroll_PropertyChanged);
        }

                    //get the indices visible from the list's data group
        private function getNewIndices():Vector.<int> {
            var indices:Vector.<int> = new Vector.<int>(2, true);
            var indicesInView:Vector.<int> = infiniteList.dataGroup.getItemIndicesInView();
            if (indicesInView.length > 0){
                indices[0] = indicesInView[0];
            }
            if (indicesInView.length > 1){
                indices[1] = indicesInView[indicesInView.length - 1];
            }
            return indices;
        }

        private function updateIndices():void {
            var indices:Vector.<int> = getNewIndices();
            if (indices.length > 0){
                firstItemInView = indices[0];
                if (indices.length > 1){
                    lastItemInView = indices[1];
                }
            }
        }

        protected function leftCalendar_VerticalScroll_PropertyChanged(event:PropertyChangeEvent):void {

            switch (event.property){
                case "verticalScrollPosition":

                    var indices:Vector.<int> = getNewIndices();
                    var oldIndices:Vector.<int> = getVisibleIndices();

                    var newNum:Number;

                    if (indices[1] - indices[0] == 2 && (oldIndices[0] != indices[0] && oldIndices[1] != indices[1])){
                        //a new item is in view. did we scroll up or down?
                        if (oldIndices[0] < indices[0]){
                            count++;
                            trace(count + " up : old[" + oldIndices[0] + "," + oldIndices[1] + "], new[" + indices[0] + "," + indices[1] + "]");
                            //newNum = Number(listData.getItemAt(listData.length - 1)) + 1;
                            //trace("new number to add: " + newNum);
                            //trace("todo remove: " + listData.getItemAt(0));
                            fixItems({ addAt : "top", removeAt : "bottom", newValue : newNum});

                        } else {
                            trace("down : old[" + oldIndices[0] + "," + oldIndices[1] + "], new[" + indices[0] + "," + indices[1] + "]");
                            fixItems({ addAt : "bottom", removeAt : "top", newValue : newNum});
                        }

                        //update indices:
                        updateIndices();
                        var newOnes = getVisibleIndices(); //seems to be getting the new ones, but the next occurance of this event handler doesn't pick up the new values! why?
                        trace(count + " current[" + newOnes[0] + ", " + newOnes[1] + "]");
                    }

                    break;
            }
        }

        protected function fixItems(data:Object):void {
            var item:Object;

            //add a new item
            if (data.addAt == "top"){
                listData.addItemAt(data.newValue, 0);
            } else {
                listData.addItem(data.newValue);
            }

            //remove one of the existing ones
            if (data.removeAt == "top"){
                item = listData.getItemAt(0);
                trace("removing " + item);
                listData.removeItemAt(0);
            } else {
                item = listData.getItemAt(listData.length - 1);
                trace("removing " + item);
                listData.removeItemAt(listData.length - 1);
            }
            updateIndices();
        }


问:
Python: Problem trying catching an output during a unit test - Unittest library
I'm trying to catching an output to be tested, I'm using unittest and unittest.mock libraries. I have taken a look in many others related questions (like this: How to assert output with nosetest/unittest in python? among others) and all they suggest something like which a have in my code, but I'm getting only an empty string, and can't find where I'm mistaking.

My function do something like that:

def my_func():
  a = int(input("put a 2 digit number"))
  b = [1,2,3,4,5,6,7,8,9,0]
  if a in b:
    print("wrong number")
```

<p>And this is the related test:</p>

<pre class="lang-py prettyprint-override"><code>import io
import sys
import unittest
from unittest.mock import patch
from io import StringIO
from somemodule import my_func

def test_entering_wrong_value(self):

        user_input = ['2']

        with patch('builtins.input', side_effect=user_input):
            self.my_func()
            capturedOutput = io.StringIO()
            sys.stdout = capturedOutput
            output = capturedOutput.getvalue().strip()
            self.assertEqual('wrong number', output)
</code>```

As I undestood this should capture the outputed string and compared with the test value, but can't capturing the string, I'm just getting an empty string and this error:

AssertionError: 'wrong number' != ''

Where am I messing up?

答:
You have to redirect stdout BEFORE you do your prints.  You can't redirect after and expect to get the prints that weren't being redirected:

```<code>import io
import sys
import unittest
from unittest.mock import patch
from somemodule import my_func

def test_entering_wrong_value(self):

        user_input = ['2']

        with patch('builtins.input', side_effect=user_input):
            capturedOutput = io.StringIO()
            sys.stdout = capturedOutput
            self.my_func()
            output = capturedOutput.getvalue().strip()
            sys.stdout = sys.__stdout__ # Restore stdout so prints work normally
            self.assertEqual('wrong number', output)
</code>```

Body:
I'm trying to catching an output to be tested, I'm using unittest and unittest.mock libraries. I have taken a look in many others related questions (like this: How to assert output with nosetest/unittest in python? among others) and all they suggest something like which a have in my code, but I'm getting only an empty string, and can't find where I'm mistaking.

My function do something like that:

def my_func():
  a = int(input("put a 2 digit number"))
  b = [1,2,3,4,5,6,7,8,9,0]
  if a in b:
    print("wrong number")

And this is the related test:

import io
import sys
import unittest
from unittest.mock import patch
from io import StringIO
from somemodule import my_func

def test_entering_wrong_value(self):

        user_input = ['2']

        with patch('builtins.input', side_effect=user_input):
            self.my_func()
            capturedOutput = io.StringIO()
            sys.stdout = capturedOutput
            output = capturedOutput.getvalue().strip()
            self.assertEqual('wrong number', output)

As I undestood this should capture the outputed string and compared with the test value, but can't capturing the string, I'm just getting an empty string and this error:

AssertionError: 'wrong number' != ''

Where am I messing up?

Body:
You have to redirect stdout BEFORE you do your prints.  You can't redirect after and expect to get the prints that weren't being redirected:

import io
import sys
import unittest
from unittest.mock import patch
from somemodule import my_func

def test_entering_wrong_value(self):

        user_input = ['2']

        with patch('builtins.input', side_effect=user_input):
            capturedOutput = io.StringIO()
            sys.stdout = capturedOutput
            self.my_func()
            output = capturedOutput.getvalue().strip()
            sys.stdout = sys.__stdout__ # Restore stdout so prints work normally
            self.assertEqual('wrong number', output)


问:
In camera2, custom camera characteristics building is not working
I need to use custom camera characteristics, but it is not working when building. I saw camera2 official website's support custom characteristics.

I tried using sdk version 25, 26 and 28, but nothing is working.

```<code>CameraCharacteristics.Key<byte[]> key = new CameraCharacteristics.Key<>(name, byte[].class);
</code>```

It shows error log when click rebuild project.

```<code>// error log display below:
<T>Key(String,Class<T>)在Key中不是公共的; 无法从外部程序包中对其进行访问
        CameraCharacteristics.Key<byte[]> key = new CameraCharacteristics.Key<>(name, byte[].class);
</code>```

but I look over the origin code, CameraCharacteristics.Key is public.

答:
Try</p>

```<code>CameraCharacteristics.Key<?> cc = new CameraCharacteristics.Key<>(name, byte[].class);
</code>```

Body:
I need to use custom camera characteristics, but it is not working when building. I saw camera2 official website's support custom characteristics.

I tried using sdk version 25, 26 and 28, but nothing is working.

CameraCharacteristics.Key<byte[]> key = new CameraCharacteristics.Key<>(name, byte[].class);

It shows error log when click rebuild project.

// error log display below:
<T>Key(String,Class<T>)在Key中不是公共的; 无法从外部程序包中对其进行访问
        CameraCharacteristics.Key<byte[]> key = new CameraCharacteristics.Key<>(name, byte[].class);

but I look over the origin code, CameraCharacteristics.Key is public.

Body:
Try

CameraCharacteristics.Key<?> cc = new CameraCharacteristics.Key<>(name, byte[].class);


问:
Pandas - Replace values based on index and not in index
Here is the sample code.

```<code>import pandas as pd, numpy as np

df = pd.DataFrame(np.random.randint(0,100,size=(10, 1)), columns=list('A'))
</code>```

I have a list dl=[0,2,3,4,7]

At the index positions specified by list, I would like to have column A as "Yes".

The following code works

```<code>df.loc[dl,'A']='Yes'
</code>```

How do I fill column 'A' with 'No' for column values not in index.
Please forgive me if this is a duplicate post.

答:
by using the difference between the list dl and the df list itself:

```<code>df.iloc[list( set(df.index) - set(dl))]  = 'No'
</code>```

or

```<code>df.iloc[[x for x in range(len(df)) if x not in dl]] = 'No'
</code>```

Body:
Here is the sample code.

import pandas as pd, numpy as np

df = pd.DataFrame(np.random.randint(0,100,size=(10, 1)), columns=list('A'))

I have a list dl=[0,2,3,4,7]

At the index positions specified by list, I would like to have column A as "Yes".

The following code works

df.loc[dl,'A']='Yes'

How do I fill column 'A' with 'No' for column values not in index.
Please forgive me if this is a duplicate post.

Body:
by using the difference between the list dl and the df list itself:

df.iloc[list( set(df.index) - set(dl))]  = 'No'

or

df.iloc[[x for x in range(len(df)) if x not in dl]] = 'No'


问:
Installing Java 8 on a Mac: Why can't I download the file? It re-directs to a log-in
I've installed Java 8 on Linux machines before, but I just tried installing it on a friend's Mac and couldn't get it to work.  I went to the Oracle page, down to Java JDK 8, accepted the license agreement, and clicked the download link for Java 8.  For whatever reason, it then directs me to log in to an Oracle account.

I re-tried the procedure for Java 12, and it worked.  I could download the .pkg file just fine.

I can't begin to guess what's going on here.  Anyone have an idea?

答:
End of life versions require login for years, according to /u/beltedgalaxy/
Try adoptopenjdk.net, the community driven implemintation of JDK.</p>


问:
LDAP Authentication - OpenShift - OKD
I have deployed a new OKD cluster (3.11) and as Identity Provider I have selected LDAPPasswordIdentityProvider

The configuration goes like this:

```<code>openshift_master_identity_providers=[{'name': 'idm', 'challenge': 'true', 'login': 'true', 'kind': 'LDAPPasswordIdentityProvider', 'attributes': {'id': ['dn'], 'email': ['mail'], 'name': ['cn'], 'preferredUsername': ['uid']}, 'bindDN': 'uid=service,cn=users,cn=accounts,dc=myorg,dc=com', 'bindPassword': 'reallysecurepasswordhere', 'insecure': 'false', 'url': 'ldaps://idm.myorg.com:636/dc=myorg,dc=com?uid??(memberof=cn=openshift,cn=accounts,dc=myorg,dc=com)'}]
</code>```

I have tried two dozens of possibilities with this URL.
On the logs I always get:

```<code> I0528 15:23:38.491659       1 ldap.go:122] searching for (&(objectClass=*)(uid=user1))
 E0528 15:23:38.494172       1 login.go:174] Error authenticating "user1" with provider "idm": multiple entries found matching "user1"
</code>```

I don't get it why is the filter showing as (&(objectClass=*)(uid=... appears as the filter isn't being parsed correctly, despite the URL being as above.
I also checked the master-config.yaml and it is correct as my ini file.

If I do ldapsearch I get the expected results:

```<code>$ ldapsearch -x -D "uid=service,cn=users,cn=accounts,dc=myorg,dc=com" -W -H  ldaps://idm.myorg.com -s sub -b "cn=accounts,dc=myorg,dc=com" '(&(uid=user1)(memberof=cn=openshift,cn=groups,cn=accounts,dc=myorg,dc=com))' uid
Enter LDAP Password:
# extended LDIF
#
# LDAPv3
# base <cn=accounts,dc=myorg,dc=com> with scope subtree
# filter: (&(uid=user1)(memberof=cn=openshift,cn=groups,cn=accounts,dc=myorg,dc=com))
# requesting: uid
#

# user1, users, accounts, myorg.com
dn: uid=user1,cn=users,cn=accounts,dc=myorg,dc=com
uid: user1

# search result
search: 2
result: 0 Success

# numResponses: 2
# numEntries: 1
</code>```

The LDAP Server is FreeIPA.

Help please!

答:
Ok, I found the solution to the problem.

I assumed ... incorrectly ... that running the playbook openshift-ansible/playbook/openshift-master/config.yml would restart the openshift-master API.
It doesn't.

I noticed this when, instead of editing my ini inventory where I have this set and running config, I started editing directly on /etc/origin/master/master-config.yaml and using master-restart api to restart the API.
Several URL alterations (many incorrect actually) had never been ran. Config uploaded them, but the master api doesn't restart, so new config doesn't go in place, and I kept hitting the wall.

Title: LDAP Authentication - OpenShift - OKD

Body:
I have deployed a new OKD cluster (3.11) and as Identity Provider I have selected LDAPPasswordIdentityProvider

The configuration goes like this:

openshift_master_identity_providers=[{'name': 'idm', 'challenge': 'true', 'login': 'true', 'kind': 'LDAPPasswordIdentityProvider', 'attributes': {'id': ['dn'], 'email': ['mail'], 'name': ['cn'], 'preferredUsername': ['uid']}, 'bindDN': 'uid=service,cn=users,cn=accounts,dc=myorg,dc=com', 'bindPassword': 'reallysecurepasswordhere', 'insecure': 'false', 'url': 'ldaps://idm.myorg.com:636/dc=myorg,dc=com?uid??(memberof=cn=openshift,cn=accounts,dc=myorg,dc=com)'}]

I have tried two dozens of possibilities with this URL.
On the logs I always get:

 I0528 15:23:38.491659       1 ldap.go:122] searching for (&(objectClass=*)(uid=user1))
 E0528 15:23:38.494172       1 login.go:174] Error authenticating "user1" with provider "idm": multiple entries found matching "user1"

I don't get it why is the filter showing as (&(objectClass=*)(uid=... appears as the filter isn't being parsed correctly, despite the URL being as above.
I also checked the master-config.yaml and it is correct as my ini file.

If I do ldapsearch I get the expected results:

$ ldapsearch -x -D "uid=service,cn=users,cn=accounts,dc=myorg,dc=com" -W -H  ldaps://idm.myorg.com -s sub -b "cn=accounts,dc=myorg,dc=com" '(&(uid=user1)(memberof=cn=openshift,cn=groups,cn=accounts,dc=myorg,dc=com))' uid
Enter LDAP Password:
# extended LDIF
#
# LDAPv3
# base <cn=accounts,dc=myorg,dc=com> with scope subtree
# filter: (&(uid=user1)(memberof=cn=openshift,cn=groups,cn=accounts,dc=myorg,dc=com))
# requesting: uid
#

# user1, users, accounts, myorg.com
dn: uid=user1,cn=users,cn=accounts,dc=myorg,dc=com
uid: user1

# search result
search: 2
result: 0 Success

# numResponses: 2
# numEntries: 1

The LDAP Server is FreeIPA.

Help please!


问:
Add UTF8 Filter for Servlet
Hi I used Initializer and it worked well.

```<code>public class Initializer implements WebApplicationInitializer {

    public void onStartup(ServletContext servletContext)
            throws ServletException {
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(WebAppConfig.class);
        servletContext.addListener(new ContextLoaderListener(ctx));

        ctx.setServletContext(servletContext);

        Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
        servlet.addMapping("/");
        servlet.setLoadOnStartup(1);

        FilterRegistration.Dynamic filterRegistration = servletContext.addFilter("encodingFilter",
                new CharacterEncodingFilter());
        filterRegistration.setInitParameter("encoding", "UTF-8");
        filterRegistration.setInitParameter("forceEncoding", "true");
        filterRegistration.addMappingForUrlPatterns(null,true,"/*");
    }
</code>```

Then I changed it to another:

```<code>public class Initializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[]{WebAppConfig.class};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[]{WebAppConfig.class};
    }
}
</code>```

But I can't add to it this method:

```<code>public void onStartup(ServletContext servletContext) {
        FilterRegistration.Dynamic filterRegistration = servletContext.addFilter("encodingFilter",
                new CharacterEncodingFilter());
        filterRegistration.setInitParameter("encoding", "UTF-8");
        filterRegistration.setInitParameter("forceEncoding", "true");
        filterRegistration.addMappingForUrlPatterns(null, true, "/*");
    }
</code>```

Because the application falls.
What am I doing wrong? How to add this filter to a new Initializer to force it work?
Thank you.

答:
```<code>@Override
    protected FilterRegistration.Dynamic registerServletFilter(ServletContext servletContext, Filter filter) {

        FilterRegistration.Dynamic filterRegistration =     servletContext.addFilter("encodingFilter",
                new CharacterEncodingFilter());
        filterRegistration.setInitParameter("encoding", "UTF-8");
        filterRegistration.setInitParameter("forceEncoding", "true");
        filterRegistration.addMappingForUrlPatterns(null, true, "/*");

        return super.registerServletFilter(servletContext, filter);
    }
</code>```

Title: Add UTF8 Filter for Servlet

Body:
Hi I used Initializer and it worked well.

public class Initializer implements WebApplicationInitializer {

    public void onStartup(ServletContext servletContext)
            throws ServletException {
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(WebAppConfig.class);
        servletContext.addListener(new ContextLoaderListener(ctx));

        ctx.setServletContext(servletContext);

        Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
        servlet.addMapping("/");
        servlet.setLoadOnStartup(1);

        FilterRegistration.Dynamic filterRegistration = servletContext.addFilter("encodingFilter",
                new CharacterEncodingFilter());
        filterRegistration.setInitParameter("encoding", "UTF-8");
        filterRegistration.setInitParameter("forceEncoding", "true");
        filterRegistration.addMappingForUrlPatterns(null,true,"/*");
    }

Then I changed it to another:

public class Initializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[]{WebAppConfig.class};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[]{WebAppConfig.class};
    }
}

But I can't add to it this method:

public void onStartup(ServletContext servletContext) {
        FilterRegistration.Dynamic filterRegistration = servletContext.addFilter("encodingFilter",
                new CharacterEncodingFilter());
        filterRegistration.setInitParameter("encoding", "UTF-8");
        filterRegistration.setInitParameter("forceEncoding", "true");
        filterRegistration.addMappingForUrlPatterns(null, true, "/*");
    }

Because the application falls.
What am I doing wrong? How to add this filter to a new Initializer to force it work?
Thank you.


问:
How to pass ReactJS props properly?
I am trying to pass some values using props in ReactJS but, values are not passing not showing.

This is my html for the project:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>React JS</title>
</head>
<body>
    <div id="app"></div>
    <script src="main.jsx"></script>
</body>
</html>
</code>```

and this is my main.jsx which renders a class named AppContainer component

```<code>'use strict';
import React from 'react';
import {render} from 'react-dom';
import AppContainer from './AppContainer';

render(<AppContainer />, document.getElementById('app'));
</code>```

This is my AppContainer.jsx which renders Users.jsx component

```<code>'use strict';
import React, {Component} from 'react';
import Users from './Users';

export default class AppContainer extends Component{
    constructor(props){
        super(props);
        this.state = {
            users: [{id: Date.now(), name: 'John'}]
        }
    }

    render(){
        return <div>
            <h1>Hello World</h1>
            <Users users={this.state.users}/>
        </div>;
    }
}
</code>```

And this is my Users.jsx class which renders User.jsx component

```<code>'user strict';
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import User from './User';

export default class Users extends Component{
    static get propTypes(){
        return {
            //validate users must be an array
            users: PropTypes.array
        }
    }

    constructor(props){
        super(props);
        this.state ={
            man: this.props
        }
    }

    render(){
        //get users from props
        const {users} = this.state.man;

        return (
            <div>
                <table>
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Name</th>
                        </tr>
                    </thead>
                    <tbody>
                        {
                            users.map((user) => {
                                return <User key={user.id} user={user}  />
                            })
                        }
                    </tbody>
                </table>
            </div>
        );
    }
}
</code>```

And this is my User.jsx where I guess values are not passing properly to the props

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

export default class User extends Component{
    constructor(props){
        super(props);
        this.state = {
            user: this.props
        }
    }

    render(){
        return(
                <tr>
                    <td>{this.state.user.id}</td>
                    <td>{this.state.user.name}</td>
                </tr>
        );
    }
}
</code>```

This is a screenshot of how my output looks like. (In outputs, the id and the name is not shown, only the  are shown as below:

Can anyone please tell me where I have done wrong? Thank you!

答:
You are saving your props to state, which is an object, doing this.state.user.name becomes undefined, do

Given props like key="34" user="objUser"

When you say user = this.props, user now becomes {key: 34, user: objUser}, to access those properties you can't user.name, you'll need to access user object, by doing user.user.name, because you have assigned the whole props object to user.

```<code>export default class User extends Component {

    constructor(props){
      super(props);
      this.state = {
        user: this.props.user
     }
   }
  // rest of the code
 }
</code>```

do the same in <Users />

```<code>export default class Users extends Component{
    static get propTypes(){
        return {
           //validate users must be an array
           users: PropTypes.array
        }
    }

    constructor(props){
        super(props);
        this.state ={
          man: this.props.users
        }
    }
   // rest of the code
  }
</code>```

Note

You don't really need to save the values in state, if the value is not going to change. You can access the value via props directly. like

```<code>render() {
   const user =  this.props.user
   const man = this.props.man
   // etc
}
</code>```

Title: How to pass ReactJS props properly?

Body:
I am trying to pass some values using props in ReactJS but, values are not passing not showing.

This is my html for the project:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>React JS</title>

and this is my main.jsx which renders a class named AppContainer component

'use strict';
import React from 'react';
import {render} from 'react-dom';
import AppContainer from './AppContainer';

render(<AppContainer />, document.getElementById('app'));

This is my AppContainer.jsx which renders Users.jsx component

'use strict';
import React, {Component} from 'react';
import Users from './Users';

export default class AppContainer extends Component{
    constructor(props){
        super(props);
        this.state = {
            users: [{id: Date.now(), name: 'John'}]
        }
    }

    render(){
        return

Hello World

            <Users users={this.state.users}/>

;
    }
}

And this is my Users.jsx class which renders User.jsx component

'user strict';
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import User from './User';

export default class Users extends Component{
    static get propTypes(){
        return {
            //validate users must be an array
            users: PropTypes.array
        }
    }

    constructor(props){
        super(props);
        this.state ={
            man: this.props
        }
    }

    render(){
        //get users from props
        const {users} = this.state.man;

        return (

                            ID
                            Name

                        {
                            users.map((user) => {
                                return <User key={user.id} user={user}  />
                            })
                        }

        );
    }
}

And this is my User.jsx where I guess values are not passing properly to the props

'use strict';
import React, {Component} from 'react';

export default class User extends Component{
    constructor(props){
        super(props);
        this.state = {
            user: this.props
        }
    }

    render(){
        return(

                    {this.state.user.id}
                    {this.state.user.name}

        );
    }
}

This is a screenshot of how my output looks like. (In outputs, the id and the name is not shown, only the  are shown as below:

Can anyone please tell me where I have done wrong? Thank you!

Body:
You are saving your props to state, which is an object, doing this.state.user.name becomes undefined, do

Given props like key="34" user="objUser"

When you say user = this.props, user now becomes {key: 34, user: objUser}, to access those properties you can't user.name, you'll need to access user object, by doing user.user.name, because you have assigned the whole props object to user.

export default class User extends Component {

    constructor(props){
      super(props);
      this.state = {
        user: this.props.user
     }
   }
  // rest of the code
 }

do the same in <Users />

export default class Users extends Component{
    static get propTypes(){
        return {
           //validate users must be an array
           users: PropTypes.array
        }
    }

    constructor(props){
        super(props);
        this.state ={
          man: this.props.users
        }
    }
   // rest of the code
  }

Note

You don't really need to save the values in state, if the value is not going to change. You can access the value via props directly. like

render() {
   const user =  this.props.user
   const man = this.props.man
   // etc
}


问:
Linear Regression in Pandas Groupby with freq='W-MON'
I have data over the timespan of over a year. I am interested in grouping the data by week, and getting the slope of two variables by week. Here is what the data looks like:

```<code>Date               | Total_Sales| Products
2015-12-30 07:42:50| 2900       | 24
2015-12-30 09:10:10| 3400       | 20
2016-02-07 07:07:07| 5400       | 25
2016-02-07 07:08:08| 1000       | 64
</code>```

So ideally I would like to perform a linear regression on total_sales and products on each week of this data and record the slope. This works when each week is represented in the data, but I have problems when there are some weeks skipped in the data. I know I could do this with turning the date into the week number but I feel like the result will be skewed because there is over a year's worth of data.

Here is the code I have so far:

```<code>df['Date']=pd.to_datetime(vals['EventDate']) - pd.to_timedelta(7,unit='d')
df.groupby(pd.Grouper(key='Week', freq='W-MON')).apply(lambda v: linregress(v.Total_Sales, v.Products)[0]).reset_index()
</code>```

However, I get the following error:

```<code>ValueError: Inputs must not be empty.
</code>```

I expect the output to look like this:

```<code>Date       | Slope
2015-12-28 | -0.008
2016-02-01 | -0.008
</code>```

答:
I assume this is happening because python is unable to groupby properly and also it is unable to recognise datetime as key ,as Date column has varying timestamp too.

Try the following code.It worked for me:

```<code>df['Date']=pd.to_datetime(df['Date'])  #### Converts Date column to Python Datetime

df['daysoffset'] = df['Date'].apply(lambda x: x.weekday())
#### Return the day of the week as an integer, where Monday is 0 and Sunday is 6.

df['week_start'] = df.apply(lambda x: x['Date'].date()-timedelta(days=x['daysoffset']), axis=1)
#### x.['Date'].date() removes timestamp and considers only Date
#### the line assigns date corresponding to last Monday to column 'week_start'.

df.groupby('week_start').apply(lambda v: stats.linregress(v.Total_Sales,v.Products)
[0]).reset_index()
</code>```

Body:
I have data over the timespan of over a year. I am interested in grouping the data by week, and getting the slope of two variables by week. Here is what the data looks like:

Date               | Total_Sales| Products
2015-12-30 07:42:50| 2900       | 24
2015-12-30 09:10:10| 3400       | 20
2016-02-07 07:07:07| 5400       | 25
2016-02-07 07:08:08| 1000       | 64

So ideally I would like to perform a linear regression on total_sales and products on each week of this data and record the slope. This works when each week is represented in the data, but I have problems when there are some weeks skipped in the data. I know I could do this with turning the date into the week number but I feel like the result will be skewed because there is over a year's worth of data.

Here is the code I have so far:

df['Date']=pd.to_datetime(vals['EventDate']) - pd.to_timedelta(7,unit='d')
df.groupby(pd.Grouper(key='Week', freq='W-MON')).apply(lambda v: linregress(v.Total_Sales, v.Products)[0]).reset_index()

However, I get the following error:

ValueError: Inputs must not be empty.

I expect the output to look like this:

Date       | Slope
2015-12-28 | -0.008
2016-02-01 | -0.008

Body:
I assume this is happening because python is unable to groupby properly and also it is unable to recognise datetime as key ,as Date column has varying timestamp too.

Try the following code.It worked for me:

df['Date']=pd.to_datetime(df['Date'])  #### Converts Date column to Python Datetime

df['daysoffset'] = df['Date'].apply(lambda x: x.weekday())
#### Return the day of the week as an integer, where Monday is 0 and Sunday is 6.

df['week_start'] = df.apply(lambda x: x['Date'].date()-timedelta(days=x['daysoffset']), axis=1)
#### x.['Date'].date() removes timestamp and considers only Date
#### the line assigns date corresponding to last Monday to column 'week_start'.

df.groupby('week_start').apply(lambda v: stats.linregress(v.Total_Sales,v.Products)
[0]).reset_index()


问:
UI Router: redirect to child state when navigating to abstract parent state
In my music app, I have an ng-repeat on the top-level states of my app to create navigation links. One of the top-level states, called library, is abstract and has child states (which are navigable using tabs). Since I am using an ng-repeat, the abstract state has a directive of ui-sref="library". However, it's not possible to navigate to an abstract parent state like that, instead I would need to write ui-sref="library.albums". I am unable to do this because of the ng-repeat data coming directly from the state provider. How can I set a default child state on "library" so that whenever that state is visited, it redirects to the child?

Here's a diagram of my setup:

答:
In V1.0 of ui-router, the state parameter redirectTo was added (see ui-router docs). This allows you to accomplish what you are looking for.

In your example you would not use abstract: true but would redirect to the library.albums state.

```<code>$stateProvider
    .state('library', {
        url: '/library',
        redirectTo: 'library.albums',
        template: '<ui-view></ui-view>',

    })
    .state('library.albums', {
        url: '/albums',
        template: '<h1>Albums</h1>'
    });
</code>```

with this you can use ui-sref="library". This is very helpful because ui-sref-active will now work.

Body:
In V1.0 of ui-router, the state parameter redirectTo was added (see ui-router docs). This allows you to accomplish what you are looking for.

In your example you would not use abstract: true but would redirect to the library.albums state.

$stateProvider
    .state('library', {
        url: '/library',
        redirectTo: 'library.albums',
        template: '<ui-view></ui-view>',

    })
    .state('library.albums', {
        url: '/albums',
        template: '<h1>Albums</h1>'
    });

with this you can use ui-sref="library". This is very helpful because ui-sref-active will now work.


答:
If you want to use forEach you need to have a variable being updated when you find a match. Array.forEach by default returns undefined. There is no build in way to break out of the forEach.

Since you are just looking for a simple element match simply use Array.includes:

let check = (arr, el) => arr.includes(el)

console.log(check([1, 2, 3, 4, 5], 3))```
</div>
</div>
</p>

<p>Array.some gives you an iterator function which in this case you really do not need.</p>

<p>With <code>Array.forEach</code>:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function check(arr, el) {
  let result = false
  arr.forEach((element) => {
    if (element === el) {
      result = true  // <-- update the result on match
    }
  })
  return result  // <-- return the result
}

console.log(check([1, 2, 3, 4, 5], 3))</code>```

Title: JavaScript: Use forEach to see if array contains a specific number value

Body:
If you want to use forEach you need to have a variable being updated when you find a match. Array.forEach by default returns undefined. There is no build in way to break out of the forEach.

Since you are just looking for a simple element match simply use Array.includes:

let check = (arr, el) => arr.includes(el)

console.log(check([1, 2, 3, 4, 5], 3))

Array.some gives you an iterator function which in this case you really do not need.

With Array.forEach:

function check(arr, el) {
  let result = false
  arr.forEach((element) => {
    if (element === el) {
      result = true  // <-- update the result on match
    }
  })
  return result  // <-- return the result
}

console.log(check([1, 2, 3, 4, 5], 3))