Programs & Examples On #Netsuite

NetSuite is a vendor of business management SaaS. The platform's scope includes ERP, CRM, PSA, and Ecommerce. Primarily tailored to mid-market companies.

How to approach a "Got minus one from a read call" error when connecting to an Amazon RDS Oracle instance

in my case, I got the same exception because the user that I configured in the app did not existed in the DB, creating the user and granting needed permissions solved the problem.

An array of List in c#

You do like this:

List<int>[] a = new List<int>[100];

Now you have an array of type List<int> containing 100 null references. You have to create lists and put in the array, for example:

a[0] = new List<int>();

Chmod 777 to a folder and all contents

for mac, should be a ‘superuser do’;

so first :

sudo -s 
password:

and then

chmod -R 777 directory_path

How to format a duration in java? (e.g format H:MM:SS)

Here is one more sample how to format duration. Note that this sample shows both positive and negative duration as positive duration.

import static java.time.temporal.ChronoUnit.DAYS;
import static java.time.temporal.ChronoUnit.HOURS;
import static java.time.temporal.ChronoUnit.MINUTES;
import static java.time.temporal.ChronoUnit.SECONDS;

import java.time.Duration;

public class DurationSample {
    public static void main(String[] args) {
        //Let's say duration of 2days 3hours 12minutes and 46seconds
        Duration d = Duration.ZERO.plus(2, DAYS).plus(3, HOURS).plus(12, MINUTES).plus(46, SECONDS);

        //in case of negative duration
        if(d.isNegative()) d = d.negated();

        //format DAYS HOURS MINUTES SECONDS 
        System.out.printf("Total duration is %sdays %shrs %smin %ssec.\n", d.toDays(), d.toHours() % 24, d.toMinutes() % 60, d.getSeconds() % 60);

        //or format HOURS MINUTES SECONDS 
        System.out.printf("Or total duration is %shrs %smin %sec.\n", d.toHours(), d.toMinutes() % 60, d.getSeconds() % 60);

        //or format MINUTES SECONDS 
        System.out.printf("Or total duration is %smin %ssec.\n", d.toMinutes(), d.getSeconds() % 60);

        //or format SECONDS only 
        System.out.printf("Or total duration is %ssec.\n", d.getSeconds());
    }
}

How to convert a string or integer to binary in Ruby?

I asked a similar question. Based on @sawa's answer, the most succinct way to represent an integer in a string in binary format is to use the string formatter:

"%b" % 245
=> "11110101"

You can also choose how long the string representation to be, which might be useful if you want to compare fixed-width binary numbers:

1.upto(10).each { |n| puts "%04b" % n }
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010

Brew install docker does not include docker engine?

To install Docker for Mac with homebrew:

brew cask install docker

To install the command line completion:

brew install bash-completion
brew install docker-completion
brew install docker-compose-completion
brew install docker-machine-completion

Getting a timestamp for today at midnight?

$today_at_midnight = strtotime(date("Ymd"));

should give you what you're after.

explanation

What I did was use PHP's date function to get today's date without any references to time, and then pass it to the 'string to time' function which converts a date and time to a epoch timestamp. If it doesn't get a time, it assumes the first second of that day.

References: Date Function: http://php.net/manual/en/function.date.php

String To Time: http://us2.php.net/manual/en/function.strtotime.php

Is it possible to find out the users who have checked out my project on GitHub?

Use the GitHub Network Graph to Track Forks

You have no way to see who has checked out your repository using standard git commands such as git clone, but you can see who has forked your repository on GitHub using the Network Graph Visualizer. At the time of this answer, you can access this feature in at least two ways:

  1. From the "Network" tab just to the right of the "Code" tab on the navigation bar at the top of your repository.
  2. By clicking on the numbers (if non-zero) in the call-out just to the right of the "Fork" widget on the right-hand side.

For example, here is a partial screenshot of the rbenv network graph:

rbenv network graph

The "Members" tab at the top of the Network Graph will also show you a different view, listing the names of the people who currently have forks on GitHub. It obviously will not show people who cloned outside of GitHub, or folks who have subsequently deleted their forks.

jQuery get specific option tag text

I wanted to get the selected label. This worked for me in jQuery 1.5.1.

$("#list :selected").text();

How to run python script in webpage

In order for your code to show, you need several things:

Firstly, there needs to be a server that handles HTTP requests. At the moment you are just opening a file with Firefox on your local hard drive. A server like Apache or something similar is required.

Secondly, presuming that you now have a server that serves the files, you will also need something that interprets the code as Python code for the server. For Python users the go to solution is nowadays mod_wsgi. But for simpler cases you could stick with CGI (more info here), but if you want to produce web pages easily, you should go with a existing Python web framework like Django.

Setting this up can be quite the hassle, so be prepared.

Omitting one Setter/Getter in Lombok

You can pass an access level to the @Getter and @Setter annotations. This is useful to make getters or setters protected or private. It can also be used to override the default.

With @Data, you have public access to the accessors by default. You can now use the special access level NONE to completely omit the accessor, like this:

@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private int mySecret;

Programmatically read from STDIN or input file in Perl

Here is how I made a script that could take either command line inputs or have a text file redirected.

if ($#ARGV < 1) {
    @ARGV = ();
    @ARGV = <>;
    chomp(@ARGV);
}


This will reassign the contents of the file to @ARGV, from there you just process @ARGV as if someone was including command line options.

WARNING

If no file is redirected, the program will sit their idle because it is waiting for input from STDIN.

I have not figured out a way to detect if a file is being redirected in yet to eliminate the STDIN issue.

How can I find the maximum value and its index in array in MATLAB?

For a matrix you can use this:

[M,I] = max(A(:))

I is the index of A(:) containing the largest element.

Now, use the ind2sub function to extract the row and column indices of A corresponding to the largest element.

[I_row, I_col] = ind2sub(size(A),I)

source: https://www.mathworks.com/help/matlab/ref/max.html

Disable back button in react navigation

using the BackHandler from react native worked for me. Just include this line in your ComponentWillMount:

BackHandler.addEventListener('hardwareBackPress', function() {return true})

it will disable back button on android device.

Undo scaffolding in Rails

rails g scaffold MyFoo 

for generating and

rails d scaffold MyFoo

for removing

Display unescaped HTML in Vue.js

You have to use v-html directive for displaying html content inside a vue component

<div v-html="html content data property"></div>

C++ Returning reference to local variable

This code snippet:

int& func1()
{
    int i;
    i = 1;
    return i;
}

will not work because you're returning an alias (a reference) to an object with a lifetime limited to the scope of the function call. That means once func1() returns, int i dies, making the reference returned from the function worthless because it now refers to an object that doesn't exist.

int main()
{
    int& p = func1();
    /* p is garbage */
}

The second version does work because the variable is allocated on the free store, which is not bound to the lifetime of the function call. However, you are responsible for deleteing the allocated int.

int* func2()
{
    int* p;
    p = new int;
    *p = 1;
    return p;
}

int main()
{
    int* p = func2();
    /* pointee still exists */
    delete p; // get rid of it
}

Typically you would wrap the pointer in some RAII class and/or a factory function so you don't have to delete it yourself.

In either case, you can just return the value itself (although I realize the example you provided was probably contrived):

int func3()
{
    return 1;
}

int main()
{
    int v = func3();
    // do whatever you want with the returned value
}

Note that it's perfectly fine to return big objects the same way func3() returns primitive values because just about every compiler nowadays implements some form of return value optimization:

class big_object 
{ 
public:
    big_object(/* constructor arguments */);
    ~big_object();
    big_object(const big_object& rhs);
    big_object& operator=(const big_object& rhs);
    /* public methods */
private:
    /* data members */
};

big_object func4()
{
    return big_object(/* constructor arguments */);
}

int main()
{
     // no copy is actually made, if your compiler supports RVO
    big_object o = func4();    
}

Interestingly, binding a temporary to a const reference is perfectly legal C++.

int main()
{
    // This works! The returned temporary will last as long as the reference exists
    const big_object& o = func4();    
    // This does *not* work! It's not legal C++ because reference is not const.
    // big_object& o = func4();  
}

How to make a copy of an object in C#

Properties in your object are value types and you can use the shallow copy in such situation like that:

obj myobj2 = (obj)myobj.MemberwiseClone();

But in other situations, like if any members are reference types, then you need Deep Copy. You can get a deep copy of an object using Serialization and Deserialization techniques with the help of BinaryFormatter class:

public static T DeepCopy<T>(T other)
{
    using (MemoryStream ms = new MemoryStream())
    {
        BinaryFormatter formatter = new BinaryFormatter();
        formatter.Context = new StreamingContext(StreamingContextStates.Clone);
        formatter.Serialize(ms, other);
        ms.Position = 0;
        return (T)formatter.Deserialize(ms);
    }
}

The purpose of setting StreamingContext: We can introduce special serialization and deserialization logic to our code with the help of either implementing ISerializable interface or using built-in attributes like OnDeserialized, OnDeserializing, OnSerializing, OnSerialized. In all cases StreamingContext will be passed as an argument to the methods(and to the special constructor in case of ISerializable interface). With setting ContextState to Clone, we are just giving hint to that method about the purpose of the serialization.

Additional Info: (you can also read this article from MSDN)

Shallow copying is creating a new object and then copying the nonstatic fields of the current object to the new object. If a field is a value type, a bit-by-bit copy of the field is performed; for a reference type, the reference is copied but the referred object is not; therefore the original object and its clone refer to the same object.

Deep copy is creating a new object and then copying the nonstatic fields of the current object to the new object. If a field is a value type, a bit-by-bit copy of the field is performed. If a field is a reference type, a new copy of the referred object is performed.

Python json.loads shows ValueError: Extra data

This may also happen if your JSON file is not just 1 JSON record. A JSON record looks like this:

[{"some data": value, "next key": "another value"}]

It opens and closes with a bracket [ ], within the brackets are the braces { }. There can be many pairs of braces, but it all ends with a close bracket ]. If your json file contains more than one of those:

[{"some data": value, "next key": "another value"}]
[{"2nd record data": value, "2nd record key": "another value"}]

then loads() will fail.

I verified this with my own file that was failing.

import json

guestFile = open("1_guests.json",'r')
guestData = guestFile.read()
guestFile.close()
gdfJson = json.loads(guestData)

This works because 1_guests.json has one record []. The original file I was using all_guests.json had 6 records separated by newline. I deleted 5 records, (which I already checked to be bookended by brackets) and saved the file under a new name. Then the loads statement worked.

Error was

   raise ValueError(errmsg("Extra data", s, end, len(s)))
ValueError: Extra data: line 2 column 1 - line 10 column 1 (char 261900 - 6964758)

PS. I use the word record, but that's not the official name. Also, if your file has newline characters like mine, you can loop through it to loads() one record at a time into a json variable.

(SC) DeleteService FAILED 1072

I had the same error due to a typo in the service name, i was trying to delete the service display name instead of the service name. Once I used the right service name it worked fine

PHP import Excel into database (xls & xlsx)

This is best plugin with proper documentation and examples

https://github.com/PHPOffice/PHPExcel

Plus point: you can ask for help in its discussion forum and you will get response within a day from the author itself, really impressive.

Java Reflection: How to get the name of a variable?

see this example :

PersonneTest pt=new PersonneTest();
System.out.println(pt.getClass().getDeclaredFields().length);
Field[]x=pt.getClass().getDeclaredFields();
System.out.println(x[1].getName());

Remove last character from C++ string

if (str.size () > 0)  str.resize (str.size () - 1);

An std::erase alternative is good, but I like the "- 1" (whether based on a size or end-iterator) - to me, it helps expresses the intent.

BTW - Is there really no std::string::pop_back ? - seems strange.

Invalid argument supplied for foreach()

Please do not depend on casting as a solution, even though others are suggesting this as a valid option to prevent an error, it might cause another one.

Be aware: If you expect a specific form of array to be returned, this might fail you. More checks are required for that.

E.g. casting a boolean to an array (array)bool, will NOT result in an empty array, but an array with one element containing the boolean value as an int: [0=>0] or [0=>1].

I wrote a quick test to present this problem. (Here is a backup Test in case the first test url fails.)

Included are tests for: null, false, true, a class, an array and undefined.


Always test your input before using it in foreach. Suggestions:

  1. Quick type checking: $array = is_array($var) or is_object($var) ? $var : [] ;
  2. Type hinting arrays in methods before using a foreach and specifying return types
  3. Wrapping foreach within if
  4. Using try{}catch(){} blocks
  5. Designing proper code / testing before production releases
  6. To test an array against proper form you could use array_key_exists on a specific key, or test the depth of an array (when it is one !).
  7. Always extract your helper methods into the global namespace in a way to reduce duplicate code

How to compare character ignoring case in primitive types

The Character class of Java API has various functions you can use.

You can convert your char to lowercase at both sides:

Character.toLowerCase(name1.charAt(i)) == Character.toLowerCase(name2.charAt(j))

There are also a methods you can use to verify if the letter is uppercase or lowercase:

Character.isUpperCase('P')
Character.isLowerCase('P') 

What is the purpose of shuffling and sorting phase in the reducer in Map Reduce Programming?

First of all shuffling is the process of transfering data from the mappers to the reducers, so I think it is obvious that it is necessary for the reducers, since otherwise, they wouldn't be able to have any input (or input from every mapper). Shuffling can start even before the map phase has finished, to save some time. That's why you can see a reduce status greater than 0% (but less than 33%) when the map status is not yet 100%.

Sorting saves time for the reducer, helping it easily distinguish when a new reduce task should start. It simply starts a new reduce task, when the next key in the sorted input data is different than the previous, to put it simply. Each reduce task takes a list of key-value pairs, but it has to call the reduce() method which takes a key-list(value) input, so it has to group values by key. It's easy to do so, if input data is pre-sorted (locally) in the map phase and simply merge-sorted in the reduce phase (since the reducers get data from many mappers).

Partitioning, that you mentioned in one of the answers, is a different process. It determines in which reducer a (key, value) pair, output of the map phase, will be sent. The default Partitioner uses a hashing on the keys to distribute them to the reduce tasks, but you can override it and use your own custom Partitioner.

A great source of information for these steps is this Yahoo tutorial (archived).

A nice graphical representation of this is the following (shuffle is called "copy" in this figure):

enter image description here

Note that shuffling and sorting are not performed at all if you specify zero reducers (setNumReduceTasks(0)). Then, the MapReduce job stops at the map phase, and the map phase does not include any kind of sorting (so even the map phase is faster).

UPDATE: Since you are looking for something more official, you can also read Tom White's book "Hadoop: The Definitive Guide". Here is the interesting part for your question.
Tom White has been an Apache Hadoop committer since February 2007, and is a member of the Apache Software Foundation, so I guess it is pretty credible and official...

What, why or when it is better to choose cshtml vs aspx?

Cshtml files are the ones used by Razor and as stated as answer for this question, their main advantage is that they can be rendered inside unit tests. The various answers to this other topic will bring a lot of other interesting points.

Regex Named Groups in Java

What kind of problem do you get with jregex? It worked well for me under java5 and java6.

Jregex does the job well (even if the last version is from 2002), unless you want to wait for javaSE 7.

How to set combobox default value?

You can do something like this:

    public myform()
    {
         InitializeComponent(); // this will be called in ComboBox ComboBox = new System.Windows.Forms.ComboBox();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        // TODO: This line of code loads data into the 'myDataSet.someTable' table. You can move, or remove it, as needed.
        this.myTableAdapter.Fill(this.myDataSet.someTable);
        comboBox1.SelectedItem = null;
        comboBox1.SelectedText = "--select--";           
    }

How to remove all characters after a specific character in python?

another easy way using re will be

import re, clr

text = 'some string... this part will be removed.'

text= re.search(r'(\A.*)\.\.\..+',url,re.DOTALL|re.IGNORECASE).group(1)

// text = some string

SSH Private Key Permissions using Git GUI or ssh-keygen are too open

I was able to fix this by doing two things, though you may not have to do step 1.

  1. copy from cygwin ssh.exe and all cyg*.dll into Git's bin directory (this may not be necessary but it is a step I took but this alone did not fix things)

  2. follow the steps from: http://zylstra.wordpress.com/2008/08/29/overcome-herokus-permission-denied-publickey-problem/

    I added some details to my ~/.ssh/config file:

Host heroku.com
Hostname heroku.com
Port 22
IdentitiesOnly yes
IdentityFile ~/.ssh/id_heroku
TCPKeepAlive yes
User brandon

I had to use User as my email address for heroku.com Note: this means you need to create a key, I followed this to create the key and when it prompts for the name of the key, be sure to specify id_heroku http://help.github.com/win-set-up-git/

  1. then add the key:
    heroku keys:add ~/.ssh/id_heroku.pub

Remove all the elements that occur in one list from another

Use the Python set type. That would be the most Pythonic. :)

Also, since it's native, it should be the most optimized method too.

See:

http://docs.python.org/library/stdtypes.html#set

http://docs.python.org/library/sets.htm (for older python)

# Using Python 2.7 set literal format.
# Otherwise, use: l1 = set([1,2,6,8])
#
l1 = {1,2,6,8}
l2 = {2,3,5,8}
l3 = l1 - l2

Reading Data From Database and storing in Array List object

Try creating new instance of customer every time e.g.

         while (rs.next()) {

        Customer customer = new Customer();
        customer.setId(rs.getInt("id"));
        customer.setName(rs.getString("name"));

        customer.setAddress(rs.getString("address"));
        customer.setPhone(rs.getString("phone"));
        customer.setEmail(rs.getString("email"));
        customer.setBountPoints(rs.getInt("bonuspoint"));
        customer.setTotalsale(rs.getInt("totalsale"));

        customers.add(customer);


    }

Remove Rows From Data Frame where a Row matches a String

if you wish to using dplyr, for to remove row "Foo":

df %>%
 filter(!C=="Foo")

How to force garbage collection in Java?

Really, I don't get you. But to be clear about "Infinite Object Creation" I meant that there is some piece of code at my big system do creation of objects whom handles and alive in memory, I could not get this piece of code actually, just gesture!!

This is correct, only gesture. You have pretty much the standard answers already given by several posters. Let's take this one by one:

  1. I could not get this piece of code actually

Correct, there is no actual jvm - such is only a specification, a bunch of computer science describing a desired behaviour ... I recently dug into initializing Java objects from native code. To get what you want, the only way is to do what is called aggressive nulling. The mistakes if done wrong are so bad doing that we have to limit ourselves to the original scope of the question:

  1. some piece of code at my big system do creation of objects

Most of the posters here will assume you are saying you are working to an interface, if such we would have to see if you are being handed the entire object or one item at a time.

If you no longer need an object, you can assign null to the object but if you get it wrong there is a null pointer exception generated. I bet you can achieve better work if you use NIO

Any time you or I or anyone else gets: "Please I need that horribly." it is almost universal precursor to near total destruction of what you are trying to work on .... write us a small sample code, sanitizing from it any actual code used and show us your question.

Do not get frustrated. Often what this resolves to is your dba is using a package bought somewhere and the original design is not tweaked for massive data structures.

That is very common.

SimpleDateFormat returns 24-hour date: how to get 12-hour date?

See code example below:

SimpleDateFormat df = new SimpleDateFormat("hh:mm");
String formattedDate = df.format(new Date());
out.println(formattedDate);

How do I check if a string contains a specific word?

To determine whether a string contains another string you can use the PHP function strpos().

int strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )

<?php

$haystack = 'how are you';
$needle = 'are';

if (strpos($haystack,$needle) !== false) {
    echo "$haystack contains $needle";
}

?>

CAUTION:

If the needle you are searching for is at the beginning of the haystack it will return position 0, if you do a == compare that will not work, you will need to do a ===

A == sign is a comparison and tests whether the variable / expression / constant to the left has the same value as the variable / expression / constant to the right.

A === sign is a comparison to see whether two variables / expresions / constants are equal AND have the same type - i.e. both are strings or both are integers.

using "if" and "else" Stored Procedures MySQL

you can use CASE WHEN as follow as achieve the as IF ELSE.

SELECT FROM A a 
LEFT JOIN B b 
ON a.col1 = b.col1 
AND (CASE 
        WHEN a.col2 like '0%' then TRIM(LEADING '0' FROM a.col2)
        ELSE substring(a.col2,1,2)
    END
)=b.col2; 

p.s:just in case somebody needs this way.

Print the data in ResultSet along with column names

For those who wanted more better version of the resultset printing as util class This was really helpful for printing resultset and does many things from a single util... thanks to Hami Torun!

In this class printResultSet uses ResultSetMetaData in a generic way have a look at it..


import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;

public final class DBTablePrinter {

    /**
     * Column type category for CHAR, VARCHAR
     * and similar text columns.
     */
    public static final int CATEGORY_STRING = 1;
    /**
     * Column type category for TINYINT, SMALLINT,
     * INT and BIGINT columns.
     */
    public static final int CATEGORY_INTEGER = 2;
    /**
     * Column type category for REAL, DOUBLE,
     * and DECIMAL columns.
     */
    public static final int CATEGORY_DOUBLE = 3;
    /**
     * Column type category for date and time related columns like
     * DATE, TIME, TIMESTAMP etc.
     */
    public static final int CATEGORY_DATETIME = 4;
    /**
     * Column type category for BOOLEAN columns.
     */
    public static final int CATEGORY_BOOLEAN = 5;
    /**
     * Column type category for types for which the type name
     * will be printed instead of the content, like BLOB,
     * BINARY, ARRAY etc.
     */
    public static final int CATEGORY_OTHER = 0;
    /**
     * Default maximum number of rows to query and print.
     */
    private static final int DEFAULT_MAX_ROWS = 10;
    /**
     * Default maximum width for text columns
     * (like a VARCHAR) column.
     */
    private static final int DEFAULT_MAX_TEXT_COL_WIDTH = 150;

    /**
     * Overloaded method that prints rows from table tableName
     * to standard out using the given database connection
     * conn. Total number of rows will be limited to
     * {@link #DEFAULT_MAX_ROWS} and
     * {@link #DEFAULT_MAX_TEXT_COL_WIDTH} will be used to limit
     * the width of text columns (like a VARCHAR column).
     *
     * @param conn      Database connection object (java.sql.Connection)
     * @param tableName Name of the database table
     */
    public static void printTable(Connection conn, String tableName) {
        printTable(conn, tableName, DEFAULT_MAX_ROWS, DEFAULT_MAX_TEXT_COL_WIDTH);
    }

    /**
     * Overloaded method that prints rows from table tableName
     * to standard out using the given database connection
     * conn. Total number of rows will be limited to
     * maxRows and
     * {@link #DEFAULT_MAX_TEXT_COL_WIDTH} will be used to limit
     * the width of text columns (like a VARCHAR column).
     *
     * @param conn      Database connection object (java.sql.Connection)
     * @param tableName Name of the database table
     * @param maxRows   Number of max. rows to query and print
     */
    public static void printTable(Connection conn, String tableName, int maxRows) {
        printTable(conn, tableName, maxRows, DEFAULT_MAX_TEXT_COL_WIDTH);
    }

    /**
     * Overloaded method that prints rows from table tableName
     * to standard out using the given database connection
     * conn. Total number of rows will be limited to
     * maxRows and
     * maxStringColWidth will be used to limit
     * the width of text columns (like a VARCHAR column).
     *
     * @param conn              Database connection object (java.sql.Connection)
     * @param tableName         Name of the database table
     * @param maxRows           Number of max. rows to query and print
     * @param maxStringColWidth Max. width of text columns
     */
    public static void printTable(Connection conn, String tableName, int maxRows, int maxStringColWidth) {
        if (conn == null) {
            System.err.println("DBTablePrinter Error: No connection to database (Connection is null)!");
            return;
        }
        if (tableName == null) {
            System.err.println("DBTablePrinter Error: No table name (tableName is null)!");
            return;
        }
        if (tableName.length() == 0) {
            System.err.println("DBTablePrinter Error: Empty table name!");
            return;
        }
        if (maxRows 
     * ResultSet to standard out using {@link #DEFAULT_MAX_TEXT_COL_WIDTH}
     * to limit the width of text columns.
     *
     * @param rs The ResultSet to print
     */
    public static void printResultSet(ResultSet rs) {
        printResultSet(rs, DEFAULT_MAX_TEXT_COL_WIDTH);
    }

    /**
     * Overloaded method to print rows of a 
     * ResultSet to standard out using maxStringColWidth
     * to limit the width of text columns.
     *
     * @param rs                The ResultSet to print
     * @param maxStringColWidth Max. width of text columns
     */
    public static void printResultSet(ResultSet rs, int maxStringColWidth) {
        try {
            if (rs == null) {
                System.err.println("DBTablePrinter Error: Result set is null!");
                return;
            }
            if (rs.isClosed()) {
                System.err.println("DBTablePrinter Error: Result Set is closed!");
                return;
            }
            if (maxStringColWidth  columns = new ArrayList(columnCount);

            // List of table names. Can be more than one if it is a joined
            // table query
            List tableNames = new ArrayList(columnCount);

            // Get the columns and their meta data.
            // NOTE: columnIndex for rsmd.getXXX methods STARTS AT 1 NOT 0
            for (int i = 1; i  maxStringColWidth) {
                                value = value.substring(0, maxStringColWidth - 3) + "...";
                            }
                            break;
                    }

                    // Adjust the column width
                    c.setWidth(value.length() > c.getWidth() ? value.length() : c.getWidth());
                    c.addValue(value);
                } // END of for loop columnCount
                rowCount++;

            } // END of while (rs.next)

            /*
            At this point we have gone through meta data, get the
            columns and created all Column objects, iterated over the
            ResultSet rows, populated the column values and adjusted
            the column widths.
            We cannot start printing just yet because we have to prepare
            a row separator String.
             */

            // For the fun of it, I will use StringBuilder
            StringBuilder strToPrint = new StringBuilder();
            StringBuilder rowSeparator = new StringBuilder();

            /*
            Prepare column labels to print as well as the row separator.
            It should look something like this:
            +--------+------------+------------+-----------+  (row separator)
            | EMP_NO | BIRTH_DATE | FIRST_NAME | LAST_NAME |  (labels row)
            +--------+------------+------------+-----------+  (row separator)
             */

            // Iterate over columns
            for (Column c : columns) {
                int width = c.getWidth();

                // Center the column label
                String toPrint;
                String name = c.getLabel();
                int diff = width - name.length();

                if ((diff % 2) == 1) {
                    // diff is not divisible by 2, add 1 to width (and diff)
                    // so that we can have equal padding to the left and right
                    // of the column label.
                    width++;
                    diff++;
                    c.setWidth(width);
                }

                int paddingSize = diff / 2; // InteliJ says casting to int is redundant.

                // Cool String repeater code thanks to user102008 at stackoverflow.com

                String padding = new String(new char[paddingSize]).replace("\0", " ");

                toPrint = "| " + padding + name + padding + " ";
                // END centering the column label

                strToPrint.append(toPrint);

                rowSeparator.append("+");
                rowSeparator.append(new String(new char[width + 2]).replace("\0", "-"));
            }

            String lineSeparator = System.getProperty("line.separator");

            // Is this really necessary ??
            lineSeparator = lineSeparator == null ? "\n" : lineSeparator;

            rowSeparator.append("+").append(lineSeparator);

            strToPrint.append("|").append(lineSeparator);
            strToPrint.insert(0, rowSeparator);
            strToPrint.append(rowSeparator);

            StringJoiner sj = new StringJoiner(", ");
            for (String name : tableNames) {
                sj.add(name);
            }

            String info = "Printing " + rowCount;
            info += rowCount > 1 ? " rows from " : " row from ";
            info += tableNames.size() > 1 ? "tables " : "table ";
            info += sj.toString();

            System.out.println(info);

            // Print out the formatted column labels
            System.out.print(strToPrint.toString());

            String format;

            // Print out the rows
            for (int i = 0; i 
     * Integers should not be truncated so column widths should
     * be adjusted without a column width limit. Text columns should be
     * left justified and can be truncated to a max. column width etc...

*

* See also: * java.sql.Types * * @param type Generic SQL type * @return The category this type belongs to */ private static int whichCategory(int type) { switch (type) { case Types.BIGINT: case Types.TINYINT: case Types.SMALLINT: case Types.INTEGER: return CATEGORY_INTEGER; case Types.REAL: case Types.DOUBLE: case Types.DECIMAL: return CATEGORY_DOUBLE; case Types.DATE: case Types.TIME: case Types.TIME_WITH_TIMEZONE: case Types.TIMESTAMP: case Types.TIMESTAMP_WITH_TIMEZONE: return CATEGORY_DATETIME; case Types.BOOLEAN: return CATEGORY_BOOLEAN; case Types.VARCHAR: case Types.NVARCHAR: case Types.LONGVARCHAR: case Types.LONGNVARCHAR: case Types.CHAR: case Types.NCHAR: return CATEGORY_STRING; default: return CATEGORY_OTHER; } } /** * Represents a database table column. */ private static class Column { /** * Column label. */ private String label; /** * Generic SQL type of the column as defined in * * java.sql.Types * . */ private int type; /** * Generic SQL type name of the column as defined in * * java.sql.Types * . */ private String typeName; /** * Width of the column that will be adjusted according to column label * and values to be printed. */ private int width = 0; /** * Column values from each row of a ResultSet. */ private List values = new ArrayList(); /** * Flag for text justification using String.format. * Empty string ("") to justify right, * dash (-) to justify left. * * @see #justifyLeft() */ private String justifyFlag = ""; /** * Column type category. The columns will be categorised according * to their column types and specific needs to print them correctly. */ private int typeCategory = 0; /** * Constructs a new Column with a column label, * generic SQL type and type name (as defined in * * java.sql.Types * ) * * @param label Column label or name * @param type Generic SQL type * @param typeName Generic SQL type name */ public Column(String label, int type, String typeName) { this.label = label; this.type = type; this.typeName = typeName; } /** * Returns the column label * * @return Column label */ public String getLabel() { return label; } /** * Returns the generic SQL type of the column * * @return Generic SQL type */ public int getType() { return type; } /** * Returns the generic SQL type name of the column * * @return Generic SQL type name */ public String getTypeName() { return typeName; } /** * Returns the width of the column * * @return Column width */ public int getWidth() { return width; } /** * Sets the width of the column to width * * @param width Width of the column */ public void setWidth(int width) { this.width = width; } /** * Adds a String representation (value) * of a value to this column object's {@link #values} list. * These values will come from each row of a * * ResultSet * of a database query. * * @param value The column value to add to {@link #values} */ public void addValue(String value) { values.add(value); } /** * Returns the column value at row index i. * Note that the index starts at 0 so that getValue(0) * will get the value for this column from the first row * of a * ResultSet. * * @param i The index of the column value to get * @return The String representation of the value */ public String getValue(int i) { return values.get(i); } /** * Returns the value of the {@link #justifyFlag}. The column * values will be printed using String.format and * this flag will be used to right or left justify the text. * * @return The {@link #justifyFlag} of this column * @see #justifyLeft() */ public String getJustifyFlag() { return justifyFlag; } /** * Sets {@link #justifyFlag} to "-" so that * the column value will be left justified when printed with * String.format. Typically numbers will be right * justified and text will be left justified. */ public void justifyLeft() { this.justifyFlag = "-"; } /** * Returns the generic SQL type category of the column * * @return The {@link #typeCategory} of the column */ public int getTypeCategory() { return typeCategory; } /** * Sets the {@link #typeCategory} of the column * * @param typeCategory The type category */ public void setTypeCategory(int typeCategory) { this.typeCategory = typeCategory; } } }

This is the scala version of doing this... which will print column names and data as well in a generic way...

def printQuery(res: ResultSet): Unit = {
    val rsmd = res.getMetaData
    val columnCount = rsmd.getColumnCount
    var rowCnt = 0
    val s = StringBuilder.newBuilder
    while (res.next()) {

      s.clear()
      if (rowCnt == 0) {
        s.append("| ")
        for (i <- 1 to columnCount) {
          val name = rsmd.getColumnName(i)
          s.append(name)
          s.append("| ")
        }
        s.append("\n")
      }
      rowCnt += 1
      s.append("| ")
      for (i <- 1 to columnCount) {
        if (i > 1)
          s.append(" | ")
        s.append(res.getString(i))
      }
      s.append(" |")
      System.out.println(s)
    }
    System.out.println(s"TOTAL: $rowCnt rows")
  }

Using async/await for multiple tasks

You can use Task.WhenAll function that you can pass n tasks; Task.WhenAll will return a task which runs to completion when all the tasks that you passed to Task.WhenAll complete. You have to wait asynchronously on Task.WhenAll so that you'll not block your UI thread:

   public async Task DoSomeThing() {

       var Task[] tasks = new Task[numTasks];
       for(int i = 0; i < numTask; i++)
       {
          tasks[i] = CallSomeAsync();
       }
       await Task.WhenAll(tasks);
       // code that'll execute on UI thread
   }

How do I remedy "The breakpoint will not currently be hit. No symbols have been loaded for this document." warning?

I was integrating a C# application with a static library using VS10 - which I'm new to. I wrote a managed code dll to interface them. I could set breakpoints everywhere but the static lib. I got the message described above - no symbols have been loaded for this document. I tried many of the suggestions above. I could see that the symbols weren't being loaded. I finally noticed a check box Configuration Debug, Enable unmanaged code debugging. That allowed me to set breakpoints in the static lib functions.

Online code beautifier and formatter

What language?? There are different tools for almost every imaginable programming language, since they all have different syntactic rules and conventions.

Good ol' indent is a nice, customizable, command-line utility to format C and C++ programs.

Unable instantiate android.gms.maps.MapFragment

I faced the same problem ant it took me tow days to figure out a solution that worked for me :

  1. Delete the project google-play-services_lib (right click on the project delete )
  2. Delete the project containing the Google maps demo ( MainActivity in my case ) if you have one
  3. Copy the project google-play-services_lib( extras\google\google_play_services\libproject\google-play-services_lib) into your workspace then import it as General project (File->import->existing projects into workspase )
  4. Right click on your project ( in which you want to load the map ) -> Android -> add (under library ) google-play-services_lib

You should see something like this :

notice the

Note : You should not have something like this ( the project should be referred from your workspace ):

enter image description here

I think that the problem is that tow projects are referencing the same library

CSS Select box arrow style

Please follow the way like below:

_x000D_
_x000D_
.selectParent {_x000D_
 width:120px;_x000D_
 overflow:hidden;   _x000D_
}_x000D_
.selectParent select { _x000D_
 display: block;_x000D_
 width: 100%;_x000D_
 padding: 2px 25px 2px 2px; _x000D_
 border: none; _x000D_
 background: url("http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/16x16/br_down.png") right center no-repeat; _x000D_
 appearance: none; _x000D_
 -webkit-appearance: none;_x000D_
 -moz-appearance: none; _x000D_
}_x000D_
.selectParent.left select {_x000D_
 direction: rtl;_x000D_
 padding: 2px 2px 2px 25px;_x000D_
 background-position: left center;_x000D_
}_x000D_
/* for IE and Edge */ _x000D_
select::-ms-expand { _x000D_
 display: none; _x000D_
}
_x000D_
<div class="selectParent">_x000D_
  <select>_x000D_
    <option value="1">Option 1</option>_x000D_
    <option value="2">Option 2</option>           _x000D_
   </select>_x000D_
</div>_x000D_
<br />_x000D_
<div class="selectParent left">_x000D_
  <select>_x000D_
    <option value="1">Option 1</option>_x000D_
    <option value="2">Option 2</option>           _x000D_
   </select>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Ignore files that have already been committed to a Git repository

another problem I had was I placed an inline comment.

tmp/*   # ignore my tmp folder (this doesn't work)

this works

# ignore my tmp folder
tmp/

iPhone App Development on Ubuntu

It can be done!!!!!!

There is someone who did it.

Enjoy :)

Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger

During runtime your application is unable to find the jar.

Taken from this answer by Jared:

It is important to keep two different exceptions straight in our head in this case:

  1. java.lang.ClassNotFoundException This an Exception, it indicates that the class was not found on the classpath. This indicates that we were trying to load the class definition, and the class did not exist on the classpath.

  2. java.lang.NoClassDefFoundError This is Error, it indicates that the JVM looked in its internal class definition data structure for the definition of a class and did not find it. This is different than saying that it could not be loaded from the classpath. Usually this indicates that we previously attempted to load a class from the classpath, but it failed for some reason - now we're trying again, but we're not even going to try to load it, because we failed loading it earlier. The earlier failure could be a ClassNotFoundException or an ExceptionInInitializerError (indicating a failure in the static initialization block) or any number of other problems. The point is, a NoClassDefFoundError is not necessarily a classpath problem.

for similarities and differences

Getting the number of filled cells in a column (VBA)

If you want to find the last populated cell in a particular column, the best method is:

Range("A" & Rows.Count).End(xlUp).Row

This code uses the very last cell in the entire column (65536 for Excel 2003, 1048576 in later versions), and then find the first populated cell above it. This has the ability to ignore "breaks" in your data and find the true last row.

How to bind bootstrap popover on dynamic elements

Update

If your popover is going to have a selector that is consistent then you can make use of selector property of popover constructor.

var popOverSettings = {
    placement: 'bottom',
    container: 'body',
    html: true,
    selector: '[rel="popover"]', //Sepcify the selector here
    content: function () {
        return $('#popover-content').html();
    }
}

$('body').popover(popOverSettings);

Demo

Other ways:

  1. (Standard Way) Bind the popover again to the new items being inserted. Save the popoversettings in an external variable.
  2. Use Mutation Event/Mutation Observer to identify if a particular element has been inserted on to the ul or an element.

Source

var popOverSettings = { //Save the setting for later use as well
    placement: 'bottom',
    container: 'body',
    html: true,
    //content:" <div style='color:red'>This is your div content</div>"
    content: function () {
        return $('#popover-content').html();
    }

}

$('ul').on('DOMNodeInserted', function () { //listed for new items inserted onto ul
    $(event.target).popover(popOverSettings);
});

$("button[rel=popover]").popover(popOverSettings);
$('.pop-Add').click(function () {
    $('ul').append("<li class='project-name'>     <a>project name 2        <button class='pop-function' rel='popover'></button>     </a>   </li>");
});

But it is not recommended to use DOMNodeInserted Mutation Event for performance issues as well as support. This has been deprecated as well. So your best bet would be to save the setting and bind after you update with new element.

Demo

Another recommended way is to use MutationObserver instead of MutationEvent according to MDN, but again support in some browsers are unknown and performance a concern.

MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
// create an observer instance
var observer = new MutationObserver(function (mutations) {
    mutations.forEach(function (mutation) {
        $(mutation.addedNodes).popover(popOverSettings);
    });
});

// configuration of the observer:
var config = {
     attributes: true, 
     childList: true, 
     characterData: true
};

// pass in the target node, as well as the observer options
observer.observe($('ul')[0], config);

Demo

Deleting a local branch with Git

You probably have Test_Branch checked out, and you may not delete it while it is your current branch. Check out a different branch, and then try deleting Test_Branch.

MySQL Orderby a number, Nulls last

Why don't you order by NULLS LAST?

SELECT * 
FROM tablename
WHERE visible = 1 
ORDER BY position ASC NULLS LAST, id DESC 

Change variable name in for loop using R

You could use assign, but using assign (or get) is often a symptom of a programming structure that is not very R like. Typically, lists or matrices allow cleaner solutions.

  • with a list:

    A <- lapply (1 : 10, function (x) d + rnorm (3))
    
  • with a matrix:

    A <- matrix (rep (d, each = 10) + rnorm (30), nrow = 10)
    

Convert Datetime column from UTC to local time in select statement

Ron's answer contains an error. It uses 2:00 AM local time where the UTC equivalent is required. I don't have enough reputation points to comment on Ron's answer so a corrected version appears below:

-- =============================================
-- Author:      Ron Smith
-- Create date: 2013-10-23
-- Description: Converts UTC to DST
--              based on passed Standard offset
-- =============================================
CREATE FUNCTION [dbo].[fn_UTC_to_DST]
(
    @UTC datetime,
    @StandardOffset int
)
RETURNS datetime
AS
BEGIN

declare 
    @DST datetime,
    @SSM datetime, -- Second Sunday in March
    @FSN datetime  -- First Sunday in November
-- get DST Range
set @SSM = datename(year,@UTC) + '0314' 
set @SSM = dateadd(hour,2 - @StandardOffset,dateadd(day,datepart(dw,@SSM)*-1+1,@SSM))
set @FSN = datename(year,@UTC) + '1107'
set @FSN = dateadd(second,-1,dateadd(hour,2 - (@StandardOffset + 1),dateadd(day,datepart(dw,@FSN)*-1+1,@FSN)))

-- add an hour to @StandardOffset if @UTC is in DST range
if @UTC between @SSM and @FSN
    set @StandardOffset = @StandardOffset + 1

-- convert to DST
set @DST = dateadd(hour,@StandardOffset,@UTC)

-- return converted datetime
return @DST

END

Turn off enclosing <p> tags in CKEditor 3.0

Found it!

ckeditor.js line #91 ... search for

B.config.enterMode==3?'div':'p'

change to

B.config.enterMode==3?'div':'' (NO P!)

Dump your cache and BAM!

Bootstrap 3: Scroll bars

You need to use the overflow option, but with the following parameters:

.nav {
    max-height:300px;
    overflow-y:auto;  
}

Use overflow-y:auto; so the scrollbar only appears when the content exceeds the maximum height.

If you use overflow-y:scroll, the scrollbar will always be visible - on all .nav - regardless if the content exceeds the maximum heigh or not.

Presumably you want something that adapts itself to the content rather then the the opposite.

Hope it may helpful

Generating (pseudo)random alpha-numeric strings

function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}
echo generateRandomString();

Check if a String contains numbers Java

Pattern p = Pattern.compile("(([A-Z].*[0-9])");
Matcher m = p.matcher("TEST 123");
boolean b = m.find();
System.out.println(b);

What does 'low in coupling and high in cohesion' mean

Short and clear answer

  • High cohesion: Elements within one class/module should functionally belong together and do one particular thing.
  • Loose coupling: Among different classes/modules should be minimal dependency.

referenced before assignment error in python

My Scenario

def example():
    cl = [0, 1]
    def inner():
        #cl = [1, 2] # access this way will throw `reference before assignment`
        cl[0] = 1 
        cl[1] = 2   # these won't

    inner()

Bootstrap 3 Collapse show state with Chevron icon

working simple example

  • get the body condition shown/hidden
  • get to its parent att
  • get find icon
  • change icon

enter simple

HTML:

<body>
    <div class="accordion-group">
        <div class="accordion-heading">
            <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#jai">Jai</a>
        </div>
        <div id="jai" class="accordion-body collapse in">
            <div>
                <div class="accordion-inner">body content 1</div>
            </div>
        </div>
    </div>
    <div class="accordion-group">
        <div class="accordion-heading">
            <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapseTwo">jai2</a>
        </div>
        <div id="collapseTwo" class="accordion-body collapse">
            <div>
                <div class="accordion-inner">body content 2</div>
            </div>
        </div>
    </div>
    <div class="accordion-group">
        <div class="accordion-heading">
            <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapse3">jai3</a>
        </div>
        <div id="collapse3" class="accordion-body collapse">
            <div>
                <div class="accordion-inner">body content 3</div>
            </div>
        </div>
    </div>
</body>

JavaScript

$('div.accordion-body').on('shown', function () {
    $(this).parent("div").find(".icon-chevron-down")
           .removeClass("icon-chevron-down").addClass("icon-chevron-up");
});

$('div.accordion-body').on('hidden', function () {
    $(this).parent("div").find(".icon-chevron-up")
           .removeClass("icon-chevron-up").addClass("icon-chevron-down");
});

HTML iframe - disable scroll

Just add an iframe styled like either option below. I hope this solves the problem.

1st option:

<iframe src="https://www.skyhub.ca/featured-listing" style="position: absolute; visibility: hidden;" onload="this.style.position='static'; this.style.visibility='visible';" scrolling="no" frameborder="0" marginheight="0px" marginwidth="0px" height="400px" width="1200px" allowfullscreen></iframe>

2nd option:

<iframe src="https://www.skyhub.ca/featured-listing" style="display: none;" onload="this.style.display='block';" scrolling="no" frameborder="0" marginheight="0px" marginwidth="0px" height="400px" width="1200px" allowfullscreen></iframe>

What is the purpose of global.asax in asp.net

MSDN has an outline of the purpose of the global.asax file.

Effectively, global.asax allows you to write code that runs in response to "system level" events, such as the application starting, a session ending, an application error occuring, without having to try and shoe-horn that code into each and every page of your site.

You can use it by by choosing Add > New Item > Global Application Class in Visual Studio. Once you've added the file, you can add code under any of the events that are listed (and created by default, at least in Visual Studio 2008):

  • Application_Start
  • Application_End
  • Session_Start
  • Session_End
  • Application_BeginRequest
  • Application_AuthenticateRequest
  • Application_Error

There are other events that you can also hook into, such as "LogRequest".

How do you change the datatype of a column in SQL Server?

Don't forget nullability.

ALTER TABLE <schemaName>.<tableName>
ALTER COLUMN <columnName> nvarchar(200) [NULL|NOT NULL]

Can you recommend a free light-weight MySQL GUI for Linux?

I really like the MySQL collection of of GUI Tools. They aren't too large or resource hungry.

There are quite a few options here as well. Of the applications presented on that page, I like SQL Buddy - it does require a web server, however.

how can I login anonymously with ftp (/usr/bin/ftp)?

Anonymous ftp logins are usually the username 'anonymous' with the user's email address as the password. Some servers parse the password to ensure it looks like an email address.

User:  anonymous
Password:  [email protected]

Private vs Protected - Visibility Good-Practice Concern

I read an article a while ago that talked about locking down every class as much as possible. Make everything final and private unless you have an immediate need to expose some data or functionality to the outside world. It's always easy to expand the scope to be more permissible later on, but not the other way around. First consider making as many things as possible final which will make choosing between private and protected much easier.

  1. Make all classes final unless you need to subclass them right away.
  2. Make all methods final unless you need to subclass and override them right away.
  3. Make all method parameters final unless you need to change them within the body of the method, which is kinda awkward most of the times anyways.

Now if you're left with a final class, then make everything private unless something is absolutely needed by the world - make that public.

If you're left with a class that does have subclass(es), then carefully examine every property and method. First consider if you even want to expose that property/method to subclasses. If you do, then consider whether a subclass can wreak havoc on your object if it messed up the property value or method implementation in the process of overriding. If it's possible, and you want to protect your class' property/method even from subclasses (sounds ironic, I know), then make it private. Otherwise make it protected.

Disclaimer: I don't program much in Java :)

Shell - Write variable contents to a file

All of the above work, but also have to work around a problem (escapes and special characters) that doesn't need to occur in the first place: Special characters when the variable is expanded by the shell. Just don't do that (variable expansion) in the first place. Use the variable directly, without expansion.

Also, if your variable contains a secret and you want to copy that secret into a file, you might want to not have expansion in the command line as tracing/command echo of the shell commands might reveal the secret. Means, all answers which use $var in the command line may have a potential security risk by exposing the variable contents to tracing and logging of the shell.

Use this:

printenv var >file

That means, in case of the OP question:

printenv var >"$destfile"

Note: variable names are case sensitive.

What are naming conventions for MongoDB?

Until we get SERVER-863 keeping the field names as short as possible is advisable especially where you have a lot of records.

Depending on your use case, field names can have a huge impact on storage. Cant understand why this is not a higher priority for MongoDb, as this will have a positive impact on all users. If nothing else, we can start being more descriptive with our field names, without thinking twice about bandwidth & storage costs.

Please do vote.

How do you test to see if a double is equal to NaN?

Beginners needs practical examples. so try the following code.

public class Not_a_Number {

public static void main(String[] args) {
    // TODO Auto-generated method stub

    String message = "0.0/0.0 is NaN.\nsimilarly Math.sqrt(-1) is NaN.";        
    String dottedLine = "------------------------------------------------";     

    Double numerator = -2.0;
    Double denominator = -2.0;      
    while (denominator <= 1) {
        Double x = numerator/denominator;           
        Double y = new Double (x);
        boolean z = y.isNaN();
        System.out.println("y =  " + y);
        System.out.println("z =  " + z);
        if (z == true){
            System.out.println(message);                
        }
        else {
            System.out.println("Hi, everyone"); 
        }
        numerator = numerator + 1;
        denominator = denominator +1;
        System.out.println(dottedLine);         
    } // end of while

} // end of main

} // end of class

Linux / Bash, using ps -o to get process by specific name?

Sometimes you need to grep the process by name - in that case:

ps aux | grep simple-scan

Example output:

simple-scan  1090  0.0  0.1   4248  1432 ?        S    Jun11   0:00

PadLeft function in T-SQL

This is what I normally use when I need to pad a value.

SET @PaddedValue = REPLICATE('0', @Length - LEN(@OrigValue)) + CAST(@OrigValue as VARCHAR)

Upload File With Ajax XmlHttpRequest

  1. There is no such thing as xhr.file = file;; the file object is not supposed to be attached this way.
  2. xhr.send(file) doesn't send the file. You have to use the FormData object to wrap the file into a multipart/form-data post data object:

    var formData = new FormData();
    formData.append("thefile", file);
    xhr.send(formData);
    

After that, the file can be access in $_FILES['thefile'] (if you are using PHP).

Remember, MDC and Mozilla Hack demos are your best friends.

EDIT: The (2) above was incorrect. It does send the file, but it would send it as raw post data. That means you would have to parse it yourself on the server (and it's often not possible, depend on server configuration). Read how to get raw post data in PHP here.

How to make ConstraintLayout work with percentage values?

With the ConstraintLayout v1.1.2, the dimension should be set to 0dp and then set the layout_constraintWidth_percent or layout_constraintHeight_percent attributes to a value between 0 and 1 like :

<!-- 50% width centered Button -->
<Button
    android:id="@+id/button"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintWidth_percent=".5" />

(You don't need to set app:layout_constraintWidth_default="percent" or app:layout_constraintHeight_default="percent" with ConstraintLayout 1.1.2 and following versions)

Removing u in list

u'AB' is just a text representation of the corresponding Unicode string. Here're several methods that create exactly the same Unicode string:

L = [u'AB', u'\x41\x42', u'\u0041\u0042', unichr(65) + unichr(66)]
print u", ".join(L)

Output

AB, AB, AB, AB

There is no u'' in memory. It is just the way to represent the unicode object in Python 2 (how you would write the Unicode string literal in a Python source code). By default print L is equivalent to print "[%s]" % ", ".join(map(repr, L)) i.e., repr() function is called for each list item:

print L
print "[%s]" % ", ".join(map(repr, L))

Output

[u'AB', u'AB', u'AB', u'AB']
[u'AB', u'AB', u'AB', u'AB']

If you are working in a REPL then a customizable sys.displayhook is used that calls repr() on each object by default:

>>> L = [u'AB', u'\x41\x42', u'\u0041\u0042', unichr(65) + unichr(66)]
>>> L
[u'AB', u'AB', u'AB', u'AB']
>>> ", ".join(L)
u'AB, AB, AB, AB'
>>> print ", ".join(L)
AB, AB, AB, AB

Don't encode to bytes. Print unicode directly.


In your specific case, I would create a Python list and use json.dumps() to serialize it instead of using string formatting to create JSON text:

#!/usr/bin/env python2
import json
# ...
test = [dict(email=player.email, gem=player.gem)
        for player in players]
print test
print json.dumps(test)

Output

[{'email': u'[email protected]', 'gem': 0}, {'email': u'test', 'gem': 0}, {'email': u'test', 'gem': 0}, {'email': u'test', 'gem': 0}, {'email': u'test', 'gem': 0}, {'email': u'test1', 'gem': 0}]
[{"email": "[email protected]", "gem": 0}, {"email": "test", "gem": 0}, {"email": "test", "gem": 0}, {"email": "test", "gem": 0}, {"email": "test", "gem": 0}, {"email": "test1", "gem": 0}]

Use mysql_fetch_array() with foreach() instead of while()

You can code like this:

$query_select = "SELECT * FROM shouts ORDER BY id DESC LIMIT 8;";
$result_select = mysql_query($query_select) or die(mysql_error());
$rows = array();
while($row = mysql_fetch_array($result_select))
    $rows[] = $row;
foreach($rows as $row){ 
    $ename = stripslashes($row['name']);
    $eemail = stripcslashes($row['email']);
    $epost = stripslashes($row['post']);
    $eid = $row['id'];

    $grav_url = "http://www.gravatar.com/avatar.php?gravatar_id=".md5(strtolower($eemail))."&size=70";

    echo ('<img src = "' . $grav_url . '" alt="Gravatar">'.'<br/>');

    echo $eid . '<br/>';

    echo $ename . '<br/>';

    echo $eemail . '<br/>';

    echo $epost . '<br/><br/><br/><br/>';
}

As you can see, it's still need a loop while to get data from mysql_fetch_array

Is there a way to run Bash scripts on Windows?

Install Cygwin, which includes Bash among many other GNU and Unix utilities (without whom its unlikely that bash will be very useful anyway).

Another option is MinGW's MSYS which includes bash and a smaller set of the more important utilities such as awk. Personally I would have preferred Cygwin because it includes such heavy lifting tools as Perl and Python which I find I cannot live without, while MSYS skimps on these and assumes you are going to install them yourself.

Updated: If anyone is interested in this answer and is running MS-Windows 10, please note that MS-Windows 10 has a "Windows Subsystem For Linux" feature which - once enabled - allows you to install a user-mode image of Ubuntu and then run Bash on that. This provides 100% compatibility with Ubuntu for debugging and running Bash scripts, but this setup is completely standalone from Windows and you cannot use Bash scripts to interact with Windows features (such as processes and APIs) except for limited access to files through the DrvFS feature.

TypeError: unhashable type: 'dict'

You're trying to use a dict as a key to another dict or in a set. That does not work because the keys have to be hashable. As a general rule, only immutable objects (strings, integers, floats, frozensets, tuples of immutables) are hashable (though exceptions are possible). So this does not work:

>>> dict_key = {"a": "b"}
>>> some_dict[dict_key] = True
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'

To use a dict as a key you need to turn it into something that may be hashed first. If the dict you wish to use as key consists of only immutable values, you can create a hashable representation of it like this:

>>> key = frozenset(dict_key.items())

Now you may use key as a key in a dict or set:

>>> some_dict[key] = True
>>> some_dict
{frozenset([('a', 'b')]): True}

Of course you need to repeat the exercise whenever you want to look up something using a dict:

>>> some_dict[dict_key]                     # Doesn't work
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'
>>> some_dict[frozenset(dict_key.items())]  # Works
True

If the dict you wish to use as key has values that are themselves dicts and/or lists, you need to recursively "freeze" the prospective key. Here's a starting point:

def freeze(d):
    if isinstance(d, dict):
        return frozenset((key, freeze(value)) for key, value in d.items())
    elif isinstance(d, list):
        return tuple(freeze(value) for value in d)
    return d

How do I create a nice-looking DMG for Mac OS X using command-line tools?

I've just written a new (friendly) command line utility to do this. It doesn’t rely on Finder/AppleScript, or on any of the (deprecated) Alias Manager APIs, and it’s easy to configure and use.

Anyway, anyone who is interested can find it on PyPi; the documentation is available on Read The Docs.

Xcode project not showing list of simulators

I ran into another situation where this can occur. I work with a team we use Xcode server for continuous integration. The server wasn't seeing any simulators, but only for one project. I eventually determined that this was due to the fact that the version of Xcode on our server was one release earlier, and the Xcode project was set to build to the newest version available. Simply updating Xcode solved the issue for us.

Ruby: What is the easiest way to remove the first element from an array?

You can use:

arr - [arr[0]]

or

arr - [arr.shift]

or simply

arr.shift(1)

DLL load failed error when importing cv2

(base) C:\WINDOWS\system32>conda install C:\Users\Todd\Downloads\opencv3-3.1.0-py35_0.tar.bz2

I ran this command from anaconda terminal after I downloaded the version from https://anaconda.org/menpo/opencv3/files

This is the only way I could get cv2 to work and I tried everything for two days.

How do I request and process JSON with python?

Python's standard library has json and urllib2 modules.

import json
import urllib2

data = json.load(urllib2.urlopen('http://someurl/path/to/json'))

Merging two images with PHP

I got it working from one I made.

<?php
$dest = imagecreatefrompng('vinyl.png');
$src = imagecreatefromjpeg('cover2.jpg');

imagealphablending($dest, false);
imagesavealpha($dest, true);

imagecopymerge($dest, $src, 10, 9, 0, 0, 181, 180, 100); //have to play with these numbers for it to work for you, etc.

header('Content-Type: image/png');
imagepng($dest);

imagedestroy($dest);
imagedestroy($src);
?>

Drawable image on a canvas

You need to load your image as bitmap:

 Resources res = getResources();
 Bitmap bitmap = BitmapFactory.decodeResource(res, R.drawable.your_image);

Then make the bitmap mutable and create a canvas over it:

Canvas canvas = new Canvas(bitmap.copy(Bitmap.Config.ARGB_8888, true));

You then can draw on the canvas.

Read user input inside a loop

Try to change the loop like this:

for line in $(cat filename); do
    read input
    echo $input;
done

Unit test:

for line in $(cat /etc/passwd); do
    read input
    echo $input;
    echo "[$line]"
done

using where and inner join in mysql

Try this :

SELECT
    (
      SELECT
          `NAME`
      FROM
          locations
      WHERE
          ID = school_locations.LOCATION_ID
    ) as `NAME`
FROM
     school_locations
WHERE
     (
      SELECT
          `TYPE`
      FROM
          locations
      WHERE
          ID = school_locations.LOCATION_ID
     ) = 'coun';

Can I use a :before or :after pseudo-element on an input field?

I used the background-image to create the red dot for required fields.

input[type="text"][required] {
  background-image: radial-gradient(red 15%, transparent 16%);
  background-size: 1em 1em;
  background-position: top right;
  background-repeat: no-repeat
}

View on Codepen

In PHP with PDO, how to check the final SQL parametrized query?

What I did to print that actual query is a bit complicated but it works :)

In method that assigns variables to my statement I have another variable that looks a bit like this:

$this->fullStmt = str_replace($column, '\'' . str_replace('\'', '\\\'', $param) . '\'', $this->fullStmt);

Where:
$column is my token
$param is the actual value being assigned to token
$this->fullStmt is my print only statement with replaced tokens

What it does is a simply replace tokens with values when the real PDO assignment happens.

I hope I did not confuse you and at least pointed you in right direction.

How to find whether or not a variable is empty in Bash?

You may want to distinguish between unset variables and variables that are set and empty:

is_empty() {
    local var_name="$1"
    local var_value="${!var_name}"
    if [[ -v "$var_name" ]]; then
       if [[ -n "$var_value" ]]; then
         echo "set and non-empty"
       else
         echo "set and empty"
       fi
    else
       echo "unset"
    fi
}

str="foo"
empty=""
is_empty str
is_empty empty
is_empty none

Result:

set and non-empty
set and empty
unset

BTW, I recommend using set -u which will cause an error when reading unset variables, this can save you from disasters such as

rm -rf $dir

You can read about this and other best practices for a "strict mode" here.

MongoDB: Is it possible to make a case-insensitive query?

If you need to create the regexp from a variable, this is a much better way to do it: https://stackoverflow.com/a/10728069/309514

You can then do something like:

var string = "SomeStringToFind";
var regex = new RegExp(["^", string, "$"].join(""), "i");
// Creates a regex of: /^SomeStringToFind$/i
db.stuff.find( { foo: regex } );

This has the benefit be being more programmatic or you can get a performance boost by compiling it ahead of time if you're reusing it a lot.

jQuery get the name of a select option

The Code is very Simple, Lets Put This Code

var name = $("#band_type_choices  option:selected").text();

Here You don't want to use $(this).find().text(), directly you can put your id name and add option:selected along with text().

This will return the result option name. Better Try this...

How can I dynamically set the position of view in Android?

Yes, you can dynamically set the position of the view in Android. Likewise, you have an ImageView in LinearLayout of your XML file. So you can set its position through LayoutParams.But make sure to take LayoutParams according to the layout taken in your XML file. There are different LayoutParams according to the layout taken.

Here is the code to set:

    LayoutParams layoutParams=new LayoutParams(int width, int height);
    layoutParams.setMargins(int left, int top, int right, int bottom);
    imageView.setLayoutParams(layoutParams);

Can't find/install libXtst.so.6?

This worked for me in Luna elementary OS

sudo apt-get install libxtst6:i386

How can I tell if a Java integer is null?

ints are value types; they can never be null. Instead, if the parsing failed, parseInt will throw a NumberFormatException that you need to catch.

Excel VBA Loop on columns

Yes, let's use Select as an example

sample code: Columns("A").select

How to loop through Columns:

Method 1: (You can use index to replace the Excel Address)

For i = 1 to 100
    Columns(i).Select
next i

Method 2: (Using the address)

For i = 1 To 100
 Columns(Columns(i).Address).Select
Next i

EDIT: Strip the Column for OP

columnString = Replace(Split(Columns(27).Address, ":")(0), "$", "")

e.g. you want to get the 27th Column --> AA, you can get it this way

React won't load local images

Actually I would like to comment, but I am not authorised yet. That is why that pretend to be next answer while it is not.

import React from 'react';
import logo from './logo.png'; // Tell Webpack this JS file uses this image
console.log(logo); // /logo.84287d09.png

function Header() {
// Import result is the URL of your image
  return <img src={logo} alt="Logo" />;

I would like to continue that path. That works smoothly when one has picture one can simple insert. In my case that is slightly more complex: I have to map several pictures it. So far the only workable way to do this I found is as follows

import upperBody from './upperBody.png';
import lowerBody from './lowerBody.png';
import aesthetics from './aesthetics.png';

let obj={upperBody:upperBody, lowerBody:lowerBody, aesthetics:aesthetics, agility:agility, endurance:endurance}

{Object.keys(skills).map((skill) => {
 return ( <img className = 'icon-size' src={obj[skill]}/> 

So, my question is whether are there simplier ways to process these images? Needless to say that in more general case number of files that must be literally imported could be huge and number of keys in object as well. (Object in that code is involved clearly to refer by names -its keys) In my case require-related procedures have not worked - loaders generated errors of strange kind during installation and shown no mark of working; and require by itself has not worked neither.

how to use "tab space" while writing in text file

You can use \t to create a tab in a file.

How do you send a Firebase Notification to all devices via CURL?

The most easiest way I came up with to send the push notification to all the devices is to subscribe them to a topic "all" and then send notification to this topic. Copy this in your main activity

FirebaseMessaging.getInstance().subscribeToTopic("all");

Now send the request as

{
   "to":"/topics/all",
   "data":
   {
      "title":"Your title",
      "message":"Your message"
      "image-url":"your_image_url"
   }
}

This might be inefficient or non-standard way, but as I mentioned above it's the easiest. Please do post if you have any better way to send a push notification to all the devices.

You can follow this tutorial if you're new to sending push notifications using Firebase Cloud Messaging Tutorial - Push Notifications using FCM


To send a message to a combination of topics, specify a condition, which is a boolean expression that specifies the target topics. For example, the following condition will send messages to devices that are subscribed to TopicA and either TopicB or TopicC:

{
   "data":
   {
      "title": "Your title",
      "message": "Your message"
      "image-url": "your_image_url"
   },
   "condition": "'TopicA' in topics && ('TopicB' in topics || 'TopicC' in topics)"
}

Read more about conditions and topics here on FCM documentation

Why are elementwise additions much faster in separate loops than in a combined loop?

It may be old C++ and optimizations. On my computer I obtained almost the same speed:

One loop: 1.577 ms

Two loops: 1.507 ms

I run Visual Studio 2015 on an E5-1620 3.5 GHz processor with 16 GB RAM.

How to perform a fade animation on Activity transition?

You could create your own .xml animation files to fade in a new Activity and fade out the current Activity:

fade_in.xml

<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
           android:interpolator="@android:anim/accelerate_interpolator"
           android:fromAlpha="0.0" android:toAlpha="1.0"
           android:duration="500" />

fade_out.xml

<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
           android:interpolator="@android:anim/accelerate_interpolator"
           android:fromAlpha="1.0" android:toAlpha="0.0"
           android:fillAfter="true"
           android:duration="500" />

Use it in code like that: (Inside your Activity)

Intent i = new Intent(this, NewlyStartedActivity.class);
startActivity(i);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);

The above code will fade out the currently active Activity and fade in the newly started Activity resulting in a smooth transition.

UPDATE: @Dan J pointed out that using the built in Android animations improves performance, which I indeed found to be the case after doing some testing. If you prefer working with the built in animations, use:

overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);

Notice me referencing android.R instead of R to access the resource id.

UPDATE: It is now common practice to perform transitions using the Transition class introduced in API level 19.

Forcing to download a file using PHP

Nice clean solution:

<?php
    header('Content-Type: application/download');
    header('Content-Disposition: attachment; filename="example.csv"');
    header("Content-Length: " . filesize("example.csv"));

    $fp = fopen("example.csv", "r");
    fpassthru($fp);
    fclose($fp);
?>

What is reflection and why is it useful?

Reflection is to let object to see their appearance. This argument seems nothing to do with reflection. In fact, this is the "self-identify" ability.

Reflection itself is a word for such languages that lack the capability of self-knowledge and self-sensing as Java and C#. Because they do not have the capability of self-knowledge, when we want to observe how it looks like, we must have another thing to reflect on how it looks like. Excellent dynamic languages such as Ruby and Python can perceive the reflection of their own without the help of other individuals. We can say that the object of Java cannot perceive how it looks like without a mirror, which is an object of the reflection class, but an object in Python can perceive it without a mirror. So that's why we need reflection in Java.

How to write character & in android strings.xml

You can find all the HTML Special Characters in this page http://www.degraeve.com/reference/specialcharacters.php Just replace the code where you want to put that character. :-)

How to handle the click event in Listview in android?

Error is coming in your code from this statement as you said

Intent intent = new Intent(context, SendMessage.class);

This is due to you are providing context of OnItemClickListener anonymous class into the Intent constructor but according to constructor of Intent

android.content.Intent.Intent(Context packageContext, Class<?> cls)

You have to provide context of you activity in which you are using intent that is the MainActivity class context. so your statement which is giving error will be converted to

Intent intent = new Intent(MainActivity.this, SendMessage.class);

Also for sending your message from this MainActivity to SendMessage class please see below code

lv.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,
                    long id) {
                ListEntry entry= (ListEntry) parent.getAdapter().getItem(position);
                Intent intent = new Intent(MainActivity.this, SendMessage.class);
                intent.putExtra(EXTRA_MESSAGE, entry.getMessage());
                startActivity(intent);
            }
        });

Please let me know if this helps you

EDIT:- If you are finding some issue to get the value of list do one thing declear your array list

ArrayList<ListEntry> members = new ArrayList<ListEntry>();

globally i.e. before oncreate and change your listener as below

 lv.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position,
                        long id) {
                    Intent intent = new Intent(MainActivity.this, SendMessage.class);
                    intent.putExtra(EXTRA_MESSAGE, members.get(position));
                    startActivity(intent);
                }
            });

So your whole code will look as

public class MainActivity extends Activity {
    public final static String EXTRA_MESSAGE = "com.example.ListViewTest.MESSAGE";
ArrayList<ListEntry> members = new ArrayList<ListEntry>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        members.add(new ListEntry("BBB","AAA",R.drawable.tab1_hdpi));
        members.add(new ListEntry("ccc","ddd",R.drawable.tab2_hdpi));
        members.add(new ListEntry("assa","cxv",R.drawable.tab3_hdpi));
        members.add(new ListEntry("BcxsadvBB","AcxdxvAA"));
        members.add(new ListEntry("BcxvadsBB","AcxzvAA"));
        members.add(new ListEntry("BcxvBB","AcxvAA"));
        members.add(new ListEntry("BvBB","AcxsvAA"));
        members.add(new ListEntry("BcxvBB","AcxsvzAA"));
        members.add(new ListEntry("Bcxadv","AcsxvAA"));
        members.add(new ListEntry("BcxcxB","AcxsvAA"));
        ListView lv = (ListView)findViewById(R.id.listView1);
        Log.i("testTag","before start adapter");
        StringArrayAdapter ad = new StringArrayAdapter (members,this);
        Log.i("testTag","after start adapter");
        Log.i("testTag","set adapter");
        lv.setAdapter(ad);
        lv.setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
                        Intent intent = new Intent(MainActivity.this, SendMessage.class);
                        intent.putExtra(EXTRA_MESSAGE, members.get(position).getMessage());
                        startActivity(intent);
                    }
                });
    }

Where getMessage() will be a getter method specified in your ListEntry class which you are using to get message which was previously set.

Form submit with AJAX passing form data to PHP without page refresh

JS Code

    $("#submit").click(function() { 
    //get input field values
    var name            = $('#name').val(); 
    var email           = $('#email').val();
    var message         = $('#comment').val();
    var flag = true;
    /********validate all our form fields***********/
    /* Name field validation  */
    if(name==""){ 
        $('#name').css('border-color','red'); 
        flag = false;
    }
    /* email field validation  */
    if(email==""){ 
        $('#email').css('border-color','red'); 
        flag = false;
    } 
    /* message field validation */
    if(message=="") {  
       $('#comment').css('border-color','red'); 
        flag = false;
    }
    /********Validation end here ****/
    /* If all are ok then we send ajax request to email_send.php *******/
    if(flag) 
    {
        $.ajax({
            type: 'post',
            url: "email_send.php", 
            dataType: 'json',
            data: 'username='+name+'&useremail='+email+'&message='+message,
            beforeSend: function() {
                $('#submit').attr('disabled', true);
                $('#submit').after('<span class="wait">&nbsp;<img src="image/loading.gif" alt="" /></span>');
            },
            complete: function() {
                $('#submit').attr('disabled', false);
                $('.wait').remove();
            },  
            success: function(data)
            {
                if(data.type == 'error')
                {
                    output = '<div class="error">'+data.text+'</div>';
                }else{
                    output = '<div class="success">'+data.text+'</div>';
                    $('input[type=text]').val(''); 
                    $('#contactform textarea').val(''); 
                }

                $("#result").hide().html(output).slideDown();           
                }
        });
    }
});
//reset previously set border colors and hide all message on .keyup()
$("#contactform input, #contactform textarea").keyup(function() { 
    $("#contactform input, #contactform textarea").css('border-color',''); 
    $("#result").slideUp();
});

HTML Form

<div  class="cover">
<div id="result"></div>
<div id="contactform">
    <p class="contact"><label for="name">Name</label></p>
    <input id="name" name="name" placeholder="Yourname" type="text">

    <p class="contact"><label for="email">Email</label></p>
    <input id="email" name="email" placeholder="[email protected]" type="text">

    <p class="contact"><label for="comment">Your Message</label></p>
    <textarea name="comment" id="comment" tabindex="4"></textarea> <br>
    <input name="submit" id="submit" tabindex="5" value="Send Mail" type="submit" style="width:200px;">
</div>

PHP Code

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

//check if its an ajax request, exit if not
if (!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {

    //exit script outputting json data
    $output = json_encode(
            array(
                'type' => 'error',
                'text' => 'Request must come from Ajax'
    ));

    die($output);
}

//check $_POST vars are set, exit if any missing
if (!isset($_POST["username"]) || !isset($_POST["useremail"]) || !isset($_POST["message"])) {
    $output = json_encode(array('type' => 'error', 'text' => 'Input fields are empty!'));
    die($output);
}

//Sanitize input data using PHP filter_var().
$username = filter_var(trim($_POST["username"]), FILTER_SANITIZE_STRING);
$useremail = filter_var(trim($_POST["useremail"]), FILTER_SANITIZE_EMAIL);
$message = filter_var(trim($_POST["message"]), FILTER_SANITIZE_STRING);

//additional php validation
if (strlen($username) < 4) { // If length is less than 4 it will throw an HTTP error.
    $output = json_encode(array('type' => 'error', 'text' => 'Name is too short!'));
    die($output);
}
if (!filter_var($useremail, FILTER_VALIDATE_EMAIL)) { //email validation
    $output = json_encode(array('type' => 'error', 'text' => 'Please enter a valid email!'));
    die($output);
}
if (strlen($message) < 5) { //check emtpy message
    $output = json_encode(array('type' => 'error', 'text' => 'Too short message!'));
    die($output);
}

$to = "[email protected]"; //Replace with recipient email address
//proceed with PHP email.
$headers = 'From: ' . $useremail . '' . "\r\n" .
        'Reply-To: ' . $useremail . '' . "\r\n" .
        'X-Mailer: PHP/' . phpversion();

$sentMail = @mail($to, $subject, $message . '  -' . $username, $headers);
//$sentMail = true;
if (!$sentMail) {
    $output = json_encode(array('type' => 'error', 'text' => 'Could not send mail! Please contact administrator.'));
    die($output);
} else {
    $output = json_encode(array('type' => 'message', 'text' => 'Hi ' . $username . ' Thank you for your email'));
    die($output);
}

This page has a simpler example http://wearecoders.net/submit-form-without-page-refresh-with-php-and-ajax/

How can I scale an entire web page with CSS?

 * {
transform: scale(1.1, 1.1)
}

this will transform every element on the page

sqlalchemy filter multiple columns

You can use SQLAlchemy's or_ function to search in more than one column (the underscore is necessary to distinguish it from Python's own or).

Here's an example:

from sqlalchemy import or_
query = meta.Session.query(User).filter(or_(User.firstname.like(searchVar),
                                            User.lastname.like(searchVar)))

How can I declare a global variable in Angular 2 / Typescript?

I think the best way is to share an object with global variables throughout your application by exporting and importing it where you want.

First create a new .ts file for example globals.ts and declare an object. I gave it an Object type but you also could use an any type or {}

export let globalVariables: Object = {
 version: '1.3.3.7',
 author: '0x1ad2',
 everything: 42
};

After that import it

import {globalVariables} from "path/to/your/globals.ts"

And use it

console.log(globalVariables);

Python 3 - ValueError: not enough values to unpack (expected 3, got 2)

ValueErrors :In Python, a value is the information that is stored within a certain object. To encounter a ValueError in Python means that is a problem with the content of the object you tried to assign the value to.

in your case name,lastname and email 3 parameters are there but unpaidmembers only contain 2 of them.

name, lastname, email in unpaidMembers.items() so you should refer data or your code might be
lastname, email in unpaidMembers.items() or name, email in unpaidMembers.items()

How to set default font family in React Native?

That works for me: Add Custom Font in React Native

download your fonts and place them in assets/fonts folder, add this line in package.json

 "rnpm": {
"assets": ["assets/fonts/Sarpanch"]}

then open terminal and run this command: react-native link

Now your are good to go. For more detailed step. visit the link above mentioned

Insert HTML from CSS

An alternative - which may work for you depending on what you're trying to do - is to have the HTML in place and then use the CSS to show or hide it depending on the class of a parent element.

OR

Use jQuery append()

How do I programmatically force an onchange event on an input?

Using JQuery you can do the following:

// for the element which uses ID
$("#id").trigger("change");

// for the element which uses class name
$(".class_name").trigger("change");

How to get character array from a string?

simple answer:

_x000D_
_x000D_
let str = 'this is string, length is >26';_x000D_
_x000D_
console.log([...str]);
_x000D_
_x000D_
_x000D_

Flask Python Buttons

I think this solution is good:

@app.route('/contact', methods=['GET', 'POST'])
def contact():
    form = ContactForm()
    if form.validate_on_submit():
        if form.submit.data:
            pass
        elif form.submit2.data:
            pass
    return render_template('contact.html', form=form)

Form:

class ContactForm(FlaskForm):

    submit = SubmitField('Do this')
    submit2 = SubmitField('Do that')

How to set a CMake option() at command line

Delete the CMakeCache.txt file and try this:

cmake -G %1 -DBUILD_SHARED_LIBS=ON -DBUILD_STATIC_LIBS=ON -DBUILD_TESTS=ON ..

You have to enter all your command-line definitions before including the path.

datetime to string with series in python pandas

There is no str accessor for datetimes and you can't do dates.astype(str) either, you can call apply and use datetime.strftime:

In [73]:

dates = pd.to_datetime(pd.Series(['20010101', '20010331']), format = '%Y%m%d')
dates.apply(lambda x: x.strftime('%Y-%m-%d'))
Out[73]:
0    2001-01-01
1    2001-03-31
dtype: object

You can change the format of your date strings using whatever you like: strftime() and strptime() Behavior.

Update

As of version 0.17.0 you can do this using dt.strftime

dates.dt.strftime('%Y-%m-%d')

will now work

How to discard local changes and pull latest from GitHub repository

In addition to the above answers, there is always the scorched earth method.

rm -R <folder>

in Windows shell the command is:

rd /s <folder>

Then you can just checkout the project again:

git clone -v <repository URL> 

This will definitely remove any local changes and pull the latest from the remote repository. Be careful with rm -R as it will delete your good data if you put the wrong path. For instance, definitely do not do:

rm -R /

edit: To fix spelling and add emphasis.

SQL Update Multiple Fields FROM via a SELECT Statement

I would write it this way

UPDATE s
SET    OrgAddress1 = bd.OrgAddress1,    OrgAddress2 = bd.OrgAddress2,    
     ...    DestZip = bd.DestZip
--select s.OrgAddress1, bd.OrgAddress1, s.OrgAddress2, bd.OrgAddress2, etc 
FROM    Shipment s
JOIN ProfilerTest.dbo.BookingDetails bd on  bd.MyID =s.MyID2
WHERE    bd.MyID = @MyId 

This way the join is explicit as implicit joins are a bad thing IMHO. You can run the commented out select (usually I specify the fields I'm updating old and new values next to each other) to make sure that what I am going to update is exactly what I meant to update.

How to hide soft keyboard on android after clicking outside EditText?

Instead of iterating through all the views or overriding dispatchTouchEvent.

Why Not just override the onUserInteraction() of the Activity this will make sure keyboard dismisses whenever the user taps outside of EditText.

Will work even when EditText is inside the scrollView.

@Override
public void onUserInteraction() {
    if (getCurrentFocus() != null) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
    }
}

Change the jquery show()/hide() animation?

There are the slideDown, slideUp, and slideToggle functions native to jquery 1.3+, and they work quite nicely...

https://api.jquery.com/category/effects/

You can use slideDown just like this:

$("test").slideDown("slow");

And if you want to combine effects and really go nuts I'd take a look at the animate function which allows you to specify a number of CSS properties to shape tween or morph into. Pretty fancy stuff, that.

How can I add spaces between two <input> lines using CSS?

You can format them as table !!

_x000D_
_x000D_
form {_x000D_
  display: table;_x000D_
}_x000D_
label {_x000D_
  display: table-row;_x000D_
}_x000D_
input {_x000D_
  display: table-cell;_x000D_
}_x000D_
p1 {_x000D_
  display: table-cell;_x000D_
}
_x000D_
<div id="header_order_form" align="center">_x000D_
  <form id="order_header" method="post">_x000D_
    <label>_x000D_
      <p1>order_no:_x000D_
        <input type="text">_x000D_
      </p1>_x000D_
      <p1>order_type:_x000D_
        <input type="text">_x000D_
      </p1>_x000D_
    </label>_x000D_
    </br>_x000D_
    </br>_x000D_
    <label>_x000D_
      <p1>_x000D_
        creation_date:_x000D_
        <input type="text">_x000D_
      </p1>_x000D_
      <p1>delivery_date:_x000D_
        <input type="text">_x000D_
      </p1>_x000D_
      <p1>billing_date:_x000D_
        <input type="text">_x000D_
      </p1>_x000D_
    </label>_x000D_
    </br>_x000D_
    </br>_x000D_
_x000D_
    <label>_x000D_
      <p1>sold_to_party:_x000D_
        <input type="text">_x000D_
      </p1>_x000D_
      <p1>sop_address:_x000D_
        <input type="text">_x000D_
      </p1>_x000D_
    </label>_x000D_
  </form>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Android Left to Right slide animation

Use this xml in res/anim/

This is for left to right animation:

<set xmlns:android="http://schemas.android.com/apk/res/android"
     android:shareInterpolator="false">
  <translate android:fromXDelta="-100%" android:toXDelta="0%"
             android:fromYDelta="0%" android:toYDelta="0%"
             android:duration="700"/>
</set>

This is for right to left animation:

<set xmlns:android="http://schemas.android.com/apk/res/android"
     android:shareInterpolator="false">
  <translate
     android:fromXDelta="0%" android:toXDelta="100%"
     android:fromYDelta="0%" android:toYDelta="0%"
     android:duration="700" />
</set>

In your coding use intent like for left to right:

this.overridePendingTransition(R.anim.animation_enter,
                   R.anim.animation_leave);

In your coding use intent like for right to left

this.overridePendingTransition(R.anim.animation_leave,
                               R.anim.animation_enter);

Can't create a docker image for COPY failed: stat /var/lib/docker/tmp/docker-builder error

I had to use the following command to start the build:

docker build .

Restarting cron after changing crontab file?

Depending on distribution, using "cron reload" might do nothing. To paste a snippet out of init.d/cron (debian squeeze):

reload|force-reload) log_daemon_msg "Reloading configuration files for periodic command scheduler" "cron"
    # cron reloads automatically
    log_end_msg 0
    ;;

Some developer/maintainer relied on it reloading, but doesn't, and in this case there's not a way to force reload. I'm generating my crontab files as part of a deploy, and unless somehow the length of the file changes, the changes are not reloaded.

Programmatically set the initial view controller using Storyboards

If you prefer not to change applicationDidFinish, you can do the following trick:

Set Navigation controller as an initial view controller and assign to it a custom class 'MyNavigationController'. Then you can tweak its root view controller during viewDidLoad - it will override the root view controller that you set in your storyboard.

class MyNavigationController: UINavigationController {
    override func viewDidLoad() {
        super.viewDidLoad()
        if !isLoggedIn() {
            viewControllers = [R.storyboard.authentication.loginView()!]
        }
    }

    private func isLoggedIn() -> Bool {
        return false
    }

}

How do I time a method's execution in Java?

For java 8+, another possible solution (more general, func-style and without aspects) could be to create some utility method accepting code as a parameter

public static <T> T timed (String description, Consumer<String> out, Supplier<T> code) {
    final LocalDateTime start = LocalDateTime.now ();
    T res = code.get ();
    final long execTime = Duration.between (start, LocalDateTime.now ()).toMillis ();
    out.accept (String.format ("%s: %d ms", description, execTime));
    return res;
}

And the calling code could be smth like that:

public static void main (String[] args) throws InterruptedException {
    timed ("Simple example", System.out::println, Timing::myCode);
}

public static Object myCode () {
    try {
        Thread.sleep (1500);
    } catch (InterruptedException e) {
        e.printStackTrace ();
    }
    return null;
}

What are .NET Assemblies?

MSDN has a good explanation:

Assemblies are the building blocks of .NET Framework applications; they form the fundamental unit of deployment, version control, reuse, activation scoping, and security permissions. An assembly is a collection of types and resources that are built to work together and form a logical unit of functionality. An assembly provides the common language runtime with the information it needs to be aware of type implementations. To the runtime, a type does not exist outside the context of an assembly.

Sending HTML email using Python

Here is a simple way to send an HTML email, just by specifying the Content-Type header as 'text/html':

import email.message
import smtplib

msg = email.message.Message()
msg['Subject'] = 'foo'
msg['From'] = '[email protected]'
msg['To'] = '[email protected]'
msg.add_header('Content-Type','text/html')
msg.set_payload('Body of <b>message</b>')

# Send the message via local SMTP server.
s = smtplib.SMTP('localhost')
s.starttls()
s.login(email_login,
        email_passwd)
s.sendmail(msg['From'], [msg['To']], msg.as_string())
s.quit()

Find string between two substrings

This is essentially cji's answer - Jul 30 '10 at 5:58. I changed the try except structure for a little more clarity on what was causing the exception.

def find_between( inputStr, firstSubstr, lastSubstr ):
'''
find between firstSubstr and lastSubstr in inputStr  STARTING FROM THE LEFT
    http://stackoverflow.com/questions/3368969/find-string-between-two-substrings
        above also has a func that does this FROM THE RIGHT   
'''
start, end = (-1,-1)
try:
    start = inputStr.index( firstSubstr ) + len( firstSubstr )
except ValueError:
    print '    ValueError: ',
    print "firstSubstr=%s  -  "%( firstSubstr ), 
    print sys.exc_info()[1]

try:
    end = inputStr.index( lastSubstr, start )       
except ValueError:
    print '    ValueError: ',
    print "lastSubstr=%s  -  "%( lastSubstr ), 
    print sys.exc_info()[1]

return inputStr[start:end]    

Action Image MVC3 Razor

This turned out to be a very useful thread.

For those who are allergic to curly braces, here is the VB.NET version of Lucas' and Crake's answers:

Public Module ActionImage
    <System.Runtime.CompilerServices.Extension()>
    Function ActionImage(html As HtmlHelper, Action As String, RouteValues As Object, ImagePath As String, AltText As String) As MvcHtmlString

        Dim url = New UrlHelper(html.ViewContext.RequestContext)

        Dim imgHtml As String
        'Build the <img> tag
        Dim imgBuilder = New TagBuilder("img")
        With imgBuilder
            .MergeAttribute("src", url.Content(ImagePath))
            .MergeAttribute("alt", AltText)
            imgHtml = .ToString(TagRenderMode.Normal)
        End With

        Dim aHtml As String
        'Build the <a> tag
        Dim aBuilder = New TagBuilder("a")
        With aBuilder
            .MergeAttribute("href", url.Action(Action, RouteValues))
            .InnerHtml = imgHtml 'Include the <img> tag inside
            aHtml = aBuilder.ToString(TagRenderMode.Normal)
        End With

        Return MvcHtmlString.Create(aHtml)

    End Function

    <Extension()>
    Function ActionImage(html As HtmlHelper, Action As String, Controller As String, RouteValues As Object, ImagePath As String, AltText As String) As MvcHtmlString

        Dim url = New UrlHelper(html.ViewContext.RequestContext)

        Dim imgHtml As String
        'Build the <img> tag
        Dim imgBuilder = New TagBuilder("img")
        With imgBuilder
            .MergeAttribute("src", url.Content(ImagePath))
            .MergeAttribute("alt", AltText)
            imgHtml = .ToString(TagRenderMode.Normal)
        End With

        Dim aHtml As String
        'Build the <a> tag
        Dim aBuilder = New TagBuilder("a")
        With aBuilder
            .MergeAttribute("href", url.Action(Action, Controller, RouteValues))
            .InnerHtml = imgHtml 'Include the <img> tag inside
            aHtml = aBuilder.ToString(TagRenderMode.Normal)
        End With

        Return MvcHtmlString.Create(aHtml)

    End Function

End Module

How to load a controller from another controller in codeigniter?

You can't load a controller from a controller in CI - unless you use HMVC or something.

You should think about your architecture a bit. If you need to call a controller method from another controller, then you should probably abstract that code out to a helper or library and call it from both controllers.

UPDATE

After reading your question again, I realize that your end goal is not necessarily HMVC, but URI manipulation. Correct me if I'm wrong, but it seems like you're trying to accomplish URLs with the first section being the method name and leave out the controller name altogether.

If this is the case, you'd get a cleaner solution by getting creative with your routes.

For a really basic example, say you have two controllers, controller1 and controller2. Controller1 has a method method_1 - and controller2 has a method method_2.

You can set up routes like this:

$route['method_1'] = "controller1/method_1";
$route['method_2'] = "controller2/method_2";

Then, you can call method 1 with a URL like http://site.com/method_1 and method 2 with http://site.com/method_2.

Albeit, this is a hard-coded, very basic, example - but it could get you to where you need to be if all you need to do is remove the controller from the URL.


You could also go with remapping your controllers.

From the docs: "If your controller contains a function named _remap(), it will always get called regardless of what your URI contains.":

public function _remap($method)
{
    if ($method == 'some_method')
    {
        $this->$method();
    }
    else
    {
        $this->default_method();
    }
}

XAMPP - Apache could not start - Attempting to start Apache service

Make sure Apache didn't get Disabled in Services (Control panel, Admin Tools, Services). If it's Disabled then Set it to Manual and it should run. That was my case, I found Apache Disabled.

How to allow Cross domain request in apache2

I had a lot of trouble getting this to work. Dummy me, don't forget that old page - even for sub-requests - gets cached in your browser. Maybe obvious, but clear your browsers cache. After that, one can also use Header set Cache-Control "no-store" This was helpful to me while testing.

SQL multiple column ordering

Multiple column ordering depends on both column's corresponding values: Here is my table example where are two columns named with Alphabets and Numbers and the values in these two columns are asc and desc orders.

enter image description here

Now I perform Order By in these two columns by executing below command:

enter image description here

Now again I insert new values in these two columns, where Alphabet value in ASC order:

enter image description here

and the columns in Example table look like this. Now again perform the same operation:

enter image description here

You can see the values in the first column are in desc order but second column is not in ASC order.

Relative imports for the billionth time

Here's a general recipe, modified to fit as an example, that I am using right now for dealing with Python libraries written as packages, that contain interdependent files, where I want to be able to test parts of them piecemeal. Let's call this lib.foo and say that it needs access to lib.fileA for functions f1 and f2, and lib.fileB for class Class3.

I have included a few print calls to help illustrate how this works. In practice you would want to remove them (and maybe also the from __future__ import print_function line).

This particular example is too simple to show when we really need to insert an entry into sys.path. (See Lars' answer for a case where we do need it, when we have two or more levels of package directories, and then we use os.path.dirname(os.path.dirname(__file__))—but it doesn't really hurt here either.) It's also safe enough to do this without the if _i in sys.path test. However, if each imported file inserts the same path—for instance, if both fileA and fileB want to import utilities from the package—this clutters up sys.path with the same path many times, so it's nice to have the if _i not in sys.path in the boilerplate.

from __future__ import print_function # only when showing how this works

if __package__:
    print('Package named {!r}; __name__ is {!r}'.format(__package__, __name__))
    from .fileA import f1, f2
    from .fileB import Class3
else:
    print('Not a package; __name__ is {!r}'.format(__name__))
    # these next steps should be used only with care and if needed
    # (remove the sys.path manipulation for simple cases!)
    import os, sys
    _i = os.path.dirname(os.path.abspath(__file__))
    if _i not in sys.path:
        print('inserting {!r} into sys.path'.format(_i))
        sys.path.insert(0, _i)
    else:
        print('{!r} is already in sys.path'.format(_i))
    del _i # clean up global name space

    from fileA import f1, f2
    from fileB import Class3

... all the code as usual ...

if __name__ == '__main__':
    import doctest, sys
    ret = doctest.testmod()
    sys.exit(0 if ret.failed == 0 else 1)

The idea here is this (and note that these all function the same across python2.7 and python 3.x):

  1. If run as import lib or from lib import foo as a regular package import from ordinary code, __package is lib and __name__ is lib.foo. We take the first code path, importing from .fileA, etc.

  2. If run as python lib/foo.py, __package__ will be None and __name__ will be __main__.

    We take the second code path. The lib directory will already be in sys.path so there is no need to add it. We import from fileA, etc.

  3. If run within the lib directory as python foo.py, the behavior is the same as for case 2.

  4. If run within the lib directory as python -m foo, the behavior is similar to cases 2 and 3. However, the path to the lib directory is not in sys.path, so we add it before importing. The same applies if we run Python and then import foo.

    (Since . is in sys.path, we don't really need to add the absolute version of the path here. This is where a deeper package nesting structure, where we want to do from ..otherlib.fileC import ..., makes a difference. If you're not doing this, you can omit all the sys.path manipulation entirely.)

Notes

There is still a quirk. If you run this whole thing from outside:

$ python2 lib.foo

or:

$ python3 lib.foo

the behavior depends on the contents of lib/__init__.py. If that exists and is empty, all is well:

Package named 'lib'; __name__ is '__main__'

But if lib/__init__.py itself imports routine so that it can export routine.name directly as lib.name, you get:

$ python2 lib.foo
Package named 'lib'; __name__ is 'lib.foo'
Package named 'lib'; __name__ is '__main__'

That is, the module gets imported twice, once via the package and then again as __main__ so that it runs your main code. Python 3.6 and later warn about this:

$ python3 lib.routine
Package named 'lib'; __name__ is 'lib.foo'
[...]/runpy.py:125: RuntimeWarning: 'lib.foo' found in sys.modules
after import of package 'lib', but prior to execution of 'lib.foo';
this may result in unpredictable behaviour
  warn(RuntimeWarning(msg))
Package named 'lib'; __name__ is '__main__'

The warning is new, but the warned-about behavior is not. It is part of what some call the double import trap. (For additional details see issue 27487.) Nick Coghlan says:

This next trap exists in all current versions of Python, including 3.3, and can be summed up in the following general guideline: "Never add a package directory, or any directory inside a package, directly to the Python path".

Note that while we violate that rule here, we do it only when the file being loaded is not being loaded as part of a package, and our modification is specifically designed to allow us to access other files in that package. (And, as I noted, we probably shouldn't do this at all for single level packages.) If we wanted to be extra-clean, we might rewrite this as, e.g.:

    import os, sys
    _i = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    if _i not in sys.path:
        sys.path.insert(0, _i)
    else:
        _i = None

    from sub.fileA import f1, f2
    from sub.fileB import Class3

    if _i:
        sys.path.remove(_i)
    del _i

That is, we modify sys.path long enough to achieve our imports, then put it back the way it was (deleting one copy of _i if and only if we added one copy of _i).

Android Studio: Where is the Compiler Error Output Window?

In my case i had a findViewById reference to a view i had deleted in xml

if you are running AS 3.1 and above:

  1. go to Settings > Build, Execution and Deployment > compiler
  2. add --stacktrace to the command line options, click apply and ok
  3. At the bottom of AS click on Console/Build(If you use the stable version 3.1.2 and above) expand the panel and run your app again.

you should see the full stacktrace in the expanded view and the specific error.

Python: SyntaxError: keyword can't be an expression

Using the Elastic search DSL API, you may hit the same error with

s = Search(using=client, index="my-index") \
    .query("match", category.keyword="Musician")

You can solve it by doing:

s = Search(using=client, index="my-index") \
    .query({"match": {"category.keyword":"Musician/Band"}})

Sum function in VBA

Range("A1").Function="=SUM(Range(Cells(2,1),Cells(3,2)))"

won't work because worksheet functions (when actually used on a worksheet) don't understand Range or Cell

Try

Range("A1").Formula="=SUM(" & Range(Cells(2,1),Cells(3,2)).Address(False,False) & ")"

Parameterize an SQL IN clause

This is possibly a half nasty way of doing it, I used it once, was rather effective.

Depending on your goals it might be of use.

  1. Create a temp table with one column.
  2. INSERT each look-up value into that column.
  3. Instead of using an IN, you can then just use your standard JOIN rules. ( Flexibility++ )

This has a bit of added flexibility in what you can do, but it's more suited for situations where you have a large table to query, with good indexing, and you want to use the parametrized list more than once. Saves having to execute it twice and have all the sanitation done manually.

I never got around to profiling exactly how fast it was, but in my situation it was needed.

How do I resolve a HTTP 414 "Request URI too long" error?

An excerpt from the RFC 2616: Hypertext Transfer Protocol -- HTTP/1.1:

The POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line. POST is designed to allow a uniform method to cover the following functions:

  • Annotation of existing resources;
  • Posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles;
  • Providing a block of data, such as the result of submitting a form, to a data-handling process;
  • Extending a database through an append operation.

How to hide status bar in Android

 if (Build.VERSION.SDK_INT < 16) {
   getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
 } else {
     View decorView = getWindow().getDecorView();
      int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
      decorView.setSystemUiVisibility(uiOptions);
      ActionBar actionBar = getActionBar();
      actionBar.hide();
 }

Find object in list that has attribute equal to some value (that meets any condition)

Old question but I use this quite frequently (for version 3.8). It's a bit of syntactic salt, but it has the advantage over the top answer in that you could retrieve a list of results (if there are multiple) by simply removing the [0] and it still defaults to None if nothing is found. For any other condition, simply change the x.value==value to what ever you're looking for.

_[0] if (_:=[x for x in test_list if x.value==value]) else None

How to use setArguments() and getArguments() methods in Fragments?

If you are using navigation components and navigation graph create a bundle like this

val bundle = bundleOf(KEY to VALUE) // or whatever you would like to create the bundle

then when navigating to the other fragment use this:

findNavController().navigate(
        R.id.action_navigate_from_frag1_to_frag2,
        bundle
    )

and when you land the destination fragment u can access that bundle using

Bundle b = getArguments()// in Java

or

val b = arguments// in kotlin

where is create-react-app webpack config and files?

Ejecting is not the best option as well as editing something under node_modules. react-app-rewired is not maintained and has the warning:

...you now "own" the configs. No support will be provided. Proceed with caution...

Solution - use craco.

Find duplicate entries in a column

Try this query.. It uses the Analytic function SUM:

SELECT * FROM
(  
 SELECT SUM(1) OVER(PARTITION BY ctn_no) cnt, A.*
 FROM table1 a 
 WHERE s_ind ='Y'   
)
WHERE cnt > 2

Am not sure why you are identifying a record as a duplicate if the ctn_no repeats more than 2 times. FOr me it repeats more than once it is a duplicate. In this case change the las part of the query to WHERE cnt > 1

How do I use InputFilter to limit characters in an EditText in Android?

It's Right, the best way to go about it to fix it in the XML Layout itself using:

<EditText
android:inputType="text"
android:digits="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" />

as rightly pointed by Florian Fröhlich, it works well for text views even.

<TextView
android:inputType="text"
android:digits="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" />

Just a word of caution, the characters mentioned in the android:digits will only be displayed, so just be careful not to miss any set of characters out :)

How to support different screen size in android

You can use sdp size unit instead of dp size unit. The sdp size unit is relative to the screen size and therefor is often preferred for targeting multiple screen sizes.

Use it carefully! for example, in most cases you still need to design a different layout for tablets.

Shell Scripting: Using a variable to define a path

Don't use spaces...

(Incorrect)

SPTH = '/home/Foo/Documents/Programs/ShellScripts/Butler'

(Correct)

SPTH='/home/Foo/Documents/Programs/ShellScripts/Butler'

Uploading Laravel Project onto Web Server

Had this problem too and found out that the easiest way is to point your domain to the public folder and leave everything else the way they are.

PLEASE ENSURE TO USE THE RIGHT VERSION OF PHP. Save yourself some stress :)

How to kill an application with all its activities?

You are correct: calling finish() will only exit the current activity, not the entire application. however, there is a workaround for this:

Every time you start an Activity, start it using startActivityForResult(...). When you want to close the entire app, you can do something like this:

setResult(RESULT_CLOSE_ALL);
finish();

Then define every activity's onActivityResult(...) callback so when an activity returns with the RESULT_CLOSE_ALL value, it also calls finish():

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch(resultCode)
    {
    case RESULT_CLOSE_ALL:
        setResult(RESULT_CLOSE_ALL);
        finish();
    }
    super.onActivityResult(requestCode, resultCode, data);
}

This will cause a cascade effect closing all activities.

Also, I support CommonsWare in his suggestion: store the password in a variable so that it will be destroyed when the application is closed.

One line if-condition-assignment

For the future time traveler from google, here is a new way (available from python 3.8 onward):

b = 1
if a := b:
    # this section is only reached if b is not 0 or false.
    # Also, a is set to b
    print(a, b)

How to delete columns that contain ONLY NAs?

Another option is the janitor package:

df <- remove_empty_cols(df)

https://github.com/sfirke/janitor

Adding integers to an int array

An array doesn't have an add method. You assign a value to an element of the array with num[i]=value;.

public static void main(String[] args) {
    int[] num = new int[args.length];
    for (int i=0; i < num.length; i++){
      int neki = Integer.parseInt(args[i]);
      num[i]=neki;
    }
}

How to get the index of a maximum element in a NumPy array along one axis

>>> import numpy as np
>>> a = np.array([[1,2,3],[4,3,1]])
>>> i,j = np.unravel_index(a.argmax(), a.shape)
>>> a[i,j]
4

Synchronizing a local Git repository with a remote one

git fetch --prune

-p, --prune
After fetching, remove any remote-tracking branches which no longer exist on the remote. prune options

Java Equivalent of C# async/await?

No, there isn't any equivalent of async/await in Java - or even in C# before v5.

It's a fairly complex language feature to build a state machine behind the scenes.

There's relatively little language support for asynchrony/concurrency in Java, but the java.util.concurrent package contains a lot of useful classes around this. (Not quite equivalent to the Task Parallel Library, but the closest approximation to it.)

org.hibernate.QueryException: could not resolve property: filename

Hibernate queries are case sensitive with property names (because they end up relying on getter/setter methods on the @Entity).

Make sure you refer to the property as fileName in the Criteria query, not filename.

Specifically, Hibernate will call the getter method of the filename property when executing that Criteria query, so it will look for a method called getFilename(). But the property is called FileName and the getter getFileName().

So, change the projection like so:

criteria.setProjection(Projections.property("fileName"));

What are the differences between json and simplejson Python modules?

Some values are serialized differently between simplejson and json.

Notably, instances of collections.namedtuple are serialized as arrays by json but as objects by simplejson. You can override this behaviour by passing namedtuple_as_object=False to simplejson.dump, but by default the behaviours do not match.

>>> import collections, simplejson, json
>>> TupleClass = collections.namedtuple("TupleClass", ("a", "b"))
>>> value = TupleClass(1, 2)
>>> json.dumps(value)
'[1, 2]'
>>> simplejson.dumps(value)
'{"a": 1, "b": 2}'
>>> simplejson.dumps(value, namedtuple_as_object=False)
'[1, 2]'

ResultSet exception - before start of result set

Every answer uses .next() or uses .beforeFirst() and then .next(). But why not this:

result.first();

So You just set the pointer to the first record and go from there. It's available since java 1.2 and I just wanted to mention this for anyone whose ResultSet exists of one specific record.

AngularJS Error: $injector:unpr Unknown Provider

Your angular module needs to be initialized properly. The global object app needs to be defined and initialized correctly to inject the service.

Please see below sample code for reference:

app.js

var app = angular.module('SampleApp',['ngRoute']); //You can inject the dependencies within the square bracket    

app.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
  $routeProvider
    .when('/', {
      templateUrl:"partials/login.html",
      controller:"login"
    });

  $locationProvider
    .html5Mode(true);
}]);

app.factory('getSettings', ['$http', '$q', function($http, $q) {
  return {
    //Code edited to create a function as when you require service it returns object by default so you can't return function directly. That's what understand...
    getSetting: function (type) { 
      var q = $q.defer();
      $http.get('models/settings.json').success(function (data) {
        q.resolve(function() {
          var settings = jQuery.parseJSON(data);
          return settings[type];
        });
      });
      return q.promise;
    }
  }
}]);

app.controller("globalControl", ['$scope','getSettings', function ($scope,getSettings) {
  //Modified the function call for updated service
  var loadSettings = getSettings.getSetting('global');
  loadSettings.then(function(val) {
    $scope.settings = val;
  });
}]);

Sample HTML code should be like this:

<!DOCTYPE html>
<html>
    <head lang="en">
        <title>Sample Application</title>
    </head>
    <body ng-app="SampleApp" ng-controller="globalControl">
        <div>
            Your UI elements go here
        </div>
        <script src="app.js"></script>
    </body>
</html>

Please note that the controller is not binding to an HTML tag but to the body tag. Also, please try to include your custom scripts at end of the HTML page as this is a standard practice to follow for performance reasons.

I hope this will solve your basic injection issue.

Switch statement fallthrough in C#?

Just a quick note to add that the compiler for Xamarin actually got this wrong and it allows fallthrough. It has supposedly been fixed, but has not been released. Discovered this in some code that actually was falling through and the compiler did not complain.

What is the maximum length of a valid email address?

To help the confused rookies like me, the answer to "What is the maximum length of a valid email address?" is 254 characters.

If your application uses an email, just set your field to accept 254 characters or less and you are good to go.

You can run a bunch of tests on an email to see if it is valid here. http://isemail.info/

The RFC, or Request for Comments is a type of publication from the Internet Engineering Task Force (IETF) that defines 254 characters as the limit. Located here - https://tools.ietf.org/html/rfc5321#section-4.5.3

Get everything after and before certain character in SQL Server

use the following function

left(@test, charindex('/', @test) - 1)

Java how to replace 2 or more spaces with single space in string and delete leading and trailing spaces

Try this one.

Sample Code

String str = " hello     there   ";
System.out.println(str.replaceAll("( +)"," ").trim());

OUTPUT

hello there

First it will replace all the spaces with single space. Than we have to supposed to do trim String because Starting of the String and End of the String it will replace the all space with single space if String has spaces at Starting of the String and End of the String So we need to trim them. Than you get your desired String.

Highlight Bash/shell code in Markdown files

It depends on the Markdown rendering engine and the Markdown flavour. There is no standard for this. If you mean GitHub flavoured Markdown for example, shell should work fine. Aliases are sh, bash or zsh. You can find the list of available syntax lexers here.

How to loop through a checkboxlist and to find what's checked and not checked?

Use the CheckBoxList's GetItemChecked or GetItemCheckState method to find out whether an item is checked or not by its index.

Print a file, skipping the first X lines, in Bash

If you want to skip first two line:

tail -n +3 <filename>

If you want to skip first x line:

tail -n +$((x+1)) <filename>

Convert DateTime in C# to yyyy-MM-dd format and Store it to MySql DateTime Field

Try setting a custom CultureInfo for CurrentCulture and CurrentUICulture.

Globalization.CultureInfo customCulture = new Globalization.CultureInfo("en-US", true);

customCulture.DateTimeFormat.ShortDatePattern = "yyyy-MM-dd h:mm tt";

System.Threading.Thread.CurrentThread.CurrentCulture = customCulture;
System.Threading.Thread.CurrentThread.CurrentUICulture = customCulture;

DateTime newDate = System.Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd h:mm tt"));

How to decode Unicode escape sequences like "\u00ed" to proper UTF-8 encoded characters?

$str = '\u0063\u0061\u0074'.'\ud83d\ude38';
$str2 = '\u0063\u0061\u0074'.'\ud83d';

// U+1F638
var_dump(
    "cat\xF0\x9F\x98\xB8" === escape_sequence_decode($str),
    "cat\xEF\xBF\xBD" === escape_sequence_decode($str2)
);

function escape_sequence_decode($str) {

    // [U+D800 - U+DBFF][U+DC00 - U+DFFF]|[U+0000 - U+FFFF]
    $regex = '/\\\u([dD][89abAB][\da-fA-F]{2})\\\u([dD][c-fC-F][\da-fA-F]{2})
              |\\\u([\da-fA-F]{4})/sx';

    return preg_replace_callback($regex, function($matches) {

        if (isset($matches[3])) {
            $cp = hexdec($matches[3]);
        } else {
            $lead = hexdec($matches[1]);
            $trail = hexdec($matches[2]);

            // http://unicode.org/faq/utf_bom.html#utf16-4
            $cp = ($lead << 10) + $trail + 0x10000 - (0xD800 << 10) - 0xDC00;
        }

        // https://tools.ietf.org/html/rfc3629#section-3
        // Characters between U+D800 and U+DFFF are not allowed in UTF-8
        if ($cp > 0xD7FF && 0xE000 > $cp) {
            $cp = 0xFFFD;
        }

        // https://github.com/php/php-src/blob/php-5.6.4/ext/standard/html.c#L471
        // php_utf32_utf8(unsigned char *buf, unsigned k)

        if ($cp < 0x80) {
            return chr($cp);
        } else if ($cp < 0xA0) {
            return chr(0xC0 | $cp >> 6).chr(0x80 | $cp & 0x3F);
        }

        return html_entity_decode('&#'.$cp.';');
    }, $str);
}

Compare string with all values in list

If you only want to know if any item of d is contained in paid[j], as you literally say:

if any(x in paid[j] for x in d): ...

If you also want to know which items of d are contained in paid[j]:

contained = [x for x in d if x in paid[j]]

contained will be an empty list if no items of d are contained in paid[j].

There are other solutions yet if what you want is yet another alternative, e.g., get the first item of d contained in paid[j] (and None if no item is so contained):

firstone = next((x for x in d if x in paid[j]), None)

BTW, since in a comment you mention sentences and words, maybe you don't necessarily want a string check (which is what all of my examples are doing), because they can't consider word boundaries -- e.g., each example will say that 'cat' is in 'obfuscate' (because, 'obfuscate' contains 'cat' as a substring). To allow checks on word boundaries, rather than simple substring checks, you might productively use regular expressions... but I suggest you open a separate question on that, if that's what you require -- all of the code snippets in this answer, depending on your exact requirements, will work equally well if you change the predicate x in paid[j] into some more sophisticated predicate such as somere.search(paid[j]) for an appropriate RE object somere. (Python 2.6 or better -- slight differences in 2.5 and earlier).

If your intention is something else again, such as getting one or all of the indices in d of the items satisfying your constrain, there are easy solutions for those different problems, too... but, if what you actually require is so far away from what you said, I'd better stop guessing and hope you clarify;-).

In Python, how do I loop through the dictionary and change the value if it equals something?

You could create a dict comprehension of just the elements whose values are None, and then update back into the original:

tmp = dict((k,"") for k,v in mydict.iteritems() if v is None)
mydict.update(tmp)

Update - did some performance tests

Well, after trying dicts of from 100 to 10,000 items, with varying percentage of None values, the performance of Alex's solution is across-the-board about twice as fast as this solution.

Interop type cannot be embedded

Here's where to set the Embed Interop in Visual Studio 2012

enter image description here

Load More Posts Ajax Button in WordPress

If I'm not using any category then how can I use this code? Actually, I want to use this code for custom post type.

Convert byte slice to io.Reader

To get a type that implements io.Reader from a []byte slice, you can use bytes.NewReader in the bytes package:

r := bytes.NewReader(byteData)

This will return a value of type bytes.Reader which implements the io.Reader (and io.ReadSeeker) interface.

Don't worry about them not being the same "type". io.Reader is an interface and can be implemented by many different types. To learn a little bit more about interfaces in Go, read Effective Go: Interfaces and Types.

How to get document height and width without using jquery

You should use getBoundingClientRect as it usually works cross browser and gives you sub-pixel precision on the bounds rectangle.

elem.getBoundingClientRect()

Select n random rows from SQL Server table

This is a combination of the initial seed idea and a checksum, which looks to me to give properly random results without the cost of NEWID():

SELECT TOP [number] 
FROM table_name
ORDER BY RAND(CHECKSUM(*) * RAND())

How to perform case-insensitive sorting in JavaScript?

arr.sort(function(a,b) {
    a = a.toLowerCase();
    b = b.toLowerCase();
    if( a == b) return 0;
    if( a > b) return 1;
    return -1;
});

In above function, if we just compare when lower case two value a and b, we will not have the pretty result.

Example, if array is [A, a, B, b, c, C, D, d, e, E] and we use the above function, we have exactly that array. It's not changed anything.

To have the result is [A, a, B, b, C, c, D, d, E, e], we should compare again when two lower case value is equal:

function caseInsensitiveComparator(valueA, valueB) {
    var valueALowerCase = valueA.toLowerCase();
    var valueBLowerCase = valueB.toLowerCase();

    if (valueALowerCase < valueBLowerCase) {
        return -1;
    } else if (valueALowerCase > valueBLowerCase) {
        return 1;
    } else { //valueALowerCase === valueBLowerCase
        if (valueA < valueB) {
            return -1;
        } else if (valueA > valueB) {
            return 1;
        } else {
            return 0;
        }
    }
}

How can I add 1 day to current date?

If you want add a day (24 hours) to current datetime you can add milliseconds like this:

new Date(Date.now() + ( 3600 * 1000 * 24))

How to add a 'or' condition in #ifdef

May use this-

#if defined CONDITION1 || defined CONDITION2
//your code here
#endif

This also does the same-

#if defined(CONDITION1) || defined(CONDITION2)
//your code here
#endif

Further-

  • AND: #if defined CONDITION1 && defined CONDITION2
  • XOR: #if defined CONDITION1 ^ defined CONDITION2
  • AND NOT: #if defined CONDITION1 && !defined CONDITION2

how to run mysql in ubuntu through terminal

You have to give a valid username. For example, to run query with user root you have to type the following command and then enter password when prompted:

mysql -u root -p

Once you are connected, prompt will be something like:

mysql>

Here you can write your query, after database selection, for example:

mysql> USE your_database;
mysql> SELECT * FROM your_table;

How do you make Vim unhighlight what you searched for?

I add the following mapping to my ~/.vimrc

map e/ /sdfdskfxxxxy

And in ESC mode, I press e/

Initializing array of structures

my_data is a struct with name as a field and data[] is arry of structs, you are initializing each index. read following:

5.20 Designated Initializers:

In a structure initializer, specify the name of a field to initialize with .fieldname =' before the element value. For example, given the following structure,

struct point { int x, y; };

the following initialization

struct point p = { .y = yvalue, .x = xvalue };

is equivalent to

struct point p = { xvalue, yvalue };

Another syntax which has the same meaning, obsolete since GCC 2.5, is fieldname:', as shown here:

struct point p = { y: yvalue, x: xvalue };

You can also write:

my_data data[] = {
    { .name = "Peter" },
    { .name = "James" },
    { .name = "John" },
    { .name = "Mike" }
};

as:

my_data data[] = {
    [0] = { .name = "Peter" },
    [1] = { .name = "James" },
    [2] = { .name = "John" },
    [3] = { .name = "Mike" }
}; 

or:

my_data data[] = {
    [0].name = "Peter",
    [1].name = "James",
    [2].name = "John",
    [3].name = "Mike"
}; 

Second and third forms may be convenient as you don't need to write in order for example all of the above example are equivalent to:

my_data data[] = {
    [3].name = "Mike",
    [1].name = "James",
    [0].name = "Peter",
    [2].name = "John"
}; 

If you have multiple fields in your struct (for example, an int age), you can initialize all of them at once using the following:

my_data data[] = {
    [3].name = "Mike",
    [2].age = 40,
    [1].name = "James",
    [3].age = 23,
    [0].name = "Peter",
    [2].name = "John"
}; 

To understand array initialization read Strange initializer expression?

Additionally, you may also like to read @Shafik Yaghmour's answer for switch case: What is “…” in switch-case in C code

XPath to select Element by attribute value

As a follow on, you could select "all nodes with a particular attribute" like this:

//*[@id='4']

Read .csv file in C

With fscanf read the file until you encounter ';' or \n, then you can just skip it with fscang(f, "%*c").

int main()
{
    char str[128];
    int result;
    FILE* f = fopen("test.txt", "r");
    ...
    
    do {
        result = fscanf(f, "%127[^;\n]", str);
        
        if(result == 0)
        {
            result = fscanf(f, "%*c");
        }
        else
        {
            //whatever you want to do with your value
            printf("%s\n", str);
        }
        
    } while(result != EOF);

    return 0;
}

What is the difference between "SMS Push" and "WAP Push"?

SMS Push uses SMS as a carrier, WAP uses download via WAP.

How do I automatically play a Youtube video (IFrame API) muted?

Update 2021 to loop and autoplay video on desktop/mobile devices (tested on iPhone X - Safari).

I am using the onPlayerStateChange event and if the video end, I play the video again. Refference to onPlayerStateChange event in YouTube API.

_x000D_
_x000D_
<div id="player"></div>
<script>
  var tag = document.createElement('script');

  tag.src = "https://www.youtube.com/iframe_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

  var player;

  function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
      height: '100%',
      width: '100%',
      playerVars: {
        autoplay: 1,
        loop: 1,
        controls: 0,
        showinfo: 0,
        autohide: 1,
        playsinline: 1,
        mute: 1,
        modestbranding: 1,
        vq: 'hd1080'
      },
      videoId: 'ScMzIvxBSi4',
      events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange
      }
    });
  }

  function onPlayerReady(event) {
    event.target.mute();

    setTimeout(function() {
      event.target.playVideo();
    }, 0);
  }

  function onPlayerStateChange(event) {
    if (event.target.getPlayerState() == 0) {
      setTimeout(function() {
        event.target.playVideo();
      }, 0);
    }
  }
</script>
_x000D_
_x000D_
_x000D_

How do I trap ctrl-c (SIGINT) in a C# console app

In my case, I passed an async lambda to Console.CancelKeyPress, which won't work.

SFTP in Python? (platform independent)

There are a bunch of answers that mention pysftp, so in the event that you want a context manager wrapper around pysftp, here is a solution that is even less code that ends up looking like the following when used

path = "sftp://user:p@[email protected]/path/to/file.txt"

# Read a file
with open_sftp(path) as f:
    s = f.read() 
print s

# Write to a file
with open_sftp(path, mode='w') as f:
    f.write("Some content.") 

The (fuller) example: http://www.prschmid.com/2016/09/simple-opensftp-context-manager-for.html

This context manager happens to have auto-retry logic baked in in the event you can't connect the first time around (which surprisingly happens more often than you'd expect in a production environment...)

The context manager gist for open_sftp: https://gist.github.com/prschmid/80a19c22012e42d4d6e791c1e4eb8515

How to have stored properties in Swift, the same way I had on Objective-C?

Here is an alternative that works also

public final class Storage : AnyObject {

    var object:Any?

    public init(_ object:Any) {
        self.object = object
    }
}

extension Date {

    private static let associationMap = NSMapTable<NSString, AnyObject>()
    private struct Keys {
        static var Locale:NSString = "locale"
    }

    public var locale:Locale? {
        get {

            if let storage = Date.associationMap.object(forKey: Keys.Locale) {
                return (storage as! Storage).object as? Locale
            }
            return nil
        }
        set {
            if newValue != nil {
                Date.associationMap.setObject(Storage(newValue), forKey: Keys.Locale)
            }
        }
    }
}



var date = Date()
date.locale = Locale(identifier: "pt_BR")
print( date.locale )

twitter bootstrap typeahead ajax example

i use $().one() for solve this; When page loaded, I send ajax to server and wait to done. Then pass result to function.$().one() is important .Because force typehead.js to attach to input one time. sorry for bad writing.

_x000D_
_x000D_
(($) => {_x000D_
    _x000D_
    var substringMatcher = function(strs) {_x000D_
        return function findMatches(q, cb) {_x000D_
          var matches, substringRegex;_x000D_
          // an array that will be populated with substring matches_x000D_
          matches = [];_x000D_
      _x000D_
          // regex used to determine if a string contains the substring `q`_x000D_
          substrRegex = new RegExp(q, 'i');_x000D_
      _x000D_
          // iterate through the pool of strings and for any string that_x000D_
          // contains the substring `q`, add it to the `matches` array_x000D_
          $.each(strs, function(i, str) {_x000D_
            if (substrRegex.test(str)) {_x000D_
              matches.push(str);_x000D_
            }_x000D_
          });_x000D_
          cb(matches);_x000D_
        };_x000D_
      };_x000D_
      _x000D_
      var states = [];_x000D_
      $.ajax({_x000D_
          url: 'https://baconipsum.com/api/?type=meat-and-filler',_x000D_
          type: 'get'_x000D_
      }).done(function(data) {_x000D_
        $('.typeahead').one().typeahead({_x000D_
            hint: true,_x000D_
            highlight: true,_x000D_
            minLength: 1_x000D_
          },_x000D_
          {_x000D_
            name: 'states',_x000D_
            source: substringMatcher(data)_x000D_
          });_x000D_
      })_x000D_
      _x000D_
_x000D_
})(jQuery);
_x000D_
.tt-query, /* UPDATE: newer versions use tt-input instead of tt-query */_x000D_
.tt-hint {_x000D_
    width: 396px;_x000D_
    height: 30px;_x000D_
    padding: 8px 12px;_x000D_
    font-size: 24px;_x000D_
    line-height: 30px;_x000D_
    border: 2px solid #ccc;_x000D_
    border-radius: 8px;_x000D_
    outline: none;_x000D_
}_x000D_
_x000D_
.tt-query { /* UPDATE: newer versions use tt-input instead of tt-query */_x000D_
    box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);_x000D_
}_x000D_
_x000D_
.tt-hint {_x000D_
    color: #999;_x000D_
}_x000D_
_x000D_
.tt-menu { /* UPDATE: newer versions use tt-menu instead of tt-dropdown-menu */_x000D_
    width: 422px;_x000D_
    margin-top: 12px;_x000D_
    padding: 8px 0;_x000D_
    background-color: #fff;_x000D_
    border: 1px solid #ccc;_x000D_
    border: 1px solid rgba(0, 0, 0, 0.2);_x000D_
    border-radius: 8px;_x000D_
    box-shadow: 0 5px 10px rgba(0,0,0,.2);_x000D_
}_x000D_
_x000D_
.tt-suggestion {_x000D_
    padding: 3px 20px;_x000D_
    font-size: 18px;_x000D_
    line-height: 24px;_x000D_
    cursor: pointer;_x000D_
}_x000D_
_x000D_
.tt-suggestion:hover {_x000D_
    color: #f0f0f0;_x000D_
    background-color: #0097cf;_x000D_
}_x000D_
_x000D_
.tt-suggestion p {_x000D_
    margin: 0;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://twitter.github.io/typeahead.js/releases/latest/typeahead.bundle.js"></script>_x000D_
_x000D_
<input class="typeahead" type="text" placeholder="where ?">
_x000D_
_x000D_
_x000D_

$.ajax - dataType

  • contentType is the HTTP header sent to the server, specifying a particular format.
    Example: I'm sending JSON or XML
  • dataType is you telling jQuery what kind of response to expect.
    Expecting JSON, or XML, or HTML, etc. The default is for jQuery to try and figure it out.

The $.ajax() documentation has full descriptions of these as well.


In your particular case, the first is asking for the response to be in UTF-8, the second doesn't care. Also the first is treating the response as a JavaScript object, the second is going to treat it as a string.

So the first would be:

success: function(data) {
  // get data, e.g. data.title;
}

The second:

success: function(data) {
  alert("Here's lots of data, just a string: " + data);
}

String isNullOrEmpty in Java?

For new projects, I've started having every class I write extend the same base class where I can put all the utility methods that are annoyingly missing from Java like this one, the equivalent for collections (tired of writing list != null && ! list.isEmpty()), null-safe equals, etc. I still use Apache Commons for the implementation but this saves a small amount of typing and I haven't seen any negative effects.

get launchable activity name of package from adb

You can also use ddms for logcat logs where just giving search of the app name you will all info but you have to select Info instead of verbose or other options. check this below image.

enter image description here

How can I INSERT data into two tables simultaneously in SQL Server?

I was also struggling with this problem, and find that the best way is to use a CURSOR.

I have tried Denis solution with OUTPUT, but as he mentiond, it's impossible to output external columns in an insert statement, and the MERGE can't work when insert multiple rows by select.

So, i've used a CURSOR, for each row in the outer table, i've done a INSERT, then use the @@IDENTITY for another INSERT.

DECLARE @OuterID int

DECLARE MY_CURSOR CURSOR 
  LOCAL STATIC READ_ONLY FORWARD_ONLY
FOR 
SELECT  ID FROM   [external_Table]

OPEN MY_CURSOR
FETCH NEXT FROM MY_CURSOR INTO @OuterID

WHILE @@FETCH_STATUS = 0
BEGIN 
INSERT INTO [Table]   (data)
    SELECT data
    FROM     [external_Table] where ID = @OuterID 

    INSERT INTO [second_table] (FK,OuterID)
    VALUES(@OuterID,@@identity)

    FETCH NEXT FROM MY_CURSOR INTO @OuterID
END
CLOSE MY_CURSOR
DEALLOCATE MY_CURSOR

How do I make a redirect in PHP?

To redirect the visitor to another page (particularly useful in a conditional loop), simply use the following code:

<?php
    header('Location: mypage.php');
?>

In this case, mypage.php is the address of the page to which you would like to redirect the visitors. This address can be absolute and may also include the parameters in this format: mypage.php?param1=val1&m2=val2)

Relative/Absolute Path

When dealing with relative or absolute paths, it is ideal to choose an absolute path from the root of the server (DOCUMENT_ROOT). Use the following format:

<?php
    header('Location: /directory/mypage.php');
?>

If ever the target page is on another server, you include the full URL:

<?php
    header('Location: http://www.ccm.net/forum/');
?>

HTTP Headers

According to HTTP protocol, HTTP headers must be sent before any type of content. This means that no characters should ever be sent before the header — not even an empty space!

Temporary/Permanent Redirections

By default, the type of redirection presented above is a temporary one. This means that search engines, such as Google Search, will not take the redirection into account when indexing.

If you would like to notify search engines that a page has been permanently moved to another location, use the following code:

<?
    header('Status: 301 Moved Permanently', false, 301);
    header('Location: new_address');
?>

For example, this page has the following code:

<?
    header('Status: 301 Moved Permanently', false, 301);
    header('Location: /pc/imprimante.php3');
    exit();
?>

When you click on the link above, you are automatically redirected to this page. Moreover, it is a permanent redirection (Status: 301 Moved Permanently). So, if you type the first URL into Google, you will automatically be redirected to the second, redirected link.

Interpretation of PHP Code

The PHP code located after the header() will be interpreted by the server, even if the visitor moves to the address specified in the redirection. In most cases, this means that you need a method to follow the header() function of the exit() function in order to decrease the load of the server:

<?
    header('Status: 301 Moved Permanently', false, 301);
    header('Location: address');
    exit();
?>