问:
CodeIgniter hooks cause automaticaly logout(kill the session)
I'm using CodeIgniter hooks, I'm trying to trigger an action before a controller to be executed(pre_controller) and another action after the controller to be executed. But I'm facing a weird situation, when I enable the hook in $config['enable_hooks'] = TRUE; it trigger automatic logout, I mean it  kills the user session. Could some one helps me on this? May be I made a wrong configuration for the hook.

Here is the hooks configuration:
     hooks.php

```<code>$hook['pre_controller'] = array(
                                'class'    => 'Hookcall',
                                'function' => 'get_post_params',
                                'filename' => 'hookcall.php',
                                'filepath' => 'hooks'
                                );
/*
  hook for saving fraude logs
*/
$hook['post_controller'] = array(
                                'class'    => 'Hookcall',
                                'function' => 'save_logs',
                                'filename' => 'hookcall.php',
                                'filepath' => 'hooks'
                                );
</code>```

答:
Hookcall should NOT extend MY_Controller. It should be a simple class instead</p>

```<code>class Hookcall
{
    public function save_logs()
    {
    }

    public function get_post_params()
    {
    }

    private function get_files_superior_5_percent($params)
    {
    }

}
</code>```

Body:
I'm using CodeIgniter hooks, I'm trying to trigger an action before a controller to be executed(pre_controller) and another action after the controller to be executed. But I'm facing a weird situation, when I enable the hook in $config['enable_hooks'] = TRUE; it trigger automatic logout, I mean it  kills the user session. Could some one helps me on this? May be I made a wrong configuration for the hook.

Here is the hooks configuration:
     hooks.php

$hook['pre_controller'] = array(
                                'class'    => 'Hookcall',
                                'function' => 'get_post_params',
                                'filename' => 'hookcall.php',
                                'filepath' => 'hooks'
                                );
/*
  hook for saving fraude logs
*/
$hook['post_controller'] = array(
                                'class'    => 'Hookcall',
                                'function' => 'save_logs',
                                'filename' => 'hookcall.php',
                                'filepath' => 'hooks'
                                );

Body:
Hookcall should NOT extend MY_Controller. It should be a simple class instead

class Hookcall
{
    public function save_logs()
    {
    }

    public function get_post_params()
    {
    }

    private function get_files_superior_5_percent($params)
    {
    }

}


来源: stackexchange

问:
PHP - How do I access specific array values in nested array?
I have an array like this:

```<code>    Array (
    [0] => Array (
        [0] => 510
        [1] => 984
        [2] => 1045
        [3] => 2068
        [4] => 1054
        [5] => 673
        )
    [1] => Array (
        [0] => 1163
        [1] => 1982
        [2] => 2067
        [3] => 3989
        [4] => 1940
        [5] => 1242
        )
    [2] => Array (
        [0] => june
        [1] => july
        [2] => august
        [3] => september
        [4] => october
        [5] => november
        )
    )
</code>```

I want to access only one of the arrays within the array at a time and echo them out.

For example, I would get: 510, 984, 1045, 2068, 1054, and 673 as one result.

I've looked at multiple threads and answers but nothing that quite solves my issue, I've been able to print out all the values but I just want some specifically.

I'd store it in the variable: $array_item

My most recent attempt was:

```<code>foreach ($array_item as $inner) {
if (is_array($inner)) {
    foreach ($inner[0] as $value) {
        echo "$value \n";
    }
}
}
</code>```

Which gives me: Warning: Invalid argument supplied for foreach().

I thought for sure that would work, what am I doing wrong?

答:
I would use implode, http://php.net/manual/en/function.implode.php

```<code>foreach($array_items as $items) {
    echo implode(', ', $items);
}
</code>```

I see that a comment was made that he wants only the first array to be outputted and not all of them.

```<code>if (is_array($array_item[0])) {
    echo implode(PHP_EOL, $array_item[0]);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have an array like this:

    Array (
    [0] => Array (
        [0] => 510
        [1] => 984
        [2] => 1045
        [3] => 2068
        [4] => 1054
        [5] => 673
        )
    [1] => Array (
        [0] => 1163
        [1] => 1982
        [2] => 2067
        [3] => 3989
        [4] => 1940
        [5] => 1242
        )
    [2] => Array (
        [0] => june
        [1] => july
        [2] => august
        [3] => september
        [4] => october
        [5] => november
        )
    )

I want to access only one of the arrays within the array at a time and echo them out.

For example, I would get: 510, 984, 1045, 2068, 1054, and 673 as one result.

I've looked at multiple threads and answers but nothing that quite solves my issue, I've been able to print out all the values but I just want some specifically.

I'd store it in the variable: $array_item

My most recent attempt was:

foreach ($array_item as $inner) {
if (is_array($inner)) {
    foreach ($inner[0] as $value) {
        echo "$value \n";
    }
}
}

Which gives me: Warning: Invalid argument supplied for foreach().

I thought for sure that would work, what am I doing wrong?

Body:
I would use implode, http://php.net/manual/en/function.implode.php

foreach($array_items as $items) {
    echo implode(', ', $items);
}

I see that a comment was made that he wants only the first array to be outputted and not all of them.

if (is_array($array_item[0])) {
    echo implode(PHP_EOL, $array_item[0]);
}


问:
Nested scrollview inside gridview place is taking only somepart
I have:
1.Coordinator layout
2.appbar layout (child of Coordinator layout)
3.Collapsing toolbar layout (child of app bar)
4.NestedScrollView (child of coordinator)

I want to put a grid view inside NestedScrollView so that user can scroll over the entire screen space.

My problem is that currently the gridview occupies a small portion of the NestedScrollView and not full space of NestedScrollView and scrolls inside that portion,like in this image:

As you can see my gridview height is limited upto only that highlighted portion in sky blue color, i want that to occupy the entire screen space below that image(which is my Collapsing toolbar).i tried different ways but nothing works out.
my xml file is:

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

```<code><android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:id="@+id/app_bar"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.design.widget.CollapsingToolbarLayout
        android:id="@+id/collapsing_toolbar"
        android:layout_width="match_parent"
        android:layout_height="196dp"
        android:background="#3f51b5"
        app:contentScrim="@color/colorPrimary"
        app:expandedTitleMarginEnd="64dp"
        app:expandedTitleMarginStart="48dp"
        app:layout_scrollFlags="scroll|exitUntilCollapsed">

        <ImageView
            android:id="@+id/imageview"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scaleType="centerCrop"
            android:src="@drawable/index"
            app:layout_collapseMode="parallax" />

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_collapseMode="pin"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/AppTheme.PopupOverlay" />
    </android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <GridView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginLeft="1dp"
        android:layout_marginRight="1dp"

        android:id="@+id/gridView"
        android:verticalSpacing="1dp"
        android:horizontalSpacing="1dp"
        android:numColumns="2"
        android:stretchMode="columnWidth"/>

</android.support.v4.widget.NestedScrollView>

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="right|bottom"
    android:layout_margin="@dimen/fab_margin"
    android:src="@android:drawable/ic_dialog_email" />
</code>```

答:
Apoorv Singh's answer helped me, but not fully. You can put a GridView inside a NestedScrollView, but only the 1st row will show up. You need to add the android:fillViewport="true" inside the NestedScrollView definition in order for everything to display properly.

But, when I scroll down, it doesn't scroll past the bottom of the screen. I have a grid with 10 rows, there are multiple rows not on screen, but I cannot scroll down to view them now.

Answer:
This worked for me now. Use RecyclerView with GridLayoutManager instead of GridView. As Recycler view is compatible with Collapsing toolbar as well. And when you use RecyclerView inside NestedScrollView, it works well. Everything sizes correctly, as well as scrolls correctly.

Body:
I have:
1.Coordinator layout
2.appbar layout (child of Coordinator layout)
3.Collapsing toolbar layout (child of app bar)
4.NestedScrollView (child of coordinator)

I want to put a grid view inside NestedScrollView so that user can scroll over the entire screen space.

My problem is that currently the gridview occupies a small portion of the NestedScrollView and not full space of NestedScrollView and scrolls inside that portion,like in this image:

As you can see my gridview height is limited upto only that highlighted portion in sky blue color, i want that to occupy the entire screen space below that image(which is my Collapsing toolbar).i tried different ways but nothing works out.
my xml file is:

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

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:id="@+id/app_bar"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.design.widget.CollapsingToolbarLayout
        android:id="@+id/collapsing_toolbar"
        android:layout_width="match_parent"
        android:layout_height="196dp"
        android:background="#3f51b5"
        app:contentScrim="@color/colorPrimary"
        app:expandedTitleMarginEnd="64dp"
        app:expandedTitleMarginStart="48dp"
        app:layout_scrollFlags="scroll|exitUntilCollapsed">

        <ImageView
            android:id="@+id/imageview"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scaleType="centerCrop"
            android:src="@drawable/index"
            app:layout_collapseMode="parallax" />

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_collapseMode="pin"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/AppTheme.PopupOverlay" />
    </android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <GridView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginLeft="1dp"
        android:layout_marginRight="1dp"

        android:id="@+id/gridView"
        android:verticalSpacing="1dp"
        android:horizontalSpacing="1dp"
        android:numColumns="2"
        android:stretchMode="columnWidth"/>

</android.support.v4.widget.NestedScrollView>

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="right|bottom"
    android:layout_margin="@dimen/fab_margin"
    android:src="@android:drawable/ic_dialog_email" />


问:
Generate SEO friendly URLs (slugs)

Definition

From Wikipedia:

A slug is the part of a URL which identifies a page using
human-readable keywords.

To make the URL easier for users to type, special characters are often
removed or replaced as well. For instance, accented characters are
usually replaced by letters from the English alphabet; punctuation
marks are generally removed; and spaces (which have to be encoded as
%20 or +) are replaced by dashes (-) or underscores (_), which are
more aesthetically pleasing.

Context

I developed a photo-sharing website on which users can upload, share and view photos.

All pages are generated automatically without my grip on the title. Because the title of a photo or the name of a user may contain accented characters or spaces, I needed a function to automatically create slugs and keep readable URLs.

I created the following function which replaces accented characters (âèêëçî), removes punctuation and bad characters (#@&~^!) and transforms spaces in dashes.

Questions

What do you think about this function?

Do you know any other functions to create slugs?

Code

php:

```<code>function sluggable($str) {

    $before = array(
        'àáâãäåòóôõöøèéêëðçìíîïùúûüñšž',
        '/[^a-z0-9\s]/',
        array('/\s/', '/--+/', '/---+/')
    );

    $after = array(
        'aaaaaaooooooeeeeeciiiiuuuunsz',
        '',
        '-'
    );

    $str = strtolower($str);
    $str = strtr($str, $before[0], $after[0]);
    $str = preg_replace($before[1], $after[1], $str);
    $str = trim($str);
    $str = preg_replace($before[2], $after[2], $str);

    return $str;
}
</code>```

答:
```<code>function remove_accents($string)
{
    $a = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûýýþÿŔŕ';
    $b = 'aaaaaaaceeeeiiiidnoooooouuuuybsaaaaaaaceeeeiiiidnoooooouuuyybyRr';
    $string = strtr(utf8_decode($string), utf8_decode($a), $b);
    return utf8_encode($string);
}

function format_slug($title)
{
    $title = remove_accents($title);
    $title = trim(strtolower($title));
    $title = preg_replace('#[^a-z0-9\\-/]#i', '_', $title);
    return trim(preg_replace('/-+/', '-', $title), '-/');
}
</code>```

use : echo format_slug($var);

Title: Generate SEO friendly URLs (slugs)

Body:
Definition

From Wikipedia:

A slug is the part of a URL which identifies a page using
human-readable keywords.

To make the URL easier for users to type, special characters are often
removed or replaced as well. For instance, accented characters are
usually replaced by letters from the English alphabet; punctuation
marks are generally removed; and spaces (which have to be encoded as
%20 or +) are replaced by dashes (-) or underscores (_), which are
more aesthetically pleasing.

Context

I developed a photo-sharing website on which users can upload, share and view photos.

All pages are generated automatically without my grip on the title. Because the title of a photo or the name of a user may contain accented characters or spaces, I needed a function to automatically create slugs and keep readable URLs.

I created the following function which replaces accented characters (âèêëçî), removes punctuation and bad characters (#@&~^!) and transforms spaces in dashes.

Questions

What do you think about this function?

Do you know any other functions to create slugs?

Code

php:

function sluggable($str) {

    $before = array(
        'àáâãäåòóôõöøèéêëðçìíîïùúûüñšž',
        '/[^a-z0-9\s]/',
        array('/\s/', '/--+/', '/---+/')
    );

    $after = array(
        'aaaaaaooooooeeeeeciiiiuuuunsz',
        '',
        '-'
    );

    $str = strtolower($str);
    $str = strtr($str, $before[0], $after[0]);
    $str = preg_replace($before[1], $after[1], $str);
    $str = trim($str);
    $str = preg_replace($before[2], $after[2], $str);

    return $str;
}

Body:
function remove_accents($string)
{
    $a = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûýýþÿŔŕ';
    $b = 'aaaaaaaceeeeiiiidnoooooouuuuybsaaaaaaaceeeeiiiidnoooooouuuyybyRr';
    $string = strtr(utf8_decode($string), utf8_decode($a), $b);
    return utf8_encode($string);
}

function format_slug($title)
{
    $title = remove_accents($title);
    $title = trim(strtolower($title));
    $title = preg_replace('#[^a-z0-9\\-/]#i', '_', $title);
    return trim(preg_replace('/-+/', '-', $title), '-/');
}

use : echo format_slug($var);


问:
How do I use the ES6 import function with a symbolic path to the source file?
I am trying to understand the ES6 import function better, and I need your help.

The Scenario

Let's assume that I have a subset of code within my application that is used frequently, and I arrange all that code into a folder so that it is together.

So now, in three separate files, I have something like the following (note: I'm using TypeScript, so the file names in the example end in '.ts'):

file0.ts:

```<code>import {AbstractCoreCommunicationClass} from '../../../core-packages/communication/abstract-core-communication'
</code>```

file1.ts:

```<code>import {AbstractCoreCommunicationClass} from '../communication/abstract-core-communication'
</code>```

file2.ts:

```<code>import {AbstractCoreCommunicationClass} from '../../../../../core-packages/communication/abstract-core-communication'
</code>```

My Hope

It is my hope that I could clean up these references to something like this:

file0.ts:

```<code>import {AbstractCoreCommunicationClass} from '@my-communication-core/abstract-core-communication'
</code>```

file1.ts:

```<code>import {AbstractCoreCommunicationClass} from '@my-communication-core/abstract-core-communication'
</code>```

file2.ts:

```<code>import {AbstractCoreCommunicationClass} from '@my-communication-core/abstract-core-communication'
</code>```

Things I have Tried

I know that in Laravel (a different framework) that modules can be created and loaded by editing one of the core loader definition files such as composer.json or the main config/app.php file.

I have looked for a similar kind of protocol that can be used in the package.json file to reference non-npm packages, but I have not found any such information. The closest information that I have found is a tutorial in which NPM explains how to use NPM private packages, which would accomplish the same goal as long as I want to pay $7/month for the rest of my life to have my package hosted on their servers.

There must be a way to handle this kind of package management locally, but I have not discovered what it is, and that is why I need YOUR help!

All help is appreciated. There are no wrong answers.  Even a bad answer can sometimes point me in the right direction, so give me your thoughts and let's figure this out together so that everyone can benefit!

答:
HOW TO USE LOCAL PACKAGES IN NPM

It turns out that NPM has a feature that allows me to do exactly what I need to do. I reread the package.json documentation after writing the question above and found that NPM now allows for a local file directory reference to a package.

How it looks in pacakge.json

I used npm to create the linkages (see next section), and then I inspected the package.json file to find the following:

```<code>  "dependencies": {
    "@angular/animations": "^4.0.0",
    "@angular/common": "^4.0.0",
    "@angular/compiler": "^4.0.0",
    "@angular/core": "^4.0.0",
    "@angular/forms": "^4.0.0",
    "@angular/http": "^4.0.0",
    "@angular/platform-browser": "^4.0.0",
    "@angular/platform-browser-dynamic": "^4.0.0",
    "@angular/router": "^4.0.0",
    "core-js": "^2.4.1",
    //###THIS IS MY NEW LINE###
    "data-structures": "file:src/app/medface/data-structures",
    "intl": "^1.2.5",
    "ng2-cookies": "^1.0.12",
    "rxjs": "^5.1.0",
    "showdown": "^1.8.0",
    "to-markdown": "^3.1.0",
    "web-animations-js": "^2.2.5",
    "zone.js": "^0.8.4"
  },
</code>```

Notice how the file: string prepends the source. I then designed a unit test to load one of the files from this directory using the name I assigned.

```<code>import {VisitDataStructure} from 'data-structures/visit';

describe( "The data structure package", ()=>{
    fit("loads without failure and allows the user to import classes within the folder.", ()=>{
        let visit = new VisitDataStructure();
        expect(visit).not.toBeNull();
    } );
} );
</code>```

The test runs with flying colors!

(Note: the function fit is just like it, except it tells the testing system that it should "focus" only on that one test and ignore all the rest.)

How to achieve this using npm

To achieve this local package reference setup, several things must occur in order.

Step 1: Create a package using npm init

Navigate to the sub-folder in the terminal and type npm init (this assumes that you are already using npm, as I am).

Follow the on screen prompts to create your package.json file. The file will ask for a name, this name is how you will refer to the package within your system. In my case, I assigned the name 'data-structures' to the test package.

Step 2: Install the sub package using npm intall --save [pathToLocalFile]

From the root of your application, the same folder that holds the package.json file for your whole application, find the relative path to your new folder.  In my case, it was src/app/medface/data-structures.

If your relative path is correct, then you should be able to use ls or dir to show a file at [relativePath]/package.json (linux/mac) or [relativePath]\package.json (windows)

Then run the command npm install --save [relativePath].

You will see npm do its thing. If it gives you an error, read the error and go back to step #1.  (When I ran it the first time, I got an error and realized that I had to use npm init in the directory before I could install it).

Note: for the terminal command alternative, yes, you CAN use npm install -S [relativePath] -- it is the same command as above.

Step 3: Use your new package name in the code.

Now that it is installed, you can use the name you assigned anywhere within your code, and the package.json file will tell your pre-processor where to find the reference files.

GREAT WORK!  Now go do some awesome coding!

Body:
I am trying to understand the ES6 import function better, and I need your help.

The Scenario

Let's assume that I have a subset of code within my application that is used frequently, and I arrange all that code into a folder so that it is together.

So now, in three separate files, I have something like the following (note: I'm using TypeScript, so the file names in the example end in '.ts'):

file0.ts:

import {AbstractCoreCommunicationClass} from '../../../core-packages/communication/abstract-core-communication'

file1.ts:

import {AbstractCoreCommunicationClass} from '../communication/abstract-core-communication'

file2.ts:

import {AbstractCoreCommunicationClass} from '../../../../../core-packages/communication/abstract-core-communication'

My Hope

It is my hope that I could clean up these references to something like this:

file0.ts:

import {AbstractCoreCommunicationClass} from '@my-communication-core/abstract-core-communication'

file1.ts:

import {AbstractCoreCommunicationClass} from '@my-communication-core/abstract-core-communication'

file2.ts:

import {AbstractCoreCommunicationClass} from '@my-communication-core/abstract-core-communication'

Things I have Tried

I know that in Laravel (a different framework) that modules can be created and loaded by editing one of the core loader definition files such as composer.json or the main config/app.php file.

I have looked for a similar kind of protocol that can be used in the package.json file to reference non-npm packages, but I have not found any such information. The closest information that I have found is a tutorial in which NPM explains how to use NPM private packages, which would accomplish the same goal as long as I want to pay $7/month for the rest of my life to have my package hosted on their servers.

There must be a way to handle this kind of package management locally, but I have not discovered what it is, and that is why I need YOUR help!

All help is appreciated. There are no wrong answers.  Even a bad answer can sometimes point me in the right direction, so give me your thoughts and let's figure this out together so that everyone can benefit!

Body:
HOW TO USE LOCAL PACKAGES IN NPM

It turns out that NPM has a feature that allows me to do exactly what I need to do. I reread the package.json documentation after writing the question above and found that NPM now allows for a local file directory reference to a package.

How it looks in pacakge.json

I used npm to create the linkages (see next section), and then I inspected the package.json file to find the following:

  "dependencies": {
    "@angular/animations": "^4.0.0",
    "@angular/common": "^4.0.0",
    "@angular/compiler": "^4.0.0",
    "@angular/core": "^4.0.0",
    "@angular/forms": "^4.0.0",
    "@angular/http": "^4.0.0",
    "@angular/platform-browser": "^4.0.0",
    "@angular/platform-browser-dynamic": "^4.0.0",
    "@angular/router": "^4.0.0",
    "core-js": "^2.4.1",
    //###THIS IS MY NEW LINE###
    "data-structures": "file:src/app/medface/data-structures",
    "intl": "^1.2.5",
    "ng2-cookies": "^1.0.12",
    "rxjs": "^5.1.0",
    "showdown": "^1.8.0",
    "to-markdown": "^3.1.0",
    "web-animations-js": "^2.2.5",
    "zone.js": "^0.8.4"
  },

Notice how the file: string prepends the source. I then designed a unit test to load one of the files from this directory using the name I assigned.

import {VisitDataStructure} from 'data-structures/visit';

describe( "The data structure package", ()=>{
    fit("loads without failure and allows the user to import classes within the folder.", ()=>{
        let visit = new VisitDataStructure();
        expect(visit).not.toBeNull();
    } );
} );

The test runs with flying colors!

(Note: the function fit is just like it, except it tells the testing system that it should "focus" only on that one test and ignore all the rest.)

How to achieve this using npm

To achieve this local package reference setup, several things must occur in order.

Step 1: Create a package using npm init

Navigate to the sub-folder in the terminal and type npm init (this assumes that you are already using npm, as I am).

Follow the on screen prompts to create your package.json file. The file will ask for a name, this name is how you will refer to the package within your system. In my case, I assigned the name 'data-structures' to the test package.

Step 2: Install the sub package using npm intall --save [pathToLocalFile]

From the root of your application, the same folder that holds the package.json file for your whole application, find the relative path to your new folder.  In my case, it was src/app/medface/data-structures.

If your relative path is correct, then you should be able to use ls or dir to show a file at [relativePath]/package.json (linux/mac) or [relativePath]\package.json (windows)

Then run the command npm install --save [relativePath].

You will see npm do its thing. If it gives you an error, read the error and go back to step #1.  (When I ran it the first time, I got an error and realized that I had to use npm init in the directory before I could install it).

Note: for the terminal command alternative, yes, you CAN use npm install -S [relativePath] -- it is the same command as above.

Step 3: Use your new package name in the code.

Now that it is installed, you can use the name you assigned anywhere within your code, and the package.json file will tell your pre-processor where to find the reference files.

GREAT WORK!  Now go do some awesome coding!


答:
In your code $inner[0] is one of the inner array elements, like 510. You can't loop over that.

If you just want to loop over $array_item[0], don't loop over the whole array.

```<code>if (is_array($array_item[0])) {
    foreach ($array_item[0] as $value) {
        echo "$value\n";
    }
}
</code>```

Title: PHP - How do I access specific array values in nested array?

Body:
In your code $inner[0] is one of the inner array elements, like 510. You can't loop over that.

If you just want to loop over $array_item[0], don't loop over the whole array.

if (is_array($array_item[0])) {
    foreach ($array_item[0] as $value) {
        echo "$value\n";
    }
}


问:
trying to draw a sprite onto canvas but I am missing something

window.onload = function(){
  theVideo();
  playVideo();
  Move();
  Draw();
};
let objectInfo = {
    canvas: null,
    context: null,
    // Number of sprites
    numberOfFrames: 16,
    image: null,
    imageWidth: 128,
    imageHeight: 192,
    frameIndex: 0,
    frameWidth: 0,
    // Animation interval (ms)
    msInterval: 1000,
    x: 10,
    y: 10,
};
const imageFile = "shaggy.png";
 function Draw(){
  objectInfo.context.drawImage(myImage, shift, 0, frameWidth, frameHeight, 120, 25, frameWidth, frameHeight);
 }
//image setup
window.onload= function () {

    // Canvas setup
    objectInfo.canvas = document.querySelector("#myCanvas");
    objectInfo.context = objectInfo.canvas.getContext("2d");

    // Image setup
    objectInfo.image = new Image();
    objectInfo.image.onload = function() {

        // The this object refers to image because within image onload event handler
        objectInfo.imageWidth = this.width;
        objectInfo.imageHeight = this.height;

        // Calculate framewidth (size of each sprite)
        objectInfo.frameWidth = objectInfo.imageWidth / objectInfo.numberOfFrames;
    };
    // Load image
    objectInfo.image.src = imageFile;

};

var xPos = 0;
var yPos = 0;

//move image
function Move(e){
  //right
  if(e.keyCode==39){
      xPos+=5;
  }
  //left
  if(e.keyCode==37){
      xPos-=5;
  }
  //up
   if(e.keyCode==38){
      yPos-=5;
   }
   //down
    if(e.keyCode==40){
      yPos+=5;
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
    <title>Sprite</title>
    <meta charset="utf-8">
    <meta name="author" content="Peyton">
    <meta name="description" content="115">
    <link rel= 'stylesheet' href="p4.css">
    <script src="p4.js"> </script>
      <style>canvas { border: 1px solid black; }</style>
<body>
    <canvas width= "1300" height= "600" id= "myCanvas">

    <video id="video" controls >
        <source src="ScoobyDooV.mp4"/>
        <source src="ScoobyDooV.ogv"/>
    </video>

    </canvas>
    </body>

    </html>
    <nav>
    </nav>
    <main id="#wrapper"><br>

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

I'm really new to coding and am not sure what I am missing to call my sprite and draw the first image onto the canvas. I later have to call each measurement of my sprite and assign to a function keydown event to make it look like its walking each direction so if I could get any guidance on that too that would be great.

答: It looks like you're calling Draw before the image is loaded. Try placing the Draw() call within the image.onload method.

Body:
window.onload = function(){
  theVideo();
  playVideo();
  Move();
  Draw();
};
let objectInfo = {
    canvas: null,
    context: null,
    // Number of sprites
    numberOfFrames: 16,
    image: null,
    imageWidth: 128,
    imageHeight: 192,
    frameIndex: 0,
    frameWidth: 0,
    // Animation interval (ms)
    msInterval: 1000,
    x: 10,
    y: 10,
};
const imageFile = "shaggy.png";
 function Draw(){
  objectInfo.context.drawImage(myImage, shift, 0, frameWidth, frameHeight, 120, 25, frameWidth, frameHeight);
 }
//image setup
window.onload= function () {

    // Canvas setup
    objectInfo.canvas = document.querySelector("#myCanvas");
    objectInfo.context = objectInfo.canvas.getContext("2d");

    // Image setup
    objectInfo.image = new Image();
    objectInfo.image.onload = function() {

        // The this object refers to image because within image onload event handler
        objectInfo.imageWidth = this.width;
        objectInfo.imageHeight = this.height;

        // Calculate framewidth (size of each sprite)
        objectInfo.frameWidth = objectInfo.imageWidth / objectInfo.numberOfFrames;
    };
    // Load image
    objectInfo.image.src = imageFile;

};

var xPos = 0;
var yPos = 0;

//move image
function Move(e){
  //right
  if(e.keyCode==39){
      xPos+=5;
  }
  //left
  if(e.keyCode==37){
      xPos-=5;
  }
  //up
   if(e.keyCode==38){
      yPos-=5;
   }
   //down
    if(e.keyCode==40){
      yPos+=5;
    }
}

<!DOCTYPE html>

    <title>Sprite</title>
    <meta charset="utf-8">
    <meta name="author" content="Peyton">
    <meta name="description" content="115">
    <link rel= 'stylesheet' href="p4.css">

    <canvas width= "1300" height= "600" id= "myCanvas">

    <video id="video" controls >
        <source src="ScoobyDooV.mp4"/>
        <source src="ScoobyDooV.ogv"/>
    </video>

    </canvas>

I'm really new to coding and am not sure what I am missing to call my sprite and draw the first image onto the canvas. I later have to call each measurement of my sprite and assign to a function keydown event to make it look like its walking each direction so if I could get any guidance on that too that would be great.


问:
Make cells visible in UITableView
][2I have a tableView with some content. There are all cells are showing perfectly. But after deleting a few rows, some cell's from below become invisible. I am deleting cells with method: tableView.deleteRows(at: [indexPath], with: .automatic). But's they are has data and it height are good too. After a little time I found a solution: I changed the cell property of isHidden to false in willDisplayCell method. I dont think that is a good solution, but it worked. What do you think? Why are the cells not appearing?

```<code>func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
     return myFavoritesProductsDataSource.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    var cell = tableView.dequeueReusableCell(withIdentifier: "productCell") as! ProductTableViewCell
    cell.product = myFavoritesProductsDataSource[indexPath.row]
    return cell
}

func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    let delete = UIContextualAction(style: .destructive, title:  "Удалить", handler: { (ac:UIContextualAction, view:UIView, success:(Bool) -> Void) in
    self.myFavoritesProductDataSource.remove(at: indexPath.row)
        tableView.beginUpdates()
        tableView.deleteRows(at: [indexPath], with: .automatic)
        tableView.endUpdates()
        success(true)
    })
    return UISwipeActionsConfiguration(actions: [delete])
}
</code>```

答:
You should be using cellForRowAt indexPath to set your data not willDisplayCell.

Here is the code formatted

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "productCell", for: indexPath) as! ProductTableViewCell
    cell.product = myFavoritesProductsDataSource[indexPath.row]
    return cell
}
</code>```

When you delete the cell you should do it like this.

```<code>myFavoritesProductsDataSource.remove(at: indexPath.row)

self.tableView.beginUpdates()
self.tableView.deleteRows(at: [indexPath], with: .automatic)
self.tableView.endUpdates()

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == UITableViewCellEditingStyle.delete {

        myFavoritesProductsDataSource.remove(at: indexPath.row)

        self.tableView.beginUpdates()
        self.tableView.deleteRows(at: [indexPath], with: .automatic)
        self.tableView.endUpdates()

    }
}
</code>```

Title: Make cells visible in UITableView

Body:
][2I have a tableView with some content. There are all cells are showing perfectly. But after deleting a few rows, some cell's from below become invisible. I am deleting cells with method: tableView.deleteRows(at: [indexPath], with: .automatic). But's they are has data and it height are good too. After a little time I found a solution: I changed the cell property of isHidden to false in willDisplayCell method. I dont think that is a good solution, but it worked. What do you think? Why are the cells not appearing?

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
     return myFavoritesProductsDataSource.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    var cell = tableView.dequeueReusableCell(withIdentifier: "productCell") as! ProductTableViewCell
    cell.product = myFavoritesProductsDataSource[indexPath.row]
    return cell
}

func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    let delete = UIContextualAction(style: .destructive, title:  "Удалить", handler: { (ac:UIContextualAction, view:UIView, success:(Bool) -> Void) in
    self.myFavoritesProductDataSource.remove(at: indexPath.row)
        tableView.beginUpdates()
        tableView.deleteRows(at: [indexPath], with: .automatic)
        tableView.endUpdates()
        success(true)
    })
    return UISwipeActionsConfiguration(actions: [delete])
}

Body:
You should be using cellForRowAt indexPath to set your data not willDisplayCell.

Here is the code formatted

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "productCell", for: indexPath) as! ProductTableViewCell
    cell.product = myFavoritesProductsDataSource[indexPath.row]
    return cell
}

When you delete the cell you should do it like this.

myFavoritesProductsDataSource.remove(at: indexPath.row)

self.tableView.beginUpdates()
self.tableView.deleteRows(at: [indexPath], with: .automatic)
self.tableView.endUpdates()

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == UITableViewCellEditingStyle.delete {

        myFavoritesProductsDataSource.remove(at: indexPath.row)

        self.tableView.beginUpdates()
        self.tableView.deleteRows(at: [indexPath], with: .automatic)
        self.tableView.endUpdates()

    }
}


问:
Java dataparse error from SQLite
I am having an error when I try to retrieve data from my SQLite database.

It retrieves the first row of data onto the table but when the date is there it gives the error shown below.

This is the code where I am getting the error.

```<code>try {
        con = DriverManager.getConnection("jdbc:sqlite:Rooms.db");
        con.setAutoCommit(false);

        pst = con.prepareStatement("Select * from Standard");
        rs = pst.executeQuery();

        while (rs.next())
        {
            LocalDate sD = null;
            LocalDate eD = null;
            if (rs.getDate(6) != null)
            {
                sD = Conv(rs.getDate(6));
                eD = Conv(rs.getDate(7));
                System.out.println(sD + "   " + eD);

                if (chkIn.getValue().isBefore(sD) == true && chkOut.getValue().isBefore(eD) == true)
                {
                    datas.add(new StandardRoomList(rs.getString(1), rs.getString(2) , "£" + (rs.getInt(3)*pri), "" + rs.getInt(4)));
                }

            }
</code>```

This is the error I am getting:

```<code>Caused by: java.text.ParseException: Unparseable date: "2017-11-17" does not match (\p{Nd}++)\Q-\E(\p{Nd}++)\Q-\E(\p{Nd}++)\Q \E(\p{Nd}++)\Q:\E(\p{Nd}++)\Q:\E(\p{Nd}++)\Q.\E(\p{Nd}++)
at org.sqlite.date.FastDateParser.parse(FastDateParser.java:299)
at org.sqlite.date.FastDateFormat.parse(FastDateFormat.java:490)
at org.sqlite.jdbc3.JDBC3ResultSet.getDate(JDBC3ResultSet.java:293)
... 64 more
</code>```

答:
The pattern in the error message implies that the JDBC driver is expecting a string of the form "YYYY-MM-DD HH:MM:SS.milliseconds".  That's not compatible with the date representation from your database.

The fundamental problem here is that SQLite doesn't support date / time / timestamp types:

SQLite JDBC rs.getDate() getTimestamp() etc. all return wrong values

You appear to have encoded your dates as strings in your database, and it appears that the JDBC driver is attempting to convert those string values to date / time values using a built-in heuristic.  But that is failing.

I suggest that use getString to retrieve the values from the results-set and then do the string -> date conversion explicitly using Java's built-in date / time classes.

Another approach would be to change the JDBC driver's default date-time format using an org.sqlite.SQLiteConfig object.  However, I can't find any documentation for this approach ... apart from the source code!

Title: Java dataparse error from SQLite

Body:
I am having an error when I try to retrieve data from my SQLite database.

It retrieves the first row of data onto the table but when the date is there it gives the error shown below.

This is the code where I am getting the error.

try {
        con = DriverManager.getConnection("jdbc:sqlite:Rooms.db");
        con.setAutoCommit(false);

        pst = con.prepareStatement("Select * from Standard");
        rs = pst.executeQuery();

        while (rs.next())
        {
            LocalDate sD = null;
            LocalDate eD = null;
            if (rs.getDate(6) != null)
            {
                sD = Conv(rs.getDate(6));
                eD = Conv(rs.getDate(7));
                System.out.println(sD + "   " + eD);

                if (chkIn.getValue().isBefore(sD) == true && chkOut.getValue().isBefore(eD) == true)
                {
                    datas.add(new StandardRoomList(rs.getString(1), rs.getString(2) , "£" + (rs.getInt(3)*pri), "" + rs.getInt(4)));
                }

            }

This is the error I am getting:

Caused by: java.text.ParseException: Unparseable date: "2017-11-17" does not match (\p{Nd}++)\Q-\E(\p{Nd}++)\Q-\E(\p{Nd}++)\Q \E(\p{Nd}++)\Q:\E(\p{Nd}++)\Q:\E(\p{Nd}++)\Q.\E(\p{Nd}++)
at org.sqlite.date.FastDateParser.parse(FastDateParser.java:299)
at org.sqlite.date.FastDateFormat.parse(FastDateFormat.java:490)
at org.sqlite.jdbc3.JDBC3ResultSet.getDate(JDBC3ResultSet.java:293)
... 64 more


问:
Unit Testing: Beginner Questions
I'm finally starting out with unit testing, having known that I should be doing it for a while, but I have a few questions:

Should or shouldn't I retest parent
classes when testing the children if
no methods have been overwritten?

Conceptually, how do you test the
submitted part of a form? I'm using
PHP. (Edit: The reason I ask this is that I have a high level form class that generates a form, validates it, filters it, and generates any error messages by taking a JSON-like array as input and delegating to a variety of smaller classes. However, I can't test the errors, etc without submitting the form. Edit: This looks like it might be an answer.)

If you have optional parameter in a
method, should you write a test for
both when they are present and when
they are not?

Should unit testing in any way be
combined with testing code execution
time or should they remain completely
separate?

Is there any valid reason not to run
your full test suite every time?

Just so I'm getting my terminology
right, to what does the unit in unit
testing refer? The class being
tested? The method? The parameter?
Something else?

答:
Answers to questions in order:

If parent classes are already tested then avoid duplication and just test the new aspects of the child or any aspects that the child changed.

Not sure - have done very little PHP.

Yes => test all aspects of the method.

You could have some unit tests that test performance but they would be focused on performance where as others may be focused on testing functionality. Don't mix both in the same test.

Ideally you should run them every time and often. Sometimes if the execution time is huge you might want to consider refactoring them into smaller suites and then only executing the effected suites when something changes - but still do everything periodically.

OwnerDisplayName: VirtuosiMedia

ContentLicense: CC BY-SA 2.5

Title: Unit Testing: Beginner Questions

LastEditorDisplayName: VirtuosiMedia

OwnerDisplayName: Stephen Doyle


问:
How do I get a random number from numbers available?
I have a table that I am trying to get a random number from:

```<code>//Fruits
id  |  FruitName
----------------
2   |  Banana
3   |  Apple
4   |  Orange
6   |  Grape
7   |  Plum
8   |  Lime
10  |  Kiwi
</code>```

The problem is because of the inconsistencies (note: ids 1, 5, and 9 are missing), writing the following statement will not work (even if written properly):

Random.Next(someLinq.id).First(), (samelinq.id).Last())

How would I get a random number from the numbers available?

答:
you can add all numbers in a array after you can create a random with array's lengt and you can use this number as index of number in the array

```<code>int[] array = new int[]{2,3,4,6,7,8,10};
Random rnd = new Random();
int randomIndex = rnd.Next(0,array.length);
var x = array[randomIndex];
</code>```

And you can do what you want with this x variable

Body:
I have a table that I am trying to get a random number from:

//Fruits
id  |  FruitName
----------------
2   |  Banana
3   |  Apple
4   |  Orange
6   |  Grape
7   |  Plum
8   |  Lime
10  |  Kiwi

The problem is because of the inconsistencies (note: ids 1, 5, and 9 are missing), writing the following statement will not work (even if written properly):

Random.Next(someLinq.id).First(), (samelinq.id).Last())

How would I get a random number from the numbers available?

Body:
you can add all numbers in a array after you can create a random with array's lengt and you can use this number as index of number in the array

int[] array = new int[]{2,3,4,6,7,8,10};
Random rnd = new Random();
int randomIndex = rnd.Next(0,array.length);
var x = array[randomIndex];

And you can do what you want with this x variable


问:
HTML code in AWS Lambda
I am using AWS Lambda to send an email after the API gateway relays the information from the web page through the contact form.
I want to also include inside the lambda code a piece of HTML code that will be actually the body of the email. I want it to look cool.
How can one make that happen?

I have tried to insert the HTML code where the text for the email is and it gives me a bunch of errors, maybe is not supposed to be inserted as is.

Here is the code

```<code>var AWS = require('aws-sdk')
var ses = new AWS.SES()
var RECEIVER1 = 'admin email'
var RECEIVER11 = 'contact email'
var SENDER = 'sender email'

exports.handler = function (event, context) {console.log('Received event:', event) sendEmail(event, function (err, data) {context.done(err, null)})}

function sendEmail (event, done) {
var params = {

        Destination: {
        ToAddresses: [
            RECEIVER1
        ]
    },
    Message: {
        Body: {
            Text: {
                Data: 'Name: ' + event.name + '\nPhone: ' + event.phone + '\nEmail: ' + event.email + '\nDescription of email: ' + event.description,
                Charset: 'UTF-8'
            }
        },
        Subject: {
            Data: 'Variable: ' + event.name,
            Charset: 'UTF-8'
        }
    },
    Source: SENDER
}
ses.sendEmail(params, done)

var params1 = {

        Destination: {
        ToAddresses: [
            RECEIVER11
        ]
    },
    Message: {
        Body: {
            Text: {
                Data: ''

<html>
...
</html>
   ,
                Charset: 'UTF-8'
            }
        },
        Subject: {
            Data: 'Variable: ' + event.name,
            Charset: 'UTF-8'
        }
    },
    Source: SENDER
}
ses.sendEmail(params1, done)
}'
</code>```

答:
Instead of this...

```<code>Message: {
    Body: {
        Text: {
</code>```

...what you are looking for is this:

```<code>Message: {
    Body: {
        Html: {
</code>```

Text means only text -- not HTML.

You can actually include both, with a plain text equivalent of your message inside the Text object, which is displayed by some mail viewers as a preview or when mousing-over a message, or if the viewer can't display HTML mail.  It may also be of benefit to people with accessibility issues, such as visual impairments.

http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SES.html#sendEmail-property

Title: HTML code in AWS Lambda

Body:
I am using AWS Lambda to send an email after the API gateway relays the information from the web page through the contact form.
I want to also include inside the lambda code a piece of HTML code that will be actually the body of the email. I want it to look cool.
How can one make that happen?

I have tried to insert the HTML code where the text for the email is and it gives me a bunch of errors, maybe is not supposed to be inserted as is.

Here is the code

var AWS = require('aws-sdk')
var ses = new AWS.SES()
var RECEIVER1 = 'admin email'
var RECEIVER11 = 'contact email'
var SENDER = 'sender email'

exports.handler = function (event, context) {console.log('Received event:', event) sendEmail(event, function (err, data) {context.done(err, null)})}

function sendEmail (event, done) {
var params = {

        Destination: {
        ToAddresses: [
            RECEIVER1
        ]
    },
    Message: {
        Body: {
            Text: {
                Data: 'Name: ' + event.name + '\nPhone: ' + event.phone + '\nEmail: ' + event.email + '\nDescription of email: ' + event.description,
                Charset: 'UTF-8'
            }
        },
        Subject: {
            Data: 'Variable: ' + event.name,
            Charset: 'UTF-8'
        }
    },
    Source: SENDER
}
ses.sendEmail(params, done)

var params1 = {

        Destination: {
        ToAddresses: [
            RECEIVER11
        ]
    },
    Message: {
        Body: {
            Text: {
                Data: ''

...

   ,
                Charset: 'UTF-8'
            }
        },
        Subject: {
            Data: 'Variable: ' + event.name,
            Charset: 'UTF-8'
        }
    },
    Source: SENDER
}
ses.sendEmail(params1, done)
}'

Body:
Instead of this...

Message: {
    Body: {
        Text: {

...what you are looking for is this:

Message: {
    Body: {
        Html: {

Text means only text -- not HTML.

You can actually include both, with a plain text equivalent of your message inside the Text object, which is displayed by some mail viewers as a preview or when mousing-over a message, or if the viewer can't display HTML mail.  It may also be of benefit to people with accessibility issues, such as visual impairments.

http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SES.html#sendEmail-property


答:
For a statitstical and cryptographically absolutely not correct random value you could go with </p>

```<code>var randomId = resultOfDbLinqQuery
    .OrderBy(e => Guid.NewGuid())
    .First()
    .Select(item = item.id);
</code>```

Title: How do I get a random number from numbers available?

Body:
For a statitstical and cryptographically absolutely not correct random value you could go with

var randomId = resultOfDbLinqQuery
    .OrderBy(e => Guid.NewGuid())
    .First()
    .Select(item = item.id);


问:
Edit Information only from the logged user
I have the following tables: Company 1 -> * Stores 1 -> * Products

And I'm using the following route to edit information:
Company/1/Store/3/Product/4/Edit

How can I secure that a user that doesn't belong to this company doesn't change the ids on the url and change information from others company?
I'm already storing the user companyId on login so I can perform this validation on Stores Controller because I know that a Store have a CompanyId associated and I just check if that companyId is equals to the logged user CompanyId. But now from the products I don't have any association with the company itself only with the store.

My question is, should I create a property CompanyId or UserId that created that product on the stores table, or maybe I should like use a join on the query and say db.Store.Find(UrlStoreId).Include(Products).FirstOrDefault(o => o.CompanyId == loggedUserCompanyId);

I would like to know the conventions for this type of problems in an Application.

Thanks in advance.

答:
For MVC controllers, the current session's user CompanyId can be recorded in session state and compared against each call. If the IDs do not match for any reason then dump the user session and kick them back to the login screen. For Web API controllers you should include a CompanyId in the claims for the Auth Token to perform the same type of validation. Again if a mismatch is found, the violation attempt should be logged and the token invalidated (if supported)

As for the joins, if you set up the references between your entities then you should be able to always enforce the Ids..

given a URL with:
Company/1/Store/3/Product/4/Edit

```<code>if(loggedInUserCompanyId != urlCompanyId)
  // Dump session, kick out.

var product = context.Companies
  .Where(c=> c.CompanyId == urlCompanyId)
  .SelectMany(c=> c.Stores.Where(s=> s.StoreId == urlStoreId)
     .SelectMany(s => s.Products))
  .SingleOrDefault(p => p.ProductId == urlProductId);
</code>```

This will enforce the hierarchy for your domain down to the company and store to ensure that someone doesn't try and "tweak" something like the Store ID or Product ID to gain access to another company's data. If you have an API call such as /Product/4/Edit then you should always ensure that your Claims in your auth token contain enough info (CompanyId) to ensure that you can validate that an API call for Product Id 4 belongs to the correct company.

There's bound to be a lot more you can/should do to ensure data is restricted, but this should provide you with a minimal starting point. Ideally you will want authorization checks as deep as possible in your code structure to ensure that checks like this are not missed. I lean towards the repository pattern to wrap calls to the DbContext rather than having controllers and such accessing the context directly. In that way, even though my repositories return IQueryable, they enforce the authorization so that controller code searching for data don't need to worry about forgetting to include "Company" checks.

Other options include enforcing Authorization at the database level, an option I believe is available in SQL Server where company data could be partitioned separately. AFAIK this would involve separate user accounts per tenant in the database server. A manual flavour of this is to adopt something like Schema-per-tenant or database-per-tenant which ensures that data is not exposed between tenants.

Body:
For MVC controllers, the current session's user CompanyId can be recorded in session state and compared against each call. If the IDs do not match for any reason then dump the user session and kick them back to the login screen. For Web API controllers you should include a CompanyId in the claims for the Auth Token to perform the same type of validation. Again if a mismatch is found, the violation attempt should be logged and the token invalidated (if supported)

As for the joins, if you set up the references between your entities then you should be able to always enforce the Ids..

given a URL with:
Company/1/Store/3/Product/4/Edit

if(loggedInUserCompanyId != urlCompanyId)
  // Dump session, kick out.

var product = context.Companies
  .Where(c=> c.CompanyId == urlCompanyId)
  .SelectMany(c=> c.Stores.Where(s=> s.StoreId == urlStoreId)
     .SelectMany(s => s.Products))
  .SingleOrDefault(p => p.ProductId == urlProductId);

This will enforce the hierarchy for your domain down to the company and store to ensure that someone doesn't try and "tweak" something like the Store ID or Product ID to gain access to another company's data. If you have an API call such as /Product/4/Edit then you should always ensure that your Claims in your auth token contain enough info (CompanyId) to ensure that you can validate that an API call for Product Id 4 belongs to the correct company.

There's bound to be a lot more you can/should do to ensure data is restricted, but this should provide you with a minimal starting point. Ideally you will want authorization checks as deep as possible in your code structure to ensure that checks like this are not missed. I lean towards the repository pattern to wrap calls to the DbContext rather than having controllers and such accessing the context directly. In that way, even though my repositories return IQueryable, they enforce the authorization so that controller code searching for data don't need to worry about forgetting to include "Company" checks.

Other options include enforcing Authorization at the database level, an option I believe is available in SQL Server where company data could be partitioned separately. AFAIK this would involve separate user accounts per tenant in the database server. A manual flavour of this is to adopt something like Schema-per-tenant or database-per-tenant which ensures that data is not exposed between tenants.


问:
What Happens to Non-Awaited Tasks In Try/Catch Block
What happens when a method returns a Task that is contained in a try/catch block? If that non-awaited Task throws an exception, is the exception caught/handled?

For example, if DoSomethingAsync() throws an exception, can I handle it in the try/catch block in TryCatchMethod()?

```<code>Task TryCatchMethod()
{
    try
    {
        return DoSomethingAsync();
    }
    catch(Exception e)
    {
        //Handle Exception
    }
}

async Task DoSomethingAsync()
{
   await Task.Delay(10000);
   throw new System.Exception();
}
</code>```

答:
Answer

No, the try/catch block in TryCatchMethod() will not catch an exception if one occurs in DoSomethingAsync() because of 2 reasons:

The exception will be caught in MoveNext()

DoSomethingAsync() is not awaitd, so the exception will never be rethrown

Solutions

Await DoSomethingAsync() (Prefered)

```<code>async Task TryCatchMethod()
{
    try
    {
       await DoSomethingAsync();
    }
    catch(Exception e)
    {
        //Handle Exception
    }
}</code>```

Use .GetAwaiter().GetResult()

```<code>void TryCatchMethod()
{
    try
    {
       DoSomethingAsync().GetAwaiter().GetResult();
    }
    catch(Exception e)
    {
        //Handle Exception
    }
}</code>```

Note: .GetAwaiter().GetResult() is not recommended because it will lock the current thread.

Explanation

To understand why the try/catch block doesn't catch the exception, it's important to first understand how the compiler generates IL code for an async method.

Compiler-Generated Code for Async Method

(Source: Xamarin University: Using Async and Await)

The compiler transforms an async method into an IAsyncStateMachine class which allows the .NET Runtime to "remember" what the method has accomplished.

(Source: Xamarin University: Using Async and Await)

The IAsyncStateMachine interface implements MoveNext(), a method that executes everytime the await operator is used inside of the async method.

MoveNext() essentially runs your code until it reaches an await statement, then it returns while the await'd method executes. This is the mechanism that allows the current method to "pause", yielding its thread execution to another thread/Task.

Try/Catch in MoveNext()

Look closely at MoveNext(); notice that it is wrapped in a try/catch block.

Because the compiler creates IAsyncStateMachine for every async method and MoveNext() is always wrapped in a try/catch, every exception thrown inside of an async method is caught!

How to Rethrow an Exception Caught By MoveNext

Now the question becomes, if every async method catches every exception thrown, How can I rethrow the exception?

There are a few ways to rethrow exceptions that are thrown in an async method:

Use the await keyword (Prefered)

e.g. await DoSomethingAsync()

Use .GetAwaiter().GetResult()

e.g. DoSomethingAsync().GetAwaiter().GetResult()

The await keyword is preferred because await allows the Task to run asynchronously on a different thread, and it will not lock-up the current thread.

What About .Result or .Wait()?

Never, never, never, never, never use .Result or .Wait():

Both .Result and .Wait() will lock-up the current thread. If the current thread is the Main Thread (also known as the UI Thread), your UI will freeze until the Task has completed.
2..Result or .Wait() rethrow your exception as a System.AggregateException, which makes it difficult to find the actual exception.

Example

Don't Do This

```<code>var longRunningTask1 = LongRunningTaskAsync();
var longRunningTask2 = LongRunningTaskAsync();

await Task.WhenAll(longRunningTask1, longRunningTask2);

var result1 = longRunningTask1.Result;
var result2 = longRunningTask2.Result;
</code>```

Instead, Do This

```<code>var longRunningTask1 = LongRunningTaskAsync();
var longRunningTask2 = LongRunningTaskAsync();

await Task.WhenAll(longRunningTask1, longRunningTask2);

var result1 = await longRunningTask1;
var result2 = await longRunningTask2;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
What happens when a method returns a Task that is contained in a try/catch block? If that non-awaited Task throws an exception, is the exception caught/handled?

For example, if DoSomethingAsync() throws an exception, can I handle it in the try/catch block in TryCatchMethod()?

Task TryCatchMethod()
{
    try
    {
        return DoSomethingAsync();
    }
    catch(Exception e)
    {
        //Handle Exception
    }
}

async Task DoSomethingAsync()
{
   await Task.Delay(10000);
   throw new System.Exception();
}

Body:
Answer

No, the try/catch block in TryCatchMethod() will not catch an exception if one occurs in DoSomethingAsync() because of 2 reasons:

The exception will be caught in MoveNext()

DoSomethingAsync() is not awaitd, so the exception will never be rethrown

Solutions

Await DoSomethingAsync() (Prefered)

async Task TryCatchMethod()
{
    try
    {
       await DoSomethingAsync();
    }
    catch(Exception e)
    {
        //Handle Exception
    }
}

Use .GetAwaiter().GetResult()

void TryCatchMethod()
{
    try
    {
       DoSomethingAsync().GetAwaiter().GetResult();
    }
    catch(Exception e)
    {
        //Handle Exception
    }
}

Note: .GetAwaiter().GetResult() is not recommended because it will lock the current thread.

Explanation

To understand why the try/catch block doesn't catch the exception, it's important to first understand how the compiler generates IL code for an async method.

Compiler-Generated Code for Async Method

(Source: Xamarin University: Using Async and Await)

The compiler transforms an async method into an IAsyncStateMachine class which allows the .NET Runtime to "remember" what the method has accomplished.

(Source: Xamarin University: Using Async and Await)

The IAsyncStateMachine interface implements MoveNext(), a method that executes everytime the await operator is used inside of the async method.

MoveNext() essentially runs your code until it reaches an await statement, then it returns while the await'd method executes. This is the mechanism that allows the current method to "pause", yielding its thread execution to another thread/Task.

Try/Catch in MoveNext()

Look closely at MoveNext(); notice that it is wrapped in a try/catch block.

Because the compiler creates IAsyncStateMachine for every async method and MoveNext() is always wrapped in a try/catch, every exception thrown inside of an async method is caught!

How to Rethrow an Exception Caught By MoveNext

Now the question becomes, if every async method catches every exception thrown, How can I rethrow the exception?

There are a few ways to rethrow exceptions that are thrown in an async method:

Use the await keyword (Prefered)

e.g. await DoSomethingAsync()

Use .GetAwaiter().GetResult()

e.g. DoSomethingAsync().GetAwaiter().GetResult()

The await keyword is preferred because await allows the Task to run asynchronously on a different thread, and it will not lock-up the current thread.

What About .Result or .Wait()?

Never, never, never, never, never use .Result or .Wait():

Both .Result and .Wait() will lock-up the current thread. If the current thread is the Main Thread (also known as the UI Thread), your UI will freeze until the Task has completed.
2..Result or .Wait() rethrow your exception as a System.AggregateException, which makes it difficult to find the actual exception.

Example

Don't Do This

var longRunningTask1 = LongRunningTaskAsync();
var longRunningTask2 = LongRunningTaskAsync();

await Task.WhenAll(longRunningTask1, longRunningTask2);

var result1 = longRunningTask1.Result;
var result2 = longRunningTask2.Result;

Instead, Do This

var longRunningTask1 = LongRunningTaskAsync();
var longRunningTask2 = LongRunningTaskAsync();

await Task.WhenAll(longRunningTask1, longRunningTask2);

var result1 = await longRunningTask1;
var result2 = await longRunningTask2;


问:
GCP Dataproc spark.jar.packages issue downloading dependencies
When creating our Dataproc Spark cluster we pass
--properties spark:spark.jars.packages=mysql:mysql-connector-java:6.0.6 to the gcloud dataproc clusters create command.

This is for our PySpark scripts to save to CloudSQL

Apparently on creation this doesn't do anything, but on the first spark-submit this will try to resolve this dependency.

Technically it seems resolve and download the necessary jar file, but the first task on the cluster will fail because of warnings emitted from spark-submit

```<code>Exception in thread "main" java.lang.RuntimeException: [download failed: mysql#mysql-connector-java;6.0.6!mysql-connector-java.jar]
    at org.apache.spark.deploy.SparkSubmitUtils$.resolveMavenCoordinates(SparkSubmit.scala:1177)
    at org.apache.spark.deploy.SparkSubmit$.prepareSubmitEnvironment(SparkSubmit.scala:298)
    at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:153)
    at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:119)
    at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
</code>```

The complete output is:

```<code>Ivy Default Cache set to: /root/.ivy2/cache
The jars for the packages stored in: /root/.ivy2/jars
:: loading settings :: url = jar:file:/usr/lib/spark/jars/ivy-2.4.0.jar!/org/apache/ivy/core/settings/ivysettings.xml
mysql#mysql-connector-java added as a dependency
:: resolving dependencies :: org.apache.spark#spark-submit-parent;1.0
    confs: [default]
    found mysql#mysql-connector-java;6.0.6 in central
downloading https://repo1.maven.org/maven2/mysql/mysql-connector-java/6.0.6/mysql-connector-java-6.0.6.jar ...
:: resolution report :: resolve 527ms :: artifacts dl 214ms
    :: modules in use:
    mysql#mysql-connector-java;6.0.6 from central in [default]
    ---------------------------------------------------------------------
    |                  |            modules            ||   artifacts   |
    |       conf       | number| search|dwnlded|evicted|| number|dwnlded|
    ---------------------------------------------------------------------
    |      default     |   1   |   1   |   1   |   0   ||   1   |   0   |
    ---------------------------------------------------------------------

:: problems summary ::
:::: WARNINGS
        [FAILED     ] mysql#mysql-connector-java;6.0.6!mysql-connector-java.jar: Downloaded file size doesn't match expected Content Length for https://repo1.maven.org/maven2/mysql/mysql-connector-java/6.0.6/mysql-connector-java-6.0.6.jar. Please retry. (212ms)

        [FAILED     ] mysql#mysql-connector-java;6.0.6!mysql-connector-java.jar: Downloaded file size doesn't match expected Content Length for https://repo1.maven.org/maven2/mysql/mysql-connector-java/6.0.6/mysql-connector-java-6.0.6.jar. Please retry. (212ms)

    ==== central: tried

      https://repo1.maven.org/maven2/mysql/mysql-connector-java/6.0.6/mysql-connector-java-6.0.6.jar

        ::::::::::::::::::::::::::::::::::::::::::::::

        ::              FAILED DOWNLOADS            ::

        :: ^ see resolution messages for details  ^ ::

        ::::::::::::::::::::::::::::::::::::::::::::::

        :: mysql#mysql-connector-java;6.0.6!mysql-connector-java.jar

        ::::::::::::::::::::::::::::::::::::::::::::::
</code>```

However subsequent tasks on the cluster show this output

```<code>Ivy Default Cache set to: /root/.ivy2/cache
The jars for the packages stored in: /root/.ivy2/jars
:: loading settings :: url = jar:file:/usr/lib/spark/jars/ivy-2.4.0.jar!/org/apache/ivy/core/settings/ivysettings.xml
mysql#mysql-connector-java added as a dependency
:: resolving dependencies :: org.apache.spark#spark-submit-parent;1.0
    confs: [default]
    found mysql#mysql-connector-java;6.0.6 in central
:: resolution report :: resolve 224ms :: artifacts dl 5ms
    :: modules in use:
    mysql#mysql-connector-java;6.0.6 from central in [default]
    ---------------------------------------------------------------------
    |                  |            modules            ||   artifacts   |
    |       conf       | number| search|dwnlded|evicted|| number|dwnlded|
    ---------------------------------------------------------------------
    |      default     |   1   |   0   |   0   |   0   ||   1   |   0   |
    ---------------------------------------------------------------------
:: retrieving :: org.apache.spark#spark-submit-parent
    confs: [default]
    0 artifacts copied, 1 already retrieved (0kB/7ms)
</code>```

So my question is:

What is the cause & can this be fixed by the good people at GCP?

Is there a temporary workaround, besides running a dummy task that is allowed to fail at inception of the cluster?

答:
How consistently can you reproduce this? My best theory after attempting to reproduce with different cluster settings is this is possibly an overloaded server that returns a 5xx error.

As far as workarounds go:

1) Download the jar from Maven Central and pass it with --jars option when submitting the job. If you frequently create new clusters than staging this file on the cluster via initialization actions is the way to go.

2) Provide an alternate ivy settings file via spark.jars.ivySettings property that points at Google Maven Central mirror (this should reduce/eliminate odds of 5xx errors)

See this article:
https://www.infoq.com/news/2015/11/maven-central-at-google

Body:
When creating our Dataproc Spark cluster we pass
--properties spark:spark.jars.packages=mysql:mysql-connector-java:6.0.6 to the gcloud dataproc clusters create command.

This is for our PySpark scripts to save to CloudSQL

Apparently on creation this doesn't do anything, but on the first spark-submit this will try to resolve this dependency.

Technically it seems resolve and download the necessary jar file, but the first task on the cluster will fail because of warnings emitted from spark-submit

Exception in thread "main" java.lang.RuntimeException: [download failed: mysql#mysql-connector-java;6.0.6!mysql-connector-java.jar]
    at org.apache.spark.deploy.SparkSubmitUtils$.resolveMavenCoordinates(SparkSubmit.scala:1177)
    at org.apache.spark.deploy.SparkSubmit$.prepareSubmitEnvironment(SparkSubmit.scala:298)
    at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:153)
    at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:119)
    at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)

The complete output is:

Ivy Default Cache set to: /root/.ivy2/cache
The jars for the packages stored in: /root/.ivy2/jars
:: loading settings :: url = jar:file:/usr/lib/spark/jars/ivy-2.4.0.jar!/org/apache/ivy/core/settings/ivysettings.xml
mysql#mysql-connector-java added as a dependency
:: resolving dependencies :: org.apache.spark#spark-submit-parent;1.0
    confs: [default]
    found mysql#mysql-connector-java;6.0.6 in central
downloading https://repo1.maven.org/maven2/mysql/mysql-connector-java/6.0.6/mysql-connector-java-6.0.6.jar ...
:: resolution report :: resolve 527ms :: artifacts dl 214ms
    :: modules in use:
    mysql#mysql-connector-java;6.0.6 from central in [default]
    ---------------------------------------------------------------------
    |                  |            modules            ||   artifacts   |
    |       conf       | number| search|dwnlded|evicted|| number|dwnlded|
    ---------------------------------------------------------------------
    |      default     |   1   |   1   |   1   |   0   ||   1   |   0   |
    ---------------------------------------------------------------------

:: problems summary ::
:::: WARNINGS
        [FAILED     ] mysql#mysql-connector-java;6.0.6!mysql-connector-java.jar: Downloaded file size doesn't match expected Content Length for https://repo1.maven.org/maven2/mysql/mysql-connector-java/6.0.6/mysql-connector-java-6.0.6.jar. Please retry. (212ms)

        [FAILED     ] mysql#mysql-connector-java;6.0.6!mysql-connector-java.jar: Downloaded file size doesn't match expected Content Length for https://repo1.maven.org/maven2/mysql/mysql-connector-java/6.0.6/mysql-connector-java-6.0.6.jar. Please retry. (212ms)

    ==== central: tried

      https://repo1.maven.org/maven2/mysql/mysql-connector-java/6.0.6/mysql-connector-java-6.0.6.jar

        ::::::::::::::::::::::::::::::::::::::::::::::

        ::              FAILED DOWNLOADS            ::

        :: ^ see resolution messages for details  ^ ::

        ::::::::::::::::::::::::::::::::::::::::::::::

        :: mysql#mysql-connector-java;6.0.6!mysql-connector-java.jar

        ::::::::::::::::::::::::::::::::::::::::::::::

However subsequent tasks on the cluster show this output

Ivy Default Cache set to: /root/.ivy2/cache
The jars for the packages stored in: /root/.ivy2/jars
:: loading settings :: url = jar:file:/usr/lib/spark/jars/ivy-2.4.0.jar!/org/apache/ivy/core/settings/ivysettings.xml
mysql#mysql-connector-java added as a dependency
:: resolving dependencies :: org.apache.spark#spark-submit-parent;1.0
    confs: [default]
    found mysql#mysql-connector-java;6.0.6 in central
:: resolution report :: resolve 224ms :: artifacts dl 5ms
    :: modules in use:
    mysql#mysql-connector-java;6.0.6 from central in [default]
    ---------------------------------------------------------------------
    |                  |            modules            ||   artifacts   |
    |       conf       | number| search|dwnlded|evicted|| number|dwnlded|
    ---------------------------------------------------------------------
    |      default     |   1   |   0   |   0   |   0   ||   1   |   0   |
    ---------------------------------------------------------------------
:: retrieving :: org.apache.spark#spark-submit-parent
    confs: [default]
    0 artifacts copied, 1 already retrieved (0kB/7ms)

So my question is:

What is the cause & can this be fixed by the good people at GCP?

Is there a temporary workaround, besides running a dummy task that is allowed to fail at inception of the cluster?


问:
Get All Values of Property in Array
I'm using jQuery to perform an AJAX request that returns a JSON array that looks similar to this:

```<code>[
  {
    "id": 1,
    "message": "test1",
    "expiration": "2017-11-17"
  },
  {
    "id": 2,
    "message": "test2",
    "expiration": "2017-11-17"
  }
]
</code>```

What I want to do is get all of the "message" values. I understand that I could iterate through each object in the array and get the value manually, but what I want to know is if there is a way of getting the values in a one-liner.

The programming language with which I'm most familiar with is VB.NET, and using the same data above, this is basically what I'm wanting to accomplish:

```<code>Dim messages = (From obj In Array Select p.message)
</code>```

答:
Do this;</p>

```<code>var returnedJsonString="[
{
"id": 1,
"message": "test1",
"expiration": "2017-11-17"
},
{
"id": 2,
"message": "test2",
"expiration": "2017-11-17"
}
]";
var data=JSON.parse(returnedJsonString);//convert json string to object array

var msgs=[];//define an array to store the messages as you retrieve

data.forEach(function(o){
     msgs.push(o.message);
});

alert(msgs.join());
</code>```

Title: Get All Values of Property in Array

Body:
I'm using jQuery to perform an AJAX request that returns a JSON array that looks similar to this:

[
  {
    "id": 1,
    "message": "test1",
    "expiration": "2017-11-17"
  },
  {
    "id": 2,
    "message": "test2",
    "expiration": "2017-11-17"
  }
]

What I want to do is get all of the "message" values. I understand that I could iterate through each object in the array and get the value manually, but what I want to know is if there is a way of getting the values in a one-liner.

The programming language with which I'm most familiar with is VB.NET, and using the same data above, this is basically what I'm wanting to accomplish:

Dim messages = (From obj In Array Select p.message)

Body:
Do this;

var returnedJsonString="[
{
"id": 1,
"message": "test1",
"expiration": "2017-11-17"
},
{
"id": 2,
"message": "test2",
"expiration": "2017-11-17"
}
]";
var data=JSON.parse(returnedJsonString);//convert json string to object array

var msgs=[];//define an array to store the messages as you retrieve

data.forEach(function(o){
     msgs.push(o.message);
});

alert(msgs.join());


问:
Adobe flex or WPF to write a visually rich desktop application
I'm interested in making a desktop application which I would want to use as a Desktop Manager. This kind-of goes to Desktop Enhancement Category. My requirements are:

Application has to be visually rich, with panels sliding,fading,wiping,rotating and etc.

It should also support flash playback. (swf, flv)

Animations/Transitions should run smoothly.

Lower CPU Usage.

My question is which is a better option to build this application. Microsoft's "WPF" or Adobe Flex(running in Adobe Air to run on desktop). And also respond as why it is better.

答:
Be suspicious of anyone who will give you an answer like "Definately use xyz" to this question.  There are pros and cons to both sides.

First, I think you might be confusing what WPF and Air are... WPF is a presentation layer on top of the .Net framework, where Air is a framework by itself.  Apples and Oranges.  If you want an analog to what Air is for the .Net stack, you probably want to look at Silverlight Out-Of-Browser, which is a much closer comparison to Air.

What is the difference, then, between WPF and Sliverlight OOB?  Again, WPF sits on top of a very large .Net framework where Sliverlight OOB is a very light framework (in comparison) like air.  It is the difference between a 200 MB download/install and a 12 MB download/install.

So, that being said, I think you should also ask what platforms this needs to run on.  Silverlight OOB runs on Mac and Windows where WPF only runs on Windows.  Air runs on Mac, Windows and Linux.

The next thing that I see is that you need to do SWF and FLV playback.  This will be easier to achieve with Air, since it is native.  You CAN do this with Silverlight OOB but you will find yourself rigging something up where you host an HTML control and run the flash movie inside the HTML control.  It is a bit more clunky, but it will work.

Other than that, Air and SLOOB are very similar in features.  It then comes down to your team and the expertise, IMO.  If they are already familiar with the WPF/Silverlight, then a SLOOB app is well suited with minimal ramp-up.  If your designers are more familiar with the Adobe suite of tools, then it might be easier to build a shiny app using Air.

In all, the decision between Air and Silverlight/WPF really comes down to preference.  That is, once you get past any particular techincal limitations like the flash playback or OS support.

Hope this helps,
Brian


问:
Text always moving behind slider
I'm having an issue with some text that I want to put in a container below a slider always appearing behind the slider. I've tried different options in CSS but I can't seem to get the text moving.

Here is the example of the project: Example

Below you can find the html/css on jsfiddle

The text should appear in the div A3L_slogan. I've tried using margins, but that doesn't make it responsive am I right?
To say it in short. The text should appear below the carousel in the center of the page.

Hope anyone can point me in the right direction or help me out

body {
  width: 100%;
  margin: 0;
  font-family: 'open sans', sans-serif;
  zoom: 1;
}

header {
  padding: 20px 0;
  background-color: #ffffff;
  box-shadow: 0 4px 6px rgba(0,0,0,.2);
}
.container {
  padding: 0 20px;
  margin: 0 auto;
}
.logo-box {
  float: left;
  margin-right: 20px;
}
.logo-box a {
  outline: none;
  display: block;
}
.logo-box img {display: block;}
nav {
  overflow: hidden;
}
ul {
  list-style: none;
  margin: 0;
  padding: 0px 10px 0px 0px;
  float: right;
}
nav li {
  display: inline-block;
  margin-left: 25px;
  height: 70px;
  line-height: 70px;
  transition: .5s linear;
}
nav a {
  text-decoration: none;
  display: block;
  position: relative;
  color: #868686;
  text-transform: uppercase;
}
nav a:after {
  content: "";
  width: 0;
  height: 2px;
  position: absolute;
  left: 0;
  bottom: 15px;
  background: #868686;
  transition: width .5s linear;
}
nav a:hover:after {width: 100%;}

@media screen and (max-width: 660px) {
  header {text-align: center;}
  .logo-box {
    float: none;
    display: inline-block;
    margin: 0 0 16px 0;
  }
  ul {float: none;}
  nav li:first-of-type {margin-left: 0;}
}
@media screen and (max-width: 550px) {
nav {overflow: visible;}
nav li {
  display: block;
  margin: 0;
  height: 40px;
  line-height: 40px;
}
nav li:hover {background: rgba(0,0,0,.1);}
nav a:after {content: none;}
}

#slide {
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
  position:fixed;
  width:100%;
  height:600px;
}
.slide1 {
  background: url(http://wallpapers.wallhaven.cc/wallpapers/full/wallhaven-159465.jpg) no-repeat center center fixed;
}
.slide2 {
  background: url(http://wallpapers.wallhaven.cc/wallpapers/full/wallhaven-160434.png) no-repeat center center fixed;
}
.slide3 {
  background: url(http://wallpapers.wallhaven.cc/wallpapers/full/wallhaven-150988.jpg) no-repeat center center fixed;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
  <head>
    <title></title>
    <link rel="stylesheet" type="text/css" href="css/style.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>
    $(function () {
    $('.fadein div:gt(0)').hide();
    setInterval(function () {
      $('.fadein :first-child').fadeOut().next('div').fadeIn().end().appendTo('.fadein');
    }, 3500);
  });
    </script>

  </head>
  <body>
    <header>
      <div class="container">
        <div class="logo-box">

            <img src="images/logo.png">

        </div>
          <nav>
            <ul>
              <li>Forums</li>
              <li>Rules</li>
              <li>Monetization</li>
              <li>Sign-up</li>
              <li>Staff</li>
           </ul>
        </nav>
      </div>
    </header>
    <div class="fadein">
       <div id="slide"class="slide1"></div>
       <div id="slide"class="slide2"></div>
       <div id="slide"class="slide3"></div>
    </div>
    <div class="A3L_Slogan">
      <div class="slogan_title">
        Hardcore Roleplay Community
      </div>
    </div>
  </body>
</html></code>```

答:
```<code>#slide {
position: fixed;
}
</code>```

to

```<code>#slide{
position: relative;
}
</code>```

and the flow of the markup styling will be fixed. and you shouldn't use multiple ids slide with the same name in your markup it's very bad and will cause a hell of problems in the nearest future.

update:

As discussed in the comments, a better solution is to remove the duplicated divs and using img tags plus applying changes on js and css to avoid flickering and overflow-x. https://codepen.io/anon/pen/eeymgo

Title: Text always moving behind slider

Body:
I'm having an issue with some text that I want to put in a container below a slider always appearing behind the slider. I've tried different options in CSS but I can't seem to get the text moving.

Here is the example of the project: Example

Below you can find the html/css on jsfiddle

The text should appear in the div A3L_slogan. I've tried using margins, but that doesn't make it responsive am I right?
To say it in short. The text should appear below the carousel in the center of the page.

Hope anyone can point me in the right direction or help me out

body {
  width: 100%;
  margin: 0;
  font-family: 'open sans', sans-serif;
  zoom: 1;
}

header {
  padding: 20px 0;
  background-color: #ffffff;
  box-shadow: 0 4px 6px rgba(0,0,0,.2);
}
.container {
  padding: 0 20px;
  margin: 0 auto;
}
.logo-box {
  float: left;
  margin-right: 20px;
}
.logo-box a {
  outline: none;
  display: block;
}
.logo-box img {display: block;}
nav {
  overflow: hidden;
}
ul {
  list-style: none;
  margin: 0;
  padding: 0px 10px 0px 0px;
  float: right;
}
nav li {
  display: inline-block;
  margin-left: 25px;
  height: 70px;
  line-height: 70px;
  transition: .5s linear;
}
nav a {
  text-decoration: none;
  display: block;
  position: relative;
  color: #868686;
  text-transform: uppercase;
}
nav a:after {
  content: "";
  width: 0;
  height: 2px;
  position: absolute;
  left: 0;
  bottom: 15px;
  background: #868686;
  transition: width .5s linear;
}
nav a:hover:after {width: 100%;}

@media screen and (max-width: 660px) {
  header {text-align: center;}
  .logo-box {
    float: none;
    display: inline-block;
    margin: 0 0 16px 0;
  }
  ul {float: none;}
  nav li:first-of-type {margin-left: 0;}
}
@media screen and (max-width: 550px) {
nav {overflow: visible;}
nav li {
  display: block;
  margin: 0;
  height: 40px;
  line-height: 40px;
}
nav li:hover {background: rgba(0,0,0,.1);}
nav a:after {content: none;}
}

#slide {
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
  position:fixed;
  width:100%;
  height:600px;
}
.slide1 {
  background: url(http://wallpapers.wallhaven.cc/wallpapers/full/wallhaven-159465.jpg) no-repeat center center fixed;
}
.slide2 {
  background: url(http://wallpapers.wallhaven.cc/wallpapers/full/wallhaven-160434.png) no-repeat center center fixed;
}
.slide3 {
  background: url(http://wallpapers.wallhaven.cc/wallpapers/full/wallhaven-150988.jpg) no-repeat center center fixed;
}

    <title></title>
    <link rel="stylesheet" type="text/css" href="css/style.css" />

Forums

Rules

Monetization

Sign-up

Staff

        Hardcore Roleplay Community

Body:
#slide {
position: fixed;
}

to

#slide{
position: relative;
}

and the flow of the markup styling will be fixed. and you shouldn't use multiple ids slide with the same name in your markup it's very bad and will cause a hell of problems in the nearest future.

update:

As discussed in the comments, a better solution is to remove the duplicated divs and using img tags plus applying changes on js and css to avoid flickering and overflow-x. https://codepen.io/anon/pen/eeymgo


问:
Function pointers in Rust using constrained generics
I'm trying to create a struct that looks like this:

```<code>struct MediaLibrary<B>
where
    B: Ord,
{
    root_dir: PathBuf,
    item_meta_fn: String,
    self_meta_fn: String,
    media_item_filter: fn(&Path) -> bool,
    media_item_sort_key: fn(&Path) -> B,
}
</code>```

The last two fields are meant to be used as a predicate to test if a given path is a valid media file and to sort a vector of paths (using sort_by_key), respectively.

However, as it is right now, the design is inflexible: both functions are fixed to accept only Path. I'd like to be able to use P: AsRef<Path> as the stdlib uses for many of its file and path methods, but I'm not sure how to add this.

A number of the methods I've impl'd for MediaLibrary are already using P: AsRef<Path> for their arguments, so my gut feeling tells me that there would be conflicts.

答:
To my knowledge, you cannot have a function pointer with a generic type, I don't even think such a construct is accepted by the Rust parser.

Furthermore, you cannot simply switch to extra type parameters on the struct as they would be unused by the struct itself:

```<code>struct MediaLibrary<F, P1, K, P2, B>
where
    F: Fn(P1) -> bool,
    P1: AsRef<Path>,
    K: Fn(P2) -> B,
    P2: AsRef<Path>,
    B: Ord,
{
    root_dir: PathBuf,
    item_meta_fn: String,
    self_meta_fn: String,
    media_item_filter: F,
    media_item_sort_key: K,
}
</code>```

error[E0392]: parameter `P1` is never used
 --> src/main.rs:3:24
  |
3 | struct MediaLibrary<F, P1, K, P2, B>
  |                        ^^ unused type parameter
  |
  = help: consider removing `P1` or using a marker such as `std::marker::PhantomData`
```

<p>Instead, you can choose to apply the constraints only on the functions where they are used:</p>

```struct MediaLibrary<F> {
    media_item_filter: F,
}

impl<F> MediaLibrary<F> {
    fn do_filter
(&self)
    where
        F: Fn(P) -> bool,
        P: AsRef<Path>,
    {}
}
```

As the message states, you could also use PhantomData.

Body:
I'm trying to create a struct that looks like this:

struct MediaLibrary
where
    B: Ord,
{
    root_dir: PathBuf,
    item_meta_fn: String,
    self_meta_fn: String,
    media_item_filter: fn(&Path) -> bool,
    media_item_sort_key: fn(&Path) -> B,
}

The last two fields are meant to be used as a predicate to test if a given path is a valid media file and to sort a vector of paths (using sort_by_key), respectively.

However, as it is right now, the design is inflexible: both functions are fixed to accept only Path. I'd like to be able to use P: AsRef<Path> as the stdlib uses for many of its file and path methods, but I'm not sure how to add this.

A number of the methods I've impl'd for MediaLibrary are already using P: AsRef<Path> for their arguments, so my gut feeling tells me that there would be conflicts.

Body:
To my knowledge, you cannot have a function pointer with a generic type, I don't even think such a construct is accepted by the Rust parser.

Furthermore, you cannot simply switch to extra type parameters on the struct as they would be unused by the struct itself:

struct MediaLibrary<F, P1, K, P2, B>
where
    F: Fn(P1) -> bool,
    P1: AsRef<Path>,
    K: Fn(P2) -> B,
    P2: AsRef<Path>,
    B: Ord,
{
    root_dir: PathBuf,
    item_meta_fn: String,
    self_meta_fn: String,
    media_item_filter: F,
    media_item_sort_key: K,
}

error[E0392]: parameter `P1` is never used
 --> src/main.rs:3:24
  |
3 | struct MediaLibrary<F, P1, K, P2, B>
  |                        ^^ unused type parameter
  |
  = help: consider removing `P1` or using a marker such as `std::marker::PhantomData`

Instead, you can choose to apply the constraints only on the functions where they are used:

struct MediaLibrary<F> {
    media_item_filter: F,
}

impl<F> MediaLibrary<F> {
    fn do_filter<P>(&self)
    where
        F: Fn(P) -> bool,
        P: AsRef<Path>,
    {}
}

As the message states, you could also use PhantomData.


问:
Kotlin data class copy method not deep copying all members
Could someone explain how exactly the copy method for Kotlin data classes work? It seems like for some members, a (deep) copy is not actually created and the references are still to the original.

```<code>fun test() {
    val bar = Bar(0)
    val foo = Foo(5, bar, mutableListOf(1, 2, 3))
    println("foo    : $foo")

    val barCopy = bar.copy()
    val fooCopy = foo.copy()
    foo.a = 10
    bar.x = 2
    foo.list.add(4)

    println("foo    : $foo")
    println("fooCopy: $fooCopy")
    println("barCopy: $barCopy")
}

data class Foo(var a: Int,
               val bar: Bar,
               val list: MutableList<Int> = mutableListOf())

data class Bar(var x: Int = 0)
</code>```

Output:

  foo    : Foo(a=5, bar=Bar(x=0), list=[1, 2, 3])

  foo    : Foo(a=10, bar=Bar(x=2), list=[1, 2, 3, 4])

  fooCopy: Foo(a=5, bar=Bar(x=2), list=[1, 2, 3, 4])

  barCopy: Bar(x=0)

Why is barCopy.x=0 (expected), but fooCopy.bar.x=2 (I would think it would be 0). Since Bar is also a data class, I would expect foo.bar to also be a copy when foo.copy() is executed.

To deep copy all members, I can do something like this:

```<code>val fooCopy = foo.copy(bar = foo.bar.copy(), list = foo.list.toMutableList())
</code>```

fooCopy: Foo(a=5, bar=Bar(x=0), list=[1, 2, 3])

But am I missing something or is there a better way to do this without needing to specify that these members need to force a deep copy?

答:
The copy method of Kotlin is not supposed to be a deep copy at all. As explained in the reference doc (https://kotlinlang.org/docs/reference/data-classes.html), for a class such as:

```<code>data class User(val name: String = "", val age: Int = 0)
</code>```

the copy implementation would be:

```<code>fun copy(name: String = this.name, age: Int = this.age) = User(name, age)
</code>```

So as you can see, it's a shallow copy. The implementations of copy in your specific cases would be:

```<code>fun copy(a: Int = this.a, bar: Bar = this.bar, list: MutableList<Int> = this.list) = Foo(a, bar, list)

fun copy(x: Int = this.x) = Bar(x)
</code>```

Body:
Could someone explain how exactly the copy method for Kotlin data classes work? It seems like for some members, a (deep) copy is not actually created and the references are still to the original.

fun test() {
    val bar = Bar(0)
    val foo = Foo(5, bar, mutableListOf(1, 2, 3))
    println("foo    : $foo")

    val barCopy = bar.copy()
    val fooCopy = foo.copy()
    foo.a = 10
    bar.x = 2
    foo.list.add(4)

    println("foo    : $foo")
    println("fooCopy: $fooCopy")
    println("barCopy: $barCopy")
}

data class Foo(var a: Int,
               val bar: Bar,
               val list: MutableList<Int> = mutableListOf())

data class Bar(var x: Int = 0)

Output:

  foo    : Foo(a=5, bar=Bar(x=0), list=[1, 2, 3])

  foo    : Foo(a=10, bar=Bar(x=2), list=[1, 2, 3, 4])

  fooCopy: Foo(a=5, bar=Bar(x=2), list=[1, 2, 3, 4])

  barCopy: Bar(x=0)

Why is barCopy.x=0 (expected), but fooCopy.bar.x=2 (I would think it would be 0). Since Bar is also a data class, I would expect foo.bar to also be a copy when foo.copy() is executed.

To deep copy all members, I can do something like this:

val fooCopy = foo.copy(bar = foo.bar.copy(), list = foo.list.toMutableList())

fooCopy: Foo(a=5, bar=Bar(x=0), list=[1, 2, 3])

But am I missing something or is there a better way to do this without needing to specify that these members need to force a deep copy?

Body:
The copy method of Kotlin is not supposed to be a deep copy at all. As explained in the reference doc (https://kotlinlang.org/docs/reference/data-classes.html), for a class such as:

data class User(val name: String = "", val age: Int = 0)

the copy implementation would be:

fun copy(name: String = this.name, age: Int = this.age) = User(name, age)

So as you can see, it's a shallow copy. The implementations of copy in your specific cases would be:

fun copy(a: Int = this.a, bar: Bar = this.bar, list: MutableList<Int> = this.list) = Foo(a, bar, list)

fun copy(x: Int = this.x) = Bar(x)


答:
You can simply use the count of the items as the max random number, and then select a random item by index:

```<code>var random = new Random();
var items = new List<int> {2, 3, 4, 6, 7, 8, 10};
var randomItem = items[random.Next(items.Count)];
</code>```

Or, in your case (and assuming you are getting a list of Fruit items which contain an Id property):

```<code>var items = new List<Fruit>
{
    new Fruit {Id = 2, Name = "Banana"},
    new Fruit {Id = 3, Name = "Apple"},
    new Fruit {Id = 4, Name = "Orange"},
    new Fruit {Id = 6, Name = "Grape"},
    new Fruit {Id = 7, Name = "Plum"},
    new Fruit {Id = 8, Name = "Lime"},
    new Fruit {Id = 10, Name = "Kiwi"}
};

var random = new Random();
var randomItem = items[random.Next(items.Count)];

Console.WriteLine("Randomly chose fruit: Id = {0}, Name = {1}",
    randomItem.Id, randomItem.Name);
</code>```

Body:
I have a table that I am trying to get a random number from:

//Fruits
id  |  FruitName
----------------
2   |  Banana
3   |  Apple
4   |  Orange
6   |  Grape
7   |  Plum
8   |  Lime
10  |  Kiwi

The problem is because of the inconsistencies (note: ids 1, 5, and 9 are missing), writing the following statement will not work (even if written properly):

Random.Next(someLinq.id).First(), (samelinq.id).Last())

How would I get a random number from the numbers available?

Body:
You can simply use the count of the items as the max random number, and then select a random item by index:

var random = new Random();
var items = new List<int> {2, 3, 4, 6, 7, 8, 10};
var randomItem = items[random.Next(items.Count)];

Or, in your case (and assuming you are getting a list of Fruit items which contain an Id property):

var items = new List<Fruit>
{
    new Fruit {Id = 2, Name = "Banana"},
    new Fruit {Id = 3, Name = "Apple"},
    new Fruit {Id = 4, Name = "Orange"},
    new Fruit {Id = 6, Name = "Grape"},
    new Fruit {Id = 7, Name = "Plum"},
    new Fruit {Id = 8, Name = "Lime"},
    new Fruit {Id = 10, Name = "Kiwi"}
};

var random = new Random();
var randomItem = items[random.Next(items.Count)];

Console.WriteLine("Randomly chose fruit: Id = {0}, Name = {1}",
    randomItem.Id, randomItem.Name);