问:
How to create thumbnail of video url form server
How to create image/thumbnails of url video form server

and I try is  not work (not show thumbnails)

```<code>String  String url = "http://clips.vorwaerts-gmbh.de/VfE_html5.mp4";

     Bitmap thumb = ThumbnailUtils.createVideoThumbnail(url,MediaStore.Images.Thumbnails.MINI_KIND);

    Glide.with(context).load(thumb).asBitmap()
    /*.override(convertDpToPx(100), convertDpToPx(100))*/
    .placeholder(R.drawable.camera)
    .override(200, 200)
    .diskCacheStrategy(DiskCacheStrategy.ALL)
    .into(new BitmapImageViewTarget(img_view) {
     protected void setResource(Bitmap resource) {
    RoundedBitmapDrawable circularBitmapDrawable =
    RoundedBitmapDrawableFactory.create(context.getResources(), resource);
    //circularBitmapDrawable.setCircular(true);
    img_view.setImageDrawable(circularBitmapDrawable);
       }
    });
</code>```

I get slove it by answer1 !

but it get some problem about thumbnails ,it's change color is stange.

example

答:
Try this Create new AsyncTask like this

```<code>public class DownloadImage extends AsyncTask<String, Void, Bitmap> {
    ImageView bmImage;

    public DownloadImage(ImageView bmImage) {
        this.bmImage = (ImageView ) bmImage;
    }

    protected Bitmap doInBackground(String... urls) {
        Bitmap myBitmap = null;
        MediaMetadataRetriever mMRetriever = null;
        try {
            mMRetriever = new MediaMetadataRetriever();
            if (Build.VERSION.SDK_INT >= 14)
                mMRetriever.setDataSource(urls[0], new HashMap<String, String>());
            else
                mMRetriever.setDataSource(urls[0]);
            myBitmap = mMRetriever.getFrameAtTime();
        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            if (mMRetriever != null) {
                mMRetriever.release();
            }
        }
        return myBitmap;
    }

    protected void onPostExecute(Bitmap result) {
        bmImage.setImageBitmap(result);
    }
}
</code>```

Than call this AsyncTask like this

```<code>   new DownloadImage(YourImageView).execute("Your URL");
</code>```

EDIT

Or you can also use Glide to create thumbnail of video from url

```<code> RequestOptions requestOptions = new RequestOptions();
 requestOptions.placeholder(R.drawable.placeholder_card_view);
 requestOptions.error(R.drawable.placeholder_card_view);

  Glide.with(getContext())
       .load(path)
       .apply(requestOptions)
       .thumbnail(Glide.with(getContext()).load(path))
       .into(ivVideoThumbnail);
</code>```

Body:
How to create image/thumbnails of url video form server

and I try is  not work (not show thumbnails)

String  String url = "http://clips.vorwaerts-gmbh.de/VfE_html5.mp4";

     Bitmap thumb = ThumbnailUtils.createVideoThumbnail(url,MediaStore.Images.Thumbnails.MINI_KIND);

    Glide.with(context).load(thumb).asBitmap()
    /*.override(convertDpToPx(100), convertDpToPx(100))*/
    .placeholder(R.drawable.camera)
    .override(200, 200)
    .diskCacheStrategy(DiskCacheStrategy.ALL)
    .into(new BitmapImageViewTarget(img_view) {
     protected void setResource(Bitmap resource) {
    RoundedBitmapDrawable circularBitmapDrawable =
    RoundedBitmapDrawableFactory.create(context.getResources(), resource);
    //circularBitmapDrawable.setCircular(true);
    img_view.setImageDrawable(circularBitmapDrawable);
       }
    });

I get slove it by answer1 !

but it get some problem about thumbnails ,it's change color is stange.

example

Body:
Try this Create new AsyncTask like this

public class DownloadImage extends AsyncTask<String, Void, Bitmap> {
    ImageView bmImage;

    public DownloadImage(ImageView bmImage) {
        this.bmImage = (ImageView ) bmImage;
    }

    protected Bitmap doInBackground(String... urls) {
        Bitmap myBitmap = null;
        MediaMetadataRetriever mMRetriever = null;
        try {
            mMRetriever = new MediaMetadataRetriever();
            if (Build.VERSION.SDK_INT >= 14)
                mMRetriever.setDataSource(urls[0], new HashMap<String, String>());
            else
                mMRetriever.setDataSource(urls[0]);
            myBitmap = mMRetriever.getFrameAtTime();
        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            if (mMRetriever != null) {
                mMRetriever.release();
            }
        }
        return myBitmap;
    }

    protected void onPostExecute(Bitmap result) {
        bmImage.setImageBitmap(result);
    }
}

Than call this AsyncTask like this

   new DownloadImage(YourImageView).execute("Your URL");

EDIT

Or you can also use Glide to create thumbnail of video from url

 RequestOptions requestOptions = new RequestOptions();
 requestOptions.placeholder(R.drawable.placeholder_card_view);
 requestOptions.error(R.drawable.placeholder_card_view);

  Glide.with(getContext())
       .load(path)
       .apply(requestOptions)
       .thumbnail(Glide.with(getContext()).load(path))
       .into(ivVideoThumbnail);


来源: stackexchange

问:
specify destination for CTestTestfile.cmake
When executing cmake to generate ctest inputs, how can I directly specify the destination directory for the cmake-generated CTestTestfile.cmake? Specifically, my test suite is an independent cmake project. I currently add it to the main cmake project with include(), but the more appropriate method is to use add_subdirectory(). However, add_subdirectory() installs CTestTestfile.cmake in the subproject's directory in the build directory, but I need it in build/ for ctest to find it.

I set up the test macros in a file CTestList.cmake which lives in the test_project. This file is included in the build in test_project/CMakeLists.txt:

```<code>include(CTest)
include(${CMAKE_CURRENT_LIST_DIR}/CTestList.cmake)
</code>```

With include():

```<code>project/
|-- CMakeLists.txt
|-- src/
|-- test_project/
`-- build/
    |-- CTestTestfile.cmake
    `-- test_project/
</code>```

With add_subdirectory():

```<code>project/
|-- CMakeLists.txt
|-- src/
|-- test_project/
`-- build/
    `-- test_project/
        `-- CTestTestfile.cmake
</code>```

答:
The include and the add_subdirectory commands of CMake are very different.

While the include command works like #include of C and C++ – loads the content of included file into the file where it appears –, the add_subdirectory adds a subdirectory to the build. This means that when you use the add_subdirectory the variables inside the subdirectory's CMakeLists.txt will be the part of a different scope and the value of CMAKE_CURRENT_BINARY_DIR variable will be different too. Just add the following line to the test_project/CMakeLists.txt and try either to include it or add it by add_subdirectory:

```<code>message(STATUS "The files will be generated into: " ${CMAKE_CURRENT_BINARY_DIR})
</code>```

The enable_testing enables testing for current directory and below. So, when you used the add_subdirecory instead of include the current directory meant build/test_project/ – as explained above.

To make sure the CTestTestfile.cmake will be created in build directory too, simply add an extra enable_testing command to the top-level CMakeLists.txt.

ContentLicense: CC BY-SA 3.0

Body:
When executing cmake to generate ctest inputs, how can I directly specify the destination directory for the cmake-generated CTestTestfile.cmake? Specifically, my test suite is an independent cmake project. I currently add it to the main cmake project with include(), but the more appropriate method is to use add_subdirectory(). However, add_subdirectory() installs CTestTestfile.cmake in the subproject's directory in the build directory, but I need it in build/ for ctest to find it.

I set up the test macros in a file CTestList.cmake which lives in the test_project. This file is included in the build in test_project/CMakeLists.txt:

include(CTest)
include(${CMAKE_CURRENT_LIST_DIR}/CTestList.cmake)

With include():

project/
|-- CMakeLists.txt
|-- src/
|-- test_project/
`-- build/
    |-- CTestTestfile.cmake
    `-- test_project/

With add_subdirectory():

project/
|-- CMakeLists.txt
|-- src/
|-- test_project/
`-- build/
    `-- test_project/
        `-- CTestTestfile.cmake

Body:
The include and the add_subdirectory commands of CMake are very different.

While the include command works like #include of C and C++ – loads the content of included file into the file where it appears –, the add_subdirectory adds a subdirectory to the build. This means that when you use the add_subdirectory the variables inside the subdirectory's CMakeLists.txt will be the part of a different scope and the value of CMAKE_CURRENT_BINARY_DIR variable will be different too. Just add the following line to the test_project/CMakeLists.txt and try either to include it or add it by add_subdirectory:

message(STATUS "The files will be generated into: " ${CMAKE_CURRENT_BINARY_DIR})

The enable_testing enables testing for current directory and below. So, when you used the add_subdirecory instead of include the current directory meant build/test_project/ – as explained above.

To make sure the CTestTestfile.cmake will be created in build directory too, simply add an extra enable_testing command to the top-level CMakeLists.txt.


问:
How to turn on editing in cell Swift 3
I have a question about cell in swift. Let's imagine that I have a cell with 20 rows. The cell is selectable right now, but the thing I want is that, when user selects 20 row it should be editable. And the value which enters the user should be saved in some variable. Is it somehow possible? Thank's in advance!</p>

答:
If you want 20 cells in tableView, then
You have to make nib of a cell, and make textfield in cell, and also create outlet in nib, (you can also create prototype cell)

Then in cellForRow AtIndexPath makes textField delegate as self (to class), in that class you have to implement textField delegate, and then you can access textFields as:

```<code>let indexPath = IndexPath(row: 0, section: 0)
let cell = tableView(tableView cellForRowAt: IndexPath) as! MYCELL
let text = cell.textField.text
</code>```

Sorry for my bad english,

I think it will be helpful

Title: How to turn on editing in cell Swift 3

Body:
If you want 20 cells in tableView, then
You have to make nib of a cell, and make textfield in cell, and also create outlet in nib, (you can also create prototype cell)

Then in cellForRow AtIndexPath makes textField delegate as self (to class), in that class you have to implement textField delegate, and then you can access textFields as:

let indexPath = IndexPath(row: 0, section: 0)
let cell = tableView(tableView cellForRowAt: IndexPath) as! MYCELL
let text = cell.textField.text

Sorry for my bad english,

I think it will be helpful


问:
Consecutive use of std::list causes crash
I have code which is meant to do memory management, but it keeps crashing at a certain point where I remove an object from the 'live' list and place it onto the 'dead' one:

```<code>class MemoryObject {
private:
    static std::list <MemoryObject *> alive, dead;
    long references;
public:
    MemoryObject() {
        alive.push_back(this);
        references = 0;
    }

    static void deepClean() {
        clean();
        std::list<MemoryObject *>::iterator iterator;
        for(iterator = alive.begin(); iterator != alive.end(); iterator ++) {
            MemoryObject *object = *iterator;
            Log::instance().write(DEBUG_LOG, "\nObject still active at the end of the program, check for memory leaks."
                    "\nSize: %d",
                    alive.size());
            delete object;
        }
        alive.clear();
    }

    void reference() {
        references ++;
    }

    void release() {
        references --;
        if(references <= 0) {
            dead.push_back(this);
            alive.remove(this);
        }
    }

    static void clean() {
        std::list<MemoryObject *>::iterator iterator;
        for(iterator = dead.begin(); iterator != dead.end(); iterator ++)
            delete(&iterator);
        dead.clear();
    }

    ~MemoryObject() {
        clean();
    }
};

std::list <MemoryObject *> MemoryObject::alive, MemoryObject::dead;
</code>```

Eclipse debug shows it failing under release(), always at the second list-related spot - I've tried putting them (alive.remove(this) and dead.push_back(this)) in a different order, which changes nothing. Interestingly however, if I place something in-between them, like a printf() statement, it doesn't crash...

Here's where I'm calling it from:

```<code>#include <stdlib.h>
#include <stdio.h>

#include "log/log.hpp"
#include "memory/object.hpp"

int main(int argc, char *argv[]) {
    MemoryObject foo;
    foo.release();
    MemoryObject::deepClean();
    return 0;
}
</code>```

答:
In your clean function you have:

```<code>    delete(&iterator);
</code>```

That will compile, but will attempt to delete the iterator itself - which is on the stack (which will crash).

I suspect you wanted:

```<code>    delete(*iterator);
</code>```

Body:
I have code which is meant to do memory management, but it keeps crashing at a certain point where I remove an object from the 'live' list and place it onto the 'dead' one:

class MemoryObject {
private:
    static std::list <MemoryObject *> alive, dead;
    long references;
public:
    MemoryObject() {
        alive.push_back(this);
        references = 0;
    }

    static void deepClean() {
        clean();
        std::list<MemoryObject *>::iterator iterator;
        for(iterator = alive.begin(); iterator != alive.end(); iterator ++) {
            MemoryObject *object = *iterator;
            Log::instance().write(DEBUG_LOG, "\nObject still active at the end of the program, check for memory leaks."
                    "\nSize: %d",
                    alive.size());
            delete object;
        }
        alive.clear();
    }

    void reference() {
        references ++;
    }

    void release() {
        references --;
        if(references <= 0) {
            dead.push_back(this);
            alive.remove(this);
        }
    }

    static void clean() {
        std::list<MemoryObject *>::iterator iterator;
        for(iterator = dead.begin(); iterator != dead.end(); iterator ++)
            delete(&iterator);
        dead.clear();
    }

    ~MemoryObject() {
        clean();
    }
};

std::list <MemoryObject *> MemoryObject::alive, MemoryObject::dead;

Eclipse debug shows it failing under release(), always at the second list-related spot - I've tried putting them (alive.remove(this) and dead.push_back(this)) in a different order, which changes nothing. Interestingly however, if I place something in-between them, like a printf() statement, it doesn't crash...

Here's where I'm calling it from:

#include <stdlib.h>
#include <stdio.h>

#include "log/log.hpp"
#include "memory/object.hpp"

int main(int argc, char *argv[]) {
    MemoryObject foo;
    foo.release();
    MemoryObject::deepClean();
    return 0;
}

Body:
In your clean function you have:

    delete(&iterator);

That will compile, but will attempt to delete the iterator itself - which is on the stack (which will crash).

I suspect you wanted:

    delete(*iterator);


问:
My script is using .encode('utf-8') a lot. I feel like im doing something wrong
The problem i have with this script is that i have to keep calling .encode('utf-8') and this doesn't seem very zen to me. I must be doing something wrong.

```<code># -*- coding: utf-8 -*-

""" Simple rss to html converter """

__version__ = "0.0.1"
__author__ = "Ricky L Wilson"

import StringIO
from feedparser import parse as parsefeed
from bs4 import BeautifulSoup as bs

def entry2html(**kwargs):
    """ Format feedparser entry """
    title = kwargs['title'].encode('utf-8')
    link = kwargs['link'].encode('utf-8')
    description = kwargs['description'].encode('utf-8')
    template = """
    <h2 class='title'>{title}</h2>
    <a class='link' href='{link}'>{title}</a>
    <span class='description'>{description}</span>
    """
    return template.format(title=title, link=link, description=description)

def convert_feed(**kwargs):
    """ Main loop """
    out = StringIO.StringIO("")
    for entry in parsefeed(kwargs['url']).entries:
        title = entry['title']
        link = entry['link']
        description = entry['description']
        print >> out, entry2html(title=title, link=link, description=description)
    return bs(out.getvalue(), 'lxml').prettify()

def save_file(url, fname):
    ''' Save data to disc'''
    with open(fname, 'w') as file_object:
        file_object.write(convert_feed(url=url).encode('utf-8'))

print save_file('http://stackoverflow.com/feeds', 'index.html')
</code>```

PS. If i remove any of them the script will break.

I tried putting # -*- coding: utf-8 -*- at the top of the file but that didn't fix it. i got this error.

```<code>C:\Python27>python rss2html.py
  File "rss2html.py", line 40
    save_file('http://stackoverflow.com/feeds', 'index.html')
            ^
SyntaxError: invalid syntax

C:\Python27>python rss2html.py
Traceback (most recent call last):
  File "rss2html.py", line 40, in <module>
    save_file('http://stackoverflow.com/feeds', 'index.html')
  File "rss2html.py", line 38, in save_file
    file_object.write(convert_feed(url=url))
  File "rss2html.py", line 32, in convert_feed
    print >> out, entry2html(title=title, link=link, description=description)
  File "rss2html.py", line 22, in entry2html
    return template.format(title=title, link=link, description=description)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa3' in position 172: ordinal not in range(128)
</code>```

答:
Well i figured it out, let me know what you guys think.
Is this method better then all those .encode('utf-8') calls or is this a hack and their is still a more pythonic way to eliminate the .encode('utf-8') calls.

Here is the new script

```<code># -*- coding: utf-8 -*-
""" Simple rss to html converter """

__version__ = "0.0.1"
__author__ = "Ricky L Wilson"

import StringIO
from feedparser import parse as parsefeed
from bs4 import BeautifulSoup as bs

def flatten_unicode_keys(d):
    '''pass unicode keywords to **kwargs '''
    for k in d:
        if isinstance(k, unicode):
            v = d[k]
            del d[k]
            d[str(k)] = v

def entry2html(**kwargs):
    """ Format feedparser entry """
    flatten_unicode_keys(kwargs)
    title = kwargs['title']
    link = kwargs['link']
    description = kwargs['description']
    template = """
    <h2 class='title'>{title}</h2>
    <a class='link' href='{link}'>{title}</a>
    <span class='description'>{description}</span>
    """
    return template.format(title=title, link=link, description=description)

def convert_feed(**kwargs):
    """ Main loop """
    out = StringIO.StringIO("")
    for entry in parsefeed(kwargs['url']).entries:
        title = entry['title']
        link = entry['link']
        description = entry['description']
        print >> out, entry2html(title=title, link=link, description=description)
    return bs(out.getvalue(), 'lxml').prettify()

def save_file(url, fname):
    ''' Save data to disc'''
    with open(fname, 'w') as file_object:
        file_object.write(convert_feed(url=url))

save_file('http://stackoverflow.com/feeds', 'index.html')
</code>```

Body:
The problem i have with this script is that i have to keep calling .encode('utf-8') and this doesn't seem very zen to me. I must be doing something wrong.

# -*- coding: utf-8 -*-

""" Simple rss to html converter """

__version__ = "0.0.1"
__author__ = "Ricky L Wilson"

import StringIO
from feedparser import parse as parsefeed
from bs4 import BeautifulSoup as bs

def entry2html(**kwargs):
    """ Format feedparser entry """
    title = kwargs['title'].encode('utf-8')
    link = kwargs['link'].encode('utf-8')
    description = kwargs['description'].encode('utf-8')
    template = """

{title}

    {title}
    {description}
    """
    return template.format(title=title, link=link, description=description)

def convert_feed(**kwargs):
    """ Main loop """
    out = StringIO.StringIO("")
    for entry in parsefeed(kwargs['url']).entries:
        title = entry['title']
        link = entry['link']
        description = entry['description']
        print >> out, entry2html(title=title, link=link, description=description)
    return bs(out.getvalue(), 'lxml').prettify()

def save_file(url, fname):
    ''' Save data to disc'''
    with open(fname, 'w') as file_object:
        file_object.write(convert_feed(url=url).encode('utf-8'))

print save_file('http://stackoverflow.com/feeds', 'index.html')

PS. If i remove any of them the script will break.

I tried putting # -*- coding: utf-8 -*- at the top of the file but that didn't fix it. i got this error.

C:\Python27>python rss2html.py
  File "rss2html.py", line 40
    save_file('http://stackoverflow.com/feeds', 'index.html')
            ^
SyntaxError: invalid syntax

C:\Python27>python rss2html.py
Traceback (most recent call last):
  File "rss2html.py", line 40, in <module>
    save_file('http://stackoverflow.com/feeds', 'index.html')
  File "rss2html.py", line 38, in save_file
    file_object.write(convert_feed(url=url))
  File "rss2html.py", line 32, in convert_feed
    print >> out, entry2html(title=title, link=link, description=description)
  File "rss2html.py", line 22, in entry2html
    return template.format(title=title, link=link, description=description)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa3' in position 172: ordinal not in range(128)

Body:
Well i figured it out, let me know what you guys think.
Is this method better then all those .encode('utf-8') calls or is this a hack and their is still a more pythonic way to eliminate the .encode('utf-8') calls.

Here is the new script

# -*- coding: utf-8 -*-
""" Simple rss to html converter """

__version__ = "0.0.1"
__author__ = "Ricky L Wilson"

import StringIO
from feedparser import parse as parsefeed
from bs4 import BeautifulSoup as bs

def flatten_unicode_keys(d):
    '''pass unicode keywords to **kwargs '''
    for k in d:
        if isinstance(k, unicode):
            v = d[k]
            del d[k]
            d[str(k)] = v

def entry2html(**kwargs):
    """ Format feedparser entry """
    flatten_unicode_keys(kwargs)
    title = kwargs['title']
    link = kwargs['link']
    description = kwargs['description']
    template = """
    <h2 class='title'>{title}</h2>
    <a class='link' href='{link}'>{title}</a>
    <span class='description'>{description}</span>
    """
    return template.format(title=title, link=link, description=description)

def convert_feed(**kwargs):
    """ Main loop """
    out = StringIO.StringIO("")
    for entry in parsefeed(kwargs['url']).entries:
        title = entry['title']
        link = entry['link']
        description = entry['description']
        print >> out, entry2html(title=title, link=link, description=description)
    return bs(out.getvalue(), 'lxml').prettify()

def save_file(url, fname):
    ''' Save data to disc'''
    with open(fname, 'w') as file_object:
        file_object.write(convert_feed(url=url))

save_file('http://stackoverflow.com/feeds', 'index.html')


问:
more efficient way of searching 2D array - break after match?
I have a 2D array of units students are studying. For each unit there are different numbers of functions (aka objectives) they are studying and for each function, different numbers of prompts they could be asked in an assessment. My data is a 2D array thus:

```<code>functions = [
  ["Unit 1",
    [ // function 1
      "prompt 1",
      "prompt 2",
      ...,
      "prompt n"],
    [ // function 2
  etc...
</code>```

My code creates assessments based on which units have been studied by pulling random prompts and then shuffling these into the array (sm1).

Some of these prompts have image files associated with them and all have audio files. The file names for these media files are based on where they occur in our material, e.g. u1f1p1.mp3

So my solution was to match this regularity by creating file names based on their position in the array. Here's my code to do that:

```<code>for (var a = 0; a < sm1.length; a++) {// for each of sm1's prompts
    for (var b = 0; b <= functions.length-6; b++) { // limit it to units 1-3 of 8 for this specific assessment
       for(var c = 1; c < functions[b].length; c++) { // for each unit's function but starting at 1 to skip "Unit x" label at this point in the array
           for (var d = 0; d < functions[b][c].length; d++) { // for each prompt for each function for each unit
               if(functions[b][c][d] === sm1[a]) { // see if it matches
                    fileNames.push('u'+(b+1)+'f'+c+'p'+(d+1)); // create file name from index and add to fileNames[]
                }
            }
        }
    }
}
</code>```

This code works fine and, because speed is effectively irrelevant for our purposes, I could say job done. However, I know that this has to be hopelessly inefficient because not only is this a long loop, but it continues to run even after a match is found.

So, two questions:

What would be the most efficient way of finding a match?

How can I break once sm1[n] is found and go on to look for sm1[n+1]?

答:
In general, the most efficient way to loop over an array is to use array.forEach, unfortunately, it is not possible to short circuit Array.forEach calling break. How to short circuit Array.forEach like calling break?. But in this case, you can use another method, such as array.some() instead.

If I had to implement your project, I would not use 2D arrays, because it is less efficient than 1D arrays. And I would use arrays as follows :

```<code>let a = [];

a["prompt 1"] = {name: "tom", age: 15, unit: 1} // You can put all your infos in your objects
a["prompt 2"] = {name: "bob", age: 42, unit: 2}
a["prompt 3"] = {name: "alex", age: 55, unit: 3}
a["prompt 4"] = {name: "homer", age: 50, unit: 3}

let b = ["prompt 2", "prompt 4"]

b.forEach((key)=>{ // for each element of array b

    if(a[key] !== undefined) // one match found
    {
        // fileNames.push('u'+(b+1)+'f'+c+'p'+(d+1));
        console.log(a[key])
    }
})
</code>```

Body:
I have a 2D array of units students are studying. For each unit there are different numbers of functions (aka objectives) they are studying and for each function, different numbers of prompts they could be asked in an assessment. My data is a 2D array thus:

functions = [
  ["Unit 1",
    [ // function 1
      "prompt 1",
      "prompt 2",
      ...,
      "prompt n"],
    [ // function 2
  etc...

My code creates assessments based on which units have been studied by pulling random prompts and then shuffling these into the array (sm1).

Some of these prompts have image files associated with them and all have audio files. The file names for these media files are based on where they occur in our material, e.g. u1f1p1.mp3

So my solution was to match this regularity by creating file names based on their position in the array. Here's my code to do that:

for (var a = 0; a < sm1.length; a++) {// for each of sm1's prompts
    for (var b = 0; b <= functions.length-6; b++) { // limit it to units 1-3 of 8 for this specific assessment
       for(var c = 1; c < functions[b].length; c++) { // for each unit's function but starting at 1 to skip "Unit x" label at this point in the array
           for (var d = 0; d < functions[b][c].length; d++) { // for each prompt for each function for each unit
               if(functions[b][c][d] === sm1[a]) { // see if it matches
                    fileNames.push('u'+(b+1)+'f'+c+'p'+(d+1)); // create file name from index and add to fileNames[]
                }
            }
        }
    }
}

This code works fine and, because speed is effectively irrelevant for our purposes, I could say job done. However, I know that this has to be hopelessly inefficient because not only is this a long loop, but it continues to run even after a match is found.

So, two questions:

What would be the most efficient way of finding a match?

How can I break once sm1[n] is found and go on to look for sm1[n+1]?

Body:
In general, the most efficient way to loop over an array is to use array.forEach, unfortunately, it is not possible to short circuit Array.forEach calling break. How to short circuit Array.forEach like calling break?. But in this case, you can use another method, such as array.some() instead.

If I had to implement your project, I would not use 2D arrays, because it is less efficient than 1D arrays. And I would use arrays as follows :

let a = [];

a["prompt 1"] = {name: "tom", age: 15, unit: 1} // You can put all your infos in your objects
a["prompt 2"] = {name: "bob", age: 42, unit: 2}
a["prompt 3"] = {name: "alex", age: 55, unit: 3}
a["prompt 4"] = {name: "homer", age: 50, unit: 3}

let b = ["prompt 2", "prompt 4"]

b.forEach((key)=>{ // for each element of array b

    if(a[key] !== undefined) // one match found
    {
        // fileNames.push('u'+(b+1)+'f'+c+'p'+(d+1));
        console.log(a[key])
    }
})


问:
How does angular provide the arguments mentioned in the component class constructor?
I'm trying to understand angular deeply, so i read the docs and it was very helpful.

now in the dependency injection chapter i read that

angular uses the injector bubbling technique to provide the service mentioned in the constructor

now the injector bubbling goes to the parent components one by one and check if there is an available instance of the service in order to provide it.

i have two questions:

Q1) is the arguments in the constructor are always services?

Q2) if there is other than the services is mentioned in the constructor do they also use the bubbling technique?

答:
Q1) is the arguments in the constructor are always services?

If you're talking about classes that are instantiated through injector (for example components) then yes, Angular expects all arguments to the constructor to be injectables.

Q2) if there is other than the services is mentioned in the
  constructor do they also use the bubbling technique?

If there's anything else in the constructor that is not defined on any injector you will get an error:

Cannot resolve all parameters to...


问:
Android SQLite how to delete with limit
I want to delete only one row  from my database table User.

I tried this, but I have no idea how to use SQLITE_ENABLE_UPDATE_DELETE_LIMIT.

Here is my code:

```<code>    SQLiteDatabase sqLiteDatabase = this.openOrCreateDatabase("User", MODE_PRIVATE, null);

        //sqLiteDatabase.execSQL("INSERT INTO user (name, age) VALUES ('jihyo', 10)");

        sqLiteDatabase.execSQL("DELETE FROM user WHERE name ='jihyo' LIMIT 1");
        Cursor c = sqLiteDatabase.rawQuery("SELECT * FROM user WHERE name = 'jihyo'", null);
        int nameIndex = c.getColumnIndex("name");
        int ageIndex = c.getColumnIndex("age");

        c.moveToFirst();
        do {
            Log.v("name", c.getString(nameIndex));
            Log.v("age", c.getString(ageIndex));
        } while (c.moveToNext());
</code>```

Here is the error:

android.database.sqlite.SQLiteException: near "LIMIT": syntax error
  (code 1): , while compiling: DELETE FROM user WHERE name ='jihyo'
  LIMIT 1

答:
Try this:

```<code>db.execSQL("Delete from user where user_id IN (Select user_id from user where name = 'jihyo' limit 1)");
</code>```

[UPDATED] : the = doesn't work with the LIMIT operation so you need to make it like this :

```<code>Cursor c = db.execSQL("Select user_id from user where name = 'jihyo' limit 1");
        if (c.moveToFirst()){
            String id = c.getString(0);
            db.execSQL("Delete from user where user_id = "+id);
        }
</code>```

Title: Android SQLite how to delete with limit

Body:
I want to delete only one row  from my database table User.

I tried this, but I have no idea how to use SQLITE_ENABLE_UPDATE_DELETE_LIMIT.

Here is my code:

    SQLiteDatabase sqLiteDatabase = this.openOrCreateDatabase("User", MODE_PRIVATE, null);

        //sqLiteDatabase.execSQL("INSERT INTO user (name, age) VALUES ('jihyo', 10)");

        sqLiteDatabase.execSQL("DELETE FROM user WHERE name ='jihyo' LIMIT 1");
        Cursor c = sqLiteDatabase.rawQuery("SELECT * FROM user WHERE name = 'jihyo'", null);
        int nameIndex = c.getColumnIndex("name");
        int ageIndex = c.getColumnIndex("age");

        c.moveToFirst();
        do {
            Log.v("name", c.getString(nameIndex));
            Log.v("age", c.getString(ageIndex));
        } while (c.moveToNext());

Here is the error:

android.database.sqlite.SQLiteException: near "LIMIT": syntax error
  (code 1): , while compiling: DELETE FROM user WHERE name ='jihyo'
  LIMIT 1

Body:
Try this:

db.execSQL("Delete from user where user_id IN (Select user_id from user where name = 'jihyo' limit 1)");

[UPDATED] : the = doesn't work with the LIMIT operation so you need to make it like this :

Cursor c = db.execSQL("Select user_id from user where name = 'jihyo' limit 1");
        if (c.moveToFirst()){
            String id = c.getString(0);
            db.execSQL("Delete from user where user_id = "+id);
        }


问:
CakePHP 3 - Select rows of containing table by date (year)
I've a table like below and now I wan't to get the rows by year. But when I try this I will get the following error:

Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Matches.date' in 'where clause'

My "Matches" table

```<code>id | goalsfor   | goalsagainst  | date
1  | 5          | 4             | 2017-07-05 15:57:36
2  | 9          | 5             | 2017-07-05 17:06:31
3  | 7          | 8             | 2015-07-05 15:57:36
4  | 0          | 2             | 2014-07-05 15:57:36
6  | 5          | 4             | 2014-07-05 15:57:36
7  | 7          | 9             | 2014-07-05 15:57:36
</code>```

My query:

```<code> $playedMatches = $this->Players
    ->find()
    ->contain([
       'MatchePlayers' => [
          'Matches'
       ]
    ]);

 $playedMatches->where(['YEAR(Matches.date) =' => "2017"]);
</code>```

My associations:

```<code>class PlayersTable extends Table {

    public function initialize(array $config) {
        parent::initialize($config);

        $this->setTable('players');
        $this->setDisplayField('id');
        $this->setPrimaryKey('id');

        $this->hasMany('MatchePlayers', [
            'className' => 'MatchPlayers',
            'foreignKey' => 'player_id',
            'propertyName' => 'matches',
            'dependent' => true
        ]);
    }
}

class MatchPlayersTable extends Table {

    public function initialize(array $config) {
        parent::initialize($config);

        $this->setTable('matches_players');
        $this->setDisplayField('id');
        $this->setPrimaryKey('id');

        $this->belongsTo('Players', [
            'className' => 'Players',
            'foreignKey' => 'player_id',
            'propertyName' => 'player'
        ]);

        $this->belongsTo('Matches', [
            'className' => 'Matches',
            'foreignKey' => 'match_id',
            'propertyName' => 'match'
        ]);
    }
}
</code>```

答:
There is mistake in your query, your syntax for contain is wrong, Try this,

```<code>$playedMatches = $this->Players
->find()
->contain([
   'MatchePlayers.Matches'
]);
$playedMatches->where(['YEAR(MatchePlayers.Matches.date) =' => "2017"]);
</code>```

Happy Coding :)

Body:
I've a table like below and now I wan't to get the rows by year. But when I try this I will get the following error:

Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Matches.date' in 'where clause'

My "Matches" table

id | goalsfor   | goalsagainst  | date
1  | 5          | 4             | 2017-07-05 15:57:36
2  | 9          | 5             | 2017-07-05 17:06:31
3  | 7          | 8             | 2015-07-05 15:57:36
4  | 0          | 2             | 2014-07-05 15:57:36
6  | 5          | 4             | 2014-07-05 15:57:36
7  | 7          | 9             | 2014-07-05 15:57:36

My query:

 $playedMatches = $this->Players
    ->find()
    ->contain([
       'MatchePlayers' => [
          'Matches'
       ]
    ]);

 $playedMatches->where(['YEAR(Matches.date) =' => "2017"]);

My associations:

class PlayersTable extends Table {

    public function initialize(array $config) {
        parent::initialize($config);

        $this->setTable('players');
        $this->setDisplayField('id');
        $this->setPrimaryKey('id');

        $this->hasMany('MatchePlayers', [
            'className' => 'MatchPlayers',
            'foreignKey' => 'player_id',
            'propertyName' => 'matches',
            'dependent' => true
        ]);
    }
}

class MatchPlayersTable extends Table {

    public function initialize(array $config) {
        parent::initialize($config);

        $this->setTable('matches_players');
        $this->setDisplayField('id');
        $this->setPrimaryKey('id');

        $this->belongsTo('Players', [
            'className' => 'Players',
            'foreignKey' => 'player_id',
            'propertyName' => 'player'
        ]);

        $this->belongsTo('Matches', [
            'className' => 'Matches',
            'foreignKey' => 'match_id',
            'propertyName' => 'match'
        ]);
    }
}

Body:
There is mistake in your query, your syntax for contain is wrong, Try this,

$playedMatches = $this->Players
->find()
->contain([
   'MatchePlayers.Matches'
]);
$playedMatches->where(['YEAR(MatchePlayers.Matches.date) =' => "2017"]);

Happy Coding :)


问:
PHP: MYSQLI Change Order By Style

Hi, i want to get data from chat table like this:

```<code>6
7
8
</code>```

My Code show like this:

```<code>8
7
6
</code>```

Code:

```<code>"SELECT * FROM `chat` WHERE
    `chat-code` = 'vm1mxo3dpi9gzuo' AND (`user_1` = '1' OR `user_2` = '1')
     ORDER BY id DESC LIMIT 3"
</code>```

答:
```<code>SELECT a.*
  FROM
     ( SELECT *
         FROM chat
        WHERE `chat-code` = 'vm1mxo3dpi9gzuo'
          AND 1 IN(user_1,user_2)
        ORDER
           BY id DESC
        LIMIT 3
     ) a
 ORDER
    BY id;
</code>```

Title: PHP: MYSQLI Change Order By Style

Body:
Hi, i want to get data from chat table like this:

6
7
8

My Code show like this:

8
7
6

Code:

"SELECT * FROM `chat` WHERE
    `chat-code` = 'vm1mxo3dpi9gzuo' AND (`user_1` = '1' OR `user_2` = '1')
     ORDER BY id DESC LIMIT 3"


问:
how to save listbox item as .config file and read it back to listbox?
In my WPF project, I have a listbox that I can add some items to it in this way:

```<code>//item is a class type of Product
var item = GetProductByID(ProductID);
lb_Configuration.Items.Add(item);
</code>```

Now I want to save the listbox items when I close this application as a config file and when I reopen it, I can reload this config file to application thus to add the corresponding items to the listbox, how should I suppose to do this? Thanks in advance!

Edit:

```<code>    private void OpenFile_Executed(object sender, ExecutedRoutedEventArgs e)
    {
        OpenFileDialog openFile = new OpenFileDialog();
        openFile.Multiselect = true;
        openFile.Title = "Please Choose Your File";
        openFile.Filter = "All Files(*,*)|*.*";
        if (openFile.ShowDialog() == true)
        {
            /* What to do after open file */
            StreamReader sr = File.OpenText(openFile.FileName);
            while (sr.EndOfStream != true) ;
        }
    }

    private void SaveFile_Executed(object sender, ExecutedRoutedEventArgs e)
    {
        SaveFileDialog saveFile = new SaveFileDialog();
        saveFile.Filter = "Text File|*.txt";
        if (saveFile.ShowDialog() == true)
        {
            StreamWriter sw = File.AppendText(saveFile.FileName);
            sw.Flush();
            sw.Close();
        }
    }
</code>```

答:
An exact working answer can't be given since we don't know the make-up of the type Product, but the bottom line here is serialization - which may be extremely simple, or could get more complicated depends on the types used and exposed by the type Product. There are numerous tools for this: JSON.net, ServiceStack, and even built-in .net serialization.

For simplicitly and an example, consider using JavaScriptSerializer:

```<code>var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(item);
</code>```

And to do it in the other direction...

```<code>var item = serializer.Deserialize<Product>(json);
</code>```

That's a starting point, if nothing else. Obviously adjust it to serialize the whole collection, make sure all the relevant values are being serialized and deserialized and properly, and save to file:

```<code>File.WriteAllText(pathToFile, json);
</code>```

To read it back:

```<code>var json = File.ReadAllText(pathToFile);
</code>```

Body:
In my WPF project, I have a listbox that I can add some items to it in this way:

//item is a class type of Product
var item = GetProductByID(ProductID);
lb_Configuration.Items.Add(item);

Now I want to save the listbox items when I close this application as a config file and when I reopen it, I can reload this config file to application thus to add the corresponding items to the listbox, how should I suppose to do this? Thanks in advance!

Edit:

    private void OpenFile_Executed(object sender, ExecutedRoutedEventArgs e)
    {
        OpenFileDialog openFile = new OpenFileDialog();
        openFile.Multiselect = true;
        openFile.Title = "Please Choose Your File";
        openFile.Filter = "All Files(*,*)|*.*";
        if (openFile.ShowDialog() == true)
        {
            /* What to do after open file */
            StreamReader sr = File.OpenText(openFile.FileName);
            while (sr.EndOfStream != true) ;
        }
    }

    private void SaveFile_Executed(object sender, ExecutedRoutedEventArgs e)
    {
        SaveFileDialog saveFile = new SaveFileDialog();
        saveFile.Filter = "Text File|*.txt";
        if (saveFile.ShowDialog() == true)
        {
            StreamWriter sw = File.AppendText(saveFile.FileName);
            sw.Flush();
            sw.Close();
        }
    }

Body:
An exact working answer can't be given since we don't know the make-up of the type Product, but the bottom line here is serialization - which may be extremely simple, or could get more complicated depends on the types used and exposed by the type Product. There are numerous tools for this: JSON.net, ServiceStack, and even built-in .net serialization.

For simplicitly and an example, consider using JavaScriptSerializer:

var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(item);

And to do it in the other direction...

var item = serializer.Deserialize<Product>(json);

That's a starting point, if nothing else. Obviously adjust it to serialize the whole collection, make sure all the relevant values are being serialized and deserialized and properly, and save to file:

File.WriteAllText(pathToFile, json);

To read it back:

var json = File.ReadAllText(pathToFile);


问:
Can't Fix ASP.NET MVC Validation
I've been trying to fix the validation on my form for a while now, but can't get it to work properly. The validation works fine, unless I enter a valid email address. If I do, then it just skips all other validation for some reason.

Also, would appreciate advice about if I'm doing it right with the split of everything in the controller. Should there be 2 actions (1 for GET to just load the empty form and 1 for POST when the user submits it)? Am I doing something wrong there?

EDIT: Correction: If I enter a valid email address, the form submits fine and ignores the other validation. If I don't have a valid email address, the validation checks everything.

Here's my model class:

```<code>public class User
{
    public int ID { get; set; }

    [DisplayName("Name")]
    [Required(ErrorMessage = "Name is required")]
    public string Name { get; set; }

    [DisplayName("Email")]
    [DataType(DataType.EmailAddress)]
    [Required(ErrorMessage = "Email is required")]
    [RegularExpression(
        @"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
            @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$",
        ErrorMessage = "Invalid email")]
    public string Email { get; set; }

    [DisplayName("Password")]
    [DataType(DataType.Password)]
    [Required(ErrorMessage = "Password required")]
    [MinLength(6, ErrorMessage = "Min 6 characters")]
    public string Password { get; set; }
}
</code>```

Here is my controller:

```<code>    public ActionResult Register()
    {
        ViewBag.LoggedIn = false;

        return View();
    }

    [HttpPost]
    public ActionResult Register(User user)
    {
        ViewBag.LoggedIn = false;

        user.Password = PasswordHash.CreateHash(user.Password);

        using (var context = new FoundationContext())
        {
            // if user exists
            if (context.Users.FirstOrDefault(n => n.Email == user.Email) != null) return Login(true);

            context.Users.Add(user);
            context.SaveChanges();
        }

        return View("~/Views/Home.Index.cshtml");
    }
</code>```

And here is my form:

```<code>    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()

        <div class="form-horizontal">
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            <div class="form-group">
                @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                <div class="col-md-10 text-center">
                    <input type="submit" value="Register" class="btn btn-primary" />
                </div>
            </div>
        </div>
    }
</code>```

And of course bottom of the body includes:

```<code>@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
</code>```

答:
In order to check if posted model is valid you need to check ModelState.IsValid in the post action (see in the example below).

Also, would appreciate advice about if I'm doing it right with the split of everything in the controller. Should there be 2 actions (1 for GET to just load the empty form and 1 for POST when the user submits it)? Am I doing something wrong there?

The approach is right but the way you do it is not.

Assuming that you have a Register.cshtml view (not a partial view):
Since a view has a model, you should always provide it. So your get method should look like this:

```<code>public ActionResult Register()
{
    ViewBag.LoggedIn = false;
    var model =  new User();
    return View(model);
}
</code>```

For the post method there are 2 approaches:

POST-REDIRECT-GET pattern (PRG) - a little bit more complex(but in my opinion it is more correct way of doing this). Post method instead of returning a view should return a redirect result both in case of error and in case of success. For handling invalid model state you can use some approaches that are described here

Your way

```<code>[HttpPost]
public ActionResult Register(User user)
{
  ViewBag.LoggedIn = false;
  if(!this.ModelState.IsValid)
  {
     return View(user);
     //this will render a view with preserved invalid model state so all the values with the corresponding error messages will be shown.
  }

  user.Password = PasswordHash.CreateHash(user.Password);

  using (var context = new FoundationContext())
  {
      // if user exists
      if (context.Users.FirstOrDefault(n => n.Email == user.Email) != null) return Login(true);

      context.Users.Add(user);
      context.SaveChanges();
  }

  return RedirectToAction("Index", "Home");
}
</code>```

Title: Can't Fix ASP.NET MVC Validation

Body:
I've been trying to fix the validation on my form for a while now, but can't get it to work properly. The validation works fine, unless I enter a valid email address. If I do, then it just skips all other validation for some reason.

Also, would appreciate advice about if I'm doing it right with the split of everything in the controller. Should there be 2 actions (1 for GET to just load the empty form and 1 for POST when the user submits it)? Am I doing something wrong there?

EDIT: Correction: If I enter a valid email address, the form submits fine and ignores the other validation. If I don't have a valid email address, the validation checks everything.

Here's my model class:

public class User
{
    public int ID { get; set; }

    [DisplayName("Name")]
    [Required(ErrorMessage = "Name is required")]
    public string Name { get; set; }

    [DisplayName("Email")]
    [DataType(DataType.EmailAddress)]
    [Required(ErrorMessage = "Email is required")]
    [RegularExpression(
        @"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
            @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$",
        ErrorMessage = "Invalid email")]
    public string Email { get; set; }

    [DisplayName("Password")]
    [DataType(DataType.Password)]
    [Required(ErrorMessage = "Password required")]
    [MinLength(6, ErrorMessage = "Min 6 characters")]
    public string Password { get; set; }
}

Here is my controller:

    public ActionResult Register()
    {
        ViewBag.LoggedIn = false;

        return View();
    }

    [HttpPost]
    public ActionResult Register(User user)
    {
        ViewBag.LoggedIn = false;

        user.Password = PasswordHash.CreateHash(user.Password);

        using (var context = new FoundationContext())
        {
            // if user exists
            if (context.Users.FirstOrDefault(n => n.Email == user.Email) != null) return Login(true);

            context.Users.Add(user);
            context.SaveChanges();
        }

        return View("~/Views/Home.Index.cshtml");
    }

And here is my form:

    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()

            @Html.ValidationSummary(true, "", new { @class = "text-danger" })

                @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })

                    @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })

                @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })

                    @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })

                @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })

                    @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })

                    <input type="submit" value="Register" class="btn btn-primary" />

    }

And of course bottom of the body includes:

@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)

Body:
In order to check if posted model is valid you need to check ModelState.IsValid in the post action (see in the example below).

Also, would appreciate advice about if I'm doing it right with the split of everything in the controller. Should there be 2 actions (1 for GET to just load the empty form and 1 for POST when the user submits it)? Am I doing something wrong there?

The approach is right but the way you do it is not.

Assuming that you have a Register.cshtml view (not a partial view):
Since a view has a model, you should always provide it. So your get method should look like this:

public ActionResult Register()
{
    ViewBag.LoggedIn = false;
    var model =  new User();
    return View(model);
}

For the post method there are 2 approaches:

POST-REDIRECT-GET pattern (PRG) - a little bit more complex(but in my opinion it is more correct way of doing this). Post method instead of returning a view should return a redirect result both in case of error and in case of success. For handling invalid model state you can use some approaches that are described here

Your way

[HttpPost]
public ActionResult Register(User user)
{
  ViewBag.LoggedIn = false;
  if(!this.ModelState.IsValid)
  {
     return View(user);
     //this will render a view with preserved invalid model state so all the values with the corresponding error messages will be shown.
  }

  user.Password = PasswordHash.CreateHash(user.Password);

  using (var context = new FoundationContext())
  {
      // if user exists
      if (context.Users.FirstOrDefault(n => n.Email == user.Email) != null) return Login(true);

      context.Users.Add(user);
      context.SaveChanges();
  }

  return RedirectToAction("Index", "Home");
}


问:
find the same elements count of two sorted array using functional programming style
Example:
Given nums1 = [1, 2, 3, 4], nums2 = [2, 3], return 2

I have the imperative style solution using python, the algorithm complexity is O(m+n) :

```<code>def sameElementsCount(nums1, nums2):
    count = 0
    len1 = len(nums1)
    len2 = len(nums2)
    i = 0
    j = 0
    while i < len1 and j < len2:
        if nums1[i] == nums2[j]:
            count += 1
            i += 1
            j += 1
        elif nums1[i] < nums2[j]:
            i += 1
        else:
            j += 1
    return count

print sameElementsCount([1,2,3,4], [2,3])
</code>```

how to do it using functional programming  higher order functions like (map/filter/reduce). make sure the
algorithm complexity is O(m+n)

答:
The answer len(set(num1) & set(num2)) given in some posts is quick to write, but it computes the  actual set intersection when only its cardinality was needed. Moreover it does not highlight any use of functional programming style.

The following behaves exactly like your program but with a functional programming style :
the while loop is turned into a recursive function and the counters disapear to let place to a pattern matching over the lists.

```<code>def sameElementsCount(nums1, nums2):
    len1 = len(nums1)
    len2 = len(nums2)
    if len1 == 0 or len2 == 0:
        return 0
    elif nums1[0] == nums2[0]:
        return 1+sameElementsCount(nums1[1:],nums2[1:])
    elif nums1[0] < nums2[0]:
        return sameElementsCount(nums1[1:],nums2)
    else:
        return sameElementsCount(nums1,nums2[1:])

print sameElementsCount([1,2,3,4], [2,3])
</code>```

Body:
Example:
Given nums1 = [1, 2, 3, 4], nums2 = [2, 3], return 2

I have the imperative style solution using python, the algorithm complexity is O(m+n) :

def sameElementsCount(nums1, nums2):
    count = 0
    len1 = len(nums1)
    len2 = len(nums2)
    i = 0
    j = 0
    while i < len1 and j < len2:
        if nums1[i] == nums2[j]:
            count += 1
            i += 1
            j += 1
        elif nums1[i] < nums2[j]:
            i += 1
        else:
            j += 1
    return count

print sameElementsCount([1,2,3,4], [2,3])

how to do it using functional programming  higher order functions like (map/filter/reduce). make sure the
algorithm complexity is O(m+n)

Body:
The answer len(set(num1) & set(num2)) given in some posts is quick to write, but it computes the  actual set intersection when only its cardinality was needed. Moreover it does not highlight any use of functional programming style.

The following behaves exactly like your program but with a functional programming style :
the while loop is turned into a recursive function and the counters disapear to let place to a pattern matching over the lists.

def sameElementsCount(nums1, nums2):
    len1 = len(nums1)
    len2 = len(nums2)
    if len1 == 0 or len2 == 0:
        return 0
    elif nums1[0] == nums2[0]:
        return 1+sameElementsCount(nums1[1:],nums2[1:])
    elif nums1[0] < nums2[0]:
        return sameElementsCount(nums1[1:],nums2)
    else:
        return sameElementsCount(nums1,nums2[1:])

print sameElementsCount([1,2,3,4], [2,3])


问:
MySQL, PHPMyAdmin - table column not accepting Decimal Datatype Length
I am creating a table named users. It has two columns, user_id and balance. For balance column the datatype is Decimal and the length is 8,2. I inserted these values while table creation. However, when I review the table structure for the balance column, I'm getting the Decimal length as '8,0' and not '8,2'. Can anyone explain why this is happening ?

答: As you can read from the comments, all you have to do is update PHPMyAdmin to its latest version. Once that is done, the column of the table accepts the mentioned length for the Decimal Datatype.


问:
weird colormap when map the scalar value to RGB using matplotlib.colors.Colormap
I am trying to get RGB hex strings from a input scalar given a specific matplot lib colormap. I use matplotlib.get_cmap() to get the matplotlib.colors.Colormap object, and pass a scalar withing range (0, 1) to this map to get the RGBA value then plot that color. But sometimes the colors gets plotted are different from those plotted by imshow(). Am I doing something stupid here?

Code for reproduction

```<code>import matplotlib.pyplot as plt
import numpy as np
plt.ioff()

cmap = 'RdBu_r'
cmap = plt.get_cmap(cmap)

f = plt.figure(figsize=(8, 4))
ax1 = f.add_subplot(121)
ax2 = f.add_subplot(122)
plot_arr = np.arange(100).reshape((10, 10)) / 99.
ax1.imshow(plot_arr, vmin=0., vmax=1., cmap=cmap, interpolation='nearest')

for i in range(10):
    for j in range(10):
        curr_rgb = cmap(plot_arr[i, j])[0:3]
        curr_rgb = tuple([int(x * 255) for x in curr_rgb])
        r, g, b = curr_rgb
        curr_cstr = '#{:0<2}{:0<2}{:0<2}'.format(hex(r)[2:], hex(g)[2:], hex(b)[2:])
        ax2.plot(j, i, 'o', mfc=curr_cstr, lw=0, mec='none', ms=20)

ax2.set_xlim([-0.5, 9.5])
ax2.set_ylim([9.5, -0.5])
plt.show()
</code>```

Actual outcome

output image

Expected outcome
As implemented in the code, the left plot is plotted as imshow(). Right plot is plotted dots with the color from the colormap object according to the input scalar. If my understanding is right, the colors at the same grid cell should be identical. But clearly different at high and low values.

Matplotlib version

    Operating System: windows 7 64-bit

    Matplotlib Version: 2.0.2

    Python Version: 3.5.3

    numpy: 1.13.0

答:
While the other answer explain well why the code from the question fails, I would like to note that there is no need to convert colors to hex at all and you may directly use the colormap to colorize the points in the plot.

You may either decide to loop over the points and directly supply the applied colormap value to the color argument of the plot. (middle plot)

Or you may use a scatter plot and supply the plot_arr to its c argument, together with the colormap, and, if needed, a normalization. (right plot)

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

cmapname = 'RdBu_r'
cmap = plt.get_cmap(cmapname)

plot_arr = np.arange(100).reshape((10, 10)) / 99.

fig, (ax1,ax2,ax3) = plt.subplots(ncols=3, figsize=(9, 3.5),subplot_kw={"aspect":"equal"})

ax1.set_title("image")
ax1.imshow(plot_arr, vmin=0., vmax=1., cmap=cmap, interpolation='nearest')

ax2.set_title("plot in loop")
for i in range(10):
    for j in range(10):
        ax2.plot(j, i, 'o', color=cmap(plot_arr[i, j]), lw=0, mec='none', ms=10)

ax2.set_ylim([9.5, -0.5])

ax3.set_title("scatter")
x = np.arange(0,10)
X,Y = np.meshgrid(x,x)
ax3.scatter(X,Y,c=plot_arr, s=100, vmin=0., vmax=1., cmap='RdBu_r', edgecolors="none")
ax3.set_ylim([9.5, -0.5])

plt.show()
</code>```

Body:
I am trying to get RGB hex strings from a input scalar given a specific matplot lib colormap. I use matplotlib.get_cmap() to get the matplotlib.colors.Colormap object, and pass a scalar withing range (0, 1) to this map to get the RGBA value then plot that color. But sometimes the colors gets plotted are different from those plotted by imshow(). Am I doing something stupid here?

Code for reproduction

import matplotlib.pyplot as plt
import numpy as np
plt.ioff()

cmap = 'RdBu_r'
cmap = plt.get_cmap(cmap)

f = plt.figure(figsize=(8, 4))
ax1 = f.add_subplot(121)
ax2 = f.add_subplot(122)
plot_arr = np.arange(100).reshape((10, 10)) / 99.
ax1.imshow(plot_arr, vmin=0., vmax=1., cmap=cmap, interpolation='nearest')

for i in range(10):
    for j in range(10):
        curr_rgb = cmap(plot_arr[i, j])[0:3]
        curr_rgb = tuple([int(x * 255) for x in curr_rgb])
        r, g, b = curr_rgb
        curr_cstr = '#{:0<2}{:0<2}{:0<2}'.format(hex(r)[2:], hex(g)[2:], hex(b)[2:])
        ax2.plot(j, i, 'o', mfc=curr_cstr, lw=0, mec='none', ms=20)

ax2.set_xlim([-0.5, 9.5])
ax2.set_ylim([9.5, -0.5])
plt.show()

Actual outcome

output image

Expected outcome
As implemented in the code, the left plot is plotted as imshow(). Right plot is plotted dots with the color from the colormap object according to the input scalar. If my understanding is right, the colors at the same grid cell should be identical. But clearly different at high and low values.

Matplotlib version

    Operating System: windows 7 64-bit

    Matplotlib Version: 2.0.2

    Python Version: 3.5.3

    numpy: 1.13.0

Body:
While the other answer explain well why the code from the question fails, I would like to note that there is no need to convert colors to hex at all and you may directly use the colormap to colorize the points in the plot.

You may either decide to loop over the points and directly supply the applied colormap value to the color argument of the plot. (middle plot)

Or you may use a scatter plot and supply the plot_arr to its c argument, together with the colormap, and, if needed, a normalization. (right plot)

import matplotlib.pyplot as plt
import numpy as np

cmapname = 'RdBu_r'
cmap = plt.get_cmap(cmapname)

plot_arr = np.arange(100).reshape((10, 10)) / 99.

fig, (ax1,ax2,ax3) = plt.subplots(ncols=3, figsize=(9, 3.5),subplot_kw={"aspect":"equal"})

ax1.set_title("image")
ax1.imshow(plot_arr, vmin=0., vmax=1., cmap=cmap, interpolation='nearest')

ax2.set_title("plot in loop")
for i in range(10):
    for j in range(10):
        ax2.plot(j, i, 'o', color=cmap(plot_arr[i, j]), lw=0, mec='none', ms=10)

ax2.set_ylim([9.5, -0.5])

ax3.set_title("scatter")
x = np.arange(0,10)
X,Y = np.meshgrid(x,x)
ax3.scatter(X,Y,c=plot_arr, s=100, vmin=0., vmax=1., cmap='RdBu_r', edgecolors="none")
ax3.set_ylim([9.5, -0.5])

plt.show()


问:
Wirte information from txt-files to xls with an identifier
I have an excel sheet with the columns

```<code>IdNr    Filename rep_cke file_description
10      5432.txt rutine  "information from txt file (5432.txt)"
20      5683.txt rutine  "information from txt file (5683.txt)"
</code>```

Now is there a way to use python to write the all the information from the text-files to the corresponding cell for the matching filename in the sheet?
 what i've come to so fare

```<code>   def main():
    file = open("51712640_Rutine.txt", "r")
    lines = file.readlines()
    file.close()
    print("Txt file read")
    #print(lines)

main()

csv_file = open("bakgrunnsData.csv")
csv_reader = csv.reader(csv_file, delimiter=";")

for row in csv_reader:
    print (row[1])

csv_file.close()
</code>```

答:
Python has a built in csv module. If you can convert your xls file to csv, this should be good enough.

Alternatively, you can use the pandas library for more advanced functionality.

Body:
I have an excel sheet with the columns

IdNr    Filename rep_cke file_description
10      5432.txt rutine  "information from txt file (5432.txt)"
20      5683.txt rutine  "information from txt file (5683.txt)"

Now is there a way to use python to write the all the information from the text-files to the corresponding cell for the matching filename in the sheet?
 what i've come to so fare

   def main():
    file = open("51712640_Rutine.txt", "r")
    lines = file.readlines()
    file.close()
    print("Txt file read")
    #print(lines)

main()

csv_file = open("bakgrunnsData.csv")
csv_reader = csv.reader(csv_file, delimiter=";")

for row in csv_reader:
    print (row[1])

csv_file.close()


问:
Significance of depth level (in a closure table) and how to get it done in php
Studying about the closure table I came across an example which has a column named “depth” which represents the depth level from the root to the tree.

```<code>comment_closure
- ancestor
- descendant
- depth
</code>```

Tutorial:

https://coderwall.com/p/lixing/closure-tables-for-browsing-trees-in-sql

What I do not understand is-

The need for having a depth column?

and if it is significant how do I code this on at the programming (php) level, since the database wouldn’t be visible on the front end for me decide what level the descendant is at.

答:
Personally I have not often had a Depth column in such a table. Conclusion: you do not need it for your code to function.
While looping over elements and going deeper in the structure you can keep track of the depth yourself. Or if you start somewhere halfway the structure, you could query up the tree to find out the depth.

That said, looking at it from a convenience and performance perspective, it would be good to always have the depth column:

During setup of the tree you always know (or can find out) the depth.

After that the depth will not change (unless the structure changes at some point in time, in which case you have to change the depths of all items as well ofcourse)

Doing it at setup-time instead of while reading it will be much more efficiënt and optimize readability as well, since you don't have to lookup things you already know.

Now why would you need the depth? That totally depends on your use case.
Like I said, I almost never have had a depth-column because I don't need it.

But I could think of use-cases where depth can be convenient, e.g.:

all items with depth 3 are of a certain type. So you can map the depth to a type or class;

or in a menu structure for instance you could have all items with a certain depth a certain CSS style

maybe in a certain case you only want to query all items with depth 1

I hope this answers your question.

Body:
Studying about the closure table I came across an example which has a column named “depth” which represents the depth level from the root to the tree.

comment_closure
- ancestor
- descendant
- depth

Tutorial:

https://coderwall.com/p/lixing/closure-tables-for-browsing-trees-in-sql

What I do not understand is-

The need for having a depth column?

and if it is significant how do I code this on at the programming (php) level, since the database wouldn’t be visible on the front end for me decide what level the descendant is at.


问:
SQL data returned in a comma-delimited list
Here are my tables:

```<code>-----------------------------------------
Hotels
-----------------------------------------
HotelID | HotelName
-----------------------------------------

-----------------------------------------
HotelImages
-----------------------------------------
HotelImageID | HotelID | Filename
-----------------------------------------
</code>```

I'd like to create a SELECT statement that will return the data like so:

```<code>HotelID | HotelName | Images
-----------------------------------------
1 | Hotel1 | Image1,Image2,Image3
2 | Hotel2 | Image4,Image5,Image6
</code>```

How can I modify my query to do this? I have:

```<code>SELECT H.HotelID, H.HotelName, '' AS Images
FROM Hotels H
</code>```

I know I can use COALESCE to create a comma-delimited list:

```<code>DECLARE @Images varchar(500)
SELECT @Images = COALESCE(@Images + ',', '') + CAST(Filename AS varchar(100)) FROM HotelImages WHERE HotelID = 1
SELECT @Images
</code>```

But I don't know how to integrate that into my current query so that the list can be returned with the rest of the hotel data.

I should mention I'm using SQL Server 2000.

答:
try this:</p>

```<code>SELECT H.HotelID, H.HotelName,
Images = (select COALESCE(HotelImageID + ',', '')
            FROM HotelImages
            WHERE HotelID = H.id)
FROM Hotels H
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Here are my tables:

-----------------------------------------
Hotels
-----------------------------------------
HotelID | HotelName
-----------------------------------------

-----------------------------------------
HotelImages
-----------------------------------------
HotelImageID | HotelID | Filename
-----------------------------------------

I'd like to create a SELECT statement that will return the data like so:

HotelID | HotelName | Images
-----------------------------------------
1 | Hotel1 | Image1,Image2,Image3
2 | Hotel2 | Image4,Image5,Image6

How can I modify my query to do this? I have:

SELECT H.HotelID, H.HotelName, '' AS Images
FROM Hotels H

I know I can use COALESCE to create a comma-delimited list:

DECLARE @Images varchar(500)
SELECT @Images = COALESCE(@Images + ',', '') + CAST(Filename AS varchar(100)) FROM HotelImages WHERE HotelID = 1
SELECT @Images

But I don't know how to integrate that into my current query so that the list can be returned with the rest of the hotel data.

I should mention I'm using SQL Server 2000.

Body:
try this:

SELECT H.HotelID, H.HotelName,
Images = (select COALESCE(HotelImageID + ',', '')
            FROM HotelImages
            WHERE HotelID = H.id)
FROM Hotels H


问:
Delegate unable to call in 2nd view controller
i want to pass image on click of a button in 1st view controller to the 2nd controller. I am unable to understand that even i have given the reference of my 1 view controller to my 2nd controller then also the delegate is not called

1.Heres my code for 1st view controller

```<code>protocol ViewControllerDelegate: class{
func Imagine(get: UIImage?)
}
class ViewController: UIViewController  {
let button = UIButton()
weak var delegate:ViewControllerDelegate?
var image = UIImage(named:"face1.png")
override func viewDidLoad() {
    super.viewDidLoad()
    addButton()
    addConstraints()

    // Do any additional setup after loading the view, typically from a nib.
}

func addButton() -> Void {
     button.setImage(UIImage(named:"face1.png"), for: .normal)
     button.layer.borderColor = UIColor.white.cgColor
     button.clipsToBounds = true
     button.showsTouchWhenHighlighted = true
     button.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)
     view.addSubview(button)
}
func buttonPressed() -> Void {
    pressed()
    let alert = UIAlertController(title: "Alert", message: "Image  sent to Tab 3", preferredStyle: UIAlertControllerStyle.alert)
    let ok = UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: nil)
    alert.addAction(ok)
    self.present(alert, animated: true, completion:nil)

}

func addConstraints() -> Void {
    button.snp.makeConstraints { (make) in
        make.width.height.equalTo(150)
        make.center.equalToSuperview()
       }

}

func pressed(){
    delegate?.Imagine(get: UIImage(named:"face1.png"))
}

}
</code>```

2.Here is the code for 2nd view controller

```<code>class ViewController3: UIViewController, ViewControllerDelegate{
var imageView=UIImageView()
var obj:ViewController?
override func viewDidLoad() {
    super.viewDidLoad()
     view.backgroundColor = UIColor.white
    // getImage = UIImage(named: "face3.png")
     addView()
     addConstraints()
    **obj.delegate = self**
}

func addView() -> Void{

    view.addSubview(imageView)
}

func addConstraints() -> Void {
    imageView.snp.makeConstraints { (make) in
        make.width.height.equalTo(150)
        make.center.equalToSuperview()
                                  }
    }
//NOT Called
    func Imagine(get: UIImage?) {
    imageView.image = get
}
}
</code>```

3.And here is my tab bar Controller

```<code>class ViewController4: UITabBarController ,UITabBarControllerDelegate {
var v:ViewController?
override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = UIColor.white
    self.delegate = self
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(true)

    let tab1 = ViewController()
    let tab1BarItem = UITabBarItem(title: "Tab1", image:UIImage(named:"bell-off-7.png"), selectedImage:UIImage(named:"bell-7.png") )
    tab1.tabBarItem = tab1BarItem

    let tab2 = ViewController2()
    let tab2BarItem = UITabBarItem(title: "Tab2", image: UIImage(named:"bell-off-7.png"), selectedImage: UIImage(named:"bell-7.png"))
    tab2.tabBarItem = tab2BarItem

    let tab3 = ViewController3()

    let tab3BarItem = UITabBarItem(title: "Tab3", image:     UIImage(named:"bell-off-7.png"), selectedImage: UIImage(named:"bell-7.png"))
    tab3.tabBarItem = tab3BarItem
    self.viewControllers = [tab1,tab2,tab3]
}

}
</code>```

答:
You have to set the image when you are switching the tab.
Currently, what you are doing is you are changing the image of a viewController which is not yet shown.

You can add tag to each item and make use of didSelectViewController delegate function

In tabBar ViewController add a variable tappedImage like

```<code>var tappedImage:UIImage?
override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(true)

    let tab1 = ViewController()
    let tab1BarItem = UITabBarItem(title: "Tab1", image:UIImage(named:"bell-off-7.png"), selectedImage:UIImage(named:"bell-7.png") )
    tab1BarItem.tag = 0
    tab1.tabBarItem = tab1BarItem

    let tab2 = ViewController2()
    let tab2BarItem = UITabBarItem(title: "Tab2", image: UIImage(named:"bell-off-7.png"), selectedImage: UIImage(named:"bell-7.png"))
    tab2BarItem.tag = 1
    tab2.tabBarItem = tab2BarItem

    let tab3 = ViewController3()

    let tab3BarItem = UITabBarItem(title: "Tab3", image:     UIImage(named:"bell-off-7.png"), selectedImage: UIImage(named:"bell-7.png"))
    tab3BarItem.tag = 2
    tab3.tabBarItem = tab3BarItem
    self.viewControllers = [tab1,tab2,tab3]
}

    func Imagine(get: UIImage?) {
        tappedImage = get
    }

        func tabBarController(tabBarController: UITabBarController, didSelectViewController viewController: UIViewController) {
            if let secondVC = viewController as? ViewController2 {
              secondVC.selectedImage = tappedImage
           }
        }
</code>```

In ViewController2's viewWillAppear set the tappedImage as the imageView's image

Body:
i want to pass image on click of a button in 1st view controller to the 2nd controller. I am unable to understand that even i have given the reference of my 1 view controller to my 2nd controller then also the delegate is not called

1.Heres my code for 1st view controller

protocol ViewControllerDelegate: class{
func Imagine(get: UIImage?)
}
class ViewController: UIViewController  {
let button = UIButton()
weak var delegate:ViewControllerDelegate?
var image = UIImage(named:"face1.png")
override func viewDidLoad() {
    super.viewDidLoad()
    addButton()
    addConstraints()

    // Do any additional setup after loading the view, typically from a nib.
}

func addButton() -> Void {
     button.setImage(UIImage(named:"face1.png"), for: .normal)
     button.layer.borderColor = UIColor.white.cgColor
     button.clipsToBounds = true
     button.showsTouchWhenHighlighted = true
     button.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)
     view.addSubview(button)
}
func buttonPressed() -> Void {
    pressed()
    let alert = UIAlertController(title: "Alert", message: "Image  sent to Tab 3", preferredStyle: UIAlertControllerStyle.alert)
    let ok = UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: nil)
    alert.addAction(ok)
    self.present(alert, animated: true, completion:nil)

}

func addConstraints() -> Void {
    button.snp.makeConstraints { (make) in
        make.width.height.equalTo(150)
        make.center.equalToSuperview()
       }

}

func pressed(){
    delegate?.Imagine(get: UIImage(named:"face1.png"))
}

}

2.Here is the code for 2nd view controller

class ViewController3: UIViewController, ViewControllerDelegate{
var imageView=UIImageView()
var obj:ViewController?
override func viewDidLoad() {
    super.viewDidLoad()
     view.backgroundColor = UIColor.white
    // getImage = UIImage(named: "face3.png")
     addView()
     addConstraints()
    **obj.delegate = self**
}

func addView() -> Void{

    view.addSubview(imageView)
}

func addConstraints() -> Void {
    imageView.snp.makeConstraints { (make) in
        make.width.height.equalTo(150)
        make.center.equalToSuperview()
                                  }
    }
//NOT Called
    func Imagine(get: UIImage?) {
    imageView.image = get
}
}

3.And here is my tab bar Controller

class ViewController4: UITabBarController ,UITabBarControllerDelegate {
var v:ViewController?
override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = UIColor.white
    self.delegate = self
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(true)

    let tab1 = ViewController()
    let tab1BarItem = UITabBarItem(title: "Tab1", image:UIImage(named:"bell-off-7.png"), selectedImage:UIImage(named:"bell-7.png") )
    tab1.tabBarItem = tab1BarItem

    let tab2 = ViewController2()
    let tab2BarItem = UITabBarItem(title: "Tab2", image: UIImage(named:"bell-off-7.png"), selectedImage: UIImage(named:"bell-7.png"))
    tab2.tabBarItem = tab2BarItem

    let tab3 = ViewController3()

    let tab3BarItem = UITabBarItem(title: "Tab3", image:     UIImage(named:"bell-off-7.png"), selectedImage: UIImage(named:"bell-7.png"))
    tab3.tabBarItem = tab3BarItem
    self.viewControllers = [tab1,tab2,tab3]
}

}

Body:
You have to set the image when you are switching the tab.
Currently, what you are doing is you are changing the image of a viewController which is not yet shown.

You can add tag to each item and make use of didSelectViewController delegate function

In tabBar ViewController add a variable tappedImage like

var tappedImage:UIImage?
override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(true)

    let tab1 = ViewController()
    let tab1BarItem = UITabBarItem(title: "Tab1", image:UIImage(named:"bell-off-7.png"), selectedImage:UIImage(named:"bell-7.png") )
    tab1BarItem.tag = 0
    tab1.tabBarItem = tab1BarItem

    let tab2 = ViewController2()
    let tab2BarItem = UITabBarItem(title: "Tab2", image: UIImage(named:"bell-off-7.png"), selectedImage: UIImage(named:"bell-7.png"))
    tab2BarItem.tag = 1
    tab2.tabBarItem = tab2BarItem

    let tab3 = ViewController3()

    let tab3BarItem = UITabBarItem(title: "Tab3", image:     UIImage(named:"bell-off-7.png"), selectedImage: UIImage(named:"bell-7.png"))
    tab3BarItem.tag = 2
    tab3.tabBarItem = tab3BarItem
    self.viewControllers = [tab1,tab2,tab3]
}

    func Imagine(get: UIImage?) {
        tappedImage = get
    }

        func tabBarController(tabBarController: UITabBarController, didSelectViewController viewController: UIViewController) {
            if let secondVC = viewController as? ViewController2 {
              secondVC.selectedImage = tappedImage
           }
        }

In ViewController2's viewWillAppear set the tappedImage as the imageView's image


问:
how do I change the order of rows in GrapheneDB node?
my nodes have the following order in GrapheneDB neo4J hosted database:

```<code><id>:3 human_date:Wednesday, July 5, 2017type:painuuid:7c74a49d-f102-4825-914b-87dcc88d339bvalue:Emptinessepoch_utc_i:1499285499
</code>```

The input of the JSON object is I first create the node with the value, and then set properties: {uuid, epoch_utc, human_time}

It's hard to use the graphical UI to see different nodes because only human_time is displayed...and that is often the same for multiple nodes.  I would prefer to see type or value

答:
You can change the properties that were picked by Neo4j Browser to be displayed as captions.

Just click at the top of the window on a Label tag, and once selected, change the caption at the bottom to type or value.

For more advanced styling, like displaying multiple captions, you can edit the Graph Style Sheet (.grass file). Just enter :style in Neo4j Browser, click on the download icon, edit and upload the file back and the changes will be reflected.

You can read more on Neo4j Browser styling here.

Body:
my nodes have the following order in GrapheneDB neo4J hosted database:

<id>:3 human_date:Wednesday, July 5, 2017type:painuuid:7c74a49d-f102-4825-914b-87dcc88d339bvalue:Emptinessepoch_utc_i:1499285499

The input of the JSON object is I first create the node with the value, and then set properties: {uuid, epoch_utc, human_time}

It's hard to use the graphical UI to see different nodes because only human_time is displayed...and that is often the same for multiple nodes.  I would prefer to see type or value


问:
Excel vba variable not defined when using range variable
I have function testFunc that takes Range as an argument, loops thorugh its cells and edits them. I have sub testSub that tests two cases: first is when I pass the current workbook's range to testFunc through: 1. variable Range 2. just as an argument testFunct(...Range("A1:A16")).

The second case is when I open another workbook and do the same - pass one of its worksheets range to the testFunc directly or via variable.

```<code>Function testFunc(aCol As Range)
    Dim i As Integer
    i = 0
    For Each cell In aCol
        MsgBox (cell.Value)
        cell.Value = i
        i = i + 1
    Next

    testFunc = i
End Function

Sub testSub()
    Dim origWorkbook As Workbook
    Set origWorkbook = ActiveWorkbook

    Dim aRange As Range
    Set aRange = ThisWorkbook.Sheets("sheet 1").Range("A1:A16")

    Dim dataWorkbook As Workbook
    Set dataWorkbook = Application.Workbooks.Open("Y:\vba\test_reserves\test_data\0503317-3_FO_001-2582480.XLS")
    Dim incomesNamesRange As Range
    Set incomesNamesRange = dataWorkbook.Worksheets("sheet 1").Range("A1:A20")
   ' origWorkbook.Worksheets("sheet 1").Cells(1, 5) = testFunc(dataWorkbook.Sheets("1").Range("A1:A20"))

     origWorkbook.Worksheets("Ëèñò2").Cells(1, 50) = testFunc(incomesNamesRange)

  '  testFunc aRange
  'origWorkbook.Worksheets("sheet 1").Cells(1, 5) = testFunc(aRange) '<---good
 ' origWorkbook.Worksheets("sheet 1").Cells(1, 5) = testFunc(ThisWorkbook.Sheets("sheet 1").Range("A1:A16"))
End Sub
</code>```

The problem is, as I indicated with comments, when I open a foreign workbook and pass its range through a variable it gives an error variable not definedFor Each cell In aCol`, while all other cases (including passing range variable of the current workbook) work fine.

I need testFunc to stay a Function, because it's a simplfied example of some code from bigger program which needs to take a returned value from a function. And I need to store that Range in a variable too, to minimize time of the execution.

EDIT: As pointed out in the comments, I replaced Cells(1,5) with origWorkbook.Worksheet("shee t1").Cells(1,5) and fixed variable name, but the original mistake changed to variable not defined. I edited the title and body of the question.

答:
The default name for the worksheet shouldn't have a space in it.

```<code>Set incomesNamesRange = dataWorkbook.Worksheets("sheet 1").Range("A1:A20")
</code>```

Change this to:

```<code>    Set incomesNamesRange = dataWorkbook.Worksheets("Sheet1").Range("A1:A20")
</code>```

And see if that fixes it.

Body:
I have function testFunc that takes Range as an argument, loops thorugh its cells and edits them. I have sub testSub that tests two cases: first is when I pass the current workbook's range to testFunc through: 1. variable Range 2. just as an argument testFunct(...Range("A1:A16")).

The second case is when I open another workbook and do the same - pass one of its worksheets range to the testFunc directly or via variable.

Function testFunc(aCol As Range)
    Dim i As Integer
    i = 0
    For Each cell In aCol
        MsgBox (cell.Value)
        cell.Value = i
        i = i + 1
    Next

    testFunc = i
End Function

Sub testSub()
    Dim origWorkbook As Workbook
    Set origWorkbook = ActiveWorkbook

    Dim aRange As Range
    Set aRange = ThisWorkbook.Sheets("sheet 1").Range("A1:A16")

    Dim dataWorkbook As Workbook
    Set dataWorkbook = Application.Workbooks.Open("Y:\vba\test_reserves\test_data\0503317-3_FO_001-2582480.XLS")
    Dim incomesNamesRange As Range
    Set incomesNamesRange = dataWorkbook.Worksheets("sheet 1").Range("A1:A20")
   ' origWorkbook.Worksheets("sheet 1").Cells(1, 5) = testFunc(dataWorkbook.Sheets("1").Range("A1:A20"))

     origWorkbook.Worksheets("Ëèñò2").Cells(1, 50) = testFunc(incomesNamesRange)

  '  testFunc aRange
  'origWorkbook.Worksheets("sheet 1").Cells(1, 5) = testFunc(aRange) '<---good
 ' origWorkbook.Worksheets("sheet 1").Cells(1, 5) = testFunc(ThisWorkbook.Sheets("sheet 1").Range("A1:A16"))
End Sub

The problem is, as I indicated with comments, when I open a foreign workbook and pass its range through a variable it gives an error variable not definedFor Each cell In aCol`, while all other cases (including passing range variable of the current workbook) work fine.

I need testFunc to stay a Function, because it's a simplfied example of some code from bigger program which needs to take a returned value from a function. And I need to store that Range in a variable too, to minimize time of the execution.

EDIT: As pointed out in the comments, I replaced Cells(1,5) with origWorkbook.Worksheet("shee t1").Cells(1,5) and fixed variable name, but the original mistake changed to variable not defined. I edited the title and body of the question.

Body:
The default name for the worksheet shouldn't have a space in it.

Set incomesNamesRange = dataWorkbook.Worksheets("sheet 1").Range("A1:A20")

Change this to:

    Set incomesNamesRange = dataWorkbook.Worksheets("Sheet1").Range("A1:A20")

And see if that fixes it.


问:
phpMyAdmin mbstring error
Whenever I try to enter my phpMyAdmin, it gives me this error:

```<code>The mbstring extension is missing. Please check your PHP configuration.
</code>```

I've looked all over the Internet for a fix, but all I've found is errors similar to mine, but not the same, or the exact same but there was no fix given.

I am also using Windows.

答:
install mbstring and restart your apache:

```<code>sudo apt-get install php-mbstring
sudo service apache restart
</code>```

then remove ; from your php.ini file:

```<code>;extension=php_mbstring.dll
</code>```

to

```<code>extension=php_mbstring.dll
</code>```

If it still doesn't work..remove your php setup, without removing the databases from your phpmyadmin. Reinstall it.

NB: * if you want to remove all, all mention the one you need to.

```<code>sudo apt-get remove php*
</code>```

Then install the php and modules of the php version that you need. here, php 7.1:

```<code>sudo apt-get install php7.1 php7.1-cli php7.1-common libapache2-mod-php7.1 php7.1-mysql php7.1-fpm php7.1-curl php7.1-gd php7.1-bz2 php7.1-mcrypt php7.1-json php7.1-tidy php7.1-mbstring php-redis php-memcached
</code>```

restart your apache and check the php version.

```<code>sudo service apache restart
php -v
</code>```

when all this is done, execute the following command to enable mbstring forcefully and restart your apache.

```<code>sudo phpenmod mbstring
sudo service apache restart
</code>```

Hope it helps.
It did to me :)

Title: phpMyAdmin mbstring error

Body:
Whenever I try to enter my phpMyAdmin, it gives me this error:

The mbstring extension is missing. Please check your PHP configuration.

I've looked all over the Internet for a fix, but all I've found is errors similar to mine, but not the same, or the exact same but there was no fix given.

I am also using Windows.

Body:
install mbstring and restart your apache:

sudo apt-get install php-mbstring
sudo service apache restart

then remove ; from your php.ini file:

;extension=php_mbstring.dll

to

extension=php_mbstring.dll

If it still doesn't work..remove your php setup, without removing the databases from your phpmyadmin. Reinstall it.

NB: * if you want to remove all, all mention the one you need to.

sudo apt-get remove php*

Then install the php and modules of the php version that you need. here, php 7.1:

sudo apt-get install php7.1 php7.1-cli php7.1-common libapache2-mod-php7.1 php7.1-mysql php7.1-fpm php7.1-curl php7.1-gd php7.1-bz2 php7.1-mcrypt php7.1-json php7.1-tidy php7.1-mbstring php-redis php-memcached

restart your apache and check the php version.

sudo service apache restart
php -v

when all this is done, execute the following command to enable mbstring forcefully and restart your apache.

sudo phpenmod mbstring
sudo service apache restart

Hope it helps.
It did to me :)


问:
Xpath deepest node whose string content is longer than a given length
How does one use XPath to find the deepest node that matches a string content length constraint.

Given a chunk of XHTML (or XML) that looks like this:

```<code><html>
    <body>
        <div id="page">
             <div id="desc">
                  This wool sweater has the following features:
                  <ul>
                       <li>4 buttons</li>
                       <li>Merino Wool</li>
                  </ul>
             </div>
        </div>
        ...
     </body>
</html>
</code>```

An an XPath expression like

```<code>//*[string-length() > 50]
</code>```

Would match the , ,
 and
.  How can one make XPath pick the deepest matching node (ie: <div id="desc">)?

Bonus points, how does one apply the constraint to space normalized content length?

答:
As Dimitre have pointed out, the problem for solving this in XPath 1.0 is that maximum expression works only for not calculated values:

```<code>$node-set[not($node-set/node-or-attribute > node-or-attribute)]
</code>```

That's why in XSLT 1.0 you would use the "standar" maximum construction:

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/">
        <xsl:for-each select="//*[string-length(normalize-space())>50]">
            <xsl:sort select="count(ancestor::*)"
                      data-type="number" order="descending"/>
            <xsl:if test="position()=1">
                <xsl:copy-of select="."/>
            </xsl:if>
        </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>
</code>```

Output:

```<code><div id="desc">                   This wool sweater has the following features:
                <ul>
<li>4 buttons</li>
<li>Merino Wool</li>
</ul>
</div>
</code>```

Body:
How does one use XPath to find the deepest node that matches a string content length constraint.

Given a chunk of XHTML (or XML) that looks like this:

                  This wool sweater has the following features:

4 buttons

Merino Wool

        ...

An an XPath expression like

//*[string-length() > 50]

Would match the , ,
 and
.  How can one make XPath pick the deepest matching node (ie: <div id="desc">)?

Bonus points, how does one apply the constraint to space normalized content length?

Body:
As Dimitre have pointed out, the problem for solving this in XPath 1.0 is that maximum expression works only for not calculated values:

$node-set[not($node-set/node-or-attribute > node-or-attribute)]

That's why in XSLT 1.0 you would use the "standar" maximum construction:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/">
        <xsl:for-each select="//*[string-length(normalize-space())>50]">
            <xsl:sort select="count(ancestor::*)"
                      data-type="number" order="descending"/>
            <xsl:if test="position()=1">
                <xsl:copy-of select="."/>
            </xsl:if>
        </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>

Output:

<div id="desc">                   This wool sweater has the following features:
                <ul>
<li>4 buttons</li>
<li>Merino Wool</li>
</ul>
</div>


问:
Viewing changes to deleted files in git
Let's say that when I branch off from master, there's a file colors.txt on the master branch of my repo with these contents:

```<code>red
green
blue
yellow
</code>```

I then branch off into my-branch, in which I make the following changes:

Delete colors.txt

Add red.txt with these contents:

```<code>red
</code>```

Add green.txt with these contents:

```<code>green
</code>```

Add blue.txt with these contents:

```<code>blue
</code>```

Add yellow.txt with these contents:

```<code>yellow
</code>```

Now, there have been some changes on master that I need, so I want to merge. However, someone has also changed colors.txt to:

```<code>red
green
blue
yellow
orange
purple
</code>```

During my merge, the only information I get is that I deleted the file colors.txt, so how can I see the changes that have been to the file on master so I can appropriately resolve the conflict (in this case, by adding the files orange.txt and purple.txt)?

答:
Okay, I tested the following:

Checkout a new branch color-test

Add orange/purple to existing colors.txt and commit

Switch back to "master"

Delete colors.txt

Try merge, which fails

For me, git diff colors-test.. -- colors.txt gives the following output:

```<code>-red
-green
-blue
-yellow
-orange
-purple
</code>```

where color-test is the branch where I added orange/purple and ..(nothing) indicates the HEAD. This might be okay when the file is that small, however, a full diff might be better.

To find out, in which commit you deleted the file, you can try something like

```<code>git log --name-status -- colors.txt
</code>```

and you'll find a commit with D       colors.txt which is the commit in which you deleted the file, in my case the short hash is e1bb165. You might want to diff against the commit before that

```<code>git diff colors-test..e1bb165~1 -- colors.txt
</code>```

which gives me

```<code>green
blue
yellow
-orange
-purple
</code>```

When you pass the -R switch to git diff, you will get + instead of - (the inputs are reversed).

Hope that helps.

Title: Viewing changes to deleted files in git

Body:
Let's say that when I branch off from master, there's a file colors.txt on the master branch of my repo with these contents:

red
green
blue
yellow

I then branch off into my-branch, in which I make the following changes:

Delete colors.txt

Add red.txt with these contents:

red

Add green.txt with these contents:

green

Add blue.txt with these contents:

blue

Add yellow.txt with these contents:

yellow

Now, there have been some changes on master that I need, so I want to merge. However, someone has also changed colors.txt to:

red
green
blue
yellow
orange
purple

During my merge, the only information I get is that I deleted the file colors.txt, so how can I see the changes that have been to the file on master so I can appropriately resolve the conflict (in this case, by adding the files orange.txt and purple.txt)?

Body:
Okay, I tested the following:

Checkout a new branch color-test

Add orange/purple to existing colors.txt and commit

Switch back to "master"

Delete colors.txt

Try merge, which fails

For me, git diff colors-test.. -- colors.txt gives the following output:

-red
-green
-blue
-yellow
-orange
-purple

where color-test is the branch where I added orange/purple and ..(nothing) indicates the HEAD. This might be okay when the file is that small, however, a full diff might be better.

To find out, in which commit you deleted the file, you can try something like

git log --name-status -- colors.txt

and you'll find a commit with D       colors.txt which is the commit in which you deleted the file, in my case the short hash is e1bb165. You might want to diff against the commit before that

git diff colors-test..e1bb165~1 -- colors.txt

which gives me

green
blue
yellow
-orange
-purple

When you pass the -R switch to git diff, you will get + instead of - (the inputs are reversed).

Hope that helps.