Programs & Examples On #Flatopc

Creating a button in Android Toolbar

You can actually put anything inside a toolbar. See the below code.

<android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:background="@color/colorPrimary">

</android.support.v7.widget.Toolbar>

Between the above toolbar tag you can put almost anything. That is the benefit of using a Toolbar.

Source: Android Toolbar Example

Java equivalent to C# extension methods

Java 8 now supports default methods, which are similar to C#'s extension methods.

Android: Create a toggle button with image and no text

  1. Can I replace the toggle text with an image

    No, we can not, although we can hide the text by overiding the default style of the toggle button, but still that won't give us a toggle button you want as we can't replace the text with an image.

  2. How can I make a normal toggle button

    Create a file ic_toggle in your res/drawable folder

    <selector xmlns:android="http://schemas.android.com/apk/res/android">
    
        <item android:state_checked="false"
              android:drawable="@drawable/ic_slide_switch_off" />
    
        <item android:state_checked="true"
              android:drawable="@drawable/ic_slide_switch_on" />
    
    </selector>
    

    Here @drawable/ic_slide_switch_on & @drawable/ic_slide_switch_off are images you create.

    Then create another file in the same folder, name it ic_toggle_bg

    <?xml version="1.0" encoding="utf-8"?>
    <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    
        <item android:id="@+android:id/background"  
              android:drawable="@android:color/transparent" />
    
        <item android:id="@+android:id/toggle"
              android:drawable="@drawable/ic_toggle" />
    
    </layer-list>
    

    Now add to your custom theme, (if you do not have one create a styles.xml file in your res/values/folder)

    <style name="Widget.Button.Toggle" parent="android:Widget">
       <item name="android:background">@drawable/ic_toggle_bg</item>
       <item name="android:disabledAlpha">?android:attr/disabledAlpha</item>
    </style>
    
    <style name="toggleButton"  parent="@android:Theme.Black">
       <item name="android:buttonStyleToggle">@style/Widget.Button.Toggle</item>
       <item name="android:textOn"></item>
       <item name="android:textOff"></item>
    </style>
    

    This creates a custom toggle button for you.

  3. How to use it

    Use the custom style and background in your view.

      <ToggleButton
            android:id="@+id/toggleButton"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="right"
            style="@style/toggleButton"
            android:background="@drawable/ic_toggle_bg"/>
    

www-data permissions?

sudo chown -R yourname:www-data cake

then

sudo chmod -R g+s cake

First command changes owner and group.

Second command adds s attribute which will keep new files and directories within cake having the same group permissions.

LINQ Orderby Descending Query

I think the second one should be

var itemList = (from t in ctn.Items
                where !t.Items && t.DeliverySelection
                select t).OrderByDescending(c => c.Delivery.SubmissionDate);

How do I make case-insensitive queries on Mongodb?

I have solved it like this.

 var thename = 'Andrew';
 db.collection.find({'name': {'$regex': thename,$options:'i'}});

If you want to query on 'case-insensitive exact matchcing' then you can go like this.

var thename =  '^Andrew$';
db.collection.find({'name': {'$regex': thename,$options:'i'}});

Remove characters from C# string

 string x = "My name @is ,Wan.;'; Wan";
 string modifiedString = x.Replace("@", "").Replace(",", "").Replace(".", "").Replace(";", "").Replace("'", "");

How to set full calendar to a specific start date when it's initialized for the 1st time?

You have it backwards. Display the calendar first, and then call gotoDate.

$('#calendar').fullCalendar({
  // Options
});

$('#calendar').fullCalendar('gotoDate', currentDate);

Add content to a new open window

in parent.html:

<script type="text/javascript">
    $(document).ready(function () {
        var output = "data";
        var OpenWindow = window.open("child.html", "mywin", '');
        OpenWindow.dataFromParent = output; // dataFromParent is a variable in child.html
        OpenWindow.init();
    });
</script>

in child.html:

<script type="text/javascript">
    var dataFromParent;    
    function init() {
        document.write(dataFromParent);
    }
</script>

check if a std::vector contains a certain object?

If searching for an element is important, I'd recommend std::set instead of std::vector. Using this:

std::find(vec.begin(), vec.end(), x) runs in O(n) time, but std::set has its own find() member (ie. myset.find(x)) which runs in O(log n) time - that's much more efficient with large numbers of elements

std::set also guarantees all the added elements are unique, which saves you from having to do anything like if not contained then push_back()....

Django - "no module named django.core.management"

My case I used pyCharm 5 on mac. I also had this problem and after running this command my problem was solved

sudo pip install django --upgrade 

How to set default text for a Tkinter Entry widget

Use Entry.insert. For example:

try:
    from tkinter import *  # Python 3.x
except Import Error:
    from Tkinter import *  # Python 2.x

root = Tk()
e = Entry(root)
e.insert(END, 'default text')
e.pack()
root.mainloop()

Or use textvariable option:

try:
    from tkinter import *  # Python 3.x
except Import Error:
    from Tkinter import *  # Python 2.x

root = Tk()
v = StringVar(root, value='default text')
e = Entry(root, textvariable=v)
e.pack()
root.mainloop()

How to center a table of the screen (vertically and horizontally)

Horizontal centering is easy. You just need to set both margins to "auto":

table {
  margin-left: auto;
  margin-right: auto;
}

Vertical centering usually is achieved by setting the parent element display type to table-cell and using vertical-align property. Assuming you have a <div class="wrapper"> around your table:

.wrapper {
  display: table-cell;
  vertical-align: middle;
}

More detailed information may be found on http://www.w3.org/Style/Examples/007/center

If you need support for older versions of Internet Explorer (I do not know what works in what version of this strange and rarely used browser ;-) ) then you may want to search the web for more information, like: http://www.jakpsatweb.cz/css/css-vertical-center-solution.html (just a first hit, which seems to mention IE)

Could not connect to SMTP host: smtp.gmail.com, port: 465, response: -1

Port 465 is for "smtp over SSL".

http://javamail.kenai.com/nonav/javadocs/com/sun/mail/smtp/package-summary.html

[...] For example, use
    props.put("mail.smtp.port", "888");
to set the mail.smtp.port property, which is of type int.

Note that if you're using the "smtps" protocol to access SMTP over SSL, 
all the properties would be named "mail.smtps.*"

Removing Data From ElasticSearch

For mass-delete by query you may use special delete by query API:

$ curl -XDELETE 'http://localhost:9200/twitter/tweet/_query' -d '{
    "query" : {
        "term" : { "user" : "kimchy" }
    }
}

In history that API was deleted and then reintroduced again

Who interesting it has long history.

  1. In first version of that answer I refer to documentation of elasticsearch version 1.6. In it that functionality was marked as deprecated but works good.
  2. In elasticsearch version 2.0 it was moved to separate plugin. And even reasons why it became plugin explained.
  3. And it again appeared in core API in version 5.0!

How to Query an NTP Server using C#?

The .NET Micro Framework Toolkit found in the CodePlex has an NTPClient. I have never used it myself but it looks good.

There is also another example located here.

One line if/else condition in linux shell scripting

You can use like bellow:

(( var0 = var1<98?9:21 ))

the same as

if [ "$var1" -lt 98 ]; then
   var0=9
else
   var0=21
fi

extends

condition?result-if-true:result-if-false

I found the interested thing on the book "Advanced Bash-Scripting Guide"

How do I create a message box with "Yes", "No" choices and a DialogResult?

DialogResult dr = MessageBox.Show("Are you happy now?", 
                      "Mood Test", MessageBoxButtons.YesNo);
switch(dr)
{
   case DialogResult.Yes:
      break;
   case DialogResult.No:
      break;
}

MessageBox class is what you are looking for.

Git log out user from command line

Try this on Windows:

cmdkey /delete:LegacyGeneric:target=git:https://github.com

How do I rename a column in a database table using SQL?

In Informix, you can use:

RENAME COLUMN TableName.OldName TO NewName;

This was implemented before the SQL standard addressed the issue - if it is addressed in the SQL standard. My copy of the SQL 9075:2003 standard does not show it as being standard (amongst other things, RENAME is not one of the keywords). I don't know whether it is actually in SQL 9075:2008.

jQuery: Setting select list 'selected' based on text, failing strangely

We can do it by searching the text in options of dropdown list and then by setting selected attribute to true.

This code is run in every environment.

 $("#numbers option:contains(" + inputText + ")").attr('selected', 'selected');

Convert DOS line endings to Linux line endings in Vim

To run directly in a Linux console:

vim file.txt +"set ff=unix" +wq

How to study design patterns?

Practice practice practice. I think 4 to 5 books is even an excessive reading exercise without some good amount of practising. Best way to do this, I believe, is to start refactoring your current projects using the patterns. Or if you don't have any projects you're actively working on then just do it your own way and then try refactoring to patterns.

You cannot appreciate them fully if you haven't suffered through the problems they solve. And please keep in mind that they are not silver bullets - you don't need to memorize them and push it hard to apply on the fly. My two cents..

Find first and last day for previous calendar month in SQL Server Reporting Services (VB.Net)

Randall, here are the VB expressions I found to work in SSRS to obtain the first and last days of any month, using the current month as a reference:

First day of last month:

=dateadd("m",-1,dateserial(year(Today),month(Today),1)) 

First day of this month:

=dateadd("m",0,dateserial(year(Today),month(Today),1)) 

First day of next month:

=dateadd("m",1,dateserial(year(Today),month(Today),1)) 

Last day of last month:

=dateadd("m",0,dateserial(year(Today),month(Today),0))

Last day of this month:

=dateadd("m",1,dateserial(year(Today),month(Today),0))

Last day of next month:

=dateadd("m",2,dateserial(year(Today),month(Today),0))

The MSDN documentation for the VisualBasic DateSerial(year,month,day) function explains that the function accepts values outside the expected range for the year, month, and day parameters. This allows you to specify useful date-relative values. For instance, a value of 0 for Day means "the last day of the preceding month". It makes sense: that's the day before day 1 of the current month.

Change directory command in Docker?

I was wondering if two times WORKDIR will work or not, but it worked :)

FROM ubuntu:18.04

RUN apt-get update && \
    apt-get install -y python3.6

WORKDIR /usr/src

COPY ./ ./

WORKDIR /usr/src/src

CMD ["python3", "app.py"]

Formatting struct timespec

You can pass the tv_sec parameter to some of the formatting function. Have a look at gmtime, localtime(). Then look at snprintf.

Why do we use web.xml?

It's the default configuration for a Java web application; it's required.

WicketFilter

is applied to every HTTP request that's sent to this web app.

Get attribute name value of <input>

var value_input = $("input[name*='xxxx']").val();

Role/Purpose of ContextLoaderListener in Spring?

The blog, "Purpose of ContextLoaderListener – Spring MVC" gives a very good explanation.

According to it, Application-Contexts are hierarchial and hence DispatcherSerlvet's context becomes the child of ContextLoaderListener's context. Due to which, technology being used in the controller layer (Struts or Spring MVC) can independent of root context created ContextLoaderListener.

How can Print Preview be called from Javascript?

You can't, Print Preview is a feature of a browser, and therefore should be protected from being called by JavaScript as it would be a security risk.

That's why your example uses Active X, which bypasses the JavaScript security issues.

So instead use the print stylesheet that you already should have and show it for media=screen,print instead of media=print.

Read Alist Apart: Going to Print for a good article on the subject of print stylesheets.

How to get a single value from FormGroup

You can get value like this

this.form.controls['your form control name'].value

python 3.x ImportError: No module named 'cStringIO'

I had the same issue because my file was called email.py. I renamed the file and the issue disappeared.

CSS: how to get scrollbars for div inside container of fixed height

FWIW, here is my approach = a simple one that works for me:

<div id="outerDivWrapper">
   <div id="outerDiv">
      <div id="scrollableContent">
blah blah blah
      </div>
   </div>
</div>

html, body {
   height: 100%;
   margin: 0em;
}

#outerDivWrapper, #outerDiv {
   height: 100%;
   margin: 0em;
}

#scrollableContent {
   height: 100%;
   margin: 0em;
   overflow-y: auto;
}

How to get a password from a shell script without echoing

For anyone needing to prompt for a password, you may be interested in using encpass.sh. This is a script I wrote for similar purposes of capturing a secret at runtime and then encrypting it for subsequent occasions. Subsequent runs do not prompt for the password as it will just use the encrypted value from disk.

It stores the encrypted passwords in a hidden folder under the user's home directory or in a custom folder that you can define through the environment variable ENCPASS_HOME_DIR. It is designed to be POSIX compliant and has an MIT License, so it can be used even in corporate enterprise environments. My company, Plyint LLC, maintains the script and occasionally releases updates. Pull requests are also welcome, if you find an issue. :)

To use it in your scripts simply source encpass.sh in your script and call the get_secret function. I'm including a copy of the script below for easy visibility.

#!/bin/sh
################################################################################
# Copyright (c) 2020 Plyint, LLC <[email protected]>. All Rights Reserved.
# This file is licensed under the MIT License (MIT). 
# Please see LICENSE.txt for more information.
# 
# DESCRIPTION: 
# This script allows a user to encrypt a password (or any other secret) at 
# runtime and then use it, decrypted, within a script.  This prevents shoulder 
# surfing passwords and avoids storing the password in plain text, which could 
# inadvertently be sent to or discovered by an individual at a later date.
#
# This script generates an AES 256 bit symmetric key for each script (or user-
# defined bucket) that stores secrets.  This key will then be used to encrypt 
# all secrets for that script or bucket.  encpass.sh sets up a directory 
# (.encpass) under the user's home directory where keys and secrets will be 
# stored.
#
# For further details, see README.md or run "./encpass ?" from the command line.
#
################################################################################

encpass_checks() {
    if [ -n "$ENCPASS_CHECKS" ]; then
        return
    fi

    if [ ! -x "$(command -v openssl)" ]; then
        echo "Error: OpenSSL is not installed or not accessible in the current path." \
            "Please install it and try again." >&2
        exit 1
    fi

    if [ -z "$ENCPASS_HOME_DIR" ]; then
        ENCPASS_HOME_DIR=$(encpass_get_abs_filename ~)/.encpass
    fi

    if [ ! -d "$ENCPASS_HOME_DIR" ]; then
        mkdir -m 700 "$ENCPASS_HOME_DIR"
        mkdir -m 700 "$ENCPASS_HOME_DIR/keys"
        mkdir -m 700 "$ENCPASS_HOME_DIR/secrets"
    fi

    if [ "$(basename "$0")" != "encpass.sh" ]; then
        encpass_include_init "$1" "$2"
    fi

    ENCPASS_CHECKS=1
}

# Initializations performed when the script is included by another script
encpass_include_init() {
    if [ -n "$1" ] && [ -n "$2" ]; then
        ENCPASS_BUCKET=$1
        ENCPASS_SECRET_NAME=$2
    elif [ -n "$1" ]; then
        ENCPASS_BUCKET=$(basename "$0")
        ENCPASS_SECRET_NAME=$1
    else
        ENCPASS_BUCKET=$(basename "$0")
        ENCPASS_SECRET_NAME="password"
    fi
}

encpass_generate_private_key() {
    ENCPASS_KEY_DIR="$ENCPASS_HOME_DIR/keys/$ENCPASS_BUCKET"

    if [ ! -d "$ENCPASS_KEY_DIR" ]; then
        mkdir -m 700 "$ENCPASS_KEY_DIR"
    fi

    if [ ! -f "$ENCPASS_KEY_DIR/private.key" ]; then
        (umask 0377 && printf "%s" "$(openssl rand -hex 32)" >"$ENCPASS_KEY_DIR/private.key")
    fi
}

encpass_get_private_key_abs_name() {
    ENCPASS_PRIVATE_KEY_ABS_NAME="$ENCPASS_HOME_DIR/keys/$ENCPASS_BUCKET/private.key"

    if [ "$1" != "nogenerate" ]; then 
        if [ ! -f "$ENCPASS_PRIVATE_KEY_ABS_NAME" ]; then
            encpass_generate_private_key
        fi
    fi
}

encpass_get_secret_abs_name() {
    ENCPASS_SECRET_ABS_NAME="$ENCPASS_HOME_DIR/secrets/$ENCPASS_BUCKET/$ENCPASS_SECRET_NAME.enc"

    if [ "$3" != "nocreate" ]; then 
        if [ ! -f "$ENCPASS_SECRET_ABS_NAME" ]; then
            set_secret "$1" "$2"
        fi
    fi
}

get_secret() {
    encpass_checks "$1" "$2"
    encpass_get_private_key_abs_name
    encpass_get_secret_abs_name "$1" "$2"
    encpass_decrypt_secret
}

set_secret() {
    encpass_checks "$1" "$2"

    if [ "$3" != "reuse" ] || { [ -z "$ENCPASS_SECRET_INPUT" ] && [ -z "$ENCPASS_CSECRET_INPUT" ]; }; then
        echo "Enter $ENCPASS_SECRET_NAME:" >&2
        stty -echo
        read -r ENCPASS_SECRET_INPUT
        stty echo
        echo "Confirm $ENCPASS_SECRET_NAME:" >&2
        stty -echo
        read -r ENCPASS_CSECRET_INPUT
        stty echo
    fi

    if [ "$ENCPASS_SECRET_INPUT" = "$ENCPASS_CSECRET_INPUT" ]; then
        encpass_get_private_key_abs_name
        ENCPASS_SECRET_DIR="$ENCPASS_HOME_DIR/secrets/$ENCPASS_BUCKET"

        if [ ! -d "$ENCPASS_SECRET_DIR" ]; then
            mkdir -m 700 "$ENCPASS_SECRET_DIR"
        fi

        printf "%s" "$(openssl rand -hex 16)" >"$ENCPASS_SECRET_DIR/$ENCPASS_SECRET_NAME.enc"

        ENCPASS_OPENSSL_IV="$(cat "$ENCPASS_SECRET_DIR/$ENCPASS_SECRET_NAME.enc")"

        echo "$ENCPASS_SECRET_INPUT" | openssl enc -aes-256-cbc -e -a -iv \
            "$ENCPASS_OPENSSL_IV" -K \
            "$(cat "$ENCPASS_HOME_DIR/keys/$ENCPASS_BUCKET/private.key")" 1>> \
                    "$ENCPASS_SECRET_DIR/$ENCPASS_SECRET_NAME.enc"
    else
        echo "Error: secrets do not match.  Please try again." >&2
        exit 1
    fi
}

encpass_get_abs_filename() {
    # $1 : relative filename
    filename="$1"
    parentdir="$(dirname "${filename}")"

    if [ -d "${filename}" ]; then
        cd "${filename}" && pwd
    elif [ -d "${parentdir}" ]; then
        echo "$(cd "${parentdir}" && pwd)/$(basename "${filename}")"
    fi
}

encpass_decrypt_secret() {
    if [ -f "$ENCPASS_PRIVATE_KEY_ABS_NAME" ]; then
        ENCPASS_DECRYPT_RESULT="$(dd if="$ENCPASS_SECRET_ABS_NAME" ibs=1 skip=32 2> /dev/null | openssl enc -aes-256-cbc \
            -d -a -iv "$(head -c 32 "$ENCPASS_SECRET_ABS_NAME")" -K "$(cat "$ENCPASS_PRIVATE_KEY_ABS_NAME")" 2> /dev/null)"
        if [ ! -z "$ENCPASS_DECRYPT_RESULT" ]; then
            echo "$ENCPASS_DECRYPT_RESULT"
        else
            # If a failed unlock command occurred and the user tries to show the secret
            # Present either locked or decrypt command
            if [ -f "$ENCPASS_HOME_DIR/keys/$ENCPASS_BUCKET/private.lock" ]; then 
            echo "**Locked**"
            else
                # The locked file wasn't present as expected.  Let's display a failure
            echo "Error: Failed to decrypt"
            fi
        fi
    elif [ -f "$ENCPASS_HOME_DIR/keys/$ENCPASS_BUCKET/private.lock" ]; then
        echo "**Locked**"
    else
        echo "Error: Unable to decrypt. The key file \"$ENCPASS_PRIVATE_KEY_ABS_NAME\" is not present."
    fi
}


##########################################################
# COMMAND LINE MANAGEMENT SUPPORT
# -------------------------------
# If you don't need to manage the secrets for the scripts
# with encpass.sh you can delete all code below this point
# in order to significantly reduce the size of encpass.sh.
# This is useful if you want to bundle encpass.sh with
# your existing scripts and just need the retrieval
# functions.
##########################################################

encpass_show_secret() {
    encpass_checks
    ENCPASS_BUCKET=$1

    encpass_get_private_key_abs_name "nogenerate"

    if [ ! -z "$2" ]; then
        ENCPASS_SECRET_NAME=$2
        encpass_get_secret_abs_name "$1" "$2" "nocreate"
        if [ -z "$ENCPASS_SECRET_ABS_NAME" ]; then
            echo "No secret named $2 found for bucket $1."
            exit 1
        fi

        encpass_decrypt_secret
    else
        ENCPASS_FILE_LIST=$(ls -1 "$ENCPASS_HOME_DIR"/secrets/"$1")
        for ENCPASS_F in $ENCPASS_FILE_LIST; do
            ENCPASS_SECRET_NAME=$(basename "$ENCPASS_F" .enc)

            encpass_get_secret_abs_name "$1" "$ENCPASS_SECRET_NAME" "nocreate"
            if [ -z "$ENCPASS_SECRET_ABS_NAME" ]; then
                echo "No secret named $ENCPASS_SECRET_NAME found for bucket $1."
                exit 1
            fi

            echo "$ENCPASS_SECRET_NAME = $(encpass_decrypt_secret)"
        done
    fi
}

encpass_getche() {
        old=$(stty -g)
        stty raw min 1 time 0
        printf '%s' "$(dd bs=1 count=1 2>/dev/null)"
        stty "$old"
}

encpass_remove() {
    if [ ! -n "$ENCPASS_FORCE_REMOVE" ]; then
        if [ ! -z "$ENCPASS_SECRET" ]; then
            printf "Are you sure you want to remove the secret \"%s\" from bucket \"%s\"? [y/N]" "$ENCPASS_SECRET" "$ENCPASS_BUCKET"
        else
            printf "Are you sure you want to remove the bucket \"%s?\" [y/N]" "$ENCPASS_BUCKET"
        fi

        ENCPASS_CONFIRM="$(encpass_getche)"
        printf "\n"
        if [ "$ENCPASS_CONFIRM" != "Y" ] && [ "$ENCPASS_CONFIRM" != "y" ]; then
            exit 0
        fi
    fi

    if [ ! -z "$ENCPASS_SECRET" ]; then
        rm -f "$1"
        printf "Secret \"%s\" removed from bucket \"%s\".\n" "$ENCPASS_SECRET" "$ENCPASS_BUCKET"
    else
        rm -Rf "$ENCPASS_HOME_DIR/keys/$ENCPASS_BUCKET"
        rm -Rf "$ENCPASS_HOME_DIR/secrets/$ENCPASS_BUCKET"
        printf "Bucket \"%s\" removed.\n" "$ENCPASS_BUCKET"
    fi
}

encpass_save_err() {
    if read -r x; then
        { printf "%s\n" "$x"; cat; } > "$1"
    elif [ "$x" != "" ]; then
        printf "%s" "$x" > "$1"
    fi
}

encpass_help() {
less << EOF
NAME:
    encpass.sh - Use encrypted passwords in shell scripts

DESCRIPTION: 
    A lightweight solution for using encrypted passwords in shell scripts 
    using OpenSSL. It allows a user to encrypt a password (or any other secret)
    at runtime and then use it, decrypted, within a script. This prevents
    shoulder surfing passwords and avoids storing the password in plain text, 
    within a script, which could inadvertently be sent to or discovered by an 
    individual at a later date.

    This script generates an AES 256 bit symmetric key for each script 
    (or user-defined bucket) that stores secrets. This key will then be used 
    to encrypt all secrets for that script or bucket.

    Subsequent calls to retrieve a secret will not prompt for a secret to be 
    entered as the file with the encrypted value already exists.

    Note: By default, encpass.sh sets up a directory (.encpass) under the 
    user's home directory where keys and secrets will be stored.  This directory
    can be overridden by setting the environment variable ENCPASS_HOME_DIR to a
    directory of your choice.

    ~/.encpass (or the directory specified by ENCPASS_HOME_DIR) will contain 
    the following subdirectories:
      - keys (Holds the private key for each script/bucket)
      - secrets (Holds the secrets stored for each script/bucket)

USAGE:
    To use the encpass.sh script in an existing shell script, source the script 
    and then call the get_secret function.

    Example:

        #!/bin/sh
        . encpass.sh
        password=\$(get_secret)

    When no arguments are passed to the get_secret function,
    then the bucket name is set to the name of the script and
    the secret name is set to "password".

    There are 2 other ways to call get_secret:

      Specify the secret name:
      Ex: \$(get_secret user)
        - bucket name = <script name>
        - secret name = "user"

      Specify both the secret name and bucket name:
      Ex: \$(get_secret personal user)
        - bucket name = "personal"
        - secret name = "user"

    encpass.sh also provides a command line interface to manage the secrets.
    To invoke a command, pass it as an argument to encpass.sh from the shell.

        $ encpass.sh [COMMAND]

    See the COMMANDS section below for a list of available commands.  Wildcard
    handling is implemented for secret and bucket names.  This enables
    performing operations like adding/removing a secret to/from multiple buckets
        at once.

COMMANDS:
    add [-f] <bucket> <secret>
        Add a secret to the specified bucket.  The bucket will be created
        if it does not already exist. If a secret with the same name already
        exists for the specified bucket, then the user will be prompted to
        confirm overwriting the value.  If the -f option is passed, then the
        add operation will perform a forceful overwrite of the value. (i.e. no
        prompt)

    list|ls [<bucket>]
        Display the names of the secrets held in the bucket.  If no bucket
        is specified, then the names of all existing buckets will be
        displayed.

    lock
        Locks all keys used by encpass.sh using a password.  The user
        will be prompted to enter a password and confirm it.  A user
        should take care to securely store the password.  If the password
        is lost then keys can not be unlocked.  When keys are locked,
        secrets can not be retrieved. (e.g. the output of the values
        in the "show" command will be encrypted/garbage)

    remove|rm [-f] <bucket> [<secret>]
        Remove a secret from the specified bucket.  If only a bucket is
        specified then the entire bucket (i.e. all secrets and keys) will
        be removed.  By default the user is asked to confirm the removal of
        the secret or the bucket.  If the -f option is passed then a 
        forceful removal will be performed.  (i.e. no prompt)

    show [<bucket>] [<secret>]
        Show the unencrypted value of the secret from the specified bucket.
        If no secret is specified then all secrets for the bucket are displayed.

    update <bucket> <secret>
        Updates a secret in the specified bucket.  This command is similar
        to using an "add -f" command, but it has a safety check to only 
        proceed if the specified secret exists.  If the secret, does not
        already exist, then an error will be reported. There is no forceable
        update implemented.  Use "add -f" for any required forceable update
        scenarios.

    unlock
        Unlocks all the keys for encpass.sh.  The user will be prompted to 
        enter the password and confirm it.

    dir
        Prints out the current value of the ENCPASS_HOME_DIR environment variable.

    help|--help|usage|--usage|?
        Display this help message.
EOF
}

# Subcommands for cli support
case "$1" in
    add )
        shift
        while getopts ":f" ENCPASS_OPTS; do
            case "$ENCPASS_OPTS" in
                f ) ENCPASS_FORCE_ADD=1;;
            esac
        done

        encpass_checks

        if [ -n "$ENCPASS_FORCE_ADD" ]; then
            shift $((OPTIND-1))
        fi

        if [ ! -z "$1" ] && [ ! -z "$2" ]; then
            # Allow globbing
            # shellcheck disable=SC2027,SC2086
            ENCPASS_ADD_LIST="$(ls -1d "$ENCPASS_HOME_DIR/secrets/"$1"" 2>/dev/null)"
            if [ -z "$ENCPASS_ADD_LIST" ]; then
                ENCPASS_ADD_LIST="$1"
            fi

            for ENCPASS_ADD_F in $ENCPASS_ADD_LIST; do
                ENCPASS_ADD_DIR="$(basename "$ENCPASS_ADD_F")"
                ENCPASS_BUCKET="$ENCPASS_ADD_DIR"
                if [ ! -n "$ENCPASS_FORCE_ADD" ] && [ -f "$ENCPASS_ADD_F/$2.enc" ]; then
                    echo "Warning: A secret with the name \"$2\" already exists for bucket $ENCPASS_BUCKET."
                    echo "Would you like to overwrite the value? [y/N]"

                    ENCPASS_CONFIRM="$(encpass_getche)"
                    if [ "$ENCPASS_CONFIRM" != "Y" ] && [ "$ENCPASS_CONFIRM" != "y" ]; then
                        continue
                    fi
                fi

                ENCPASS_SECRET_NAME="$2"
                echo "Adding secret \"$ENCPASS_SECRET_NAME\" to bucket \"$ENCPASS_BUCKET\"..."
                set_secret "$ENCPASS_BUCKET" "$ENCPASS_SECRET_NAME" "reuse"
            done
        else
            echo "Error: A bucket name and secret name must be provided when adding a secret."
            exit 1
        fi
        ;;
    update )
        shift

        encpass_checks
        if [ ! -z "$1" ] && [ ! -z "$2" ]; then

            ENCPASS_SECRET_NAME="$2"
            # Allow globbing
            # shellcheck disable=SC2027,SC2086
            ENCPASS_UPDATE_LIST="$(ls -1d "$ENCPASS_HOME_DIR/secrets/"$1"" 2>/dev/null)"

            for ENCPASS_UPDATE_F in $ENCPASS_UPDATE_LIST; do
                # Allow globbing
                # shellcheck disable=SC2027,SC2086
                if [ -f "$ENCPASS_UPDATE_F/"$2".enc" ]; then
                        ENCPASS_UPDATE_DIR="$(basename "$ENCPASS_UPDATE_F")"
                        ENCPASS_BUCKET="$ENCPASS_UPDATE_DIR"
                        echo "Updating secret \"$ENCPASS_SECRET_NAME\" to bucket \"$ENCPASS_BUCKET\"..."
                        set_secret "$ENCPASS_BUCKET" "$ENCPASS_SECRET_NAME" "reuse"
                else
                    echo "Error: A secret with the name \"$2\" does not exist for bucket $1."
                    exit 1
                fi
            done
        else
            echo "Error: A bucket name and secret name must be provided when updating a secret."
            exit 1
        fi
        ;;
    rm|remove )
        shift
        encpass_checks

        while getopts ":f" ENCPASS_OPTS; do
            case "$ENCPASS_OPTS" in
                f ) ENCPASS_FORCE_REMOVE=1;;
            esac
        done

        if [ -n "$ENCPASS_FORCE_REMOVE" ]; then
            shift $((OPTIND-1))
        fi

        if [ -z "$1" ]; then 
            echo "Error: A bucket must be specified for removal."
        fi

        # Allow globbing
        # shellcheck disable=SC2027,SC2086
        ENCPASS_REMOVE_BKT_LIST="$(ls -1d "$ENCPASS_HOME_DIR/secrets/"$1"" 2>/dev/null)"
        if [ ! -z "$ENCPASS_REMOVE_BKT_LIST" ]; then
            for ENCPASS_REMOVE_B in $ENCPASS_REMOVE_BKT_LIST; do

                ENCPASS_BUCKET="$(basename "$ENCPASS_REMOVE_B")"
                if [ ! -z "$2" ]; then
                    # Removing secrets for a specified bucket
                    # Allow globbing
                    # shellcheck disable=SC2027,SC2086
                    ENCPASS_REMOVE_LIST="$(ls -1p "$ENCPASS_REMOVE_B/"$2".enc" 2>/dev/null)"

                    if [ -z "$ENCPASS_REMOVE_LIST" ]; then
                        echo "Error: No secrets found for $2 in bucket $ENCPASS_BUCKET."
                        exit 1
                    fi

                    for ENCPASS_REMOVE_F in $ENCPASS_REMOVE_LIST; do
                        ENCPASS_SECRET="$2"
                        encpass_remove "$ENCPASS_REMOVE_F"
                    done
                else
                    # Removing a specified bucket
                    encpass_remove
                fi

            done
        else
            echo "Error: The bucket named $1 does not exist."
            exit 1
        fi
        ;;
    show )
        shift
        encpass_checks
        if [ -z "$1" ]; then
            ENCPASS_SHOW_DIR="*"
        else
            ENCPASS_SHOW_DIR=$1
        fi

        if [ ! -z "$2" ]; then
            # Allow globbing
            # shellcheck disable=SC2027,SC2086
            if [ -f "$(encpass_get_abs_filename "$ENCPASS_HOME_DIR/secrets/$ENCPASS_SHOW_DIR/"$2".enc")" ]; then
                encpass_show_secret "$ENCPASS_SHOW_DIR" "$2"
            fi
        else
            # Allow globbing
            # shellcheck disable=SC2027,SC2086
            ENCPASS_SHOW_LIST="$(ls -1d "$ENCPASS_HOME_DIR/secrets/"$ENCPASS_SHOW_DIR"" 2>/dev/null)"

            if [ -z "$ENCPASS_SHOW_LIST" ]; then
                if [ "$ENCPASS_SHOW_DIR" = "*" ]; then
                    echo "Error: No buckets exist."
                else
                    echo "Error: Bucket $1 does not exist."
                fi
                exit 1
            fi

            for ENCPASS_SHOW_F in $ENCPASS_SHOW_LIST; do
                ENCPASS_SHOW_DIR="$(basename "$ENCPASS_SHOW_F")"
                echo "$ENCPASS_SHOW_DIR:"
                encpass_show_secret "$ENCPASS_SHOW_DIR"
                echo " "
            done
        fi
        ;;
    ls|list )
        shift
        encpass_checks
        if [ ! -z "$1" ]; then
            # Allow globbing
            # shellcheck disable=SC2027,SC2086
            ENCPASS_FILE_LIST="$(ls -1p "$ENCPASS_HOME_DIR/secrets/"$1"" 2>/dev/null)"

            if [ -z "$ENCPASS_FILE_LIST" ]; then
                # Allow globbing
                # shellcheck disable=SC2027,SC2086
                ENCPASS_DIR_EXISTS="$(ls -d "$ENCPASS_HOME_DIR/secrets/"$1"" 2>/dev/null)"
                if [ ! -z "$ENCPASS_DIR_EXISTS" ]; then
                    echo "Bucket $1 is empty."
                else
                    echo "Error: Bucket $1 does not exist."
                fi
                exit 1
            fi

            ENCPASS_NL=""
            for ENCPASS_F in $ENCPASS_FILE_LIST; do
                if [ -d "${ENCPASS_F%:}" ]; then
                    printf "$ENCPASS_NL%s\n" "$(basename "$ENCPASS_F")"
                    ENCPASS_NL="\n"
                else
                    printf "%s\n" "$(basename "$ENCPASS_F" .enc)"
                fi
            done
        else
            # Allow globbing
            # shellcheck disable=SC2027,SC2086
            ENCPASS_BUCKET_LIST="$(ls -1p "$ENCPASS_HOME_DIR/secrets/"$1"" 2>/dev/null)"
            for ENCPASS_C in $ENCPASS_BUCKET_LIST; do
                if [ -d "${ENCPASS_C%:}" ]; then
                    printf "\n%s" "\n$(basename "$ENCPASS_C")"
                else
                    basename "$ENCPASS_C" .enc
                fi
            done
        fi
        ;;
    lock )
        shift
        encpass_checks

        echo "************************!!!WARNING!!!*************************" >&2
        echo "* You are about to lock your keys with a password.           *" >&2
        echo "* You will not be able to use your secrets again until you   *" >&2
        echo "* unlock the keys with the same password. It is important    *" >&2
        echo "* that you securely store the password, so you can recall it *" >&2
        echo "* in the future.  If you forget your password you will no    *" >&2
        echo "* longer be able to access your secrets.                     *" >&2
        echo "************************!!!WARNING!!!*************************" >&2

        printf "\n%s\n" "About to lock keys held in directory $ENCPASS_HOME_DIR/keys/"

        printf "\nEnter Password to lock keys:" >&2
        stty -echo
        read -r ENCPASS_KEY_PASS
        printf "\nConfirm Password:" >&2
        read -r ENCPASS_CKEY_PASS
        printf "\n"
        stty echo

        if [ -z "$ENCPASS_KEY_PASS" ]; then
            echo "Error: You must supply a password value."
            exit 1
        fi

        if [ "$ENCPASS_KEY_PASS" = "$ENCPASS_CKEY_PASS" ]; then
            ENCPASS_NUM_KEYS_LOCKED=0
            ENCPASS_KEYS_LIST="$(ls -1d "$ENCPASS_HOME_DIR/keys/"*"/" 2>/dev/null)"
            for ENCPASS_KEY_F in $ENCPASS_KEYS_LIST; do

                if [ -d "${ENCPASS_KEY_F%:}" ]; then
                    ENCPASS_KEY_NAME="$(basename "$ENCPASS_KEY_F")"
                    ENCPASS_KEY_VALUE=""
                    if [ -f "$ENCPASS_KEY_F/private.key" ]; then
                        ENCPASS_KEY_VALUE="$(cat "$ENCPASS_KEY_F/private.key")"
                        if [ ! -f "$ENCPASS_KEY_F/private.lock" ]; then
                        echo "Locking key $ENCPASS_KEY_NAME..."
                        else
                          echo "Error: The key $ENCPASS_KEY_NAME appears to have been previously locked."
                            echo "       The current key file may hold a bad value. Exiting to avoid encrypting"
                            echo "       a bad value and overwriting the lock file."
                            exit 1
                        fi
                    else
                        echo "Error: Private key file ${ENCPASS_KEY_F}private.key missing for bucket $ENCPASS_KEY_NAME."
                        exit 1
                    fi
                    if [ ! -z "$ENCPASS_KEY_VALUE" ]; then
                        openssl enc -aes-256-cbc -pbkdf2 -iter 10000 -salt -in "$ENCPASS_KEY_F/private.key" -out "$ENCPASS_KEY_F/private.lock" -k "$ENCPASS_KEY_PASS"
                        if [ -f "$ENCPASS_KEY_F/private.key" ] && [ -f "$ENCPASS_KEY_F/private.lock" ]; then
                            # Both the key and lock file exist.  We can remove the key file now
                            rm -f "$ENCPASS_KEY_F/private.key"
                            echo "Locked key $ENCPASS_KEY_NAME."
                            ENCPASS_NUM_KEYS_LOCKED=$(( ENCPASS_NUM_KEYS_LOCKED + 1 ))
                        else
                            echo "Error: The key fle and/or lock file were not found as expected for key $ENCPASS_KEY_NAME."
                        fi
                    else
                        echo "Error: No key value found for the $ENCPASS_KEY_NAME key."
                        exit 1
                    fi
                fi
            done
            echo "Locked $ENCPASS_NUM_KEYS_LOCKED keys."
        else
            echo "Error: Passwords do not match."
        fi
        ;;
    unlock )
        shift
        encpass_checks

        printf "%s\n" "About to unlock keys held in the $ENCPASS_HOME_DIR/keys/ directory."

        printf "\nEnter Password to unlock keys: " >&2
        stty -echo
        read -r ENCPASS_KEY_PASS
        printf "\n"
        stty echo

        if [ ! -z "$ENCPASS_KEY_PASS" ]; then
            ENCPASS_NUM_KEYS_UNLOCKED=0
            ENCPASS_KEYS_LIST="$(ls -1d "$ENCPASS_HOME_DIR/keys/"*"/" 2>/dev/null)"
            for ENCPASS_KEY_F in $ENCPASS_KEYS_LIST; do

                if [ -d "${ENCPASS_KEY_F%:}" ]; then
                    ENCPASS_KEY_NAME="$(basename "$ENCPASS_KEY_F")"
                    echo "Unlocking key $ENCPASS_KEY_NAME..."
                    if [ -f "$ENCPASS_KEY_F/private.key" ] && [ ! -f "$ENCPASS_KEY_F/private.lock" ]; then
                        echo "Error: Key $ENCPASS_KEY_NAME appears to be unlocked already."
                        exit 1
                    fi

                    if [ -f "$ENCPASS_KEY_F/private.lock" ]; then
                        # Remove the failed file in case previous decryption attempts were unsuccessful
                        rm -f "$ENCPASS_KEY_F/failed" 2>/dev/null

                        # Decrypt key. Log any failure to the "failed" file.
                        openssl enc -aes-256-cbc -d -pbkdf2 -iter 10000 -salt \
                            -in "$ENCPASS_KEY_F/private.lock" -out "$ENCPASS_KEY_F/private.key" \
                            -k "$ENCPASS_KEY_PASS" 2>&1 | encpass_save_err "$ENCPASS_KEY_F/failed"

                        if [ ! -f "$ENCPASS_KEY_F/failed" ]; then
                            # No failure has occurred.
                          if [ -f "$ENCPASS_KEY_F/private.key" ] && [ -f "$ENCPASS_KEY_F/private.lock" ]; then
                              # Both the key and lock file exist.  We can remove the lock file now.
                              rm -f "$ENCPASS_KEY_F/private.lock"
                              echo "Unlocked key $ENCPASS_KEY_NAME."
                              ENCPASS_NUM_KEYS_UNLOCKED=$(( ENCPASS_NUM_KEYS_UNLOCKED + 1 ))
                          else
                              echo "Error: The key file and/or lock file were not found as expected for key $ENCPASS_KEY_NAME."
                          fi
                        else
                          printf "Error: Failed to unlock key %s.\n" "$ENCPASS_KEY_NAME"
                            printf "       Please view %sfailed for details.\n" "$ENCPASS_KEY_F"
                        fi
                    else
                        echo "Error: No lock file found for the $ENCPASS_KEY_NAME key."
                    fi
                fi
            done
            echo "Unlocked $ENCPASS_NUM_KEYS_UNLOCKED keys."
        else
            echo "No password entered."
        fi
        ;;
    dir )
        shift
        encpass_checks
        echo "ENCPASS_HOME_DIR=$ENCPASS_HOME_DIR"
        ;;
    help|--help|usage|--usage|\? )
        encpass_checks
        encpass_help
        ;;
    * )
        if [ ! -z "$1" ]; then
            echo "Command not recognized. See \"encpass.sh help\" for a list commands."
            exit 1
        fi
        ;;
esac

How to import an existing project from GitHub into Android Studio

In Github click the "Clone or download" button of the project you want to import --> download the ZIP file and unzip it. In Android Studio Go to File -> New Project -> Import Project and select the newly unzipped folder -> press OK. It will build the Gradle automatically.

Good Luck with your project

Cropping images in the browser BEFORE the upload

If you will still use JCrop, you will need only this php functions to crop the file:

$img_src = imagecreatefromjpeg($src);
$img_dest = imagecreatetruecolor($new_w,$new_h);
imagecopyresampled($img_dest,$img_src,0,0,$x,$y,$new_w,$new_h,$w,$h);
imagejpeg($img_dest,$dest);

client side:

jQuery(function($){

    $('#target').Jcrop({
    onChange:   showCoords,
    onSelect:   showCoords,
    onRelease:  clearCoords
    });

});

var x,y,w,h; //these variables are necessary to crop
function showCoords(c)
{
    x = c.x;
    y = c.y;
    w = c.w;
    h = c.h;
};
function clearCoords()
{
    x=y=w=h=0;
}

check if file exists in php

for me also the file_exists() function is not working properly. So I got this alternative solution. Hope this one help someone

$path = 'http://localhost/admin/public/upload/video_thumbnail/thumbnail_1564385519_0.png';

    if (@GetImageSize($path)) {
        echo 'File exits';
    } else {
        echo "File doesn't exits";
    }

How do I find the duplicates in a list and create another list with them?

I would do this with pandas, because I use pandas a lot

import pandas as pd
a = [1,2,3,3,3,4,5,6,6,7]
vc = pd.Series(a).value_counts()
vc[vc > 1].index.tolist()

Gives

[3,6]

Probably isn't very efficient, but it sure is less code than a lot of the other answers, so I thought I would contribute

Retrieving an element from array list in Android?

public class DemoActivity extends Activity {
    /** Called when the activity is first created. */
    ArrayList<String> al = new ArrayList<String>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);



        // add elements to the array list

        al.add("C");
        al.add("A");
        al.add("E");
        al.add("B");
        al.add("D");
        al.add("F");

        // retrieve elements from array

        String data = al.get(pass the index here);
        System.out.println("Data is "+ data);

This is another way of getting element

        Iterator<String> it = al.iterator();
        while (it.hasNext()) {
            System.out.println("Data is "+ it.next());
        }
    }

How to setup virtual environment for Python in VS Code?

Have you activated your environment? Also you could try this: vscode select venv

Laravel Rule Validation for Numbers

If I correctly got what you want:

$rules = ['Fno' => 'digits_between:2,5', 'Lno' => 'numeric|min:2'];

or

$rules = ['Fno' => 'numeric|min:2|max:5', 'Lno' => 'numeric|min:2'];

For all the available rules: http://laravel.com/docs/4.2/validation#available-validation-rules

digits_between :min,max

The field under validation must have a length between the given min and max.

numeric

The field under validation must have a numeric value.

max:value

The field under validation must be less than or equal to a maximum value. Strings, numerics, and files are evaluated in the same fashion as the size rule.

min:value

The field under validation must have a minimum value. Strings, numerics, and files are evaluated in the same fashion as the size rule.

newline character in c# string

They might be just a \r or a \n. I just checked and the text visualizer in VS 2010 displays both as newlines as well as \r\n.

This string

string test = "blah\r\nblah\rblah\nblah";

Shows up as

blah
blah
blah
blah

in the text visualizer.

So you could try

string modifiedString = originalString
    .Replace(Environment.NewLine, "<br />")
    .Replace("\r", "<br />")
    .Replace("\n", "<br />");

LIMIT 10..20 in SQL Server

as you found, this is the preferred sql server method:

SELECT * FROM ( 
  SELECT *, ROW_NUMBER() OVER (ORDER BY name) as row FROM sys.databases 
 ) a WHERE a.row > 5 and a.row <= 10

How can I import a large (14 GB) MySQL dump file into a new MySQL database?

navigate to C:\wamp64\alias\phpmyadmin.conf and change from:

php_admin_value upload_max_filesize 128M
php_admin_value post_max_size 128M

to

php_admin_value upload_max_filesize 2048M
php_admin_value post_max_size 2048M

or more :)

Error: unexpected symbol/input/string constant/numeric constant/SPECIAL in my code

For me the error was:

Error: unexpected input in "?"

and the fix was opening the script in a hex editor and removing the first 3 characters from the file. The file was starting with an UTF-8 BOM and it seems that Rscript can't read that.

EDIT: OP requested an example. Here it goes.

?  ~ cat a.R
cat('hello world\n')
?  ~ xxd a.R
00000000: efbb bf63 6174 2827 6865 6c6c 6f20 776f  ...cat('hello wo
00000010: 726c 645c 6e27 290a                      rld\n').
?  ~ R -f a.R        

R version 3.4.4 (2018-03-15) -- "Someone to Lean On"
Copyright (C) 2018 The R Foundation for Statistical Computing
Platform: x86_64-pc-linux-gnu (64-bit)

R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.

  Natural language support but running in an English locale

R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.

Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.

> cat('hello world\n')
Error: unexpected input in "?"
Execution halted

How to make an HTTP get request with parameters

My preferred way is this. It handles the escaping and parsing for you.

WebClient webClient = new WebClient();
webClient.QueryString.Add("param1", "value1");
webClient.QueryString.Add("param2", "value2");
string result = webClient.DownloadString("http://theurl.com");

Reload an iframe with jQuery

This is possible with simple JavaScript.

  • In iFrame1, make a JavaScript function that is called in the body tag onload. I have it check a server side variable that I set, so it does not try to run the JavaScript function in iframe2 unless I have taken a specific action in iframe1. You could set this up as a function fired by a button press or however you want to in iframe1.
  • Then in iframe2, you have the second function I list below. The function in iframe1 basically goes to the parent page and then uses the window.frames syntax to fire a JavaScript function in iframe2. Just make sure to use the id/name of iframe2 and not the src.
//function in iframe1
function refreshIframe2()
{
    if (<cfoutput>#didValidation#</cfoutput> == 1)
    {   
         parent.window.frames.iframe2.refreshPage();
    }
}

//function in iframe2
function refreshPage()
{   
    document.location.reload();
}

using wildcards in LDAP search filters/queries

A filter argument with a trailing * can be evaluated almost instantaneously via an index lookup. A leading * implies a sequential search through the index, so it is O(N). It will take ages.

I suggest you reconsider the requirement.

How can I merge two commits into one if I already started rebase?

you can cancel the rebase with

git rebase --abort

and when you run the interactive rebase command again the 'squash; commit must be below the pick commit in the list

What are some ways of accessing Microsoft SQL Server from Linux?

If you use eclipse you can install Data Tools Platform plugin on it and use it for every DB engines including MS SQLServer. It just needs to get JDBC driver for that DB engine.

Finding what methods a Python object has

If you specifically want methods, you should use inspect.ismethod.

For method names:

import inspect
method_names = [attr for attr in dir(self) if inspect.ismethod(getattr(self, attr))]

For the methods themselves:

import inspect
methods = [member for member in [getattr(self, attr) for attr in dir(self)] if inspect.ismethod(member)]

Sometimes inspect.isroutine can be useful too (for built-ins, C extensions, Cython without the "binding" compiler directive).

CSS submit button weird rendering on iPad/iPhone

oops! just found myself: just add this line on any element you need

   -webkit-appearance: none;

SVN: Folder already under version control but not comitting?

Have you tried performing an svn cleanup?

Difference between -XX:+UseParallelGC and -XX:+UseParNewGC

Parallel GC

  • XX:+UseParallelGC Use parallel garbage collection for scavenges. (Introduced in 1.4.1)
  • XX:+UseParallelOldGC Use parallel garbage collection for the full collections. Enabling this option automatically sets -XX:+UseParallelGC. (Introduced in 5.0 update 6.)

UseParNewGC

UseParNewGC A parallel version of the young generation copying collector is used with the concurrent collector (i.e. if -XX:+ UseConcMarkSweepGC is used on the command line then the flag UseParNewGC is also set to true if it is not otherwise explicitly set on the command line).

Perhaps the easiest way to understand was combinations of garbage collection algorithms made by Alexey Ragozin

_x000D_
_x000D_
<table border="1" style="width:100%">_x000D_
  <tr>_x000D_
    <td align="center">Young collector</td>_x000D_
    <td align="center">Old collector</td>_x000D_
    <td align="center">JVM option</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Serial (DefNew)</td>_x000D_
    <td>Serial Mark-Sweep-Compact</td>_x000D_
    <td>-XX:+UseSerialGC</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Parallel scavenge (PSYoungGen)</td>_x000D_
    <td>Serial Mark-Sweep-Compact (PSOldGen)</td>_x000D_
    <td>-XX:+UseParallelGC</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Parallel scavenge (PSYoungGen)</td>_x000D_
    <td>Parallel Mark-Sweep-Compact (ParOldGen)</td>_x000D_
    <td>-XX:+UseParallelOldGC</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Serial (DefNew)</td>_x000D_
    <td>Concurrent Mark Sweep</td>_x000D_
    <td>_x000D_
      <p>-XX:+UseConcMarkSweepGC</p>_x000D_
      <p>-XX:-UseParNewGC</p>_x000D_
    </td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Parallel (ParNew)</td>_x000D_
    <td>Concurrent Mark Sweep</td>_x000D_
    <td>_x000D_
      <p>-XX:+UseConcMarkSweepGC</p>_x000D_
      <p>-XX:+UseParNewGC</p>_x000D_
    </td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td colspan="2">G1</td>_x000D_
    <td>-XX:+UseG1GC</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Conclusion:

  1. Apply -XX:+UseParallelGC when you require parallel collection method over YOUNG generation ONLY, (but still) use serial-mark-sweep method as OLD generation collection
  2. Apply -XX:+UseParallelOldGC when you require parallel collection method over YOUNG generation (automatically sets -XX:+UseParallelGC) AND OLD generation collection
  3. Apply -XX:+UseParNewGC & -XX:+UseConcMarkSweepGC when you require parallel collection method over YOUNG generation AND require CMS method as your collection over OLD generation memory
  4. You can't apply -XX:+UseParallelGC or -XX:+UseParallelOldGC with -XX:+UseConcMarkSweepGC simultaneously, that's why your require -XX:+UseParNewGC to be paired with CMS otherwise use -XX:+UseSerialGC explicitly OR -XX:-UseParNewGC if you wish to use serial method against young generation

'was not declared in this scope' error

You need to declare y and c outside the scope of the if/else statement. A variable is only valid inside the scope it is declared (and a scope is marked with { })

#include <iostream> 
using namespace std; 
//Using the Gaussian algorithm 
int dayofweek(int date, int month, int year ){ 
int d=date; 
int y, c;
if (month==1||month==2) 
        {y=((year-1)%100);c=(year-1)/100;} 
else 
        {y=year%100;c=year/100;} 
int m=(month+9)%12+1; 
int product=(d+(2.6*m-0.2)+y+y/4+c/4-2*c); 
return product%7; 
} 

int main(){ 
cout<<dayofweek(19,1,2054); 
return 0; 
} 

How to make a PHP SOAP call using the SoapClient class

read this;-

http://php.net/manual/en/soapclient.call.php

Or

This is a good example, for the SOAP function "__call". However it is deprecated.

<?php
    $wsdl = "http://webservices.tekever.eu/ctt/?wsdl";
    $int_zona = 5;
    $int_peso = 1001;
    $cliente = new SoapClient($wsdl);
    print "<p>Envio Internacional: ";
    $vem = $cliente->__call('CustoEMSInternacional',array($int_zona, $int_peso));
    print $vem;
    print "</p>";
?>

I am not able launch JNLP applications using "Java Web Start"?

Try Java Web Launcher, rather than Java Web Start Launcher. It worked for me.

How to get row index number in R?

I'm interpreting your question to be about getting row numbers.

  • You can try as.numeric(rownames(df)) if you haven't set the rownames. Otherwise use a sequence of 1:nrow(df).
  • The which() function converts a TRUE/FALSE row index into row numbers.

Avoid trailing zeroes in printf()

I like the answer of R. slightly tweaked:

float f = 1234.56789;
printf("%d.%.0f", f, 1000*(f-(int)f));

'1000' determines the precision.

Power to the 0.5 rounding.

EDIT

Ok, this answer was edited a few times and I lost track what I was thinking a few years back (and originally it did not fill all the criteria). So here is a new version (that fills all criteria and handles negative numbers correctly):

double f = 1234.05678900;
char s[100]; 
int decimals = 10;

sprintf(s,"%.*g", decimals, ((int)(pow(10, decimals)*(fabs(f) - abs((int)f)) +0.5))/pow(10,decimals));
printf("10 decimals: %d%s\n", (int)f, s+1);

And the test cases:

#import <stdio.h>
#import <stdlib.h>
#import <math.h>

int main(void){

    double f = 1234.05678900;
    char s[100];
    int decimals;

    decimals = 10;
    sprintf(s,"%.*g", decimals, ((int)(pow(10, decimals)*(fabs(f) - abs((int)f)) +0.5))/pow(10,decimals));
    printf("10 decimals: %d%s\n", (int)f, s+1);

    decimals = 3;
    sprintf(s,"%.*g", decimals, ((int)(pow(10, decimals)*(fabs(f) - abs((int)f)) +0.5))/pow(10,decimals));
    printf(" 3 decimals: %d%s\n", (int)f, s+1);

    f = -f;
    decimals = 10;
    sprintf(s,"%.*g", decimals, ((int)(pow(10, decimals)*(fabs(f) - abs((int)f)) +0.5))/pow(10,decimals));
    printf(" negative 10: %d%s\n", (int)f, s+1);

    decimals = 3;
    sprintf(s,"%.*g", decimals, ((int)(pow(10, decimals)*(fabs(f) - abs((int)f)) +0.5))/pow(10,decimals));
    printf(" negative  3: %d%s\n", (int)f, s+1);

    decimals = 2;
    f = 1.012;
    sprintf(s,"%.*g", decimals, ((int)(pow(10, decimals)*(fabs(f) - abs((int)f)) +0.5))/pow(10,decimals));
    printf(" additional : %d%s\n", (int)f, s+1);

    return 0;
}

And the output of the tests:

 10 decimals: 1234.056789
  3 decimals: 1234.057
 negative 10: -1234.056789
 negative  3: -1234.057
 additional : 1.01

Now, all criteria are met:

  • maximum number of decimals behind the zero is fixed
  • trailing zeros are removed
  • it does it mathematically right (right?)
  • works (now) also when first decimal is zero

Unfortunately this answer is a two-liner as sprintf does not return the string.

Change button text from Xcode?

[myButton setTitle:@"Play" forState:UIControlStateNormal];

Count number of occurrences by month

For anyone finding this post through Google (as I did) here's the correct formula for cell F5 in the above example:

=SUMPRODUCT((MONTH(Sheet1!$A$1:$A$50)=MONTH(DATEVALUE(E5&" 1")))*(Sheet1!$A$1:$A$50<>""))

Formula assumes a list of dates in Sheet1!A1:A50 and a month name or abbr ("April" or "Apr") in cell E5.

Groovy: How to check if a string contains any element of an array?

def valid = pointAddress.findAll { a ->
    validPointTypes.any { a.contains(it) }
}

Should do it

Switch between python 2.7 and python 3.5 on Mac OS X

IMHO, the best way to use two different Python versions on macOS is via homebrew. After installing homebrew on macOS, run the commands below on your terminal.

brew install python@2
brew install python

Now you can run Python 2.7 by invoking python2 or Python 3 by invoking python3. In addition to this, you can use virtualenv or pyenv to manage different versions of python environments.

I have never personally used miniconda but from the documentation, it looks like it is similar to using pip and virtualenv in combination.

Why isn't sizeof for a struct equal to the sum of sizeof of each member?

If you want the structure to have a certain size with GCC for example use __attribute__((packed)).

On Windows you can set the alignment to one byte when using the cl.exe compier with the /Zp option.

Usually it is easier for the CPU to access data that is a multiple of 4 (or 8), depending platform and also on the compiler.

So it is a matter of alignment basically.

You need to have good reasons to change it.

php mail setup in xampp

My favorite smtp server is hMailServer.

It has a nice windows friendly installer and wizard. Hands down the easiest mail server I've ever setup.

It can proxy through your gmail/yahoo/etc account or send email directly.

Once it is installed, email in xampp just works with no config changes.

How to fluently build JSON in Java?

I recently created a library for creating Gson objects fluently:

http://jglue.org/fluent-json/

It works like this:

  JsonObject jsonObject = JsonBuilderFactory.buildObject() //Create a new builder for an object
  .addNull("nullKey")                            //1. Add a null to the object

  .add("stringKey", "Hello")                     //2. Add a string to the object
  .add("stringNullKey", (String) null)           //3. Add a null string to the object

  .add("numberKey", 2)                           //4. Add a number to the object
  .add("numberNullKey", (Float) null)            //5. Add a null number to the object

  .add("booleanKey", true)                       //6. Add a boolean to the object
  .add("booleanNullKey", (Boolean) null)         //7. Add a null boolean to the object

  .add("characterKey", 'c')                      //8. Add a character to the object
  .add("characterNullKey", (Character) null)     //9. Add a null character to the object

  .addObject("objKey")                           //10. Add a nested object
    .add("nestedPropertyKey", 4)                 //11. Add a nested property to the nested object
    .end()                                       //12. End nested object and return to the parent builder

  .addArray("arrayKey")                          //13. Add an array to the object
    .addObject()                                 //14. Add a nested object to the array
      .end()                                     //15. End the nested object
    .add("arrayElement")                         //16. Add a string to the array
    .end()                                       //17. End the array

    .getJson();                                  //Get the JsonObject

String json = jsonObject.toString();

And through the magic of generics it generates compile errors if you try to add an element to an array with a property key or an element to an object without a property name:

JsonObject jsonArray = JsonBuilderFactory.buildArray().addObject().end().add("foo", "bar").getJson(); //Error: tried to add a string with property key to array.
JsonObject jsonObject = JsonBuilderFactory.buildObject().addArray().end().add("foo").getJson(); //Error: tried to add a string without property key to an object.
JsonArray jsonArray = JsonBuilderFactory.buildObject().addArray("foo").getJson(); //Error: tried to assign an object to an array.
JsonObject jsonObject = JsonBuilderFactory.buildArray().addObject().getJson(); //Error: tried to assign an object to an array.

Lastly there is mapping support in the API which allows you to map your domain objects to JSON. The goal being when Java8 is released you'll be able to do something like this:

Collection<User> users = ...;
JsonArray jsonArray = JsonBuilderFactory.buildArray(users, { u-> buildObject()
                                                                 .add("userName", u.getName())
                                                                 .add("ageInYears", u.getAge()) })
                                                                 .getJson();

ng-repeat finish event

There is no need of creating a directive especially just to have a ng-repeat complete event.

ng-init does the magic for you.

  <div ng-repeat="thing in things" ng-init="$last && finished()">

the $last makes sure, that finished only gets fired, when the last element has been rendered to the DOM.

Do not forget to create $scope.finished event.

Happy Coding!!

EDIT: 23 Oct 2016

In case you also want to call the finished function when there is no item in the array then you may use the following workaround

<div style="display:none" ng-init="things.length < 1 && finished()"></div>
//or
<div ng-if="things.length > 0" ng-init="finished()"></div>

Just add the above line on the top of the ng-repeat element. It will check if the array is not having any value and call the function accordingly.

E.g.

<div ng-if="things.length > 0" ng-init="finished()"></div>
<div ng-repeat="thing in things" ng-init="$last && finished()">

Adding integers to an int array

An array has a fixed length. You cannot 'add' to it. You define at the start how long it will be.

int[] num = new int[5];

This creates an array of integers which has 5 'buckets'. Each bucket contains 1 integer. To begin with these will all be 0.

num[0] = 1;
num[1] = 2;

The two lines above set the first and second values of the array to 1 and 2. Now your array looks like this:

[1,2,0,0,0]

As you can see you set values in it, you don't add them to the end.

If you want to be able to create a list of numbers which you add to, you should use ArrayList.

How to print a single backslash?

do you like it

print(fr"\{''}")

or how about this

print(r"\ "[0])

Where is the web server root directory in WAMP?

If you installed WAMP to c:\wamp then I believe your webserver root directory would be c:\wamp\www, however this might vary depending on version.

Yes, this is where you would put your site files to access them through a browser.

Python json.loads shows ValueError: Extra data

One-liner for your problem:

data = [json.loads(line) for line in open('tweets.json', 'r')]

What are ODEX files in Android?

ART

According to the docs: http://web.archive.org/web/20170909233829/https://source.android.com/devices/tech/dalvik/configure an .odex file:

contains AOT compiled code for methods in the APK.

Furthermore, they appear to be regular shared libraries, since if you get any app, and check:

file /data/app/com.android.appname-*/oat/arm64/base.odex

it says:

base.odex: ELF shared object, 64-bit LSB arm64, stripped

and aarch64-linux-gnu-objdump -d base.odex seems to work and give some meaningful disassembly (but also some rubbish sections).

In python, how do I cast a class object to a dict

There are at least five six ways. The preferred way depends on what your use case is.

Option 1:

Simply add an asdict() method.

Based on the problem description I would very much consider the asdict way of doing things suggested by other answers. This is because it does not appear that your object is really much of a collection:

class Wharrgarbl(object):

    ...

    def asdict(self):
        return {'a': self.a, 'b': self.b, 'c': self.c}

Using the other options below could be confusing for others unless it is very obvious exactly which object members would and would not be iterated or specified as key-value pairs.

Option 1a:

Inherit your class from 'typing.NamedTuple' (or the mostly equivalent 'collections.namedtuple'), and use the _asdict method provided for you.

from typing import NamedTuple

class Wharrgarbl(NamedTuple):
    a: str
    b: str
    c: str
    sum: int = 6
    version: str = 'old'

Using a named tuple is a very convenient way to add lots of functionality to your class with a minimum of effort, including an _asdict method. However, a limitation is that, as shown above, the NT will include all the members in its _asdict.

If there are members you don't want to include in your dictionary, you'll need to modify the _asdict result:

from typing import NamedTuple

class Wharrgarbl(NamedTuple):
    a: str
    b: str
    c: str
    sum: int = 6
    version: str = 'old'

    def _asdict(self):
        d = super()._asdict()
        del d['sum']
        del d['version']
        return d

Another limitation is that NT is read-only. This may or may not be desirable.

Option 2:

Implement __iter__.

Like this, for example:

def __iter__(self):
    yield 'a', self.a
    yield 'b', self.b
    yield 'c', self.c

Now you can just do:

dict(my_object)

This works because the dict() constructor accepts an iterable of (key, value) pairs to construct a dictionary. Before doing this, ask yourself the question whether iterating the object as a series of key,value pairs in this manner- while convenient for creating a dict- might actually be surprising behavior in other contexts. E.g., ask yourself the question "what should the behavior of list(my_object) be...?"

Additionally, note that accessing values directly using the get item obj["a"] syntax will not work, and keyword argument unpacking won't work. For those, you'd need to implement the mapping protocol.

Option 3:

Implement the mapping protocol. This allows access-by-key behavior, casting to a dict without using __iter__, and also provides unpacking behavior ({**my_obj}) and keyword unpacking behavior if all the keys are strings (dict(**my_obj)).

The mapping protocol requires that you provide (at minimum) two methods together: keys() and __getitem__.

class MyKwargUnpackable:
    def keys(self):
        return list("abc")
    def __getitem__(self, key):
        return dict(zip("abc", "one two three".split()))[key]

Now you can do things like:

>>> m=MyKwargUnpackable()
>>> m["a"]
'one'
>>> dict(m)  # cast to dict directly
{'a': 'one', 'b': 'two', 'c': 'three'}
>>> dict(**m)  # unpack as kwargs
{'a': 'one', 'b': 'two', 'c': 'three'}

As mentioned above, if you are using a new enough version of python you can also unpack your mapping-protocol object into a dictionary comprehension like so (and in this case it is not required that your keys be strings):

>>> {**m}
{'a': 'one', 'b': 'two', 'c': 'three'}

Note that the mapping protocol takes precedence over the __iter__ method when casting an object to a dict directly (without using kwarg unpacking, i.e. dict(m)). So it is possible- and sometimes convenient- to cause the object to have different behavior when used as an iterable (e.g., list(m)) vs. when cast to a dict (dict(m)).

EMPHASIZED: Just because you CAN use the mapping protocol, does NOT mean that you SHOULD do so. Does it actually make sense for your object to be passed around as a set of key-value pairs, or as keyword arguments and values? Does accessing it by key- just like a dictionary- really make sense?

If the answer to these questions is yes, it's probably a good idea to consider the next option.

Option 4:

Look into using the 'collections.abc' module.

Inheriting your class from 'collections.abc.Mapping or 'collections.abc.MutableMapping signals to other users that, for all intents and purposes, your class is a mapping * and can be expected to behave that way.

You can still cast your object to a dict just as you require, but there would probably be little reason to do so. Because of duck typing, bothering to cast your mapping object to a dict would just be an additional unnecessary step the majority of the time.

This answer might also be helpful.

As noted in the comments below: it's worth mentioning that doing this the abc way essentially turns your object class into a dict-like class (assuming you use MutableMapping and not the read-only Mapping base class). Everything you would be able to do with dict, you could do with your own class object. This may be, or may not be, desirable.

Also consider looking at the numerical abcs in the numbers module:

https://docs.python.org/3/library/numbers.html

Since you're also casting your object to an int, it might make more sense to essentially turn your class into a full fledged int so that casting isn't necessary.

Option 5:

Look into using the dataclasses module (Python 3.7 only), which includes a convenient asdict() utility method.

from dataclasses import dataclass, asdict, field, InitVar

@dataclass
class Wharrgarbl(object):
    a: int
    b: int
    c: int
    sum: InitVar[int]  # note: InitVar will exclude this from the dict
    version: InitVar[str] = "old"

    def __post_init__(self, sum, version):
        self.sum = 6  # this looks like an OP mistake?
        self.version = str(version)

Now you can do this:

    >>> asdict(Wharrgarbl(1,2,3,4,"X"))
    {'a': 1, 'b': 2, 'c': 3}

Option 6:

Use typing.TypedDict, which has been added in python 3.8.

NOTE: option 6 is likely NOT what the OP, or other readers based on the title of this question, are looking for. See additional comments below.

class Wharrgarbl(TypedDict):
    a: str
    b: str
    c: str

Using this option, the resulting object is a dict (emphasis: it is not a Wharrgarbl). There is no reason at all to "cast" it to a dict (unless you are making a copy).

And since the object is a dict, the initialization signature is identical to that of dict and as such it only accepts keyword arguments or another dictionary.

    >>> w = Wharrgarbl(a=1,b=2,b=3)
    >>> w
    {'a': 1, 'b': 2, 'c': 3}
    >>> type(w)
    <class 'dict'>

Emphasized: the above "class" Wharrgarbl isn't actually a new class at all. It is simply syntactic sugar for creating typed dict objects with fields of different types for the type checker.

As such this option can be pretty convenient for signaling to readers of your code (and also to a type checker such as mypy) that such a dict object is expected to have specific keys with specific value types.

But this means you cannot, for example, add other methods, although you can try:

class MyDict(TypedDict):
    def my_fancy_method(self):
        return "world changing result"

...but it won't work:

>>> MyDict().my_fancy_method()
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
AttributeError: 'dict' object has no attribute 'my_fancy_method'

* "Mapping" has become the standard "name" of the dict-like duck type

UICollectionView - dynamic cell height?

TL;DR: Scan down to image, and then check out working project here.

Updating my answer for a simpler solution that I found..

In my case, I wanted to fix the width, and have variable height cells. I wanted a drop in, reusable solution that handled rotation and didn't require a lot of intervention.

What I arrived at, was override (just) systemLayoutFitting(...) in the collection cell (in this case a base class for me), and first defeat UICollectionView's effort to set the wrong dimension on contentView by adding a constraint for the known dimension, in this case, the width.

class EstimatedWidthCell: UICollectionViewCell {
    override init(frame: CGRect) {
        super.init(frame: frame)
        contentView.translatesAutoresizingMaskIntoConstraints = false
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        contentView.translatesAutoresizingMaskIntoConstraints = false
    }

    override func systemLayoutSizeFitting(
        _ targetSize: CGSize, withHorizontalFittingPriority
        horizontalFittingPriority: UILayoutPriority,
        verticalFittingPriority: UILayoutPriority) -> CGSize {

        width.constant = targetSize.width

and then return the final size for the cell - used for (and this feels like a bug) the dimension of the cell itself, but not contentView - which is otherwise constrained to a conflicting size (hence the constraint above). To calculate the correct cell size, I use a lower priority for the dimension that I wanted to float, and I get back the height required to fit the content within the width to which I want to fix:

        let size = contentView.systemLayoutSizeFitting(
            CGSize(width: targetSize.width, height: 1),
            withHorizontalFittingPriority: .required,
            verticalFittingPriority: verticalFittingPriority)

        print("\(#function) \(#line) \(targetSize) -> \(size)")
        return size
    }

    lazy var width: NSLayoutConstraint = {
        return contentView.widthAnchor
            .constraint(equalToConstant: bounds.size.width)
            .isActive(true)
    }()
}

But where does this width come from? It is configured via the estimatedItemSize on the collection view's flow layout:

lazy var collectionView: UICollectionView = {
    let view = UICollectionView(frame: CGRect(), collectionViewLayout: layout)
    view.backgroundColor = .cyan
    view.translatesAutoresizingMaskIntoConstraints = false
    return view
}()

lazy var layout: UICollectionViewFlowLayout = {
    let layout = UICollectionViewFlowLayout()
    let width = view.bounds.size.width // should adjust for inset
    layout.estimatedItemSize = CGSize(width: width, height: 10)
    layout.scrollDirection = .vertical
    return layout
}()

Finally, to handle rotation, I implement trailCollectionDidChange to invalidate the layout:

override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
    layout.estimatedItemSize = CGSize(width: view.bounds.size.width, height: 10)
    layout.invalidateLayout()
    super.traitCollectionDidChange(previousTraitCollection)
}

The final result looks like this:

enter image description here

And I have published a working sample here.

Error:Execution failed for task ':app:transformClassesWithDexForDebug' in android studio

Error:Execution failed for task ':app:transformClassesWithDexForDebug'. com.android.build.api.transform.TransformException: java.lang.RuntimeException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.7.0_79\bin\java.exe'' finished with non-zero exit value 1

The upper error occure due to lot of reason. So I can put why this error occure and how to solve it.

REASON 1 : Duplicate of class file name

SOLUTION :

when your refactoring of some of your class files to a library project. and that time you write name of class file So, double check that you do not have any duplicate names

REASON 2 : When you have lot of cache Memory

SOLUTION :

Sometime if you have lot of cache memory then this error occure so solve it. go to File/Invalidate caches / Restart then select Invalidate and Restart it will clean your cache memory.

REASON 3 : When there is internal bug or used beta Version to Switch back to stable version.

SOLUTION :

Solution is just simple go to Build menu and click Clean Project and after cleaning click Rebuild Project.

REASON 4 : When you memory of the system Configuration is low.

SOLUTION :

open Task Manager and stop the other application which are not most used at that time so it will free the space and solve OutOfMemory.

REASON 5 : The problem is your method count has exceed from 65K.

SOLUTION :

open your Project build.gradle file add

defaultConfig {
        ...
        multiDexEnabled true
    }

and in dependencies add below line.

dependencies 
    {
       compile 'com.android.support:multidex:1.0.0'
    }

jQuery UI autocomplete with item and id

You need to use the ui.item.label (the text) and ui.item.value (the id) properties

$('#selector').autocomplete({
    source: url,
    select: function (event, ui) {
        $("#txtAllowSearch").val(ui.item.label); // display the selected text
        $("#txtAllowSearchID").val(ui.item.value); // save selected id to hidden input
    }
});

$('#button').click(function() {
    alert($("#txtAllowSearchID").val()); // get the id from the hidden input
}); 

[Edit] You also asked how to create the multi-dimensional array...

You should be able create the array like so:

var $local_source = [[0,"c++"], [1,"java"], [2,"php"], [3,"coldfusion"], 
                     [4,"javascript"], [5,"asp"], [6,"ruby"]];

Read more about how to work with multi-dimensional arrays here: http://www.javascriptkit.com/javatutors/literal-notation2.shtml

What does $@ mean in a shell script?

From the manual:

@

Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word. That is, "$@" is equivalent to "$1" "$2" .... If the double-quoted expansion occurs within a word, the expansion of the first parameter is joined with the beginning part of the original word, and the expansion of the last parameter is joined with the last part of the original word. When there are no positional parameters, "$@" and $@ expand to nothing (i.e., they are removed).

Oracle 12c Installation failed to access the temporary location

Try cleaning your hosts file.

I spent about half a day on this, and none of these answers worked for me. I finally found the solution hinted at on OTN (the last place I look when I run into Oracle issues), and someone mentioned looking at the hosts file. I had recently modified the hosts file because this particular machine didn't have access to DNS.

I had a line for this host:

123.123.123.123     fully.qualified.domain.name.com     hostname

Commenting out the line above allowed me to install the Oracle client.

how to install apk application from my pc to my mobile android

1) Put the apk on your SDKCard and install file browsers like "Estrongs File Explorer", "Easy Installer", etc...

https://market.android.com/details?id=com.estrongs.android.pop&feature=search_result https://market.android.com/details?id=mobi.infolife.installer&feature=search_result

2) Go to your mobile settings - applications- debuging - and thick "USB debugging" enter image description here

What's your most controversial programming opinion?

Not all programmers are created equal

Quite often managers think that DeveloperA == DeveloperB simply because they have same level of experience and so on. In actual fact, the performance of one developer can be 10x or even 100x that of another.

It's politically risky to talk about it, but sometimes I feel like pointing out that, even though several team members may appear to be of equal skill, it's not always the case. I have even seen cases where lead developers were 'beyond hope' and junior devs did all the actual work - I made sure they got the credit, though. :)

ClassNotFoundException: org.slf4j.LoggerFactory

For a bit more explanation: keep in mind that the "I" in "api" is interface. The slf4j-api jar only holds the needed interfaces (actually LoggerFactory is an abstract class). You also need the actual implementations (an example of which, as noted above, can be found in slf4j-simple). If you look in the jar, you'll find the required classes under the "org.slf4j.impl" package.

hadoop No FileSystem for scheme: file

This is a typical case of the maven-assembly plugin breaking things.

Why this happened to us

Different JARs (hadoop-commons for LocalFileSystem, hadoop-hdfs for DistributedFileSystem) each contain a different file called org.apache.hadoop.fs.FileSystem in their META-INFO/services directory. This file lists the canonical classnames of the filesystem implementations they want to declare (This is called a Service Provider Interface implemented via java.util.ServiceLoader, see org.apache.hadoop.FileSystem#loadFileSystems).

When we use maven-assembly-plugin, it merges all our JARs into one, and all META-INFO/services/org.apache.hadoop.fs.FileSystem overwrite each-other. Only one of these files remains (the last one that was added). In this case, the FileSystem list from hadoop-commons overwrites the list from hadoop-hdfs, so DistributedFileSystem was no longer declared.

How we fixed it

After loading the Hadoop configuration, but just before doing anything FileSystem-related, we call this:

    hadoopConfig.set("fs.hdfs.impl", 
        org.apache.hadoop.hdfs.DistributedFileSystem.class.getName()
    );
    hadoopConfig.set("fs.file.impl",
        org.apache.hadoop.fs.LocalFileSystem.class.getName()
    );

Update: the correct fix

It has been brought to my attention by krookedking that there is a configuration-based way to make the maven-assembly use a merged version of all the FileSystem services declarations, check out his answer below.

Convert form data to JavaScript object with jQuery

Turn anything into an object (not unit tested)

<script type="text/javascript">
string = {};

string.repeat = function(string, count)
{
    return new Array(count+1).join(string);
}

string.count = function(string)
{
    var count = 0;

    for (var i=1; i<arguments.length; i++)
    {
        var results = string.match(new RegExp(arguments[i], 'g'));
        count += results ? results.length : 0;
    }

    return count;
}

array = {};

array.merge = function(arr1, arr2)
{
    for (var i in arr2)
    {
        if (arr1[i] && typeof arr1[i] == 'object' && typeof arr2[i] == 'object')
            arr1[i] = array.merge(arr1[i], arr2[i]);
        else
            arr1[i] = arr2[i]
    }

    return arr1;
}

array.print = function(obj)
{
    var arr = [];
    $.each(obj, function(key, val) {
        var next = key + ": ";
        next += $.isPlainObject(val) ? array.print(val) : val;
        arr.push( next );
      });

    return "{ " +  arr.join(", ") + " }";
}

node = {};

node.objectify = function(node, params)
{
    if (!params)
        params = {};

    if (!params.selector)
        params.selector = "*";

    if (!params.key)
        params.key = "name";

    if (!params.value)
        params.value = "value";

    var o = {};
    var indexes = {};

    $(node).find(params.selector+"["+params.key+"]").each(function()
    {
        var name = $(this).attr(params.key),
            value = $(this).attr(params.value);

        var obj = $.parseJSON("{"+name.replace(/([^\[]*)/, function()
        {
            return '"'+arguments[1]+'"';
        }).replace(/\[(.*?)\]/gi, function()
        {
            if (arguments[1].length == 0)
            {
                var index = arguments[3].substring(0, arguments[2]);
                indexes[index] = indexes[index] !== undefined ? indexes[index]+1 : 0;

                return ':{"'+indexes[index]+'"';
            }
            else
                return ':{"'+escape(arguments[1])+'"';
        })+':"'+value.replace(/[\\"]/gi, function()
        {
            return "\\"+arguments[0]; 
        })+'"'+string.repeat('}', string.count(name, ']'))+"}");

        o = array.merge(o, obj);
    });

    return o;
}
</script>

The output of test:

$(document).ready(function()
{
    console.log(array.print(node.objectify($("form"), {})));
    console.log(array.print(node.objectify($("form"), {selector: "select"})));
});

on

<form>
    <input name='input[a]' type='text' value='text'/>
    <select name='input[b]'>
        <option>select</option>
    </select>

    <input name='otherinput[c][a]' value='a'/>
    <input name='otherinput[c][]' value='b'/>
    <input name='otherinput[d][b]' value='c'/>
    <input name='otherinput[c][]' value='d'/>

    <input type='hidden' name='anotherinput' value='hidden'/>
    <input type='hidden' name='anotherinput' value='1'/>

    <input type='submit' value='submit'/>
</form>

will yield:

{ input: { a: text, b: select }, otherinput: { c: { a: a, 0: b, 1: d }, d: { b: c } }, anotherinput: 1 }
{ input: { b: select } }

window.onload vs <body onload=""/>

Think of onload like any other attribute. On an input box, for example, you could put:

<input id="test1" value="something"/>

Or you could call:

document.getElementById('test1').value = "somethingelse";

The onload attribute works the same way, except that it takes a function as its value instead of a string like the value attribute does. That also explains why you can "only use one of them" - calling window.onload reassigns the value of the onload attribute for the body tag.

Also, like others here are saying, usually it is cleaner to keep style and javascript separated from the content of the page, which is why most people advise to use window.onload or like jQuery's ready function.

What is the difference between cssSelector & Xpath and which is better with respect to performance for cross browser testing?

I’m going to hold the unpopular on SO selenium tag opinion that XPath is preferable to CSS in the longer run.

This long post has two sections - first I'll put a back-of-the-napkin proof the performance difference between the two is 0.1-0.3 milliseconds (yes; that's 100 microseconds), and then I'll share my opinion why XPath is more powerful.


Performance difference

Let's first tackle "the elephant in the room" – that xpath is slower than css.

With the current cpu power (read: anything x86 produced since 2013), even on browserstack/saucelabs/aws VMs, and the development of the browsers (read: all the popular ones in the last 5 years) that is hardly the case. The browser's engines have developed, the support of xpath is uniform, IE is out of the picture (hopefully for most of us). This comparison in the other answer is being cited all over the place, but it is very contextual – how many are running – or care about – automation against IE8?

If there is a difference, it is in a fraction of a millisecond.

Yet, most higher-level frameworks add at least 1ms of overhead over the raw selenium call anyways (wrappers, handlers, state storing etc); my personal weapon of choice – RobotFramework – adds at least 2ms, which I am more than happy to sacrifice for what it provides. A network roundtrip from an AWS us-east-1 to BrowserStack's hub is usually 11 milliseconds.

So with remote browsers if there is a difference between xpath and css, it is overshadowed by everything else, in orders of magnitude.


The measurements

There are not that many public comparisons (I've really seen only the cited one), so – here's a rough single-case, dummy and simple one.
It will locate an element by the two strategies X times, and compare the average time for that.

The target – BrowserStack's landing page, and its "Sign Up" button; a screenshot of the html as writing this post:

enter image description here

Here's the test code (python):

from selenium import webdriver
import timeit


if __name__ == '__main__':

    xpath_locator = '//div[@class="button-section col-xs-12 row"]'
    css_locator = 'div.button-section.col-xs-12.row'

    repetitions = 1000

    driver = webdriver.Chrome()
    driver.get('https://www.browserstack.com/')

    css_time = timeit.timeit("driver.find_element_by_css_selector(css_locator)", 
                             number=repetitions, globals=globals())
    xpath_time = timeit.timeit('driver.find_element_by_xpath(xpath_locator)', 
                             number=repetitions, globals=globals())

    driver.quit()

    print("css total time {} repeats: {:.2f}s, per find: {:.2f}ms".
          format(repetitions, css_time, (css_time/repetitions)*1000))
    print("xpath total time for {} repeats: {:.2f}s, per find: {:.2f}ms".
          format(repetitions, xpath_time, (xpath_time/repetitions)*1000))

For those not familiar with Python – it opens the page, and finds the element – first with the css locator, then with the xpath; the find operation is repeated 1,000 times. The output is the total time in seconds for the 1,000 repetitions, and average time for one find in milliseconds.

The locators are:

  • for xpath – "a div element having this exact class value, somewhere in the DOM";
  • the css is similar – "a div element with this class, somewhere in the DOM".

Deliberately chosen not to be over-tuned; also, the class selector is cited for the css as "the second fastest after an id".

The environment – Chrome v66.0.3359.139, chromedriver v2.38, cpu: ULV Core M-5Y10 usually running at 1.5GHz (yes, a "word-processing" one, not even a regular i7 beast).

Here's the output:

css total time 1000 repeats: 8.84s, per find: 8.84ms

xpath total time for 1000 repeats: 8.52s, per find: 8.52ms

Obviously the per find timings are pretty close; the difference is 0.32 milliseconds. Don't jump "the xpath is faster" – sometimes it is, sometimes it's css.


Let's try with another set of locators, a tiny-bit more complicated – an attribute having a substring (common approach at least for me, going after an element's class when a part of it bears functional meaning):

xpath_locator = '//div[contains(@class, "button-section")]'
css_locator = 'div[class~=button-section]'

The two locators are again semantically the same – "find a div element having in its class attribute this substring".
Here are the results:

css total time 1000 repeats: 8.60s, per find: 8.60ms

xpath total time for 1000 repeats: 8.75s, per find: 8.75ms

Diff of 0.15ms.


As an exercise - the same test as done in the linked blog in the comments/other answer - the test page is public, and so is the testing code.

They are doing a couple of things in the code - clicking on a column to sort by it, then getting the values, and checking the UI sort is correct.
I'll cut it - just get the locators, after all - this is the root test, right?

The same code as above, with these changes in:

  • The url is now http://the-internet.herokuapp.com/tables; there are 2 tests.

  • The locators for the first one - "Finding Elements By ID and Class" - are:

css_locator = '#table2 tbody .dues'
xpath_locator = "//table[@id='table2']//tr/td[contains(@class,'dues')]"

And here is the outcome:

css total time 1000 repeats: 8.24s, per find: 8.24ms

xpath total time for 1000 repeats: 8.45s, per find: 8.45ms

Diff of 0.2 milliseconds.

The "Finding Elements By Traversing":

css_locator = '#table1 tbody tr td:nth-of-type(4)'
xpath_locator = "//table[@id='table1']//tr/td[4]"

The result:

css total time 1000 repeats: 9.29s, per find: 9.29ms

xpath total time for 1000 repeats: 8.79s, per find: 8.79ms

This time it is 0.5 ms (in reverse, xpath turned out "faster" here).

So 5 years later (better browsers engines) and focusing only on the locators performance (no actions like sorting in the UI, etc), the same testbed - there is practically no difference between CSS and XPath.


So, out of xpath and css, which of the two to choose for performance? The answer is simple – choose locating by id.

Long story short, if the id of an element is unique (as it's supposed to be according to the specs), its value plays an important role in the browser's internal representation of the DOM, and thus is usually the fastest.

Yet, unique and constant (e.g. not auto-generated) ids are not always available, which brings us to "why XPath if there's CSS?"


The XPath advantage

With the performance out of the picture, why do I think xpath is better? Simple – versatility, and power.

Xpath is a language developed for working with XML documents; as such, it allows for much more powerful constructs than css.
For example, navigation in every direction in the tree – find an element, then go to its grandparent and search for a child of it having certain properties.
It allows embedded boolean conditions – cond1 and not(cond2 or not(cond3 and cond4)); embedded selectors – "find a div having these children with these attributes, and then navigate according to it".
XPath allows searching based on a node's value (its text) – however frowned upon this practice is, it does come in handy especially in badly structured documents (no definite attributes to step on, like dynamic ids and classes - locate the element by its text content).

The stepping in css is definitely easier – one can start writing selectors in a matter of minutes; but after a couple of days of usage, the power and possibilities xpath has quickly overcomes css.
And purely subjective – a complex css is much harder to read than a complex xpath expression.

Outro ;)

Finally, again very subjective - which one to chose?

IMO, there is no right or wrong choice - they are different solutions to the same problem, and whatever is more suitable for the job should be picked.

Being "a fan" of XPath I'm not shy to use in my projects a mix of both - heck, sometimes it is much faster to just throw a CSS one, if I know it will do the work just fine.

Android SDK location

Just add a new empty directory that path is “/Users/username/Library/Android/sdk”. Then reopen it.

How to retrieve available RAM from Windows command line?

Bit old but I wanted to know similar. Just adding the solution I came across since IMO the best answer came from Everardo w/ Physical Memory

wmic OS get FreePhysicalMemory /Value

This lead me to look deeper into wmic... Keep in mind Free Physical Memory is not the type to look at.

wmic OS get FreePhysicalMemory,FreeVirtualMemory,FreeSpaceInPagingFiles /VALUE

This returns something like...

FreePhysicalMemory=2083440
FreeSpaceInPagingFiles=3636128
FreeVirtualMemory=842124

Yarn install command error No such file or directory: 'install'

My solution was

curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -

echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list

sudo apt-get update && sudo apt-get install yarn

Getting String value from enum in Java

You can use values() method:

For instance Status.values()[0] will return PAUSE in your case, if you print it, toString() will be called and "PAUSE" will be printed.

How to connect to SQL Server from command prompt with Windows authentication

You can use different syntax to achieve different things. If it is windows authentication you want, you could try this:

sqlcmd /S  /d  -E

If you want to use SQL Server authentication you could try this:

sqlcmd /S  /d -U -P 

Definitions:

/S = the servername/instance name. Example: Pete's Laptop/SQLSERV
/d = the database name. Example: Botlek1
-E = Windows authentication.
-U = SQL Server authentication/user. Example: Pete
-P = password that belongs to the user. Example: 1234

Hope this helps!

How do I fix a compilation error for unhandled exception on call to Thread.sleep()?

Thread.sleep can throw an InterruptedException which is a checked exception. All checked exceptions must either be caught and handled or else you must declare that your method can throw it. You need to do this whether or not the exception actually will be thrown. Not declaring a checked exception that your method can throw is a compile error.

You either need to catch it:

try {
    Thread.sleep(1000);
} catch (InterruptedException e) {
    e.printStackTrace();
    // handle the exception...        
    // For example consider calling Thread.currentThread().interrupt(); here.
}

Or declare that your method can throw an InterruptedException:

public static void main(String[]args) throws InterruptedException

Related

Python: get key of index in dictionary

You could do something like this:

i={'foo':'bar', 'baz':'huh?'}
keys=i.keys()  #in python 3, you'll need `list(i.keys())`
values=i.values()
print keys[values.index("bar")]  #'foo'

However, any time you change your dictionary, you'll need to update your keys,values because dictionaries are not ordered in versions of Python prior to 3.7. In these versions, any time you insert a new key/value pair, the order you thought you had goes away and is replaced by a new (more or less random) order. Therefore, asking for the index in a dictionary doesn't make sense.

As of Python 3.6, for the CPython implementation of Python, dictionaries remember the order of items inserted. As of Python 3.7+ dictionaries are ordered by order of insertion.

Also note that what you're asking is probably not what you actually want. There is no guarantee that the inverse mapping in a dictionary is unique. In other words, you could have the following dictionary:

d={'i':1, 'j':1}

In that case, it is impossible to know whether you want i or j and in fact no answer here will be able to tell you which ('i' or 'j') will be picked (again, because dictionaries are unordered). What do you want to happen in that situation? You could get a list of acceptable keys ... but I'm guessing your fundamental understanding of dictionaries isn't quite right.

JOptionPane Yes or No window

You are writing if(true) so it will always show "Hello " message.

You should take decision on the basis of value of n returned.

The type or namespace name could not be found

It is also possible, that the referenced projects targets .NET 4.0, while the Console App Project targets .NET 4.0 Client Library.

While it might not have been related to this particular case, I think someone else can find this information useful.

How to use a global array in C#?

Your class shoud look something like this:

class Something {     int[] array; //global array, replace type of course     void function1() {        array = new int[10]; //let say you declare it here that will be 10 integers in size     }     void function2() {        array[0] = 12; //assing value at index 0 to 12.     } } 

That way you array will be accessible in both functions. However, you must be careful with global stuff, as you can quickly overwrite something.

Swift: Convert enum value to String?

Not sure in which Swift version this feature was added, but right now (Swift 2.1) you only need this code:

enum Audience : String {
    case public
    case friends
    case private
}

let audience = Audience.public.rawValue // "public"

When strings are used for raw values, the implicit value for each case is the text of that case’s name.

[...]

enum CompassPoint : String {
    case north, south, east, west
}

In the example above, CompassPoint.south has an implicit raw value of "south", and so on.

You access the raw value of an enumeration case with its rawValue property:

let sunsetDirection = CompassPoint.west.rawValue
// sunsetDirection is "west"

Source.

Import Error: No module named numpy

solution for me - I installed numpy inside a virtual environment, but then running ipython was not inside virtual env:

(venv) ?  which python
/Users/alon/code/google_photos_project/venv/bin/python
(venv) ?  which ipython
/usr/bin/ipython

so I had to install ipython, and run ipython from the venv like this:

python -c 'import IPython; IPython.terminal.ipapp.launch_new_instance()'

How do I use grep to search the current directory for all files having the a string "hello" yet display only .h and .cc files?

If you need a recursive search, you have a variety of options. You should consider ack.

Failing that, if you have GNU find and xargs:

find . -name '*.cc' -print0 -o -name '*.h' -print0 | xargs -0 grep hello /dev/null

The use of /dev/null ensures you get file names printed; the -print0 and -0 deals with file names containing spaces (newlines, etc).

If you don't have obstreperous names (with spaces etc), you can use:

find . -name '*.*[ch]' -print | xargs grep hello /dev/null

This might pick up a few names you didn't intend, because the pattern match is fuzzier (but simpler), but otherwise works. And it works with non-GNU versions of find and xargs.

How to compare types

You can use for it the is operator. You can then check if object is specific type by writing:

if (myObject is string)
{
  DoSomething()
}

justify-content property isn't working

I was having a lot of problems with justify-content, and I figured out the problem was "margin: 0 auto"

The auto part overrides the justify-content so its always displayed according to the margin and not to the justify-content.

Moment.js transform to date object

.toDate did not really work for me, So, Here is what i did :

futureStartAtDate = new Date(moment().locale("en").add(1, 'd').format("MMM DD, YYYY HH:MM"))

hope this helps

How can I see the current value of my $PATH variable on OS X?

Use the command:

 echo $PATH

and you will see all path:

/Users/name/.rvm/gems/ruby-2.5.1@pe/bin:/Users/name/.rvm/gems/ruby-2.5.1@global/bin:/Users/sasha/.rvm/rubies/ruby-2.5.1/bin:/Users/sasha/.rvm/bin:

Bootstrap: Open Another Modal in Modal

Modals in Modal:

_x000D_
_x000D_
$('.modal-child').on('show.bs.modal', function () {_x000D_
    var modalParent = $(this).attr('data-modal-parent');_x000D_
    $(modalParent).css('opacity', 0);_x000D_
});_x000D_
 _x000D_
$('.modal-child').on('hidden.bs.modal', function () {_x000D_
    var modalParent = $(this).attr('data-modal-parent');_x000D_
    $(modalParent).css('opacity', 1);_x000D_
});
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
_x000D_
<a href="#myModal" role="button" class="btn btn-primary" data-toggle="modal">Modals in Modal</a>_x000D_
_x000D_
_x000D_
<div id="myModal" class="modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">_x000D_
    <div class="modal-dialog">_x000D_
        <!-- Modal content-->_x000D_
        <div class="modal-content">_x000D_
            <div class="modal-header">_x000D_
             _x000D_
                <button type="button" class="close" data-dismiss="modal">&times;</button>_x000D_
                <h4 class="modal-title">Modal Header</h4>_x000D_
            </div>_x000D_
            <div class="modal-body">_x000D_
                <a href="#myModal1" role="button" class="btn btn-primary" data-toggle="modal">Launch other modal 1</a>_x000D_
                <a href="#myModal2" role="button" class="btn btn-primary" data-toggle="modal">Launch other modal 2</a>_x000D_
            </div>_x000D_
_x000D_
        </div>_x000D_
    </div>_x000D_
</div>_x000D_
_x000D_
<div id="myModal1" class="modal modal-child" data-backdrop-limit="1" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-modal-parent="#myModal">_x000D_
    <div class="modal-dialog">_x000D_
        <!-- Modal content-->_x000D_
        <div class="modal-content">_x000D_
            <div class="modal-header">_x000D_
                <button type="button" class="close" data-dismiss="modal">&times;</button>_x000D_
                <h4 class="modal-title">Modal Header 1</h4>_x000D_
            </div>_x000D_
            <div class="modal-body">_x000D_
                <p>Two modal body…1</p>_x000D_
            </div>_x000D_
            <div class="modal-footer">_x000D_
                <button class="btn btn-default" data-dismiss="modal" data-dismiss="modal" aria-hidden="true">Cancel</button>_x000D_
            </div>_x000D_
_x000D_
        </div>_x000D_
    </div>_x000D_
</div>_x000D_
_x000D_
<div id="myModal2" class="modal modal-child" data-backdrop-limit="1" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-modal-parent="#myModal">_x000D_
    <div class="modal-dialog">_x000D_
        <!-- Modal content-->_x000D_
        <div class="modal-content">_x000D_
            <div class="modal-header">_x000D_
                _x000D_
                <button type="button" class="close" data-dismiss="modal">&times;</button>_x000D_
                <h4 class="modal-title">Modal Header 2</h4>_x000D_
            </div>_x000D_
            <div class="modal-body">_x000D_
                <p>Modal body…2</p>_x000D_
            </div>_x000D_
            <div class="modal-footer">_x000D_
                <button class="btn btn-default" data-dismiss="modal" data-dismiss="modal" aria-hidden="true">Cancel</button>_x000D_
            </div>_x000D_
_x000D_
        </div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Regular expression to return text between parenthesis

No need to use regex .... Just use list slicing ...

string="(tidtkdgkxkxlgxlhxl) ¥£%#_¥#_¥#_¥#"
print(string[string.find("(")+1:string.find(")")])

Override intranet compatibility mode IE8

This question is a duplicate of Force "Internet Explorer 8" browser mode in intranet.

The responses there indicate that it's not possible to disable the compatibility view (on the server side) - https://stackoverflow.com/a/4130343/24267. That certainly seems to be the case, as none of the suggestions I've tried have worked. In IE8 the "Browser Mode" gets set to Internet Explorer 8 Compatibility view no matter what kind of X-UA-Compatible header you send.

I had to do some special handling for IE7 and compatibility mode, which caused the browser to render using IE8 but report it was IE7, broke my code. This is how I fixed my code (I am aware this is a horrible hack and I should be testing for features not browser versions):

isIE8 = navigator.appVersion.indexOf("MSIE") != -1 && parseFloat(navigator.appVersion.split("MSIE")[1]) == 8;
if (!isIE8 && navigator.appVersion.indexOf("MSIE") != -1 && parseFloat(navigator.appVersion.split("MSIE")[1]) == 7 && navigator.appVersion.indexOf("Trident") != -1) {
    // Liar, this is IE8 in compatibility mode.
    isIE8 = true;
}

jQuery If DIV Doesn't Have Class "x"

When you are checking if an element has or does not have a class, make sure you didn't accidentally put a dot in the class name:

<div class="className"></div>

$('div').hasClass('className');
$('div').hasClass('.className'); #will not work!!!!

After a long time of staring at my code I realized I had done this. A little typo like this took me an hour to figure out what I had done wrong. Check your code!

"Could not run curl-config: [Errno 2] No such file or directory" when installing pycurl

Similarly with yum package manager

yum install libcurl-devel

If you use dnf, use

dnf install libcurl-devel

How to get the 'height' of the screen using jquery

$(window).height();   // returns height of browser viewport
$(document).height(); // returns height of HTML document

As documented here: http://api.jquery.com/height/

How to print a string multiple times?

rows = int(input('How many stars in each row do you want?'))
columns = int(input('How many columns do you want?'))
i = 0

for i in range(columns): 
    print ("*" * rows)

i = i + 1

How do I reflect over the members of dynamic object?

In the case of ExpandoObject, the ExpandoObject class actually implements IDictionary<string, object> for its properties, so the solution is as trivial as casting:

IDictionary<string, object> propertyValues = (IDictionary<string, object>)s;

Note that this will not work for general dynamic objects. In these cases you will need to drop down to the DLR via IDynamicMetaObjectProvider.

How to redirect output of systemd service to a file

If for a some reason can't use rsyslog, this will do: ExecStart=/bin/bash -ce "exec /usr/local/bin/binary1 agent -config-dir /etc/sample.d/server >> /var/log/agent.log 2>&1"

Is there a better alternative than this to 'switch on type'?

Try to go that way:

public void Test(BaseType @base)
{
    switch (@base)
    {
        case ConcreteType concrete:
            DoSomething(concrete);
            break;

        case AnotherConcrete concrete:
            DoSomething(concrete);
            break;
    }
}

How to fix Git error: object file is empty?

I solved this removing the various empty files that git fsck was detecting, and then running a simple git pull.

I find it disappointing that now that even filesystems implement journaling and other "transactional" techniques to keep the fs sane, git can get to a corrupted state (and not be able to recover by itself) because of a power failure or space on device.

Make header and footer files to be included in multiple html pages

Aloha from 2018. Unfortunately, I don't have anything cool or futuristic to share with you.

I did however want to point out to those who have commented that the jQuery load() method isn't working in the present are probably trying to use the method with local files without running a local web server. Doing so will throw the above mentioned "cross origin" error, which specifies that cross origin requests such as that made by the load method are only supported for protocol schemes like http, data, or https. (I'm assuming that you're not making an actual cross-origin request, i.e the header.html file is actually on the same domain as the page you're requesting it from)

So, if the accepted answer above isn't working for you, please make sure you're running a web server. The quickest and simplest way to do that if you're in a rush (and using a Mac, which has Python pre-installed) would be to spin up a simple Python http server. You can see how easy it is to do that here.

I hope this helps!

Installing tensorflow with anaconda in windows

To install TF on windows, follow the below-mentioned steps:

conda create --name tensorflow python=3.5
activate tensorflow
conda install jupyter
conda install scipy
pip install tensorflow-gpu

Use pip install tensorflow in place of pip install tensorflow-gpu, in case if you want to install CPU only version of TF.

Note: This installation has been tested with Anaconda Python 3.5 (64 bit). I have also tried the same installation steps with (a) Anaconda Python 3.6 (32 bit), (b) Anaconda Python 3.6 (64 bit), and (c) Anaconda Python 3.5 (32 bit), but all of them (i.e. (a), (b) and (c) ) failed.

Getting rid of \n when using .readlines()

I used the strip function to get rid of newline character as split lines was throwing memory errors on 4 gb File.

Sample Code:

with open('C:\\aapl.csv','r') as apple:
    for apps in apple.readlines():
        print(apps.strip())

Why is my JQuery selector returning a n.fn.init[0], and what is it?

I just want to add something to these great answers. If your DOM element ins't loading in time. You can still set the value.

let Ctrl = $('#mySelectElement'); ... Ctrl.attr('value', myValue);

after that most DOM elements that accept a value attribute should populate correctly.

Cross-reference (named anchor) in markdown

For most common markdown generators. You have a simple self generated anchor in each header. For instance with pandoc, the generated anchor will be a kebab case slug of your header.

 echo "# Hello, world\!" | pandoc
 # => <h1 id="hello-world">Hello, world!</h1>

Depending on which markdown parser you use, the anchor can change (take the exemple of symbolrush and La muerte Peluda answers, they are different!). See this babelmark where you can see generated anchors depending on your markdown implementation.

AngularJS $watch window resize inside directive

// Following is angular 2.0 directive for window re size that adjust scroll bar for give element as per your tag

---- angular 2.0 window resize directive.
import { Directive, ElementRef} from 'angular2/core';

@Directive({
       selector: '[resize]',
       host: { '(window:resize)': 'onResize()' } // Window resize listener
})

export class AutoResize {

element: ElementRef; // Element that associated to attribute.
$window: any;
       constructor(_element: ElementRef) {

         this.element = _element;
         // Get instance of DOM window.
         this.$window = angular.element(window);

         this.onResize();

    }

    // Adjust height of element.
    onResize() {
         $(this.element.nativeElement).css('height', (this.$window.height() - 163) + 'px');
   }
}

Class JavaLaunchHelper is implemented in both. One of the two will be used. Which one is undefined

From what I've found online, this is a bug introduced in JDK 1.7.0_45. It appears to also be present in JDK 1.7.0_60. A bug report on Oracle's website states that, while there was a fix, it was removed before the JDK was released. I do not know why the fix was removed, but it confirms what we've already suspected -- the JDK is still broken.

The bug report claims that the error is benign and should not cause any run-time problems, though one of the comments disagrees with that. In my own experience, I have been able to work without any problems using JDK 1.7.0_60 despite seeing the message.

If this issue is causing serious problems, here are a few things I would suggest:

  • Revert back to JDK 1.7.0_25 until a fix is added to the JDK.

  • Keep an eye on the bug report so that you are aware of any work being done on this issue. Maybe even add your own comment so Oracle is aware of the severity of the issue.

  • Try the JDK early releases as they come out. One of them might fix your problem.

Instructions for installing the JDK on Mac OS X are available at JDK 7 Installation for Mac OS X. It also contains instructions for removing the JDK.

The POM for project is missing, no dependency information available

The scope <scope>provided</scope> gives you an opportunity to tell that the jar would be available at runtime, so do not bundle it. It does not mean that you do not need it at compile time, hence maven would try to download that.

Now I think, the below maven artifact do not exist at all. I tries searching google, but not able to find. Hence you are getting this issue.

Change groupId to <groupId>net.sourceforge.ant4x</groupId> to get the latest jar.

<dependency>
  <groupId>net.sourceforge.ant4x</groupId>
  <artifactId>ant4x</artifactId>
  <version>${net.sourceforge.ant4x-version}</version>
  <scope>provided</scope>
</dependency>

Another solution for this problem is:

  1. Run your own maven repo.
  2. download the jar
  3. Install the jar into the repository.
  4. Add a code in your pom.xml something like:

Where http://localhost/repo is your local repo URL:

<repositories>
    <repository>
        <id>wmc-central</id>
        <url>http://localhost/repo</url>
    </repository>
    <-- Other repository config ... -->
</repositories>

How do I find the difference between two values without knowing which is larger?

So simple just use abs((a) - (b)).

will work seamless without any additional care in signs(positive , negative)

def get_distance(p1,p2):
     return abs((p1) - (p2))

get_distance(0,2)
2

get_distance(0,2)
2

get_distance(-2,0)
2

get_distance(2,-1)
3

get_distance(-2,-1)
1

Python script header

Yes, there is - python may not be in /usr/bin, but for example in /usr/local/bin (BSD).

When using virtualenv, it may even be something like ~/projects/env/bin/python

What does the 'L' in front a string mean in C++?

L is a prefix used for wide strings. Each character uses several bytes (depending on the size of wchar_t). The encoding used is independent from this prefix. I mean it must not be necessarily UTF-16 unlike stated in other answers here.

Last segment of URL in jquery

Just another solution with regex.

var href = location.href;
console.log(href.match(/([^\/]*)\/*$/)[1]);

Receiving "Attempted import error:" in react app

i had the same issue, but I just typed export on top and erased the default one on the bottom. Scroll down and check the comments.

import React, { Component } from "react";

export class Counter extends Component { // type this  
export default Counter; // this is eliminated  

Repeat command automatically in Linux

while true; do
    sleep 5
    ls -l
done

Fatal error: Call to undefined function sqlsrv_connect()

When you install third-party extensions you need to make sure that all the compilation parameters match:

  • PHP version
  • Architecture (32/64 bits)
  • Compiler (VC9, VC10, VC11...)
  • Thread safety

Common glitches includes:

  • Editing the wrong php.ini file (that's typical with bundles); the right path is shown in phpinfo().
  • Forgetting to restart Apache.
  • Not being able to see the startup errors; those should show up in Apache logs, but you can also use the command line to diagnose it, e.g.:

    php -d display_startup_errors=1 -d error_reporting=-1 -d display_errors -c "C:\Path\To\php.ini" -m
    

If everything's right you should see sqlsrv in the command output and/or phpinfo() (depending on what SAPI you're configuring):

[PHP Modules]
bcmath
calendar
Core
[...]
SPL
sqlsrv
standard
[...]

phpinfo()

How do I get the absolute directory of a file in bash?

Problem with the above answer comes with files input with "./" like "./my-file.txt"

Workaround (of many):

    myfile="./somefile.txt"
    FOLDER="$(dirname $(readlink -f "${ARG}"))"
    echo ${FOLDER}

'router-outlet' is not a known element

In your app.module.ts file

import { RouterModule, Routes } from '@angular/router';

const appRoutes: Routes = [
{
    path: '',
    redirectTo: '/dashboard',
    pathMatch: 'full',
    component: DashboardComponent
},  
{
    path: 'dashboard',
    component: DashboardComponent
}
];

@NgModule({
imports: [
    BrowserModule,
    RouterModule.forRoot(appRoutes),
    FormsModule               
],
declarations: [
    AppComponent,  
    DashboardComponent      
],
bootstrap: [AppComponent]
})
export class AppModule {

}

Add this code. Happy Coding.

How to reload page the page with pagination in Angular 2?

This should technically be achievable using window.location.reload():

HTML:

<button (click)="refresh()">Refresh</button>

TS:

refresh(): void {
    window.location.reload();
}

Update:

Here is a basic StackBlitz example showing the refresh in action. Notice the URL on "/hello" path is retained when window.location.reload() is executed.

How to jump back to NERDTree from file in tab?

The top answers here mention using T to open a file in a new tab silently, or Ctrl+WW to hop back to nerd-tree window after file is opened normally.

IF WORKING WITH BUFFERS: use go to open a file in a new buffer, silently, meaning your focus will remain on nerd-tree.

Use this to open multiple files fast :)

Cast Object to Generic Type for returning

You have to use a Class instance because of the generic type erasure during compilation.

public static <T> T convertInstanceOfObject(Object o, Class<T> clazz) {
    try {
        return clazz.cast(o);
    } catch(ClassCastException e) {
        return null;
    }
}

The declaration of that method is:

public T cast(Object o)

This can also be used for array types. It would look like this:

final Class<int[]> intArrayType = int[].class;
final Object someObject = new int[]{1,2,3};
final int[] instance = convertInstanceOfObject(someObject, intArrayType);

Note that when someObject is passed to convertToInstanceOfObject it has the compile time type Object.

How to put scroll bar only for modal-body?

#scroll-wrap {
    max-height: 50vh;
    overflow-y: auto;
}

Using max-height with vh as the unit on the modal-body or a wrapper div inside of the modal-body. This will resize the height of modal-body or the wrapping div(in this example) automatically when a user resize the window.

vh is length unit representing 1% of the viewport size for viewport height.

Browser compatibility chart for vh unit.

Example: https://jsfiddle.net/q3xwr53f/

How to programmatically open the Permission Screen for a specific app on Android Marshmallow?

Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivity(intent);

Description

Settings.ACTION_APPLICATION_DETAILS_SETTINGS
   Opens Details setting page for App. From here user have to manually assign desired permission.

Intent.FLAG_ACTIVITY_NEW_TASK
   Optional. If set then opens Settings Screen(Activity) as new activity. Otherwise, it will be opened in currently running activity.

Uri.fromParts("package", getPackageName(), null)
   Prepares or creates URI, whereas, getPackageName() - returns name of your application package.

intent.setData(uri)
   Don't forget to set this. Otherwise, you will get android.content.ActivityNotFoundException. Because you have set your intent as Settings.ACTION_APPLICATION_DETAILS_SETTINGS and android expects some name to search.

How to solve a pair of nonlinear equations using Python?

If you prefer sympy you can use nsolve.

>>> nsolve([x+y**2-4, exp(x)+x*y-3], [x, y], [1, 1])
[0.620344523485226]
[1.83838393066159]

The first argument is a list of equations, the second is list of variables and the third is an initial guess.

XPath test if node value is number

The one I found very useful is the following:

<xsl:choose>
  <xsl:when test="not(number(myNode))">
      <!-- myNode is a not a number or empty(NaN) or zero -->      
  </xsl:when>
  <xsl:otherwise>
      <!-- myNode is a number (!= zero) -->        
  </xsl:otherwise>
</xsl:choose>

Adding external library in Android studio

There are some changes in new gradle 4.1

instead of compile we should use implementation

implementation 'com.android.support:appcompat-v7:26.0.0'

Make xargs handle filenames that contain spaces

The xargs utility reads space, tab, newline and end-of-file delimited strings from the standard input and executes utility with the strings as arguments.

You want to avoid using space as a delimiter. This can be done by changing the delimiter for xargs. According to the manual:

 -0      Change xargs to expect NUL (``\0'') characters as separators,
         instead of spaces and newlines.  This is expected to be used in
         concert with the -print0 function in find(1).

Such as:

 find . -name "*.mp3" -print0 | xargs -0 mplayer

To answer the question about playing the seventh mp3; it is simpler to run

 mplayer "$(ls *.mp3 | sed -n 7p)"

how to put image in center of html page?

Put your image in a container div then use the following CSS (changing the dimensions to suit your image.

.imageContainer{
        position: absolute;
        width: 100px; /*the image width*/
        height: 100px; /*the image height*/
        left: 50%;
        top: 50%;
        margin-left: -50px; /*half the image width*/
        margin-top: -50px; /*half the image height*/
    }

Resetting Select2 value in dropdown with reset button

Select2 uses a specific CSS class, so an easy way to reset it is:

$('.select2-container').select2('val', '');

And you have the advantage of if you have multiple Select2 at the same form, all them will be reseted with this single command.

Getting HTTP code in PHP using curl

Try PHP's "get_headers" function.

Something along the lines of:

<?php
    $url = 'http://www.example.com';
    print_r(get_headers($url));
    print_r(get_headers($url, 1));
?>

Sites not accepting wget user agent header

It seems Yahoo server does some heuristic based on User-Agent in a case Accept header is set to */*.

Accept: text/html

did the trick for me.

e.g.

wget  --header="Accept: text/html" --user-agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:21.0) Gecko/20100101 Firefox/21.0"  http://yahoo.com

Note: if you don't declare Accept header then wget automatically adds Accept:*/* which means give me anything you have.

What is <=> (the 'Spaceship' Operator) in PHP 7?

According to the RFC that introduced the operator, $a <=> $b evaluates to:

  • 0 if $a == $b
  • -1 if $a < $b
  • 1 if $a > $b

which seems to be the case in practice in every scenario I've tried, although strictly the official docs only offer the slightly weaker guarantee that $a <=> $b will return

an integer less than, equal to, or greater than zero when $a is respectively less than, equal to, or greater than $b

Regardless, why would you want such an operator? Again, the RFC addresses this - it's pretty much entirely to make it more convenient to write comparison functions for usort (and the similar uasort and uksort).

usort takes an array to sort as its first argument, and a user-defined comparison function as its second argument. It uses that comparison function to determine which of a pair of elements from the array is greater. The comparison function needs to return:

an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

The spaceship operator makes this succinct and convenient:

$things = [
    [
        'foo' => 5.5,
        'bar' => 'abc'
    ],
    [
        'foo' => 7.7,
        'bar' => 'xyz'
    ],
    [
        'foo' => 2.2,
        'bar' => 'efg'
    ]
];

// Sort $things by 'foo' property, ascending
usort($things, function ($a, $b) {
    return $a['foo'] <=> $b['foo'];
});

// Sort $things by 'bar' property, descending
usort($things, function ($a, $b) {
    return $b['bar'] <=> $a['bar'];
});

More examples of comparison functions written using the spaceship operator can be found in the Usefulness section of the RFC.

How to convert a List<String> into a comma separated string without iterating List explicitly

The following:

String joinedString = ids.toString()

will give you a comma delimited list. See docs for details.

You will need to do some post-processing to remove the square brackets, but nothing too tricky.

How to set min-font-size in CSS

.class {
    font-size: clamp(minimum-size, prefered-size, maximum-size)
}

using this you could set it up so prefered and max values are 5vw but the minimum is 15px or something so it won't go over 5vw but if 5vw < 15px it will stick to 15px

How to find a text inside SQL Server procedures / triggers?

You can find it like

SELECT DISTINCT OBJECT_NAME(id) FROM syscomments WHERE [text] LIKE '%User%'

It will list distinct stored procedure names that contain text like 'User' inside stored procedure. More info

How can I remove or replace SVG content?

Here is the solution:

d3.select("svg").remove();

This is a remove function provided by D3.js.

Unity Scripts edited in Visual studio don't provide autocomplete

Keep in mind that if you are using the ReSharper tool, it will override the IntelliSense and show it's own. To change that, on VS, go to Extensions -> ReSharper -> Options -> IntelliSense -> General then choose Visual Studio and not ReSharper.

how to add a day to a date using jquery datepicker

This answer really helped me get started (noob) - but I encountered some weird behavior when I set a start date of 12/31/2014 and added +1 to default the end date. Instead of giving me an end date of 01/01/2015 I was getting 02/01/2015 (!!!). This version parses the components of the start date to avoid these end of year oddities.


 $( "#date_start" ).datepicker({

   minDate: 0,
   dateFormat: "mm/dd/yy",

   onSelect: function(selected) {
         $("#date_end").datepicker("option","minDate", selected); //  mindate on the End datepicker cannot be less than start date already selected.
         var date = $(this).datepicker('getDate');
         var tempStartDate = new Date(date);
         var default_end = new Date(tempStartDate.getFullYear(), tempStartDate.getMonth(), tempStartDate.getDate()+1); //this parses date to overcome new year date weirdness
         $('#date_end').datepicker('setDate', default_end); // Set as default                           
   }

 });

 $( "#date_end" ).datepicker({

   minDate: 0,
   dateFormat: "mm/dd/yy",

   onSelect: function(selected) {
     $("#date_start").datepicker("option","maxDate", selected); //  maxdate on the Start datepicker cannot be more than end date selected.

  }

});

Run task only if host does not belong to a group

Here's another way to do this:

- name: my command
  command: echo stuff
  when: "'groupname' not in group_names"

group_names is a magic variable as documented here: https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html#accessing-information-about-other-hosts-with-magic-variables :

group_names is a list (array) of all the groups the current host is in.

How do I work with dynamic multi-dimensional arrays in C?

There's no way to allocate the whole thing in one go. Instead, create an array of pointers, then, for each pointer, create the memory for it. For example:

int** array;
array = (int**)malloc(sizeof(int*) * 50);
for(int i = 0; i < 50; i++)
    array[i] = (int*)malloc(sizeof(int) * 50);

Of course, you can also declare the array as int* array[50] and skip the first malloc, but the second set is needed in order to dynamically allocate the required storage.

It is possible to hack a way to allocate it in a single step, but it would require a custom lookup function, but writing that in such a way that it will always work can be annoying. An example could be L(arr,x,y,max_x) arr[(y)*(max_x) + (x)], then malloc a block of 50*50 ints or whatever and access using that L macro, e.g.

#define L(arr,x,y,max_x) arr[(y)*(max_x) + (x)]

int dim_x = 50;
int dim_y = 50;

int* array = malloc(dim_x*dim_y*sizeof(int));

int foo = L(array, 4, 6, dim_x);

But that's much nastier unless you know the effects of what you're doing with the preprocessor macro.

Dropping connected users in Oracle database

This can be as simple as:

SQL> ALTER SYSTEM ENABLE RESTRICTED SESSION;

SQL> DROP USER test CASCADE;

SQL> ALTER SYSTEM DISABLE RESTRICTED SESSION;

'typeid' versus 'typeof' in C++

C++ language has no such thing as typeof. You must be looking at some compiler-specific extension. If you are talking about GCC's typeof, then a similar feature is present in C++11 through the keyword decltype. Again, C++ has no such typeof keyword.

typeid is a C++ language operator which returns type identification information at run time. It basically returns a type_info object, which is equality-comparable with other type_info objects.

Note, that the only defined property of the returned type_info object has is its being equality- and non-equality-comparable, i.e. type_info objects describing different types shall compare non-equal, while type_info objects describing the same type have to compare equal. Everything else is implementation-defined. Methods that return various "names" are not guaranteed to return anything human-readable, and even not guaranteed to return anything at all.

Note also, that the above probably implies (although the standard doesn't seem to mention it explicitly) that consecutive applications of typeid to the same type might return different type_info objects (which, of course, still have to compare equal).

How do I import global modules in Node? I get "Error: Cannot find module <module>"?

Install any package globally as below:

$ npm install -g replace  // replace is one of the node module.

As this replace module is installed globally so if you see your node modules folder you would not see replace module there and so you can not use this package using require('replace').

because with require you can use only local modules which are present in your node module folder.

Now to use global module you should link it with node module path using below command.

$ npm link replace

Now go back and see your node module folder you could now be able to see replace module there and can use it with require('replace') in your application as it is linked with your local node module.

Pls let me know if any further clarification is needed.

Json.NET serialize object with root name

You can easily create your own serializer

var car = new Car() { Name = "Ford", Owner = "John Smith" };
string json = Serialize(car);

string Serialize<T>(T o)
{
    var attr = o.GetType().GetCustomAttribute(typeof(JsonObjectAttribute)) as JsonObjectAttribute;

    var jv = JValue.FromObject(o);

    return new JObject(new JProperty(attr.Title, jv)).ToString();
}

Best way to show a loading/progress indicator?

Use ProgressDialog

ProgressDialog.show(Context context, CharSequence title, CharSequence message);

enter image description here

However this is considered as an anti pattern today (2013): http://www.youtube.com/watch?v=pEGWcMTxs3I

Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in

Your query ($myQuery) is failing and therefore not producing a query resource, but instead producing FALSE.

To reveal what your dynamically generated query looks like and reveal the errors, try this:

$result2 = mysql_query($myQuery) or die($myQuery."<br/><br/>".mysql_error());

The error message will guide you to the solution, which from your comment below is related to using ORDER BY on a field that doesn't exist in the table you're SELECTing from.

Java 8 lambdas, Function.identity() or t->t

From the JDK source:

static <T> Function<T, T> identity() {
    return t -> t;
}

So, no, as long as it is syntactically correct.

Reloading .env variables without restarting server (Laravel 5, shared hosting)

In config/database.php I changed the default DB connection from mysql to sqlite. I deleted the .env file (actually renamed it) and created the sqlite file with touch storage/database.sqlite. The migration worked with sqlite.

Then I switched back the config/database.php default DB connection to mysql and recovered the .env file. The migration worked with mysql.

It doesn't make sense I guess. Maybe was something serverside.

Can a PDF file's print dialog be opened with Javascript?

Another solution:

<input type="button" value="Print" onclick="document.getElementById('PDFtoPrint').focus(); document.getElementById('PDFtoPrint').contentWindow.print();">

VBA copy rows that meet criteria to another sheet

After formatting the previous answer to my own code, I have found an efficient way to copy all necessary data if you are attempting to paste the values returned via AutoFilter to a separate sheet.

With .Range("A1:A" & LastRow)
    .Autofilter Field:=1, Criteria1:="=*" & strSearch & "*"
    .Offset(1,0).SpecialCells(xlCellTypeVisible).Cells.Copy
    Sheets("Sheet2").activate
    DestinationRange.PasteSpecial
End With

In this block, the AutoFilter finds all of the rows that contain the value of strSearch and filters out all of the other values. It then copies the cells (using offset in case there is a header), opens the destination sheet and pastes the values to the specified range on the destination sheet.

Vertical alignment of text and icon in button

Alternativly if your using bootstrap then you can just add align-middle to vertical align the element.

<button id="whaever" class="btn btn-large btn-primary" style="padding: 20px;" name="Continue" type="submit">Continue
    <i class="icon-ok align-middle" style="font-size:40px;"></i>
</button>

Number of days between two dates in Joda-Time

tl;dr

java.time.temporal.ChronoUnit.DAYS.between( 
    earlier.toLocalDate(), 
    later.toLocalDate() 
)

…or…

java.time.temporal.ChronoUnit.HOURS.between( 
    earlier.truncatedTo( ChronoUnit.HOURS )  , 
    later.truncatedTo( ChronoUnit.HOURS ) 
)

java.time

FYI, the Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes.

The equivalent of Joda-Time DateTime is ZonedDateTime.

ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
ZonedDateTime now = ZonedDateTime.now( z ) ;

Apparently you want to count the days by dates, meaning you want to ignore the time of day. For example, starting a minute before midnight and ending a minute after midnight should result in a single day. For this behavior, extract a LocalDate from your ZonedDateTime. The LocalDate class represents a date-only value without time-of-day and without time zone.

LocalDate localDateStart = zdtStart.toLocalDate() ;
LocalDate localDateStop = zdtStop.toLocalDate() ;

Use the ChronoUnit enum to calculate elapsed days or other units.

long days = ChronoUnit.DAYS.between( localDateStart , localDateStop ) ;

Truncate

As for you asking about a more general way to do this counting where you are interested the delta of hours as hour-of-the-clock rather than complete hours as spans-of-time of sixty minutes, use the truncatedTo method.

Here is your example of 14:45 to 15:12 on same day.

ZoneId z = ZoneId.of( "America/Montreal" ); 
ZonedDateTime start = ZonedDateTime.of( 2017 , 1 , 17 , 14 , 45 , 0 , 0 , z );
ZonedDateTime stop = ZonedDateTime.of( 2017 , 1 , 17 , 15 , 12 , 0 , 0 , z );

long hours = ChronoUnit.HOURS.between( start.truncatedTo( ChronoUnit.HOURS ) , stop.truncatedTo( ChronoUnit.HOURS ) );

1

This does not work for days. Use toLocalDate() in this case.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

How to vertically center a <span> inside a div?

To the parent div add a height say 50px. In the child span, add the line-height: 50px; Now the text in the span will be vertically center. This worked for me.

How to add number of days in postgresql datetime

This will give you the deadline :

select id,  
       title,
       created_at + interval '1' day * claim_window as deadline
from projects

Alternatively the function make_interval can be used:

select id,  
       title,
       created_at + make_interval(days => claim_window) as deadline
from projects

To get all projects where the deadline is over, use:

select *
from (
  select id, 
         created_at + interval '1' day * claim_window as deadline
  from projects
) t
where localtimestamp at time zone 'UTC' > deadline

Read line with Scanner

Try to use r.hasNext() instead of r.hasNextLine():

while(r.hasNext()) {
        scan = r.next();

How to check if a file exists from a url

Hi according to our test between 2 different servers the results are as follows:

using curl for checking 10 .png files (each about 5 mb) was on average 5.7 secs. using header check for the same thing took average of 7.8 seconds!

So in our test curl was much faster if you have to check larger files!

our curl function is:

function remote_file_exists($url){
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if( $httpCode == 200 ){return true;}
    return false;
}

here is our header check sample:

function UR_exists($url){
   $headers=get_headers($url);
   return stripos($headers[0],"200 OK")?true:false;
}

Using VBA code, how to export Excel worksheets as image in Excel 2003?

Solution without charts

Function SelectionToPicture(nome)

'save location ( change if you want )
FName = CreateObject("WScript.Shell").SpecialFolders("Desktop") & "\" & nome & ".jpg"

'copy selection and get size
Selection.CopyPicture xlScreen, xlBitmap
w = Selection.Width
h = Selection.Height



With ThisWorkbook.ActiveSheet

    .Activate

    Dim chtObj As ChartObject
    Set chtObj = .ChartObjects.Add(100, 30, 400, 250)
    chtObj.Name = "TemporaryPictureChart"

    'resize obj to picture size
    chtObj.Width = w
    chtObj.Height = h

    ActiveSheet.ChartObjects("TemporaryPictureChart").Activate
    ActiveChart.Paste

    ActiveChart.Export FileName:=FName, FilterName:="jpg"

    chtObj.Delete

End With
End Function

Get Absolute Position of element within the window in wpf

I think what BrandonS wants is not the position of the mouse relative to the root element, but rather the position of some descendant element.

For that, there is the TransformToAncestor method:

Point relativePoint = myVisual.TransformToAncestor(rootVisual)
                              .Transform(new Point(0, 0));

Where myVisual is the element that was just double-clicked, and rootVisual is Application.Current.MainWindow or whatever you want the position relative to.

Create Carriage Return in PHP String?

Fragment PHP (in console Cloud9):

echo "\n";
echo "1: first_srt=1\nsecnd_srt=2\n";
echo "\n";
echo '2: first_srt=1\nsecnd_srt=2\n';
echo "\n";
echo "==============\n";
echo "\n";

resulting output:

  1: first_srt=1
  secnd_srt=2

  2: first_srt=1\nsecnd_srt=2\n
  ==============

Difference between 1 and 2: " versus '

Is java.sql.Timestamp timezone specific?

I think the correct answer should be java.sql.Timestamp is NOT timezone specific. Timestamp is a composite of java.util.Date and a separate nanoseconds value. There is no timezone information in this class. Thus just as Date this class simply holds the number of milliseconds since January 1, 1970, 00:00:00 GMT + nanos.

In PreparedStatement.setTimestamp(int parameterIndex, Timestamp x, Calendar cal) Calendar is used by the driver to change the default timezone. But Timestamp still holds milliseconds in GMT.

API is unclear about how exactly JDBC driver is supposed to use Calendar. Providers seem to feel free about how to interpret it, e.g. last time I worked with MySQL 5.5 Calendar the driver simply ignored Calendar in both PreparedStatement.setTimestamp and ResultSet.getTimestamp.

How to top, left justify text in a <td> cell that spans multiple rows

td[rowspan] {
  vertical-align: top;
  text-align: left;
}

See: CSS attribute selectors.

Javascript, Change google map marker color

You can use this code it works fine.

 var pinImage = new google.maps.MarkerImage("http://www.googlemapsmarkers.com/v1/009900/");

 var marker = new google.maps.Marker({
            position: yourlatlong,
            icon: pinImage,
            map: map
        });

see Example here

Unable to get provider com.google.firebase.provider.FirebaseInitProvider

In my case the problem happened after we migrated to AndroidX. For some reason, app was calling MultiDex.install() with reflection:

    final Class<?> clazz = Class.forName("android.support.multidex.MultiDex");
    final Method method = clazz.getDeclaredMethod("install", Context.class);
    method.invoke(null, this);

I changed package from android.support.multidex.MultiDex to androidx.multidex.MultiDex. It worked.

How to delete images from a private docker registry?

There are some clients (in Python, Ruby, etc) which do exactly that. For my taste, it isn't sustainable to install a runtime (e.g. Python) on my registry server, just to housekeep my registry!


So deckschrubber is my solution:

go get github.com/fraunhoferfokus/deckschrubber
$GOPATH/bin/deckschrubber

images older than a given age are automatically deleted. Age can be specified using -year, -month, -day, or a combination of them:

$GOPATH/bin/deckschrubber -month 2 -day 13 -registry http://registry:5000

UPDATE: here's a short introduction on deckschrubber.

Use a JSON array with objects with javascript

Your question feels a little incomplete, but I think what you're looking for is a way of making your JSON accessible to your code:

if you have the JSON string as above then you'd just need to do this

var jsonObj = eval('[{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}]');

then you can access these vars with something like jsonObj[0].id etc

Let me know if that's not what you were getting at and I'll try to help.

M

Subset data.frame by date

The first thing you should do with date variables is confirm that R reads it as a Date. To do this, for the variable (i.e. vector/column) called Date, in the data frame called EPL2011_12, input

class(EPL2011_12$Date)

The output should read [1] "Date". If it doesn't, you should format it as a date by inputting

EPL2011_12$Date <- as.Date(EPL2011_12$Date, "%d-%m-%y")

Note that the hyphens in the date format ("%d-%m-%y") above can also be slashes ("%d/%m/%y"). Confirm that R sees it as a Date. If it doesn't, try a different formatting command

EPL2011_12$Date <- format(EPL2011_12$Date, format="%d/%m/%y")

Once you have it in Date format, you can use the subset command, or you can use brackets

WhateverYouWant <- EPL2011_12[EPL2011_12$Date > as.Date("2014-12-15"),]

How to select top n rows from a datatable/dataview in ASP.NET

If you want the number of rows to be flexible, you can add row_number in the SQL. For SQL server:

SELECT ROW_NUMBER() OVER (ORDER BY myOrder) ROW_NUMBER, * FROM myTable

Then filter the datatable on row_number:

Dataview dv= new Dataview(dt, "ROW_NUMBER<=100", "", CurrentRows)

How to get the sign, mantissa and exponent of a floating point number

I think it is better to use unions to do the casts, it is clearer.

#include <stdio.h>

typedef union {
  float f;
  struct {
    unsigned int mantisa : 23;
    unsigned int exponent : 8;
    unsigned int sign : 1;
  } parts;
} float_cast;

int main(void) {
  float_cast d1 = { .f = 0.15625 };
  printf("sign = %x\n", d1.parts.sign);
  printf("exponent = %x\n", d1.parts.exponent);
  printf("mantisa = %x\n", d1.parts.mantisa);
}

Example based on http://en.wikipedia.org/wiki/Single_precision

What is meaning of negative dbm in signal strength?

I think it is confusing to think of it in terms of negative numbers. Since it is a logarithm think of the negative values the same way you think of powers of ten. 10^3 = 1000 while 10^-3 = 0.001.

With this in mind and using the formulas from S Lists's answer (and assuming our base power is 1mW in all these cases) we can build a little table:

|--------|-------------------|
| P(dBm) |        P(mW)      |
|--------|-------------------|
|    50  |  100000           |    
|    40  |   10000           |    strong transmitter
|    30  |    1000           |             ^  
|    20  |     100           |             |
|    10  |      10           |             |
|     0  |       1           |
|   -10  |       0.1         |
|   -20  |       0.01        |
|   -30  |       0.001       |
|   -40  |       0.0001      |
|   -50  |       0.00001     |             |
|   -60  |       0.000001    |             |
|   -70  |       0.0000001   |             v
|   -80  |       0.00000001  |    sensitive receiver
|   -90  |       0.000000001 |
|--------|-------------------|

When I think of it like this I find that it's easier to see that the more negative the dBm value then the farther to the right of the decimal the actual power value is.

When it comes to mobile networks, it not so much that they aren't powerful enough, rather it is that they are more sensitive. When you see receivers specs with dBm far into the negative values, then what you are seeing is more sensitive equipment.

Normally you would want your transmitter to be powerful (further in to the positives) and your receiver to be sensitive (further in to the negatives).

Setting width/height as percentage minus pixels

Don't define the height as a percent, just set the top=0 and bottom=0, like this:

#div {
   top: 0; bottom: 0;
   position: absolute;
   width: 100%;
}

How do I make UITableViewCell's ImageView a fixed size even when the image is smaller

I had the same problem. Thank you to everyone else who answered - I was able to get a solution together using parts of several of these answers.

My solution is using swift 5

The problem that we are trying to solve is that we may have images with different aspect ratios in our TableViewCells but we want them to render with consistent widths. The images should, of course, render with no distortion and fill the entire space. In my case, I was fine with some "cropping" of tall, skinny images, so I used the content mode .scaleAspectFill

To do this, I created a custom subclass of UITableViewCell. In my case, I named it StoryTableViewCell. The entire class is pasted below, with comments inline.

This approach worked for me when also using a custom Accessory View and long text labels. Here's an image of the final result:

Rendered Table View with consistent image width

class StoryTableViewCell: UITableViewCell {

    override func layoutSubviews() {
        super.layoutSubviews()

        // ==== Step 1 ====
        // ensure we have an image
        guard let imageView = self.imageView else {return}

        // create a variable for the desired image width
        let desiredWidth:CGFloat = 70;

        // get the width of the image currently rendered in the cell
        let currentImageWidth = imageView.frame.size.width;

        // grab the width of the entire cell's contents, to be used later
        let contentWidth = self.contentView.bounds.width

        // ==== Step 2 ====
        // only update the image's width if the current image width isn't what we want it to be
        if (currentImageWidth != desiredWidth) {
            //calculate the difference in width
            let widthDifference = currentImageWidth - desiredWidth;

            // ==== Step 3 ====
            // Update the image's frame,
            // maintaining it's original x and y values, but with a new width
            self.imageView?.frame = CGRect(imageView.frame.origin.x,
                                           imageView.frame.origin.y,
                                           desiredWidth,
                                           imageView.frame.size.height);

            // ==== Step 4 ====
            // If there is a texst label, we want to move it's x position to
            // ensure it isn't overlapping with the image, and that it has proper spacing with the image
            if let textLabel = self.textLabel
            {
                let originalFrame = self.textLabel?.frame

                // the new X position for the label is just the original position,
                // minus the difference in the image's width
                let newX = textLabel.frame.origin.x - widthDifference
                self.textLabel?.frame = CGRect(newX,
                                               textLabel.frame.origin.y,
                                               contentWidth - newX,
                                               textLabel.frame.size.height);
                print("textLabel info: Original =\(originalFrame!)", "updated=\(self.textLabel!.frame)")
            }

            // ==== Step 4 ====
            // If there is a detail text label, do the same as step 3
            if let detailTextLabel = self.detailTextLabel {
                let originalFrame = self.detailTextLabel?.frame
                let newX = detailTextLabel.frame.origin.x-widthDifference
                self.detailTextLabel?.frame = CGRect(x: newX,
                                                     y: detailTextLabel.frame.origin.y,
                                                     width: contentWidth - newX,
                                                     height: detailTextLabel.frame.size.height);
                print("detailLabel info: Original =\(originalFrame!)", "updated=\(self.detailTextLabel!.frame)")
            }

            // ==== Step 5 ====
            // Set the image's content modoe to scaleAspectFill so it takes up the entire view, but doesn't get distorted
            self.imageView?.contentMode = .scaleAspectFill;
        }
    }
}

What Java ORM do you prefer, and why?

I have stopped using ORMs.

The reason is not any great flaw in the concept. Hibernate works well. Instead, I have found that queries have low overhead and I can fit lots of complex logic into large SQL queries, and shift a lot of my processing into the database.

So consider just using the JDBC package.

How to generate a HTML page dynamically using PHP?

You dont need to generate any dynamic html page, just use .htaccess file and rewrite the URL.

Explanation of "ClassCastException" in Java

You are trying to treat an object as an instance of a class that it is not. It's roughly analogous to trying to press the damper pedal on a guitar (pianos have damper pedals, guitars don't).

How do I add one month to current date in Java?

(adapted from Duggu)

public static Date addOneMonth(Date date)
{
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    cal.add(Calendar.MONTH, 1);
    return cal.getTime();
}

Remove lines that contain certain string

Today I needed to accomplish a similar task so I wrote up a gist to accomplish the task based on some research I did. I hope that someone will find this useful!

import os

os.system('cls' if os.name == 'nt' else 'clear')

oldfile = raw_input('{*} Enter the file (with extension) you would like to strip domains from: ')
newfile = raw_input('{*} Enter the name of the file (with extension) you would like me to save: ')

emailDomains = ['windstream.net', 'mail.com', 'google.com', 'web.de', 'email', 'yandex.ru', 'ymail', 'mail.eu', 'mail.bg', 'comcast.net', 'yahoo', 'Yahoo', 'gmail', 'Gmail', 'GMAIL', 'hotmail', 'comcast', 'bellsouth.net', 'verizon.net', 'att.net', 'roadrunner.com', 'charter.net', 'mail.ru', '@live', 'icloud', '@aol', 'facebook', 'outlook', 'myspace', 'rocketmail']

print "\n[*] This script will remove records that contain the following strings: \n\n", emailDomains

raw_input("\n[!] Press any key to start...\n")

linecounter = 0

with open(oldfile) as oFile, open(newfile, 'w') as nFile:
    for line in oFile:
        if not any(domain in line for domain in emailDomains):
            nFile.write(line)
            linecounter = linecounter + 1
            print '[*] - {%s} Writing verified record to %s ---{ %s' % (linecounter, newfile, line)

print '[*] === COMPLETE === [*]'
print '[*] %s was saved' % newfile
print '[*] There are %s records in your saved file.' % linecounter

Link to Gist: emailStripper.py

Best, Az

javax.crypto.IllegalBlockSizeException : Input length must be multiple of 16 when decrypting with padded cipher

Well that is Because of

you are only able to encrypt data in blocks of 128 bits or 16 bytes. That's why you are getting that IllegalBlockSizeException exception. and the one way is to encrypt that data Directly into the String.

look this. Try and u will be able to resolve this

public static String decrypt(String encryptedData) throws Exception {

    Key key = generateKey();
    Cipher c = Cipher.getInstance(ALGO);
    c.init(Cipher.DECRYPT_MODE, key);
    String decordedValue = new BASE64Decoder().decodeBuffer(encryptedData).toString().trim();
    System.out.println("This is Data to be Decrypted" + decordedValue);
    return decordedValue;
}

hope that will help.

How to create circular ProgressBar in android?

You can try this Circle Progress library

enter image description here

enter image description here

NB: please always use same width and height for progress views

DonutProgress:

 <com.github.lzyzsd.circleprogress.DonutProgress
        android:id="@+id/donut_progress"
        android:layout_marginLeft="50dp"
        android:layout_width="100dp"
        android:layout_height="100dp"
        custom:circle_progress="20"/>

CircleProgress:

  <com.github.lzyzsd.circleprogress.CircleProgress
        android:id="@+id/circle_progress"
        android:layout_marginLeft="50dp"
        android:layout_width="100dp"
        android:layout_height="100dp"
        custom:circle_progress="20"/>

ArcProgress:

<com.github.lzyzsd.circleprogress.ArcProgress
        android:id="@+id/arc_progress"
        android:background="#214193"
        android:layout_marginLeft="50dp"
        android:layout_width="100dp"
        android:layout_height="100dp"
        custom:arc_progress="55"
        custom:arc_bottom_text="MEMORY"/>

How do I get the real .height() of a overflow: hidden or overflow: scroll div?

I have just cooked up another solution for this, where it's not longer necessary to use a -much to high- max-height value. It needs a few lines of javascript code to calculate the inner height of the collapsed DIV but after that, it's all CSS.

1) Fetching and setting height

Fetch the inner height of the collapsed element (using scrollHeight). My element has a class .section__accordeon__content and I actually run this in a forEach() loop to set the height for all panels, but you get the idea.

document.querySelectorAll( '.section__accordeon__content' ).style.cssText = "--accordeon-height: " + accordeonPanel.scrollHeight + "px";

2) Use the CSS variable to expand the active item

Next, use the CSS variable to set the max-height value when the item has an .active class.

.section__accordeon__content.active {
  max-height: var(--accordeon-height);
}

Final example

So the full example goes like this: first loop through all accordeon panels and store their scrollHeight values as CSS variables. Next use the CSS variable as the max-height value on the active/expanded/open state of the element.

Javascript:

document.querySelectorAll( '.section__accordeon__content' ).forEach(
  function( accordeonPanel ) {
    accordeonPanel.style.cssText = "--accordeon-height: " + accordeonPanel.scrollHeight + "px";
  }
);

CSS:

.section__accordeon__content {
  max-height: 0px;
  overflow: hidden;
  transition: all 425ms cubic-bezier(0.465, 0.183, 0.153, 0.946);
}

.section__accordeon__content.active {
  max-height: var(--accordeon-height);
}

And there you have it. A adaptive max-height animation using only CSS and a few lines of JavaScript code (no jQuery required).

Hope this helps someone in the future (or my future self for reference).

How to add headers to OkHttp request interceptor?

package com.example.network.interceptors;

import androidx.annotation.NonNull;

import java.io.IOException;
import java.util.Map;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

public class RequestHeadersNetworkInterceptor implements Interceptor {

    private final Map<String, String> headers;

    public RequestHeadersNetworkInterceptor(@NonNull Map<String, String> headers) {
        this.headers = headers;
    }

    @NonNull
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request.Builder builder = chain.request().newBuilder();
        for (Map.Entry<String, String> header : headers.entrySet()) {
            if (header.getKey() == null || header.getKey().trim().isEmpty()) {
                continue;
            }
            if (header.getValue() == null || header.getValue().trim().isEmpty()) {
                builder.removeHeader(header.getKey());
            } else {
                builder.header(header.getKey(), header.getValue());
            }
        }
        return chain.proceed(builder.build());
    }

}

Example of usage:

httpClientBuilder.networkInterceptors().add(new RequestHeadersNetworkInterceptor(new HashMap<String, String>()
{
    {
        put("User-Agent", getUserAgent());
        put("Accept", "application/json");
    }
}));

Where should I put the log4j.properties file?

I've spent a great deal of time to figure out why the log4j.properties file is not seen.
Then I noticed it was visible for the project only when it was in both MyProject/target/classes/ and MyProject/src/main/resources folders.
Hope it'll be useful to somebody.
PS: The project was maven-based.

Export specific rows from a PostgreSQL table as INSERT SQL script

SQL Workbench has such a feature.

After running a query, right click on the query results and choose "Copy Data As SQL > SQL Insert"

What is the meaning of polyfills in HTML5?

Here are some high level thoughts and info that might help, aside from the other answers.

Pollyfills are like a compatability patch for specific browsers. Shims are changes to specific arguments. Fallbacks can be used if say a @mediaquery is not compatible with a browser.

It kind of depends on the requirements of what your app/website needs to be compatible with.

You cna check this site out for compatability of specific libraries with specific browsers. https://caniuse.com/

Get filename from input [type='file'] using jQuery

You have to do this on the change event of the input type file this way:

$('#select_file').click(function() {
    $('#image_file').show();
    $('.btn').prop('disabled', false);
    $('#image_file').change(function() {
        var filename = $('#image_file').val();
        $('#select_file').html(filename);
    });
});?