问:
Squid Proxy blocking HTTPS
fairly new to squid proxy. Id like to test out blocking HTTPS sites, I've done a fair share of googling, but I don't understand a lot of the solution and the why aspect of it. Can someone help me understand? I'd like to just simply block https://www.facebook.com/ or something for testing purposes. I can easily block any http site or all of them, why is it so much different for HTTPS? I found Blocking HTTPS sites through Squid but the solution does not work for me.

Thanks in advance.

答:
So it turns out the AMI I was using

Ubuntu Server 16.04 LTS (HVM), SSD Volume Type - ami-da05a4a0

the default squid it was installing could not block https for some reason, I have absolutely no idea why. I switched to using

Amazon Linux AMI 2017.09.1 (HVM), SSD Volume Type - ami-6057e21a

and everything now works...If anyone knows why this is the case please let me know.

Title: Squid Proxy blocking HTTPS


来源: stackexchange

问:
How to get the file name and file size for the attachment of my custom post type
I am making a plugin with a custom post_type called circular I use a meta box to upload PDF or image file now I can retrive the url of the file but how can I get the file name and size from my custom post_type meta field .

Here is my Meta Box code

```<code>function add_custom_meta_boxes() {

    // Define the custom attachment for posts
    add_meta_box(
        'wp_custom_attachment',
        'Custom Attachment',
        'wp_custom_attachment',
        'circular',
        'side'
    );

} // end add_custom_meta_boxes
add_action('add_meta_boxes', 'add_custom_meta_boxes');

function wp_custom_attachment() {

    wp_nonce_field(plugin_basename(__FILE__), 'wp_custom_attachment_nonce');

    $html = '<p class="description">';
        $html .= 'Upload your PDF here.';
    $html .= '</p>';
    $html .= '<input type="file" id="wp_custom_attachment" name="wp_custom_attachment" value="" size="25" />';

    echo $html;

} // end wp_custom_attachment

function save_custom_meta_data($id) {

    /* --- security verification --- */
    if(!wp_verify_nonce($_POST['wp_custom_attachment_nonce'], plugin_basename(__FILE__))) {
      return $id;
    } // end if

    if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
      return $id;
    } // end if

    if('circular' == $_POST['post_type']) {
      if(!current_user_can('edit_page', $id)) {
        return $id;
      } // end if
    } else {
        if(!current_user_can('edit_page', $id)) {
            return $id;
        } // end if
    } // end if
    /* - end security verification - */

    // Make sure the file array isn't empty
    if(!empty($_FILES['wp_custom_attachment']['name'])) {

        // Setup the array of supported file types. In this case, it's just PDF.
        $supported_types = array('application/pdf');

        // Get the file type of the upload
        $arr_file_type = wp_check_filetype(basename($_FILES['wp_custom_attachment']['name']));
        $uploaded_type = $arr_file_type['type'];

        // Check if the type is supported. If not, throw an error.
        if(in_array($uploaded_type, $supported_types)) {

            // Use the WordPress API to upload the file
            $upload = wp_upload_bits($_FILES['wp_custom_attachment']['name'], null, file_get_contents($_FILES['wp_custom_attachment']['tmp_name']));

            if(isset($upload['error']) && $upload['error'] != 0) {
                wp_die('There was an error uploading your file. The error is: ' . $upload['error']);
            } else {
                add_post_meta($id, 'wp_custom_attachment', $upload);
                update_post_meta($id, 'wp_custom_attachment', $upload);
            } // end if/else

        } else {
            wp_die("The file type that you've uploaded is not a PDF.");
        } // end if/else

    } // end if

} // end save_custom_meta_data
add_action('save_post', 'save_custom_meta_data');

function update_edit_form() {
    echo ' enctype="multipart/form-data"';
} // end update_edit_form
add_action('post_edit_form_tag', 'update_edit_form');
</code>```

do out put the link of that file

```<code><?php $img = get_post_meta(get_the_ID(), 'wp_custom_attachment', true); ?>
<a href="<?php echo $img['url']; ?>"> Download PDF Here</a>
</code>```

答:
First need to get the file url the we can get the size and name . here wp_custom_attachment is the custom field id.

```<code> // retrieve file of the custom field
 $file = get_post_meta(get_the_ID(), 'wp_custom_attachment', true);

 //get the url
 $url = $file['url'];

 //Replace url to directory path
  $path = str_replace( site_url('/'), ABSPATH, esc_url( $url) );

  if ( is_file( $path ) ){
    $filesize = size_format( filesize( $path ) );
    $filename = basename($path);
  }

            echo '<p>Name: ' . $filename . '</p>';
            echo '<p>Size: ' . $filesize . '</p>';
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am making a plugin with a custom post_type called circular I use a meta box to upload PDF or image file now I can retrive the url of the file but how can I get the file name and size from my custom post_type meta field .

Here is my Meta Box code

function add_custom_meta_boxes() {

    // Define the custom attachment for posts
    add_meta_box(
        'wp_custom_attachment',
        'Custom Attachment',
        'wp_custom_attachment',
        'circular',
        'side'
    );

} // end add_custom_meta_boxes
add_action('add_meta_boxes', 'add_custom_meta_boxes');

function wp_custom_attachment() {

    wp_nonce_field(plugin_basename(__FILE__), 'wp_custom_attachment_nonce');

    $html = '
';
        $html .= 'Upload your PDF here.';
    $html .= '
';
    $html .= '<input type="file" id="wp_custom_attachment" name="wp_custom_attachment" value="" size="25" />';

    echo $html;

} // end wp_custom_attachment

function save_custom_meta_data($id) {

    /* --- security verification --- */
    if(!wp_verify_nonce($_POST['wp_custom_attachment_nonce'], plugin_basename(__FILE__))) {
      return $id;
    } // end if

    if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
      return $id;
    } // end if

    if('circular' == $_POST['post_type']) {
      if(!current_user_can('edit_page', $id)) {
        return $id;
      } // end if
    } else {
        if(!current_user_can('edit_page', $id)) {
            return $id;
        } // end if
    } // end if
    /* - end security verification - */

    // Make sure the file array isn't empty
    if(!empty($_FILES['wp_custom_attachment']['name'])) {

        // Setup the array of supported file types. In this case, it's just PDF.
        $supported_types = array('application/pdf');

        // Get the file type of the upload
        $arr_file_type = wp_check_filetype(basename($_FILES['wp_custom_attachment']['name']));
        $uploaded_type = $arr_file_type['type'];

        // Check if the type is supported. If not, throw an error.
        if(in_array($uploaded_type, $supported_types)) {

            // Use the WordPress API to upload the file
            $upload = wp_upload_bits($_FILES['wp_custom_attachment']['name'], null, file_get_contents($_FILES['wp_custom_attachment']['tmp_name']));

            if(isset($upload['error']) && $upload['error'] != 0) {
                wp_die('There was an error uploading your file. The error is: ' . $upload['error']);
            } else {
                add_post_meta($id, 'wp_custom_attachment', $upload);
                update_post_meta($id, 'wp_custom_attachment', $upload);
            } // end if/else

        } else {
            wp_die("The file type that you've uploaded is not a PDF.");
        } // end if/else

    } // end if

} // end save_custom_meta_data
add_action('save_post', 'save_custom_meta_data');

function update_edit_form() {
    echo ' enctype="multipart/form-data"';
} // end update_edit_form
add_action('post_edit_form_tag', 'update_edit_form');

do out put the link of that file

<?php $img = get_post_meta(get_the_ID(), 'wp_custom_attachment', true); ?>
<a href="<?php echo $img['url']; ?>"> Download PDF Here

Body:
First need to get the file url the we can get the size and name . here wp_custom_attachment is the custom field id.

 // retrieve file of the custom field
 $file = get_post_meta(get_the_ID(), 'wp_custom_attachment', true);

 //get the url
 $url = $file['url'];

 //Replace url to directory path
  $path = str_replace( site_url('/'), ABSPATH, esc_url( $url) );

  if ( is_file( $path ) ){
    $filesize = size_format( filesize( $path ) );
    $filename = basename($path);
  }

            echo '<p>Name: ' . $filename . '</p>';
            echo '<p>Size: ' . $filesize . '</p>';


问:
Returning a list of filenames with keywords associated with it
I'm not sure why I get an empty list I test this function. Can anyone please help me fix this?</p>

```<code>def find_images_with_keyword(key_dict, keywords_list):
'''(dict of {str: list of str}, list of str) -> list
Given a keyword_dictionary and a list of keywords,
return the list of filenames associated with the given keywords.
The list of filenames should include all filenames having one or more
of the specified keywords(ie, a filename may be associated with only one,
not all of the keywords in the list).
>>> find_images_with_keyword({'dog': ['1.png', '2.png'], 'animal': ['1.png',  '3.png']}, ['dog', 'animal'])
  ['1.png', '2.png', '3.png']
'''
new_list = []
for keyword in key_dict.items():
    for filename in keywords_list:
        if keyword == filename:
            new_list.append(filename)
return new_list
</code>```

答:
Try this

```<code>def find_images_with_keyword(key_dict, keywords_list):
    '''(dict of {str: list of str}, list of str) -> list
    Given a keyword_dictionary and a list of keywords,
    return the list of filenames associated with the given keywords.
    The list of filenames should include all filenames having one or more
    of the specified keywords(ie, a filename may be associated with only one,
    not all of the keywords in the list).
    >>> find_images_with_keyword({'dog': ['1.png', '2.png'], 'animal': ['1.png',  '3.png']}, ['dog', 'animal'])
      ['1.png', '2.png', '3.png']
    '''

    found_imgs = set()
    for keyword, value in key_dict.items():
        if keyword in keywords_list:
            found_imgs = found_imgs.union(set(value))
    return found_imgs

print find_images_with_keyword({'dog': ['1.png', '2.png'], 'animal': ['1.png', '3.png']}, ['dog', 'animal'])
</code>```

EDIT: add list version based on yours.

```<code>def find_images_with_keyword(key_dict, keywords_list):
    new_list = []
    for item in key_dict.items():
        key, filenames = item
        if key in keywords_list:
            for filename in filenames:
                if filename not in new_list:  # add this
                    new_list.append(filename)
    return new_list
</code>```

Body:
I'm not sure why I get an empty list I test this function. Can anyone please help me fix this?

def find_images_with_keyword(key_dict, keywords_list):
'''(dict of {str: list of str}, list of str) -> list
Given a keyword_dictionary and a list of keywords,
return the list of filenames associated with the given keywords.
The list of filenames should include all filenames having one or more
of the specified keywords(ie, a filename may be associated with only one,
not all of the keywords in the list).
>>> find_images_with_keyword({'dog': ['1.png', '2.png'], 'animal': ['1.png',  '3.png']}, ['dog', 'animal'])
  ['1.png', '2.png', '3.png']
'''
new_list = []
for keyword in key_dict.items():
    for filename in keywords_list:
        if keyword == filename:
            new_list.append(filename)
return new_list

Body:
Try this

def find_images_with_keyword(key_dict, keywords_list):
    '''(dict of {str: list of str}, list of str) -> list
    Given a keyword_dictionary and a list of keywords,
    return the list of filenames associated with the given keywords.
    The list of filenames should include all filenames having one or more
    of the specified keywords(ie, a filename may be associated with only one,
    not all of the keywords in the list).
    >>> find_images_with_keyword({'dog': ['1.png', '2.png'], 'animal': ['1.png',  '3.png']}, ['dog', 'animal'])
      ['1.png', '2.png', '3.png']
    '''

    found_imgs = set()
    for keyword, value in key_dict.items():
        if keyword in keywords_list:
            found_imgs = found_imgs.union(set(value))
    return found_imgs

print find_images_with_keyword({'dog': ['1.png', '2.png'], 'animal': ['1.png', '3.png']}, ['dog', 'animal'])

EDIT: add list version based on yours.

def find_images_with_keyword(key_dict, keywords_list):
    new_list = []
    for item in key_dict.items():
        key, filenames = item
        if key in keywords_list:
            for filename in filenames:
                if filename not in new_list:  # add this
                    new_list.append(filename)
    return new_list


问:
How to merge every two lines into one from the command line?
I have a text file with the following format. The first line is the "KEY" and the second line is the "VALUE".

```<code>KEY 4048:1736 string
3
KEY 0:1772 string
1
KEY 4192:1349 string
1
KEY 7329:2407 string
2
KEY 0:1774 string
1
</code>```

I need the value in the same line as of the key. So the output should look like this...

```<code>KEY 4048:1736 string 3
KEY 0:1772 string 1
KEY 4192:1349 string 1
KEY 7329:2407 string 2
KEY 0:1774 string 1
</code>```

It will be better if I could use some delimiter like $ or ,:

```<code>KEY 4048:1736 string , 3
</code>```

How do I merge two lines into one?

答:
A slight variation on glenn jackman's answer using paste: if the value for the -d delimiter option contains more than one character, paste cycles through the characters one by one, and combined with the -s options keeps doing that while processing the same input file.

This means that we can use whatever we want to have as the separator plus the escape sequence \n to merge two lines at a time.

Using a comma:

```<code>$ paste -s -d ',\n' infile
KEY 4048:1736 string,3
KEY 0:1772 string,1
KEY 4192:1349 string,1
KEY 7329:2407 string,2
KEY 0:1774 string,1
</code>```

and the dollar sign:

```<code>$ paste -s -d '$\n' infile
KEY 4048:1736 string$3
KEY 0:1772 string$1
KEY 4192:1349 string$1
KEY 7329:2407 string$2
KEY 0:1774 string$1
</code>```

What this cannot do is use a separator consisting of multiple characters.

As a bonus, if the paste is POSIX compliant, this won't modify the newline of the last line in the file, so for an input file with an odd number of lines like

```<code>KEY 4048:1736 string
3
KEY 0:1772 string
</code>```

paste won't tack on the separation character on the last line:

```<code>$ paste -s -d ',\n' infile
KEY 4048:1736 string,3
KEY 0:1772 string
</code>```

Body:
I have a text file with the following format. The first line is the "KEY" and the second line is the "VALUE".

KEY 4048:1736 string
3
KEY 0:1772 string
1
KEY 4192:1349 string
1
KEY 7329:2407 string
2
KEY 0:1774 string
1

I need the value in the same line as of the key. So the output should look like this...

KEY 4048:1736 string 3
KEY 0:1772 string 1
KEY 4192:1349 string 1
KEY 7329:2407 string 2
KEY 0:1774 string 1

It will be better if I could use some delimiter like $ or ,:

KEY 4048:1736 string , 3

How do I merge two lines into one?

Body:
A slight variation on glenn jackman's answer using paste: if the value for the -d delimiter option contains more than one character, paste cycles through the characters one by one, and combined with the -s options keeps doing that while processing the same input file.

This means that we can use whatever we want to have as the separator plus the escape sequence \n to merge two lines at a time.

Using a comma:

$ paste -s -d ',\n' infile
KEY 4048:1736 string,3
KEY 0:1772 string,1
KEY 4192:1349 string,1
KEY 7329:2407 string,2
KEY 0:1774 string,1

and the dollar sign:

$ paste -s -d '$\n' infile
KEY 4048:1736 string$3
KEY 0:1772 string$1
KEY 4192:1349 string$1
KEY 7329:2407 string$2
KEY 0:1774 string$1

What this cannot do is use a separator consisting of multiple characters.

As a bonus, if the paste is POSIX compliant, this won't modify the newline of the last line in the file, so for an input file with an odd number of lines like

KEY 4048:1736 string
3
KEY 0:1772 string

paste won't tack on the separation character on the last line:

$ paste -s -d ',\n' infile
KEY 4048:1736 string,3
KEY 0:1772 string


问:
System Log Dump on Tizen OS
I am working for a project on Samsung Gear Fit2 which has Samsung's Tizen OS. I want to get system log dump to debug my application. How can I do that?</p>

答:
Open Settings>Gear Info>About Device

Scroll down to Serial Number and tap on it five times

(The number pad appears), enter *#9900#

Select Run LOG_DUMP

Connect to the Gear Fit2 via Tizen Studio

In Tizen Studio file explorer, select the log_dump file in /opt/usr/media/SLP_Debug/ and “pull” the file

Title: System Log Dump on Tizen OS


问:
EXCEL VBA: Condensing multiple ranges with a SUMIF formula to one line
I have the following lines of code to fill specific ranges with SUMIF formulas:

```<code>Range("B7").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B8").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B9").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B12").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B13").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B17").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B21").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B22").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B23").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B24").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B25").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B29").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B30").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B31").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B32").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B33").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B37").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
</code>```

I'm having a hard time turning the above lines of code into something shorter like the code below. I receive the same answer but I am unsure how to code it with multiple ranges.

```<code>Dim Sumact As Range

Set Sumact = Sheets("IS Branch 12").Range("B7")

Sumact = Application.sumif(Range("M2:M500"),Range("A7"),Range("L2:L500"))
</code>```

答:
I was under the impression that you wanted to reduce the calculation to a single code line. You can with the SUM(SUMIF(..., ..., ...)) formula but the series of criteria values needs to be an array, not cells and it best to remove duplicates.

```<code>=sum(sumifs(L2:L500, M2:M500, {1, 2, 3, 4, 5}))
</code>```

In code to collect the values from the discontiguous range into an array while removing duplicate values,

```<code>Dim a As Long, arr As Variant, rng As Range
ReDim arr(30)  'total 31 possible values before duplicate removal

For Each rng In Range("a7:a9,a12:a13,a17,a21:a25,a29:a33,a37")
    Debug.Print rng.Address
    If IsError(Application.Match(rng.Value2, arr, 0)) Then
        arr(a) = rng.Value2
        a = a + 1
    End If
Next rng
ReDim Preserve arr(a - 1)
Debug.Print Application.Sum(Application.SumIfs(Range("L2:L500"), Range("M2:M500"), arr))

Dim Sumact As Range
Set Sumact = Sheets("IS Branch 12").Range("B7")
Sumact = Application.Sum(Application.SumIfs(Range("L2:L500"), Range("M2:M500"), arr))
</code>```

Body:
I have the following lines of code to fill specific ranges with SUMIF formulas:

Range("B7").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B8").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B9").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B12").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B13").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B17").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B21").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B22").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B23").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B24").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B25").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B29").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B30").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B31").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B32").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B33").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"
Range("B37").FormulaR1C1 = "=SUMIF(R2C13:R500C13,RC[-1],R2C12:R500C12)"

I'm having a hard time turning the above lines of code into something shorter like the code below. I receive the same answer but I am unsure how to code it with multiple ranges.

Dim Sumact As Range

Set Sumact = Sheets("IS Branch 12").Range("B7")

Sumact = Application.sumif(Range("M2:M500"),Range("A7"),Range("L2:L500"))

Body:
I was under the impression that you wanted to reduce the calculation to a single code line. You can with the SUM(SUMIF(..., ..., ...)) formula but the series of criteria values needs to be an array, not cells and it best to remove duplicates.

=sum(sumifs(L2:L500, M2:M500, {1, 2, 3, 4, 5}))

In code to collect the values from the discontiguous range into an array while removing duplicate values,

Dim a As Long, arr As Variant, rng As Range
ReDim arr(30)  'total 31 possible values before duplicate removal

For Each rng In Range("a7:a9,a12:a13,a17,a21:a25,a29:a33,a37")
    Debug.Print rng.Address
    If IsError(Application.Match(rng.Value2, arr, 0)) Then
        arr(a) = rng.Value2
        a = a + 1
    End If
Next rng
ReDim Preserve arr(a - 1)
Debug.Print Application.Sum(Application.SumIfs(Range("L2:L500"), Range("M2:M500"), arr))

Dim Sumact As Range
Set Sumact = Sheets("IS Branch 12").Range("B7")
Sumact = Application.Sum(Application.SumIfs(Range("L2:L500"), Range("M2:M500"), arr))


问:
Change hamburger icon in master detail navigation xamarin forms

I am working on Xamarin forms where I need to show master detail navigation after successful login screen. I want to change default hamburger icon but not able to change it.

Please see below code I am using.

Since my app have login screen so I don't want to show any navigation on Login screen. I am just setting main page in app.xaml.cs

public App()
{
    InitializeComponent();

    MainPage = new Login();
}
```

<p>Now after login clicked I tried following approach to change icon but didn't work</p>

<pre class="lang-cs prettyprint-override"><code>var dashboard = new Dashboard(){Icon = "Menuicon.png" };
Application.Current.MainPage = dashboard;
</code>```

Dashbaord is masterdetail page and on its ctor, I am setting detail page like below

Detail = new NavigationPage((Page)Activator.CreateInstance(typeof(DashbaordDetail))) { Icon = "Menuicon.png" };
```

Its not reflecting new icon

答:
You should use a custom renderer.

In your Android project, like this:

[assembly: ExportRenderer(typeof(CustomIcon.Views.MainPage), typeof(IconNavigationPageRenderer))]
namespace CustomIcon.Droid
{
    public class IconNavigationPageRenderer : MasterDetailPageRenderer
    {
        private static Android.Support.V7.Widget.Toolbar GetToolbar() => (CrossCurrentActivity.Current?.Activity as MainActivity)?.FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);

        protected override void OnLayout(bool changed, int l, int t, int r, int b)
        {
            base.OnLayout(changed, l, t, r, b);
            var toolbar = GetToolbar();
            if (toolbar != null)
            {
                for (var i = 0; i < toolbar.ChildCount; i++)
                {
                    var imageButton = toolbar.GetChildAt(i) as ImageButton;

                    var drawerArrow = imageButton?.Drawable as DrawerArrowDrawable;
                    if (drawerArrow == null)
                        continue;

                    imageButton.SetImageDrawable(Forms.Context.GetDrawable(Resource.Drawable.newIcon));
                }
            }
        }
    }
}
```

<p>In your iOS project only use the same icon from you xaml file in your PCL project, like this:</p>

<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="utf-8" ?>
<MasterDetailPage  xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:local="clr-namespace:CustomIcon.Views;assembly=CustomIcon"
         Title="MainPage"
         Icon="newIcon.png"
         x:Class="CustomIcon.Views.MainPage">
<MasterDetailPage.Master>
    <local:MasterPage x:Name="masterPage" />
</MasterDetailPage.Master>
<MasterDetailPage.Detail>
    <NavigationPage>
        <x:Arguments>
            <local:Page1 />
        </x:Arguments>
    </NavigationPage>
</MasterDetailPage.Detail>
</code>```

For more information see my repo on github: https://github.com/wilsonvargas/CustomIconNavigationPage

ContentLicense: CC BY-SA 4.0

Body:
I am working on Xamarin forms where I need to show master detail navigation after successful login screen. I want to change default hamburger icon but not able to change it.

Please see below code I am using.

Since my app have login screen so I don't want to show any navigation on Login screen. I am just setting main page in app.xaml.cs

public App()
{
    InitializeComponent();

    MainPage = new Login();
}

Now after login clicked I tried following approach to change icon but didn't work

var dashboard = new Dashboard(){Icon = "Menuicon.png" };
Application.Current.MainPage = dashboard;

Dashbaord is masterdetail page and on its ctor, I am setting detail page like below

Detail = new NavigationPage((Page)Activator.CreateInstance(typeof(DashbaordDetail))) { Icon = "Menuicon.png" };

Its not reflecting new icon

Body:
You should use a custom renderer.

In your Android project, like this:

[assembly: ExportRenderer(typeof(CustomIcon.Views.MainPage), typeof(IconNavigationPageRenderer))]
namespace CustomIcon.Droid
{
    public class IconNavigationPageRenderer : MasterDetailPageRenderer
    {
        private static Android.Support.V7.Widget.Toolbar GetToolbar() => (CrossCurrentActivity.Current?.Activity as MainActivity)?.FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);

        protected override void OnLayout(bool changed, int l, int t, int r, int b)
        {
            base.OnLayout(changed, l, t, r, b);
            var toolbar = GetToolbar();
            if (toolbar != null)
            {
                for (var i = 0; i < toolbar.ChildCount; i++)
                {
                    var imageButton = toolbar.GetChildAt(i) as ImageButton;

                    var drawerArrow = imageButton?.Drawable as DrawerArrowDrawable;
                    if (drawerArrow == null)
                        continue;

                    imageButton.SetImageDrawable(Forms.Context.GetDrawable(Resource.Drawable.newIcon));
                }
            }
        }
    }
}

In your iOS project only use the same icon from you xaml file in your PCL project, like this:

<?xml version="1.0" encoding="utf-8" ?>
<MasterDetailPage  xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:local="clr-namespace:CustomIcon.Views;assembly=CustomIcon"
         Title="MainPage"
         Icon="newIcon.png"
         x:Class="CustomIcon.Views.MainPage">
<MasterDetailPage.Master>
    <local:MasterPage x:Name="masterPage" />
</MasterDetailPage.Master>
<MasterDetailPage.Detail>
    <NavigationPage>
        <x:Arguments>
            <local:Page1 />
        </x:Arguments>
    </NavigationPage>
</MasterDetailPage.Detail>

For more information see my repo on github: https://github.com/wilsonvargas/CustomIconNavigationPage


问:
socket.io - hundreds of requests instead of one connection
I created simple app to start with socket.io, but when I run it, Chrome(tested in other browsers, result same) eats all of my CPU and makes many requests:

I'm new to sockets, but I'm sure this is not how it should work. The code running in browser is really simple, it should just connect to socket and log all received data to console:

index.html

```<code><!DOCTYPE html>
<html>
<head>
    <script src="https://cdn.socket.io/socket.io-1.2.0.js" charset="UTF-8"></script>
</head>
<body>
<script type="application/javascript">
    var Sockets = io.connect('http://localhost:4000');
    Sockets.on('Test', function (data) {
        console.log(data);
    });
</script>

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

Also, my server file looks like this:

server.js

```<code>var app = require('express')();
var http = require('http').Server(app);
var bodyParser = require("body-parser");
var io = require('socket.io')(http);
var port = 4000;

http.listen(port, function () {
    console.log('Server running at port ' + port);
});

var urlencodedParser = bodyParser.urlencoded({extended: false});
app.post('/', urlencodedParser, function (req, res) {
    if (!req.body) return res.sendStatus(400);
    var post = req.body;
    io.emit("Test", post.data);
    console.log(post.data);
    res.send('true');
});

io.on('connection', function(socket){
    console.log('a user connected');
    socket.on('disconnect', function(){
        console.log('user disconnected');
    });
});
</code>```

When I run the server node server.js, I got the Server running at port 4000 message and everything seems fine. But when I open the index.html in my browser, the node console is spammed by a user connected messages. Instead of connecting one client, the browser makes dozens of requests every second. When I close the browser, there is no output for some time, and then the node console is spammed by user disconnected messages.

This server should redirect all data sent via POST to connected sockets. When I make this POST request, the node server receives it (I know because it print's it into node console). But it's not received by the socket client, as there is no output in browser console (but the browser still makes dozens of new connections every second.

What is wrong here? First I thought I just messed up, so I went back and copy-pasted code from tutorial I found (not in English, but in Czech), but nothing changed. The tutorial has a lot of positive feedback, so there is propably something wrong with my computer. But what?

答:
So to find what exactly was wrong, I downloaded example socket chat from socket.io website. When I runned it, I experienced exactly the same wrong behaviour - browser is opening many socket connections every second instead of keeping one.

So I deleted node_modules folder and used npm to install these modules again and whoa, it worked. So propably the files just corrupted during download or whatever it was, but doing the same procedure again was working this time.

Body:
I created simple app to start with socket.io, but when I run it, Chrome(tested in other browsers, result same) eats all of my CPU and makes many requests:

I'm new to sockets, but I'm sure this is not how it should work. The code running in browser is really simple, it should just connect to socket and log all received data to console:

index.html

<!DOCTYPE html>

Also, my server file looks like this:

server.js

var app = require('express')();
var http = require('http').Server(app);
var bodyParser = require("body-parser");
var io = require('socket.io')(http);
var port = 4000;

http.listen(port, function () {
    console.log('Server running at port ' + port);
});

var urlencodedParser = bodyParser.urlencoded({extended: false});
app.post('/', urlencodedParser, function (req, res) {
    if (!req.body) return res.sendStatus(400);
    var post = req.body;
    io.emit("Test", post.data);
    console.log(post.data);
    res.send('true');
});

io.on('connection', function(socket){
    console.log('a user connected');
    socket.on('disconnect', function(){
        console.log('user disconnected');
    });
});

When I run the server node server.js, I got the Server running at port 4000 message and everything seems fine. But when I open the index.html in my browser, the node console is spammed by a user connected messages. Instead of connecting one client, the browser makes dozens of requests every second. When I close the browser, there is no output for some time, and then the node console is spammed by user disconnected messages.

This server should redirect all data sent via POST to connected sockets. When I make this POST request, the node server receives it (I know because it print's it into node console). But it's not received by the socket client, as there is no output in browser console (but the browser still makes dozens of new connections every second.

What is wrong here? First I thought I just messed up, so I went back and copy-pasted code from tutorial I found (not in English, but in Czech), but nothing changed. The tutorial has a lot of positive feedback, so there is propably something wrong with my computer. But what?


问:
ValueError: Shapes (1024, 3) and (1024, 1024, 3) are incompatible
I have a array as size - 1024, 1024, 3 and need to  create a FIFOQueue of this size.

```<code>a  = np.zeros((1024, 1024, 3))
dtypes=[tf.float32]
print len(dtypes)
shapes=[1024, 1024, 3]
print len(shapes)
q = tf.FIFOQueue(capacity=200,dtypes=dtypes,shapes=shapes)
</code>```

When I tried this I get this error -

```<code>ValueError: Shapes (1024, 3) and (1024, 1024, 3) are incompatible
</code>```

答:
The code you posted runs without error. I suspect there is a missing line:

```<code>enqueue_op = q.enqueue_many(a)
</code>```

...which when executed gives the exception:

```<code>ValueError: Shapes (1024, 3) and (1024, 1024, 3) are incompatible
</code>```

There are two possible solutions:

If you want to enqueue the array as a single element, you should use q.enqueue(a) instead of q.enqueue_many(a)

If you want to enqueue the array as 1024 separate elements, you should define shapes = [1024, 3], which is the shape of a single element when using q.enqueue_many(a).

Body:
I have a array as size - 1024, 1024, 3 and need to  create a FIFOQueue of this size.

a  = np.zeros((1024, 1024, 3))
dtypes=[tf.float32]
print len(dtypes)
shapes=[1024, 1024, 3]
print len(shapes)
q = tf.FIFOQueue(capacity=200,dtypes=dtypes,shapes=shapes)

When I tried this I get this error -

ValueError: Shapes (1024, 3) and (1024, 1024, 3) are incompatible

Body:
The code you posted runs without error. I suspect there is a missing line:

enqueue_op = q.enqueue_many(a)

...which when executed gives the exception:

ValueError: Shapes (1024, 3) and (1024, 1024, 3) are incompatible

There are two possible solutions:

If you want to enqueue the array as a single element, you should use q.enqueue(a) instead of q.enqueue_many(a)

If you want to enqueue the array as 1024 separate elements, you should define shapes = [1024, 3], which is the shape of a single element when using q.enqueue_many(a).


问:
Better alternative to pass variables via stdin with '\n'
I'm creating a bash script to automate a process to create an Oracle database. Basically I want to invoke dbca. I already found two ways to do it but I still did not like those solutions. I was just wondering if has a better way to do it.

First I already have the sys_password defined on my script

```<code>read -p -s "SYS Password: " sys_password
</code>```

The simplest way is to create a temporary file with the password and pass it via STDIN.

```<code>echo $sys_password > /tmp/file_pwd.txt
echo $sys_password >> /tmp/file_pwd.txt
echo "" >> /tmp/file_pwd.txt
dbca -silent -createDatabase -responseFile /assets/dbca.rsp < /tmp/file_pwd.txt
</code>```

However, this approach has a security issue because I'm creating a physical file with a sensitive information in the filesystem, even after removed in somehow it can be recovered.

So, the best solution that I could imagine was using the heredocs and pass it via pipe to dbca.

```<code>cat <<EOF | dbca -silent -createDatabase  -responseFile /assets/dbca.rsp
${sys_password}
${sys_password}
EOF
</code>```

I have tried echo and printf combined with pipe but it did not produce the same result, anyway, it does not work. Bellow is the code not working:

```<code>printf "${sys_password}\n${sys_password}\n" | \
    dbca -silent -createDatabase  -responseFile /assets/dbca.rsp
</code>```

I would like to know if there is another way to send the printf or echo output to dbca STDIN in jut one line

答:
With tom's hints, I could solve this question. Also, Charles Duffy gave me valuable advisor to make the code better. Thanks for all your support!
Here is the final code:

printf "%s\n%s\n" "${sys_password}" "${sys_password}" | \
    dbca -silent -createDatabase -responseFile /assets/dbca.rsp
```

Body:
I'm creating a bash script to automate a process to create an Oracle database. Basically I want to invoke dbca. I already found two ways to do it but I still did not like those solutions. I was just wondering if has a better way to do it.

First I already have the sys_password defined on my script

read -p -s "SYS Password: " sys_password

The simplest way is to create a temporary file with the password and pass it via STDIN.

echo $sys_password > /tmp/file_pwd.txt
echo $sys_password >> /tmp/file_pwd.txt
echo "" >> /tmp/file_pwd.txt
dbca -silent -createDatabase -responseFile /assets/dbca.rsp < /tmp/file_pwd.txt

However, this approach has a security issue because I'm creating a physical file with a sensitive information in the filesystem, even after removed in somehow it can be recovered.

So, the best solution that I could imagine was using the heredocs and pass it via pipe to dbca.

cat <<EOF | dbca -silent -createDatabase  -responseFile /assets/dbca.rsp
${sys_password}
${sys_password}
EOF

I have tried echo and printf combined with pipe but it did not produce the same result, anyway, it does not work. Bellow is the code not working:

printf "${sys_password}\n${sys_password}\n" | \
    dbca -silent -createDatabase  -responseFile /assets/dbca.rsp

I would like to know if there is another way to send the printf or echo output to dbca STDIN in jut one line


问:
iPad css3 animation flickers after keyboard use
I'm developing an app for the iPad using HTML5/CSS3. I'm not using any framework and am just using whatever is natively supported on the device. I have created some css3 animations to emulate the typical iOS sliding left or sliding right when navigating between screens. Here's an example of the slide left animation which is taking advantage of the iPad's CSS3 hardware acceleration: (the ipad is running 4.2).

```<code>/*************************************************
Slide Left
*************************************************/
.screen.slideleft{
 -webkit-animation-duration: 0.5s;
 -webkit-animation-timing-function: ease-in-out;
}
.screen.slideleft.outgoing{
 z-index: 50 !important;
 -webkit-animation-name: slideleft-outgoing;

}
.screen.slideleft.incoming{
 z-index: 100 !important;
 -webkit-animation-name: slideleft-incoming;
}
@-webkit-keyframes slideleft-outgoing{
 from { -webkit-transform: translate3d(0%,0,0); }
 to { -webkit-transform: translate3d(-100%,0,0); }
}
@-webkit-keyframes slideleft-incoming{
 from { -webkit-transform: translate3d(100%,0,0); }
 to { -webkit-transform: translate3d(0%,0,0); }
}</code>```

I also have this CSS which I've attempted to use to fix the flicker:
```
.incoming,
.outgoing{
 display: block !important;
 -webkit-backface-visibility: hidden;
}
```

This works great until the iPad keyboard is used. After which point all the animations flicker severely.

I've been looking for examples of an iPad HTML5 app that uses the keyboard and doesn't have flickers afterwards, but haven't turned up much. The jqTouch demos exhibit the same behavior on the iPad (although I know they were designed for the iPhone).

I've turned up a few posts/questions of similar questions but have never found a good answer.  I've been through http://css3animator.com/2010/12/fight-the-flicker-making-your-css3-animation-bomb-proof/ and the articles linked there but haven't had any success.

Any other suggestions?

Update 1/13 @ 9am

I've added this css and it helped a lot:
```
.incoming *,
.outgoing *{
 -webkit-backface-visibility: hidden;
 -webkit-transform: translate3d(0,0,0); /* This helps with the flicker a lot. */
}
</code>```

The foreground elements don't seem to flicker anymore, but the backgrounds still do. Still looking for some help or helpful resources on Mobile Safari's memory handling tactics.

Update 1/16 @ 11pm

Increasing the z-index as suggested by anonymous. Didn't seem to make a difference.

Update 1/17 @ 8:30am

I've posted a demo of the problem here.

The transitions between screens work great...until you tap/click inside one of the form fields. After the keyboard slides up and returns, all the transitions flicker. Go to the URL inside the iOS simulator or on an actual iPad to see what I'm talking about.

答:
Looking at your source, the translate3d(0,0,0) isn't applied until the transition starts?

Try

```<code>.screen{
    -webkit-transform: translate3d(0,0,0);
}
</code>```

or

```<code>.screen *, .screen{
        -webkit-transform: translate3d(0,0,0);
}
</code>```

The flicker is probably the hardware acceleration kicking in (it currently only works on 3d translated elements).

ContentLicense: CC BY-SA 2.5

Body:
I'm developing an app for the iPad using HTML5/CSS3. I'm not using any framework and am just using whatever is natively supported on the device. I have created some css3 animations to emulate the typical iOS sliding left or sliding right when navigating between screens. Here's an example of the slide left animation which is taking advantage of the iPad's CSS3 hardware acceleration: (the ipad is running 4.2).

/*************************************************
Slide Left
*************************************************/
.screen.slideleft{
 -webkit-animation-duration: 0.5s;
 -webkit-animation-timing-function: ease-in-out;
}
.screen.slideleft.outgoing{
 z-index: 50 !important;
 -webkit-animation-name: slideleft-outgoing;

}
.screen.slideleft.incoming{
 z-index: 100 !important;
 -webkit-animation-name: slideleft-incoming;
}
@-webkit-keyframes slideleft-outgoing{
 from { -webkit-transform: translate3d(0%,0,0); }
 to { -webkit-transform: translate3d(-100%,0,0); }
}
@-webkit-keyframes slideleft-incoming{
 from { -webkit-transform: translate3d(100%,0,0); }
 to { -webkit-transform: translate3d(0%,0,0); }
}

I also have this CSS which I've attempted to use to fix the flicker:

.incoming,
.outgoing{
 display: block !important;
 -webkit-backface-visibility: hidden;
}

This works great until the iPad keyboard is used. After which point all the animations flicker severely.

I've been looking for examples of an iPad HTML5 app that uses the keyboard and doesn't have flickers afterwards, but haven't turned up much. The jqTouch demos exhibit the same behavior on the iPad (although I know they were designed for the iPhone).

I've turned up a few posts/questions of similar questions but have never found a good answer.  I've been through http://css3animator.com/2010/12/fight-the-flicker-making-your-css3-animation-bomb-proof/ and the articles linked there but haven't had any success.

Any other suggestions?

Update 1/13 @ 9am

I've added this css and it helped a lot:

.incoming *,
.outgoing *{
 -webkit-backface-visibility: hidden;
 -webkit-transform: translate3d(0,0,0); /* This helps with the flicker a lot. */
}

The foreground elements don't seem to flicker anymore, but the backgrounds still do. Still looking for some help or helpful resources on Mobile Safari's memory handling tactics.

Update 1/16 @ 11pm

Increasing the z-index as suggested by anonymous. Didn't seem to make a difference.

Update 1/17 @ 8:30am

I've posted a demo of the problem here.

The transitions between screens work great...until you tap/click inside one of the form fields. After the keyboard slides up and returns, all the transitions flicker. Go to the URL inside the iOS simulator or on an actual iPad to see what I'm talking about.

Body:
Looking at your source, the translate3d(0,0,0) isn't applied until the transition starts?

Try

.screen{
    -webkit-transform: translate3d(0,0,0);
}

or

.screen *, .screen{
        -webkit-transform: translate3d(0,0,0);
}

The flicker is probably the hardware acceleration kicking in (it currently only works on 3d translated elements).


问:
Need to send test emails from local PC
I am working on an ASP.Net web application that sends email, but doing this over the weekend from home and do not have access to my organization's smtp server for sending mail.  What are my options for sending test emails to myself through the app?  I've tried plugging in Google's smtp settings using my credentials and ssl port number, but when I do, I get the following exception in the event viewer:

```<code>Exception information:
Exception type: IOException
Exception message: Unable to read data from the transport connection: net_io_connectionclosed. at system.Net.Mail.SmtpReplyReaderFactory.ProcessRead(Byte[] buffer, Int32 offset, Int32 read, Boolean readLine) at System.Net.Mail.SmtpReplyReaderFactory.ReadLines(SmtpReplyReader caller, Boolean oneLine) at System.Net.Mail.SmtpReplyReaderFactory.ReadLine(SmtpReplyReader caller) at System.Net.Mail.SmtpConnection.GetConnection(ServicePoint servicePoint) at System.Net.Mail.SmtpTransport.GetConnection(ServicePoint servicePoint) at System.Net.Mail.SmtpClient.GetConnection()
</code>```

at System.Net.Mail.SmtpClient.Send(MailMessage message)

I'm wondering what options I have at this point.  Are there public SMTP Servers/services that can be used to send mail just to yourself?

Edit - I've tried some additional smtp based off of other posts here settings:

```<code><network enableSsl="true" password="XXXXX" userName="XXXXX@gmail.com" host="smtp.gmail.com" port="587" />
</code>```

but I'm still getting an exception, although a different one: Exception information:

```<code>
    Exception type: SmtpException
    Exception message: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at
   at System.Net.Mail.MailCommand.CheckResponse(SmtpStatusCode statusCode, String response)
   at System.Net.Mail.MailCommand.Send(SmtpConnection conn, Byte[] command, MailAddress from, Boolean allowUnicode)
   at System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, Boolean allowUnicode, SmtpFailedRecipientException& exception)
   at System.Net.Mail.SmtpClient.Send(MailMessage message)
   at Tricare.handlers.ContactUs.SubmitForm() in c:\TFS\Tricare\Upgrade-branch\Website\handlers\ContactUs.ashx.cs:line 201
   at Tricare.handlers.ContactUs.ProcessRequest(HttpContext context) in c:\TFS\Tricare\Upgrade-branch\Website\handlers\ContactUs.ashx.cs:line 47
   at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
</code>```

答: https://websocket.email does what you want and will accept emails without credentials and allow you to poll for test emails as they arrive.</p>

Title: Need to send test emails from local PC

Body:
I am working on an ASP.Net web application that sends email, but doing this over the weekend from home and do not have access to my organization's smtp server for sending mail.  What are my options for sending test emails to myself through the app?  I've tried plugging in Google's smtp settings using my credentials and ssl port number, but when I do, I get the following exception in the event viewer:

Exception information:
Exception type: IOException
Exception message: Unable to read data from the transport connection: net_io_connectionclosed. at system.Net.Mail.SmtpReplyReaderFactory.ProcessRead(Byte[] buffer, Int32 offset, Int32 read, Boolean readLine) at System.Net.Mail.SmtpReplyReaderFactory.ReadLines(SmtpReplyReader caller, Boolean oneLine) at System.Net.Mail.SmtpReplyReaderFactory.ReadLine(SmtpReplyReader caller) at System.Net.Mail.SmtpConnection.GetConnection(ServicePoint servicePoint) at System.Net.Mail.SmtpTransport.GetConnection(ServicePoint servicePoint) at System.Net.Mail.SmtpClient.GetConnection()

at System.Net.Mail.SmtpClient.Send(MailMessage message)

I'm wondering what options I have at this point.  Are there public SMTP Servers/services that can be used to send mail just to yourself?

Edit - I've tried some additional smtp based off of other posts here settings:

<network enableSsl="true" password="XXXXX" userName="XXXXX@gmail.com" host="smtp.gmail.com" port="587" />

but I'm still getting an exception, although a different one: Exception information:

    Exception type: SmtpException
    Exception message: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at
   at System.Net.Mail.MailCommand.CheckResponse(SmtpStatusCode statusCode, String response)
   at System.Net.Mail.MailCommand.Send(SmtpConnection conn, Byte[] command, MailAddress from, Boolean allowUnicode)
   at System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, Boolean allowUnicode, SmtpFailedRecipientException& exception)
   at System.Net.Mail.SmtpClient.Send(MailMessage message)
   at Tricare.handlers.ContactUs.SubmitForm() in c:\TFS\Tricare\Upgrade-branch\Website\handlers\ContactUs.ashx.cs:line 201
   at Tricare.handlers.ContactUs.ProcessRequest(HttpContext context) in c:\TFS\Tricare\Upgrade-branch\Website\handlers\ContactUs.ashx.cs:line 47
   at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)


问:
swift UITapGestureRecognizer not working on view
I had to create a new thread bcoz it's driving me crazy and all the other answers online are exactly the same. I have done this countless of times but I cannot see what I am missing for the life of me. I am using a "test" view controller just to get the tap gesture working but it isn't working at all... I am fairly certain that I am setting this up correctly, as this is how I've always implemented it in the past: (yes, I have checked the box for isUserInteractionEnabled). I am even implementing this on a different viewcontroller this exact way and it is working...

```<code>class TestViewController: UIViewController {

  override func viewDidLoad() {
    super.viewDidLoad()
    view.addGestureRecognizer(tap)
  }

  let tap = UITapGestureRecognizer(target: self, action: #selector(wasTapped))

  @objc func wasTapped() {
    print("tapped")
  }
}
</code>```

I have also tried adding the parameters to wasTapped:

```<code>@objc func wasTapped(gestureRecognizer: UITapGestureRecognizer) {
  print("tapped")
}
</code>```

答:
You have to enable interaction if you want to use gesture recognizers for standard UIView's

Add view.isUserInteractionEnabled = true in your viewDidLoad.

Body:
I had to create a new thread bcoz it's driving me crazy and all the other answers online are exactly the same. I have done this countless of times but I cannot see what I am missing for the life of me. I am using a "test" view controller just to get the tap gesture working but it isn't working at all... I am fairly certain that I am setting this up correctly, as this is how I've always implemented it in the past: (yes, I have checked the box for isUserInteractionEnabled). I am even implementing this on a different viewcontroller this exact way and it is working...

class TestViewController: UIViewController {

  override func viewDidLoad() {
    super.viewDidLoad()
    view.addGestureRecognizer(tap)
  }

  let tap = UITapGestureRecognizer(target: self, action: #selector(wasTapped))

  @objc func wasTapped() {
    print("tapped")
  }
}

I have also tried adding the parameters to wasTapped:

@objc func wasTapped(gestureRecognizer: UITapGestureRecognizer) {
  print("tapped")
}


问:
Xcode9, only iPhone X "Could not successfully update network info during initialization."
Xcode 9, other Simulators running well and iPhone X appear this error message，AFNetworking cannot work.</p>

答: When this happened to me I was able to work around it by following the suggestion in this answer. That is, setting the Simulator location to Apple.


问:
Sublime Text 3 Build System issue
I have just started playing around with Sublime Text 3 and i am trying to create a build system for python 3.6.3. I have created a .sublime-build file with the name Python3.6.3.sublime-build which contains the following code :

```<code>{
"cmd": ["C:/Python32/python.exe", "-u", "$file"],
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
"quiet": true
}
</code>```

Whenever I try to build a python file I receive this message at the bottom of the Sublime, in the place where the results from the program should be displayed:

```<code>[WinError 2] Finding the specified file was not possible by the system
[cmd: ['C:/Python32/python.exe', '-u',
'C:\\Users\\user\\Desktop\\String_examples.py']]
[dir: C:\Users\user\Desktop]
[path: C:\Program Files (x86)\ARM\ADSv1_2\bin;C:\ProgramData\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\MATLAB\R2012b\runtime\win64;C:\Program Files\MATLAB\R2012b\bin]
</code>```

Sorry but the [WinError 2] message was translated in english so it may not be the exact error text.

Moreover when I open sublime I receive this error window:

Sublime Text

I am running Windows 7 if that plays any role.

Could someone please explain what did i do wrong because i am kind of stuck with this?
Thanks in advance...!

答:
After several hours of search on the Internet i found that we need to find the right path of the python.exe file and use double backslash instead of single backslash (\) when declaring the file's path. The following answers refer to Windows users.
So the correct code is:

```<code>{
"cmd": ["C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python36-32\\python.exe", "-u", "$file"],
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
"quiet": true
}
</code>```

If we have the following it will not work:

```<code>{
"cmd": ["C:\Users\user\AppData\Local\Programs\Python\Python36-32\python.exe", "-u", "$file"],
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
"quiet": true
}
</code>```

A second way to create the python build system is with this code :

```<code>{
"cmd": ["python", "-u", "$file"],
"file_regex": "^ ]File \"(...?)\", line ([0-9]*)",
"selector": "source.python"
}
</code>```

In this code notice that the file's path is absent. We only refer the file's name. So Windows will not know where to find the python.exe file and we will have an error message on the Sublime console like the one I describe in my question above. So we need to do the following steps:

1.Go here C:\Users\user\AppData\Local\Programs\Python\Python36-32 and copy this path

Note: Here user is the user name of my computer. It will be different in your case.
(AppData folder maybe hidden check the show hidden files option)

Now right click on Computer icon and click on PROPERTIES's option. Then select ADVANCED SYSTEM settings in left sidebar.

Now click on [Environment Variables] and then under [System variables] > [select variable] with name [Path].

Click Edit button and then in [Path] value field keep the already existing data and go to end of the line. Type semicolon ( ; ) and don't erase anything just paste the path of Python directory that you copied after the semicolon at the end of the line.

( It should be something like this          ;C:\Users\user\AppData\Local\Programs\Python\Python36-32     )

Then save the changes and close the Sublime Text. Re-open Sublime and it should be ok.

Notice that the code "selector": "source.python"

was not included in the first explation above. Instead there was this code
     "quiet": true
but it does not play any role in the solution of this problem.

After completing the procedure explained second, we have a bonus result. We can use the command python on the cmd window without receiving an error because now Windows knows where to find the python.exe file (the path for this file is now included in the PATH parameter of the Windows system).

Title: Sublime Text 3 Build System issue

Body:
I have just started playing around with Sublime Text 3 and i am trying to create a build system for python 3.6.3. I have created a .sublime-build file with the name Python3.6.3.sublime-build which contains the following code :

{
"cmd": ["C:/Python32/python.exe", "-u", "$file"],
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
"quiet": true
}

Whenever I try to build a python file I receive this message at the bottom of the Sublime, in the place where the results from the program should be displayed:

[WinError 2] Finding the specified file was not possible by the system
[cmd: ['C:/Python32/python.exe', '-u',
'C:\\Users\\user\\Desktop\\String_examples.py']]
[dir: C:\Users\user\Desktop]
[path: C:\Program Files (x86)\ARM\ADSv1_2\bin;C:\ProgramData\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\MATLAB\R2012b\runtime\win64;C:\Program Files\MATLAB\R2012b\bin]

Sorry but the [WinError 2] message was translated in english so it may not be the exact error text.

Moreover when I open sublime I receive this error window:

Sublime Text

I am running Windows 7 if that plays any role.

Could someone please explain what did i do wrong because i am kind of stuck with this?
Thanks in advance...!

Body:
After several hours of search on the Internet i found that we need to find the right path of the python.exe file and use double backslash instead of single backslash (\) when declaring the file's path. The following answers refer to Windows users.
So the correct code is:

{
"cmd": ["C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python36-32\\python.exe", "-u", "$file"],
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
"quiet": true
}

If we have the following it will not work:

{
"cmd": ["C:\Users\user\AppData\Local\Programs\Python\Python36-32\python.exe", "-u", "$file"],
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
"quiet": true
}

A second way to create the python build system is with this code :

{
"cmd": ["python", "-u", "$file"],
"file_regex": "^ ]File \"(...?)\", line ([0-9]*)",
"selector": "source.python"
}

In this code notice that the file's path is absent. We only refer the file's name. So Windows will not know where to find the python.exe file and we will have an error message on the Sublime console like the one I describe in my question above. So we need to do the following steps:

1.Go here C:\Users\user\AppData\Local\Programs\Python\Python36-32 and copy this path

Note: Here user is the user name of my computer. It will be different in your case.
(AppData folder maybe hidden check the show hidden files option)

Now right click on Computer icon and click on PROPERTIES's option. Then select ADVANCED SYSTEM settings in left sidebar.

Now click on [Environment Variables] and then under [System variables] > [select variable] with name [Path].

Click Edit button and then in [Path] value field keep the already existing data and go to end of the line. Type semicolon ( ; ) and don't erase anything just paste the path of Python directory that you copied after the semicolon at the end of the line.

( It should be something like this          ;C:\Users\user\AppData\Local\Programs\Python\Python36-32     )

Then save the changes and close the Sublime Text. Re-open Sublime and it should be ok.

Notice that the code "selector": "source.python"

was not included in the first explation above. Instead there was this code
     "quiet": true
but it does not play any role in the solution of this problem.

After completing the procedure explained second, we have a bonus result. We can use the command python on the cmd window without receiving an error because now Windows knows where to find the python.exe file (the path for this file is now included in the PATH parameter of the Windows system).


问:
retrieve a record from sqlite
Sorry for my bad English.

I am new to Android Studio.

I have an external database. With columns id, text1, text2...text6
Somehow i succeeded to add that database to my application following a youtube tutorial. That works fine.

I added it to asset and in mainActivity is copied to data/data/mypackage/databases. I checked that in emulator file explorer.

Now I need to get data from that database but I can't figure it out how to do it.

id column is auto increment integer.
I have an array in my application containing x randomly generated integers in a certain range.
Now i want to make a query to database for the first integer from array and update textViews in my activity with the results. After user clicks on a button i need to send another query for next integer from the array and so on.

I don't know hot to open database, send query... I tried so many tutorials, searched on the Internet for the solution but non of them worked. Now i just confused.

I have experience in SQL. That shouldn't be a problem. In PHP and MySql it can be done with just few lines of code.
Can anybody help me to solve the problem.

This is my dbHelper

```<code>package com.examle.mydbapp;

import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.SQLException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.util.Log;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Locale;

class dbHelper extends SQLiteOpenHelper {

    private static final String DATABASE_PATH = "/data/data/com.example.mydbapp/databases/";
    private static final String DATABASE_NAME = "quotes.db";
    private  static final int SCHEMA_VERSION = 1;

    public SQLiteDatabase dbSglite;

    private final Context myContext;

    public dbHelper(Context context) {
        super(context, DATABASE_NAME, null, SCHEMA_VERSION);
        this.myContext=context;
       }

       @Override
    public void onCreate(SQLiteDatabase db){

       }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    public void createDatabase(){
        createDB();
    }

    private void createDB(){

        boolean dbExist = DBExists();

        if(!dbExist){
            this.getReadableDatabase();
            copyDBFromResource();

        }

    }

    private boolean DBExists(){

        SQLiteDatabase db = null;

        try {
            String databasePath = DATABASE_PATH+DATABASE_NAME;
            db = SQLiteDatabase.openDatabase(databasePath,null, SQLiteDatabase.OPEN_READWRITE);
            db.setLocale(Locale.getDefault());
            db.setLockingEnabled(true);
            db.setVersion(1);
        } catch (SQLiteException e) {

            Log.e("SqlHelper", "database not found");
        }

        if (db != null) {
            db.close();
        }
        return db != null ? true : false;

    }

    private void copyDBFromResource() {
        InputStream inputStream = null;
        OutputStream outputStream = null;
        String dbFilePath=DATABASE_PATH+DATABASE_NAME;

        try {
            inputStream = myContext.getAssets().open(DATABASE_NAME);
            outputStream = new FileOutputStream(dbFilePath);

            byte[] buffer = new byte[1024];
            int length;
            while ((length=inputStream.read(buffer))>0){
                outputStream.write(buffer, 0, length);
            }

            outputStream.flush();
            outputStream.close();
            inputStream.close();

        } catch (IOException e) {

            throw new Error("Problem copying database.");
        }

    }

    public void openDataBase() throws SQLException {

        String myPath = DATABASE_PATH + DATABASE_NAME;
        dbSglite = SQLiteDatabase.openDatabase(myPath, null,
                SQLiteDatabase.OPEN_READWRITE);

    }

}
</code>```

答:
in short, assuming you want to access the data from an activity, then

You could a) create an instance of the databasehelper b) invoke the databasehelper's createDatabase method and then c) retrieve an SQLiteDatabase instance by invoking the databasehelper's getWriteableDatbase method.

(You have probably already done a and b)

e.g. :-

```<code>    dbhlpr = new dbHelper(this);
    // Create the Database if need be
    dbhlpr.createDatabase();
    // An example of getting a instance outside of the helper
    SQLiteDatabase db = dbhlpr.getWritableDatabase();
</code>```

You could also use SQLiteDatabase db = dbhlpr.dbSglite; instead of SQLiteDatabase db = dbhlpr.getWritableDatabase();

where in the above dbhlpr is a class variable defined using dbHelper dbhlpr;

You can then retrieve data from the tables by creating a Cursor(s). In the following examples (preceded by the previous example code and assuming that the table is called quotes) you could do something along the lines of the following examples :-

EX 1 (from sqlite_master)

```<code>    Cursor csr = db.query("sqlite_master",null,null,null,null,null,null);
    while (csr.moveToNext()) {
        String tblinfo = "Row " + csr.getPosition();
        for (int i=0; i < csr.getColumnCount(); i++) {
            tblinfo = tblinfo + " Column = " + csr.getColumnName(i) + " Value = " + csr.getString(i);
        }
        Log.d("SQLITEINFO",tblinfo);
    }
    csr.close();
</code>```

EX 2 (all rows from quotes table)

```<code>    // Get and process data from the quotes table
    Cursor csr2 = db.query("quotes",null,null,null,null,null,null);
    while (csr2.moveToNext()) {
        String tblinfo = "Row " + csr2.getPosition();
        for (int i=0; i < csr2.getColumnCount(); i++) {
            tblinfo = tblinfo + " Column = " + csr2.getColumnName(i) + " Value = " + csr2.getString(i);
        }
        Log.d("CURSOR 2 INFO",tblinfo);
    }
    csr2.close();
</code>```

EX 3 - Specific row using WHERE clause and placeholder ?

```<code>    // Get and processs data for a specific row according to id
    Cursor csr3 = db.query("quotes",null,"id=?",new String[]{"1"},null,null,null);
    if (csr3.moveToFirst()) {
        Log.d("CURSOR 3 INFO",
                " ID is" + csr3.getLong(0) +
                        " ID is " + csr3.getLong(csr3.getColumnIndex("id")) +
                        " TEXT1 is " + csr3.getString(csr3.getColumnIndex("text1"))
                // ..... etc
        );
    }
    csr3.close();
</code>```

Things to note:-

An empty cursor is a valid cursor a; query will not return a null cursor.

Using column offsets, e.g. csr3.getLong(0) can be problematic, hence the alternative more flexible csr3.getLong(csr3.getColumnIndex("id"))

When a Cursor is returned from the query method it's position is before the first row (-1). To access the data you must use a move???? method e.g. csr3.moveToFirst(). The move???? methods return true if the move was made, false if it couldn't be made.

Testing

The above code has been tested using a DatabaseHelper that is very much the same as the DatabaseHelper provided in the question.

The Database was created outside of the app with a single table added named quotes with two rows of data added as per :-

Output from Test 1 run with no existing database :-

```<code>-15 11:30:20.066 8446-8446/? E/SQLiteLog: (14) cannot open file at line 30046 of [9491ba7d73]
11-15 11:30:20.066 8446-8446/? E/SQLiteLog: (14) os_unix.c:30046: (2) open(/data/data/mjt.usingrecyclerviews/databases/quotes.db) -
11-15 11:30:20.066 8446-8446/? E/SQLiteDatabase: Failed to open database '/data/data/mjt.usingrecyclerviews/databases/quotes.db'.
android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
    at android.database.sqlite.SQLiteConnection.nativeOpen(Native Method)
    at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:209)
    at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:193)
    at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:463)
    at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:185)
    at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:177)
    at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:806)
    at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:791)
    at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:694)
    at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:669)
    at mjt.usingrecyclerviews.dbHelper.DBExists(dbHelper.java:68)
    at mjt.usingrecyclerviews.dbHelper.createDB(dbHelper.java:54)
    at mjt.usingrecyclerviews.dbHelper.createDatabase(dbHelper.java:49)
    at mjt.usingrecyclerviews.MainActivity.onCreate(MainActivity.java:27)
    at android.app.Activity.performCreate(Activity.java:5990)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
    at android.app.ActivityThread.access$800(ActivityThread.java:151)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:135)
    at android.app.ActivityThread.main(ActivityThread.java:5254)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
11-15 11:30:20.066 8446-8446/? E/SqlHelper: database not found
11-15 11:30:20.093 8446-8446/? D/ONCREATE: OnCreate Method Called.
11-15 11:30:20.096 8446-8446/? D/SQLITEINFO: Row 0 Column = type Value = table Column = name Value = quotes Column = tbl_name Value = quotes Column = rootpage Value = 2 Column = sql Value = CREATE TABLE quotes (id INTEGER PRIMARY KEY, text1 TEXT,  text2 TEXT, text3 TEXT, text4 TEXT, text5 TEXT)
11-15 11:30:20.096 8446-8446/? D/SQLITEINFO: Row 1 Column = type Value = table Column = name Value = android_metadata Column = tbl_name Value = android_metadata Column = rootpage Value = 3 Column = sql Value = CREATE TABLE android_metadata (locale TEXT)
11-15 11:30:20.096 8446-8446/? D/CURSOR 2 INFO: Row 0 Column = id Value = 1 Column = text1 Value = Some quote Column = text2 Value = Another quote Column = text3 Value = Yet another quote Column = text4 Value = This is a quote Column = text5 Value = Too many quotes
11-15 11:30:20.096 8446-8446/? D/CURSOR 2 INFO: Row 1 Column = id Value = 2 Column = text1 Value = Seccond quote Column = text2 Value = Third Quote Column = text3 Value = Fourth Quote Column = text4 Value = Fifth Quote Column = text5 Value = Sixth Quote
11-15 11:30:20.096 8446-8446/? D/CURSOR 3 INFO:  ID is1 ID is 1 TEXT1 is Some quote
</code>```

Note! File error was trapped and bypassed/handled (i.e. just because the database didn't exist)

Output from Test 2 - database exists :-

```<code>11-15 11:33:17.111 8511-8511/mjt.usingrecyclerviews D/SQLITEINFO: Row 0 Column = type Value = table Column = name Value = quotes Column = tbl_name Value = quotes Column = rootpage Value = 2 Column = sql Value = CREATE TABLE quotes (id INTEGER PRIMARY KEY, text1 TEXT,  text2 TEXT, text3 TEXT, text4 TEXT, text5 TEXT)
11-15 11:33:17.111 8511-8511/mjt.usingrecyclerviews D/SQLITEINFO: Row 1 Column = type Value = table Column = name Value = android_metadata Column = tbl_name Value = android_metadata Column = rootpage Value = 3 Column = sql Value = CREATE TABLE android_metadata (locale TEXT)
11-15 11:33:17.111 8511-8511/mjt.usingrecyclerviews D/CURSOR 2 INFO: Row 0 Column = id Value = 1 Column = text1 Value = Some quote Column = text2 Value = Another quote Column = text3 Value = Yet another quote Column = text4 Value = This is a quote Column = text5 Value = Too many quotes
11-15 11:33:17.112 8511-8511/mjt.usingrecyclerviews D/CURSOR 2 INFO: Row 1 Column = id Value = 2 Column = text1 Value = Seccond quote Column = text2 Value = Third Quote Column = text3 Value = Fourth Quote Column = text4 Value = Fifth Quote Column = text5 Value = Sixth Quote
11-15 11:33:17.113 8511-8511/mjt.usingrecyclerviews D/CURSOR 3 INFO:  ID is1 ID is 1 TEXT1 is Some quote
</code>```

DatabaseHelper used for the above

As the packagename was hard coded in the Databasehelper changes had to be made. So rather than hard code the package the database path (without databasename and separatinf /) is obtained via context.getDatabasePath(DATABASE_NAME).getParent();. Just in case the databases folder/directory doesn't exist the changed helper will create the directories using File databasesdir =  new File(myContext.getDatabasePath(DATABASE_NAME).getParent());
            databasesdir.mkdirs();

The full Helper is :-

```<code>class dbHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "quotes.db";
    private  static final int SCHEMA_VERSION = 1;

    public SQLiteDatabase dbSglite;
    private String mDBPAth;

    private final Context myContext;

    public dbHelper(Context context) {
        super(context, DATABASE_NAME, null, SCHEMA_VERSION);
        this.myContext=context;
        this.mDBPAth = context.getDatabasePath(DATABASE_NAME).getParent();
    }

    @Override
    public void onCreate(SQLiteDatabase db){
        Log.d("ONCREATE","OnCreate Method Called.");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    public void createDatabase(){
        createDB();
    }

    private void createDB(){

        boolean dbExist = DBExists();

        if(!dbExist){
            copyDBFromResource();

        }
        dbSglite = getWritableDatabase();
    }

    private boolean DBExists(){

        SQLiteDatabase db = null;

        try {
            String databasePath = myContext.getDatabasePath(DATABASE_NAME).getPath();
            db = SQLiteDatabase.openDatabase(databasePath,null, SQLiteDatabase.OPEN_READWRITE);
            db.setLocale(Locale.getDefault());
            db.setLockingEnabled(true);
            db.setVersion(1);
        } catch (SQLiteException e) {

            Log.e("SqlHelper", "database not found");
        }

        if (db != null) {
            db.close();
        }
        return db != null;
    }

    private void copyDBFromResource() {
        InputStream inputStream = null;
        OutputStream outputStream = null;

        try {
            inputStream = myContext.getAssets().open(DATABASE_NAME);
            File databasesdir =  new File(myContext.getDatabasePath(DATABASE_NAME).getParent());
            databasesdir.mkdirs();
            outputStream = new FileOutputStream(mDBPAth+"/"+DATABASE_NAME);
            byte[] buffer = new byte[1024];
            int length;
            while ((length=inputStream.read(buffer))>0){
                outputStream.write(buffer, 0, length);
            }

            outputStream.flush();
            outputStream.close();
            inputStream.close();

        } catch (IOException e) {
            e.printStackTrace();
            throw new Error("Problem copying database.");
        }
    }

    public void openDataBase() throws SQLException {

        String myPath = myContext.getDatabasePath(DATABASE_NAME).getPath();
        dbSglite = SQLiteDatabase.openDatabase(myPath, null,
                SQLiteDatabase.OPEN_READWRITE);
    }
}
</code>```

Title: retrieve a record from sqlite

Body:
Sorry for my bad English.

I am new to Android Studio.

I have an external database. With columns id, text1, text2...text6
Somehow i succeeded to add that database to my application following a youtube tutorial. That works fine.

I added it to asset and in mainActivity is copied to data/data/mypackage/databases. I checked that in emulator file explorer.

Now I need to get data from that database but I can't figure it out how to do it.

id column is auto increment integer.
I have an array in my application containing x randomly generated integers in a certain range.
Now i want to make a query to database for the first integer from array and update textViews in my activity with the results. After user clicks on a button i need to send another query for next integer from the array and so on.

I don't know hot to open database, send query... I tried so many tutorials, searched on the Internet for the solution but non of them worked. Now i just confused.

I have experience in SQL. That shouldn't be a problem. In PHP and MySql it can be done with just few lines of code.
Can anybody help me to solve the problem.

This is my dbHelper

package com.examle.mydbapp;

import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.SQLException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.util.Log;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Locale;

class dbHelper extends SQLiteOpenHelper {

    private static final String DATABASE_PATH = "/data/data/com.example.mydbapp/databases/";
    private static final String DATABASE_NAME = "quotes.db";
    private  static final int SCHEMA_VERSION = 1;

    public SQLiteDatabase dbSglite;

    private final Context myContext;

    public dbHelper(Context context) {
        super(context, DATABASE_NAME, null, SCHEMA_VERSION);
        this.myContext=context;
       }

       @Override
    public void onCreate(SQLiteDatabase db){

       }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    public void createDatabase(){
        createDB();
    }

    private void createDB(){

        boolean dbExist = DBExists();

        if(!dbExist){
            this.getReadableDatabase();
            copyDBFromResource();

        }

    }

    private boolean DBExists(){

        SQLiteDatabase db = null;

        try {
            String databasePath = DATABASE_PATH+DATABASE_NAME;
            db = SQLiteDatabase.openDatabase(databasePath,null, SQLiteDatabase.OPEN_READWRITE);
            db.setLocale(Locale.getDefault());
            db.setLockingEnabled(true);
            db.setVersion(1);
        } catch (SQLiteException e) {

            Log.e("SqlHelper", "database not found");
        }

        if (db != null) {
            db.close();
        }
        return db != null ? true : false;

    }

    private void copyDBFromResource() {
        InputStream inputStream = null;
        OutputStream outputStream = null;
        String dbFilePath=DATABASE_PATH+DATABASE_NAME;

        try {
            inputStream = myContext.getAssets().open(DATABASE_NAME);
            outputStream = new FileOutputStream(dbFilePath);

            byte[] buffer = new byte[1024];
            int length;
            while ((length=inputStream.read(buffer))>0){
                outputStream.write(buffer, 0, length);
            }

            outputStream.flush();
            outputStream.close();
            inputStream.close();

        } catch (IOException e) {

            throw new Error("Problem copying database.");
        }

    }

    public void openDataBase() throws SQLException {

        String myPath = DATABASE_PATH + DATABASE_NAME;
        dbSglite = SQLiteDatabase.openDatabase(myPath, null,
                SQLiteDatabase.OPEN_READWRITE);

    }

}

Body:
in short, assuming you want to access the data from an activity, then

You could a) create an instance of the databasehelper b) invoke the databasehelper's createDatabase method and then c) retrieve an SQLiteDatabase instance by invoking the databasehelper's getWriteableDatbase method.

(You have probably already done a and b)

e.g. :-

    dbhlpr = new dbHelper(this);
    // Create the Database if need be
    dbhlpr.createDatabase();
    // An example of getting a instance outside of the helper
    SQLiteDatabase db = dbhlpr.getWritableDatabase();

You could also use SQLiteDatabase db = dbhlpr.dbSglite; instead of SQLiteDatabase db = dbhlpr.getWritableDatabase();

where in the above dbhlpr is a class variable defined using dbHelper dbhlpr;

You can then retrieve data from the tables by creating a Cursor(s). In the following examples (preceded by the previous example code and assuming that the table is called quotes) you could do something along the lines of the following examples :-

EX 1 (from sqlite_master)

    Cursor csr = db.query("sqlite_master",null,null,null,null,null,null);
    while (csr.moveToNext()) {
        String tblinfo = "Row " + csr.getPosition();
        for (int i=0; i < csr.getColumnCount(); i++) {
            tblinfo = tblinfo + " Column = " + csr.getColumnName(i) + " Value = " + csr.getString(i);
        }
        Log.d("SQLITEINFO",tblinfo);
    }
    csr.close();

EX 2 (all rows from quotes table)

    // Get and process data from the quotes table
    Cursor csr2 = db.query("quotes",null,null,null,null,null,null);
    while (csr2.moveToNext()) {
        String tblinfo = "Row " + csr2.getPosition();
        for (int i=0; i < csr2.getColumnCount(); i++) {
            tblinfo = tblinfo + " Column = " + csr2.getColumnName(i) + " Value = " + csr2.getString(i);
        }
        Log.d("CURSOR 2 INFO",tblinfo);
    }
    csr2.close();

EX 3 - Specific row using WHERE clause and placeholder ?

    // Get and processs data for a specific row according to id
    Cursor csr3 = db.query("quotes",null,"id=?",new String[]{"1"},null,null,null);
    if (csr3.moveToFirst()) {
        Log.d("CURSOR 3 INFO",
                " ID is" + csr3.getLong(0) +
                        " ID is " + csr3.getLong(csr3.getColumnIndex("id")) +
                        " TEXT1 is " + csr3.getString(csr3.getColumnIndex("text1"))
                // ..... etc
        );
    }
    csr3.close();

Things to note:-

An empty cursor is a valid cursor a; query will not return a null cursor.

Using column offsets, e.g. csr3.getLong(0) can be problematic, hence the alternative more flexible csr3.getLong(csr3.getColumnIndex("id"))

When a Cursor is returned from the query method it's position is before the first row (-1). To access the data you must use a move???? method e.g. csr3.moveToFirst(). The move???? methods return true if the move was made, false if it couldn't be made.

Testing

The above code has been tested using a DatabaseHelper that is very much the same as the DatabaseHelper provided in the question.

The Database was created outside of the app with a single table added named quotes with two rows of data added as per :-

Output from Test 1 run with no existing database :-

-15 11:30:20.066 8446-8446/? E/SQLiteLog: (14) cannot open file at line 30046 of [9491ba7d73]
11-15 11:30:20.066 8446-8446/? E/SQLiteLog: (14) os_unix.c:30046: (2) open(/data/data/mjt.usingrecyclerviews/databases/quotes.db) -
11-15 11:30:20.066 8446-8446/? E/SQLiteDatabase: Failed to open database '/data/data/mjt.usingrecyclerviews/databases/quotes.db'.
android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
    at android.database.sqlite.SQLiteConnection.nativeOpen(Native Method)
    at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:209)
    at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:193)
    at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:463)
    at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:185)
    at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:177)
    at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:806)
    at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:791)
    at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:694)
    at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:669)
    at mjt.usingrecyclerviews.dbHelper.DBExists(dbHelper.java:68)
    at mjt.usingrecyclerviews.dbHelper.createDB(dbHelper.java:54)
    at mjt.usingrecyclerviews.dbHelper.createDatabase(dbHelper.java:49)
    at mjt.usingrecyclerviews.MainActivity.onCreate(MainActivity.java:27)
    at android.app.Activity.performCreate(Activity.java:5990)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
    at android.app.ActivityThread.access$800(ActivityThread.java:151)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:135)
    at android.app.ActivityThread.main(ActivityThread.java:5254)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
11-15 11:30:20.066 8446-8446/? E/SqlHelper: database not found
11-15 11:30:20.093 8446-8446/? D/ONCREATE: OnCreate Method Called.
11-15 11:30:20.096 8446-8446/? D/SQLITEINFO: Row 0 Column = type Value = table Column = name Value = quotes Column = tbl_name Value = quotes Column = rootpage Value = 2 Column = sql Value = CREATE TABLE quotes (id INTEGER PRIMARY KEY, text1 TEXT,  text2 TEXT, text3 TEXT, text4 TEXT, text5 TEXT)
11-15 11:30:20.096 8446-8446/? D/SQLITEINFO: Row 1 Column = type Value = table Column = name Value = android_metadata Column = tbl_name Value = android_metadata Column = rootpage Value = 3 Column = sql Value = CREATE TABLE android_metadata (locale TEXT)
11-15 11:30:20.096 8446-8446/? D/CURSOR 2 INFO: Row 0 Column = id Value = 1 Column = text1 Value = Some quote Column = text2 Value = Another quote Column = text3 Value = Yet another quote Column = text4 Value = This is a quote Column = text5 Value = Too many quotes
11-15 11:30:20.096 8446-8446/? D/CURSOR 2 INFO: Row 1 Column = id Value = 2 Column = text1 Value = Seccond quote Column = text2 Value = Third Quote Column = text3 Value = Fourth Quote Column = text4 Value = Fifth Quote Column = text5 Value = Sixth Quote
11-15 11:30:20.096 8446-8446/? D/CURSOR 3 INFO:  ID is1 ID is 1 TEXT1 is Some quote

Note! File error was trapped and bypassed/handled (i.e. just because the database didn't exist)

Output from Test 2 - database exists :-

11-15 11:33:17.111 8511-8511/mjt.usingrecyclerviews D/SQLITEINFO: Row 0 Column = type Value = table Column = name Value = quotes Column = tbl_name Value = quotes Column = rootpage Value = 2 Column = sql Value = CREATE TABLE quotes (id INTEGER PRIMARY KEY, text1 TEXT,  text2 TEXT, text3 TEXT, text4 TEXT, text5 TEXT)
11-15 11:33:17.111 8511-8511/mjt.usingrecyclerviews D/SQLITEINFO: Row 1 Column = type Value = table Column = name Value = android_metadata Column = tbl_name Value = android_metadata Column = rootpage Value = 3 Column = sql Value = CREATE TABLE android_metadata (locale TEXT)
11-15 11:33:17.111 8511-8511/mjt.usingrecyclerviews D/CURSOR 2 INFO: Row 0 Column = id Value = 1 Column = text1 Value = Some quote Column = text2 Value = Another quote Column = text3 Value = Yet another quote Column = text4 Value = This is a quote Column = text5 Value = Too many quotes
11-15 11:33:17.112 8511-8511/mjt.usingrecyclerviews D/CURSOR 2 INFO: Row 1 Column = id Value = 2 Column = text1 Value = Seccond quote Column = text2 Value = Third Quote Column = text3 Value = Fourth Quote Column = text4 Value = Fifth Quote Column = text5 Value = Sixth Quote
11-15 11:33:17.113 8511-8511/mjt.usingrecyclerviews D/CURSOR 3 INFO:  ID is1 ID is 1 TEXT1 is Some quote

DatabaseHelper used for the above

As the packagename was hard coded in the Databasehelper changes had to be made. So rather than hard code the package the database path (without databasename and separatinf /) is obtained via context.getDatabasePath(DATABASE_NAME).getParent();. Just in case the databases folder/directory doesn't exist the changed helper will create the directories using File databasesdir =  new File(myContext.getDatabasePath(DATABASE_NAME).getParent());
            databasesdir.mkdirs();

The full Helper is :-

class dbHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "quotes.db";
    private  static final int SCHEMA_VERSION = 1;

    public SQLiteDatabase dbSglite;
    private String mDBPAth;

    private final Context myContext;

    public dbHelper(Context context) {
        super(context, DATABASE_NAME, null, SCHEMA_VERSION);
        this.myContext=context;
        this.mDBPAth = context.getDatabasePath(DATABASE_NAME).getParent();
    }

    @Override
    public void onCreate(SQLiteDatabase db){
        Log.d("ONCREATE","OnCreate Method Called.");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    public void createDatabase(){
        createDB();
    }

    private void createDB(){

        boolean dbExist = DBExists();

        if(!dbExist){
            copyDBFromResource();

        }
        dbSglite = getWritableDatabase();
    }

    private boolean DBExists(){

        SQLiteDatabase db = null;

        try {
            String databasePath = myContext.getDatabasePath(DATABASE_NAME).getPath();
            db = SQLiteDatabase.openDatabase(databasePath,null, SQLiteDatabase.OPEN_READWRITE);
            db.setLocale(Locale.getDefault());
            db.setLockingEnabled(true);
            db.setVersion(1);
        } catch (SQLiteException e) {

            Log.e("SqlHelper", "database not found");
        }

        if (db != null) {
            db.close();
        }
        return db != null;
    }

    private void copyDBFromResource() {
        InputStream inputStream = null;
        OutputStream outputStream = null;

        try {
            inputStream = myContext.getAssets().open(DATABASE_NAME);
            File databasesdir =  new File(myContext.getDatabasePath(DATABASE_NAME).getParent());
            databasesdir.mkdirs();
            outputStream = new FileOutputStream(mDBPAth+"/"+DATABASE_NAME);
            byte[] buffer = new byte[1024];
            int length;
            while ((length=inputStream.read(buffer))>0){
                outputStream.write(buffer, 0, length);
            }

            outputStream.flush();
            outputStream.close();
            inputStream.close();

        } catch (IOException e) {
            e.printStackTrace();
            throw new Error("Problem copying database.");
        }
    }

    public void openDataBase() throws SQLException {

        String myPath = myContext.getDatabasePath(DATABASE_NAME).getPath();
        dbSglite = SQLiteDatabase.openDatabase(myPath, null,
                SQLiteDatabase.OPEN_READWRITE);
    }
}


问:
How to create links that thereby change a turtle's breed?
I'm trying to model families. I would like to set it so that males meet females and form a link that will subsequently allow them to reproduce. I have not been able to figure out or find online how to code links to do this although I think it is quite basic.

I have as breeds males and females and husbands and wives. This code is to be run by males.

```<code>to marry
if hunger < 10 [create-link-with one-of females]
ask my-links [set breed wives]
end
</code>```

This returns a runtime error "you can't see breed to a non-link agentset". I thought this meant that I needed to use some kind of breed-command, e.g.

```<code>create-<breed>-link-with
</code>```

But

```<code>create-<wives>-link-with
</code>```

and

```<code>create-<a wife>-link-with
</code>```

etc all generate error messages.

I have also tried making the link directed, e.g.

```<code>  create-link-to one-of females
</code>```

but to no avail.

答:
You're having the turtles ask the links rather than the link-neighbors, I think that's all:

```<code>breed [ cats cat ]

to setup
ca
  crt 10 [ setxy random-pxcor random-pycor ]
reset-ticks
end

to go

  ask one-of turtles [
    create-link-with one-of other turtles
    ask link-neighbors [
      set breed cats
    ]
  ]
end
</code>```

Edit

I think this does what you want:

```<code>breed [ males male ]
breed [ husbands husband ]
breed [ females female ]
breed [ wives wife ]

males-own [ mood ]

to setup
  ca
  create-males 5 [
    set color green
    setxy abs random-pxcor / 2 random-pycor
    set mood "lonely"
  ]
  create-females 5 [
    set color white
    setxy ( abs random-pxcor ) / -2  random-pycor
  ]
  reset-ticks
end

to go
  if any? females [
    ask one-of males [
      set breed husbands
      create-link-with one-of females
      ask link-neighbors [
        set breed wives
      ]
    ]
  ]
end
</code>```

However, you may want to reconsider having the turtles switch breeds, and instead give them all a turtles-own boolean variable like married? that you can use as a flag. If you want to do the breed switching, do make sure any variables that you create for related breeds are identical- note that in the example above males have a mood variable but they lose that info when they change breeds to husbands.

Body:
I'm trying to model families. I would like to set it so that males meet females and form a link that will subsequently allow them to reproduce. I have not been able to figure out or find online how to code links to do this although I think it is quite basic.

I have as breeds males and females and husbands and wives. This code is to be run by males.

to marry
if hunger < 10 [create-link-with one-of females]
ask my-links [set breed wives]
end

This returns a runtime error "you can't see breed to a non-link agentset". I thought this meant that I needed to use some kind of breed-command, e.g.

create-<breed>-link-with

But

create-<wives>-link-with

and

create--link-with

etc all generate error messages.

I have also tried making the link directed, e.g.

  create-link-to one-of females

but to no avail.

Body:
You're having the turtles ask the links rather than the link-neighbors, I think that's all:

breed [ cats cat ]

to setup
ca
  crt 10 [ setxy random-pxcor random-pycor ]
reset-ticks
end

to go

  ask one-of turtles [
    create-link-with one-of other turtles
    ask link-neighbors [
      set breed cats
    ]
  ]
end

Edit

I think this does what you want:

breed [ males male ]
breed [ husbands husband ]
breed [ females female ]
breed [ wives wife ]

males-own [ mood ]

to setup
  ca
  create-males 5 [
    set color green
    setxy abs random-pxcor / 2 random-pycor
    set mood "lonely"
  ]
  create-females 5 [
    set color white
    setxy ( abs random-pxcor ) / -2  random-pycor
  ]
  reset-ticks
end

to go
  if any? females [
    ask one-of males [
      set breed husbands
      create-link-with one-of females
      ask link-neighbors [
        set breed wives
      ]
    ]
  ]
end

However, you may want to reconsider having the turtles switch breeds, and instead give them all a turtles-own boolean variable like married? that you can use as a flag. If you want to do the breed switching, do make sure any variables that you create for related breeds are identical- note that in the example above males have a mood variable but they lose that info when they change breeds to husbands.


问:
"For" loop better alternative
Having too many many "For" loop in my code increase complexity to my development, is there a better solution to For loop alternative?

In my code. I have used 50% of the time to loop array.

答:
Well if you have to work on Arrays alot check the reference under Array. They have very usefull functions like Array.every() or Array.forEach() or Array.map().

Maybe one of those is helpful to your concern.

Title: "For" loop better alternative