问:
Populate ComboBox with Enum in Delphi with MySQL
I have an Enum TRole

```<code>type
  TRole = (Admin, Common);
</code>```

In my database (MySQL), I have a table users with a column role of type INTEGER. I want to populate a ComboBox with the Roles in the following way:
The ComboBox should display "Administrator" in the role Admin and "Common User" in the role Common; when I save the value to the database, it should be save as 0 for the Admin role or 1 for the Common Role (their respective indexes).

Also, when displaying the role field, it should be displayed as the Strings showed above.

Can anyone please explain me how can I do that?

答:
You don't need TRole enums for this at all. Simply populate ComboBox with entries so that their index corresponds to database values (0 = Administrator; 1 = Common User). Also set Style property of ComboBox to csDropDownList.

```<code>procedure PopulateComboBox(const cb: TComboBox);
begin
  cb.Clear;
  cb.Items.Add('Administrator'); // ItemIndex = 0
  cb.Items.Add('Common User'); // ItemIndex = 1
end;
</code>```

Now when you get your data with SQL request you apply value of Role column directly to ItemIndex property of combobox:

```<code>Query.SQL.Text := 'select Name, Role from table where ID = :ID';
...
if Query.FieldByName('Role').AsInteger in [0..1] then
  RoleComboBox.ItemIndex := Query.FieldByName('Role').AsInteger
else
  raise Exception.Create('Role column value must be in range of 0..1');
</code>```

You do pretty much the same when you're saving role to database. Use ItemIndex property as value to be saved:

```<code>if RoleComboBox.ItemIndex in [0..1] then
begin
  ...
  Query.SQL.Text := 'update table set Role = :Role where ID = :ID';
  Query.ParamByName('Role').AsInteger := RoleComboBox.ItemIndex;
  Query.ExecSQL;
end
else
  raise Exception.Create('Invalid role index');
</code>```

Body:
I have an Enum TRole

type
  TRole = (Admin, Common);

In my database (MySQL), I have a table users with a column role of type INTEGER. I want to populate a ComboBox with the Roles in the following way:
The ComboBox should display "Administrator" in the role Admin and "Common User" in the role Common; when I save the value to the database, it should be save as 0 for the Admin role or 1 for the Common Role (their respective indexes).

Also, when displaying the role field, it should be displayed as the Strings showed above.

Can anyone please explain me how can I do that?

Body:
You don't need TRole enums for this at all. Simply populate ComboBox with entries so that their index corresponds to database values (0 = Administrator; 1 = Common User). Also set Style property of ComboBox to csDropDownList.

procedure PopulateComboBox(const cb: TComboBox);
begin
  cb.Clear;
  cb.Items.Add('Administrator'); // ItemIndex = 0
  cb.Items.Add('Common User'); // ItemIndex = 1
end;

Now when you get your data with SQL request you apply value of Role column directly to ItemIndex property of combobox:

Query.SQL.Text := 'select Name, Role from table where ID = :ID';
...
if Query.FieldByName('Role').AsInteger in [0..1] then
  RoleComboBox.ItemIndex := Query.FieldByName('Role').AsInteger
else
  raise Exception.Create('Role column value must be in range of 0..1');

You do pretty much the same when you're saving role to database. Use ItemIndex property as value to be saved:

if RoleComboBox.ItemIndex in [0..1] then
begin
  ...
  Query.SQL.Text := 'update table set Role = :Role where ID = :ID';
  Query.ParamByName('Role').AsInteger := RoleComboBox.ItemIndex;
  Query.ExecSQL;
end
else
  raise Exception.Create('Invalid role index');


来源: stackexchange

问:
Reusable summary_fields getter Silverstripe
I have a couple of Time datatypes in my summary_fields array that I'd like to modify with the same getter method, but it doesn't seem possible to pass properties to them. My original thought was:

class BusinessHour extends DataObject {

    private static $db = array(
        'Title' => 'Varchar(9)',
        'Day' => 'Enum("Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday", "Monday")',
        'Open' => 'Time',
        'Close' => 'Time',
        'Closed' => 'Boolean'
    );

    private static $summary_fields = array(
        'Day' => 'Day',
        'OpenClose(Open)' => 'Open',
        'OpenClose(Close)' => 'Close'
    );

    public function getOpenClose($val) {
        if($val == FALSE) {
             return "Closed";
        }else {
             return $val;
        }
    }
}
```

<p>I'm assuming I can extend the Time datatype and use it like this:</p>

<pre class="lang-php prettyprint-override"><code>private static $summary_fields = array(
    'Open.OpenClose' => 'Open',
    'Close.OpenClose' => 'Close'
);
</code>```

But is this the right way to about this?

答:
I suggest you add the desired functionality via Extension to the Time DBField. Your extension could be something like:

```<code>class TimeExtension extends Extension
{
    public function OpenClose(){
        $val = $this->owner->getValue();
        return $val ? $val : 'Closed';
    }
}
</code>```

Then you add the extension via YAML (eg. in _config.yml)

```<code>Time
  extensions:
    - TimeExtension
</code>```

You should then be able to use something like this as your summary_fields:

```<code>private static $summary_fields = [
    'Open.OpenClose' => 'Open',
    'Close.OpenClose' => 'Close'
];
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a couple of Time datatypes in my summary_fields array that I'd like to modify with the same getter method, but it doesn't seem possible to pass properties to them. My original thought was:

class BusinessHour extends DataObject {

    private static $db = array(
        'Title' => 'Varchar(9)',
        'Day' => 'Enum("Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday", "Monday")',
        'Open' => 'Time',
        'Close' => 'Time',
        'Closed' => 'Boolean'
    );

    private static $summary_fields = array(
        'Day' => 'Day',
        'OpenClose(Open)' => 'Open',
        'OpenClose(Close)' => 'Close'
    );

    public function getOpenClose($val) {
        if($val == FALSE) {
             return "Closed";
        }else {
             return $val;
        }
    }
}

I'm assuming I can extend the Time datatype and use it like this:

private static $summary_fields = array(
    'Open.OpenClose' => 'Open',
    'Close.OpenClose' => 'Close'
);

But is this the right way to about this?

Body:
I suggest you add the desired functionality via Extension to the Time DBField. Your extension could be something like:

class TimeExtension extends Extension
{
    public function OpenClose(){
        $val = $this->owner->getValue();
        return $val ? $val : 'Closed';
    }
}

Then you add the extension via YAML (eg. in _config.yml)

Time
  extensions:
    - TimeExtension

You should then be able to use something like this as your summary_fields:

private static $summary_fields = [
    'Open.OpenClose' => 'Open',
    'Close.OpenClose' => 'Close'
];


问:
What is the most performant 2D graphics engine for use with Android?
I have managed to make a hello world JBox2D application, and it works (I have some bouncing balls). However, I just read a comment on a forum post, which claims that JBox2D produces a lot of garbage, and so causes animation to be poor. Is this true?

If yes, then what other 2D engines are available to me? I would very much like to use a physics engine for my 2D game, even if it's just a very simple one.

Update:

Just tried running the JBox2D bouncing balls demo on my phone, and the performance was terrible. Looks like libgdx is the way to go for physics, since I think it comes with a  native version of Box2D that works well on Android. As for AndEngine, this is a game engine and not a physics engine, but I may use it in conjunction with libgdx to give myself a head start.

Update 2:

I've had a quick play with libgdx and AndEngine. I've found that they're both Android game engines, but AndEngine has a less steep learing curve at the cost of being more limiting. So if you want to build a serious game, you probably want to use libgdx as it will allow you to do more (but is harder to use).

答: Have you seen AndEngine? You can take a look at this app: Farm Tower. They used AndEngine to write it, and it uses physics.</p>

ContentLicense: CC BY-SA 2.5


问:
Kotlin top-level function scopes & shadowing
Let's say I write a Kotlin package containing the following code:

```<code>package CoolWithATwist

// code that solves the TSP in linear time followed by this:

fun <T> println(x: T) {
    kotlin.io.println(x)
    haltAndCatchFire()  // or any annoying/destructive function
}
</code>```

Should the package be distributed in bytecode form, am I correct in assuming that Kotlin's rules on default importing of standard library modules as per the documentation and that subsequently importing another module such as CoolWithATwist will in fact shadow the standard library auto-included println function and thus the above code will execute should the user actually call println?

What is the best way of detecting this since Kotlin compiler doesn't warn about shadowing global functions or about having to explicitly name which function you're actually calling, nor does the Kotlin plugin on IntelliJ Idea (as of version 1.1.3) or, to the best of my Knowledge, Android Studio, say anything about it?

答:
let's say you have the following classes in your source folders:

```<code>kotlin
|
|---- CoolWithATwist
|        |
|        |--- function.kt which contains your own println() function
|        |
|        |--- test1.kt (no imports)
|        |
|        |--- test2.kt (import kotlin.io.println)
|        |
|        |--- test.kt (import kotlin.io.*)
|        |
|        |___ NestedPackage
|                   |
|                   |___ test3.kt (no imports)
|
|____ main.kt
</code>```

the main.kt, test2.kt and test3.kt will using kotlin.io.println directly.

the test1.kt will using the package top-level function println.

the test.kt will using the package top-level function println since the star import statement priority is lower than package top-level scope.

which means the function find strategy in kotlin is not bubbled, only find the top-level function in itself package. and the find strategy order is:  local > enclosing > function > class > script > import statement > package top-level > star import statement > kotlin top-level.

you can simply using CTRL+B/CTRL+ALT+B/F4 at the call-site function, then you can jump to the source code which the function was actually called,for example:

```<code>fun foo(){
   println("bar");
   // ^--- move the cursor here and press `CTRL+B`/`CTRL+ALT+B`/`F4`
}
</code>```

Body:
Let's say I write a Kotlin package containing the following code:

package CoolWithATwist

// code that solves the TSP in linear time followed by this:

fun <T> println(x: T) {
    kotlin.io.println(x)
    haltAndCatchFire()  // or any annoying/destructive function
}

Should the package be distributed in bytecode form, am I correct in assuming that Kotlin's rules on default importing of standard library modules as per the documentation and that subsequently importing another module such as CoolWithATwist will in fact shadow the standard library auto-included println function and thus the above code will execute should the user actually call println?

What is the best way of detecting this since Kotlin compiler doesn't warn about shadowing global functions or about having to explicitly name which function you're actually calling, nor does the Kotlin plugin on IntelliJ Idea (as of version 1.1.3) or, to the best of my Knowledge, Android Studio, say anything about it?

Body:
let's say you have the following classes in your source folders:

kotlin
|
|---- CoolWithATwist
|        |
|        |--- function.kt which contains your own println() function
|        |
|        |--- test1.kt (no imports)
|        |
|        |--- test2.kt (import kotlin.io.println)
|        |
|        |--- test.kt (import kotlin.io.*)
|        |
|        |___ NestedPackage
|                   |
|                   |___ test3.kt (no imports)
|
|____ main.kt

the main.kt, test2.kt and test3.kt will using kotlin.io.println directly.

the test1.kt will using the package top-level function println.

the test.kt will using the package top-level function println since the star import statement priority is lower than package top-level scope.

which means the function find strategy in kotlin is not bubbled, only find the top-level function in itself package. and the find strategy order is:  local > enclosing > function > class > script > import statement > package top-level > star import statement > kotlin top-level.

you can simply using CTRL+B/CTRL+ALT+B/F4 at the call-site function, then you can jump to the source code which the function was actually called,for example:

fun foo(){
   println("bar");
   // ^--- move the cursor here and press `CTRL+B`/`CTRL+ALT+B`/`F4`
}


问:
Rails: Order with nulls last
In my Rails app I've run into an issue a couple times that I'd like to know how other people solve:

I have certain records where a value is optional, so some records have a value and some are null for that column.

If I order by that column on some databases the nulls sort first and on some databases the nulls sort last.

For instance, I have Photos which may or may not belong to a Collection, ie there are some Photos where collection_id=nil and some where collection_id=1 etc.

If I do Photo.order('collection_id desc) then on SQLite I get the nulls last but on PostgreSQL I get the nulls first.

Is there a nice, standard Rails way to handle this and get consistent performance across any database?

答:
Even though it's 2017 now, there is still yet to be a consensus on whether NULLs should take precedence. Without you being explicit about it, your results are going to vary depending on the DBMS.

The standard doesn't specify how NULLs should be ordered in comparison with non-NULL values, except that any two NULLs are to be considered equally ordered, and that NULLs should sort either above or below all non-NULL values.

source, comparison of most DBMSs

To illustrate the problem, I compiled a list of a few most popular cases when it comes to Rails development:

PostgreSQL

NULLs have the highest value.

By default, null values sort as if larger than any non-null value.

source: PostgreSQL documentation

MySQL

NULLs have the lowest value.

When doing an ORDER BY, NULL values are presented first if you do ORDER BY ... ASC and last if you do ORDER BY ... DESC.

source: MySQL documentation

SQLite

NULLs have the lowest value.

A row with a NULL value is higher than rows with regular values in ascending order, and it is reversed for descending order.

source

Solution

Unfortunately, Rails itself doesn't provide a solution for it yet.

PostgreSQL specific

For PostgreSQL you could quite intuitively use:

Photo.order('collection_id DESC NULLS LAST') # NULLs come last

MySQL specific

For MySQL, you could put the minus sign upfront, yet this feature seems to be undocumented. Appears to work not only with numerical values, but with dates as well.

Photo.order('-collection_id DESC') # NULLs come last

PostgreSQL and MySQL specific

To cover both of them, this appears to work:

Photo.order('collection_id IS NULL, collection_id DESC') # NULLs come last

Still, this one does not work in SQLite.

Universal solution

To provide cross-support for all DBMSs you'd have to write a query using CASE, already suggested by @PhilIT:

Photo.order('CASE WHEN collection_id IS NULL THEN 1 ELSE 0 END, collection_id')

which translates to first sorting each of the records first by CASE results (by default ascending order, which means NULL values will be the last ones), second by calculation_id.

Title: Rails: Order with nulls last


问:
Do you know why the plot-screen don't appear on the pie charm?
Now, I use pycharm as python-IDE. When I use imshow() from matplotlib, the function works well,but the plot-screen don't appear.
the plot-screen appear on jupyter notebook.</p>

```<code>import numpy as np

image = np.array([[[[1],[2],[3]],
                   [[4],[5],[6]],
                   [[7],[8],[9]]]], dtype=np.float32)
print(image.shape)
plt.imshow(image.reshape(3,3), cmap='Greys')
</code>```

答:
I think you're missing a line from your question from matplotlib import pyplot as plt. Try adding the line plt.show(). Interestingly when I run this from the PyCharm command line I don't need the line, but when I run it in a script I do. I also need the extra line when I run from the linux command line.

```<code>import numpy as np
from matplotlib import pyplot as plt

image = np.array([[[[1],[2],[3]],
                   [[4],[5],[6]],
                   [[7],[8],[9]]]], dtype=np.float32)
print(image.shape)
plt.imshow(image.reshape(3,3), cmap='Greys')
plt.show()
</code>```

Body:
Now, I use pycharm as python-IDE. When I use imshow() from matplotlib, the function works well,but the plot-screen don't appear.
the plot-screen appear on jupyter notebook.

import numpy as np

image = np.array([[[[1],[2],[3]],
                   [[4],[5],[6]],
                   [[7],[8],[9]]]], dtype=np.float32)
print(image.shape)
plt.imshow(image.reshape(3,3), cmap='Greys')

Body:
I think you're missing a line from your question from matplotlib import pyplot as plt. Try adding the line plt.show(). Interestingly when I run this from the PyCharm command line I don't need the line, but when I run it in a script I do. I also need the extra line when I run from the linux command line.

import numpy as np
from matplotlib import pyplot as plt

image = np.array([[[[1],[2],[3]],
                   [[4],[5],[6]],
                   [[7],[8],[9]]]], dtype=np.float32)
print(image.shape)
plt.imshow(image.reshape(3,3), cmap='Greys')
plt.show()


问:
jQuery - check if all mandatory fields in a section have been answered
I need to run a check on a lightbox popUp to see if all fields that are not optional have been input.

HTML

```<code><div id="manualAddressEntry01" class="container popUp large hidden shadow02 rounded03">
    <div class="popUpHeading">
        <h4>Please enter your full address:</h4>
    </div>
    <div class="popUpContent rounded03">
        <img class="closeContainer cursor" src="resource/nw/images/hires/helpClose.gif"/>
        <div class="fl">
            <label for="form_popup1_HouseName">House Number/Name</label>
            <input class="jsValid_required" id="form_popup1_HouseName" type="text" size="25"/>
        </div>

        <div class="fl" style="padding-left:10px">
            <label for="form_popup1_Street">Street</label>
            <input class="jsValid_required" id="form_popup1_Street" type="text" size="25"/>
        </div>

        <br class="cb"/>

        <input id="form_popup1_AddressLine2" type="text" size="35"/>

        <label for="form_popup1_TownCity">Town/City</label>
        <input class="jsValid_alpha" id="form_popup1_TownCity" type="text" size="35"/>

        <label for="form_popup1_County">County</label>
        <input class="jsValid_alpha jsOptional countyInput" id="form_popup1_County" name="text" type="text" size="35"/>

        <label for="form_popup2_Country">Country</label>
        <select class="countrySelect" name="select" id="form_popup1_CountryList">
            <option value="AF">Afghanistan</option>
            <option value="AL">Albania</option>
        </select>

        <label for="form_p">Postcode</label>
        <input class="jsOptional" id="form_popup1_PostCode" type="text" size="10" maxlength="8"/>
        <img class="cursor submit confirmAllInputs" src="confirmBTN2.gif" id="confirmManualAddressEntry01" style="margin-bottom:-5px;"/>
        <br/>
    </div>
</div>
</code>```

What I need to do
I could go the long way round and check each input field by id, and replicate this, changing id's for each pop up in this format - but I want to write some jQuery that when the ".confirmAllInputs" button at the bottom of the pop up is clicked, it finds all input fields within that ".container" that do not have the class jsOptional, and check if these have all been input.  If not, an error message should be displayed, otherwise, it's all accepted.

I've attempted a few things. The closest I got was :

```<code>$('.confirmAllInputs').click(function(){
    var container = $(this).parents('.container');
    var optionalFields = (container.find('input[class!=jsOptional]').val());
    $(container).each(function(i){
       alert('These are the value of the fields: ' + optionalFields);
    });
});
</code>```

But this only reports back the first fields value. I need to cycle through all and check they are not empty.

答:
```<code>$('.confirmAllInputs').click(function(){
    var container = $(this).parents('.container');
    var optionalFields = (container.find('input[class!=jsOptional]').val());
  var szMessage = "";
    $(container).each(function(i){
       szMessage += <YOUR_MESSAGE> ;
    }
  alert(szMessage);
 );
</code>```

Body:
I need to run a check on a lightbox popUp to see if all fields that are not optional have been input.

HTML

Please enter your full address:

            House Number/Name
            <input class="jsValid_required" id="form_popup1_HouseName" type="text" size="25"/>

            Street
            <input class="jsValid_required" id="form_popup1_Street" type="text" size="25"/>

        <input id="form_popup1_AddressLine2" type="text" size="35"/>

        Town/City
        <input class="jsValid_alpha" id="form_popup1_TownCity" type="text" size="35"/>

        County
        <input class="jsValid_alpha jsOptional countyInput" id="form_popup1_County" name="text" type="text" size="35"/>

        Country
        <select class="countrySelect" name="select" id="form_popup1_CountryList">
            <option value="AF">Afghanistan</option>
            <option value="AL">Albania</option>
        </select>

        Postcode
        <input class="jsOptional" id="form_popup1_PostCode" type="text" size="10" maxlength="8"/>

What I need to do
I could go the long way round and check each input field by id, and replicate this, changing id's for each pop up in this format - but I want to write some jQuery that when the ".confirmAllInputs" button at the bottom of the pop up is clicked, it finds all input fields within that ".container" that do not have the class jsOptional, and check if these have all been input.  If not, an error message should be displayed, otherwise, it's all accepted.

I've attempted a few things. The closest I got was :

$('.confirmAllInputs').click(function(){
    var container = $(this).parents('.container');
    var optionalFields = (container.find('input[class!=jsOptional]').val());
    $(container).each(function(i){
       alert('These are the value of the fields: ' + optionalFields);
    });
});

But this only reports back the first fields value. I need to cycle through all and check they are not empty.


问:
React do not render new components, new webpack setup
Today I was setting up my first Webpack Bebel React project and I got some strange case here.I don't know why, but every single Component that I make is not recognized by React. I can see it directly in the inspector, and It seems like it's not getting compiled. All standard HTML elements are getting rendered. Even console.log inside of constructor function of a component that I have created is not called. I run Hot mode with webpack -p

Here is my Webpack config:

```<code>    const ExtractTextPlugin = require('extract-text-webpack-plugin')
const webpack = require('webpack')
const path = require('path')

const isProduction = process.env.NODE_ENV === 'production'
const cssDeveloperLoaders = ['style-loader', 'css-loader', 'sass-loader']
const cssProduction = ExtractTextPlugin.extract({
    fallback: 'style-loader',
    loader: ['css-loader', 'sass-loader'],
    publicPath: '/dist'
})

const cssConfig = isProduction ? cssProduction : cssDeveloperLoaders

module.exports = {
    entry: {
        app: './src/app.jsx'
    },
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].bundle.js'
    },
    module: {
        rules: [
            {
                test: /\.scss$/,
                use: cssConfig
            },
            {
                test: /\.jsx$/,
                exclude: path.resolve(__dirname + '/node_modules/'),
                use: 'babel-loader',
                query: {
                    presents: ['es2015','react']
                }
            }
        ]
    },
    devServer: {
        contentBase: path.join(__dirname, 'dist'),
        compress: true,
        hot: true,
        open: true,
        openPage: ''                    //Fix to webpack version 3.0.0 after removing redirection to /undefined
    },
    plugins: [
        new ExtractTextPlugin({
            filename: 'app.css',
            disable: !isProduction,     //So if production is running it will generate file otherwise not
            allChunks: true
        }),
        new webpack.HotModuleReplacementPlugin(),
        new webpack.NamedModulesPlugin()
    ]
}
</code>```

My .bablerc

```<code>{
    "presets": [
        "es2015",
        "react"
    ]
}
</code>```

App.jsx:

```<code>import './app.scss'

import React from 'react';
import { render } from 'react-dom';

import engine from './engine.jsx'

render(
    <engine/>,
    document.getElementById('root')
);
</code>```

engine.jsx

```<code>import React from 'react';

class engine extends React.Component{
    constructor(){
        super();
        console.log('Component has been constructed ')
    }
    render(){
        return(
            <div>xD</div>
        )
    }
}
export default engine;
</code>```

The picture of React Chrome extension.

Please notice, console.log is not been called.

My html is empty, I see only engine element (Not compiled.)

Any suggestions about this problem?

HTML:

```<code>    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
<div id="root"></div>
<script src="app.bundle.js"></script>
</body>
</html>
</code>```

答:
In your webpack config file add

resolve : {
       extensions: [".js", ".jsx"]
      }

So that you won't need to import your jsx file with extenstion.

Class names should start with Capital letters otherwise methods in react components will not be invoked and also no error will be thrown.

engine.jsx

```<code>    class Engine extends React.Component{
        constructor(){
            super();
            console.log('Component has been constructed ')
        }
        render(){
            return(
                <div>xD</div>
            )
        }
    }

export default Engine;
</code>```

App.jsx

```<code>import Engine from './engine'
render(
    <Engine/>,
    document.getElementById('root')
);
</code>```

Please verify  https://codesandbox.io/s/D9rpvWWG6
Also you can refer https://github.com/facebook/react/issues/4695

Body:
Today I was setting up my first Webpack Bebel React project and I got some strange case here.I don't know why, but every single Component that I make is not recognized by React. I can see it directly in the inspector, and It seems like it's not getting compiled. All standard HTML elements are getting rendered. Even console.log inside of constructor function of a component that I have created is not called. I run Hot mode with webpack -p

Here is my Webpack config:

    const ExtractTextPlugin = require('extract-text-webpack-plugin')
const webpack = require('webpack')
const path = require('path')

const isProduction = process.env.NODE_ENV === 'production'
const cssDeveloperLoaders = ['style-loader', 'css-loader', 'sass-loader']
const cssProduction = ExtractTextPlugin.extract({
    fallback: 'style-loader',
    loader: ['css-loader', 'sass-loader'],
    publicPath: '/dist'
})

const cssConfig = isProduction ? cssProduction : cssDeveloperLoaders

module.exports = {
    entry: {
        app: './src/app.jsx'
    },
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].bundle.js'
    },
    module: {
        rules: [
            {
                test: /\.scss$/,
                use: cssConfig
            },
            {
                test: /\.jsx$/,
                exclude: path.resolve(__dirname + '/node_modules/'),
                use: 'babel-loader',
                query: {
                    presents: ['es2015','react']
                }
            }
        ]
    },
    devServer: {
        contentBase: path.join(__dirname, 'dist'),
        compress: true,
        hot: true,
        open: true,
        openPage: ''                    //Fix to webpack version 3.0.0 after removing redirection to /undefined
    },
    plugins: [
        new ExtractTextPlugin({
            filename: 'app.css',
            disable: !isProduction,     //So if production is running it will generate file otherwise not
            allChunks: true
        }),
        new webpack.HotModuleReplacementPlugin(),
        new webpack.NamedModulesPlugin()
    ]
}

My .bablerc

{
    "presets": [
        "es2015",
        "react"
    ]
}

App.jsx:

import './app.scss'

import React from 'react';
import { render } from 'react-dom';

import engine from './engine.jsx'

render(
    <engine/>,
    document.getElementById('root')
);

engine.jsx

import React from 'react';

class engine extends React.Component{
    constructor(){
        super();
        console.log('Component has been constructed ')
    }
    render(){
        return(

xD

        )
    }
}
export default engine;

The picture of React Chrome extension.

Please notice, console.log is not been called.

My html is empty, I see only engine element (Not compiled.)

Any suggestions about this problem?

HTML:

    <!DOCTYPE html>

    <meta charset="UTF-8">
    <title></title>
    <link rel="stylesheet" href="style.css">

Body:
In your webpack config file add

resolve : {
       extensions: [".js", ".jsx"]
      }

So that you won't need to import your jsx file with extenstion.

Class names should start with Capital letters otherwise methods in react components will not be invoked and also no error will be thrown.

engine.jsx

    class Engine extends React.Component{
        constructor(){
            super();
            console.log('Component has been constructed ')
        }
        render(){
            return(
                <div>xD</div>
            )
        }
    }

export default Engine;

App.jsx

import Engine from './engine'
render(
    <Engine/>,
    document.getElementById('root')
);

Please verify  https://codesandbox.io/s/D9rpvWWG6
Also you can refer https://github.com/facebook/react/issues/4695


问:
TypeError when calling document.getElementById
the following code should display the word Test...but instead the message TypeError: document.getElementById(...) is displayed.
I can't figure out why:

```<code><html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Testtree</title>
  </head>
  <script>
    document.getElementById("kaptree").innerHTML="TEST";
  </script>
  <body>
     <div id="kaptree"></div>
  </body>
</html>
</code>```

Can anyone help me to open my eyes?

答:
Sometimes the solution is so simple.

I will put the function call into a:

```<code>$( document ).ready(function() {

});
</code>```

Body:
the following code should display the word Test...but instead the message TypeError: document.getElementById(...) is displayed.
I can't figure out why:

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Testtree</title>

Can anyone help me to open my eyes?

Body:
Sometimes the solution is so simple.

I will put the function call into a:

$( document ).ready(function() {

});


问:
Rails 5 not saving data
After bashing away at this for two days, I'm completely stumped. I can't seem to save any data for any models that include this (outlined below) or anything I added afterward.

I have a migration that looks like this:

```<code>class CreateScenarios < ActiveRecord::Migration[5.1]
 def change
  create_table :scenarios do |t|
  t.string :title
  t.text :description
  t.string :scenariotype
  t.references :activity, foreign_key: true
  t.timestamps
   end
 end
end
</code>```

My schema:

```<code>create_table "scenarios", force: :cascade do |t|
t.string "title"
t.text "description"
t.string "scenariotype"
t.bigint "activity_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["activity_id"], name: "index_scenarios_on_activity_id"
end
</code>```

Model looks like this:

```<code>class Scenario < ApplicationRecord
  has_many :pages
  belongs_to :activities
end
</code>```

In my controller, I have these params set:

```<code>def scenario_params
  params.require(:scenario).permit(:title, :description, :scenariotype, :activity_id)
end
</code>```

The new method looks like this:

```<code>def new
   @scenario = Scenario.new
   @activity = Activity.find(params[:activity])
end
</code>```

And the create method looks like this:

```<code>def create
   @scenario = Scenario.new(scenario_params)
   @activity = Activity.find(@scenario.activity_id)
   @scenario.save
   redirect_to new_page_path(scenario: @scenario.id)
end
</code>```

When I try to save a record, even in the console, from this migration or any later migrations, it won't save and rolls back because it isn't autoincrementing. So running something like this:

```<code>scenario=Scenario.new(:activity_id =>1, :title =>"asfdasdf", :scenariotype=>"Teaching", :description=>"asdfadsf")
</code>```

results in something like this

```<code><Scenario id: nil, title: "asfdasdf", description: "asdfadsf", scenariotype: "Teaching", activity_id: 1, created_at: nil, updated_at: nil>
</code>```

And then it rolls back because it's missing an id.

I've dropped and recreated the databases. I thought something might be wrong with a previous migration, but those both work just fine. I'm hoping I'm missing something incredibly straightforward and stupid, but I'm just not seeing it. Database is Postgres.

Thanks in advance for any help anyone can provide.

答:
You have mistake in your Scenario model - when setting belongs_to association, singular form should be used. So instead of belongs_to :activities your model should look like:

```<code>class Scenario < ApplicationRecord
  has_many :pages
  belongs_to :activity
end
</code>```

Title: Rails 5 not saving data

Body:
After bashing away at this for two days, I'm completely stumped. I can't seem to save any data for any models that include this (outlined below) or anything I added afterward.

I have a migration that looks like this:

class CreateScenarios < ActiveRecord::Migration[5.1]
 def change
  create_table :scenarios do |t|
  t.string :title
  t.text :description
  t.string :scenariotype
  t.references :activity, foreign_key: true
  t.timestamps
   end
 end
end

My schema:

create_table "scenarios", force: :cascade do |t|
t.string "title"
t.text "description"
t.string "scenariotype"
t.bigint "activity_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["activity_id"], name: "index_scenarios_on_activity_id"
end

Model looks like this:

class Scenario < ApplicationRecord
  has_many :pages
  belongs_to :activities
end

In my controller, I have these params set:

def scenario_params
  params.require(:scenario).permit(:title, :description, :scenariotype, :activity_id)
end

The new method looks like this:

def new
   @scenario = Scenario.new
   @activity = Activity.find(params[:activity])
end

And the create method looks like this:

def create
   @scenario = Scenario.new(scenario_params)
   @activity = Activity.find(@scenario.activity_id)
   @scenario.save
   redirect_to new_page_path(scenario: @scenario.id)
end

When I try to save a record, even in the console, from this migration or any later migrations, it won't save and rolls back because it isn't autoincrementing. So running something like this:

scenario=Scenario.new(:activity_id =>1, :title =>"asfdasdf", :scenariotype=>"Teaching", :description=>"asdfadsf")

results in something like this

<Scenario id: nil, title: "asfdasdf", description: "asdfadsf", scenariotype: "Teaching", activity_id: 1, created_at: nil, updated_at: nil>

And then it rolls back because it's missing an id.

I've dropped and recreated the databases. I thought something might be wrong with a previous migration, but those both work just fine. I'm hoping I'm missing something incredibly straightforward and stupid, but I'm just not seeing it. Database is Postgres.

Thanks in advance for any help anyone can provide.

Body:
You have mistake in your Scenario model - when setting belongs_to association, singular form should be used. So instead of belongs_to :activities your model should look like:

class Scenario < ApplicationRecord
  has_many :pages
  belongs_to :activity
end


问:
NameError: name 'classname' is not defined error in python
I was working on a python program. I have created a class named "Perception". The code is given below:

import numpy as np
class Perceptron(object):

    def __init__(self, eta=0.01, n_iter=10):
        self.eta=eta
        self.n_iter=n_iter

    def fit(self, X, y):
        self.w_=np.zeros(1+X.shape[1])
        self.errors_ = []

        for _ in range(self.n_iter):
            errors =0
            for xi,target in zip(X,y):
                update = self.eta * (target - self.predict(xi))
                self.w_[1:] += update * xi
                self.w_[0] += update
                errors += int(update != 0.0)
            self.errors_.append(errors)
        return self

    def net_input(self, X):
        """Calculate net input"""
        return np.dot(X, self.w_[1:]) + self.w_[0]

    def predict(self, X):
        """Return class label after unit step"""
        return np.where(self.net_input(X) >= 0.0, 1, -1)```
</div>
</div>
</p>

<p>when i want to declare the class in the following line: </p>

```ppn = Perceptron(eta=0.1, n_iter=10)
```

I get the following error:

NameError: name 'Perceptron' is not defined

I am new to Python. Please help me in the next steps. And Thanks in advance.

答:
```<code>Run this it should work , if not share the screen hot of code and output.
import numpy as np
class Perceptron(object):

    def __init__(self, eta=0.01, n_iter=10):
        self.eta=eta
        self.n_iter=n_iter

    def fit(self, X, y):
        self.w_=np.zeros(1+X.shape[1])
        self.errors_ = []

        for _ in range(self.n_iter):
            errors =0
            for xi,target in zip(X,y):
                update = self.eta * (target - self.predict(xi))
                self.w_[1:] += update * xi
                self.w_[0] += update
                errors += int(update != 0.0)
            self.errors_.append(errors)
        return self

    def net_input(self, X):
        """Calculate net input"""
        return np.dot(X, self.w_[1:]) + self.w_[0]

    def predict(self, X):
        """Return class label after unit step"""
        return np.where(self.net_input(X) >= 0.0, 1, -1)

ppn = Perceptron(eta=0.1, n_iter=10)
</code>```

Body:
I was working on a python program. I have created a class named "Perception". The code is given below:

import numpy as np
class Perceptron(object):

    def __init__(self, eta=0.01, n_iter=10):
        self.eta=eta
        self.n_iter=n_iter

    def fit(self, X, y):
        self.w_=np.zeros(1+X.shape[1])
        self.errors_ = []

        for _ in range(self.n_iter):
            errors =0
            for xi,target in zip(X,y):
                update = self.eta * (target - self.predict(xi))
                self.w_[1:] += update * xi
                self.w_[0] += update
                errors += int(update != 0.0)
            self.errors_.append(errors)
        return self

    def net_input(self, X):
        """Calculate net input"""
        return np.dot(X, self.w_[1:]) + self.w_[0]

    def predict(self, X):
        """Return class label after unit step"""
        return np.where(self.net_input(X) >= 0.0, 1, -1)

when i want to declare the class in the following line:

ppn = Perceptron(eta=0.1, n_iter=10)

I get the following error:

NameError: name 'Perceptron' is not defined

I am new to Python. Please help me in the next steps. And Thanks in advance.


问:
How to parallelize computation of pairwise distance matrix?
My problem is roughly as follows. Given a numerical matrix X, where each row is an item. I want to find each row's nearest neighbor in terms of L2 distance in all rows except itself. I tried reading the official documentation but was still a little confused about how to achieve this. Could someone give me some hint?

My code is as follows

```<code>function l2_dist(v1, v2)
    return sqrt(sum((v1 - v2) .^ 2))
end

function main(Mat, dist_fun)
    n = size(Mat, 1)

    Dist = SharedArray{Float64}(n) #[Inf for i in 1:n]
    Id = SharedArray{Int64}(n) #[-1 for i in 1:n]
    @parallel for i = 1:n
        Dist[i] = Inf
        Id[i] = 0
    end
    Threads.@threads for i in 1:n
        for j in 1:n
            if i != j
                println(i, j)
                dist_temp = dist_fun(Mat[i, :], Mat[j, :])
                if dist_temp < Dist[i]
                    println("Dist updated!")
                    Dist[i] = dist_temp
                    Id[i] = j
                end
            end
        end
    end
    return Dict("Dist" => Dist, "Id" => Id)
end

n = 4000
p = 30

X = [rand() for i in 1:n, j in 1:p];

main(X[1:30, :], l2_dist)
@time N = main(X, l2_dist)
</code>```

I'm trying to distributed all the i's (i.e. calculating each row minimum) over different cores. But the version above apparently isn't working correctly. It is even slower than the sequential version. Can someone point me to the right direction? Thanks.

答:
Maybe you're doing something in addition to what you have written down, but, at this point from what I can see, you aren't actually doing any computations in parallel. Julia requires you to tell it how many processors (or threads) you would like it to have access to. You can do this through either

Starting Julia with multiple processors julia -p # (where # is the number of processors you want Julia to have access to)

Once you have started a Julia "session" you can call the addprocs function to add additional processors.

To have more than 1 thread, you need to run command export JULIA_NUM_THREADS = #. I don't know very much about threading, so I will be sticking with the @parallel macro. I suggest reading documentation for more details on threading -- Maybe @Chris Rackauckas could expand a little more on the difference.

A few comments below about my code and on your code:

I'm on version 0.6.1-pre.0. I don't think I'm doing anything 0.6 specific, but this is a heads up just in case.

I'm going to use the Distances.jl package when computing the distances between vectors. I think it is a good habit to farm out as many of my computations to well-written and well-maintained packages as possible.

Rather than compute the distance between rows, I'm going to compute the distance between columns. This is because Julia is a column-major language, so this will increase the number of cache hits and give a little extra speed. You can obviously get the row-wise results you want by just transposing the input.

Unless you expect to have that many memory allocations then that many allocations are a sign that something in your code is inefficient. It is often a type stability problem. I don't know if that was the case in your code before, but that doesn't seem to be an issue in the current version (it wasn't immediately clear to me why you were having so many allocations).

Code is below

```<code># Make sure all processors have access to Distances package
@everywhere using Distances

# Create a random matrix
nrow = 30
ncol = 4000

# Seed creation of random matrix so it is always same matrix
srand(42)
X = rand(nrow, ncol)

function main(X::AbstractMatrix{Float64}, M::Distances.Metric)
    # Get size of the matrix
    nrow, ncol = size(X)

    # Create `SharedArray` to store output
    ind_vec = SharedArray{Int}(ncol)
    dist_vec = SharedArray{Float64}(ncol)

    # Compute the distance between columns
    @sync @parallel for i in 1:ncol
        # Initialize various temporary variables
        min_dist_i = Inf
        min_ind_i = -1
        X_i = view(X, :, i)

        # Check distance against all other columns
        for j in 1:ncol
            # Skip comparison with itself
            if i==j
                continue
            end

            # Tell us who is doing the work
            # (can uncomment if you want to verify stuff)
            # println("Column $i compared with Column $j by worker $(myid())")

            # Evaluate the new distance...
            # If it is less then replace it, otherwise proceed
            dist_temp = evaluate(M, X_i, view(X, :, j))
            if dist_temp < min_dist_i
                min_dist_i = dist_temp
                min_ind_i = j
            end
        end

        # Which column is minimum distance from column i
        dist_vec[i] = min_dist_i
        ind_vec[i] = min_ind_i
    end

    return dist_vec, ind_vec
end

# Using Euclidean metric
metric = Euclidean()
inds, dist = main(X, metric)

@time main(X, metric);
@show dist[[1, 5, 25]], inds[[1, 5, 25]]
</code>```

You can run the code with

1 processor julia testfile.jl

```<code>% julia testfile.jl
  0.640365 seconds (16.00 M allocations: 732.495 MiB, 3.70% gc time)
  (dist[[1, 5, 25]], inds[[1, 5, 25]]) = ([2541, 2459, 1602], [1.40892, 1.38206, 1.32184])
</code>```

n processors (in this case 4) julia -p n testfile.jl

```<code>% julia -p 4 testfile.jl
  0.201523 seconds (2.10 k allocations: 99.107 KiB)
  (dist[[1, 5, 25]], inds[[1, 5, 25]]) = ([2541, 2459, 1602], [1.40892, 1.38206, 1.32184])
</code>```

Body:
My problem is roughly as follows. Given a numerical matrix X, where each row is an item. I want to find each row's nearest neighbor in terms of L2 distance in all rows except itself. I tried reading the official documentation but was still a little confused about how to achieve this. Could someone give me some hint?

My code is as follows

function l2_dist(v1, v2)
    return sqrt(sum((v1 - v2) .^ 2))
end

function main(Mat, dist_fun)
    n = size(Mat, 1)

    Dist = SharedArray{Float64}(n) #[Inf for i in 1:n]
    Id = SharedArray{Int64}(n) #[-1 for i in 1:n]
    @parallel for i = 1:n
        Dist[i] = Inf
        Id[i] = 0
    end
    Threads.@threads for i in 1:n
        for j in 1:n
            if i != j
                println(i, j)
                dist_temp = dist_fun(Mat[i, :], Mat[j, :])
                if dist_temp < Dist[i]
                    println("Dist updated!")
                    Dist[i] = dist_temp
                    Id[i] = j
                end
            end
        end
    end
    return Dict("Dist" => Dist, "Id" => Id)
end

n = 4000
p = 30

X = [rand() for i in 1:n, j in 1:p];

main(X[1:30, :], l2_dist)
@time N = main(X, l2_dist)

I'm trying to distributed all the i's (i.e. calculating each row minimum) over different cores. But the version above apparently isn't working correctly. It is even slower than the sequential version. Can someone point me to the right direction? Thanks.

Body:
Maybe you're doing something in addition to what you have written down, but, at this point from what I can see, you aren't actually doing any computations in parallel. Julia requires you to tell it how many processors (or threads) you would like it to have access to. You can do this through either

Starting Julia with multiple processors julia -p # (where # is the number of processors you want Julia to have access to)

Once you have started a Julia "session" you can call the addprocs function to add additional processors.

To have more than 1 thread, you need to run command export JULIA_NUM_THREADS = #. I don't know very much about threading, so I will be sticking with the @parallel macro. I suggest reading documentation for more details on threading -- Maybe @Chris Rackauckas could expand a little more on the difference.

A few comments below about my code and on your code:

I'm on version 0.6.1-pre.0. I don't think I'm doing anything 0.6 specific, but this is a heads up just in case.

I'm going to use the Distances.jl package when computing the distances between vectors. I think it is a good habit to farm out as many of my computations to well-written and well-maintained packages as possible.

Rather than compute the distance between rows, I'm going to compute the distance between columns. This is because Julia is a column-major language, so this will increase the number of cache hits and give a little extra speed. You can obviously get the row-wise results you want by just transposing the input.

Unless you expect to have that many memory allocations then that many allocations are a sign that something in your code is inefficient. It is often a type stability problem. I don't know if that was the case in your code before, but that doesn't seem to be an issue in the current version (it wasn't immediately clear to me why you were having so many allocations).

Code is below

# Make sure all processors have access to Distances package
@everywhere using Distances

# Create a random matrix
nrow = 30
ncol = 4000

# Seed creation of random matrix so it is always same matrix
srand(42)
X = rand(nrow, ncol)

function main(X::AbstractMatrix{Float64}, M::Distances.Metric)
    # Get size of the matrix
    nrow, ncol = size(X)

    # Create `SharedArray` to store output
    ind_vec = SharedArray{Int}(ncol)
    dist_vec = SharedArray{Float64}(ncol)

    # Compute the distance between columns
    @sync @parallel for i in 1:ncol
        # Initialize various temporary variables
        min_dist_i = Inf
        min_ind_i = -1
        X_i = view(X, :, i)

        # Check distance against all other columns
        for j in 1:ncol
            # Skip comparison with itself
            if i==j
                continue
            end

            # Tell us who is doing the work
            # (can uncomment if you want to verify stuff)
            # println("Column $i compared with Column $j by worker $(myid())")

            # Evaluate the new distance...
            # If it is less then replace it, otherwise proceed
            dist_temp = evaluate(M, X_i, view(X, :, j))
            if dist_temp < min_dist_i
                min_dist_i = dist_temp
                min_ind_i = j
            end
        end

        # Which column is minimum distance from column i
        dist_vec[i] = min_dist_i
        ind_vec[i] = min_ind_i
    end

    return dist_vec, ind_vec
end

# Using Euclidean metric
metric = Euclidean()
inds, dist = main(X, metric)

@time main(X, metric);
@show dist[[1, 5, 25]], inds[[1, 5, 25]]

You can run the code with

1 processor julia testfile.jl

% julia testfile.jl
  0.640365 seconds (16.00 M allocations: 732.495 MiB, 3.70% gc time)
  (dist[[1, 5, 25]], inds[[1, 5, 25]]) = ([2541, 2459, 1602], [1.40892, 1.38206, 1.32184])

n processors (in this case 4) julia -p n testfile.jl

% julia -p 4 testfile.jl
  0.201523 seconds (2.10 k allocations: 99.107 KiB)
  (dist[[1, 5, 25]], inds[[1, 5, 25]]) = ([2541, 2459, 1602], [1.40892, 1.38206, 1.32184])


问:
Checking for a null int value from a Java ResultSet
In Java I'm trying to test for a null value, from a ResultSet, where the column is being cast to a primitive int type.

```<code>int iVal;
ResultSet rs = magicallyAppearingStmt.executeQuery(query);
if (rs.next()) {
  if (rs.getObject("ID_PARENT") != null && !rs.wasNull()) {
    iVal = rs.getInt("ID_PARENT");
  }
}
</code>```

From the code fragment above, is there a better way to do this, and I assume that the second wasNull() test is redundant?

Educate us, and Thanks

答:
Just an update with Java Generics.

You could create an utility method to retrieve an optional value of any Java type from a given ResultSet, previously casted.

Unfortunately, getObject(columnName, Class) does not return null, but the default value for given Java type, so 2 calls are required

```<code>public <T> T getOptionalValue(final ResultSet rs, final String columnName, final Class<T> clazz) throws SQLException {
    final T value = rs.getObject(columnName, clazz);
    return rs.wasNull() ? null : value;
}
</code>```

In this example, your code could look like below:

```<code>final Integer columnValue = getOptionalValue(rs, Integer.class);
if (columnValue == null) {
    //null handling
} else {
    //use int value of columnValue with autoboxing
}
</code>```

Happy to get feedback

Body:
In Java I'm trying to test for a null value, from a ResultSet, where the column is being cast to a primitive int type.

int iVal;
ResultSet rs = magicallyAppearingStmt.executeQuery(query);
if (rs.next()) {
  if (rs.getObject("ID_PARENT") != null && !rs.wasNull()) {
    iVal = rs.getInt("ID_PARENT");
  }
}

From the code fragment above, is there a better way to do this, and I assume that the second wasNull() test is redundant?

Educate us, and Thanks

Body:
Just an update with Java Generics.

You could create an utility method to retrieve an optional value of any Java type from a given ResultSet, previously casted.

Unfortunately, getObject(columnName, Class) does not return null, but the default value for given Java type, so 2 calls are required

public <T> T getOptionalValue(final ResultSet rs, final String columnName, final Class<T> clazz) throws SQLException {
    final T value = rs.getObject(columnName, clazz);
    return rs.wasNull() ? null : value;
}

In this example, your code could look like below:

final Integer columnValue = getOptionalValue(rs, Integer.class);
if (columnValue == null) {
    //null handling
} else {
    //use int value of columnValue with autoboxing
}

Happy to get feedback


问:
NSWindow Content Border messing with CALayer's geometry
I have an NSWindow with a 32px bottom content border. Inside the window's view, I have two custom subviews. Each of them are layer backed, and I'm tracking the mouse with an NSTrackingArea. Part of what I'm doing is some mouseOver effects with CoreAnimation. This is not a problem in general, but I noticed something kind of strange and wondered if anyone knows why this is happening.

When setting up the trackingArea and mouseOver method, I hitTest the root layer and log the layer's name so I can see if the geometry of the various sublayers hold water when I resize the window. Internally, they seem (and look) fine. Visually, they are in the right place, but when I move the mouse, I notice that the though the mouse is physically over a layer, hitTest is returning whatever layer is 32 px above it. However, if I remove the content border, it works as you would expect and the correct layer is returned.

I obviously need the content border, so I have a very simple workaround which involves offsetting the hitTest point by 32px. This works fine, but it just seems weird that the presence of a content border seems to skewing the co-ordinate system of these subviews. Does anyone know why this could be happening?

答: NSEvent returns mouse locations relative to the window's coordinate system, not the targeted view's. You probably need to call convertRect:fromView: to get the correct coordinates.


问:
How to modify view controller after pressing a button?
Let's say that if you press the button from the bottom of the screen after typing something in the account text field, you would be required to also enter the password like in the second image.

How should I do this? I don't think that creating a new view controller would be good. So, should I somehow modify the same view controller?

How could I add the new password text field under the account text field?

Keep in mind that they are still centered. Hiding and unhiding wouldn't work in this case and I also need to modify more things than only adding that text field.

答:
First, create a UIView with everything you need on them. in this example I will have only two text fields and they are all color coded.

The view needs to be centered both horizontally and vertically, with width and height. Set identifiler for the height constraint to be updated later. Set the clip to board to true so that when we redeuce the height of the view, text fields below will hide. The settings for the view will be like this

For your text fields, they must have a constant padding to top. In my example, they are set to be in center horizontally, having a constant height, width and padding to opp.

Now, all you need to do is to get the height of the view from code and set the height to show or hide the text fields.

```<code>var flag = true

@IBAction func click(_ sender: Any) {
    if flag {
        flag = false
        let filteredConstraints = theView.constraints.filter { $0.identifier == "viewHeight" }
        if let heightConstraint = filteredConstraints.first {
            heightConstraint.constant = 60
        }
    } else {
        flag = true
        let filteredConstraints = theView.constraints.filter { $0.identifier == "viewHeight" }
        if let heightConstraint = filteredConstraints.first {
            heightConstraint.constant = 128
        }
    }
}
</code>```

Here is the code running in simulater.

Body:
First, create a UIView with everything you need on them. in this example I will have only two text fields and they are all color coded.

The view needs to be centered both horizontally and vertically, with width and height. Set identifiler for the height constraint to be updated later. Set the clip to board to true so that when we redeuce the height of the view, text fields below will hide. The settings for the view will be like this

For your text fields, they must have a constant padding to top. In my example, they are set to be in center horizontally, having a constant height, width and padding to opp.

Now, all you need to do is to get the height of the view from code and set the height to show or hide the text fields.

var flag = true

@IBAction func click(_ sender: Any) {
    if flag {
        flag = false
        let filteredConstraints = theView.constraints.filter { $0.identifier == "viewHeight" }
        if let heightConstraint = filteredConstraints.first {
            heightConstraint.constant = 60
        }
    } else {
        flag = true
        let filteredConstraints = theView.constraints.filter { $0.identifier == "viewHeight" }
        if let heightConstraint = filteredConstraints.first {
            heightConstraint.constant = 128
        }
    }
}

Here is the code running in simulater.


问:
Angularjs Unexpected token JSON
I have a problem with angularjs and JSON.

This is my code.

list_user.jsp (this is the page where I print the table)

```<code><tr ng-repeat="per in persons">
  <td>{{ per.user }}</td>
  <td>{{ per.password }}</td>
  <td>{{ per.profile }}</td>
</tr>
</code>```

controller.js

```<code> $http({
      method : 'POST',
      url : 'views/user/user.json'
    }).success(function(data){
      $scope.persons = data;
    });
</code>```

user.json

```<code> [
        {
            "user": "Quarterback",
            "password": 5,
            "profile": "ppp"
        },
        {
            "user": "Wide Receiver",
            "password": 89,
            "profile": "oooo"
        }
    ]
</code>```

This way the table is generated correctly, but the json is fixed.
Now I'll paste the code with which I want to print the data by taking them from a query

controller.js

```<code> $http({
        method : 'POST',
        url : 'views/user/user.jsp'
    }).success(function(data){

        /*
        var jsonStr="your json string";
        var json=JSON.stringify(data);
        json=JSON.parse(json)
        console.log(json);
        */
        console.log(data);
        $scope.persons = data;
    });
</code>```

The code between / * .. * / left them to show that I also tried that road without success.

user.jsp

```<code>JSONArray jdata = new JSONArray();
UserRest as = new UserRest();
jdata = as.getAll();
logger.info("jdata in user.jsp "+jdata);
</code>```

UserRest.class (just paste the code where I create the JSON)

```<code> while (iter.hasNext()) {
      User ut = (User) iter.next();
      JSONObject jtemp = new JSONObject();
      jtemp.put("user", ut.getUserName());
      jtemp.put("password", ut.getPassword());
      jtemp.put("profilo", ut.getProfilo());
      jarray.put(jtemp);
    }
    return  jarray;
</code>```

the result of logger.info("jdata in user.jsp "+jdata) in user.jsp

```<code>jdata in user.jsp [{"user":"aaaaaaa","password":"1111111","profile":"0"},{"user":"bbbbbbbb","password":"222222222","profile":"1"}]
</code>```

As you can see the json looks the same, but when in the browser I call the list_user.jsp page in the console the value "data" in controller.js returns me

```<code> <? Xml version = "1.0" encoding = "utf-8"?>
</code>```

I also tried with JSON.parse or JSON.stringify but it does not work.
I also added "track by $ index" here:

```<code><tr ng-repeat = "for people track by $ index">
</code>```

in list_user.jsp but it does not work.

Please help me because I do not know how to do it anymore.

答:
Thank you very much @inigoD, I solved my problem.
Following the new code.

controller.js (UserRest is the servlet)

```<code>$http({
        method : 'POST',
        url : 'UserRest'
    }).success(function(data){
        $scope.persons = data;
    });
</code>```

web.xml

```<code><servlet>
        <servlet-name>UserRest</servlet-name>
        <servlet-class>"path application".UserRest</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>UserRest</servlet-name>
        <url-pattern>/UserRest</url-pattern>
    </servlet-mapping>
</code>```

UserRest.class

```<code>@Override
    protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        try
        {
            JSONArray jdata = new JSONArray();
            jdata = getAll();

            logger.info("prima del response "+jdata);

            response.setContentType("application/json");
            response.getWriter().write(jdata.toString());

        }
        catch ( Exception ex )
        {
            ex.printStackTrace();
        }
    }
</code>```

The function getAll() Is the same as I had pasted on, which contained this code.

```<code>while (iter.hasNext()) {
      User ut = (User) iter.next();
      JSONObject jtemp = new JSONObject();
      jtemp.put("user", ut.getUserName());
      jtemp.put("password", ut.getPassword());
      jtemp.put("profilo", ut.getProfilo());
      jarray.put(jtemp);
    }
    return  jarray;
</code>```

Title: Angularjs Unexpected token JSON

Body:
I have a problem with angularjs and JSON.

This is my code.

list_user.jsp (this is the page where I print the table)

  {{ per.user }}
  {{ per.password }}
  {{ per.profile }}

controller.js

 $http({
      method : 'POST',
      url : 'views/user/user.json'
    }).success(function(data){
      $scope.persons = data;
    });

user.json

 [
        {
            "user": "Quarterback",
            "password": 5,
            "profile": "ppp"
        },
        {
            "user": "Wide Receiver",
            "password": 89,
            "profile": "oooo"
        }
    ]

This way the table is generated correctly, but the json is fixed.
Now I'll paste the code with which I want to print the data by taking them from a query

controller.js

 $http({
        method : 'POST',
        url : 'views/user/user.jsp'
    }).success(function(data){

        /*
        var jsonStr="your json string";
        var json=JSON.stringify(data);
        json=JSON.parse(json)
        console.log(json);
        */
        console.log(data);
        $scope.persons = data;
    });

The code between / * .. * / left them to show that I also tried that road without success.

user.jsp

JSONArray jdata = new JSONArray();
UserRest as = new UserRest();
jdata = as.getAll();
logger.info("jdata in user.jsp "+jdata);

UserRest.class (just paste the code where I create the JSON)

 while (iter.hasNext()) {
      User ut = (User) iter.next();
      JSONObject jtemp = new JSONObject();
      jtemp.put("user", ut.getUserName());
      jtemp.put("password", ut.getPassword());
      jtemp.put("profilo", ut.getProfilo());
      jarray.put(jtemp);
    }
    return  jarray;

the result of logger.info("jdata in user.jsp "+jdata) in user.jsp

jdata in user.jsp [{"user":"aaaaaaa","password":"1111111","profile":"0"},{"user":"bbbbbbbb","password":"222222222","profile":"1"}]

As you can see the json looks the same, but when in the browser I call the list_user.jsp page in the console the value "data" in controller.js returns me

 <? Xml version = "1.0" encoding = "utf-8"?>

I also tried with JSON.parse or JSON.stringify but it does not work.
I also added "track by $ index" here:

in list_user.jsp but it does not work.

Please help me because I do not know how to do it anymore.

Body:
Thank you very much @inigoD, I solved my problem.
Following the new code.

controller.js (UserRest is the servlet)

$http({
        method : 'POST',
        url : 'UserRest'
    }).success(function(data){
        $scope.persons = data;
    });

web.xml

<servlet>
        <servlet-name>UserRest</servlet-name>
        <servlet-class>"path application".UserRest</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>UserRest</servlet-name>
        <url-pattern>/UserRest</url-pattern>
    </servlet-mapping>

UserRest.class

@Override
    protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        try
        {
            JSONArray jdata = new JSONArray();
            jdata = getAll();

            logger.info("prima del response "+jdata);

            response.setContentType("application/json");
            response.getWriter().write(jdata.toString());

        }
        catch ( Exception ex )
        {
            ex.printStackTrace();
        }
    }

The function getAll() Is the same as I had pasted on, which contained this code.

while (iter.hasNext()) {
      User ut = (User) iter.next();
      JSONObject jtemp = new JSONObject();
      jtemp.put("user", ut.getUserName());
      jtemp.put("password", ut.getPassword());
      jtemp.put("profilo", ut.getProfilo());
      jarray.put(jtemp);
    }
    return  jarray;


问:
Signalr send message from browser to .net client on the same machine
We need to communicate a native application with a web application.

We think to use signalr to send the message/command.

The pipeline would be:

User clicks to make an action.

Javascript (with signalr) send a message to a server in azure.

The server re-send the message a specific client. It must be the client installed on the same machine.

Once the result is completed, NET sends the resulting reverse.

The matter is, How I can find client from the same machine in the signalr Server?

The organization in our system is:

There is center/gym.

Every center has staff who can login.

We could identify client at the same center with some file configuration. Saving our key center, for example. But, in a center, could there are more than one.NET client installed on the different computer.

We think to use the private IP of the computer to make a key on the signalr server.

```<code>var ips = [];

    var RTCPeerConnection = window.RTCPeerConnection ||
        window.webkitRTCPeerConnection || window.mozRTCPeerConnection;

    var pc = new RTCPeerConnection({
        // Don't specify any stun/turn servers, otherwise you will
        // also find your public IP addresses.
        iceServers: []
    });
    // Add a media line, this is needed to activate candidate gathering.
    pc.createDataChannel('');

    // onicecandidate is triggered whenever a candidate has been found.
    pc.onicecandidate = function (e) {
        if (!e.candidate) { // Candidate gathering completed.
            pc.close();
            console.log(ips);
            return;
        }
        var ip = /^candidate:.+ (\S+) \d+ typ/.exec(e.candidate.candidate)[1];

        ips.push(ip);
    };
    pc.createOffer(function (sdp) {
        pc.setLocalDescription(sdp);
    }, function onerror() { });
</code>```

This data can be obtained in .NET client without a problem. But in javascript, the previous code works regularly. In some PC, it only returns ipv4. And in Mozilla it doesn't work.

How can we identify both clients? Do You know another way to reach the goal?

Thanks,

答:
Finally, we didn't find a good solution filtering ip adress.

We did the as follow:

We used URI schema to launch our app. URI Schema windows

```

    Public Class RegistrarURI

        Const URI_SCHEME As String = "xxx"
        Const URI_KEY As String = "URL:xxx"
        Private Shared APP_PATH As String = Location.AssemblyDirectory() ' "C:\Program Files (x86)\xxx.exe"

        Public Shared Sub RegisterUriScheme()

            Using hkcrClass As RegistryKey = Registry.ClassesRoot.CreateSubKey(URI_SCHEME)
                hkcrClass.SetValue(Nothing, URI_KEY)
                hkcrClass.SetValue("URL Protocol", [String].Empty, RegistryValueKind.[String])

                Using defaultIcon As RegistryKey = hkcrClass.CreateSubKey("DefaultIcon")
                    Dim iconValue As String = [String].Format("""{0}"",0", APP_PATH)
                    defaultIcon.SetValue(Nothing, iconValue)
                End Using

                Using shell As RegistryKey = hkcrClass.CreateSubKey("shell")
                    Using open As RegistryKey = shell.CreateSubKey("open")
                        Using command As RegistryKey = open.CreateSubKey("command")
                            Dim cmdValue As String = [String].Format("""{0}"" ""%1""", APP_PATH)
                            command.SetValue(Nothing, cmdValue)
                        End Using
                    End Using
                End Using
            End Using
        End Sub

    End Class

```

In an Azure WebApp we launch a SignalR Server. This server will send data from our .NET app to Chrome.

To achive that, when the web is loaded, we connect to the signalR server. To build de uri, We send the connectionId from Javascript client to the .NET Client.

Then, when the native process is completed. .NET client send the information to signalR server, and this server mirrored the data to javacript client using the connectionId.

To avoid launch some instance of our native app, we use IPC channel to send data to one instance to the previous and closind the new one.

Link to source Blog source

Body:
We need to communicate a native application with a web application.

We think to use signalr to send the message/command.

The pipeline would be:

User clicks to make an action.

Javascript (with signalr) send a message to a server in azure.

The server re-send the message a specific client. It must be the client installed on the same machine.

Once the result is completed, NET sends the resulting reverse.

The matter is, How I can find client from the same machine in the signalr Server?

The organization in our system is:

There is center/gym.

Every center has staff who can login.

We could identify client at the same center with some file configuration. Saving our key center, for example. But, in a center, could there are more than one.NET client installed on the different computer.

We think to use the private IP of the computer to make a key on the signalr server.

var ips = [];

    var RTCPeerConnection = window.RTCPeerConnection ||
        window.webkitRTCPeerConnection || window.mozRTCPeerConnection;

    var pc = new RTCPeerConnection({
        // Don't specify any stun/turn servers, otherwise you will
        // also find your public IP addresses.
        iceServers: []
    });
    // Add a media line, this is needed to activate candidate gathering.
    pc.createDataChannel('');

    // onicecandidate is triggered whenever a candidate has been found.
    pc.onicecandidate = function (e) {
        if (!e.candidate) { // Candidate gathering completed.
            pc.close();
            console.log(ips);
            return;
        }
        var ip = /^candidate:.+ (\S+) \d+ typ/.exec(e.candidate.candidate)[1];

        ips.push(ip);
    };
    pc.createOffer(function (sdp) {
        pc.setLocalDescription(sdp);
    }, function onerror() { });

This data can be obtained in .NET client without a problem. But in javascript, the previous code works regularly. In some PC, it only returns ipv4. And in Mozilla it doesn't work.

How can we identify both clients? Do You know another way to reach the goal?

Thanks,

Body:
Finally, we didn't find a good solution filtering ip adress.

We did the as follow:

We used URI schema to launch our app. URI Schema windows

    Public Class RegistrarURI

        Const URI_SCHEME As String = "xxx"
        Const URI_KEY As String = "URL:xxx"
        Private Shared APP_PATH As String = Location.AssemblyDirectory() ' "C:\Program Files (x86)\xxx.exe"

        Public Shared Sub RegisterUriScheme()

            Using hkcrClass As RegistryKey = Registry.ClassesRoot.CreateSubKey(URI_SCHEME)
                hkcrClass.SetValue(Nothing, URI_KEY)
                hkcrClass.SetValue("URL Protocol", [String].Empty, RegistryValueKind.[String])

                Using defaultIcon As RegistryKey = hkcrClass.CreateSubKey("DefaultIcon")
                    Dim iconValue As String = [String].Format("""{0}"",0", APP_PATH)
                    defaultIcon.SetValue(Nothing, iconValue)
                End Using

                Using shell As RegistryKey = hkcrClass.CreateSubKey("shell")
                    Using open As RegistryKey = shell.CreateSubKey("open")
                        Using command As RegistryKey = open.CreateSubKey("command")
                            Dim cmdValue As String = [String].Format("""{0}"" ""%1""", APP_PATH)
                            command.SetValue(Nothing, cmdValue)
                        End Using
                    End Using
                End Using
            End Using
        End Sub

    End Class

In an Azure WebApp we launch a SignalR Server. This server will send data from our .NET app to Chrome.

To achive that, when the web is loaded, we connect to the signalR server. To build de uri, We send the connectionId from Javascript client to the .NET Client.

Then, when the native process is completed. .NET client send the information to signalR server, and this server mirrored the data to javacript client using the connectionId.

To avoid launch some instance of our native app, we use IPC channel to send data to one instance to the previous and closind the new one.

Link to source Blog source


问:
difference between dcos-kafka-service and mesos-kafka
I’m doing a POC to deploy Kafka as an application on Mesos Cluster. I came across these 2 codebases on github. One developed by apache-mesos (github page) & other developed by mesosphere and can run only on DCOS (github page).

Question: Would like to know if there are any differences between DCOS-Kafka & mesos-Kafka in terms of features and extended functionality.

Regarding Mesos-Kafka:
I don’t see active participation on github (and some open issues) for mesos-kafka in the past months. Can I assume that the service is robust enough that I can use in production environment? Any Inputs on this would be helpful.

答:
kakfa-mesos is a package that includes a release of Kafka and a custom mesos scheduler that was meant to work around issues with running Kafka as a stateful service on Marathon. I think post but confluent is useful. It also includes a RESTful api for doing ops tasks and aims to include these features in the future (this is pulled from the article I linked)

Integrating Kafka commands (e.g. kafka-topics, etc) into the Scheduler so it can be used through the CLI and REST API.

Auto-scaling clusters (including auto reassignment of partitions) so that the resources (CPU, RAM, etc.) that brokers are using can be used elsewhere in known valleys of traffic.

Rack-aware partition assignment for fault tolerance.

Hooks so that producers and consumers can also be launched from the Scheduler and managed with the cluster.

Automated partition reassignment based on load and traffic

I haven't used it in a production environment myself but it has the support of Confluent which is a good sign.

DC/OS Kafka on the other hand is a DC/OS service which will probably only be useful if you are already running or plan on running services through Mesosphere's DC/OS. It also includes an API and a CLI management tool but is less ambitious with additional features. It's current feature set includes

Single-command installation for rapid provisioning

Multiple clusters for multiple tenancy with DC/OS

High availability runtime configuration and software updates

Storage volumes for enhanced data durability, known as Mesos Dynamic * * Reservations and Persistent Volumes

Integration with syslog-compatible logging services for diagnostics and troubleshooting

Integration with statsd-compatible metrics services for capacity and performance monitoring


问:
Is there a CRC or criptographic function for generating smaller size unique results from unique inputs?
I have a manufacturer unique number ID of 128 bits that I cannot change and it's size is just too long for our purpose (2^128). This is on some embedded micro controller.

One idea is to compute a (run time) CRC32 or hash for narrowing the results but I am not sure for unicity CRC32 as a example: this can be unique for 2^32

Or what king of cryptography function I can use for guarantee unicity of 32 bits output based on unique input?

Thanks for clarifications,

答:
If you know all these ID values in advance, then you can check them using a hash table. You can save space by storing only as many bits of each hash value as are necessary to tell them apart if them happen to land in the same bucket.

If not, then you're going to have a hard time, I'm afraid.

Let's assume these 128-bit IDs are produced as the output of a cryptographic hash function (e.g., MD5), so each ID resembles 128 bits chosen uniformly at random.

If you reduce these to 32-bit values, then the best you can hope to achieve is a set of 32-bit numbers where each bit is 0 or 1 with uniform probability. You could do this by calculating the CRC32 checksum, or by simply discarding 96 bits — it makes no difference.

32 bits is not enough enough to avoid collisions. The collision probability exceeds 1 in a million after just 93 inputs, and 1 in a thousand after 2,900 inputs. After 77,000 inputs, the collision probability reaches 50%. (Source).

So instead, your only real options are to somehow reverse-engineer the ID values into something smaller, or implement some external means of replacing these IDs with sequential integers (e.g., using a hash table).


问:
build maven project with propriatery libraries included
How to create maven pom, which will make project buildable, can I include propriatery jars with my project directly without having to take them from repository? anyone did this before ?

EDIT :

I don't want to make it runnable by building assembly with dependencies jar, I want it to be buildable. So anyone having this project is able to build it, even if jars are nowhere to be found at any repository.

答: You can use the maven-assembly-plugin and create a jar with all dependencies included.</p>


问:
Laravel 5 has one relationship
I have two tables: drugs table and formulations table. The drugs table has fields id, name, quantity and formulation_id. The formulations table has fields  id and name.

What relationship should I use to get the drugs records including the name of the formulation.

Note that 1 drug record has only one 1 formulation record.

I have tried using hasOne relashionship but doesn't work:

My view looks as follows:

```<code>@foreach($drugs as $drug)
        <li>
            <a class="padded-list" href="">{{$drug->name}} ({{$drug->formulation->name}})</a>
        </li>
        @endforeach
</code>```

My model relationship in the the Drug model looks as follows:

```<code>public function formulation()
{
    return $this->hasOne('App\Formulation');
}
</code>```

答:
If you call $drug->formulation return Eloquent Collection, you can't get name

You should call $drug->formulation()->first()->name

Title: Laravel 5 has one relationship

Body:
I have two tables: drugs table and formulations table. The drugs table has fields id, name, quantity and formulation_id. The formulations table has fields  id and name.

What relationship should I use to get the drugs records including the name of the formulation.

Note that 1 drug record has only one 1 formulation record.

I have tried using hasOne relashionship but doesn't work:

My view looks as follows:

@foreach($drugs as $drug)

            {{$drug->name}} ({{$drug->formulation->name}})

        @endforeach

My model relationship in the the Drug model looks as follows:

public function formulation()
{
    return $this->hasOne('App\Formulation');
}


问:
How to get SSAS tabular model attributes and dimensions usage details
I need to create a cube which purpose would be to gather detailed information about tabular model dimensions and attributes usage by users (e.g. how many times users access certain dimension).
So far, I tried to use Data Management View Query (http://msdn.microsoft.com/en-us/library/hh230820.aspx) and SQLProfiler and I could see which commands were executed in a session.
I wonder if there is any way to get the number of dimensions/attributes usage without parsing the commands.
Any suggestion would be much appreciated.</p>

答:
It is possible to monitor all queries sent to an analysis services (tabular) instance by setting up Extended Events.

You can set up an extended event on your analysis services instance through SQL Server Management Studio by navigating to Management-->Extended Events-->Sessions, and then right clicking and selecting "New session...".

You can set up your extended events session to catch specific event types, such as "QueryBegin" and "QueryEnd". This will log all QueryBegin and QueryEnd events to a log file on the path you've specified. In the log files created by the extended event you will then be able to find information about all queries that have hit the analysis services instance.

With a bit of work you should be able to create a cube that shows how many queries have hit a certain dimension, how many queries have been sent by a certain user, etc.


问:
How to configure htaccess for beta(subdirectory) keeping the root htacess as it is
I have live website in the root folder, now I have created a sub-directory to keep the development changes and test them on server, How Can I configure htaccess for subdirectory, I want to keep the live website running.

Currently my htaccess is as follows, similar to root htaccess

```<code>RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f

RewriteRule ^(member-([0-9]+)-([a-zA-Z0-9\-]+))/?$ team.php?id=$2&%{QUERY_STRING} [NC,L]
</code>```

Please help me

Edit : I want to access beta site by just adding /beta at the end of the url. ex https://www.example.com/beta

答:
Multiple .htaccess files

You should probably be OK by simply creating the same .htaccess in your sub-directory and just removing the RewriteBase command - it really isn't needed in most cases, and except when rewriting paths to files on the document root, configuring it correctly can be quite confusing.

Here is a sample setup:

```<code>+- DOCROOT/index.php :

   <?php echo $_SERVER['PATH_INFO'];

+- DOCROOT/.htaccess :

   RewriteEngine On
   RewriteBase /
   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteRule ^(.*) index.php/$1

+- DOCROOT/subdir/index.php :

   <?php echo $_SERVER['PATH_INFO'];

+- DOCROOT/.htaccess :

   RewriteEngine On
   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteRule ^(.*) index.php/$1
</code>```

With that setup, you can call http://server/some-path and see /some-path echoed back, or call http://server/subdir/other-path and see /other-path echoed back.

Single .htaccess

You can also add the rewrite rule for the sub-directory in your main .htaccess file that is in the document root - just dup the last rewrite chain (the only one that is interesting) and add a RewriteCond to the first one that limits only to the sub directory.

Taking your example above, it might look like this:

```<code>RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]

RewriteBase /

RewriteCond %{REQUEST_URI} subdirectory/
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^subdirectory/(member-([0-9]+)-([a-zA-Z0-9\-]+))/?$ subdirectory/team.php?id=$2&%{QUERY_STRING} [NC,L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(member-([0-9]+)-([a-zA-Z0-9\-]+))/?$ team.php?id=$2&%{QUERY_STRING} [NC,L]
</code>```

(I've also took the libery to remove the redundant RewriteEngine On command). If a request comes to the sub directory, it will be caught by the first rule, rewritten using the subdirectory context and the [L] flag will cause mod_rewrite stop processing. Otherwise it'll do the main routing. This setup is a bit too complex for my taste and I'd probably go with the additional .htaccess file.

Body:
I have live website in the root folder, now I have created a sub-directory to keep the development changes and test them on server, How Can I configure htaccess for subdirectory, I want to keep the live website running.

Currently my htaccess is as follows, similar to root htaccess

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f

RewriteRule ^(member-([0-9]+)-([a-zA-Z0-9\-]+))/?$ team.php?id=$2&%{QUERY_STRING} [NC,L]

Please help me

Edit : I want to access beta site by just adding /beta at the end of the url. ex https://www.example.com/beta

Body:
Multiple .htaccess files

You should probably be OK by simply creating the same .htaccess in your sub-directory and just removing the RewriteBase command - it really isn't needed in most cases, and except when rewriting paths to files on the document root, configuring it correctly can be quite confusing.

Here is a sample setup:

+- DOCROOT/index.php :

   <?php echo $_SERVER['PATH_INFO'];

+- DOCROOT/.htaccess :

   RewriteEngine On
   RewriteBase /
   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteRule ^(.*) index.php/$1

+- DOCROOT/subdir/index.php :

   <?php echo $_SERVER['PATH_INFO'];

+- DOCROOT/.htaccess :

   RewriteEngine On
   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteRule ^(.*) index.php/$1

With that setup, you can call http://server/some-path and see /some-path echoed back, or call http://server/subdir/other-path and see /other-path echoed back.

Single .htaccess

You can also add the rewrite rule for the sub-directory in your main .htaccess file that is in the document root - just dup the last rewrite chain (the only one that is interesting) and add a RewriteCond to the first one that limits only to the sub directory.

Taking your example above, it might look like this:

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]

RewriteBase /

RewriteCond %{REQUEST_URI} subdirectory/
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^subdirectory/(member-([0-9]+)-([a-zA-Z0-9\-]+))/?$ subdirectory/team.php?id=$2&%{QUERY_STRING} [NC,L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(member-([0-9]+)-([a-zA-Z0-9\-]+))/?$ team.php?id=$2&%{QUERY_STRING} [NC,L]

(I've also took the libery to remove the redundant RewriteEngine On command). If a request comes to the sub directory, it will be caught by the first rule, rewritten using the subdirectory context and the [L] flag will cause mod_rewrite stop processing. Otherwise it'll do the main routing. This setup is a bit too complex for my taste and I'd probably go with the additional .htaccess file.