问:
Serving Static files Django 1.11.3
I'm new to programming(Python 3.6, Django 1.11.3), I've been teaching myself over youtube and the product's documentation. Now I'm following a youtube video by Chris Hawkes, titled Django 1.10 Tutorial. I followed every instruction down to the nail, but for some reason, the database still doesn't find the static files.here's the link to the project structure, setting.py and index.html. https://www.dropbox.com/sh/q6yfxqt7k4wy43l/AACBcgMiOsdnCyGEvBK4zd45a?dl=0

May you kindly assist, I'd appreciate any pointers as to what I should be doing.
Thank you

```<code>    {%load static%}
    <!DOCTYPE html>
    <html lang="en">
    ......

        <title>Green Soil Group</title>

        <!-- Bootstrap Core CSS -->
        <link  rel="stylesheet" href="{%static'
         vendor/bootstrap/css/bootstrap.min.css' %}'"  >

        <!-- Custom Fonts -->
        <link href=" {%static ' vendor/font-awesome/css/font-
         awesome.min.css' %}' " rel="stylesheet" type="text/css">
        <link href='https://fonts.googleapis.com/css?

        <!-- Plugin CSS -->
        <link href=" {%static ' vendor/magnific-popup/magnific-popup.css '
         %}' "
         rel="stylesheet">
</code>```

setting.py

```<code>    INSTALLED_APPS = [
       'django.contrib.admin',
       'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',

    ROOT_URLCONF = 'book.urls'

    TEMPLATES = [
           {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR+'/templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                      ],
                    },
                },
            ]

    # Static files (CSS, JavaScript, Images)
    # https://docs.djangoproject.com/en/1.11/howto/static-files/

    STATIC_URL = '/static/'

    STATICFILES_DIR = [
        BASE_DIR + "/static/",
       ]
</code>```

答:
try this:

Make sure that your project follows the typical Django project structure:

```<code>> book
 \ - settings.py
   - urls.py
   - wsgi.py
   > yourapp
    \ - models.py
      - views.py
      - tests.py
      - admin.py
      - apps.py
</code>```

I see in your settings.py that you don't have any apps installed. Add the following entry to your settings.py

```<code>INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'yourapp.apps.YourappConfig'  # <- add this entry
]
</code>```

Note that i'm using yourapp as the app name, but here use your real app name. If you have not started any app refer first to the docs.

Place your static content inside books/yourapp/static/yourapp. Here you can copy your vendor directory. Again, refer to the docs for more info.

remove the STATICFILES_DIR in your settings.py

add the following entry to your settings.py:

```<code>STATICFILES_FINDERS = [
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]
</code>```

In your templates, refer to the static content in this way:

```<code>href="{% static 'yourapp/path/to/the/resource' %}"
</code>```

Example:

```<code><link rel="stylesheet" href="{%static 'yourapp/vendor/bootstrap/css/bootstrap.min.css' %}'">
</code>```

Hope this helps.

Title: Serving Static files Django 1.11.3

Body:
I'm new to programming(Python 3.6, Django 1.11.3), I've been teaching myself over youtube and the product's documentation. Now I'm following a youtube video by Chris Hawkes, titled Django 1.10 Tutorial. I followed every instruction down to the nail, but for some reason, the database still doesn't find the static files.here's the link to the project structure, setting.py and index.html. https://www.dropbox.com/sh/q6yfxqt7k4wy43l/AACBcgMiOsdnCyGEvBK4zd45a?dl=0

May you kindly assist, I'd appreciate any pointers as to what I should be doing.
Thank you

    {%load static%}
    <!DOCTYPE html>

    ......

        <title>Green Soil Group</title>

        <link  rel="stylesheet" href="{%static'
         vendor/bootstrap/css/bootstrap.min.css' %}'"  >

        <link href=" {%static ' vendor/font-awesome/css/font-
         awesome.min.css' %}' " rel="stylesheet" type="text/css">
        <link href='https://fonts.googleapis.com/css?

        <link href=" {%static ' vendor/magnific-popup/magnific-popup.css '
         %}' "
         rel="stylesheet">

setting.py

    INSTALLED_APPS = [
       'django.contrib.admin',
       'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',

    ROOT_URLCONF = 'book.urls'

    TEMPLATES = [
           {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR+'/templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                      ],
                    },
                },
            ]

    # Static files (CSS, JavaScript, Images)
    # https://docs.djangoproject.com/en/1.11/howto/static-files/

    STATIC_URL = '/static/'

    STATICFILES_DIR = [
        BASE_DIR + "/static/",
       ]

Body:
try this:

Make sure that your project follows the typical Django project structure:

> book
 \ - settings.py
   - urls.py
   - wsgi.py
   > yourapp
    \ - models.py
      - views.py
      - tests.py
      - admin.py
      - apps.py

I see in your settings.py that you don't have any apps installed. Add the following entry to your settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'yourapp.apps.YourappConfig'  # <- add this entry
]

Note that i'm using yourapp as the app name, but here use your real app name. If you have not started any app refer first to the docs.

Place your static content inside books/yourapp/static/yourapp. Here you can copy your vendor directory. Again, refer to the docs for more info.

remove the STATICFILES_DIR in your settings.py

add the following entry to your settings.py:

STATICFILES_FINDERS = [
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]

In your templates, refer to the static content in this way:

href="{% static 'yourapp/path/to/the/resource' %}"

Example:

<link rel="stylesheet" href="{%static 'yourapp/vendor/bootstrap/css/bootstrap.min.css' %}'">

Hope this helps.


来源: stackexchange

问:
Install Boost headers to specific directory (Windows)
I've downloaded, extracted, and compiled the Boost libraries (including the separately compiled libraries). I've used their install procedure a couple times now but I can't seem to get it to do exactly what I want. Right now, when I install Boost after compiling it goes to

```<code>C:\Boost
</code>```

This is fine. The compiled libs go to

```<code>C:\Boost\lib
</code>```

which is also fine. The problem I have is with the installation of the precompiled headers. They got put at

```<code>C:\Boost\include\boost-1_54\boost
</code>```

Is there a way to use the Boost build system and install tools to set the precompiled headers to be installed to just

```<code>C:\Boost\include
</code>```

and not have the Boost version number be a part of that folder hierarchy?

I don't plan on using multiple versions of Boost at the same time so I don't have a use for actually having that version number. I realize I could move them manually after the install is complete, but I wanted to see first if I've overlooked or misunderstood something about Boost's build system.

答:
--layout=system removes the versioned subdirectory from the include path (as @IgorR. pointed out).

"Removing that second boost in the path" is a bad idea. In a respectable OS (cough...), the include files for various libraries are supposed to co-exist in one common include directory, hence the boost subdirectory to avoid clashes. Boost headers are therefore habitually referred to as e.g. #include <boost/any.hpp>, i.e. including that boost/ subdirectory.

This is done both by third-party software using Boost, and by Boost itself. If you remove the second boost from the path, you would end up with C:\Boost\include\any.hpp, and any Boost-using software won't compile as not even Boost could find its own includes.

ContentLicense: CC BY-SA 3.0

Body:
I've downloaded, extracted, and compiled the Boost libraries (including the separately compiled libraries). I've used their install procedure a couple times now but I can't seem to get it to do exactly what I want. Right now, when I install Boost after compiling it goes to

C:\Boost

This is fine. The compiled libs go to

C:\Boost\lib

which is also fine. The problem I have is with the installation of the precompiled headers. They got put at

C:\Boost\include\boost-1_54\boost

Is there a way to use the Boost build system and install tools to set the precompiled headers to be installed to just

C:\Boost\include

and not have the Boost version number be a part of that folder hierarchy?

I don't plan on using multiple versions of Boost at the same time so I don't have a use for actually having that version number. I realize I could move them manually after the install is complete, but I wanted to see first if I've overlooked or misunderstood something about Boost's build system.


问:
Symfony 1.4 doctrine admin generator display i18n form fields
My problem is that iam using admin generator for model with some extra virtual attributes which i need to have in generator.yml definitions:

```<code>config:
  form:
    display: [name, design_by, description, _images, add_image, _videos, add_video]
</code>```

But the "description" attribute is in i18n mode of doctrine model s it does'nt exists in core model object anymore - moved into i18n model.
So iam getting logical error 'Widget "description" does not exist'.

I tryed somthing like:

```<code>config:
  form:
    display: [description_i18n]
</code>```

but did'nt found solution.

When i cut the form display definition into default, form starts working, but it miss my extra fields _images, add_image, _videos, add_video, so i need to have the definition there.

Google doesnt helped too...

Does anybody know how to define i18n widgets into generator.yml?
THX!

答:
I have done this before and I am not sure if this is the answer you are looking for but in order for Symfony to display i18n fields in the admin generator you need to add a line to each Form class in your project/lib folder.

For instance if you have a Form class in: <myproject>/lib/form/doctrine/MyForm.class.php

Add this to the configure method like so:

```<code>  public function configure()
  {
    parent::configure();

    // Add this line.
    $this->embedI18n(array('en', 'de'));
    ...
  }
</code>```

Change en and de to the languages you have set up. You need to do this for every form object you have.

ContentLicense: CC BY-SA 2.5

Body:
My problem is that iam using admin generator for model with some extra virtual attributes which i need to have in generator.yml definitions:

config:
  form:
    display: [name, design_by, description, _images, add_image, _videos, add_video]

But the "description" attribute is in i18n mode of doctrine model s it does'nt exists in core model object anymore - moved into i18n model.
So iam getting logical error 'Widget "description" does not exist'.

I tryed somthing like:

config:
  form:
    display: [description_i18n]

but did'nt found solution.

When i cut the form display definition into default, form starts working, but it miss my extra fields _images, add_image, _videos, add_video, so i need to have the definition there.

Google doesnt helped too...

Does anybody know how to define i18n widgets into generator.yml?
THX!

Body:
I have done this before and I am not sure if this is the answer you are looking for but in order for Symfony to display i18n fields in the admin generator you need to add a line to each Form class in your project/lib folder.

For instance if you have a Form class in: <myproject>/lib/form/doctrine/MyForm.class.php

Add this to the configure method like so:

  public function configure()
  {
    parent::configure();

    // Add this line.
    $this->embedI18n(array('en', 'de'));
    ...
  }

Change en and de to the languages you have set up. You need to do this for every form object you have.


问:
I need to align 3 divs in the center of my page with flexbox
I have a flex container and 3 divs inside it of equal width and I am trying to get the divs to align in the centre of the page with equal distance between them and also equal distance from the edge of the page.

.container {
    display : flex;
    width : 60%;
}

.para {
    width : 33%;
    padding : 1em;
    border:.5px solid black;
    margin :1em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class = "container">
<div class ="para one">para one para one para one para one para one para one
para one para one para one para one para one</div>

<div class ="para two">para two para two para two para two para two para two
para two para two para two para two para two para two </div>

<div class ="para three">para three  para three para three para three para
three para three para three para three para three para three</div>
</div></code>```

答:
Automatic margins for the parent and space-around for the flex items.

.container {
  display: flex;
  width: 60%;
  justify-content: space-around;
  margin: 0 auto;
}

.para {
  width: 33%;
  padding: 1em;
  border: .5px solid black;
  margin: 1em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="para one">para one para one para one para one para one para one para one para one para one para one para one</div>
  <div class="para two">para two para two para two para two para two para two para two para two para two para two para two para two </div>
  <div class="para three">para three para three para three para three para three para three para three para three para three para three</div>
</div></code>```

Body:
I have a flex container and 3 divs inside it of equal width and I am trying to get the divs to align in the centre of the page with equal distance between them and also equal distance from the edge of the page.

.container {
    display : flex;
    width : 60%;
}

.para {
    width : 33%;
    padding : 1em;
    border:.5px solid black;
    margin :1em;
}

para one para one para one para one para one para one
para one para one para one para one para one

para two para two para two para two para two para two
para two para two para two para two para two para two

para three  para three para three para three para
three para three para three para three para three para three

Body:
Automatic margins for the parent and space-around for the flex items.

.container {
  display: flex;
  width: 60%;
  justify-content: space-around;
  margin: 0 auto;
}

.para {
  width: 33%;
  padding: 1em;
  border: .5px solid black;
  margin: 1em;
}

<div class="container">
  <div class="para one">para one para one para one para one para one para one para one para one para one para one para one</div>
  <div class="para two">para two para two para two para two para two para two para two para two para two para two para two para two </div>
  <div class="para three">para three para three para three para three para three para three para three para three para three para three</div>
</div>


问:
How to set a hex color to an ImageView inside a notification?
I'm trying to set a color as an image to an ImageView that exists inside a custom notification. I can give it predefined colors by writing this line:

```<code>remoteViews.setImageViewResource(R.id.imageView, R.color.Green);
</code>```

But i want to be able to give it hex color values, and set that as the color. I tried setting the color as the background of the ImageView, but i couldn't get access to it, and the only options i have to access the ImageView are these:

```<code>remoteViews
    .setImageViewResource()
    .setImageViewBitmap()
    .setImageViewIcon()
    .setImageViewUri()
</code>```

Is there a way to pass in a color by parsing the hex value to any of these?
I think if I was able to create a bitmap and set the bitmap to the image view, it could be done, so i wrote the code bellow to create the bitmap:

```<code>    int[] colors = {Color.parseColor("#64DD17"), Color.parseColor("#D32F2F")};
    Bitmap bitmap = Bitmap.createBitmap(colors, 10, 10, Bitmap.Config.RGB_565);
</code>```

, but i get a java.lang.ArrayIndexOutOfBoundsException. I tried with one element in the colors array too, but same error.
What is my error here?

答:
Simple solution: generate png images(or use svg) to put inside the image view, instead of the color you want.

but, if u want to use that approach, you can create a colored bitmap using something like that:

```<code>Bitmap image = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
  image.eraseColor(android.graphics.Color.GREEN);
</code>```

Body:
I'm trying to set a color as an image to an ImageView that exists inside a custom notification. I can give it predefined colors by writing this line:

remoteViews.setImageViewResource(R.id.imageView, R.color.Green);

But i want to be able to give it hex color values, and set that as the color. I tried setting the color as the background of the ImageView, but i couldn't get access to it, and the only options i have to access the ImageView are these:

remoteViews
    .setImageViewResource()
    .setImageViewBitmap()
    .setImageViewIcon()
    .setImageViewUri()

Is there a way to pass in a color by parsing the hex value to any of these?
I think if I was able to create a bitmap and set the bitmap to the image view, it could be done, so i wrote the code bellow to create the bitmap:

    int[] colors = {Color.parseColor("#64DD17"), Color.parseColor("#D32F2F")};
    Bitmap bitmap = Bitmap.createBitmap(colors, 10, 10, Bitmap.Config.RGB_565);

, but i get a java.lang.ArrayIndexOutOfBoundsException. I tried with one element in the colors array too, but same error.
What is my error here?

Body:
Simple solution: generate png images(or use svg) to put inside the image view, instead of the color you want.

but, if u want to use that approach, you can create a colored bitmap using something like that:

Bitmap image = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
  image.eraseColor(android.graphics.Color.GREEN);


问:
Vue router and Cordova (Vue.js)
EDIT

So I just found out it has to do with the router being in history mode, if I remove 'mode': 'history', from router.js everything works again! Leaving here if others have the same problem, or if someone can provide an explanation...

Original

I'm not able to use vue v2 with vue-router and cordova (i.e. building to cordova/www and having cordova work from the index.html file). I used to be able to with vue and vue-router v1. I'm also able to with vue v2 but without using vue-router.

To be clear, the app works when using npm run dev just not when opening the built index.html.

I have a feeling this has to do with the router looking for a path of / but seeing index.html?

Here's a repo where you can reproduce the problem.

Below is some relevant code:

main.js:

import Vue from 'vue';
import App from './App.vue';
import router from './router/router.js';

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  // replace the content of

 with App
  render: h => h(App),
});
```
<p><strong>app.vue:</strong></p>
<pre class="lang-html prettyprint-override"><code><template>
  <div id="app">
    <img src="./assets/logo.png">
    <router-view></router-view>
  </div>
</template>

<script>
import Hello from './components/Hello';

export default {
  name: 'app',
  components: {
    Hello,
  }
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
</code>```

/router/router.js:

import Vue from 'vue';
import Router from 'vue-router';

Vue.use(Router);

import Hello from '../components/Hello';

export default new Router({
  'mode': 'history',
  scrollBehavior: () => ({ y: 0 }),
  'routes': [
    {
      'path': '/',
      'component': Hello,
    }
  ]
})
```
<p><strong>config/index.js:</strong></p>
<pre class="lang-js prettyprint-override"><code>// see http://vuejs-templates.github.io/webpack for documentation.
var path = require('path');

module.exports = {
  build: {
    env: require('./prod.env'),
    index: path.resolve(__dirname, '../../cordova/www/index.html'),
    assetsRoot: path.resolve(__dirname, '../../cordova/www'),
    assetsSubDirectory: 'static',
    assetsPublicPath: '',
    productionSourceMap: true,
    // Gzip off by default as many popular static hosts such as
    // Surge or Netlify already gzip all static assets for you.
    // Before setting to `true`, make sure to:
    // npm install --save-dev compression-webpack-plugin
    productionGzip: false,
    productionGzipExtensions: ['js', 'css'],
  },
  dev: {
    env: require('./dev.env'),
    port: 8080,
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {},
    // CSS Sourcemaps off by default because relative paths are "buggy"
    // with this option, according to the CSS-Loader README
    // (https://github.com/webpack/css-loader#sourcemaps)
    // In our experience, they generally work as expected,
    // just be aware of this issue when enabling this option.
    cssSourceMap: false,
  }
}
</code>```

答: Set build: assetsPublicPath: 'file:///android_asset/www/'

ContentLicense: CC BY-SA 4.0

Title: Vue router and Cordova (Vue.js)

Body:
EDIT

So I just found out it has to do with the router being in history mode, if I remove 'mode': 'history', from router.js everything works again! Leaving here if others have the same problem, or if someone can provide an explanation...

Original

I'm not able to use vue v2 with vue-router and cordova (i.e. building to cordova/www and having cordova work from the index.html file). I used to be able to with vue and vue-router v1. I'm also able to with vue v2 but without using vue-router.

To be clear, the app works when using npm run dev just not when opening the built index.html.

I have a feeling this has to do with the router looking for a path of / but seeing index.html?

Here's a repo where you can reproduce the problem.

Below is some relevant code:

main.js:

import Vue from 'vue';
import App from './App.vue';
import router from './router/router.js';

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  // replace the content of

 with App
  render: h => h(App),
});

app.vue:

<template>

    <router-view></router-view>

</template>

/router/router.js:

import Vue from 'vue';
import Router from 'vue-router';

Vue.use(Router);

import Hello from '../components/Hello';

export default new Router({
  'mode': 'history',
  scrollBehavior: () => ({ y: 0 }),
  'routes': [
    {
      'path': '/',
      'component': Hello,
    }
  ]
})

config/index.js:

// see http://vuejs-templates.github.io/webpack for documentation.
var path = require('path');

module.exports = {
  build: {
    env: require('./prod.env'),
    index: path.resolve(__dirname, '../../cordova/www/index.html'),
    assetsRoot: path.resolve(__dirname, '../../cordova/www'),
    assetsSubDirectory: 'static',
    assetsPublicPath: '',
    productionSourceMap: true,
    // Gzip off by default as many popular static hosts such as
    // Surge or Netlify already gzip all static assets for you.
    // Before setting to `true`, make sure to:
    // npm install --save-dev compression-webpack-plugin
    productionGzip: false,
    productionGzipExtensions: ['js', 'css'],
  },
  dev: {
    env: require('./dev.env'),
    port: 8080,
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {},
    // CSS Sourcemaps off by default because relative paths are "buggy"
    // with this option, according to the CSS-Loader README
    // (https://github.com/webpack/css-loader#sourcemaps)
    // In our experience, they generally work as expected,
    // just be aware of this issue when enabling this option.
    cssSourceMap: false,
  }
}


问:
Form won't store data in POST
I'm trying to mke a delete button by a simple form and php won't get any data from POST.

index.php

```<code>    echo '<tr style="background:green; border:1px solid black;"><td>' . date("d M y", strtotime($row["time"]))  . "</td>";
    echo "<td><b>" . $row["caseId"]. "</b></td>";
    echo "<td>" . $row["snPaper"]  . "</td>";
    echo "<td>" . $row["snBox"] . "</td>";
    echo "<td>" . $row["snUnit"] . '</td>';
    echo '<td><form action="remove.php" mehod="post" id="delete"><input type="text" value="kokot" name="id" id="id" /><input type="submit" name="submit" value="Delete"></td>';
    echo '<td>' . $row["id"] . '</td></tr>';
</code>```

remove.php

```<code>$id = $_POST['id'];
echo 'id=' . $id;
print_r($_POST);
// Create connection
$dir = 'sqlite:db.sqlite';

$conn = new PDO($dir) or die("hovno");

$conn->exec("'DELETE FROM favorite_apps WHERE id = '$id" );
</code>```

答:
Try isset

```<code>if(isset($_POST['id'])) {
// id index exists
</code>```

}

Or you can also use

```<code>$id = isset($_POST['id']) ? $_POST['id'] : '';
</code>```

And replace mehod with method in

```<code><form method="post">
</code>```

This will work

Title: Form won't store data in POST

Body:
I'm trying to mke a delete button by a simple form and php won't get any data from POST.

index.php

    echo '
' . date("d M y", strtotime($row["time"]))  . "	";
    echo "" . $row["caseId"]. "	";
    echo "" . $row["snPaper"]  . "	";
    echo "" . $row["snBox"] . "	";
    echo "" . $row["snUnit"] . '	';
    echo '<form action="remove.php" mehod="post" id="delete"><input type="text" value="kokot" name="id" id="id" /><input type="submit" name="submit" value="Delete">	';
    echo '' . $row["id"] . '
';

remove.php

$id = $_POST['id'];
echo 'id=' . $id;
print_r($_POST);
// Create connection
$dir = 'sqlite:db.sqlite';

$conn = new PDO($dir) or die("hovno");

$conn->exec("'DELETE FROM favorite_apps WHERE id = '$id" );

Body:
Try isset

if(isset($_POST['id'])) {
// id index exists

}

Or you can also use

$id = isset($_POST['id']) ? $_POST['id'] : '';

And replace mehod with method in

<form method="post">

This will work


问:
redux-thunk dispatch does not work
I have a problem with thunk and async dispatching. So here is my code:

```<code>function fetchProvider() {
  return (dispatch) => {
    graphqlService(fetchProviderQuery)
      .then((result) => {
        dispatch({
          type: FETCH_PROVIDER,
          data: result.data.data.CurrentProvider,
        });
      });
  };
}

class Dashboard extends React.Component {
  componentDidMount() {
    this.props.fetchProvider();
  }

  render() {
    const { provider } = this.props;

    return (
      <div>
        <ul>
          <li>id: {provider.id}</li>
          <li>name: {provider.name}</li>
          <li>description: {provider.description}</li>
        </ul>
      </div>
    );
  }
}

const mapStateToProps = (state) => ({
  provider: state.provider,
});

const mapDispatchToProps = (dispatch) => ({
  fetchProvider: () => dispatch(fetchProvider()),
});

export default connect(mapStateToProps, mapDispatchToProps)(Dashboard);
</code>```

I don't know why but dispatch inside fetchProvider action creator does not work. graphqlService works well and in moment of dispatching FETCH_PROVIDER action data passed to dispatch is correct but then something goes wrong and reducers doesn't called with this action. What possibly could cause this problem?

答:
Your thunk has to return also the promise, or it won't work as expected.
Just modify slightly your fetchProvider function

```<code>function fetchProvider() {
  return (dispatch) => {
    return graphqlService(fetchProviderQuery)
      .then((result) => {
        dispatch({
          type: FETCH_PROVIDER,
          data: result.data.data.CurrentProvider,
        });
      });
  };
}
</code>```

Title: redux-thunk dispatch does not work

Body:
I have a problem with thunk and async dispatching. So here is my code:

function fetchProvider() {
  return (dispatch) => {
    graphqlService(fetchProviderQuery)
      .then((result) => {
        dispatch({
          type: FETCH_PROVIDER,
          data: result.data.data.CurrentProvider,
        });
      });
  };
}

class Dashboard extends React.Component {
  componentDidMount() {
    this.props.fetchProvider();
  }

  render() {
    const { provider } = this.props;

    return (

id: {provider.id}

name: {provider.name}

description: {provider.description}

    );
  }
}

const mapStateToProps = (state) => ({
  provider: state.provider,
});

const mapDispatchToProps = (dispatch) => ({
  fetchProvider: () => dispatch(fetchProvider()),
});

export default connect(mapStateToProps, mapDispatchToProps)(Dashboard);

I don't know why but dispatch inside fetchProvider action creator does not work. graphqlService works well and in moment of dispatching FETCH_PROVIDER action data passed to dispatch is correct but then something goes wrong and reducers doesn't called with this action. What possibly could cause this problem?

Body:
Your thunk has to return also the promise, or it won't work as expected.
Just modify slightly your fetchProvider function

function fetchProvider() {
  return (dispatch) => {
    return graphqlService(fetchProviderQuery)
      .then((result) => {
        dispatch({
          type: FETCH_PROVIDER,
          data: result.data.data.CurrentProvider,
        });
      });
  };
}


问:
How to invoke method from one component to another component in Angular 2?
I have two different component - one component has click event method for the list users & I want to inherit(invoke) that click event method on detail page(another component) )

How to do that, Please help me...

ANSWER UPDATE

Thanks For your Answers.

I have got the solution by Using extend Class & using super() in constructor.

First Class

```<code>export class TeamsView {
   constructor(private test:TestService){
   }
   ...
}
</code>```

Second Class

```<code>export class TeamsForm extends TeamsView {
   constructor(private test:TestService, private router: Router){
     super(test)
   }
   ...
}
</code>```

答:
You can try this:

```<code><first-component (click)="mySecondComponent.myFunction()"></first-component>
<second-component #mySecondComponent></second-component>
</code>```

myFunction must be public.

Body:
I have two different component - one component has click event method for the list users & I want to inherit(invoke) that click event method on detail page(another component) )

How to do that, Please help me...

ANSWER UPDATE

Thanks For your Answers.

I have got the solution by Using extend Class & using super() in constructor.

First Class

export class TeamsView {
   constructor(private test:TestService){
   }
   ...
}

Second Class

export class TeamsForm extends TeamsView {
   constructor(private test:TestService, private router: Router){
     super(test)
   }
   ...
}

Body:
You can try this:

<first-component (click)="mySecondComponent.myFunction()"></first-component>
<second-component #mySecondComponent></second-component>

myFunction must be public.


问:
I created several stored procedures in phpmyadmin, how to call them using an sql query?
I created several stored procedures in phpmyadmin, how is it possible to call them using an sql query (mysql) ?</p>

答:
```<code>CALL name_of_stored_procedure(parameters);
</code>```

Try this on the 'SQL' tab:

```<code>CREATE DEFINER=`root`@`localhost` PROCEDURE `storedprocedure1`(OUT myvar1 CHAR(64))
SET myvar1="IT ";
CREATE DEFINER=`root`@`localhost` PROCEDURE `storedprocedure2`(OUT myvar2 CHAR(64))
SET myvar2="WORKS";
</code>```

Then call:

```<code>CALL procedure1(@var1);
CALL procedure2(@var2);
SELECT @var1,@var2;
</code>```

Body:
CALL name_of_stored_procedure(parameters);

Try this on the 'SQL' tab:

CREATE DEFINER=`root`@`localhost` PROCEDURE `storedprocedure1`(OUT myvar1 CHAR(64))
SET myvar1="IT ";
CREATE DEFINER=`root`@`localhost` PROCEDURE `storedprocedure2`(OUT myvar2 CHAR(64))
SET myvar2="WORKS";

Then call:

CALL procedure1(@var1);
CALL procedure2(@var2);
SELECT @var1,@var2;


问:
Retrieve Google Access Token after authenticated using Firebase Authentication
I am trying to retrieve Google Access Token to access Google REST API such as YouTube Data API from an authenticated user (using Firebase Authentication).

I have successfully integrated Google Sign-In in my app with the help of Firebase-UI for Android - Auth library. The token retrieved from FirebaseUser.getToken() method is not a valid Google Access Token for REST API.

```<code>user.getToken(true).addOnCompleteListener(new OnCompleteListener<GetTokenResult>() {
    public void onComplete(@NonNull Task<GetTokenResult> task) {
        if (task.isSuccessful()) {
            String token = task.getResult().getToken();
            // 'token' is not a Google Access Token
        }
    }
});
</code>```

In Google Sign-In for Web guide, it's possible to get the access token by calling var token = result.credential.accessToken;, but I can't find the similar method in Android.

Any inputs? Please comment here if I do not provide enough information. Thank you :)

答:
Try GoogleAuthUtil.getToken where scope is like "oauth2:scope1 scope2 scope3" </p>

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(getString(R.string.default_web_client_id))
            .requestEmail()
            .build();

    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this, this)
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
            .build();
}

private void signIn() {
    Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
    startActivityForResult(signInIntent, RC_SIGN_IN);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == RC_SIGN_IN) {
        GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
        if (result.isSuccess()) {
            final GoogleSignInAccount account = result.getSignInAccount();

                Runnable runnable = new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String scope = "oauth2:"+Scopes.EMAIL+" "+ Scopes.PROFILE;
                            String accessToken = GoogleAuthUtil.getToken(getApplicationContext(), account.getAccount(), scope, new Bundle());
                            Log.d(TAG, "accessToken:"+accessToken); //accessToken:ya29.Gl...

                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (GoogleAuthException e) {
                            e.printStackTrace();
                        }
                    }
                };
                AsyncTask.execute(runnable);

        } else {
        }
    }
}
</code>```

Body:
I am trying to retrieve Google Access Token to access Google REST API such as YouTube Data API from an authenticated user (using Firebase Authentication).

I have successfully integrated Google Sign-In in my app with the help of Firebase-UI for Android - Auth library. The token retrieved from FirebaseUser.getToken() method is not a valid Google Access Token for REST API.

user.getToken(true).addOnCompleteListener(new OnCompleteListener<GetTokenResult>() {
    public void onComplete(@NonNull Task<GetTokenResult> task) {
        if (task.isSuccessful()) {
            String token = task.getResult().getToken();
            // 'token' is not a Google Access Token
        }
    }
});

In Google Sign-In for Web guide, it's possible to get the access token by calling var token = result.credential.accessToken;, but I can't find the similar method in Android.

Any inputs? Please comment here if I do not provide enough information. Thank you :)

Body:
Try GoogleAuthUtil.getToken where scope is like "oauth2:scope1 scope2 scope3"

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(getString(R.string.default_web_client_id))
            .requestEmail()
            .build();

    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this, this)
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
            .build();
}

private void signIn() {
    Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
    startActivityForResult(signInIntent, RC_SIGN_IN);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == RC_SIGN_IN) {
        GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
        if (result.isSuccess()) {
            final GoogleSignInAccount account = result.getSignInAccount();

                Runnable runnable = new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String scope = "oauth2:"+Scopes.EMAIL+" "+ Scopes.PROFILE;
                            String accessToken = GoogleAuthUtil.getToken(getApplicationContext(), account.getAccount(), scope, new Bundle());
                            Log.d(TAG, "accessToken:"+accessToken); //accessToken:ya29.Gl...

                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (GoogleAuthException e) {
                            e.printStackTrace();
                        }
                    }
                };
                AsyncTask.execute(runnable);

        } else {
        }
    }
}


问:
XML Serialize elements inside one another
I have a class that could be serialized on its own, for example:

```<code>[XmlRoot("NameOfMyRoot", Namespace = "myNamespace")]
public class Inner
{
    public Inner(){}
    public string SomeString { get; set; }
}
</code>```

Which is perfectly serializing into (I am using ns alias for myNamespace, see full demo)

```<code><?xml version="1.0" encoding="utf-16"?>
<NameOfMyRoot xmlns:ns="myNamespace">
    <ns:SomeString></ns:SomeString>
</NameOfMyRoot>
</code>```

Now I want this object to be part of another one (the wrapper):

```<code>[XmlRoot("Root")]
public class Outer<T>
{
    public T Property{ get; set; }

    public Outer(){}
    public Outer(T inner)
    {
        Property = inner;
    }
}
</code>```

Which gives me this:

```<code><?xml version="1.0" encoding="utf-16"?>
<Root xmlns:ns="myNamespace">
    <Property>
        <ns:SomeString></ns:SomeString>
    </Property>
</Root>
</code>```

What I want is just embedding inner object as-is into its parent, like so:

```<code><?xml version="1.0" encoding="utf-16"?>
<Root>
    <NameOfMyRoot xmlns:ns="myNamespace">
        <ns:SomeString></ns:SomeString>
    </NameOfMyRoot>
</Root>
</code>```

Notice that namespace should not move to root, and I can't specify element's name, since there will be many different types.
Fiddle with full example.

Of cource, I can just serialize them separately and combine through some nasty string manipulation, but I hope there is a neat way to achieve this somehow.

答:
There's no easy way to do that. You can do it at runtime, though:

```<code>// perhaps discover these details at runtime
var attribs = new XmlAttributeOverrides();
attribs.Add(typeof(Outer<Inner>), "Property", new XmlAttributes
{
    XmlElements = { new XmlElementAttribute {ElementName = "NameOfMyRoot" } }
});
attribs.Add(typeof(Inner), "SomeString", new XmlAttributes
{
    XmlElements = { new XmlElementAttribute {  Namespace = "myNamespace"} }
});

var ser = new XmlSerializer(typeof(Outer<Inner>), attribs);

var obj = new Outer<Inner> { Property = new Inner { SomeString = "abc" } };
ser.Serialize(Console.Out, obj);
</code>```

Note that you must store and re-use such a serializer; for simple new XmlSerializer() examples, the serializer is cached internally and re-used; however, for non-trivial cases like this, a new dynamic type is emitted each time, so you will leak memory (it won't be unloaded).

That gives you:

```<code><Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <NameOfMyRoot>
    <SomeString xmlns="myNamespace">abc</SomeString>
  </NameOfMyRoot>
</Root>
</code>```

If you don't want the two xmlns alias declaration, those can be removed separately, but they do not change the meaning, at least to a compliant reader. Likewise, the ns can be added as an alias:

```<code>var obj = new Outer<Inner> { Property = new Inner { SomeString = "abc" } };
var ns = new XmlSerializerNamespaces();
ns.Add("", "");
ns.Add("ns", "myNamespace");
ser.Serialize(Console.Out, obj, ns);
</code>```

which gives:

```<code><Root xmlns:ns="myNamespace">
  <NameOfMyRoot>
    <ns:SomeString>abc</ns:SomeString>
  </NameOfMyRoot>
</Root>
</code>```

As an alternative approach:

```<code>using System;
using System.Xml;
using System.Xml.Serialization;

[XmlRoot("NameOfMyRoot")]
public class Inner
{
    public Inner() { }
    [XmlElement(Namespace = "myNamespace")]
    public string SomeString { get; set; }
}
static class Program
{
    static void Main()
    {
        using (XmlWriter writer = XmlWriter.Create(Console.Out))
        {
            writer.WriteStartDocument(false);
            writer.WriteStartElement("Root");

            var ser = new XmlSerializer(typeof(Inner));
            var obj = new Inner { SomeString = "abc" };

            var ns = new XmlSerializerNamespaces();
            ns.Add("", "");
            ns.Add("ns", "myNamespace");
            ser.Serialize(writer, obj, ns);

            writer.WriteEndElement();
            writer.WriteEndDocument();
        }
    }
}
</code>```

What I've done here is to manually write the root node, and only get the XmlSerializer to write the inner content. Note that I had to change the attributes aroung SomeString to make it work in the way you expect (where it is the string that has the namespace, not the object).

Body:
I have a class that could be serialized on its own, for example:

[XmlRoot("NameOfMyRoot", Namespace = "myNamespace")]
public class Inner
{
    public Inner(){}
    public string SomeString { get; set; }
}

Which is perfectly serializing into (I am using ns alias for myNamespace, see full demo)

<?xml version="1.0" encoding="utf-16"?>
<NameOfMyRoot xmlns:ns="myNamespace">
    <ns:SomeString></ns:SomeString>
</NameOfMyRoot>

Now I want this object to be part of another one (the wrapper):

[XmlRoot("Root")]
public class Outer<T>
{
    public T Property{ get; set; }

    public Outer(){}
    public Outer(T inner)
    {
        Property = inner;
    }
}

Which gives me this:

<?xml version="1.0" encoding="utf-16"?>
<Root xmlns:ns="myNamespace">
    <Property>
        <ns:SomeString></ns:SomeString>
    </Property>
</Root>

What I want is just embedding inner object as-is into its parent, like so:

<?xml version="1.0" encoding="utf-16"?>
<Root>
    <NameOfMyRoot xmlns:ns="myNamespace">
        <ns:SomeString></ns:SomeString>
    </NameOfMyRoot>
</Root>

Notice that namespace should not move to root, and I can't specify element's name, since there will be many different types.
Fiddle with full example.

Of cource, I can just serialize them separately and combine through some nasty string manipulation, but I hope there is a neat way to achieve this somehow.

Body:
There's no easy way to do that. You can do it at runtime, though:

// perhaps discover these details at runtime
var attribs = new XmlAttributeOverrides();
attribs.Add(typeof(Outer<Inner>), "Property", new XmlAttributes
{
    XmlElements = { new XmlElementAttribute {ElementName = "NameOfMyRoot" } }
});
attribs.Add(typeof(Inner), "SomeString", new XmlAttributes
{
    XmlElements = { new XmlElementAttribute {  Namespace = "myNamespace"} }
});

var ser = new XmlSerializer(typeof(Outer<Inner>), attribs);

var obj = new Outer<Inner> { Property = new Inner { SomeString = "abc" } };
ser.Serialize(Console.Out, obj);

Note that you must store and re-use such a serializer; for simple new XmlSerializer() examples, the serializer is cached internally and re-used; however, for non-trivial cases like this, a new dynamic type is emitted each time, so you will leak memory (it won't be unloaded).

That gives you:

<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <NameOfMyRoot>
    <SomeString xmlns="myNamespace">abc</SomeString>
  </NameOfMyRoot>
</Root>

If you don't want the two xmlns alias declaration, those can be removed separately, but they do not change the meaning, at least to a compliant reader. Likewise, the ns can be added as an alias:

var obj = new Outer<Inner> { Property = new Inner { SomeString = "abc" } };
var ns = new XmlSerializerNamespaces();
ns.Add("", "");
ns.Add("ns", "myNamespace");
ser.Serialize(Console.Out, obj, ns);

which gives:

<Root xmlns:ns="myNamespace">
  <NameOfMyRoot>
    <ns:SomeString>abc</ns:SomeString>
  </NameOfMyRoot>
</Root>

As an alternative approach:

using System;
using System.Xml;
using System.Xml.Serialization;

[XmlRoot("NameOfMyRoot")]
public class Inner
{
    public Inner() { }
    [XmlElement(Namespace = "myNamespace")]
    public string SomeString { get; set; }
}
static class Program
{
    static void Main()
    {
        using (XmlWriter writer = XmlWriter.Create(Console.Out))
        {
            writer.WriteStartDocument(false);
            writer.WriteStartElement("Root");

            var ser = new XmlSerializer(typeof(Inner));
            var obj = new Inner { SomeString = "abc" };

            var ns = new XmlSerializerNamespaces();
            ns.Add("", "");
            ns.Add("ns", "myNamespace");
            ser.Serialize(writer, obj, ns);

            writer.WriteEndElement();
            writer.WriteEndDocument();
        }
    }
}

What I've done here is to manually write the root node, and only get the XmlSerializer to write the inner content. Note that I had to change the attributes aroung SomeString to make it work in the way you expect (where it is the string that has the namespace, not the object).


问:
Model is null?
I've read a lot of similar posts about null model but my case is very very simple and still the model on Create action is null. What am I doing wrong???

Here is the situation: One main view, two strongly typed partial views inside, each binded to a public property of the main model. Any help is appreciated.
models:

```<code>public class SimpleModel1
{
    public IEnumerable<string> SomeStrings1 { get; set; }
}

public class SimpleModel2
{
    public IEnumerable<string> SomeStrings2 { get; set; }
}

public class ComplexModel
{
    public SimpleModel1 model1 { get; set; }
    public SimpleModel2 model2 { get; set; }
    public IEnumerable<string> SomeStringsComplex { get; set; }
}
</code>```

int he controller:

```<code>public ActionResult Create()
    {
        ComplexModel complex = new ComplexModel();
        complex.model1 = new SimpleModel1();
        complex.model1.SomeStrings1 = new List<string> { "a1", "a2", "a3"};

        complex.model2 = new SimpleModel2();
        complex.model2.SomeStrings2 = new List<string> { "b1", "b2", "b3" };

        complex.SomeStringsComplex = new List<string> { "c1", "c2", "c3" };
        return View(complex);
    }

    [HttpPost]
    public ActionResult Create(ComplexModel model)
    {
        if (ModelState.IsValid)
        {
            var test = model.SomeStringsComplex;
        }
        return View();
    }
</code>```

Views:
2 strong partial views -each for model

```<code><%@ Control Language="C#"
Inherits="System.Web.Mvc.ViewUserControl<MvcApp1.Models.SimpleModel2>" %>

<fieldset>
    <legend>Fields</legend>
    <% foreach (string item in Model.SomeStrings2)
            {%>
            <p>
            <label for="Title">Item Title:</label>
            <%= Html.TextBox(item,item)%>
            </p>
            <%
            }
         %>
</fieldset>
</code>```

1 main view:

```<code><%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
    Inherits="System.Web.Mvc.ViewPage<MvcApp1.Models.ComplexModel>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
 Create
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

<h2>Create</h2>
 <% using (Html.BeginForm()) {%>
 <fieldset>
<div> Own values
<% foreach (string item in Model.SomeStringsComplex)
            {%>
            <p>
            <label for="Title">Item Title:</label>
            <%= Html.TextBox(item,item) %>
            </p>
            <%
            }
         %>
</div>
<div>Simple values 1
<%Html.RenderPartial("SimpleModelView1", this.ViewData.Model.model1, new ViewDataDictionary()); %>
</div>

<div>Simple values 2
<%Html.RenderPartial("SimpleModelView2", Model.model2, new ViewDataDictionary()); %>
</div>
<p>
            <input type="submit" value="Create" />
        </p>
</fieldset>
 <% } %>
</code>```

答:
Finally I found a solution. The data posted to Create method should look s.th. like this:

```<code>[HttpPost]
public ActionResult Create(ComplexModel mainModel, SimpleModel nestedModel, SimpleModel2 nested2Model)
{
    if (ModelState.IsValid)
    {
        var main = mainModel;
        var nested1 = nestedModel;
        var nested2 = nested2Model;
    }

    return View();
}
</code>```

The nested parameters are not null when the models are binded to partial views. If used in the main form through main model than the values are in the instance of the main model. I've also changed IEnumerable<string> to IList<string> and then rendered the string values with

```<code>for (int i = 0; i < Model.Strings.Count; i++)
{ %>
    <%: Html.EditorFor(m => m.Strings[i])%>
<% }
</code>```

Thanks all

Title: Model is null?

Body:
I've read a lot of similar posts about null model but my case is very very simple and still the model on Create action is null. What am I doing wrong???

Here is the situation: One main view, two strongly typed partial views inside, each binded to a public property of the main model. Any help is appreciated.
models:

public class SimpleModel1
{
    public IEnumerable<string> SomeStrings1 { get; set; }
}

public class SimpleModel2
{
    public IEnumerable<string> SomeStrings2 { get; set; }
}

public class ComplexModel
{
    public SimpleModel1 model1 { get; set; }
    public SimpleModel2 model2 { get; set; }
    public IEnumerable<string> SomeStringsComplex { get; set; }
}

int he controller:

public ActionResult Create()
    {
        ComplexModel complex = new ComplexModel();
        complex.model1 = new SimpleModel1();
        complex.model1.SomeStrings1 = new List<string> { "a1", "a2", "a3"};

        complex.model2 = new SimpleModel2();
        complex.model2.SomeStrings2 = new List<string> { "b1", "b2", "b3" };

        complex.SomeStringsComplex = new List<string> { "c1", "c2", "c3" };
        return View(complex);
    }

    [HttpPost]
    public ActionResult Create(ComplexModel model)
    {
        if (ModelState.IsValid)
        {
            var test = model.SomeStringsComplex;
        }
        return View();
    }

Views:
2 strong partial views -each for model

<%@ Control Language="C#"
Inherits="System.Web.Mvc.ViewUserControl<MvcApp1.Models.SimpleModel2>" %>

<fieldset>
    <legend>Fields</legend>
    <% foreach (string item in Model.SomeStrings2)
            {%>

            Item Title:
            <%= Html.TextBox(item,item)%>

            <%
            }
         %>
</fieldset>

1 main view:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
    Inherits="System.Web.Mvc.ViewPage<MvcApp1.Models.ComplexModel>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
 Create
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

Create

 <% using (Html.BeginForm()) {%>
 <fieldset>

 Own values
<% foreach (string item in Model.SomeStringsComplex)
            {%>

            Item Title:
            <%= Html.TextBox(item,item) %>

            <%
            }
         %>

Simple values 1
<%Html.RenderPartial("SimpleModelView1", this.ViewData.Model.model1, new ViewDataDictionary()); %>

Simple values 2
<%Html.RenderPartial("SimpleModelView2", Model.model2, new ViewDataDictionary()); %>

            <input type="submit" value="Create" />

</fieldset>
 <% } %>

Body:
Finally I found a solution. The data posted to Create method should look s.th. like this:

[HttpPost]
public ActionResult Create(ComplexModel mainModel, SimpleModel nestedModel, SimpleModel2 nested2Model)
{
    if (ModelState.IsValid)
    {
        var main = mainModel;
        var nested1 = nestedModel;
        var nested2 = nested2Model;
    }

    return View();
}

The nested parameters are not null when the models are binded to partial views. If used in the main form through main model than the values are in the instance of the main model. I've also changed IEnumerable<string> to IList<string> and then rendered the string values with

for (int i = 0; i < Model.Strings.Count; i++)
{ %>
    <%: Html.EditorFor(m => m.Strings[i])%>
<% }

Thanks all


问:
[KIK MESSENGER]Configure Bot, JSON give a suggestion
my question is , how do i add something like a suggestion, here is how it works

User : suggestions
Bot : We're happy to hear that you have a suggestion! Please type your suggestion below
User : Pleaz add sumthin cool
Bot: Thanks for suggesting!
[ Bot Sends the suggestion to my kik pringlejingle]

id like to know how go do this using JSON

答:
Is 'pringlejingle' a chat bot? You won't be able to send a message directly to your user account, but you could build a chatbot to do this.

Have a look at https://dev.kik.com/ for the API reference. There's also a python sample bot available on github (linked in the above dev docs).

You can also reach out to bots@kik.com for development help.


问:
Google Tag Manager Click Variables sometimes not populating on click
I'm using Google Tag Manager click variables click element and click url to track button clicks on my website.

For some reason, the Click variables are sometimes not populating upon click sending "undefined" data to Google Tag Manager.

For example the BOOK NOW button on this page in both desktop and mobile (http://www.maverickhelicopter.com/mobile/foodie.aspx) often fail to populate click variable data. This is just an example page.

It happens on other pages as well (both desktop and mobile version). If it refresh the page a few times or start a new session and try the click again the variables populate.

Does anyone know why this might be happening? Is it an issue with the way Tag Manager is loading, or with the html on the site? Website is built in ASP.net and Google Tag Manager is installed per the instructions provided by Google.

答:
It's happening becuase the actual click element is different depending where exactly you click on your button. From your page:

Notice how "BOOK NOW" button is not fully highlighted. That means when you click outside of highligted area the browser understands to navigate to href page but actual clicked element in GTM is not the link href="..."> but rather your wrapper
 element which does not have url so that's why you can see "undefined"

You can fix it by removing any padding you have set on  link inside your wrapper div.

Body:
It's happening becuase the actual click element is different depending where exactly you click on your button. From your page:

Notice how "BOOK NOW" button is not fully highlighted. That means when you click outside of highligted area the browser understands to navigate to href page but actual clicked element in GTM is not the link <a href="..."> but rather your wrapper <div style="float:right; width:50%;> element which does not have url so that's why you can see "undefined"

You can fix it by removing any padding you have set on  link inside your wrapper div.


问:
R - Calculate difference (similarity measure) between similar datasets
I have seen many questions that touch on this topic but haven't yet found an answer. If I have missed a question that does answer this question, please do mark this and point us to the question.

Scenario: We have a benchmark dataset, we have imputation methods, we systematically delete values from the benchmark and use two different imputation methods. Thus we have a benchmark, imputedData1 and imputedData2.

Question: Is there a function that can produce a number that represents the difference between the benchmark and imputedData1 or/and the difference between the benchmark and imputedData2. Ie function(benchmark, imputedData1) = 3.3 and function(benchmark, imputedData2) = 2.8

Note: Datasets are numerical, datasets are the same size, method should work at the data level if possible (ie not creating a regression and comparing regressions - unless it can work with ANY numerical dataset).

Reproducible datasets, they have only been changed in the first row:

benchmark:

```<code>> head(mtcars,n=10)
                   mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Mazda RX4         21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag     21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
Datsun 710        22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive    21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout 18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
Valiant           18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
Duster 360        14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
Merc 240D         24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2
Merc 230          22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2
Merc 280          19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4
</code>```

imputedData1:

```<code>> head(mtcars,n=10)
                   mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Mazda RX4         22.0   4 108.0 100 3.90 2.200 16.46  0  1    4    4
Mazda RX4 Wag     21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
Datsun 710        22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive    21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout 18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
Valiant           18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
Duster 360        14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
Merc 240D         24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2
Merc 230          22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2
Merc 280          19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4
</code>```

imputedData2:

```<code>> head(mtcars,n=10)
                   mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Mazda RX4         18.0   6 112.0 105 3.90 2.620 16.46  0  0    3    4
Mazda RX4 Wag     21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
Datsun 710        22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive    21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout 18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
Valiant           18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
Duster 360        14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
Merc 240D         24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2
Merc 230          22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2
Merc 280          19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4
</code>```

I have tried to use RMSE (root mean squared error) but it didn't work very well so I am trying to find other ways to tackle this problem.

答:
A simple implementation of what was discussed in the comments that gives a result with same order of magnitude as P Lapointe's answer, just FYI.</p>

```<code>library(magrittr)
center_and_reduce_df <- function(df,bm){
  centered <- mapply('-',df,sapply(bm,mean)) %>% as.data.frame(stringsAsFactors= FALSE)
  reduced <- mapply('/',centered,sapply(bm,sd)) %>% as.data.frame(stringsAsFactors= FALSE)
}
mean((center_and_reduce_df(id1,bm) - center_and_reduce_df(bm,bm))^2) # 0.03083166
</code>```

Body:
I have seen many questions that touch on this topic but haven't yet found an answer. If I have missed a question that does answer this question, please do mark this and point us to the question.

Scenario: We have a benchmark dataset, we have imputation methods, we systematically delete values from the benchmark and use two different imputation methods. Thus we have a benchmark, imputedData1 and imputedData2.

Question: Is there a function that can produce a number that represents the difference between the benchmark and imputedData1 or/and the difference between the benchmark and imputedData2. Ie function(benchmark, imputedData1) = 3.3 and function(benchmark, imputedData2) = 2.8

Note: Datasets are numerical, datasets are the same size, method should work at the data level if possible (ie not creating a regression and comparing regressions - unless it can work with ANY numerical dataset).

Reproducible datasets, they have only been changed in the first row:

benchmark:

> head(mtcars,n=10)
                   mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Mazda RX4         21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag     21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
Datsun 710        22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive    21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout 18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
Valiant           18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
Duster 360        14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
Merc 240D         24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2
Merc 230          22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2
Merc 280          19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4

imputedData1:

> head(mtcars,n=10)
                   mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Mazda RX4         22.0   4 108.0 100 3.90 2.200 16.46  0  1    4    4
Mazda RX4 Wag     21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
Datsun 710        22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive    21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout 18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
Valiant           18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
Duster 360        14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
Merc 240D         24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2
Merc 230          22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2
Merc 280          19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4

imputedData2:

> head(mtcars,n=10)
                   mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Mazda RX4         18.0   6 112.0 105 3.90 2.620 16.46  0  0    3    4
Mazda RX4 Wag     21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
Datsun 710        22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive    21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout 18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
Valiant           18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
Duster 360        14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
Merc 240D         24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2
Merc 230          22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2
Merc 280          19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4

I have tried to use RMSE (root mean squared error) but it didn't work very well so I am trying to find other ways to tackle this problem.

Body:
A simple implementation of what was discussed in the comments that gives a result with same order of magnitude as P Lapointe's answer, just FYI.

library(magrittr)
center_and_reduce_df <- function(df,bm){
  centered <- mapply('-',df,sapply(bm,mean)) %>% as.data.frame(stringsAsFactors= FALSE)
  reduced <- mapply('/',centered,sapply(bm,sd)) %>% as.data.frame(stringsAsFactors= FALSE)
}
mean((center_and_reduce_df(id1,bm) - center_and_reduce_df(bm,bm))^2) # 0.03083166


问:
How can I get data from a Cross domain API
I'm trying to get data from an API in a different domain but I get this error:

XMLHttpRequest cannot load https://www.bitstamp.net/api/ticker/. No
  'Access-Control-Allow-Origin' header is present on the requested
  resource. Origin 'localhost' is therefore not allowed
  access.

I tried to add this in the header but it still doesn't work:

```<code><!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    Access-Control-Allow-Origin: https://www.bitstamp.net
</head>
<body>
<script src="Index.js"></script>
</body>
</html>
</code>```

This is my JavaScript:

```<code>var ticker = "https://www.bitstamp.net/api/ticker/";
$.ajax({
    dataType: "json",
    url: ticker,
    type: "POST",
    crossDomain: true,
    scriptCharset: "utf-8"
});
</code>```

I can not use JSONP because the website doesn't support this.
How can I receive the data from the API with JSON on a different domain?
I would like to do this with JavaScript or C#.

答:
there is a security impact if you allow * with CORS. A script from any other website will be able to get the data from your api on logged in users browser.
never use * with CORS, whitelist your allowed host instead.</p>

Body:
I'm trying to get data from an API in a different domain but I get this error:

XMLHttpRequest cannot load https://www.bitstamp.net/api/ticker/. No
  'Access-Control-Allow-Origin' header is present on the requested
  resource. Origin 'localhost' is therefore not allowed
  access.

I tried to add this in the header but it still doesn't work:

<!DOCTYPE html>

    <title></title>
    Access-Control-Allow-Origin: https://www.bitstamp.net

This is my JavaScript:

var ticker = "https://www.bitstamp.net/api/ticker/";
$.ajax({
    dataType: "json",
    url: ticker,
    type: "POST",
    crossDomain: true,
    scriptCharset: "utf-8"
});

I can not use JSONP because the website doesn't support this.
How can I receive the data from the API with JSON on a different domain?
I would like to do this with JavaScript or C#.


问:
What is the best way to have custom css styles to theme a layout?
Let's say we have a massive CSS file that is used to style the layout of an application. Now, we want to let users change the colours of the layout to personalize it. What is the best way to do this customization, like in terms of design and architecture? I'm looking for a solution that is pretty easy to implement and isn't very intrusive.

I also don't want to make the whole css file templated on the server if I don't have to. I'd like to keep it in my /css file if it's possible, without any server dependencies.

Ideally, I'd like to just override the styles in the default, but I don't think that's possible as it will probably erase the existing styles. Which means I'll have duplicate style information as I overwrite them... which is also bad. Duplication = bad.

I guess we can assume that there's some server object related their account that has several properties for various colours, like backgrounds, menu tabs, link colours, hovered versions, etc.

```<code>public class Theme {

    private String headerBackground = "#172636";
    private String displayName = "#ffffff";

    private String tabBackground = "#284767";
    private String tabText = displayName;
    private String hoverTabBackground = tabBackground;
    private String hoverTabText = tabText;
    private String selectedTabBackground = "#f5f5f5";
    private String selectedTabText = "#172636";

    private String tableHeaderBackground = headerBackground;
    private String tableHeaderText = displayName;
    private String tableSubHeaderBackground = tabBackground;
    private String tableSubHeaderText = displayName;
    private String hoverTableRowBackground = "#c0d2e4";

    private String link = "#4e6c92";
</code>```

My best guess is to just serve the entire css file and have my MVC framework merge the Theme with the css text and than serve it out. Is this the best way? Will that force the browser to never cache it?

My application is using Spring/Hibernate, but I'm pretty sure any recommendations even if you don't use Java/Spring will be doable with these technologies.

Thanks for the help.

答:
Letting visitors/users customise their look & feel can be rather fraught.  You will need to store the properties in their profile to persist that look & feel across browser sessions.

In essence this means serving up their custom CSS file which you render on demand.  You could cache this on their client and use client-side JS to re-load this file when/if they change their LAF preferences.

One way is to link to their stylesheet like this:

```<code><link type="text/css" rel="stylesheet" href="siteStyles.css" />
<link type="text/css" rel="stylesheet"
      href="customStylesheet.jsp?userId=123123123" />
</code>```

You'd need a fairly stand-alone application listener that simply loads their profile and (probably) populates a template file using string replacements (or whatever is best).  You'll need to make sure the response mime-type is set to "text/css".  The browser will do the rest.

To force the browser to re-load the CSS file,  simply add some guff,  such as a version number, to the querystring:

```<code><link type="text/css" rel="stylesheet"
   href="customStylesheet.jsp?userId=123123123&vn=123" />
</code>```

Body:
Let's say we have a massive CSS file that is used to style the layout of an application. Now, we want to let users change the colours of the layout to personalize it. What is the best way to do this customization, like in terms of design and architecture? I'm looking for a solution that is pretty easy to implement and isn't very intrusive.

I also don't want to make the whole css file templated on the server if I don't have to. I'd like to keep it in my /css file if it's possible, without any server dependencies.

Ideally, I'd like to just override the styles in the default, but I don't think that's possible as it will probably erase the existing styles. Which means I'll have duplicate style information as I overwrite them... which is also bad. Duplication = bad.

I guess we can assume that there's some server object related their account that has several properties for various colours, like backgrounds, menu tabs, link colours, hovered versions, etc.

public class Theme {

    private String headerBackground = "#172636";
    private String displayName = "#ffffff";

    private String tabBackground = "#284767";
    private String tabText = displayName;
    private String hoverTabBackground = tabBackground;
    private String hoverTabText = tabText;
    private String selectedTabBackground = "#f5f5f5";
    private String selectedTabText = "#172636";

    private String tableHeaderBackground = headerBackground;
    private String tableHeaderText = displayName;
    private String tableSubHeaderBackground = tabBackground;
    private String tableSubHeaderText = displayName;
    private String hoverTableRowBackground = "#c0d2e4";

    private String link = "#4e6c92";

My best guess is to just serve the entire css file and have my MVC framework merge the Theme with the css text and than serve it out. Is this the best way? Will that force the browser to never cache it?

My application is using Spring/Hibernate, but I'm pretty sure any recommendations even if you don't use Java/Spring will be doable with these technologies.

Thanks for the help.

Body:
Letting visitors/users customise their look & feel can be rather fraught.  You will need to store the properties in their profile to persist that look & feel across browser sessions.

In essence this means serving up their custom CSS file which you render on demand.  You could cache this on their client and use client-side JS to re-load this file when/if they change their LAF preferences.

One way is to link to their stylesheet like this:

<link type="text/css" rel="stylesheet" href="siteStyles.css" />
<link type="text/css" rel="stylesheet"
      href="customStylesheet.jsp?userId=123123123" />

You'd need a fairly stand-alone application listener that simply loads their profile and (probably) populates a template file using string replacements (or whatever is best).  You'll need to make sure the response mime-type is set to "text/css".  The browser will do the rest.

To force the browser to re-load the CSS file,  simply add some guff,  such as a version number, to the querystring:

<link type="text/css" rel="stylesheet"
   href="customStylesheet.jsp?userId=123123123&vn=123" />


问:
How to insert multiple rows from a single query using eloquent/fluent
I have the following query:

```<code>  $query = UserSubject::where('user_id', Auth::id())->select('subject_id')->get();
</code>```

and as expected I get the following result:

```<code>[{"user_id":8,"subject_id":9},{"user_id":8,"subject_id":2}]
</code>```

Is there a way of copying the above result into another table so that my table looks like this?

```<code>ID|user_id|subject_id
1 |8      |9
2 |8      |2
</code>```

The problem I have is that the $query can expect any number of rows and so im unsure how to iterate through an unknown number of rows.

答:
using Eloquent</p>

```<code>$data = array(
    array('user_id'=>'Coder 1', 'subject_id'=> 4096),
    array('user_id'=>'Coder 2', 'subject_id'=> 2048),
    //...
);

Model::insert($data);
</code>```

Body:
I have the following query:

  $query = UserSubject::where('user_id', Auth::id())->select('subject_id')->get();

and as expected I get the following result:

[{"user_id":8,"subject_id":9},{"user_id":8,"subject_id":2}]

Is there a way of copying the above result into another table so that my table looks like this?

ID|user_id|subject_id
1 |8      |9
2 |8      |2

The problem I have is that the $query can expect any number of rows and so im unsure how to iterate through an unknown number of rows.

Body:
using Eloquent

$data = array(
    array('user_id'=>'Coder 1', 'subject_id'=> 4096),
    array('user_id'=>'Coder 2', 'subject_id'=> 2048),
    //...
);

Model::insert($data);


问:
Google Plus Domains Api Activities: insert 403 Forbidden
I try to use insert activity request through this special form http://joxi.net/J2bykQQS4XYxXm

```<code>    {
  "object": {
    "originalContent": "LaLALaLALa"
  },
  "access": {
    "items": [
      {
        "type": "domain"
      }
    ],
    "domainRestricted": true
  }
}
</code>```

but always I have 403 error in answer. http://joxi.net/DrllG33c4vnb5r

I tried to use user_id instead me but had same results :(

答:
Most likely, you are not doing this as part of a Google Domain. Now also known as "gsuite", this allows companies to be able to post messages that are visible to other members of the same company. This does not allow you to post messages that are available for most Google+ users to see.

There is no public API available from Google to let you post to the public Google+. There is an API available to select partners (such as HootSuite) which let them post to the public Google+, but they seem to be slow or reluctant to add additional partners.

Body:
I try to use insert activity request through this special form http://joxi.net/J2bykQQS4XYxXm

    {
  "object": {
    "originalContent": "LaLALaLALa"
  },
  "access": {
    "items": [
      {
        "type": "domain"
      }
    ],
    "domainRestricted": true
  }
}

but always I have 403 error in answer. http://joxi.net/DrllG33c4vnb5r

I tried to use user_id instead me but had same results :(


问:
ALTER TABLE,Error Code: 1064
I have created database and table with a MySQLWorkBench.But I want to have column with number 1995

```<code>ALTER TABLE ldp ADD COLUMN '1995' INT(128);
</code>```

The response is

```<code>Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''1995' INT(128)' at line 1
</code>```

答:
Column names cannot begin with a number in MySQL unless they are escaped.  The way to escape a column name in MySQL is to use backticks, not single quotes.  Single quotes denote a string literal.  Hence the following should work:

```<code>ALTER TABLE ldp ADD COLUMN `1995` INT(128);
</code>```

But I find it odd to use a column name which starts with a number.  You might want to call it something else beginning with a letter.

Title: ALTER TABLE,Error Code: 1064

Body:
I have created database and table with a MySQLWorkBench.But I want to have column with number 1995

ALTER TABLE ldp ADD COLUMN '1995' INT(128);

The response is

Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''1995' INT(128)' at line 1

Body:
Column names cannot begin with a number in MySQL unless they are escaped.  The way to escape a column name in MySQL is to use backticks, not single quotes.  Single quotes denote a string literal.  Hence the following should work:

ALTER TABLE ldp ADD COLUMN `1995` INT(128);

But I find it odd to use a column name which starts with a number.  You might want to call it something else beginning with a letter.


问:
What's a legit use case for a function call to be on left-hand side of assignment?
There's a compile error in VBA that reads as follows:

Compile error:

Function call on left-hand side of assignment must return Variant or Object.

To produce this compile error, you just need a function:

```<code>Public Function Foo(ByVal x As Integer) As Integer
    Foo = x
End Function
</code>```

..And then a function call on the left-hand side of an assignment - for example:

```<code>Public Sub Test()
    Foo(42) = 12
End Sub
</code>```

If I remove the As Integer return type from the function's signature, I get a function that returns an implicit Variant, and the compiler is satisfied - but now there's a run-time error 424 / "Object Required".

So I make the function return an actual object:

```<code>Public Function Foo(ByVal x As Integer) As Object
    Dim result As Collection
    Set result = New Collection
    result.Add x
    Set Foo = result
End Function

Public Sub Test()
    Foo(42) = 12
End Sub
</code>```

Now at run-time the error is 438 / "Object doesn't support this property or method" - obviously, that Test method makes no sense whatsoever.

I cannot for the life of me think of anything that would be a valid, legitimate (and warranted?) use of a function call on the LHS of an assignment.

That compile error exists for a reason, so there must be a valid use case. What is it?

答:
VB variant is analogous to dynamic in C#, meaning that the type is dynamically resolved at run time. So it would make sense that you can assign a value to a variant type (i.e. the return value of a function that returns a variant type).

I imagine the use case is very narrow and 99.9% of the time, if you're trying to do this, you're doing something wrong.

https://msdn.microsoft.com/VBA/Language-Reference-VBA/articles/function-call-on-left-hand-side-of-assignment-must-return-variant-or-object

Body:
There's a compile error in VBA that reads as follows:

Compile error:

Function call on left-hand side of assignment must return Variant or Object.

To produce this compile error, you just need a function:

Public Function Foo(ByVal x As Integer) As Integer
    Foo = x
End Function

..And then a function call on the left-hand side of an assignment - for example:

Public Sub Test()
    Foo(42) = 12
End Sub

If I remove the As Integer return type from the function's signature, I get a function that returns an implicit Variant, and the compiler is satisfied - but now there's a run-time error 424 / "Object Required".

So I make the function return an actual object:

Public Function Foo(ByVal x As Integer) As Object
    Dim result As Collection
    Set result = New Collection
    result.Add x
    Set Foo = result
End Function

Public Sub Test()
    Foo(42) = 12
End Sub

Now at run-time the error is 438 / "Object doesn't support this property or method" - obviously, that Test method makes no sense whatsoever.

I cannot for the life of me think of anything that would be a valid, legitimate (and warranted?) use of a function call on the LHS of an assignment.

That compile error exists for a reason, so there must be a valid use case. What is it?


问:
JMeter -> http request -> POST parameters don't work in lowercase and changes POST to GET in uppercase
i have a strange issue.
I am testing different group rights of members on a website with JMeter and i have solved the tasks which appeared, for know.

A "http request" which has to "POST" some parameters (4 names, 3 values) doesn't work and has strange behaviors.

I inspect the network dialog of the browser (firefox dev or IE) when i request the new page with the selected parameters and get the following information:
i have 4 parameters, the first has no value and the other 3 have always the same values.
The parameter names are in uppercase.
The Status is 302 Moved Temporarily and not 200.
And i get the expected site.

When i insert these parameters in JMeter (or by value of regex extractor) and set the "http request" to "POST", "Follow Redirects", "Use Keep Alive",
JMeter is send to the url where it comes from and the "http request" shows me a "GET" request in the "Result Tree".
The Status is 200.

When i write the parameter names in lowercase, JMeter is also send back to the previous url but the "Result Tree" has "POST" in the request with the lowercase parameters.
The Status is 200.

When i disable "Follow Redirects", the uppercase parameters get no Response (no html code), but now they were "POST" in the "Result Tree" and have the Status 302 Moved Temporarily.

When i disable "Follow Redirects", the lowercase parameters are still redirecting me to the previous site, the Status is 200.

I don't know why this happens and how i have to handle with JMeter to get to the expected site.

答:
If your redirect is executed in javascript you can't expect Jmeter to execute it:

JMeter does not execute the Javascript found in HTML pages. Nor does
  it render the HTML pages as a browser does

See Jmeter


问:
How to access an element of an array in Assembly?
The documentation says:

(Index ∗ Scale) + Displacement ⎯ This address mode offers an efficient way to index into a static array when the element size is 2,
  4, or 8 bytes. The displacement locates the beginning of the array,
  the index register holds the subscript of the desired array element,
  and the processor automatically converts the subscript into an index
  by applying the scaling factor.

Can Base be used instead of Displacement to specify the beginning of the array:

```<code>Base + (Index ∗ Scale)
</code>```

答:
base, index, scale, and displacement are just the names for the four parts of a memory operand. You are free to use each part for whatever purpose you like. For example, to fetch the n+k-th entry of an array, you might use something like this:

```<code>mov al, [array + ebx + ecx]
</code>```

where n is stored in ebx and k is stored in ecx. In This case, the “base” is really used as an index into the array and so is the “index” part.

Body:
The documentation says:

(Index ∗ Scale) + Displacement ⎯ This address mode offers an efficient way to index into a static array when the element size is 2,
  4, or 8 bytes. The displacement locates the beginning of the array,
  the index register holds the subscript of the desired array element,
  and the processor automatically converts the subscript into an index
  by applying the scaling factor.

Can Base be used instead of Displacement to specify the beginning of the array:

Base + (Index ∗ Scale)

Body:
base, index, scale, and displacement are just the names for the four parts of a memory operand. You are free to use each part for whatever purpose you like. For example, to fetch the n+k-th entry of an array, you might use something like this:

mov al, [array + ebx + ecx]

where n is stored in ebx and k is stored in ecx. In This case, the “base” is really used as an index into the array and so is the “index” part.


问:
Overriding styles of Angular 4 components
I am writing an Angular library that contains re-usable components. I want to deliver some default stylings for these that make sense out of the box, but I want it to be easy to override these default styles or to do fine grained customizations when using these library components in an app.

What is the best practice when doing this? For example, if I have defined a component template for a 'test' component like this and I decided most of the time the width will be set to 50% (simplistic example):

```<code><div class="title">
   Test
</div>

.title {
  width: 50%;
}
</code>```

In one particular consumer app, I want this title to display 100% of the particular container I'm using:

```<code><div class="container">
  <test></test>
</div>
</code>```

In my SCSS for this app component I would then try to do something like:

```<code>test {
  .title {
    width: 100%;
  }
}
</code>```

However currently I am having issues with CSS scope and inheritance precedence, and on more complicated components with many nested elements it might get tricky and unmaintainable to express this way.

Does this even make sense doing this or am I breaking component encapsulation by knowing too much about the internals using CSS like this? If so, how do you handle layout and styling of sub-components like this when trying to fit them into a bigger application? Should it be done instead via data binding particular attributes or an options object?

Any help appreciated!

答:
Create parameterized directives for the part which you would want customizable. Every implementation can then pass its own set of values to the directive. It will be something like</p>

```<code><test [userprop]="value"></test>
</code>```

Body:
I am writing an Angular library that contains re-usable components. I want to deliver some default stylings for these that make sense out of the box, but I want it to be easy to override these default styles or to do fine grained customizations when using these library components in an app.

What is the best practice when doing this? For example, if I have defined a component template for a 'test' component like this and I decided most of the time the width will be set to 50% (simplistic example):

   Test

.title {
  width: 50%;
}

In one particular consumer app, I want this title to display 100% of the particular container I'm using:

  <test></test>

In my SCSS for this app component I would then try to do something like:

test {
  .title {
    width: 100%;
  }
}

However currently I am having issues with CSS scope and inheritance precedence, and on more complicated components with many nested elements it might get tricky and unmaintainable to express this way.

Does this even make sense doing this or am I breaking component encapsulation by knowing too much about the internals using CSS like this? If so, how do you handle layout and styling of sub-components like this when trying to fit them into a bigger application? Should it be done instead via data binding particular attributes or an options object?

Any help appreciated!

Body:
Create parameterized directives for the part which you would want customizable. Every implementation can then pass its own set of values to the directive. It will be something like

<test [userprop]="value"></test>


问:
How can I rearrange an array in MATLAB by a specific rule?
Suppose that I have this array:

```<code>a = [1,2,3,4,5];
</code>```

The output should be something like this:

```<code>1,2,3,4,5
2,1,3,4,5
3,1,2,4,5
4,1,2,3,5
5,1,2,3,4
</code>```

how Can I do this? This function should be valid for different lengths of a.

答:
Using combinatory:</p>

```<code>b = [a.' flipud(nchoosek(a,numel(a)-1))];
</code>```

Body:
Suppose that I have this array:

a = [1,2,3,4,5];

The output should be something like this:

1,2,3,4,5
2,1,3,4,5
3,1,2,4,5
4,1,2,3,5
5,1,2,3,4

how Can I do this? This function should be valid for different lengths of a.

Body:
Using combinatory:

b = [a.' flipud(nchoosek(a,numel(a)-1))];


问:
postgresql "idle in transaction" with all locks granted
A very simple delete (by key) on a small table (700 rows) every now and then stays "idle in transaction" for minutes (takes milliseconds usually) even though all the locks are marked as "granted".

What can I do to pinpoint what causes it?
I'm using this select:

```<code>  SELECT a.datname,
     c.relname,
     l.transactionid,
     l.mode,
     l.GRANTED,
     a.usename,
     a.waiting,
     a.query,
     a.query_start,
     age(now(), a.query_start) AS "age",
     a.pid
FROM  pg_stat_activity a
 JOIN pg_locks         l ON l.pid = a.pid
 JOIN pg_class         c ON c.oid = l.relation
ORDER BY a.query_start;
</code>```

which shows a lot of "RowExclusiveLock"s but all are granted... so I don't see what is causing this spikes of delays.

答:
This is a problem of the application server.

Sessions are in state "idle in transaction" when the application does not end the transaction with COMMIT or ROLLBACK. This is to be considered a bug in the application.

The locks remain (and are of course granted, otherwise the session could not be idle) until the transaction ends.

From PostgreSQL 9.6 on, you can set the parameter idle_in_transaction_session_timeout to terminate such transactions automatically with a ROLLBACK, but that is a band-aid to avoid problems on the database rather than a solution.

Body:
A very simple delete (by key) on a small table (700 rows) every now and then stays "idle in transaction" for minutes (takes milliseconds usually) even though all the locks are marked as "granted".

What can I do to pinpoint what causes it?
I'm using this select:

  SELECT a.datname,
     c.relname,
     l.transactionid,
     l.mode,
     l.GRANTED,
     a.usename,
     a.waiting,
     a.query,
     a.query_start,
     age(now(), a.query_start) AS "age",
     a.pid
FROM  pg_stat_activity a
 JOIN pg_locks         l ON l.pid = a.pid
 JOIN pg_class         c ON c.oid = l.relation
ORDER BY a.query_start;

which shows a lot of "RowExclusiveLock"s but all are granted... so I don't see what is causing this spikes of delays.