问:
Remove last character from dictionary<string, dictionary<string, string>> using C#
I have

```<code>Dictionary<string, Dictionary<string, string>>
</code>```

My inner dictionary has the following data

```<code>{
  "1": {
    "message-Code1": "   0",
    "msg-Number-Pos11": "0",
    "msg-Number-Pos21": "0",
    "msg-Number-Pos31": " "
  },
  "2": {
    "message-Code2": "   0",
    "msg-Number-Pos12": "0",
    "msg-Number-Pos22": "0",
    "msg-Number-Pos32": " "
  }
</code>```

But I want a out like below

```<code>{
  "1": {
    "message-Code": "   0",
    "msg-Number-Pos1": "0",
    "msg-Number-Pos2": "0",
    "msg-Number-Pos3": " "
  },
  "2": {
    "message-Code": "   0",
    "msg-Number-Pos1": "0",
    "msg-Number-Pos2": "0",
    "msg-Number-Pos3": " "
  }
</code>```

Last character of the all the Key's is removed i.e 1 in the first set and 2 in the second set of result.

I was trying with below code

```<code>var result = dictionary.Where(pair => pair.Value.Remove(pair.Value.Key.Last()));
</code>```

This is throwing an error.
Can anyone help me in bringing the output that I need.

答:
Basically you should create new "inner" dictionaries. That's easy to do though:

```<code>var replacedOuter = outerDictionary.ToDictionary(
   outerKey => outerKey, // Outer key stays the same
   outerValue => outerValue.ToDictionary(
       innerKey => innerKey.Substring(0, innerKey.Length - 1),
       innerValue => innerValue));
</code>```

Note that if this creates any duplicate keys (i.e. if there were any keys that only differed by final character) an exception will be thrown by the inner ToDictionary call.

Body:
I have

Dictionary<string, Dictionary<string, string>>

My inner dictionary has the following data

{
  "1": {
    "message-Code1": "   0",
    "msg-Number-Pos11": "0",
    "msg-Number-Pos21": "0",
    "msg-Number-Pos31": " "
  },
  "2": {
    "message-Code2": "   0",
    "msg-Number-Pos12": "0",
    "msg-Number-Pos22": "0",
    "msg-Number-Pos32": " "
  }

But I want a out like below

{
  "1": {
    "message-Code": "   0",
    "msg-Number-Pos1": "0",
    "msg-Number-Pos2": "0",
    "msg-Number-Pos3": " "
  },
  "2": {
    "message-Code": "   0",
    "msg-Number-Pos1": "0",
    "msg-Number-Pos2": "0",
    "msg-Number-Pos3": " "
  }

Last character of the all the Key's is removed i.e 1 in the first set and 2 in the second set of result.

I was trying with below code

var result = dictionary.Where(pair => pair.Value.Remove(pair.Value.Key.Last()));

This is throwing an error.
Can anyone help me in bringing the output that I need.

Body:
Basically you should create new "inner" dictionaries. That's easy to do though:

var replacedOuter = outerDictionary.ToDictionary(
   outerKey => outerKey, // Outer key stays the same
   outerValue => outerValue.ToDictionary(
       innerKey => innerKey.Substring(0, innerKey.Length - 1),
       innerValue => innerValue));

Note that if this creates any duplicate keys (i.e. if there were any keys that only differed by final character) an exception will be thrown by the inner ToDictionary call.


来源: stackexchange

问:
Javascript - unable to understand function parentheses
I am confused how the way functions are called. Sometimes they are given in functionName() format and sometimes just the name, functionName.

For example in HTML, when we call onclick="functionName()" but in Javascript we just pass function functionName as argument to another function.
setTimeout(functionName, 1000);

Here's an example from a book, suppose we have to pass a callback function with arguments.

```<code>var mySetTimeout = function(callback, delay){
  var dollars = 100;
  callback(dollars);
};
var onCompletion = function(dollars,name){
  console.log(name + ": Here's your $" + dollars);
};
var getMoney = function (name) {
  var requestB = mySetTimeout(function(dollars){
    onCompletion(dollars,name);
  }, 1000);
};
getMoney('Simon');
</code>```

Here in mySetTimeout function we are passing callback as an argument but with nothing in it. But later on in mySetTimeout function we are passing callback function with argument.

Can anyone explain me the all the cases? Thanks!

答:
The mySetimeout function can be used in 2 ways:

Syntax:

```<code>var timeoutID = window.setTimeout(func, delay, [param1, param2, ...]);
</code>```

or

```<code>var timeoutID = window.setTimeout(code, delay);
</code>```

Hope this helps :)

ContentLicense: CC BY-SA 3.0

Body:
I am confused how the way functions are called. Sometimes they are given in functionName() format and sometimes just the name, functionName.

For example in HTML, when we call onclick="functionName()" but in Javascript we just pass function functionName as argument to another function.
setTimeout(functionName, 1000);

Here's an example from a book, suppose we have to pass a callback function with arguments.

var mySetTimeout = function(callback, delay){
  var dollars = 100;
  callback(dollars);
};
var onCompletion = function(dollars,name){
  console.log(name + ": Here's your $" + dollars);
};
var getMoney = function (name) {
  var requestB = mySetTimeout(function(dollars){
    onCompletion(dollars,name);
  }, 1000);
};
getMoney('Simon');

Here in mySetTimeout function we are passing callback as an argument but with nothing in it. But later on in mySetTimeout function we are passing callback function with argument.

Can anyone explain me the all the cases? Thanks!

Body:
The mySetimeout function can be used in 2 ways:

Syntax:

var timeoutID = window.setTimeout(func, delay, [param1, param2, ...]);

or

var timeoutID = window.setTimeout(code, delay);

Hope this helps :)


问:
How can I set password in aws EC2 instead of ppk file?
I have created a account in aws ec2 and logged in through converted ppk file with putty. Now I would like to login via password.

Here how can I set password?

Can any one provide step by step process.

Thanks in advance.

Please help!!

答:
Are you talking about logging into an instance via a SSH password?

If so, know that EC2 instances only allow key-based SSH authentication by default.

In-order to do ssh password authentication, edit the configuration file(as for Debian linux),

/etc/ssh/sshd_config

Edit following to change it to yes,

```<code>PasswordAuthentication yes
</code>```

Restart ssh service,

```<code>sudo service ssh restart
</code>```

Then try SSH into instance,

```<code>ssh <username>@<IP address or public DNS>
</code>```

Body:
Are you talking about logging into an instance via a SSH password?

If so, know that EC2 instances only allow key-based SSH authentication by default.

In-order to do ssh password authentication, edit the configuration file(as for Debian linux),

/etc/ssh/sshd_config

Edit following to change it to yes,

PasswordAuthentication yes

Restart ssh service,

sudo service ssh restart

Then try SSH into instance,

ssh <username>@<IP address or public DNS>


问:
How to check the Emoji property of a character in Python?
In unicode a character can have an Emoji property.

Is there a standard way in Python to determine if a character is an Emoji?

I know of unicodedata, but it doesn't appear to expose all these extra character details.

Note: I'm asking about the specific attribute called "Emoji" in the unicdoe standard, as provided in the link. I don't want to have an arbitrary list of pattern ranges, and preferably use a standard library.

答:
This is the code I ended up creating to load the Emoji information. The get_emoji function gets the data file, parses it, and calls the enumeraton callback.  The rest of the code uses this to produce a JSON file of the information I needed.

```<code>#!/usr/bin/env python3
# Generates a list of emoji characters and names in JS format
import urllib.request
import unicodedata
import re, json

'''
Enumerates the Emoji characters that match an attributes from the Unicode standard (the Emoji list).

@param on_emoji A callback that is called with each found character. Signature `on_emoji( code_point_value )`
@param attribute  The attribute that  is desired, such as `Emoji` or `Emoji_Presentation`
'''
def get_emoji(on_emoji, attribute):
    with urllib.request.urlopen('http://www.unicode.org/Public/emoji/5.0/emoji-data.txt') as f:
        content = f.read().decode(f.headers.get_content_charset())

        cldr = re.compile('^([0-9A-F]+)(..([0-9A-F]+))?([^;]*);([^#]*)#(.*)$')
        for line in content.splitlines():
            m = cldr.match(line)
            if m == None:
                continue

            line_attribute = m.group(5).strip()
            if line_attribute != attribute:
                continue

            code_point = int(m.group(1),16)
            if m.group(3) == None:
                on_emoji(code_point)
            else:
                to_code_point = int(m.group(3),16)
                for i in range(code_point,to_code_point+1):
                    on_emoji(i)

# Dumps the values into a JSON format
def print_emoji(value):
    c = chr(value)
    try:
        obj = {
            'code': value,
            'name': unicodedata.name(c).lower(),
        }
        print(json.dumps(obj),',')
    except:
        # Unicode DB is likely outdated in installed Python
        pass

print( "module.exports = [" )
get_emoji(print_emoji, "Emoji_Presentation")
print( "]" )
</code>```

That solved my original problem. To answer the question itself it'd just be a matter of sticking the results into a dictionary and doing a lookup.

Body:
This is the code I ended up creating to load the Emoji information. The get_emoji function gets the data file, parses it, and calls the enumeraton callback.  The rest of the code uses this to produce a JSON file of the information I needed.

#!/usr/bin/env python3
# Generates a list of emoji characters and names in JS format
import urllib.request
import unicodedata
import re, json

'''
Enumerates the Emoji characters that match an attributes from the Unicode standard (the Emoji list).

@param on_emoji A callback that is called with each found character. Signature `on_emoji( code_point_value )`
@param attribute  The attribute that  is desired, such as `Emoji` or `Emoji_Presentation`
'''
def get_emoji(on_emoji, attribute):
    with urllib.request.urlopen('http://www.unicode.org/Public/emoji/5.0/emoji-data.txt') as f:
        content = f.read().decode(f.headers.get_content_charset())

        cldr = re.compile('^([0-9A-F]+)(..([0-9A-F]+))?([^;]*);([^#]*)#(.*)$')
        for line in content.splitlines():
            m = cldr.match(line)
            if m == None:
                continue

            line_attribute = m.group(5).strip()
            if line_attribute != attribute:
                continue

            code_point = int(m.group(1),16)
            if m.group(3) == None:
                on_emoji(code_point)
            else:
                to_code_point = int(m.group(3),16)
                for i in range(code_point,to_code_point+1):
                    on_emoji(i)

# Dumps the values into a JSON format
def print_emoji(value):
    c = chr(value)
    try:
        obj = {
            'code': value,
            'name': unicodedata.name(c).lower(),
        }
        print(json.dumps(obj),',')
    except:
        # Unicode DB is likely outdated in installed Python
        pass

print( "module.exports = [" )
get_emoji(print_emoji, "Emoji_Presentation")
print( "]" )

That solved my original problem. To answer the question itself it'd just be a matter of sticking the results into a dictionary and doing a lookup.


问:
Android, want to delete the image after selected from the gallery
I'm creating a program that can select image from gallery and after selected, the text next to the image will change to "Delete" for delete the image.
I have worked on select image from gallery, and now I don't know how to make the delete function. Can someone please help!
And here is my code. Where I should put the delete.</p>

```<code>addPhotoText.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            selectNewsFeedImage();
        }
    });

.....else if (items[item].equals("Choose from Gallery")) {
                Intent i = new Intent();
                i.setType("image/*");
                i.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(i, "Select File"), RESULT_LOAD_IMAGE);
            }

 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == Activity.RESULT_OK) {
        if (requestCode == RESULT_LOAD_IMAGE && data != null) {
            Bitmap bm = null;
            try {
                bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
            } catch (IOException e) {
                e.printStackTrace();
            }
            addPhotoIcon.setImageBitmap(bm);......
</code>```

答:
You need to get the path of the image that you have selected from the gallery first, next you need to delete that image from the sdcard using its path.

To get the path of the selected image refer this
Get filepath and filename of selected gallery image in Android

To delete the image using the path from sdcard
Android Delete Image from SD Card with OnClick

Body:
I'm creating a program that can select image from gallery and after selected, the text next to the image will change to "Delete" for delete the image.
I have worked on select image from gallery, and now I don't know how to make the delete function. Can someone please help!
And here is my code. Where I should put the delete.

addPhotoText.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            selectNewsFeedImage();
        }
    });

.....else if (items[item].equals("Choose from Gallery")) {
                Intent i = new Intent();
                i.setType("image/*");
                i.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(i, "Select File"), RESULT_LOAD_IMAGE);
            }

 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == Activity.RESULT_OK) {
        if (requestCode == RESULT_LOAD_IMAGE && data != null) {
            Bitmap bm = null;
            try {
                bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
            } catch (IOException e) {
                e.printStackTrace();
            }
            addPhotoIcon.setImageBitmap(bm);......


问:
How does one test item membership in an unordered sequence (C++)?
I've used python for a long time, and I'm just beginning to use C++

In python, if one has a set or a dictionary it is relatively easy to get a boolean value indicating whether or not a particular item is in that sequence using the in keyword.
i.e.

```<code>a = set(2,4,3)
if 4 in a
print "yes, 4 is in a, thank you for asking!"
</code>```

it's much more efficient than doing this:

```<code>a = [2,3,4]
for number in a
>if number == 4
>>return "yes, 4 is in a, thank you for asking!"
</code>```

is there a way to do make a membership test simple and efficient in cpp or do you always have to iterate through some ordered sequence?

答:
Python's method is not "much more efficient" because you don't know the complexity of in construct.

In C++ there are many methods of storing data. Binary trees are best for searching.

If you work with numbers like 2,3,4 etc, you may consider having an array of bools, and simply see if array[4] == true

ContentLicense: CC BY-SA 2.5

Body:
I've used python for a long time, and I'm just beginning to use C++

In python, if one has a set or a dictionary it is relatively easy to get a boolean value indicating whether or not a particular item is in that sequence using the in keyword.
i.e.

a = set(2,4,3)
if 4 in a
print "yes, 4 is in a, thank you for asking!"

it's much more efficient than doing this:

a = [2,3,4]
for number in a
>if number == 4
>>return "yes, 4 is in a, thank you for asking!"

is there a way to do make a membership test simple and efficient in cpp or do you always have to iterate through some ordered sequence?


问:
How to change the Fontsize for text in tabs in TabbedPage
I am working on Xamarin forms, it seems I need to adjust the FontSize for text in each tabs when I have to include a number of tabs for TabbedPage.

Problem: How to adjust the fontsize for the Tabs?

I tried to use the properties of the tab, but there is none.

```<code>public Product()
{
    InitializeComponent();

    this.title = ??
}

<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
            xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
            xmlns:local ="clr-namespace:MyApp.View"
            BackgroundColor="White"
            Title="Product and Service"
            x:Class="MayApp.View.MainMenu">
    <ContentPage.ToolbarItems>
        <ToolbarItem Name="MenuItem1" Order="Primary" Icon="itemIcon1" Command="{Binding Item1Command}"  Priority="0" />
        <ToolbarItem Name="MenuItem2" Order="Primary" Icon="itemIcon2" Priority="1" />
    </ContentPage.ToolbarItems>

    <local:Product>
    </local:Product>

    <local:Service>
    </local:Service>

</TabbedPage>
</code>```

答:
To change this for iOS you will need a custom renderer with code that iterates over the TabBar items and changes their font size using UITextAttributes. There is no way to do it in Xamarin.Forms itself.

```<code>if (TabBar.Items != null)
{
    foreach (var t in TabBar.Items)
    {
        var fontSize = new UITextAttributes() { Font =   UIFont.SystemFontOfSize(15) };
        t.SetTitleTextAttributes(fontSize, UIControlState.Normal);
    }
}
</code>```

Body:
I am working on Xamarin forms, it seems I need to adjust the FontSize for text in each tabs when I have to include a number of tabs for TabbedPage.

Problem: How to adjust the fontsize for the Tabs?

I tried to use the properties of the tab, but there is none.

public Product()
{
    InitializeComponent();

    this.title = ??
}

<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
            xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
            xmlns:local ="clr-namespace:MyApp.View"
            BackgroundColor="White"
            Title="Product and Service"
            x:Class="MayApp.View.MainMenu">
    <ContentPage.ToolbarItems>
        <ToolbarItem Name="MenuItem1" Order="Primary" Icon="itemIcon1" Command="{Binding Item1Command}"  Priority="0" />
        <ToolbarItem Name="MenuItem2" Order="Primary" Icon="itemIcon2" Priority="1" />
    </ContentPage.ToolbarItems>

    <local:Product>
    </local:Product>

    <local:Service>
    </local:Service>

</TabbedPage>

Body:
To change this for iOS you will need a custom renderer with code that iterates over the TabBar items and changes their font size using UITextAttributes. There is no way to do it in Xamarin.Forms itself.

if (TabBar.Items != null)
{
    foreach (var t in TabBar.Items)
    {
        var fontSize = new UITextAttributes() { Font =   UIFont.SystemFontOfSize(15) };
        t.SetTitleTextAttributes(fontSize, UIControlState.Normal);
    }
}


问:
In IE11 Symbol.Iterator is giving error when i am using for each on array of elements?
I am trying to loop an array of buttons and creating react component button at runtime, the error is reproducible only in IE 11 , I'm getting error in Symbol. Iterator which means that the array i am passing is non valid and internal iterator cannot be returned, but this works fine with any other browser, Is it a problem with IE or i am using jQuery selector to get the array of buttons.

```<code>export default function(buttons){

   for(let button of buttons){
       //Code for creating button as react component button.
   }
}

//call to replaceButtons

var btns = $('.continue-buttons');
replaceButtons(btns);
</code>```

Getting error with
SYMBOL.ITERATOR

I know this is not optimized way to write react code but requirement and design is quite a challenge.

答:
jQuery does not return an array, it returns a jQuery collection. <s>Which isn't iterable indeed.</s> It actually is since v1.12/v2.2.

However, Internet Explorer 11 just doesn't support iterators or for of loops at all.

Body:
I am trying to loop an array of buttons and creating react component button at runtime, the error is reproducible only in IE 11 , I'm getting error in Symbol. Iterator which means that the array i am passing is non valid and internal iterator cannot be returned, but this works fine with any other browser, Is it a problem with IE or i am using jQuery selector to get the array of buttons.

export default function(buttons){

   for(let button of buttons){
       //Code for creating button as react component button.
   }
}

//call to replaceButtons

var btns = $('.continue-buttons');
replaceButtons(btns);

Getting error with
SYMBOL.ITERATOR

I know this is not optimized way to write react code but requirement and design is quite a challenge.


问:
python 2 instead of python 3 as the (temporary) default python?
on my computer

```<code>~$ python -V
 Python 3.2.1
</code>```

but I get into problems when I run some python programs. my guess is (or at least I want to try this) that there is some backward compatibility issues, and I want to run those python scripts with

```<code> python2 2.7.2-2
</code>```

which is also installed on my system but I do not know how to make it as the (temporary) default python. The python script starts with

```<code> #!/usr/bin/env python
</code>```

and I am using arch linux.

答:
If you have some problems with virtualenv,

You can use it:

```<code>sudo ln -sf python2 /usr/bin/python
</code>```

and

```<code>sudo ln -sf python3 /usr/bin/python
</code>```

Body:
on my computer

~$ python -V
 Python 3.2.1

but I get into problems when I run some python programs. my guess is (or at least I want to try this) that there is some backward compatibility issues, and I want to run those python scripts with

 python2 2.7.2-2

which is also installed on my system but I do not know how to make it as the (temporary) default python. The python script starts with

 #!/usr/bin/env python

and I am using arch linux.

Body:
If you have some problems with virtualenv,

You can use it:

sudo ln -sf python2 /usr/bin/python

and

sudo ln -sf python3 /usr/bin/python


问:
Need help for migrating OsCommerce database it Magento database
I need to migrate OsCommerce database to Magento database. I found a tool on the Magento site but it does not work for me. :( Can somebody help me with that task?</p>

答:
It's easy to import Products, but not Customers

I always tell my clients that they need to start from a new number for all new Customers as there are much more information in Magento and the "conversion" is not suitable, and they always have the customer information with all sales in their ERP system, so they will never lose anything that special, only that the new customer needs to create a new account again, witch that as well, can be easily managed by sending a newsletter to all customers explaining that they will have a much better service with the new system.

To have the products imported sucessfully, do this:

Create manually all attributes in Magento for the products you need to use

Create 1 product manually with all information you have

Go to import/export and export the CSV file with that one and only product

Analyse the CSV file and in OSCommerce, export the same data into a new CSV file

Import the CSV from OSCommerce into Magento using the import tool.

you will have to upload the product images manually by FTP and all will work fine.


问:
Match substring in string divided by a dot
I have following strings:

```<code>'sample1.sample2'
'sample1.sample2.samaple3'
</code>```

on so on..

I want to separate values sample1, sample2 and sample3 from this string (please note the quotation mark is there).

My code:

```<code>$matches = [];
$regex = "'(.*?)\.(.*?)'";
$string = "'dużotekstu.tekstpokropce'";
$match = preg_match(sprintf("/^%s$/", $regex), $string, $matches);
</code>```

works fine only for first case.

答:
You can do it like this

```<code>$string = "dużotekstu.tekstpokropce";
$exp = explode(".",$string);
$output = implode(",",$exp);
</code>```

Output

```<code>dużotekstu,tekstpokropce
</code>```

Try with this code. it may helps you.

Body:
I have following strings:

'sample1.sample2'
'sample1.sample2.samaple3'

on so on..

I want to separate values sample1, sample2 and sample3 from this string (please note the quotation mark is there).

My code:

$matches = [];
$regex = "'(.*?)\.(.*?)'";
$string = "'dużotekstu.tekstpokropce'";
$match = preg_match(sprintf("/^%s$/", $regex), $string, $matches);

works fine only for first case.

Body:
You can do it like this

$string = "dużotekstu.tekstpokropce";
$exp = explode(".",$string);
$output = implode(",",$exp);

Output

dużotekstu,tekstpokropce

Try with this code. it may helps you.


问:
Django: standard location/conventions for data import scripts?
I'm working on a number of Django projects, and in most of them, I have initial data to import.

This data isn't neat JSON, as shown in the fixture examples in the Django docs - it tends to be messy Excel or CSV files. The scripts tend to look like the following snippet, and I just run them as standalone Python, because I don't know any better:

```<code>import sys
from django.core.management import setup_environ
sys.path.append(LOCATION OF YOUR DJANGO PROJECTS, EX: 'C:\django')
from mysite import settings
setup_environ(settings)

from PROJECT_NAME.APP_NAME.models import MODEL_NAME

import csv
reader = csv.reader(open(COMPLETE PATH TO YOUR DATA, EX: "C:/django/mysite/restaurants.csv"), dialect='excel')

for row in reader:
   COLUMN_ONE_TITLE = row[0]
   COLUMN_TWO_TITLE = row[1]

   MODEL_NAME.objects.get_or_create(MY_FIRST_COLUMN=COLUMN_ONE_TITLE, MY_SECOND_COLUMN=COLUMN_TWO_TITLE)
</code>```

I feel that when I commit these projects to GitHub or send them to the client or whatever, I should include the import scripts. They're an important part of the project.

Is there a standard way, in Django, to store the import scripts  that I've written to import this data?

Where in the project should they sit? Should I be using management commands?

Thanks!

答:
I would first suggest what Martin or Luke suggested.

But if that won't work for you for some reason, then putting the script right in the root of the git project makes sense. Note, I did not suggest putting it in the root of the django project (though, frankly, that isn't a wrong idea either), but I'm suggesting that the django project be a sub folder of the git repo for the very reason that you can put these helper files somewhere that's not clogging up the django project.

Body:
I'm working on a number of Django projects, and in most of them, I have initial data to import.

This data isn't neat JSON, as shown in the fixture examples in the Django docs - it tends to be messy Excel or CSV files. The scripts tend to look like the following snippet, and I just run them as standalone Python, because I don't know any better:

import sys
from django.core.management import setup_environ
sys.path.append(LOCATION OF YOUR DJANGO PROJECTS, EX: 'C:\django')
from mysite import settings
setup_environ(settings)

from PROJECT_NAME.APP_NAME.models import MODEL_NAME

import csv
reader = csv.reader(open(COMPLETE PATH TO YOUR DATA, EX: "C:/django/mysite/restaurants.csv"), dialect='excel')

for row in reader:
   COLUMN_ONE_TITLE = row[0]
   COLUMN_TWO_TITLE = row[1]

   MODEL_NAME.objects.get_or_create(MY_FIRST_COLUMN=COLUMN_ONE_TITLE, MY_SECOND_COLUMN=COLUMN_TWO_TITLE)

I feel that when I commit these projects to GitHub or send them to the client or whatever, I should include the import scripts. They're an important part of the project.

Is there a standard way, in Django, to store the import scripts  that I've written to import this data?

Where in the project should they sit? Should I be using management commands?

Thanks!


问:
How to stop some records displaying multiple times in SQL Query
Here is the Complete SQL Fiddle

As you can see, the records from recommendations table are displaying multiple times. But If i remove this line LEFT JOIN cast ON cast.cast_tmdb_id=tmdb_movies.tmdb_id
 then, they do not display multiple times. So this line is the main problem.

I did not use cast table in my SQL Query, just for the sake of simplicity. But I need it.

And yes, I need group_concat to display the records together in my PHP code

That's all the information needed, i guess. Please let me know, if you need more information or want me to explain again.

Edit: Dear @Shadow, who marked this suggestion as duplicate. If I use DISTINCT then, not all records will display. Because it is possible that 2 movies have an average rating of 7.5

答:
Your question is not really clear. That is because you have not shown the desired result.

In your query you are selecting a column of recommended movie titles and another with votes. However, these are not related, as you didn't specify an order. So the first recommended movie may have the fifth vote shown for instance. And even if the votes were sorted by movie, that would still be hard to read.

So start with how the result would ideally look like. Only then write the query.

Example:

Expected result:

```
movie_title       | roles                          | recommendations
------------------+--------------------------------+------------------------
The Dark Knight   | Christian Bale (Bruce Wayne /  | The Dark Knight Rises (7.5),
                  | Batman), Michael Caine (Alfred | Batman Begins (7.5), Iron
                  | Pennyworth), ...               | Man (7.3), ...
```

So we need an aggreation from the cast table (all roles per movie) and one from the recommendation table (all recommendations per movie). Do the aggregations first and then join the results:

```<code>SELECT
  m.movie_title,
  c.roles,
  r.movies as recommendations
FROM tmdb_movies m
LEFT JOIN
(
  SELECT
    cast_tmdb_id as movie_id,
    GROUP_CONCAT(CONCAT(cast_name, ' (', cast_character, ')') SEPARATOR ', ') as roles
  FROM cast
  GROUP BY cast_tmdb_id
) c ON c.movie_id = m.tmdb_id
LEFT JOIN
(
  SELECT
    recommendations_tmdb_id as movie_id,
    GROUP_CONCAT(CONCAT(recommendations_title, ' (', recommendations_vote_average, ')')
                 SEPARATOR ', ') as movies
  FROM recommendations
  GROUP BY recommendations_tmdb_id
) r ON r.movie_id = m.tmdb_id
WHERE m.tmdb_id = 1;
</code>```

Here is the rextester link: http://rextester.com/FHA48503

Body:
Your question is not really clear. That is because you have not shown the desired result.

In your query you are selecting a column of recommended movie titles and another with votes. However, these are not related, as you didn't specify an order. So the first recommended movie may have the fifth vote shown for instance. And even if the votes were sorted by movie, that would still be hard to read.

So start with how the result would ideally look like. Only then write the query.

Example:

Expected result:

movie_title       | roles                          | recommendations
------------------+--------------------------------+------------------------
The Dark Knight   | Christian Bale (Bruce Wayne /  | The Dark Knight Rises (7.5),
                  | Batman), Michael Caine (Alfred | Batman Begins (7.5), Iron
                  | Pennyworth), ...               | Man (7.3), ...

So we need an aggreation from the cast table (all roles per movie) and one from the recommendation table (all recommendations per movie). Do the aggregations first and then join the results:

SELECT
  m.movie_title,
  c.roles,
  r.movies as recommendations
FROM tmdb_movies m
LEFT JOIN
(
  SELECT
    cast_tmdb_id as movie_id,
    GROUP_CONCAT(CONCAT(cast_name, ' (', cast_character, ')') SEPARATOR ', ') as roles
  FROM cast
  GROUP BY cast_tmdb_id
) c ON c.movie_id = m.tmdb_id
LEFT JOIN
(
  SELECT
    recommendations_tmdb_id as movie_id,
    GROUP_CONCAT(CONCAT(recommendations_title, ' (', recommendations_vote_average, ')')
                 SEPARATOR ', ') as movies
  FROM recommendations
  GROUP BY recommendations_tmdb_id
) r ON r.movie_id = m.tmdb_id
WHERE m.tmdb_id = 1;

Here is the rextester link: http://rextester.com/FHA48503


问:
Best way to updating a list in Mongodb
I have documents with list elements in mongodb. When i get an input to a program, I need to retrieve the document for the given id, get the list element from document and check if the value is there already. If it is not there, need to update that list in the particular document and update db.

What is the best way to do it in MongoDB java driver? I'm thinking of :

retrieving the document and getting the list element

Check for the value. If it is not there add it to the list

Create a BasicDBObject with "$set" operator for that list (say updatedList)

finally, collection.update(searchQuery, updatedList);

Please let me know the best way to do this considering performance. Can i use $addToSet for this scenario?

Thanks.

答: If you want to edit in the list of an element. You can use $each </p>

Title: Best way to updating a list in Mongodb


问:
answer repeating in the foor-loop
I have a data frame which has everyday for a month, and for each day the times every 10 minutes:

```<code>        Date     Time   Temp
0   31/05/2006  09:00   9.3
1   31/05/2006  09:10   10.1
2   31/05/2006  09:20   10.7
</code>```

I am trying to get the time (hh:mm) for the Max(Temp), so I used the function argmax for calculating the index of the Max(Temp)

maxTime = data.iloc[data[data['Date'] == '31/05/2006']['Outside Temperature'].argmax()]['Time']

That's fine, but now I need to calculate this for each day of the month, so I put this inside a loop. First I created the list MaxTempTime for saving the results of my loop:

```<code>MaxTempTime = []
for i in data['Date']:
    maxTime = data.iloc[data[data['Date'] == i ]['Outside Temperature'].argmax()]['Time']
    MaxTempTime.extend(maxTime)
    print maxTime
</code>```

But I get the answer as many times as there are per day, I just need it only once and then go on to the next date

(having periods of 10 min, there are 144 periods of 10 minutes within the 1440 minutes per day, so I get 144 of the same answer per each day)

Can anybody help me sort out this please? Thanks!

答:
You could just add the following slight modification to your initial attempt:

```<code>MaxTempTime = []
for i in data['Date'].unique():
    maxTime = data.iloc[data[data['Date'] == i ]['Outside Temperature'].argmax()]['Time']
    MaxTempTime.append(maxTime)
</code>```

That way, you iterate over all days in your DataFrame, but each one only once. This gets the job done without much change needed in your code, although there might be faster ways using groupby(), which could be a concern if your DataFrame is big.

As a sidenote, you should use append() instead of extend() to add elements to a list. Using extend() in this case splits the time-string into single characters and appends every one as it's own element. See here for an explanation of the difference between the two methods.

Title: answer repeating in the foor-loop

Body:
I have a data frame which has everyday for a month, and for each day the times every 10 minutes:

        Date     Time   Temp
0   31/05/2006  09:00   9.3
1   31/05/2006  09:10   10.1
2   31/05/2006  09:20   10.7

I am trying to get the time (hh:mm) for the Max(Temp), so I used the function argmax for calculating the index of the Max(Temp)

maxTime = data.iloc[data[data['Date'] == '31/05/2006']['Outside Temperature'].argmax()]['Time']

That's fine, but now I need to calculate this for each day of the month, so I put this inside a loop. First I created the list MaxTempTime for saving the results of my loop:

MaxTempTime = []
for i in data['Date']:
    maxTime = data.iloc[data[data['Date'] == i ]['Outside Temperature'].argmax()]['Time']
    MaxTempTime.extend(maxTime)
    print maxTime

But I get the answer as many times as there are per day, I just need it only once and then go on to the next date

(having periods of 10 min, there are 144 periods of 10 minutes within the 1440 minutes per day, so I get 144 of the same answer per each day)

Can anybody help me sort out this please? Thanks!

Body:
You could just add the following slight modification to your initial attempt:

MaxTempTime = []
for i in data['Date'].unique():
    maxTime = data.iloc[data[data['Date'] == i ]['Outside Temperature'].argmax()]['Time']
    MaxTempTime.append(maxTime)

That way, you iterate over all days in your DataFrame, but each one only once. This gets the job done without much change needed in your code, although there might be faster ways using groupby(), which could be a concern if your DataFrame is big.

As a sidenote, you should use append() instead of extend() to add elements to a list. Using extend() in this case splits the time-string into single characters and appends every one as it's own element. See here for an explanation of the difference between the two methods.


问:
Scale down UIImage but returns larger memory size?
I want to scale down UIImage and use following method.

```<code>- (UIImage *)imageWithImage:(UIImage *)image convertToSize:(CGSize)size {
    UIGraphicsBeginImageContext(size);
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage *destImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return destImage;
}
</code>```

It returns correct dimensions but having larger image size(memory) than original image. How to optimize the method?

答:
You can compress your image so its size will decrese</p>

```<code>NSData* data = UIImageJPEGRepresentation(image, 0.8);
</code>```

Body:
I want to scale down UIImage and use following method.

- (UIImage *)imageWithImage:(UIImage *)image convertToSize:(CGSize)size {
    UIGraphicsBeginImageContext(size);
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage *destImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return destImage;
}

It returns correct dimensions but having larger image size(memory) than original image. How to optimize the method?

Body:
You can compress your image so its size will decrese

NSData* data = UIImageJPEGRepresentation(image, 0.8);


问:
Why does an in-loop print() output after the loop is completed?
In the code below, the diamond characters (\4) are not printed immediately but after the loop is completed. Any ideas why?

```<code>from os import system
from time import sleep

def load():
    system('cls')
    i = 0
    sleep(1)
    print("\n\n\n\n\n\n\n\n\n\n\n\t\t\t Loading ", end=' ')
    for i in range(6):
        sleep(1)
        print("\4", end=' ')
        sleep(2)
load()
</code>```

答:
The printing is working in Python IDLE for me. In Windows cmd it does not. Removing the end=' ' solves this, but then each diamond gets printed on a new line.

Depending on your OS you have to change the line ending.
Check this page for more info on that:  Python print on same line

This is working on Windows:

```<code>from os import system
from time import sleep
import sys

def load():
    system('cls')
    i = 0
    sleep(1)
    sys.stdout.write("\n\n\n\n\n\n\n\n\n\n\n\t\t\t Loading ")
    for i in range(6):
        sleep(1)
        sys.stdout.write("\4")
        sys.stdout.flush()
        sleep(2)

load()
</code>```

Body:
In the code below, the diamond characters (\4) are not printed immediately but after the loop is completed. Any ideas why?

from os import system
from time import sleep

def load():
    system('cls')
    i = 0
    sleep(1)
    print("\n\n\n\n\n\n\n\n\n\n\n\t\t\t Loading ", end=' ')
    for i in range(6):
        sleep(1)
        print("\4", end=' ')
        sleep(2)
load()

Body:
The printing is working in Python IDLE for me. In Windows cmd it does not. Removing the end=' ' solves this, but then each diamond gets printed on a new line.

Depending on your OS you have to change the line ending.
Check this page for more info on that:  Python print on same line

This is working on Windows:

from os import system
from time import sleep
import sys

def load():
    system('cls')
    i = 0
    sleep(1)
    sys.stdout.write("\n\n\n\n\n\n\n\n\n\n\n\t\t\t Loading ")
    for i in range(6):
        sleep(1)
        sys.stdout.write("\4")
        sys.stdout.flush()
        sleep(2)

load()


问:
Programmatically binding List to ListBox
Let's say, for instance, I have the following extremely simple window:

```<code><Window x:Class="CalendarGenerator.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1"
        Height="300"
        Width="447">
  <Grid>
    <ListBox Margin="12,40,0,12"
             Name="eventList"
             HorizontalAlignment="Left"
             Width="134" />
  </Grid>
</Window>
</code>```

And a simple list defined as:

```<code>List<String> ListOfNames = new List<String>();
</code>```

And let's assume that the list has several names in it. How would I go about binding the List to the ListBox using as much code-behind as possible?

OwnerDisplayName: Jason Miesionczek

ContentLicense: CC BY-SA 4.0

Body:
Let's say, for instance, I have the following extremely simple window:

<Window x:Class="CalendarGenerator.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1"
        Height="300"
        Width="447">
  <Grid>
    <ListBox Margin="12,40,0,12"
             Name="eventList"
             HorizontalAlignment="Left"
             Width="134" />
  </Grid>
</Window>

And a simple list defined as:

List<String> ListOfNames = new List<String>();

And let's assume that the list has several names in it. How would I go about binding the List to the ListBox using as much code-behind as possible?

Body: eventList.ItemsSource = ListOfNames;

OwnerDisplayName: Shane Blazek


问:
How to apply validation on an int variable so that it accepts only integer data and in case of any other data doesn't give an error?
I want to limit the input of the user to integer data only. So I need to validate an integer variable to an extent that it accept only integer data and not alphabetic and special character data. For example, see the code below

```<code>int a;
cout << "Enter any number: ";
cin >> a;
</code>```

Now if the user enter any data other than integer type. It should give the following output without any error

```<code>Enter any number: alphabet
Invalid Input! Try again..
Enter any number:
</code>```

So how do i implement it?

答:
The operator>> sets the stream's fail state if bad input is entered. You can  test the stream's state after the read, eg:

```<code>#include <iostream>
#include <limits>

int a;
do
{
    std::cout << "Enter any number: ";
    if (std::cin >> a)
        break; // no error, a is valid
    std::cout << "Invalid Input! Try again.." << endl;
    std::cin.clear(); // reset error state
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // ignore any pending data
}
while (true);

// use a as needed...
</code>```

Body:
I want to limit the input of the user to integer data only. So I need to validate an integer variable to an extent that it accept only integer data and not alphabetic and special character data. For example, see the code below

int a;
cout << "Enter any number: ";
cin >> a;

Now if the user enter any data other than integer type. It should give the following output without any error

Enter any number: alphabet
Invalid Input! Try again..
Enter any number:

So how do i implement it?

Body:
The operator>> sets the stream's fail state if bad input is entered. You can  test the stream's state after the read, eg:

#include <iostream>
#include <limits>

int a;
do
{
    std::cout << "Enter any number: ";
    if (std::cin >> a)
        break; // no error, a is valid
    std::cout << "Invalid Input! Try again.." << endl;
    std::cin.clear(); // reset error state
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // ignore any pending data
}
while (true);

// use a as needed...


问:
Passing an integer variable into an MySql select statement
I'm puzzle about how MySql handle the data in the select statement considering the following scenario.

selecting user with normal SQL statement

select * from users where userid = 15;

select user with single quote around the integer values

select * from users where userid = '15';

in both cases, MySql return same result so is there any difference between single quote integer and normal integer in MySql.
Is it safe to use quotes around the integer values?

答:
According to the docs (I don't rember the position exactly), it is better to use the integer variant.

It is outside of the scope of the question, buit it cannot be stressed enough: if you insert an arbitrary integer here, don't forget to make the query injection-safe. The best way to do so is to use prepared statements and to prepare the statement as select * from users where userid = ? and then set the parameter 1 of the statement to the integer value 15. How to do so exactly depends on the MySQL frameqork you use.


问:
Laravel - Delete data record from Database
I want to delete record Photo and Photo_list from Database but give me error

This is my Code in Controller

```<code>public function deletephoto($id)
{

    $product = $this->productRepository->findWithoutFail($id);
    Product::select('photo','photo_list')->delete($product->id);

    return redirect(route('stores.index'));

}
</code>```

答:
You can try this :</p>

```<code>public function deletephoto($id)
    {

        $product = $this->productRepository->findWithoutFail($id);
        if($product){
          $product->photo= null;
          $product->photo_list= null;
          $product->save();
        }

        return redirect(route('stores.index'));

    }
</code>```

Body:
I want to delete record Photo and Photo_list from Database but give me error

This is my Code in Controller

public function deletephoto($id)
{

    $product = $this->productRepository->findWithoutFail($id);
    Product::select('photo','photo_list')->delete($product->id);

    return redirect(route('stores.index'));

}

Body:
You can try this :

public function deletephoto($id)
    {

        $product = $this->productRepository->findWithoutFail($id);
        if($product){
          $product->photo= null;
          $product->photo_list= null;
          $product->save();
        }

        return redirect(route('stores.index'));

    }


问:
Disable activeX warning on excel open
Now iam working in excel macro project.There i have used one activeX object in form.Whenever i open the excel file it showing popup saying activeX control might be unsafe.Attached the screen shot.I dont want this warning.Please help Warning Screenshot</p>

答:
This is a default warning, which is a good thing - You don't want ActiveX controls to be instantiated if you don't know the source. Same goes for Macro's in general, etc. etc.

Under File -> Options -> Trust Center you can play around with these settings and disable the warning. I would advise against it, though.

Keep in mind that this setting will have to be changed for each individual user that will use your Macro enabled workbook.

Title: Disable activeX warning on excel open


问:
Different plot size for plt.show() and fig.savefig()
I have to create some plots that I want to integrate into a scientific document. Due to space limitations the size of the plot as well as the font size is rather small.
For debugging/convenience reasons it would be nice to interactively show the plot using plt.show() with a larger size for the plot and fonts, before storing it as a PDF file using fig.savefig(...) with smaller sizes.

I achieved to set a different plot size before displaying it. However, I was not able to update the font size. Any ideas how this would be possible?

```<code>#!/usr/bin/env python

import matplotlib as mpl
from pylab import *

params = {
    'text.usetex': True,
    'font.size': 6,
}
mpl.rcParams.update(params)

fig = plt.figure(figsize=(3,2))
ax = fig.add_subplot(111)

x = [1, 2, 3]
y = [2, 2, 2]

ax.plot(x,y, label='label')

plt.tight_layout()
fig.savefig('plot.pdf')

fig.set_size_inches(10, 8, forward=True)
params = {'font.size': 20}
mpl.rcParams.update(params)
plt.show()
</code>```

I am using Matplotlib 2.0.2, but also tried 1.5.3.

答:
I think you don't want to change anything in the plot if showing it on a larger scale is for debugging or magnifying reasons. That's why you may not want to change any of the rc paramters, nor would you want to change the figure size.

Instead you'd just prepare the figure the way it should be saved for your publication and after saving, change its dpi (dots per inch), fig.set_dpi(xxx).

```<code>import matplotlib as mpl
import matplotlib.pyplot as plt

params = {
    'text.usetex': True,
    'font.size': 6,
}
plt.rcParams.update(params)

fig = plt.figure(figsize=(3,2))
ax = fig.add_subplot(111)

x = [1, 2, 3]
y = [2, 2, 2]

ax.plot(x,y, label='label')
plt.legend()
plt.tight_layout()
fig.savefig('plot.pdf')

fig.set_dpi(300)

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

saved figure:

shown figure (with 300 dpi):

Body:
I have to create some plots that I want to integrate into a scientific document. Due to space limitations the size of the plot as well as the font size is rather small.
For debugging/convenience reasons it would be nice to interactively show the plot using plt.show() with a larger size for the plot and fonts, before storing it as a PDF file using fig.savefig(...) with smaller sizes.

I achieved to set a different plot size before displaying it. However, I was not able to update the font size. Any ideas how this would be possible?

#!/usr/bin/env python

import matplotlib as mpl
from pylab import *

params = {
    'text.usetex': True,
    'font.size': 6,
}
mpl.rcParams.update(params)

fig = plt.figure(figsize=(3,2))
ax = fig.add_subplot(111)

x = [1, 2, 3]
y = [2, 2, 2]

ax.plot(x,y, label='label')

plt.tight_layout()
fig.savefig('plot.pdf')

fig.set_size_inches(10, 8, forward=True)
params = {'font.size': 20}
mpl.rcParams.update(params)
plt.show()

I am using Matplotlib 2.0.2, but also tried 1.5.3.

Body:
I think you don't want to change anything in the plot if showing it on a larger scale is for debugging or magnifying reasons. That's why you may not want to change any of the rc paramters, nor would you want to change the figure size.

Instead you'd just prepare the figure the way it should be saved for your publication and after saving, change its dpi (dots per inch), fig.set_dpi(xxx).

import matplotlib as mpl
import matplotlib.pyplot as plt

params = {
    'text.usetex': True,
    'font.size': 6,
}
plt.rcParams.update(params)

fig = plt.figure(figsize=(3,2))
ax = fig.add_subplot(111)

x = [1, 2, 3]
y = [2, 2, 2]

ax.plot(x,y, label='label')
plt.legend()
plt.tight_layout()
fig.savefig('plot.pdf')

fig.set_dpi(300)

plt.show()

saved figure:

shown figure (with 300 dpi):


问:
How to get the title of YouTube video through the YouTube API
I've the layout for a YouTube video. I would like to set the video's Thumbnail and Title. (I succeeded to set the thumbnail but not the title)

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:weightSum="1.0">

    <com.google.android.youtube.player.YouTubeThumbnailView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginLeft="6dp"
        android:layout_marginTop="10dp"
        android:id="@+id/youtubeThumbnailView"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="YouTube Video"
        android:textSize="20sp"
        android:layout_marginLeft="4dp"
        android:layout_marginTop="10dp"
        android:layout_gravity="center"
        android:id="@+id/textViewTitle"/>
</LinearLayout>
</code>```

I set the Thumbnail here:

```<code>YouTubeThumbnailView youTubeThumbnailView = (YouTubeThumbnailView) newChild.findViewById(R.id.youtubeThumbnailView);
youTubeThumbnailView.initialize(YouTubePlayer.DEVELOPER_KEY, new YouTubeThumbnailView.OnInitializedListener() {
    @Override
    public void onInitializationSuccess(YouTubeThumbnailView youTubeThumbnailView, final YouTubeThumbnailLoader youTubeThumbnailLoader) {
        youTubeThumbnailLoader.setVideo("FM7MFYoylVs");
        youTubeThumbnailLoader.setOnThumbnailLoadedListener(new YouTubeThumbnailLoader.OnThumbnailLoadedListener() {
             @Override
             public void onThumbnailLoaded(YouTubeThumbnailView youTubeThumbnailView, String s) {
                  youTubeThumbnailLoader.release();
             }

             @Override
             public void onThumbnailError(YouTubeThumbnailView youTubeThumbnailView, YouTubeThumbnailLoader.ErrorReason errorReason) {
             }
        });
    }

    @Override
    public void onInitializationFailure(YouTubeThumbnailView youTubeThumbnailView, YouTubeInitializationResult youTubeInitializationResult) {
    }
});
</code>```

How do I get the title from the video?

I saw a solution here: Get title of YouTube video

but I'm not sure if this is the correct way. I guess that YouTube API lets us get the title in an easier way such as: youTubeThumbnailView.getText() for example.

答:
Json data from youtube is:

```<code>{...
 "items": [
  {
   "kind": "youtube#video",
   "etag": ".....",
   "id": "....",
   "snippet": {
    "publishedAt": ".....",
    "channelId": "...",
    "title": "This is the title",
    "description": "",
    "thumbnails": {
     "default": {
      "url": "https://....jpg",
      "width": 120,
      "height": 90
....
</code>```

To get the title:

```<code>JsonArray items = jsondata.getAsJsonArray("items");
JsonObject snippet = item.getAsJsonObject("snippet");
String title = snippet.get("title").getAsString();
</code>```

I recommend use https://github.com/koush/ion to load data.

Body:
I've the layout for a YouTube video. I would like to set the video's Thumbnail and Title. (I succeeded to set the thumbnail but not the title)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:weightSum="1.0">

    <com.google.android.youtube.player.YouTubeThumbnailView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginLeft="6dp"
        android:layout_marginTop="10dp"
        android:id="@+id/youtubeThumbnailView"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="YouTube Video"
        android:textSize="20sp"
        android:layout_marginLeft="4dp"
        android:layout_marginTop="10dp"
        android:layout_gravity="center"
        android:id="@+id/textViewTitle"/>
</LinearLayout>

I set the Thumbnail here:

YouTubeThumbnailView youTubeThumbnailView = (YouTubeThumbnailView) newChild.findViewById(R.id.youtubeThumbnailView);
youTubeThumbnailView.initialize(YouTubePlayer.DEVELOPER_KEY, new YouTubeThumbnailView.OnInitializedListener() {
    @Override
    public void onInitializationSuccess(YouTubeThumbnailView youTubeThumbnailView, final YouTubeThumbnailLoader youTubeThumbnailLoader) {
        youTubeThumbnailLoader.setVideo("FM7MFYoylVs");
        youTubeThumbnailLoader.setOnThumbnailLoadedListener(new YouTubeThumbnailLoader.OnThumbnailLoadedListener() {
             @Override
             public void onThumbnailLoaded(YouTubeThumbnailView youTubeThumbnailView, String s) {
                  youTubeThumbnailLoader.release();
             }

             @Override
             public void onThumbnailError(YouTubeThumbnailView youTubeThumbnailView, YouTubeThumbnailLoader.ErrorReason errorReason) {
             }
        });
    }

    @Override
    public void onInitializationFailure(YouTubeThumbnailView youTubeThumbnailView, YouTubeInitializationResult youTubeInitializationResult) {
    }
});

How do I get the title from the video?

I saw a solution here: Get title of YouTube video

but I'm not sure if this is the correct way. I guess that YouTube API lets us get the title in an easier way such as: youTubeThumbnailView.getText() for example.

Body:
Json data from youtube is:

{...
 "items": [
  {
   "kind": "youtube#video",
   "etag": ".....",
   "id": "....",
   "snippet": {
    "publishedAt": ".....",
    "channelId": "...",
    "title": "This is the title",
    "description": "",
    "thumbnails": {
     "default": {
      "url": "https://....jpg",
      "width": 120,
      "height": 90
....

To get the title:

JsonArray items = jsondata.getAsJsonArray("items");
JsonObject snippet = item.getAsJsonObject("snippet");
String title = snippet.get("title").getAsString();

I recommend use https://github.com/koush/ion to load data.


问:
How to make refresh function in VBA
I am using Access Database to make a program.

Here is the problem:

After I enter the data in textbox, which is in a blue boxes, and click 'Add Data' button, data move to the ListBox, which is marked with orange box. But I should press 'F5' button(refresh) to see the data. I want to see the data immediately after I click 'Add Data' button. Is there any way to do that?
Any comments would be greatly thankful(It would be nice if you can share your code)

答:
Add ListBox.Requery to the button's click event right after new data has been added to the ListBox.

```<code>Private Sub YourButtonName_Click()
    'Add data
    Me.YourListBoxControlName.Requery
End Sub
</code>```

Title: How to make refresh function in VBA

Body:
Add ListBox.Requery to the button's click event right after new data has been added to the ListBox.

Private Sub YourButtonName_Click()
    'Add data
    Me.YourListBoxControlName.Requery
End Sub


问:
What is the recommended size of dataset for optimized broadcast joins?
I am being provided with a large data-set in JSON text files, one JSON object per row.  One of the fields I need to parse/convert is an epoch time-stamp (to a readable date).

So, step one of processing the data is to load it and parse it.  If I do an rdd.map operation, I can either:

Create a simple date format object inside the map (will happen for every record).

Create a simple date format object and broadcast it, creating it only once.

I don't quite understand which of these is better for an object of this size (I usually use broadcast for somewhat sizeable collections calculated on the driver).

Can anyone help me understand which option is better and why?

答:
Your question seems to suggest that you want to use the dataset (you wonder whether it could be a good candidate for broadcasting) to join it with some other dataset.

If so, I think you may want to read my Mastering Apache Spark 2 gitbook about Broadcast Joins (aka Map-Side Joins):

Spark SQL uses broadcast join (aka broadcast hash join) instead of hash join to optimize join queries when the size of one side data is below spark.sql.autoBroadcastJoinThreshold.

You can therefore fine-tune the broadcast join using spark.sql.autoBroadcastJoinThreshold property that is 10M by default.

Quoting Broadcast Variables:

Broadcast variables allow the programmer to keep a read-only variable cached on each machine rather than shipping a copy of it with tasks. They can be used, for example, to give every node a copy of a large input dataset in an efficient manner. Spark also attempts to distribute broadcast variables using efficient broadcast algorithms to reduce communication cost.

That does not say about how big your dataset should be that would allow for effective broadcast. It does depend on the amount of memory for your Spark application. If you have a beefy cluster with a plenty of RAM, any size would work. It's a tradeoff between network bandwidth and the available RAM.

My recommendation would be to calculate the required memory for a Spark application and see how much is left for broadcast variables (per executor). I'd then calculate the size of a dataset for broadcast and see whether it'd fit. If so, I'd give broadcast a shot and monitor performance. If it worked fine, I'd go live.


问:
How to avoid java.net.URISyntaxException in URL.toURI()
In a particular program, I am passed a file: URL and I need to convert it to a URI object.  Using the toURI method will throw a java.net.URISyntaxException if there are spaces or any other invalid characters in the URL.

For example:

```<code>URL url = Platform.getInstallURL();  // file:/Applications/Program
System.out.println(url.toURI());  // prints file:/Applications/Program

URL url = Platform.getConfigurationURL();  // file:/Users/Andrew Eisenberg
System.out.println(url.toURI());  // throws java.net.URISyntaxException because of the space
</code>```

What is the best way of performing this conversion so that all special characters are handled?

答:
This is untested but you could, effectively, do this:

```<code>URL url = Platform.getConfigurationURL();  // file:/Users/Andrew Eisenberg
System.out.println(new URI(URLEncoder.encode(url.toString(), "UTF-8")));
</code>```

Alternatively, you could do this:

```<code>System.out.println(new URI(url.toString().replace(" ", "%20")));
</code>```

Body:
In a particular program, I am passed a file: URL and I need to convert it to a URI object.  Using the toURI method will throw a java.net.URISyntaxException if there are spaces or any other invalid characters in the URL.

For example:

URL url = Platform.getInstallURL();  // file:/Applications/Program
System.out.println(url.toURI());  // prints file:/Applications/Program

URL url = Platform.getConfigurationURL();  // file:/Users/Andrew Eisenberg
System.out.println(url.toURI());  // throws java.net.URISyntaxException because of the space

What is the best way of performing this conversion so that all special characters are handled?

Body:
This is untested but you could, effectively, do this:

URL url = Platform.getConfigurationURL();  // file:/Users/Andrew Eisenberg
System.out.println(new URI(URLEncoder.encode(url.toString(), "UTF-8")));

Alternatively, you could do this:

System.out.println(new URI(url.toString().replace(" ", "%20")));


问:
Unable to pack a Nuget Package on VSTS Unable to cast object of type 'System.String' to type 'NuGet.Frameworks.NuGetFramework'
On running 'pack' I am getting the following error...

```<code>2017-07-05T10:37:09.7762333Z ##[section]Starting: NuGet pack
2017-07-05T10:37:09.7762333Z ==============================================================================
2017-07-05T10:37:09.7762333Z Task         : NuGet
2017-07-05T10:37:09.7762333Z Description  : Restore, pack, or push NuGet packages, or run a NuGet command. Supports NuGet.org and authenticated feeds like Package Management and MyGet.
2017-07-05T10:37:09.7762333Z Version      : 2.0.3
2017-07-05T10:37:09.7762333Z Author       : Microsoft Corporation
2017-07-05T10:37:09.7762333Z Help         : [More Information](https://go.microsoft.com/fwlink/?LinkID=613747)
2017-07-05T10:37:09.7762333Z ==============================================================================
2017-07-05T10:37:10.9664575Z Downloading: https://dist.nuget.org/win-x86-commandline/v4.0.0/nuget.exe
2017-07-05T10:37:11.0954621Z Caching tool: NuGet 4.0.0 x64
2017-07-05T10:37:11.1084622Z Using version: 4.0.0
2017-07-05T10:37:11.1094622Z Found tool in cache: NuGet 4.0.0 x64
2017-07-05T10:37:11.1214629Z [command]C:\Windows\system32\chcp.com 65001
2017-07-05T10:37:11.1634626Z Active code page: 65001
2017-07-05T10:37:11.2234637Z Attempting to pack file: d:\a\1\s\src\Esoterix\Esoterix.csproj
2017-07-05T10:37:11.2294640Z [command]d:\a\_tool\NuGet\4.0.0\x64\nuget.exe pack d:\a\1\s\src\Esoterix\Esoterix.csproj -NonInteractive -OutputDirectory d:\a\1\a -Properties Configuration=release -version 1.0.0-CI-201765-103711 -Verbosity Detailed
2017-07-05T10:37:12.3087180Z NuGet Version: 4.0.0.2283
2017-07-05T10:37:12.3187144Z Attempting to build package from 'Esoterix.csproj'.
2017-07-05T10:37:12.7569409Z MSBuild auto-detection: using msbuild version '15.1.1012.6693' from 'C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\bin'. Use option -MSBuildVersion to force nuget to use a specific version of MSBuild.
2017-07-05T10:37:15.3118046Z Packing files from 'd:\a\1\s\src\Esoterix\bin\release\netcoreapp1.1'.
2017-07-05T10:37:15.7119285Z Add file 'd:\a\1\s\src\Esoterix\bin\release\netcoreapp1.1\Esoterix.dll' to package as 'lib\netcoreapp1.1\Esoterix.dll'
2017-07-05T10:37:15.7959331Z System.InvalidCastException: Unable to cast object of type 'System.String' to type 'NuGet.Frameworks.NuGetFramework'.
2017-07-05T10:37:15.7969309Z    at NuGet.ProjectManagement.NuGetProject.GetMetadata[T](String key)
2017-07-05T10:37:15.7969309Z    at NuGet.ProjectManagement.PackagesConfigNuGetProject..ctor(String folderPath, Dictionary`2 metadata)
2017-07-05T10:37:15.7969309Z    at CallSite.Target(Closure , CallSite , Type , Object , Dictionary`2 )
2017-07-05T10:37:15.7969309Z    at System.Dynamic.UpdateDelegates.UpdateAndExecute3[T0,T1,T2,TRet](CallSite site, T0 arg0, T1 arg1, T2 arg2)
2017-07-05T10:37:15.7969309Z    at NuGet.CommandLine.ProjectFactory.AddDependencies(Dictionary`2 packagesAndDependencies)
2017-07-05T10:37:15.7969309Z    at NuGet.CommandLine.ProjectFactory.ProcessDependencies(PackageBuilder builder)
2017-07-05T10:37:15.7969309Z    at NuGet.CommandLine.ProjectFactory.CreateBuilder(String basePath, NuGetVersion version, String suffix, Boolean buildIfNeeded, PackageBuilder builder)
2017-07-05T10:37:15.7969309Z    at NuGet.Commands.PackCommandRunner.BuildFromProjectFile(String path)
2017-07-05T10:37:15.7969309Z    at NuGet.CommandLine.PackCommand.ExecuteCommand()
2017-07-05T10:37:15.7969309Z    at NuGet.CommandLine.Command.ExecuteCommandAsync()
2017-07-05T10:37:15.7969309Z    at NuGet.CommandLine.Command.Execute()
2017-07-05T10:37:15.7969309Z    at NuGet.CommandLine.Program.MainCore(String workingDirectory, String[] args)
2017-07-05T10:37:15.8259323Z ##[error]Error: d:\a\_tool\NuGet\4.0.0\x64\nuget.exe failed with return code: 1
2017-07-05T10:37:15.8259323Z ##[error]An error ocurred while trying to pack the files.
2017-07-05T10:37:15.8289336Z ##[section]Finishing: NuGet pack
</code>```

It seems that everything is picked up fine up to this point so I'm a bit stuck . Any ideas welcome.

答: This seems to be an issue using the Nuget pack item built in to VSTS. I swapped it out for a Command Line element to call dotnet pack instead and it now works.</p>

Body:
On running 'pack' I am getting the following error...

2017-07-05T10:37:09.7762333Z ##[section]Starting: NuGet pack
2017-07-05T10:37:09.7762333Z ==============================================================================
2017-07-05T10:37:09.7762333Z Task         : NuGet
2017-07-05T10:37:09.7762333Z Description  : Restore, pack, or push NuGet packages, or run a NuGet command. Supports NuGet.org and authenticated feeds like Package Management and MyGet.
2017-07-05T10:37:09.7762333Z Version      : 2.0.3
2017-07-05T10:37:09.7762333Z Author       : Microsoft Corporation
2017-07-05T10:37:09.7762333Z Help         : [More Information](https://go.microsoft.com/fwlink/?LinkID=613747)
2017-07-05T10:37:09.7762333Z ==============================================================================
2017-07-05T10:37:10.9664575Z Downloading: https://dist.nuget.org/win-x86-commandline/v4.0.0/nuget.exe
2017-07-05T10:37:11.0954621Z Caching tool: NuGet 4.0.0 x64
2017-07-05T10:37:11.1084622Z Using version: 4.0.0
2017-07-05T10:37:11.1094622Z Found tool in cache: NuGet 4.0.0 x64
2017-07-05T10:37:11.1214629Z [command]C:\Windows\system32\chcp.com 65001
2017-07-05T10:37:11.1634626Z Active code page: 65001
2017-07-05T10:37:11.2234637Z Attempting to pack file: d:\a\1\s\src\Esoterix\Esoterix.csproj
2017-07-05T10:37:11.2294640Z [command]d:\a\_tool\NuGet\4.0.0\x64\nuget.exe pack d:\a\1\s\src\Esoterix\Esoterix.csproj -NonInteractive -OutputDirectory d:\a\1\a -Properties Configuration=release -version 1.0.0-CI-201765-103711 -Verbosity Detailed
2017-07-05T10:37:12.3087180Z NuGet Version: 4.0.0.2283
2017-07-05T10:37:12.3187144Z Attempting to build package from 'Esoterix.csproj'.
2017-07-05T10:37:12.7569409Z MSBuild auto-detection: using msbuild version '15.1.1012.6693' from 'C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\bin'. Use option -MSBuildVersion to force nuget to use a specific version of MSBuild.
2017-07-05T10:37:15.3118046Z Packing files from 'd:\a\1\s\src\Esoterix\bin\release\netcoreapp1.1'.
2017-07-05T10:37:15.7119285Z Add file 'd:\a\1\s\src\Esoterix\bin\release\netcoreapp1.1\Esoterix.dll' to package as 'lib\netcoreapp1.1\Esoterix.dll'
2017-07-05T10:37:15.7959331Z System.InvalidCastException: Unable to cast object of type 'System.String' to type 'NuGet.Frameworks.NuGetFramework'.
2017-07-05T10:37:15.7969309Z    at NuGet.ProjectManagement.NuGetProject.GetMetadata[T](String key)
2017-07-05T10:37:15.7969309Z    at NuGet.ProjectManagement.PackagesConfigNuGetProject..ctor(String folderPath, Dictionary`2 metadata)
2017-07-05T10:37:15.7969309Z    at CallSite.Target(Closure , CallSite , Type , Object , Dictionary`2 )
2017-07-05T10:37:15.7969309Z    at System.Dynamic.UpdateDelegates.UpdateAndExecute3[T0,T1,T2,TRet](CallSite site, T0 arg0, T1 arg1, T2 arg2)
2017-07-05T10:37:15.7969309Z    at NuGet.CommandLine.ProjectFactory.AddDependencies(Dictionary`2 packagesAndDependencies)
2017-07-05T10:37:15.7969309Z    at NuGet.CommandLine.ProjectFactory.ProcessDependencies(PackageBuilder builder)
2017-07-05T10:37:15.7969309Z    at NuGet.CommandLine.ProjectFactory.CreateBuilder(String basePath, NuGetVersion version, String suffix, Boolean buildIfNeeded, PackageBuilder builder)
2017-07-05T10:37:15.7969309Z    at NuGet.Commands.PackCommandRunner.BuildFromProjectFile(String path)
2017-07-05T10:37:15.7969309Z    at NuGet.CommandLine.PackCommand.ExecuteCommand()
2017-07-05T10:37:15.7969309Z    at NuGet.CommandLine.Command.ExecuteCommandAsync()
2017-07-05T10:37:15.7969309Z    at NuGet.CommandLine.Command.Execute()
2017-07-05T10:37:15.7969309Z    at NuGet.CommandLine.Program.MainCore(String workingDirectory, String[] args)
2017-07-05T10:37:15.8259323Z ##[error]Error: d:\a\_tool\NuGet\4.0.0\x64\nuget.exe failed with return code: 1
2017-07-05T10:37:15.8259323Z ##[error]An error ocurred while trying to pack the files.
2017-07-05T10:37:15.8289336Z ##[section]Finishing: NuGet pack

It seems that everything is picked up fine up to this point so I'm a bit stuck . Any ideas welcome.


问:
Inserting information in the sql lite database not working
The texts that were already stored in the database are displaying without any problem. But new inserted data not showing. I think "Nothing will be displayed by adding new text, as if the insertion action was not performed.". I don't know why it's not working.Please help...

My DatabaseHandler class

```<code> public class databaseHandler extends SQLiteOpenHelper
{

    private Context main_context;
    private static String DB_PATH;
    private static String DB_NAME = "word.sqlite";
    private static String DB_TBL_BOOKS = "word";
    private static String DB_TBL_SETTING = "setting";
    private static final  int DB_version = 1;
    public static final String COLUMN_ID = "ID";
    public static final String COLUMN_FIRST_NAME = "title";
    public static final String COLUMN_LAST_NAME = "content";
    private SQLiteDatabase db;

    public databaseHandler(Context con)
    {

        super(con, DB_NAME, null, DB_version);

        main_context = con;
        DB_PATH = con.getCacheDir().getPath() + "/" +DB_NAME;

    }
    public void createDataBase() throws IOException {
        boolean dbExist = checkDataBase();
        if (dbExist) {
            // do nothing - database already exist
        } else {

            // By calling this method and empty database will be created into
            // the default system path
            // of your application so we are gonna be able to overwrite that
            // database with our database.
            this.getReadableDatabase();
            copyDB();
        }
    }

    /**
     * Check if the database already exist to avoid re-copying the file each
     * time you open the application.
     *
     * @return true if it exists, false if it doesn't
     */
    private boolean checkDataBase() {
        SQLiteDatabase checkDB = null;
        try {
            String myPath = DB_PATH + DB_NAME;
            checkDB = SQLiteDatabase.openDatabase(myPath, null,
                    SQLiteDatabase.OPEN_READONLY);
        } catch (SQLiteException e) {
            // database does't exist yet.
        }
        if (checkDB != null) {
            checkDB.close();
        }
        return checkDB != null ? true : false;
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        String query;
        query = "CREATE TABLE word (id INTEGER PRIMARY KEY  NOT NULL , title VARCHAR, content VARCHAR DEFAULT null)";
        db.execSQL(query);
        Log.d("log","table Created");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {
        Log.w("tag", "Upgrading database from version " + oldVersion + " to "
                + newVersion + ", which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS word");
        onCreate(db);
    }

    private boolean db_exist() {

        File f = new File(DB_PATH);
        if (f.exists())
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    private boolean copyDB() {
        try {
            FileOutputStream out = new FileOutputStream(DB_PATH);
            InputStream in =main_context.getAssets().open(DB_NAME);
            byte[] buffer = new byte[1024];
            int ch;
            while ((ch = in.read(buffer)) > 0)
            {
                out.write(buffer , 0, ch);
            }
            out.flush();
            out.close();
            in.close();
            return true;
        } catch (Exception e) {
            Log.i("amirmessage", "error in 84 -> " + e.toString());
            return false;
        }
    }

    public void open()
    {
        if (db_exist())
        {
            try {
                File temp = new File(DB_PATH);
                db =SQLiteDatabase.openDatabase(temp.getAbsolutePath() , null ,  SQLiteDatabase.OPEN_READWRITE);
            }catch (Exception e) {
                Log.i("amirmessage", "error in 100 -> " + e.toString());

            }

        }
        else {
            if (copyDB())
            {
                open();
            }

        }
    }
    @Override
    public synchronized void close() {

        db.close();
    }
    //---------

    public List<HashMap<String , Object>> getresultOfSerach()
    {
        Cursor result = db.rawQuery("SELECT * FROM "+ DB_TBL_BOOKS  ,null);
        List<HashMap<String , Object>> all_data = new ArrayList<>();

       try {
           while ( result.moveToNext())
           {
               HashMap<String , Object> temp = new HashMap<>();
               temp.put("id" , result.getString(0));
               temp.put("content" , result.getString(2));

               temp.put("title" , result.getString(1));

               all_data.add(temp);
               Log.d("update","Query: ");

           }
       } finally
        {
            result.close();
        }

        return all_data;
    }

    public void addcontent(String state, String title)
    {

        ContentValues cv  = new ContentValues();
        cv.put("content", state);
        cv.put("title", title);
        db = this.getWritableDatabase();

            db.insert(DB_TBL_BOOKS,null,cv);

        Toast.makeText(main_context,state+title , Toast.LENGTH_SHORT).show();

    }
 }
</code>```

My Activity insert code is here

```<code>public class addcontent extends AppCompatActivity

  {

    private databaseHandler db;
    public String title1;
    public String content;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_addcontent);
        db = new databaseHandler(getBaseContext());
        sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

        EditText etcontent = (EditText)findViewById(R.id.editText);
        EditText ettitle1 = (EditText)findViewById(R.id.editText2);

        title1=ettitle1.getText().toString();
        content=etcontent.getText().toString();

    }

      public void onbtnadd(View v)
    {

        db.open();
        db.addcontent( content,title1);

        db.close();

    }
}
</code>```

My MainActivity  code to Show information is here

```<code> public class Main2Activity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

private databaseHandler db;
private ListView resultListView;
private List<HashMap<String , Object>> resultsbooks;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Intent i = new Intent(getBaseContext(),addcontent.class);
            startActivity(i);
        }
    });

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    resultListView = (ListView) findViewById(R.id.catListview);
    db = new databaseHandler(getBaseContext());
    showresultOfSerarch();
}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main2, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_camera) {
        // Handle the camera action
    } else if (id == R.id.nav_gallery) {

    } else if (id == R.id.nav_slideshow) {

    } else if (id == R.id.nav_manage) {

    } else if (id == R.id.nav_share) {

    } else if (id == R.id.nav_send) {

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

public void onbtnfind()
{
    resultListView.setAdapter(null);

    String serachBy;

    serachBy = "author";

    String query =" ";

    showresultOfSerarch();

}
  public void showresultOfSerarch()
{
    db.open();

    resultsbooks = db.getresultOfSerach();
    db.close();

    String[] from = {"title","content"};
    int[] to = {R.id.txttitle,  R.id.txtcontent};

    SimpleAdapter adp = new SimpleAdapter(
            getBaseContext(), resultsbooks, R.layout.tbl_contest_row, from, to
    );
    resultListView.setAdapter(adp);
 }
</code>```

}

答:
You can add return to addcontent instead of void method to understand insertion is working or not..

```<code>public float addcontent(String state, String title)
{

    float insert_result = 0.0f;
    ContentValues cv  = new ContentValues();
    cv.put("content", state);
    cv.put("title", title);
    db = this.getWritableDatabase();

    insert_result = db.insert(DB_TBL_BOOKS,null,cv);

    Toast.makeText(main_context,state+title , Toast.LENGTH_SHORT).show();

    return insert_result;

}
</code>```

then you can call it  and get value on onClick event like this

```<code>public void onbtnadd(View v) {

    title1 = ettitle1.getText().toString();
    content = etcontent.getText().toString();

    db.open();
    float result = db.addcontent(content, title1);
    if(result>0){
       Toast.makeText(main_context,"Insert Successful!" , Toast.LENGTH_SHORT).show();
    }else{
       Toast.makeText(main_context,"Insert Failed!" , Toast.LENGTH_SHORT).show();
    }
    db.close();

}
</code>```

Update

To read database create a method like

```<code>/*
Prepare BD To Read
 */
private void read() {
    if (db != null) {
        if (!db.isOpen()) {
            db = getReadableDatabase();
        }
    } else {
        db = getReadableDatabase();
    }
}
</code>```

Then edit your getresultOfSerach() to show data

```<code>public List<HashMap<String , Object>> getresultOfSerach()
{

    read();

    Cursor result = db.rawQuery("SELECT * FROM "+ DB_TBL_BOOKS  ,null);
    List<HashMap<String , Object>> all_data = new ArrayList<>();

    String id = "";
    String contact = "";
    String title = "";

    try {
        if(result!=null) {
            while (result.moveToNext()) {
                HashMap<String, Object> temp = new HashMap<>();

                id =  result.getString(0);
                contact =  result.getString(2);
                title =  result.getString(1);

                temp.put("id", id);
                temp.put("content", contact);
                temp.put("title", title);

                all_data.add(temp);
                Log.e("data ", id + "-"+ contact +"-"+ title);

            }
        }
    } finally
    {
        result.close();
    }

    return all_data;
}
</code>```

Call this method inside your activity like this

```<code>public void showData() {
    db.getresultOfSerach();
}
</code>```

Body:
The texts that were already stored in the database are displaying without any problem. But new inserted data not showing. I think "Nothing will be displayed by adding new text, as if the insertion action was not performed.". I don't know why it's not working.Please help...

My DatabaseHandler class

 public class databaseHandler extends SQLiteOpenHelper
{

    private Context main_context;
    private static String DB_PATH;
    private static String DB_NAME = "word.sqlite";
    private static String DB_TBL_BOOKS = "word";
    private static String DB_TBL_SETTING = "setting";
    private static final  int DB_version = 1;
    public static final String COLUMN_ID = "ID";
    public static final String COLUMN_FIRST_NAME = "title";
    public static final String COLUMN_LAST_NAME = "content";
    private SQLiteDatabase db;

    public databaseHandler(Context con)
    {

        super(con, DB_NAME, null, DB_version);

        main_context = con;
        DB_PATH = con.getCacheDir().getPath() + "/" +DB_NAME;

    }
    public void createDataBase() throws IOException {
        boolean dbExist = checkDataBase();
        if (dbExist) {
            // do nothing - database already exist
        } else {

            // By calling this method and empty database will be created into
            // the default system path
            // of your application so we are gonna be able to overwrite that
            // database with our database.
            this.getReadableDatabase();
            copyDB();
        }
    }

    /**
     * Check if the database already exist to avoid re-copying the file each
     * time you open the application.
     *
     * @return true if it exists, false if it doesn't
     */
    private boolean checkDataBase() {
        SQLiteDatabase checkDB = null;
        try {
            String myPath = DB_PATH + DB_NAME;
            checkDB = SQLiteDatabase.openDatabase(myPath, null,
                    SQLiteDatabase.OPEN_READONLY);
        } catch (SQLiteException e) {
            // database does't exist yet.
        }
        if (checkDB != null) {
            checkDB.close();
        }
        return checkDB != null ? true : false;
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        String query;
        query = "CREATE TABLE word (id INTEGER PRIMARY KEY  NOT NULL , title VARCHAR, content VARCHAR DEFAULT null)";
        db.execSQL(query);
        Log.d("log","table Created");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {
        Log.w("tag", "Upgrading database from version " + oldVersion + " to "
                + newVersion + ", which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS word");
        onCreate(db);
    }

    private boolean db_exist() {

        File f = new File(DB_PATH);
        if (f.exists())
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    private boolean copyDB() {
        try {
            FileOutputStream out = new FileOutputStream(DB_PATH);
            InputStream in =main_context.getAssets().open(DB_NAME);
            byte[] buffer = new byte[1024];
            int ch;
            while ((ch = in.read(buffer)) > 0)
            {
                out.write(buffer , 0, ch);
            }
            out.flush();
            out.close();
            in.close();
            return true;
        } catch (Exception e) {
            Log.i("amirmessage", "error in 84 -> " + e.toString());
            return false;
        }
    }

    public void open()
    {
        if (db_exist())
        {
            try {
                File temp = new File(DB_PATH);
                db =SQLiteDatabase.openDatabase(temp.getAbsolutePath() , null ,  SQLiteDatabase.OPEN_READWRITE);
            }catch (Exception e) {
                Log.i("amirmessage", "error in 100 -> " + e.toString());

            }

        }
        else {
            if (copyDB())
            {
                open();
            }

        }
    }
    @Override
    public synchronized void close() {

        db.close();
    }
    //---------

    public List<HashMap<String , Object>> getresultOfSerach()
    {
        Cursor result = db.rawQuery("SELECT * FROM "+ DB_TBL_BOOKS  ,null);
        List<HashMap<String , Object>> all_data = new ArrayList<>();

       try {
           while ( result.moveToNext())
           {
               HashMap<String , Object> temp = new HashMap<>();
               temp.put("id" , result.getString(0));
               temp.put("content" , result.getString(2));

               temp.put("title" , result.getString(1));

               all_data.add(temp);
               Log.d("update","Query: ");

           }
       } finally
        {
            result.close();
        }

        return all_data;
    }

    public void addcontent(String state, String title)
    {

        ContentValues cv  = new ContentValues();
        cv.put("content", state);
        cv.put("title", title);
        db = this.getWritableDatabase();

            db.insert(DB_TBL_BOOKS,null,cv);

        Toast.makeText(main_context,state+title , Toast.LENGTH_SHORT).show();

    }
 }

My Activity insert code is here

public class addcontent extends AppCompatActivity

  {

    private databaseHandler db;
    public String title1;
    public String content;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_addcontent);
        db = new databaseHandler(getBaseContext());
        sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

        EditText etcontent = (EditText)findViewById(R.id.editText);
        EditText ettitle1 = (EditText)findViewById(R.id.editText2);

        title1=ettitle1.getText().toString();
        content=etcontent.getText().toString();

    }

      public void onbtnadd(View v)
    {

        db.open();
        db.addcontent( content,title1);

        db.close();

    }
}

My MainActivity  code to Show information is here

 public class Main2Activity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

private databaseHandler db;
private ListView resultListView;
private List<HashMap<String , Object>> resultsbooks;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Intent i = new Intent(getBaseContext(),addcontent.class);
            startActivity(i);
        }
    });

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    resultListView = (ListView) findViewById(R.id.catListview);
    db = new databaseHandler(getBaseContext());
    showresultOfSerarch();
}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main2, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_camera) {
        // Handle the camera action
    } else if (id == R.id.nav_gallery) {

    } else if (id == R.id.nav_slideshow) {

    } else if (id == R.id.nav_manage) {

    } else if (id == R.id.nav_share) {

    } else if (id == R.id.nav_send) {

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

public void onbtnfind()
{
    resultListView.setAdapter(null);

    String serachBy;

    serachBy = "author";

    String query =" ";

    showresultOfSerarch();

}
  public void showresultOfSerarch()
{
    db.open();

    resultsbooks = db.getresultOfSerach();
    db.close();

    String[] from = {"title","content"};
    int[] to = {R.id.txttitle,  R.id.txtcontent};

    SimpleAdapter adp = new SimpleAdapter(
            getBaseContext(), resultsbooks, R.layout.tbl_contest_row, from, to
    );
    resultListView.setAdapter(adp);
 }

}

Body:
You can add return to addcontent instead of void method to understand insertion is working or not..

public float addcontent(String state, String title)
{

    float insert_result = 0.0f;
    ContentValues cv  = new ContentValues();
    cv.put("content", state);
    cv.put("title", title);
    db = this.getWritableDatabase();

    insert_result = db.insert(DB_TBL_BOOKS,null,cv);

    Toast.makeText(main_context,state+title , Toast.LENGTH_SHORT).show();

    return insert_result;

}

then you can call it  and get value on onClick event like this

public void onbtnadd(View v) {

    title1 = ettitle1.getText().toString();
    content = etcontent.getText().toString();

    db.open();
    float result = db.addcontent(content, title1);
    if(result>0){
       Toast.makeText(main_context,"Insert Successful!" , Toast.LENGTH_SHORT).show();
    }else{
       Toast.makeText(main_context,"Insert Failed!" , Toast.LENGTH_SHORT).show();
    }
    db.close();

}

Update

To read database create a method like

/*
Prepare BD To Read
 */
private void read() {
    if (db != null) {
        if (!db.isOpen()) {
            db = getReadableDatabase();
        }
    } else {
        db = getReadableDatabase();
    }
}

Then edit your getresultOfSerach() to show data

public List<HashMap<String , Object>> getresultOfSerach()
{

    read();

    Cursor result = db.rawQuery("SELECT * FROM "+ DB_TBL_BOOKS  ,null);
    List<HashMap<String , Object>> all_data = new ArrayList<>();

    String id = "";
    String contact = "";
    String title = "";

    try {
        if(result!=null) {
            while (result.moveToNext()) {
                HashMap<String, Object> temp = new HashMap<>();

                id =  result.getString(0);
                contact =  result.getString(2);
                title =  result.getString(1);

                temp.put("id", id);
                temp.put("content", contact);
                temp.put("title", title);

                all_data.add(temp);
                Log.e("data ", id + "-"+ contact +"-"+ title);

            }
        }
    } finally
    {
        result.close();
    }

    return all_data;
}

Call this method inside your activity like this

public void showData() {
    db.getresultOfSerach();
}


问:
How methods execute with respective to JavaScript Object
This is my Class

```<code>MyFunction = function(args) {
    var parameter1 = args.parameter1;
    var parameter2 = args.parameter2;
    var ObjId = args.ID;

    function getData(callback) {
        // Some code for getting data;
    }

    someFunction = function() {
        // Some calculation
    }

    someFunction2 = function() {
        //Some calculation
    }
</code>```

Now I am creating two objects of this class. myObj1 and myObj2

```<code>var args1 = {
    parameter1 : "x",
    parameter2 : "Y",
    ObjId : "ID1"
}
var myObj1 = new MyFunction(args1);

var args2 = {
    parameter1 : "x",
    parameter2 : "Y",
    ObjId : "ID1"
}
var myObj2 = new MyFunction(args2);

// Third way. Don't know it is correct or not.
new MyFunction(args2);
</code>```

When I am creating myObj1 or myObj2 my code will reach to MyFunction class and all the methods inside the class like someFunction,someFunction2 and getData with reference to respective args will execute.

My question is

After execute Javascript class, what happened to objects later.

If all the methods present inside the will execute by var myObj1 = new MyFunction(args1);  then when to use myObj1.someFunction()

Am I misiing anything ?

答:
If all the methods present inside the will execute by var myObj1 = new MyFunction(args1);

That is where your understanding is wrong. No, they don't until you call them.

Function gets called only when you do

```<code>myObj1.someFunction()
</code>```

Body:
This is my Class

MyFunction = function(args) {
    var parameter1 = args.parameter1;
    var parameter2 = args.parameter2;
    var ObjId = args.ID;

    function getData(callback) {
        // Some code for getting data;
    }

    someFunction = function() {
        // Some calculation
    }

    someFunction2 = function() {
        //Some calculation
    }

Now I am creating two objects of this class. myObj1 and myObj2

var args1 = {
    parameter1 : "x",
    parameter2 : "Y",
    ObjId : "ID1"
}
var myObj1 = new MyFunction(args1);

var args2 = {
    parameter1 : "x",
    parameter2 : "Y",
    ObjId : "ID1"
}
var myObj2 = new MyFunction(args2);

// Third way. Don't know it is correct or not.
new MyFunction(args2);

When I am creating myObj1 or myObj2 my code will reach to MyFunction class and all the methods inside the class like someFunction,someFunction2 and getData with reference to respective args will execute.

My question is

After execute Javascript class, what happened to objects later.

If all the methods present inside the will execute by var myObj1 = new MyFunction(args1);  then when to use myObj1.someFunction()

Am I misiing anything ?

Body:
If all the methods present inside the will execute by var myObj1 = new MyFunction(args1);

That is where your understanding is wrong. No, they don't until you call them.

Function gets called only when you do

myObj1.someFunction()