Programs & Examples On #Cql

CQL (Cassandra Query Language) is used to interact with and query Cassandra tables. Its syntax is similar to SQL, helping to lower the learning curve to working with Cassandra. For the Cypher graph query language, use the cypher tag.

Difference between partition key, composite key and clustering key in Cassandra?

Primary Key: Is composed of partition key(s) [and optional clustering keys(or columns)]
Partition Key: The hash value of Partition key is used to determine the specific node in a cluster to store the data
Clustering Key: Is used to sort the data in each of the partitions(or responsible node and it's replicas)

Compound Primary Key: As said above, the clustering keys are optional in a Primary Key. If they aren't mentioned, it's a simple primary key. If clustering keys are mentioned, it's a Compound primary key.

Composite Partition Key: Using just one column as a partition key, might result in wide row issues (depends on use case/data modeling). Hence the partition key is sometimes specified as a combination of more than one column.

Regarding confusion of which one is mandatory, which one can be skipped etc. in a query, trying to imagine Cassandra as a giant HashMap helps. So in a HashMap, you can't retrieve the values without the Key.
Here, the Partition keys play the role of that key. So each query needs to have them specified. Without which Cassandra won't know which node to search for.
The clustering keys (columns, which are optional) help in further narrowing your query search after Cassandra finds out the specific node(and it's replicas) responsible for that specific Partition key.

Write a file on iOS

Your code is working at my end, i have just tested it. Where are you checking your changes? Use Documents directory path. To get path -

NSLog(@"%@",documentsDirectory);

and copy path from console and then open finder and press Cmd+shift+g and paste path here and then open your file

Javascript / Chrome - How to copy an object from the webkit inspector as code

This should help stringify deep objects by leaving out recursive Window and Node objects.

function stringifyObject(e) {
  const obj = {};
  for (let k in e) {
    obj[k] = e[k];
  }

  return JSON.stringify(obj, (k, v) => {
    if (v instanceof Node) return 'Node';
    if (v instanceof Window) return 'Window';
    return v;
  }, ' ');
}

How do I clear my Jenkins/Hudson build history?

Navigate to: %JENKINS_HOME%\jobs\jobName

Open the file "nextBuildNumber" and change the number. After that reload Jenkins configuration. Note: "nextBuildNumber" file contains the next build no that will be used by Jenkins.

Regular vs Context Free Grammars

Regular grammar:- grammar containing production as follows is RG:

V->TV or VT
V->T

where V=variable and T=terminal

RG may be Left Linear Grammar or Right Liner Grammar, but not Middle linear Grammar.

As we know all RG are Linear Grammar but only Left Linear or Right Linear Grammar are RG.

A regular grammar can be ambiguous.

S->aA|aB
A->a
B->a

Ambiguous Grammar:- for a string x their exist more than one LMD or More than RMD or More than one Parse tree or One LMD and One RMD but both Produce different Parse tree.

                S                   S

              /   \               /   \
             a     A             a     B
                    \                   \
                     a                   a

this Grammar is ambiguous Grammar because two parse tree.

CFG:- A grammar said to be CFG if its Production is in form:

   V->@   where @ belongs to (V+T)*

DCFL:- as we know all DCFL are LL(1) Grammar and all LL(1) is LR(1) so it is Never be ambiguous. so DCFG is Never be ambiguous.

We also know all RL are DCFL so RL never be ambiguous. Note that RG may be ambiguous but RL not.

CFL: CFl May or may not ambiguous.

Note: RL never be Inherently ambiguous.

How do I fix certificate errors when running wget on an HTTPS URL in Cygwin?

May be this will help:

wget --no-check-certificate https://blah-blah.tld/path/filename

How to see the CREATE VIEW code for a view in PostgreSQL?

GoodNews from v.9.6 and above, View editing are now native from psql. Just invoke \ev command. View definitions will show in your configured editor.

julian@assange=# \ev {your_view_names}

Bonus. Some useful command to interact with query buffer.

Query Buffer
  \e [FILE] [LINE]       edit the query buffer (or file) with external editor
  \ef [FUNCNAME [LINE]]  edit function definition with external editor
  \ev [VIEWNAME [LINE]]  edit view definition with external editor
  \p                     show the contents of the query buffer
  \r                     reset (clear) the query buffer
  \s [FILE]              display history or save it to file
  \w FILE                write query buffer to file

How to do joins in LINQ on multiple fields in single join

Declare a Class(Type) to hold the elements you want to join. In the below example declare JoinElement

 public class **JoinElement**
{
    public int? Id { get; set; }
    public string Name { get; set; }

}

results = from course in courseQueryable.AsQueryable()
                  join agency in agencyQueryable.AsQueryable()
                   on new **JoinElement**() { Id = course.CourseAgencyId, Name = course.CourseDeveloper } 
                   equals new **JoinElement**() { Id = agency.CourseAgencyId, Name = "D" } into temp1

How to read from input until newline is found using scanf()?

Sounds like a homework problem. scanf() is the wrong function to use for the problem. I'd recommend getchar() or getch().

Note: I'm purposefully not solving the problem since this seems like homework, instead just pointing you in the right direction.

Generate MD5 hash string with T-SQL

CONVERT(VARCHAR(32), HashBytes('MD5', '[email protected]'), 2)

Visual Studio : short cut Key : Duplicate Line

In visual studio code (WebMatrix):

Copy Lines Down: Shift + Alt + down

Copy Lines Up: Shift + Alt + up

Delete Lines: Ctrl + Shift + k

Retrieving Android API version programmatically

android.os.Build.VERSION.SDK should give you the value of the API Level. You can easily find the mapping from api level to android version in the android documentation. I believe, 8 is for 2.2, 7 for 2.1, and so on.

How can I connect to MySQL in Python 3 on Windows?

PyMySQL gives MySQLDb like interface as well. You could try in your initialization:

import pymysql
pymysql.install_as_MySQLdb()

Also there is a port of mysql-python on github for python3.

https://github.com/davispuh/MySQL-for-Python-3

Get a list of all threads currently running in Java

Apache Commons users can use ThreadUtils. The current implementation uses the walk the thread group approach previously outlined.

for (Thread t : ThreadUtils.getAllThreads()) {
      System.out.println(t.getName() + ", " + t.isDaemon());
}

What does "res.render" do, and what does the html file look like?

What does res.render do and what does the html file look like?

res.render() function compiles your template (please don't use ejs), inserts locals there, and creates html output out of those two things.


Answering Edit 2 part.

// here you set that all templates are located in `/views` directory
app.set('views', __dirname + '/views');

// here you set that you're using `ejs` template engine, and the
// default extension is `ejs`
app.set('view engine', 'ejs');

// here you render `orders` template
response.render("orders", {orders: orders_json});

So, the template path is views/ (first part) + orders (second part) + .ejs (third part) === views/orders.ejs


Anyway, express.js documentation is good for what it does. It is API reference, not a "how to use node.js" book.

How to get the current location latitude and longitude in android

Here is Android Location library you can find your current location without using Google account or subscription.

Find this link and download repository

https://github.com/mrmans0n/smart-location-lib

Take care and Enjoy...

How to automatically generate a stacktrace when my program crashes

You can use DeathHandler - small C++ class which does everything for you, reliable.

What is the Maximum Size that an Array can hold?

Here is an answer to your question that goes into detail: http://www.velocityreviews.com/forums/t372598-maximum-size-of-byte-array.html

You may want to mention which version of .NET you are using and your memory size.

You will be stuck to a 2G, for your application, limit though, so it depends on what is in your array.

The executable gets signed with invalid entitlements in Xcode

Another thing to check - make sure you have the correct entities selected in both

Targets -> Your Target -> Build Settings -> Signing

and

Project -> Your Project -> Build Settings -> Code Signing Entity

I got this message when I had a full dev profile selected in one and a different (non-developer) Apple ID selected in the other, even with no entitlements requested in the app.

System.BadImageFormatException: Could not load file or assembly

I had the same exception installing using correct framework.

My solution was running cmd as administrator .... then it worked fine.

Getting output of system() calls in Ruby

As a direct system(...) replacement you may use Open3.popen3(...)

Further discussion: http://tech.natemurray.com/2007/03/ruby-shell-commands.html

How to detect pressing Enter on keyboard using jQuery?

The whole point of jQuery is that you don't have to worry about browser differences. I am pretty sure you can safely go with enter being 13 in all browsers. So with that in mind, you can do this:

$(document).on('keypress',function(e) {
    if(e.which == 13) {
        alert('You pressed enter!');
    }
});

org.apache.jasper.JasperException: Unable to compile class for JSP:

There's no need to manually put class files on Tomcat. Just make sure your package declaration for Member is correctly defined as

package pageNumber;

since, that's the only application package you're importing in your JSP.

<%@ page import="pageNumber.*, java.util.*, java.io.*" %>

How to pass a PHP variable using the URL

just put

$a='Link1';
$b='Link2';

in your pass.php and you will get your answer and do a double quotation in your link.php:

echo '<a href="pass.php?link=' . $a . '">Link 1</a>';

Setting up Eclipse with JRE Path

You should specify where Eclipse should find your JDK in the file eclipse.ini. Specifically, the following parameter (note that it is 2 separate lines in the ini file):

-vm
C:\Java\JDK\1.8\bin\javaw.exe

or wherever your javaw.exe happens to be.

Note: The format of the ini file is very particular; make sure to consult https://wiki.eclipse.org/Eclipse.ini to ensure you get it exactly right

In Tkinter is there any way to make a widget not visible?

For hiding a widget you can use function pack_forget() and to again show it you can use pack() function and implement them both in separate functions.

from Tkinter import *
root = Tk()
label=Label(root,text="I was Hidden")
def labelactive():
    label.pack()
def labeldeactive():
    label.pack_forget()
Button(root,text="Show",command=labelactive).pack()
Button(root,text="Hide",command=labeldeactive).pack()
root.mainloop()

Can't concat bytes to str

subprocess.check_output() returns a bytestring.

In Python 3, there's no implicit conversion between unicode (str) objects and bytes objects. If you know the encoding of the output, you can .decode() it to get a string, or you can turn the \n you want to add to bytes with "\n".encode('ascii')

Choose newline character in Notepad++

on windows 10, Notepad 7.8.5, i found this solution to convert from CRLF to LF.
Edit > Format end of line
and choose either Windows(CR+LF) or Unix(LF)

jquery: get value of custom attribute

You can also do this by passing function with onclick event

<a onclick="getColor(this);" color="red">

<script type="text/javascript">

function getColor(el)
{
     color = $(el).attr('color');
     alert(color);
}

</script> 

Remove CSS from a Div using JQuery

As a note, depending upon the property you may be able to set it to auto.

How to make a JSONP request from Javascript without JQuery?

Just pasting an ES6 version of sobstel's nice answer:

send(someUrl + 'error?d=' + encodeURI(JSON.stringify(json)) + '&callback=c', 'c', 5)
    .then((json) => console.log(json))
    .catch((err) => console.log(err))

function send(url, callback, timeout) {
    return new Promise((resolve, reject) => {
        let script = document.createElement('script')
        let timeout_trigger = window.setTimeout(() => {
            window[callback] = () => {}
            script.parentNode.removeChild(script)
            reject('No response')
        }, timeout * 1000)

        window[callback] = (data) => {
            window.clearTimeout(timeout_trigger)
            script.parentNode.removeChild(script)
            resolve(data)
        }

        script.type = 'text/javascript'
        script.async = true
        script.src = url

        document.getElementsByTagName('head')[0].appendChild(script)
    })
}

MySQL - Rows to Columns

I figure out one way to make my reports converting rows to columns almost dynamic using simple querys. You can see and test it online here.

The number of columns of query is fixed but the values are dynamic and based on values of rows. You can build it So, I use one query to build the table header and another one to see the values:

SELECT distinct concat('<th>',itemname,'</th>') as column_name_table_header FROM history order by 1;

SELECT
     hostid
    ,(case when itemname = (select distinct itemname from history a order by 1 limit 0,1) then itemvalue else '' end) as col1
    ,(case when itemname = (select distinct itemname from history a order by 1 limit 1,1) then itemvalue else '' end) as col2
    ,(case when itemname = (select distinct itemname from history a order by 1 limit 2,1) then itemvalue else '' end) as col3
    ,(case when itemname = (select distinct itemname from history a order by 1 limit 3,1) then itemvalue else '' end) as col4
FROM history order by 1;

You can summarize it, too:

SELECT
     hostid
    ,sum(case when itemname = (select distinct itemname from history a order by 1 limit 0,1) then itemvalue end) as A
    ,sum(case when itemname = (select distinct itemname from history a order by 1 limit 1,1) then itemvalue end) as B
    ,sum(case when itemname = (select distinct itemname from history a order by 1 limit 2,1) then itemvalue end) as C
FROM history group by hostid order by 1;
+--------+------+------+------+
| hostid | A    | B    | C    |
+--------+------+------+------+
|      1 |   10 |    3 | NULL |
|      2 |    9 | NULL |   40 |
+--------+------+------+------+

Results of RexTester:

Results of RexTester

http://rextester.com/ZSWKS28923

For one real example of use, this report bellow show in columns the hours of departures arrivals of boat/bus with a visual schedule. You will see one additional column not used at the last col without confuse the visualization: sistema venda de passagens online e consumidor final e controle de frota - xsl tecnologia - xsl.com.br ** ticketing system to of sell ticket online and presential

javaw.exe cannot find path

Make sure to download these from here:

enter image description here

Also create PATH enviroment variable on you computer like this (if it doesn't exist already):

  1. Right click on My Computer/Computer
  2. Properties
  3. Advanced system settings (or just Advanced)
  4. Enviroment variables
  5. If PATH variable doesn't exist among "User variables" click New (Variable name: PATH, Variable value : C:\Program Files\Java\jdk1.8.0\bin; <-- please check out the right version, this may differ as Oracle keeps updating Java). ; in the end enables assignment of multiple values to PATH variable.
  6. Click OK! Done

enter image description here

To be sure that everything works, open CMD Prompt and type: java -version to check for Java version and javac to be sure that compiler responds.

enter image description here

I hope this helps. Good luck!

What is initial scale, user-scalable, minimum-scale, maximum-scale attribute in meta tag?

user-scalable:

user-scalable=yes (default) to allow the user to zoom in or out on the web page;

user-scalable=no to prevent the user from zooming in or out.

You can get more detailed information by reading the following articles.

Demo Code (recommended)

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
    <meta charset="UTF-8">_x000D_
    <meta http-equiv="X-UA-Compatible" content="IE=edge">_x000D_
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=0.5, maximum-scale=3.0">_x000D_
</head>_x000D_
<body>_x000D_
    <header>_x000D_
    </header>_x000D_
    <main>_x000D_
        <section>_x000D_
            <h1>do not using <mark>user-scalable=no</mark></h1>_x000D_
        </section>_x000D_
    </main>_x000D_
    <footer>_x000D_
    </footer>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

What datatype to use when storing latitude and longitude data in SQL databases?

In vanilla Oracle, the feature called LOCATOR (a crippled version of Spatial) requires that the coordinate data be stored using the datatype of NUMBER (no precision). When you try to create Function Based Indexes to support spatial queries it'll gag otherwise.

To enable extensions, verify that they are enabled in those .ini files - Vagrant/Ubuntu/Magento 2.0.2

Updated....For ubuntu users

sudo apt-get install libapache2-mod-php php-common php-gd php-mysql php-curl php-intl php-xsl php-mbstring php-zip php-bcmath php-soap php-xdebug php-imagick

What does body-parser do with express?

To handle HTTP POST request in Express.js version 4 and above, you need to install middleware module called body-parser.

body-parser extract the entire body portion of an incoming request stream and exposes it on req.body.

The middleware was a part of Express.js earlier but now you have to install it separately.

This body-parser module parses the JSON, buffer, string and URL encoded data submitted using HTTP POST request. Install body-parser using NPM as shown below.

npm install body-parser --save

edit in 2019-april-2: in [email protected] the body-parser middleware bundled with express. for more details see this

Find largest and smallest number in an array

big=small=values[0]; //assigns element to be highest or lowest value

Should be AFTER fill loop

//counts to 20 and prompts user for value and stores it
for ( int i = 0; i < 20; i++ )
{
    cout << "Enter value " << i << ": ";
    cin >> values[i];
}
big=small=values[0]; //assigns element to be highest or lowest value

since when you declare array - it's unintialized (store some undefined values) and so, your big and small after assigning would store undefined values too.

And of course, you can use std::min_element, std::max_element, or std::minmax_element from C++11, instead of writing your loops.

Installing Python library from WHL file

From How do I install a Python package with a .whl file? [sic], How do I install a Python package USING a .whl file ?

For all Windows platforms:

1) Download the .WHL package install file.

2) Make Sure path [C:\Progra~1\Python27\Scripts] is in the system PATH string. This is for using both [pip.exe] and [easy-install.exe].

3) Make sure the latest version of pip.EXE is now installed. At this time of posting:

pip.EXE --version

  pip 9.0.1 from C:\PROGRA~1\Python27\lib\site-packages (python 2.7)

4) Run pip.EXE in an Admin command shell.

 - Open an Admin privileged command shell.

 > easy_install.EXE --upgrade  pip

 - Check the pip.EXE version:
 > pip.EXE --version

 pip 9.0.1 from C:\PROGRA~1\Python27\lib\site-packages (python 2.7)

 > pip.EXE install --use-wheel --no-index 
     --find-links="X:\path to wheel file\DownloadedWheelFile.whl"

Be sure to double-quote paths or path\filenames with embedded spaces in them ! Alternatively, use the MSW 'short' paths and filenames.

PostgreSQL error 'Could not connect to server: No such file or directory'

The Cause

Lion comes with a version of postgres already installed and uses those binaries by default. In general you can get around this by using the full path to the homebrew postgres binaries but there may be still issues with other programs.

The Solution

curl http://nextmarvel.net/blog/downloads/fixBrewLionPostgres.sh | sh

Via

http://nextmarvel.net/blog/2011/09/brew-install-postgresql-on-os-x-lion/

Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed

My error was solved after adding this dependency.

<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator -->
    <dependency>
        <groupId>org.hibernate.validator</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>6.0.16.Final</version>
    </dependency>

Java - Check if input is a positive integer, negative integer, natural number and so on.

(You should you as Else-If statement to check the for the three different state (positive, negative, 0)

Here is a simple example (excludes the possibility of non-integer values)

  import java.util.Scanner;

  public class Compare {

   public static void main(String[] args) { 

    Scanner input = new Scanner(System.in);

    System.out.print("Enter a number: ");
    int number = input.nextInt();

    if( number == 0)
    { System.out.println("Number is equal to zero"); }
    else if (number > 0)
    { System.out.println("Number is positive"); }
    else 
    { System.out.println("Number is negative"); }


  }
 }

What is this spring.jpa.open-in-view=true property in Spring Boot?

The OSIV Anti-Pattern

Instead of letting the business layer decide how it’s best to fetch all the associations that are needed by the View layer, OSIV (Open Session in View) forces the Persistence Context to stay open so that the View layer can trigger the Proxy initialization, as illustrated by the following diagram.

enter image description here

  • The OpenSessionInViewFilter calls the openSession method of the underlying SessionFactory and obtains a new Session.
  • The Session is bound to the TransactionSynchronizationManager.
  • The OpenSessionInViewFilter calls the doFilter of the javax.servlet.FilterChain object reference and the request is further processed
  • The DispatcherServlet is called, and it routes the HTTP request to the underlying PostController.
  • The PostController calls the PostService to get a list of Post entities.
  • The PostService opens a new transaction, and the HibernateTransactionManager reuses the same Session that was opened by the OpenSessionInViewFilter.
  • The PostDAO fetches the list of Post entities without initializing any lazy association.
  • The PostService commits the underlying transaction, but the Session is not closed because it was opened externally.
  • The DispatcherServlet starts rendering the UI, which, in turn, navigates the lazy associations and triggers their initialization.
  • The OpenSessionInViewFilter can close the Session, and the underlying database connection is released as well.

At first glance, this might not look like a terrible thing to do, but, once you view it from a database perspective, a series of flaws start to become more obvious.

The service layer opens and closes a database transaction, but afterward, there is no explicit transaction going on. For this reason, every additional statement issued from the UI rendering phase is executed in auto-commit mode. Auto-commit puts pressure on the database server because each transaction issues a commit at end, which can trigger a transaction log flush to disk. One optimization would be to mark the Connection as read-only which would allow the database server to avoid writing to the transaction log.

There is no separation of concerns anymore because statements are generated both by the service layer and by the UI rendering process. Writing integration tests that assert the number of statements being generated requires going through all layers (web, service, DAO) while having the application deployed on a web container. Even when using an in-memory database (e.g. HSQLDB) and a lightweight webserver (e.g. Jetty), these integration tests are going to be slower to execute than if layers were separated and the back-end integration tests used the database, while the front-end integration tests were mocking the service layer altogether.

The UI layer is limited to navigating associations which can, in turn, trigger N+1 query problems. Although Hibernate offers @BatchSize for fetching associations in batches, and FetchMode.SUBSELECT to cope with this scenario, the annotations are affecting the default fetch plan, so they get applied to every business use case. For this reason, a data access layer query is much more suitable because it can be tailored to the current use case data fetch requirements.

Last but not least, the database connection is held throughout the UI rendering phase which increases connection lease time and limits the overall transaction throughput due to congestion on the database connection pool. The more the connection is held, the more other concurrent requests are going to wait to get a connection from the pool.

Spring Boot and OSIV

Unfortunately, OSIV (Open Session in View) is enabled by default in Spring Boot, and OSIV is really a bad idea from a performance and scalability perspective.

So, make sure that in the application.properties configuration file, you have the following entry:

spring.jpa.open-in-view=false

This will disable OSIV so that you can handle the LazyInitializationException the right way.

Starting with version 2.0, Spring Boot issues a warning when OSIV is enabled by default, so you can discover this problem long before it affects a production system.

Error "initializer element is not constant" when trying to initialize variable with const

In C language, objects with static storage duration have to be initialized with constant expressions, or with aggregate initializers containing constant expressions.

A "large" object is never a constant expression in C, even if the object is declared as const.

Moreover, in C language, the term "constant" refers to literal constants (like 1, 'a', 0xFF and so on), enum members, and results of such operators as sizeof. Const-qualified objects (of any type) are not constants in C language terminology. They cannot be used in initializers of objects with static storage duration, regardless of their type.

For example, this is NOT a constant

const int N = 5; /* `N` is not a constant in C */

The above N would be a constant in C++, but it is not a constant in C. So, if you try doing

static int j = N; /* ERROR */

you will get the same error: an attempt to initialize a static object with a non-constant.

This is the reason why, in C language, we predominantly use #define to declare named constants, and also resort to #define to create named aggregate initializers.

Using the "animated circle" in an ImageView while loading stuff

This is generally referred to as an Indeterminate Progress Bar or Indeterminate Progress Dialog.

Combine this with a Thread and a Handler to get exactly what you want. There are a number of examples on how to do this via Google or right here on SO. I would highly recommend spending the time to learn how to use this combination of classes to perform a task like this. It is incredibly useful across many types of applications and will give you a great insight into how Threads and Handlers can work together.

I'll get you started on how this works:

The loading event starts the dialog:

//maybe in onCreate
showDialog(MY_LOADING_DIALOG);
fooThread = new FooThread(handler);
fooThread.start();

Now the thread does the work:

private class FooThread extends Thread {
    Handler mHandler;

    FooThread(Handler h) {
        mHandler = h;
    }

    public void run() { 
        //Do all my work here....you might need a loop for this

        Message msg = mHandler.obtainMessage();
        Bundle b = new Bundle();                
        b.putInt("state", 1);   
        msg.setData(b);
        mHandler.sendMessage(msg);
    }
}

Finally get the state back from the thread when it is complete:

final Handler handler = new Handler() {
    public void handleMessage(Message msg) {
        int state = msg.getData().getInt("state");
        if (state == 1){
            dismissDialog(MY_LOADING_DIALOG);
            removeDialog(MY_LOADING_DIALOG);
        }
    }
};

MySQL - SELECT WHERE field IN (subquery) - Extremely slow why?

sometimes when data grow bigger mysql WHERE IN's could be pretty slow because of query optimization. Try using STRAIGHT_JOIN to tell mysql to execute query as is, e.g.

SELECT STRAIGHT_JOIN table.field FROM table WHERE table.id IN (...)

but beware: in most cases mysql optimizer works pretty well, so I would recommend to use it only when you have this kind of problem

Check if a row exists using old mysql_* API

function checkLectureStatus($lectureName) {
  global $con;
  $lectureName = mysql_real_escape_string($lectureName);
  $sql = "SELECT 1 FROM preditors_assigned WHERE lecture_name='$lectureName'";
  $result = mysql_query($sql) or trigger_error(mysql_error()." ".$sql);
  if (mysql_fetch_row($result)) {
    return 'Assigned';
  }
  return 'Available';
}

however you have to use some abstraction library for the database access.
the code would become

function checkLectureStatus($lectureName) {
  $res = db::getOne("SELECT 1 FROM preditors_assigned WHERE lecture_name=?",$lectureName);
  if($res) {
    return 'Assigned';
  }
  return 'Available';
}

Calculate age given the birth date in the format YYYYMMDD

function getAge(dateString) {

    var dates = dateString.split("-");
    var d = new Date();

    var userday = dates[0];
    var usermonth = dates[1];
    var useryear = dates[2];

    var curday = d.getDate();
    var curmonth = d.getMonth()+1;
    var curyear = d.getFullYear();

    var age = curyear - useryear;

    if((curmonth < usermonth) || ( (curmonth == usermonth) && curday < userday   )){

        age--;

    }

    return age;
}

To get the age when european date has entered:

getAge('16-03-1989')

Difference between Divide and Conquer Algo and Dynamic Programming

I think of Divide & Conquer as an recursive approach and Dynamic Programming as table filling.

For example, Merge Sort is a Divide & Conquer algorithm, as in each step, you split the array into two halves, recursively call Merge Sort upon the two halves and then merge them.

Knapsack is a Dynamic Programming algorithm as you are filling a table representing optimal solutions to subproblems of the overall knapsack. Each entry in the table corresponds to the maximum value you can carry in a bag of weight w given items 1-j.

Go Back to Previous Page

You specifically asked for JS solutions, but in the event that someone visits your form with JS disabled a PHP backup is always nice:

when the form loads grab the previous page address via something like $previous = $_SERVER['HTTP_REFERER']; and then set that as a <input type="hidden" value="$previous" /> in your form. When you process your form with the script you can grab that value and stick it in the header("Location:___") or stick the address directly into a link to send them back where they came from

No JS, pretty simple, and you can structure it so that it's only handled if the client doesn't have JS enabled.

How to obtain Signing certificate fingerprint (SHA1) for OAuth 2.0 on Android?

If you are using Android Studio. You don't need to generate a SHA1 fingerprint using cmd prompt. You just need to create a project with default Maps Activity of Android Studio.In the project you can get the fingerprint in google_maps_api.xml under Values folder. Hope this will help you. :)

enter image description here

SQL Delete Records within a specific Range

You can use this way because id can not be sequential in all cases.

SELECT * 
FROM  `ht_news` 
LIMIT 0 , 30

How to check if any value is NaN in a Pandas DataFrame

df.isnull().sum()

This will give you count of all NaN values present in the respective coloums of the DataFrame.

Best approach to remove time part of datetime in SQL Server

Just in case anyone is looking in here for a Sybase version since several of the versions above didn't work

CAST(CONVERT(DATE,GETDATE(),103) AS DATETIME)
  • Tested in I SQL v11 running on Adaptive Server 15.7

Angular ng-repeat Error "Duplicates in a repeater are not allowed."

I was having an issue in my project where I was using ng-repeat track by $index but the products were not getting reflecting when data comes from database. My code is as below:

<div ng-repeat="product in productList.productList track by $index">
  <product info="product"></product>
 </div>

In the above code, product is a separate directive to display the product.But i came to know that $index causes issue when we pass data out from the scope. So the data losses and DOM can not be updated.

I found the solution by using product.id as a key in ng-repeat like below:

<div ng-repeat="product in productList.productList track by product.id">
  <product info="product"></product>
 </div>

But the above code again fails and throws the below error when more than one product comes with same id:

angular.js:11706 Error: [ngRepeat:dupes] Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater

So finally i solved the problem by making dynamic unique key of ng-repeat like below:

<div ng-repeat="product in productList.productList track by (product.id + $index)">
  <product info="product"></product>
 </div>

This solved my problem and hope this will help you in future.

Load image from resources

    this.toolStrip1 = new System.Windows.Forms.ToolStrip();
    this.toolStrip1.Location = new System.Drawing.Point(0, 0);
    this.toolStrip1.Name = "toolStrip1";
    this.toolStrip1.Size = new System.Drawing.Size(444, 25);
    this.toolStrip1.TabIndex = 0;
    this.toolStrip1.Text = "toolStrip1";
    object O = global::WindowsFormsApplication1.Properties.Resources.ResourceManager.GetObject("best_robust_ghost");

    ToolStripButton btn = new ToolStripButton("m1");
    btn.DisplayStyle = ToolStripItemDisplayStyle.Image;
    btn.Image = (Image)O;
    this.toolStrip1.Items.Add(btn);

    this.Controls.Add(this.toolStrip1);

Clean out Eclipse workspace metadata

The only way I know to deal with this is to create a new workspace, import projects from the polluted workspace, reconstructing all my settings (a major pain) and then delete the old workspace. Is there an easier way to deal with this?

For synchronizing or restoring all our settings we use Workspace Mechanic. Once all the settings are recorded its one click and all settings are restored... You can also setup a server which provides those settings for all users.

How can I see if a Perl hash already has a certain key?

You can just go with:

if(!$strings{$string}) ....

How to prevent scanf causing a buffer overflow in C?

Most of the time a combination of fgets and sscanf does the job. The other thing would be to write your own parser, if the input is well formatted. Also note your second example needs a bit of modification to be used safely:

#define LENGTH          42
#define str(x)          # x
#define xstr(x)         str(x)

/* ... */ 
int nc = scanf("%"xstr(LENGTH)"[^\n]%*[^\n]", array); 

The above discards the input stream upto but not including the newline (\n) character. You will need to add a getchar() to consume this. Also do check if you reached the end-of-stream:

if (!feof(stdin)) { ...

and that's about it.

jQuery counter to count up to a target number

I ended up creating my own plugin. Here it is in case this helps anyone:

(function($) {
    $.fn.countTo = function(options) {
        // merge the default plugin settings with the custom options
        options = $.extend({}, $.fn.countTo.defaults, options || {});
        
        // how many times to update the value, and how much to increment the value on each update
        var loops = Math.ceil(options.speed / options.refreshInterval),
            increment = (options.to - options.from) / loops;
        
        return $(this).each(function() {
            var _this = this,
                loopCount = 0,
                value = options.from,
                interval = setInterval(updateTimer, options.refreshInterval);
            
            function updateTimer() {
                value += increment;
                loopCount++;
                $(_this).html(value.toFixed(options.decimals));
                
                if (typeof(options.onUpdate) == 'function') {
                    options.onUpdate.call(_this, value);
                }
                
                if (loopCount >= loops) {
                    clearInterval(interval);
                    value = options.to;
                    
                    if (typeof(options.onComplete) == 'function') {
                        options.onComplete.call(_this, value);
                    }
                }
            }
        });
    };
    
    $.fn.countTo.defaults = {
        from: 0,  // the number the element should start at
        to: 100,  // the number the element should end at
        speed: 1000,  // how long it should take to count between the target numbers
        refreshInterval: 100,  // how often the element should be updated
        decimals: 0,  // the number of decimal places to show
        onUpdate: null,  // callback method for every time the element is updated,
        onComplete: null,  // callback method for when the element finishes updating
    };
})(jQuery);

Here's some sample code of how to use it:

<script type="text/javascript"><!--
    jQuery(function($) {
        $('.timer').countTo({
            from: 50,
            to: 2500,
            speed: 1000,
            refreshInterval: 50,
            onComplete: function(value) {
                console.debug(this);
            }
        });
    });
//--></script>

<span class="timer"></span>

View the demo on JSFiddle: http://jsfiddle.net/YWn9t/

How to enable C++11/C++0x support in Eclipse CDT?

Eclipse C/C++ does not recognize the symbol std::unique_ptr even though you have included the C++11 memory header in your file.

Assuming you are using the GNU C++ compiler, this is what I did to fix:

Project -> Properties -> C/C++ General -> Preprocessor Include Paths -> GNU C++ -> CDT User Setting Entries

  1. Click on the "Add..." button

  2. Select "Preprocessor Macro" from the dropdown menu

    Name: __cplusplus     Value:  201103L
    
  3. Hit Apply, and then OK to go back to your project

  4. Then rebuild you C++ index: Projects -> C/C++ Index -> Rebuild

Displaying splash screen for longer than default seconds

In Swift 4.2

For Delay 1 second after default launch time...

Thread.sleep(forTimeInterval: 1)

How can I find all *.js file in directory recursively in Linux?

If you just want the list, then you should ask here: http://unix.stackexchange.com

The answer is: cd / && find -name *.js

If you want to implement this, you have to specify the language.

Parsing JSON with Unix tools

There are a number of tools specifically designed for the purpose of manipulating JSON from the command line, and will be a lot easier and more reliable than doing it with Awk, such as jq:

curl -s 'https://api.github.com/users/lambda' | jq -r '.name'

You can also do this with tools that are likely already installed on your system, like Python using the json module, and so avoid any extra dependencies, while still having the benefit of a proper JSON parser. The following assume you want to use UTF-8, which the original JSON should be encoded in and is what most modern terminals use as well:

Python 3:

curl -s 'https://api.github.com/users/lambda' | \
    python3 -c "import sys, json; print(json.load(sys.stdin)['name'])"

Python 2:

export PYTHONIOENCODING=utf8
curl -s 'https://api.github.com/users/lambda' | \
    python2 -c "import sys, json; print json.load(sys.stdin)['name']"

Frequently Asked Questions

Why not a pure shell solution?

The standard POSIX/Single Unix Specification shell is a very limited language which doesn't contain facilities for representing sequences (list or arrays) or associative arrays (also known as hash tables, maps, dicts, or objects in some other languages). This makes representing the result of parsing JSON somewhat tricky in portable shell scripts. There are somewhat hacky ways to do it, but many of them can break if keys or values contain certain special characters.

Bash 4 and later, zsh, and ksh have support for arrays and associative arrays, but these shells are not universally available (macOS stopped updating Bash at Bash 3, due to a change from GPLv2 to GPLv3, while many Linux systems don't have zsh installed out of the box). It's possible that you could write a script that would work in either Bash 4 or zsh, one of which is available on most macOS, Linux, and BSD systems these days, but it would be tough to write a shebang line that worked for such a polyglot script.

Finally, writing a full fledged JSON parser in shell would be a significant enough enough dependency that you might as well just use an existing dependency like jq or Python instead. It's not going to be a one-liner, or even small five-line snippet, to do a good implementation.

Why not use awk, sed, or grep?

It is possible to use these tools to do some quick extraction from JSON with a known shape and formatted in a known way, such as one key per line. There are several examples of suggestions for this in other answers.

However, these tools are designed for line based or record based formats; they are not designed for recursive parsing of matched delimiters with possible escape characters.

So these quick and dirty solutions using awk/sed/grep are likely to be fragile, and break if some aspect of the input format changes, such as collapsing whitespace, or adding additional levels of nesting to the JSON objects, or an escaped quote within a string. A solution that is robust enough to handle all JSON input without breaking will also be fairly large and complex, and so not too much different than adding another dependency on jq or Python.

I have had to deal with large amounts of customer data being deleted due to poor input parsing in a shell script before, so I never recommend quick and dirty methods that may be fragile in this way. If you're doing some one-off processing, see the other answers for suggestions, but I still highly recommend just using an existing tested JSON parser.

Historical notes

This answer originally recommended jsawk, which should still work, but is a little more cumbersome to use than jq, and depends on a standalone JavaScript interpreter being installed which is less common than a Python interpreter, so the above answers are probably preferable:

curl -s 'https://api.github.com/users/lambda' | jsawk -a 'return this.name'

This answer also originally used the Twitter API from the question, but that API no longer works, making it hard to copy the examples to test out, and the new Twitter API requires API keys, so I've switched to using the GitHub API which can be used easily without API keys. The first answer for the original question would be:

curl 'http://twitter.com/users/username.json' | jq -r '.text'

How to add a button programmatically in VBA next to some sheet cell data?

Suppose your function enters data in columns A and B and you want to a custom Userform to appear if the user selects a cell in column C. One way to do this is to use the SelectionChange event:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim clickRng As Range
    Dim lastRow As Long

    lastRow = Range("A1").End(xlDown).Row
    Set clickRng = Range("C1:C" & lastRow) //Dynamically set cells that can be clicked based on data in column A

    If Not Intersect(Target, clickRng) Is Nothing Then
        MyUserForm.Show //Launch custom userform
    End If

End Sub

Note that the userform will appear when a user selects any cell in Column C and you might want to populate each cell in Column C with something like "select cell to launch form" to make it obvious that the user needs to perform an action (having a button naturally suggests that it should be clicked)

Fragment Inside Fragment

Curently in nested fragment, the nested one(s) are only supported if they are generated programmatically! So at this time no nested fragment layout are supported in xml layout scheme!

How to get value in the session in jQuery

Assuming you are using this plugin, you are misusing the .set method. .set must be passed the name of the key as a string as well as the value. I suppose you meant to write:

$.session.set("userName", $("#uname").val());

This sets the userName key in session storage to the value of the input, and allows you to retrieve it using:

$.session.get('userName');

Reading a text file using OpenFileDialog in windows forms

for this approach, you will need to add system.IO to your references by adding the next line of code below the other references near the top of the c# file(where the other using ****.** stand).

using System.IO;

this next code contains 2 methods of reading the text, the first will read single lines and stores them in a string variable, the second one reads the whole text and saves it in a string variable(including "\n" (enters))

both should be quite easy to understand and use.


    string pathToFile = "";//to save the location of the selected object
    private void openToolStripMenuItem_Click(object sender, EventArgs e)
    {
        OpenFileDialog theDialog = new OpenFileDialog();
        theDialog.Title = "Open Text File";
        theDialog.Filter = "TXT files|*.txt";
        theDialog.InitialDirectory = @"C:\";
        if (theDialog.ShowDialog() == DialogResult.OK)
        {
            MessageBox.Show(theDialog.FileName.ToString());
            pathToFile = theDialog.FileName;//doesn't need .tostring because .filename returns a string// saves the location of the selected object

        }

        if (File.Exists(pathToFile))// only executes if the file at pathtofile exists//you need to add the using System.IO reference at the top of te code to use this
        {
            //method1
            string firstLine = File.ReadAllLines(pathToFile).Skip(0).Take(1).First();//selects first line of the file
            string secondLine = File.ReadAllLines(pathToFile).Skip(1).Take(1).First();

            //method2
            string text = "";
            using(StreamReader sr =new StreamReader(pathToFile))
            {
                text = sr.ReadToEnd();//all text wil be saved in text enters are also saved
            }
        }
    }

To split the text you can use .Split(" ") and use a loop to put the name back into one string. if you don't want to use .Split() then you could also use foreach and ad an if statement to split it where needed.


to add the data to your class you can use the constructor to add the data like:

  public Employee(int EMPLOYEENUM, string NAME, string ADRESS, double WAGE, double HOURS)
        {
            EmployeeNum = EMPLOYEENUM;
            Name = NAME;
            Address = ADRESS;
            Wage = WAGE;
            Hours = HOURS;
        }

or you can add it using the set by typing .variablename after the name of the instance(if they are public and have a set this will work). to read the data you can use the get by typing .variablename after the name of the instance(if they are public and have a get this will work).

Java String.split() Regex

str.split (" ") 
res27: Array[java.lang.String] = Array(a, +, b, -, c, *, d, /, e, <, f, >, g, >=, h, <=, i, ==, j)

Apache could not be started - ServerRoot must be a valid directory and Unable to find the specified module

If you use an actuall version there is a "setup_xampp.bat/.sh" script in the root directory. The path has to be absolute but the script changes all needed paths to your current location.

Responsive timeline UI with Bootstrap3

"Timeline (responsive)" snippet:

This looks very, very close to what your example shows. The bootstrap snippet linked below covers all the bases you are looking for. I've been considering it myself, with the same requirements you have ( especially responsiveness ). This morphs well between screen sizes and devices.

You can fork this and use it as a great starting point for your specific expectations:


Here are two screenshots I took for you... wide and thin:

wide thin

Send email using java

The following code works very well.Try this as a java application with javamail-1.4.5.jar

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

public class MailSender
{
    final String senderEmailID = "[email protected]";
    final String senderPassword = "typesenderpassword";
    final String emailSMTPserver = "smtp.gmail.com";
    final String emailServerPort = "465";
    String receiverEmailID = null;
    static String emailSubject = "Test Mail";
    static String emailBody = ":)";

    public MailSender(
            String receiverEmailID,
            String emailSubject,
            String emailBody
    ) {
        this.receiverEmailID=receiverEmailID;
        this.emailSubject=emailSubject;
        this.emailBody=emailBody;
        Properties props = new Properties();
        props.put("mail.smtp.user",senderEmailID);
        props.put("mail.smtp.host", emailSMTPserver);
        props.put("mail.smtp.port", emailServerPort);
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.socketFactory.port", emailServerPort);
        props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");
        SecurityManager security = System.getSecurityManager();
        try {
            Authenticator auth = new SMTPAuthenticator();
            Session session = Session.getInstance(props, auth);
            MimeMessage msg = new MimeMessage(session);
            msg.setText(emailBody);
            msg.setSubject(emailSubject);
            msg.setFrom(new InternetAddress(senderEmailID));
            msg.addRecipient(Message.RecipientType.TO,
                    new InternetAddress(receiverEmailID));
            Transport.send(msg);
            System.out.println("Message send Successfully:)");
        }
        catch (Exception mex)
        {
            mex.printStackTrace();
        }
    }

    public class SMTPAuthenticator extends javax.mail.Authenticator
    {
        public PasswordAuthentication getPasswordAuthentication()
        {
            return new PasswordAuthentication(senderEmailID, senderPassword);
        }
    }

    public static void main(String[] args)
    {
        MailSender mailSender=new
            MailSender("[email protected]",emailSubject,emailBody);
    }
}

Showing/Hiding Table Rows with Javascript - can do with ID - how to do with Class?

You can change the class of the entire table and use the cascade in the CSS: http://jsbin.com/oyunuy/1/

Safely remove migration In Laravel

I accidentally created a migration with a bad name (command: php artisan migrate:make). I did not run (php artisan migrate) the migration, so I decided to remove it. My steps:

  1. Manually delete the migration file under app/database/migrations/my_migration_file_name.php
  2. Reset the composer autoload files: composer dump-autoload
  3. Relax

If you did run the migration (php artisan migrate), you may do this:

a) Run migrate:rollback - it is the right way to undo the last migration (Thnx @Jakobud)

b) If migrate:rollback does not work, do it manually (I remember bugs with migrate:rollback in previous versions):

  1. Manually delete the migration file under app/database/migrations/my_migration_file_name.php
  2. Reset the composer autoload files: composer dump-autoload
  3. Modify your database: Remove the last entry from the migrations table

Instagram: Share photo from webpage

Uploading on Instagram is possible. Their API provides a media upload endpoint, even if it's not documented.

POST https://instagram.com/api/v1/media/upload/

Check this code for example https://code.google.com/p/twitubas/source/browse/common/instagram.php

Replace Div Content onclick

Working from your jsFiddle example:

The jsFiddle was fine, but you were missing semi-colons at the end of the event.preventDefault() statements.

This works: Revised jsFiddle

jQuery(document).ready(function() {
    jQuery(".rec1").click(function(event) {
        event.preventDefault();
        jQuery('#rec-box').html(jQuery(this).next().html()); 
    });
    jQuery(".rec2").click(function(event) {
        event.preventDefault();
        jQuery('#rec-box2').html(jQuery(this).next().html()); 
    });
});

iPhone App Development on Ubuntu

I found one interesting site which seems pretty detailed on how you could setup a ubuntu for iPhone development. But it's a little old from November 2008 for the SDK 2.0.

Ubuntu 8.10 for iPhone open toolchain SDK2.0

The instructions also include something about the Android SDK/Emulator which you can leave out.

How to run docker-compose up -d at system start up?

As an addition to user39544's answer, one more type of syntax for crontab -e:

@reboot sleep 60 && /usr/local/bin/docker-compose -f /path_to_your_project/docker-compose.yml up -d

VBA Excel - Insert row below with same format including borders and frames

When inserting a row, regardless of the CopyOrigin, Excel will only put vertical borders on the inserted cells if the borders above and below the insert position are the same.

I'm running into a similar (but rotated) situation with inserting columns, but Copy/Paste is too slow for my workbook (tens of thousands of rows, many columns, and complex formatting).

I've found three workarounds that don't require copying the formatting from the source row:

  1. Ensure the vertical borders are the same weight, color, and pattern above and below the insert position so Excel will replicate them in your new row. (This is the "It hurts when I do this," "Stop doing that!" answer.)

  2. Use conditional formatting to establish the border (with a Formula of "=TRUE"). The conditional formatting will be copied to the new row, so you still end up with a border.Caveats:

    • Conditional formatting borders are limited to the thin-weight lines.
    • Works best for sheets where borders are relatively consistent so you don't have to create a bunch of conditional formatting rules.
  3. Set the border on the inserted row in VBA after inserting the row. Setting a border on a range is much faster than copying and pasting all of the formatting just to get a border (assuming you know ahead of time what the border should be or can sample it from the row above without losing performance).

How to get a value inside an ArrayList java

You haven't shown your Car type, but assuming you'd want the price of the first car, you could use:

public static void processCars(ArrayList<Car> cars) {
    Car car = cars.get(0);
    System.out.println(car.getPrice());
}

Note that I've changed the name of the list from car to cars - this is a list of cars, not a single car. (I've changed the method name in a similar way.)

If you only want the method to process a single car, you should change the parameter to be of type Car:

public static void processCar(Car car)

and then call it like this:

// In the main method
processCar(cars.get(0));

If you do leave it as processing the whole list, it would be worth generalizing the parameter to List<Car> - it's unlikely that you'll really require that it's an ArrayList<Car>.

Android Studio build fails with "Task '' not found in root project 'MyProject'."

  1. Open Command Prompt
  2. then go your project folder thru Command prompt
  3. Type gradlew build and run

How do I create directory if it doesn't exist to create a file?

var filePath = context.Server.MapPath(Convert.ToString(ConfigurationManager.AppSettings["ErrorLogFile"]));

var file = new FileInfo(filePath);

file.Directory.Create(); If the directory already exists, this method does nothing.

var sw = new StreamWriter(filePath, true);

sw.WriteLine(Enter your message here);

sw.Close();

How do I create a file and write to it?

If you for some reason want to separate the act of creating and writing, the Java equivalent of touch is

try {
   //create a file named "testfile.txt" in the current working directory
   File myFile = new File("testfile.txt");
   if ( myFile.createNewFile() ) {
      System.out.println("Success!");
   } else {
      System.out.println("Failure!");
   }
} catch ( IOException ioe ) { ioe.printStackTrace(); }

createNewFile() does an existence check and file create atomically. This can be useful if you want to ensure you were the creator of the file before writing to it, for example.

How can I build a recursive function in python?

Let's say you want to build: u(n+1)=f(u(n)) with u(0)=u0

One solution is to define a simple recursive function:

u0 = ...

def f(x):
  ...

def u(n):
  if n==0: return u0
  return f(u(n-1))

Unfortunately, if you want to calculate high values of u, you will run into a stack overflow error.

Another solution is a simple loop:

def u(n):
  ux = u0
  for i in xrange(n):
    ux=f(ux)
  return ux

But if you want multiple values of u for different values of n, this is suboptimal. You could cache all values in an array, but you may run into an out of memory error. You may want to use generators instead:

def u(n):
  ux = u0
  for i in xrange(n):
    ux=f(ux)
  yield ux

for val in u(1000):
  print val

There are many other options, but I guess these are the main ones.

How to prevent browser to invoke basic auth popup and handle 401 error using Jquery?

If WWW-Authenticate header is removed, then you wont get the caching of credentials and wont get back the Authorization header in request. That means now you will have to enter the credentials for every new request you generate.

How can I get around MySQL Errcode 13 with SELECT INTO OUTFILE?

MySQL is getting stupid here. It tries to create files under /tmp/data/.... So what you can do is the following:

mkdir /tmp/data
mount --bind /data /tmp/data

Then try your query. This worked for me after hours of debugging the issue.

android pinch zoom

There is also this project that does the job and worked perfectly for me: https://github.com/chrisbanes/PhotoView

Get Insert Statement for existing row in MySQL

Since you copied the table with the SQL produced by SHOW CREATE TABLE MyTable, you could just do the following to load the data into the new table.

INSERT INTO dest_db.dest_table SELECT * FROM source_db.source_table;

If you really want the INSERT statements, then the only way that I know of is to use mysqldump http://dev.mysql.com/doc/refman/5.1/en/mysqldump.htm. You can give it options to just dump data for a specific table and even limit rows.

How to change button background image on mouseOver?

I made a quick project in visual studio 2008 for a .net 3.5 C# windows form application and was able to create the following code. I found events for both the enter and leave methods.

In the InitializeComponent() function. I added the event handler using the Visual Studio designer.

this.button1.MouseLeave += new System.EventHandler( this.button1_MouseLeave );
this.button1.MouseEnter += new System.EventHandler( this.button1_MouseEnter );

In the button event handler methods set the background images.

/// <summary>
/// Handles the MouseEnter event of the button1 control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void button1_MouseEnter( object sender, EventArgs e )
{
      this.button1.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.img2));
}

/// <summary>
/// Handles the MouseLeave event of the button1 control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void button1_MouseLeave( object sender, EventArgs e )
{
       this.button1.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.img1));
}

Freeze the top row for an html table only (Fixed Table Header Scrolling)

Using css zebra styling

Copy paste this example and see the header fixed.

       <style>
       .zebra tr:nth-child(odd){
       background:white;
       color:black;
       }

       .zebra tr:nth-child(even){
       background: grey;
       color:black;
       }

      .zebra tr:nth-child(1) {
       background:black;
       color:yellow;
       position: fixed;
       margin:-30px 0px 0px 0px;
       }
       </style>


   <DIV  id= "stripped_div"

         class= "zebra"
         style = "
            border:solid 1px red;
            height:15px;
            width:200px;
            overflow-x:none;
            overflow-y:scroll;
            padding:30px 0px 0px 0px;"
            >

                <table>
                   <tr >
                       <td>Name:</td>
                       <td>Age:</td>
                   </tr>
                    <tr >
                       <td>Peter</td>
                       <td>10</td>
                   </tr>
                </table>

    </DIV>

Notice the top padding of of 30px in the div leaves space that is utilized by the 1st row of stripped data ie tr:nth-child(1) that is "fixed position" and formatted to a margin of -30px

Sound alarm when code finishes

This one seems to work on both Windows and Linux* (from this question):

def beep():
    print("\a")

beep()

In Windows, can put at the end:

import winsound
winsound.Beep(500, 1000)

where 500 is the frequency in Herz
      1000 is the duration in miliseconds

To work on Linux, you may need to do the following (from QO's comment):

  • in a terminal, type 'cd /etc/modprobe.d' then 'gksudo gedit blacklist.conf'
  • comment the line that says 'blacklist pcspkr', then reboot
  • check also that the terminal preferences has the 'Terminal Bell' checked.

Markdown `native` text alignment

I found pretty useful to use latex syntax on jupyter notebooks cells, like:

![good-boy](https://i.imgur.com/xtoLyW2.jpg  "Good boy on boat")

$$\text{This is some centered text}$$

Maven: How to run a .java file from command line passing arguments

You could run: mvn exec:exec -Dexec.args="arg1".

This will pass the argument arg1 to your program.

You should specify the main class fully qualified, for example, a Main.java that is in a package test would need

mvn exec:java  -Dexec.mainClass=test.Main

By using the -f parameter, as decribed here, you can also run it from other directories.

mvn exec:java -Dexec.mainClass=test.Main -f folder/pom.xm

For multiple arguments, simply separate them with a space as you would at the command line.

mvn exec:java -Dexec.mainClass=test.Main -Dexec.args="arg1 arg2 arg3"

For arguments separated with a space, you can group using 'argument separated with space' inside the quotation marks.

mvn exec:java -Dexec.mainClass=test.Main -Dexec.args="'argument separated with space' 'another one'"

Inline list initialization in VB.NET

Use this syntax for VB.NET 2005/2008 compatibility:

Dim theVar As New List(Of String)(New String() {"one", "two", "three"})

Although the VB.NET 2010 syntax is prettier.

Authenticating in PHP using LDAP through Active Directory

PHP has libraries: http://ca.php.net/ldap

PEAR also has a number of packages: http://pear.php.net/search.php?q=ldap&in=packages&x=0&y=0

I haven't used either, but I was going to at one point and they seemed like they should work.

Android: Vertical alignment for multi line EditText (Text area)

Use this:

android:gravity="top"

or

android:gravity="top|left"

how to make log4j to write to the console as well

Your root logger definition is a bit confused. See the log4j documentation.

This is a standard Java properties file, which means that lines are treated as key=value pairs. Your second log4j.rootLogger line is overwriting the first, which explains why you aren't seeing anything on the console appender.

You need to merge your two rootLogger definitions into one. It looks like you're trying to have DEBUG messages go to the console and INFO messages to the file. The root logger can only have one level, so you need to change your configuration so that the appenders have appropriate levels.

While I haven't verified that this is correct, I'd guess it'll look something like this:

log4j.rootLogger=DEBUG,console,file
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.file=org.apache.log4j.RollingFileAppender

Note that you also have an error in casing - you have console lowercase in one place and in CAPS in another.

JFrame in full screen Java

Just use this code :

import java.awt.event.*;
import javax.swing.*;

public class FullscreenJFrame extends JFrame {
    private JPanel contentPane = new JPanel();
    private JButton fullscreenButton = new JButton("Fullscreen Mode");
    private boolean Am_I_In_FullScreen = false;
    private int PrevX, PrevY, PrevWidth, PrevHeight;

    public static void main(String[] args) {
        FullscreenJFrame frame = new FullscreenJFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(600, 500);
        frame.setVisible(true);
    }

    public FullscreenJFrame() {
        super("My FullscreenJFrame");

        setContentPane(contentPane);

        // From Here starts the trick
        FullScreenEffect effect = new FullScreenEffect();

        fullscreenButton.addActionListener(effect);

        contentPane.add(fullscreenButton);
        fullscreenButton.setVisible(true);
    }

    private class FullScreenEffect implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            if (Am_I_In_FullScreen == false) {
                PrevX = getX();
                PrevY = getY();
                PrevWidth = getWidth();
                PrevHeight = getHeight();

                // Destroys the whole JFrame but keeps organized every Component
                // Needed if you want to use Undecorated JFrame dispose() is the
                // reason that this trick doesn't work with videos.
                dispose();
                setUndecorated(true);

                setBounds(0, 0, getToolkit().getScreenSize().width,
                        getToolkit().getScreenSize().height);
                setVisible(true);
                Am_I_In_FullScreen = true;
            } else {
                setVisible(true);
                setBounds(PrevX, PrevY, PrevWidth, PrevHeight);
                dispose();
                setUndecorated(false);
                setVisible(true);
                Am_I_In_FullScreen = false;
            }
        }
    }
}

I hope this helps.

How to get a ListBox ItemTemplate to stretch horizontally the full width of the ListBox?

I found another solution here, since I ran into both post...

This is from the Myles answer:

<ListBox.ItemContainerStyle> 
    <Style TargetType="ListBoxItem"> 
        <Setter Property="HorizontalContentAlignment" Value="Stretch"></Setter> 
    </Style> 
</ListBox.ItemContainerStyle> 

This worked for me.

Adding to an ArrayList Java

If you're using Java 9, there's an easy way with less number of lines without needing to initialize or add method.

List<String> list = List.of("first", "second", "third");

RegisterStartupScript from code behind not working when Update Panel is used

You need to use ScriptManager.RegisterStartupScript for Ajax.

protected void ButtonPP_Click(object sender, EventArgs e) {     if (radioBtnACO.SelectedIndex < 0)     {         string csname1 = "PopupScript";          var cstext1 = new StringBuilder();         cstext1.Append("alert('Please Select Criteria!')");          ScriptManager.RegisterStartupScript(this, GetType(), csname1,             cstext1.ToString(), true);     } } 

Placeholder in UITextView

I was able to do add a "place holder" to a UITextView with ALOT less code. This is what I did:

UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(60, 800, 200, 60)];
textView.text = @"Write characters here...";
textView.textColor=[UIColor grayColor];
textView.font = [UIFont fontWithName:@"Hevlatica" size:15];
textView.delegate=self;

I guess it's not an actual placeholder because you have to delete the text before you write but it could help if you wanted something a bit more simple.

.NET / C# - Convert char[] to string

String mystring = new String(mychararray);

Android, How to create option Menu

please see :==

private int group1Id = 1;

int homeId = Menu.FIRST;
int profileId = Menu.FIRST +1;
int searchId = Menu.FIRST +2;
int dealsId = Menu.FIRST +3;
int helpId = Menu.FIRST +4;
int contactusId = Menu.FIRST +5;

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    menu.add(group1Id, homeId, homeId, "").setIcon(R.drawable.home_menu);
    menu.add(group1Id, profileId, profileId, "").setIcon(R.drawable.profile_menu);
    menu.add(group1Id, searchId, searchId, "").setIcon(R.drawable.search_menu);
    menu.add(group1Id, dealsId, dealsId, "").setIcon(R.drawable.deals_menu);
    menu.add(group1Id, helpId, helpId, "").setIcon(R.drawable.help_menu);
    menu.add(group1Id, contactusId, contactusId, "").setIcon(R.drawable.contactus_menu);

    return super.onCreateOptionsMenu(menu); 
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case 1:
        // write your code here
        Toast msg = Toast.makeText(MainHomeScreen.this, "Menu 1", Toast.LENGTH_LONG);
        msg.show();
        return true;

    case 2:
        // write your code here
        return true;

    case 3:
        // write your code here
        return true;

    case 4:
        // write your code here
        return true;

    case 5:
        // write your code here
        return true;

    case 6:
        // write your code here
        return true;

    default:
        return super.onOptionsItemSelected(item);
    }
}

Android Studio: Application Installation Failed

I was having the same error, but i fixed it after reinstalling the HAXM. This problem is caused because of the virtual device not starting properly. If your device keep showing on screen "Android" or the screen is black, it have not started yet, you have to wait more for it to start properly, then it shall run. If it is too slow, maybe you should find a way to accelerate the Android Virtual Device (AVD). The Intel computers have the HAXM (hardware-accelerated-execution-manager).

In my computer was not starting because of the HAXM not working, I fixed it by reinstalling the HAXM, downloading it from the intel website: "https://software.intel.com/en-us/android/articles/intel-hardware-accelerated-execution-manager"

Then i set the HAXM max memory to 1536MB in the installation, for not having the problem of this other post, that you maybe have and i was having too: "HAXM configuration in android studio"

After all done, it worked fine.

Which one is the best PDF-API for PHP?

http://sourceforge.net/projects/html2ps/, is the best if you need the css and 3c compatibily.

if you can install software on your server, i suggest you to use http://wkhtmltopdf.org/.

There is also a drupal module using wkhtmltopdf :)

PHP take many resources to convert html in pdf, imho, php is not the right language to do that (if you expect a large numbers of coversion or large files to convert)

Combining multiple condition in single case statement in Sql Server

select ROUND(CASE 

WHEN  CONVERT( float, REPLACE( isnull( value1,''),',',''))='' AND CONVERT( float, REPLACE( isnull( value2,''),',',''))='' then  CONVERT( float, REPLACE( isnull( value3,''),',',''))

WHEN  CONVERT( float, REPLACE( isnull( value1,''),',',''))='' AND CONVERT( float, REPLACE( isnull( value2,''),',',''))!='' then  CONVERT( float, REPLACE( isnull( value3,''),',',''))

WHEN  CONVERT( float, REPLACE( isnull( value1,''),',',''))!='' AND CONVERT( float, REPLACE( isnull( value2,''),',',''))='' then  CONVERT( float, REPLACE( isnull( value3,''),',',''))

else CONVERT( float, REPLACE(isnull( value1,''),',','')) end,0)  from Tablename where    ID="123" 

How to convert a HTMLElement to a string

The most easy way to do is copy innerHTML of that element to tmp variable and make it empty, then append new element, and after that copy back tmp variable to it. Here is an example I used to add jquery script to top of head.

var imported = document.createElement('script');
imported.src = 'http://code.jquery.com/jquery-1.7.1.js';
var tmpHead = document.head.innerHTML;
document.head.innerHTML = "";
document.head.append(imported);
document.head.innerHTML += tmpHead;

That simple :)

How can I sanitize user input with PHP?

Do not try to prevent SQL injection by sanitizing input data.

Instead, do not allow data to be used in creating your SQL code. Use Prepared Statements (i.e. using parameters in a template query) that uses bound variables. It is the only way to be guaranteed against SQL injection.

Please see my website http://bobby-tables.com/ for more about preventing SQL injection.

How to fix Terminal not loading ~/.bashrc on OS X Lion

Renaming .bashrc to .profile (or soft-linking the latter to the former) should also do the trick. See here.

Using ls to list directories and their total sizes

du -sm * | sort -nr

Output by size

C#: New line and tab characters in strings

sb.Append(Environment.Newline);
sb.Append("\t");

login to remote using "mstsc /admin" with password

Save your username, password and sever name in an RDP file and run the RDP file from your script

ORA-12154 could not resolve the connect identifier specified

Use this link.on Microsoft Support

I gave permission to IUSR_MachineName user on oracle home folder and I was able to resolve the problem

How can I create an object based on an interface file definition in TypeScript?

You can set default values using Class.

Without Class Constructor:

interface IModal {
  content: string;
  form: string;
  href: string;
  isPopup: boolean;
};

class Modal implements IModal {
  content = "";
  form = "";
  href: string;  // will not be added to object
  isPopup = true;
}

const myModal = new Modal();
console.log(myModal); // output: {content: "", form: "", isPopup: true}

With Class Constructor

interface IModal {
  content: string;
  form: string;
  href: string;
  isPopup: boolean;
}

class Modal implements IModal {
  constructor() {
    this.content = "";
    this.form = "";
    this.isPopup = true;
  }

  content: string;

  form: string;

  href: string; // not part of constructor so will not be added to object

  isPopup: boolean;
}

const myModal = new Modal();
console.log(myModal); // output: {content: "", form: "", isPopup: true}

Magento Product Attribute Get Value

If you have an text/textarea attribute named my_attr you can get it by: product->getMyAttr();

Loop until a specific user input

Your code won't work because you haven't assigned anything to n before you first use it. Try this:

def oracle():
    n = None
    while n != 'Correct':
        # etc...

A more readable approach is to move the test until later and use a break:

def oracle():
    guess = 50

    while True:
        print 'Current number = {0}'.format(guess)
        n = raw_input("lower, higher or stop?: ")
        if n == 'stop':
            break
        # etc...

Also input in Python 2.x reads a line of input and then evaluates it. You want to use raw_input.

Note: In Python 3.x, raw_input has been renamed to input and the old input method no longer exists.

Loop through JSON in EJS

JSON.stringify returns a String. So, for example:

var data = [
    { id: 1, name: "bob" },
    { id: 2, name: "john" },
    { id: 3, name: "jake" },
];

JSON.stringify(data)

will return the equivalent of:

"[{\"id\":1,\"name\":\"bob\"},{\"id\":2,\"name\":\"john\"},{\"id\":3,\"name\":\"jake\"}]"

as a String value.

So when you have

<% for(var i=0; i<JSON.stringify(data).length; i++) {%>

what that ends up looking like is:

<% for(var i=0; i<"[{\"id\":1,\"name\":\"bob\"},{\"id\":2,\"name\":\"john\"},{\"id\":3,\"name\":\"jake\"}]".length; i++) {%>

which is probably not what you want. What you probably do want is something like this:

<table>
<% for(var i=0; i < data.length; i++) { %>
   <tr>
     <td><%= data[i].id %></td>
     <td><%= data[i].name %></td>
   </tr>
<% } %>
</table>

This will output the following table (using the example data from above):

<table>
  <tr>
    <td>1</td>
    <td>bob</td>
  </tr>
  <tr>
    <td>2</td>
    <td>john</td>
  </tr>
  <tr>
    <td>3</td>
    <td>jake</td>
  </tr>
</table>

jQuery Get Selected Option From Dropdown

$('nameofDropDownList').prop('selectedIndex', whateverNumberasInt);

Imagine the DDL as an array with indexes, you are selecting one index. Choose the one which you want to set it to with your JS.

Difference between web reference and service reference?

The service reference is the newer interface for adding references to all manner of WCF services (they may not be web services) whereas Web reference is specifically concerned with ASMX web references.

You can access web references via the advanced options in add service reference (if I recall correctly).

I'd use service reference because as I understand it, it's the newer mechanism of the two.

Filtering array of objects with lodash based on property value

lodash also has a remove method

var myArr = [
    { name: "john", age: 23 },
    { name: "john", age: 43 },
    { name: "jim", age: 101 },
    { name: "bob", age: 67 }
];

var onlyJohn = myArr.remove( person => { return person.name == "john" })

stale element reference: element is not attached to the page document

try {
    WebElement button = driver.findElement(By.xpath("xpath"));
            button.click();
}
catch(org.openqa.selenium.StaleElementReferenceException ex)
{
    WebElement button = driver.findElement(By.xpath("xpath"));
            button.click();
}

This try/catch code actually worked for me. I got the same stale element error.

Delete all files in directory (but not directory) - one liner solution

For deleting all files from directory say "C:\Example"

File file = new File("C:\\Example");      
String[] myFiles;    
if (file.isDirectory()) {
    myFiles = file.list();
    for (int i = 0; i < myFiles.length; i++) {
        File myFile = new File(file, myFiles[i]); 
        myFile.delete();
    }
}

Is there a way to catch the back button event in javascript?

onLocationChange may also be useful. Not sure if this is a Mozilla-only thing though, appears that it might be.

Failed to build gem native extension (installing Compass)

On yosemite, all you must do is install the command line tools. then it works.

Even if other gems installed fine. You must run xcode-select --install for gem install compass to work.

Good luck.

Automate scp file transfer using a shell script

What about wildcards or multiple files?

scp file1 file2 more-files* user@remote:/some/dir/

How to use router.navigateByUrl and router.navigate in Angular

navigateByUrl

routerLink directive as used like this:

<a [routerLink]="/inbox/33/messages/44">Open Message 44</a>

is just a wrapper around imperative navigation using router and its navigateByUrl method:

router.navigateByUrl('/inbox/33/messages/44')

as can be seen from the sources:

export class RouterLink {
  ...

  @HostListener('click')
  onClick(): boolean {
    ...
    this.router.navigateByUrl(this.urlTree, extras);
    return true;
  }

So wherever you need to navigate a user to another route, just inject the router and use navigateByUrl method:

class MyComponent {
   constructor(router: Router) {
      this.router.navigateByUrl(...);
   }
}

navigate

There's another method on the router that you can use - navigate:

router.navigate(['/inbox/33/messages/44'])

difference between the two

Using router.navigateByUrl is similar to changing the location bar directly–we are providing the “whole” new URL. Whereas router.navigate creates a new URL by applying an array of passed-in commands, a patch, to the current URL.

To see the difference clearly, imagine that the current URL is '/inbox/11/messages/22(popup:compose)'.

With this URL, calling router.navigateByUrl('/inbox/33/messages/44') will result in '/inbox/33/messages/44'. But calling it with router.navigate(['/inbox/33/messages/44']) will result in '/inbox/33/messages/44(popup:compose)'.

Read more in the official docs.

How do I get indices of N maximum values in a NumPy array?

Here's a more complicated way that increases n if the nth value has ties:

>>>> def get_top_n_plus_ties(arr,n):
>>>>     sorted_args = np.argsort(-arr)
>>>>     thresh = arr[sorted_args[n]]
>>>>     n_ = np.sum(arr >= thresh)
>>>>     return sorted_args[:n_]
>>>> get_top_n_plus_ties(np.array([2,9,8,3,0,2,8,3,1,9,5]),3)
array([1, 9, 2, 6])

submit the form using ajax

Nobody has actually given a pure javascript answer (as requested by OP), so here it is:

function postAsync(url2get, sendstr)    {
    var req;
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
        } else if (window.ActiveXObject) {
        req = new ActiveXObject("Microsoft.XMLHTTP");
        }
    if (req != undefined) {
        // req.overrideMimeType("application/json"); // if request result is JSON
        try {
            req.open("POST", url2get, false); // 3rd param is whether "async"
            }
        catch(err) {
            alert("couldnt complete request. Is JS enabled for that domain?\\n\\n" + err.message);
            return false;
            }
        req.send(sendstr); // param string only used for POST

        if (req.readyState == 4) { // only if req is "loaded"
            if (req.status == 200)  // only if "OK"
                { return req.responseText ; }
            else    { return "XHR error: " + req.status +" "+req.statusText; }
            }
        }
    alert("req for getAsync is undefined");
}

var var_str = "var1=" + var1  + "&var2=" + var2;
var ret = postAsync(url, var_str) ;
    // hint: encodeURIComponent()

if (ret.match(/^XHR error/)) {
    console.log(ret);
    return;
    }

In your case:

var var_str = "video_time=" + document.getElementById('video_time').value 
     + "&video_id=" + document.getElementById('video_id').value;

SQL Server function to return minimum date (January 1, 1753)

As I can not comment on the accepted answer due to insufficeint reputation points my comment comes as a reply.

using the select cast('1753-1-1' as datetime) is due to fail if run on a database with regional settings not accepting a datestring of YYYY-MM-DD format.

Instead use the select cast(-53690 as datetime) or a Convert with specified datetime format.

"Multiple definition", "first defined here" errors

The problem here is that you are including commands.c in commands.h before the function prototype. Therefore, the C pre-processor inserts the content of commands.c into commands.h before the function prototype. commands.c contains the function definition. As a result, the function definition ends up before than the function declaration causing the error.

The content of commands.h after the pre-processor phase looks like this:

#ifndef COMMANDS_H_
#define COMMANDS_H_

// function definition
void f123(){

}

// function declaration
void f123();

#endif /* COMMANDS_H_ */

This is an error because you can't declare a function after its definition in C. If you swapped #include "commands.c" and the function declaration the error shouldn't happen because, now, the function prototype comes before the function declaration.

However, including a .c file is a bad practice and should be avoided. A better solution for this problem would be to include commands.h in commands.c and link the compiled version of command to the main file. For example:

commands.h

#ifndef COMMANDS_H_
#define COMMANDS_H_

void f123(); // function declaration

#endif

commands.c

#include "commands.h"

void f123(){} // function definition

Same Navigation Drawer in different Activities

So this answer is a few years late but someone may appreciate it. Android has given us a new widget that makes using one navigation drawer with several activities easier.

android.support.design.widget.NavigationView is modular and has its own layout in the menu folder. The way that you use it is to wrap xml layouts the following way:

  1. Root Layout is a android.support.v4.widget.DrawerLayout that contains two children: an <include ... /> for the layout that is being wrapped (see 2) and a android.support.design.widget.NavigationView.

    <android.support.v4.widget.DrawerLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        tools:openDrawer="start">
    
    <include
        layout="@layout/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    
    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/activity_main_drawer" />
    

nav_header_main is just a LinearLayout with orientation = vertical for the header of your Navigation Drawar.

activity_main_drawer is a menu xml in your res/menu directory. It can contain items and groups of your choice. If you use the AndroidStudio Gallery the wizard will make a basic one for you and you can see what your options are.

  1. App bar layout is usually now a android.support.design.widget.CoordinatorLayout and this will include two children: a android.support.design.widget.AppBarLayout (which contains a android.support.v7.widget.Toolbar) and an <include ... > for your actual content (see 3).

    <android.support.design.widget.CoordinatorLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="yourpackage.MainActivity">
    
     <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">
    
        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />
    
    </android.support.design.widget.AppBarLayout>
    
    <include layout="@layout/content_main" />
    

  2. Content layout can be whatever layout you want. This is the layout that contains the main content of the activity (not including the navigation drawer or app bar).

Now, the cool thing about all of this is that you can wrap each activity in these two layouts but have your NavigationView (see step 1) always point to activity_main_drawer (or whatever). This means that you will have the same(*) Navigation Drawer on all activities.

  • They won't be the same instance of NavigationView but, to be fair, that wasn't possible even with the BaseActivity solution outlined above.

React Native add bold or italics to single words in <Text> field

You can use <Text> like a container for your other text components. This is example:

...
<Text>
  <Text>This is a sentence</Text>
  <Text style={{fontWeight: "bold"}}> with</Text>
  <Text> one word in bold</Text>
</Text>
...

Here is an example.

Update and left outer join statements

Just another example where the value of a column from table 1 is inserted into a column in table 2:

UPDATE  Address
SET     Phone1 = sp.Phone
FROM    Address ad LEFT JOIN Speaker sp
ON      sp.AddressID = ad.ID
WHERE   sp.Phone <> '' 

Rails raw SQL example

You can execute raw query using ActiveRecord. And I will suggest to go with SQL block

query = <<-SQL 
  SELECT * 
  FROM payment_details
  INNER JOIN projects 
          ON projects.id = payment_details.project_id
  ORDER BY payment_details.created_at DESC
SQL

result = ActiveRecord::Base.connection.execute(query)

How to configure Git post commit hook

Hope this helps: http://nrecursions.blogspot.in/2014/02/how-to-trigger-jenkins-build-on-git.html

It's just a matter of using curl to trigger a Jenkins job using the git hooks provided by git.
The command

curl http://localhost:8080/job/someJob/build?delay=0sec

can run a Jenkins job, where someJob is the name of the Jenkins job.

Search for the hooks folder in your hidden .git folder. Rename the post-commit.sample file to post-commit. Open it with Notepad, remove the : Nothing line and paste the above command into it.

That's it. Whenever you do a commit, Git will trigger the post-commit commands defined in the file.

String.equals() with multiple conditions (and one action on result)

Pattern p = Pattern.compile("tom"); //the regular-expression pattern
Matcher m = p.matcher("(bob)(tom)(harry)"); //The data to find matches with

while (m.find()) {
    //do something???
}   

Use regex to find a match maybe?

Or create an array

 String[] a = new String[]{
        "tom",
        "bob",
        "harry"
 };

 if(a.contains(stringtomatch)){
     //do something
 }

HTML email with Javascript

you can use html radio/checkbox input with labels and css to achieve the expanding effects you want.

How to change facebook login button with my custom image

Found a site on google explaining some changes, according to the author of the page fb does not allow custom buttons. Heres the website.

Unfortunately, it’s against Facebook’s developer policies, which state:

You must not circumvent our intended limitations on core Facebook features.

The Facebook Connect button is intended to be rendered in FBML, which means it’s only meant to look the way Facebook lets it.

How to "grep" out specific line ranges of a file

If I understand correctly, you want to find a pattern between two line numbers. The awk one-liner could be

awk '/whatev/ && NR >= 1234 && NR <= 5555' file

You don't need to run grep followed by sed.

Perl one-liner:

perl -ne 'if (/whatev/ && $. >= 1234 && $. <= 5555') {print}' file

Python Pandas Replacing Header with Top Row

If you want a one-liner, you can do:

df.rename(columns=df.iloc[0]).drop(df.index[0])

how to upload file using curl with php

Use:

if (function_exists('curl_file_create')) { // php 5.5+
  $cFile = curl_file_create($file_name_with_full_path);
} else { // 
  $cFile = '@' . realpath($file_name_with_full_path);
}
$post = array('extra_info' => '123456','file_contents'=> $cFile);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result=curl_exec ($ch);
curl_close ($ch);

You can also refer:

http://blog.derakkilgo.com/2009/06/07/send-a-file-via-post-with-curl-and-php/

Important hint for PHP 5.5+:

Now we should use https://wiki.php.net/rfc/curl-file-upload but if you still want to use this deprecated approach then you need to set curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);

How to specify font attributes for all elements on an html web page?

* {
 font-size: 100%;
 font-family: Arial;
}

The asterisk implies all elements.

eclipse won't start - no java virtual machine was found

In my case the problem was that the path was enclosed in quotation marks ("):

-vm 
"C:\Program Files\Java\jdk1.8.0_25\bin"

Removing them fixed the problem:

-vm 
C:\Program Files\Java\jdk1.8.0_25\bin

Get public/external IP address?

With a few lines of code you can write your own Http Server for this.

HttpListener listener = new HttpListener();
listener.Prefixes.Add("http://+/PublicIP/");
listener.Start();
while (true)
{
    HttpListenerContext context = listener.GetContext();
    string clientIP = context.Request.RemoteEndPoint.Address.ToString();
    using (Stream response = context.Response.OutputStream)
    using (StreamWriter writer = new StreamWriter(response))
        writer.Write(clientIP);

    context.Response.Close();
}

Then anytime you need to know your public ip, you can do this.

WebClient client = new WebClient();
string ip = client.DownloadString("http://serverIp/PublicIP");

Populating a razor dropdownlist from a List<object> in MVC

@model AdventureWork.CRUD.WebApp4.Models.EmployeeViewModel
@{
    ViewBag.Title = "Detalle";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Ingresar Usuario</h2>

@using (Html.BeginForm())
{

    @Html.AntiForgeryToken()
<div class="form-horizontal">


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

    <div class="form-group">
        @Html.LabelFor(model => model.Employee.PersonType, labelText: "Tipo de Persona", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(model => model.Employee.PersonType, new List<SelectListItem>
       {
               new SelectListItem{ Text= "SC", Value = "SC" },
               new SelectListItem{ Text= "VC", Value = "VC" },
                  new SelectListItem{ Text= "IN", Value = "IN" },
               new SelectListItem{ Text= "EM", Value = "EM" },
                new SelectListItem{ Text= "SP", Value = "SP" },

       }, htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.Employee.PersonType, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Employee.EmployeeGender, labelText: "Genero", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(model => model.Employee.EmployeeGender, new List<SelectListItem>
       {
           new SelectListItem{ Text= "Masculino", Value = "M" },
           new SelectListItem{ Text= "Femenino", Value = "F" }
       }, htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.Employee.EmployeeGender, "", new { @class = "text-danger" })
        </div>
    </div>

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

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

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

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

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

    <div class="form-group">
        @Html.LabelFor(model => model.Employee.DepartmentID, labelText: "Departamento", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(model => model.Employee.DepartmentID, new SelectList(Model.ListDepartment, "DepartmentID", "DepartmentName"), htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.Employee.DepartmentID, "", new { @class = "text-danger" })
        </div>
    </div>


    <div class="form-group">
        @Html.LabelFor(model => model.Employee.EmployeeMaritalStatus, labelText: "Estado Civil", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(model => model.Employee.EmployeeMaritalStatus, new List<SelectListItem>
       {
           new SelectListItem{ Text= "Soltero", Value = "S" },
           new SelectListItem{ Text= "Casado", Value = "M" }
       }, htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.Employee.EmployeeMaritalStatus, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Employee.ShiftId, labelText: "Turno", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(model => model.Employee.ShiftId, new SelectList(Model.ListShift, "ShiftId", "ShiftName"), htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.Employee.ShiftId, "", new { @class = "text-danger" })
        </div>
    </div>



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

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

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

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

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



    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Guardar" class="btn btn-default" />
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10" style="color:green">
            @ViewBag.Message
        </div>
        <div class="col-md-offset-2 col-md-10" style="color:red">
            @ViewBag.ErrorMessage
        </div>
    </div>
</div>


}

How to print jquery object/array

var arrofobject = [{"id":"197","category":"Damskie"},{"id":"198","category":"M\u0119skie"}];

$.each(arrofobject, function(index, val) {
    console.log(val.category);
});

how to sort order of LEFT JOIN in SQL query?

This will get you the most expensive car for the user:

SELECT users.userName, MAX(cars.carPrice)
FROM users
LEFT JOIN cars ON cars.belongsToUser=users.id
WHERE users.id=4
GROUP BY users.userName

However, this statement makes me think that you want all of the cars prices sorted, descending:

So question: How do I set the LEFT JOIN table to be ordered by carPrice, DESC ?

So you could try this:

SELECT users.userName, cars.carPrice
FROM users
LEFT JOIN cars ON cars.belongsToUser=users.id
WHERE users.id=4
GROUP BY users.userName
ORDER BY users.userName ASC, cars.carPrice DESC

Bootstrap Element 100% Width

There is a workaround using vw. Is useful when you can't create a new fluid container. This, inside a classic 'container' div will be full size.

.row-full{
 width: 100vw;
 position: relative;
 margin-left: -50vw;
 left: 50%;
}

After this there is the sidebar problem (thanks to @Typhlosaurus), solved with this js function, calling it on document load and resize:

function full_row_resize(){
    var body_width = $('body').width();
    $('.row-full').css('width', (body_width));
    $('.row-full').css('margin-left', ('-'+(body_width/2)+'px'));
    return false;
}

How to sort with lambda in Python

Use

a = sorted(a, key=lambda x: x.modified, reverse=True)
#             ^^^^

On Python 2.x, the sorted function takes its arguments in this order:

sorted(iterable, cmp=None, key=None, reverse=False)

so without the key=, the function you pass in will be considered a cmp function which takes 2 arguments.

How to get the index with the key in Python dictionary?

No, there is no straightforward way because Python dictionaries do not have a set ordering.

From the documentation:

Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions.

In other words, the 'index' of b depends entirely on what was inserted into and deleted from the mapping before:

>>> map={}
>>> map['b']=1
>>> map
{'b': 1}
>>> map['a']=1
>>> map
{'a': 1, 'b': 1}
>>> map['c']=1
>>> map
{'a': 1, 'c': 1, 'b': 1}

As of Python 2.7, you could use the collections.OrderedDict() type instead, if insertion order is important to your application.

How to delete multiple pandas (python) dataframes from memory to save RAM?

In python automatic garbage collection deallocates the variable (pandas DataFrame are also just another object in terms of python). There are different garbage collection strategies that can be tweaked (requires significant learning).

You can manually trigger the garbage collection using

import gc
gc.collect()

But frequent calls to garbage collection is discouraged as it is a costly operation and may affect performance.

Reference

libpng warning: iCCP: known incorrect sRGB profile

Using IrfanView image viewer in Windows, I simply resaved the PNG image and that corrected the problem.

Provisioning Profiles menu item missing from Xcode 5

Try this:

Xcode >> Preferences >> Accounts

Move the most recent commit(s) to a new branch with Git

If you just need to move all your unpushed commits to a new branch, then you just need to,

  1. create a new branch from the current one :git branch new-branch-name

  2. push your new branch: git push origin new-branch-name

  3. revert your old(current) branch to the last pushed/stable state: git reset --hard origin/old-branch-name

Some people also have other upstreams rather than origin, they should use appropriate upstream

JUnit 4 compare Sets

Apache commons to the rescue again.

assertTrue(CollectionUtils.isEqualCollection(coll1, coll2));

Works like a charm. I don't know why but I found that with collections the following assertEquals(coll1, coll2) doesn't always work. In the case where it failed for me I had two collections backed by Sets. Neither hamcrest nor junit would say the collections were equal even though I knew for sure that they were. Using CollectionUtils it works perfectly.

Determine the number of rows in a range

That single last line worked perfectly @GSerg.

The other function was what I had been working on but I don't like having to resort to UDF's unless absolutely necessary.

I had been trying a combination of excel and vba and had got this to work - but its clunky compared with your answer.

strArea = Sheets("Oper St Report CC").Range("cc_rev").CurrentRegion.Address
cc_rev_rows = "=ROWS(" & strArea & ")"
Range("cc_rev_count").Formula = cc_rev_rows

entity framework Unable to load the specified metadata resource

Craig Stuntz has written an extensive (in my opinion) blog post on troubleshooting this exact error message, I personally would start there.

The following res: (resource) references need to point to your model.

<add name="Entities" connectionString="metadata=
    res://*/Models.WraithNath.co.uk.csdl|
    res://*/Models.WraithNath.co.uk.ssdl|
    res://*/Models.WraithNath.co.uk.msl;

Make sure each one has the name of your .edmx file after the "*/", with the "edmx" changed to the extension for that res (.csdl, .ssdl, or .msl).

It also may help to specify the assembly rather than using "//*/".

Worst case, you can check everything (a bit slower but should always find the resource) by using

<add name="Entities" connectionString="metadata=
        res://*/;provider= <!-- ... -->

How to Access Hive via Python?

Similar to eycheu's solution, but a little more detailed.

Here is an alternative solution specifically for hive2 that does not require PyHive or installing system-wide packages. I am working on a linux environment that I do not have root access to so installing the SASL dependencies as mentioned in Tristin's post was not an option for me:

If you're on Linux, you may need to install SASL separately before running the above. Install the package libsasl2-dev using apt-get or yum or whatever package manager for your distribution.

Specifically, this solution focuses on leveraging the python package: JayDeBeApi. In my experience installing this one extra package on top of a python Anaconda 2.7 install was all I needed. This package leverages java (JDK). I am assuming that is already set up.

Step 1: Install JayDeBeApi

pip install jaydebeap

Step 2: Download appropriate drivers for your environment:

  • Here is a link to the jars required for an enterprise CDH environment
  • Another post that talks about where to find jdbc drivers for Apache Hive

Store all .jar files in a directory. I will refer to this directory as /path/to/jar/files/.

Step 3: Identify your systems authentication mechanism:

In the pyhive solutions listed I've seen PLAIN listed as the authentication mechanism as well as Kerberos. Note that your jdbc connection URL will depend on the authentication mechanism you are using. I will explain Kerberos solution without passing a username/password. Here is more information Kerberos authentication and options.

Create a Kerberos ticket if one is not already created

$ kinit

Tickets can be viewed via klist.

You are now ready to make the connection via python:

import jaydebeapi
import glob
# Creates a list of jar files in the /path/to/jar/files/ directory
jar_files = glob.glob('/path/to/jar/files/*.jar')

host='localhost'
port='10000'
database='default'

# note: your driver will depend on your environment and drivers you've
# downloaded in step 2
# this is the driver for my environment (jdbc3, hive2, cloudera enterprise)
driver='com.cloudera.hive.jdbc3.HS2Driver'

conn_hive = jaydebeapi.connect(driver,
        'jdbc:hive2://'+host+':' +port+'/'+database+';AuthMech=1;KrbHostFQDN='+host+';KrbServiceName=hive'
                           ,jars=jar_files)

If you only care about reading, then you can read it directly into a panda's dataframe with ease via eycheu's solution:

import pandas as pd
df = pd.read_sql("select * from table", conn_hive)

Otherwise, here is a more versatile communication option:

cursor = conn_hive.cursor()
sql_expression = "select * from table"
cursor.execute(sql_expression)
results = cursor.fetchall()

You could imagine, if you wanted to create a table, you would not need to "fetch" the results, but could submit a create table query instead.

How to fast get Hardware-ID in C#?

Here is a DLL that shows:
* Hard drive ID (unique hardware serial number written in drive's IDE electronic chip)
* Partition ID (volume serial number)
* CPU ID (unique hardware ID)
* CPU vendor
* CPU running speed
* CPU theoretic speed
* Memory Load ( Total memory used in percentage (%) )
* Total Physical ( Total physical memory in bytes )
* Avail Physical ( Physical memory left in bytes )
* Total PageFile ( Total page file in bytes )
* Available PageFile( Page file left in bytes )
* Total Virtual( Total virtual memory in bytes )
* Available Virtual ( Virtual memory left in bytes )
* Bios unique identification numberBiosDate
* Bios unique identification numberBiosVersion
* Bios unique identification numberBiosProductID
* Bios unique identification numberBiosVideo

(text grabbed from original web site)
It works with C#.

How do android screen coordinates work?

For Android API level 13 and you need to use this:

Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int maxX = size.x; 
int maxY = size.y;

Then (0,0) is top left corner and (maxX,maxY) is bottom right corner of the screen.

The 'getWidth()' for screen size is deprecated since API 13

Furthermore getwidth() and getHeight() are methods of android.view.View class in android.So when your java class extends View class there is no windowManager overheads.

          int maxX=getwidht();
          int maxY=getHeight();

as simple as that.

reactjs - how to set inline style of backgroundcolor?

If you want more than one style this is the correct full answer. This is div with class and style:

<div className="class-example" style={{width: '300px', height: '150px'}}></div>

Cannot run emulator in Android Studio

In my case (Windows 10) the reason was that I dared to unzip the android sdk into non default folder. When I moved it to the default one c:/Users/[username]/AppData/Local/Android/Sdk and changed the paths in Android Studio and System Variables, it started to work.

How do you scroll up/down on the console of a Linux VM

VM Ubuntu on a Mac...fn + shift + up/down arrows

Adding system header search path to Xcode

To use quotes just for completeness.

"/Users/my/work/a project with space"/**

If not recursive, remove the /**

How to force JS to do math instead of putting two strings together

You can add + behind the variable and it will force it to be an integer

var dots = 5
    function increase(){
        dots = +dots + 5;
    }

difference between $query>num_rows() and $this->db->count_all_results() in CodeIgniter & which one is recommended

Simply as bellow;

$this->db->get('table_name')->num_rows();

This will get number of rows/records. however you can use search parameters as well;

$this->db->select('col1','col2')->where('col'=>'crieterion')->get('table_name')->num_rows();

However, it should be noted that you will see bad bad errors if applying as below;

$this->db->get('table_name')->result()->num_rows();

Display current time in 12 hour format with AM/PM

Just replace below statement and it will work.

SimpleDateFormat formatDate = new SimpleDateFormat("hh:mm a");

How to embed new Youtube's live video permanent URL?

The embed URL for a channel's live stream is:

https://www.youtube.com/embed/live_stream?channel=CHANNEL_ID

You can find your CHANNEL_ID at https://www.youtube.com/account_advanced

How to change options of <select> with jQuery?

I threw CMS's excellent answer into a quick jQuery extension:

(function($, window) {
  $.fn.replaceOptions = function(options) {
    var self, $option;

    this.empty();
    self = this;

    $.each(options, function(index, option) {
      $option = $("<option></option>")
        .attr("value", option.value)
        .text(option.text);
      self.append($option);
    });
  };
})(jQuery, window);

It expects an array of objects which contain "text" and "value" keys. So usage is as follows:

var options = [
  {text: "one", value: 1},
  {text: "two", value: 2}
];

$("#foo").replaceOptions(options);

Why are arrays of references illegal?

Because like many have said here, references are not objects. they are simply aliases. True some compilers might implement them as pointers, but the standard does not force/specify that. And because references are not objects, you cannot point to them. Storing elements in an array means there is some kind of index address (i.e., pointing to elements at a certain index); and that is why you cannot have arrays of references, because you cannot point to them.

Use boost::reference_wrapper, or boost::tuple instead; or just pointers.

Escaping single quotes in JavaScript string for JavaScript evaluation

strInputString = strInputString.replace(/'/g, "''");

Using :before and :after CSS selector to insert Html

content doesn't support HTML, only text. You should probably use javascript, jQuery or something like that.

Another problem with your code is " inside a " block. You should mix ' and " (class='headingDetail').

If content did support HTML you could end up in an infinite loop where content is added inside content.

git pull displays "fatal: Couldn't find remote ref refs/heads/xxxx" and hangs up

I have same error. Problem was that branch was deleted, released. But in PhpStorm I still could see it in remote branches. I could checkout as local branch. And then doing git pull was giving this error.

So need to check if this brnach really exists remotely.

Tar a directory, but don't store full absolute paths in the archive

Using the "point" leads to the creation of a folder named "point" (on Ubuntu 16).

tar -tf site1.bz2 -C /var/www/site1/ .

I dealt with this in more detail and prepared an example. Multi-line recording, plus an exception.

tar -tf site1.bz2\
    -C /var/www/site1/ style.css\
    -C /var/www/site1/ index.html\
    -C /var/www/site1/ page2.html\
    -C /var/www/site1/ page3.html\
    --exclude=images/*.zip\
    -C /var/www/site1/ images/
    -C /var/www/site1/ subdir/
/

Find the location of a character in string

Here's another straightforward alternative.

> which(strsplit(string, "")[[1]]=="2")
[1]  4 24

Assigning strings to arrays of characters

When initializing an array, C allows you to fill it with values. So

char s[100] = "abcd";

is basically the same as

int s[3] = { 1, 2, 3 };

but it doesn't allow you to do the assignment since s is an array and not a free pointer. The meaning of

s = "abcd" 

is to assign the pointer value of abcd to s but you can't change s since then nothing will be pointing to the array.
This can and does work if s is a char* - a pointer that can point to anything.

If you want to copy the string simple use strcpy.

How do I navigate to another page when PHP script is done?

if ($done)
{
    header("Location: /url/to/the/other/page");
    exit;
}

Handling click events on a drawable within an EditText

So many solutions, but none worked for me when I had two fields in a row. This is drop in solution for adding clear button to edit text, worked for me in my situations where I have two fields or one field in a row. Written in kotlin !

@SuppressLint("PrivateResource")
fun <T : EditText> T.withClear(): T {
    addTextChangedListener(object : TextWatcher {
        override fun afterTextChanged(editable: Editable) {
            setCompoundDrawablesWithIntrinsicBounds(0, 0,
                    if (editable.isNotEmpty()) abc_ic_clear_material else 0, 0)
        }

        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit
        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) = Unit
    })

    setOnTouchListener { _, event ->
        if (event.action == ACTION_UP && event.x >= (right - this.compoundPaddingRight)) {
            setText("")
            return@setOnTouchListener true
        }
        false
    }
    return this
}

Bulk create model objects in django

Check out this blog post on the bulkops module.

On my django 1.3 app, I have experienced significant speedup.

Using COALESCE to handle NULL values in PostgreSQL

You can use COALESCE in conjunction with NULLIF for a short, efficient solution:

COALESCE( NULLIF(yourField,'') , '0' )

The NULLIF function will return null if yourField is equal to the second value ('' in the example), making the COALESCE function fully working on all cases:

                 QUERY                     |                RESULT 
---------------------------------------------------------------------------------
SELECT COALESCE(NULLIF(null  ,''),'0')     |                 '0'
SELECT COALESCE(NULLIF(''    ,''),'0')     |                 '0'
SELECT COALESCE(NULLIF('foo' ,''),'0')     |                 'foo'

How to set caret(cursor) position in contenteditable element (div)?

Most answers you find on contenteditable cursor positioning are fairly simplistic in that they only cater for inputs with plain vanilla text. Once you using html elements within the container the text entered gets split into nodes and distributed liberally across a tree structure.

To set the cursor position I have this function which loops round all the child text nodes within the supplied node and sets a range from the start of the initial node to the chars.count character:

function createRange(node, chars, range) {
    if (!range) {
        range = document.createRange()
        range.selectNode(node);
        range.setStart(node, 0);
    }

    if (chars.count === 0) {
        range.setEnd(node, chars.count);
    } else if (node && chars.count >0) {
        if (node.nodeType === Node.TEXT_NODE) {
            if (node.textContent.length < chars.count) {
                chars.count -= node.textContent.length;
            } else {
                range.setEnd(node, chars.count);
                chars.count = 0;
            }
        } else {
           for (var lp = 0; lp < node.childNodes.length; lp++) {
                range = createRange(node.childNodes[lp], chars, range);

                if (chars.count === 0) {
                    break;
                }
            }
        }
    } 

    return range;
};

I then call the routine with this function:

function setCurrentCursorPosition(chars) {
    if (chars >= 0) {
        var selection = window.getSelection();

        range = createRange(document.getElementById("test").parentNode, { count: chars });

        if (range) {
            range.collapse(false);
            selection.removeAllRanges();
            selection.addRange(range);
        }
    }
};

The range.collapse(false) sets the cursor to the end of the range. I've tested it with the latest versions of Chrome, IE, Mozilla and Opera and they all work fine.

PS. If anyone is interested I get the current cursor position using this code:

function isChildOf(node, parentId) {
    while (node !== null) {
        if (node.id === parentId) {
            return true;
        }
        node = node.parentNode;
    }

    return false;
};

function getCurrentCursorPosition(parentId) {
    var selection = window.getSelection(),
        charCount = -1,
        node;

    if (selection.focusNode) {
        if (isChildOf(selection.focusNode, parentId)) {
            node = selection.focusNode; 
            charCount = selection.focusOffset;

            while (node) {
                if (node.id === parentId) {
                    break;
                }

                if (node.previousSibling) {
                    node = node.previousSibling;
                    charCount += node.textContent.length;
                } else {
                     node = node.parentNode;
                     if (node === null) {
                         break
                     }
                }
           }
      }
   }

    return charCount;
};

The code does the opposite of the set function - it gets the current window.getSelection().focusNode and focusOffset and counts backwards all text characters encountered until it hits a parent node with id of containerId. The isChildOf function just checks before running that the suplied node is actually a child of the supplied parentId.

The code should work straight without change, but I have just taken it from a jQuery plugin I've developed so have hacked out a couple of this's - let me know if anything doesn't work!

Can you pass parameters to an AngularJS controller on creation?

I'm very late to this and I have no idea if this is a good idea, but you can include the $attrs injectable in the controller function allowing the controller to be initialized using "arguments" provided on an element, e.g.

app.controller('modelController', function($scope, $attrs) {
    if (!$attrs.model) throw new Error("No model for modelController");

    // Initialize $scope using the value of the model attribute, e.g.,
    $scope.url = "http://example.com/fetch?model="+$attrs.model;
})

<div ng-controller="modelController" model="foobar">
  <a href="{{url}}">Click here</a>
</div>

Again, no idea if this is a good idea, but it seems to work and is another alternative.

Function to Calculate a CRC16 Checksum

crcany will generate efficient C code for any CRC, and includes a library of over one hundred known CRC definitions.

Efficient CRC code uses tables instead of bit-wise calculations. crcany generates both byte-wise routines and word-wise routines, the latter tuned to the architecture they are generated on. Word-wise is the fastest. Byte-wise is still much faster than bit-wise, but the implementation is more easily portable over architectures.

You do not seem to have a protocol definition with a specific CRC definition that you need to match. In this case, you can pick any 16-bit CRC in the catalog, and you will get good performance.

If you have a relatively low bit error rate, e.g. single digit number of errors per packet, and you want to maximize your error detection performance, you would need to look at the packet size you are applying the CRC to, assuming that that is constant or bounded, and look at the performance of the best polynomials in Philip Koopman's extensive research. The classic CRCs, such as the CCITT/Kermit 16-bit CRC or the X.25 16-bit CRC are not the best performers.

One of the good 16-bit performers in Koopman's tables that is also in the catalog of CRCs used in practice is CRC-16/DNP. It has very good performance detecting up to 6-bit errors in a packet. Following is the code generated by crcany for that CRC definition. This code assumes a little-endian architecture for the word-wise calculation, e.g. Intel x86 and x86-64, and it assumes that uintmax_t is 64 bits. crcany can be used to generate alternative code for big-endian and other word sizes.

crc16dnp.h:

// The _bit, _byte, and _word routines return the CRC of the len bytes at mem,
// applied to the previous CRC value, crc. If mem is NULL, then the other
// arguments are ignored, and the initial CRC, i.e. the CRC of zero bytes, is
// returned. Those routines will all return the same result, differing only in
// speed and code complexity. The _rem routine returns the CRC of the remaining
// bits in the last byte, for when the number of bits in the message is not a
// multiple of eight. The low bits bits of the low byte of val are applied to
// crc. bits must be in 0..8.

#include <stddef.h>

// Compute the CRC a bit at a time.
unsigned crc16dnp_bit(unsigned crc, void const *mem, size_t len);

// Compute the CRC of the low bits bits in val.
unsigned crc16dnp_rem(unsigned crc, unsigned val, unsigned bits);

// Compute the CRC a byte at a time.
unsigned crc16dnp_byte(unsigned crc, void const *mem, size_t len);

// Compute the CRC a word at a time.
unsigned crc16dnp_word(unsigned crc, void const *mem, size_t len);

crc16dnp.c:

#include <stdint.h>
#include "crc16dnp.h"

// This code assumes that unsigned is 4 bytes.

unsigned crc16dnp_bit(unsigned crc, void const *mem, size_t len) {
    unsigned char const *data = mem;
    if (data == NULL)
        return 0xffff;
    crc = ~crc;
    crc &= 0xffff;
    while (len--) {
        crc ^= *data++;
        for (unsigned k = 0; k < 8; k++)
            crc = crc & 1 ? (crc >> 1) ^ 0xa6bc : crc >> 1;
    }
    crc ^= 0xffff;
    return crc;
}

unsigned crc16dnp_rem(unsigned crc, unsigned val, unsigned bits) {
    crc = ~crc;
    crc &= 0xffff;
    val &= (1U << bits) - 1;
    crc ^= val;
    while (bits--)
        crc = crc & 1 ? (crc >> 1) ^ 0xa6bc : crc >> 1;
    crc ^= 0xffff;
    return crc;
}

#define table_byte table_word[0]

static unsigned short const table_word[][256] = {
   {0xed35, 0xdb6b, 0x8189, 0xb7d7, 0x344d, 0x0213, 0x58f1, 0x6eaf, 0x12bc, 0x24e2,
    0x7e00, 0x485e, 0xcbc4, 0xfd9a, 0xa778, 0x9126, 0x5f5e, 0x6900, 0x33e2, 0x05bc,
    0x8626, 0xb078, 0xea9a, 0xdcc4, 0xa0d7, 0x9689, 0xcc6b, 0xfa35, 0x79af, 0x4ff1,
    0x1513, 0x234d, 0xc49a, 0xf2c4, 0xa826, 0x9e78, 0x1de2, 0x2bbc, 0x715e, 0x4700,
    0x3b13, 0x0d4d, 0x57af, 0x61f1, 0xe26b, 0xd435, 0x8ed7, 0xb889, 0x76f1, 0x40af,
    0x1a4d, 0x2c13, 0xaf89, 0x99d7, 0xc335, 0xf56b, 0x8978, 0xbf26, 0xe5c4, 0xd39a,
    0x5000, 0x665e, 0x3cbc, 0x0ae2, 0xbe6b, 0x8835, 0xd2d7, 0xe489, 0x6713, 0x514d,
    0x0baf, 0x3df1, 0x41e2, 0x77bc, 0x2d5e, 0x1b00, 0x989a, 0xaec4, 0xf426, 0xc278,
    0x0c00, 0x3a5e, 0x60bc, 0x56e2, 0xd578, 0xe326, 0xb9c4, 0x8f9a, 0xf389, 0xc5d7,
    0x9f35, 0xa96b, 0x2af1, 0x1caf, 0x464d, 0x7013, 0x97c4, 0xa19a, 0xfb78, 0xcd26,
    0x4ebc, 0x78e2, 0x2200, 0x145e, 0x684d, 0x5e13, 0x04f1, 0x32af, 0xb135, 0x876b,
    0xdd89, 0xebd7, 0x25af, 0x13f1, 0x4913, 0x7f4d, 0xfcd7, 0xca89, 0x906b, 0xa635,
    0xda26, 0xec78, 0xb69a, 0x80c4, 0x035e, 0x3500, 0x6fe2, 0x59bc, 0x4b89, 0x7dd7,
    0x2735, 0x116b, 0x92f1, 0xa4af, 0xfe4d, 0xc813, 0xb400, 0x825e, 0xd8bc, 0xeee2,
    0x6d78, 0x5b26, 0x01c4, 0x379a, 0xf9e2, 0xcfbc, 0x955e, 0xa300, 0x209a, 0x16c4,
    0x4c26, 0x7a78, 0x066b, 0x3035, 0x6ad7, 0x5c89, 0xdf13, 0xe94d, 0xb3af, 0x85f1,
    0x6226, 0x5478, 0x0e9a, 0x38c4, 0xbb5e, 0x8d00, 0xd7e2, 0xe1bc, 0x9daf, 0xabf1,
    0xf113, 0xc74d, 0x44d7, 0x7289, 0x286b, 0x1e35, 0xd04d, 0xe613, 0xbcf1, 0x8aaf,
    0x0935, 0x3f6b, 0x6589, 0x53d7, 0x2fc4, 0x199a, 0x4378, 0x7526, 0xf6bc, 0xc0e2,
    0x9a00, 0xac5e, 0x18d7, 0x2e89, 0x746b, 0x4235, 0xc1af, 0xf7f1, 0xad13, 0x9b4d,
    0xe75e, 0xd100, 0x8be2, 0xbdbc, 0x3e26, 0x0878, 0x529a, 0x64c4, 0xaabc, 0x9ce2,
    0xc600, 0xf05e, 0x73c4, 0x459a, 0x1f78, 0x2926, 0x5535, 0x636b, 0x3989, 0x0fd7,
    0x8c4d, 0xba13, 0xe0f1, 0xd6af, 0x3178, 0x0726, 0x5dc4, 0x6b9a, 0xe800, 0xde5e,
    0x84bc, 0xb2e2, 0xcef1, 0xf8af, 0xa24d, 0x9413, 0x1789, 0x21d7, 0x7b35, 0x4d6b,
    0x8313, 0xb54d, 0xefaf, 0xd9f1, 0x5a6b, 0x6c35, 0x36d7, 0x0089, 0x7c9a, 0x4ac4,
    0x1026, 0x2678, 0xa5e2, 0x93bc, 0xc95e, 0xff00},
   {0x740f, 0xdf41, 0x6fea, 0xc4a4, 0x43c5, 0xe88b, 0x5820, 0xf36e, 0x1b9b, 0xb0d5,
    0x007e, 0xab30, 0x2c51, 0x871f, 0x37b4, 0x9cfa, 0xab27, 0x0069, 0xb0c2, 0x1b8c,
    0x9ced, 0x37a3, 0x8708, 0x2c46, 0xc4b3, 0x6ffd, 0xdf56, 0x7418, 0xf379, 0x5837,
    0xe89c, 0x43d2, 0x8726, 0x2c68, 0x9cc3, 0x378d, 0xb0ec, 0x1ba2, 0xab09, 0x0047,
    0xe8b2, 0x43fc, 0xf357, 0x5819, 0xdf78, 0x7436, 0xc49d, 0x6fd3, 0x580e, 0xf340,
    0x43eb, 0xe8a5, 0x6fc4, 0xc48a, 0x7421, 0xdf6f, 0x379a, 0x9cd4, 0x2c7f, 0x8731,
    0x0050, 0xab1e, 0x1bb5, 0xb0fb, 0xdf24, 0x746a, 0xc4c1, 0x6f8f, 0xe8ee, 0x43a0,
    0xf30b, 0x5845, 0xb0b0, 0x1bfe, 0xab55, 0x001b, 0x877a, 0x2c34, 0x9c9f, 0x37d1,
    0x000c, 0xab42, 0x1be9, 0xb0a7, 0x37c6, 0x9c88, 0x2c23, 0x876d, 0x6f98, 0xc4d6,
    0x747d, 0xdf33, 0x5852, 0xf31c, 0x43b7, 0xe8f9, 0x2c0d, 0x8743, 0x37e8, 0x9ca6,
    0x1bc7, 0xb089, 0x0022, 0xab6c, 0x4399, 0xe8d7, 0x587c, 0xf332, 0x7453, 0xdf1d,
    0x6fb6, 0xc4f8, 0xf325, 0x586b, 0xe8c0, 0x438e, 0xc4ef, 0x6fa1, 0xdf0a, 0x7444,
    0x9cb1, 0x37ff, 0x8754, 0x2c1a, 0xab7b, 0x0035, 0xb09e, 0x1bd0, 0x6f20, 0xc46e,
    0x74c5, 0xdf8b, 0x58ea, 0xf3a4, 0x430f, 0xe841, 0x00b4, 0xabfa, 0x1b51, 0xb01f,
    0x377e, 0x9c30, 0x2c9b, 0x87d5, 0xb008, 0x1b46, 0xabed, 0x00a3, 0x87c2, 0x2c8c,
    0x9c27, 0x3769, 0xdf9c, 0x74d2, 0xc479, 0x6f37, 0xe856, 0x4318, 0xf3b3, 0x58fd,
    0x9c09, 0x3747, 0x87ec, 0x2ca2, 0xabc3, 0x008d, 0xb026, 0x1b68, 0xf39d, 0x58d3,
    0xe878, 0x4336, 0xc457, 0x6f19, 0xdfb2, 0x74fc, 0x4321, 0xe86f, 0x58c4, 0xf38a,
    0x74eb, 0xdfa5, 0x6f0e, 0xc440, 0x2cb5, 0x87fb, 0x3750, 0x9c1e, 0x1b7f, 0xb031,
    0x009a, 0xabd4, 0xc40b, 0x6f45, 0xdfee, 0x74a0, 0xf3c1, 0x588f, 0xe824, 0x436a,
    0xab9f, 0x00d1, 0xb07a, 0x1b34, 0x9c55, 0x371b, 0x87b0, 0x2cfe, 0x1b23, 0xb06d,
    0x00c6, 0xab88, 0x2ce9, 0x87a7, 0x370c, 0x9c42, 0x74b7, 0xdff9, 0x6f52, 0xc41c,
    0x437d, 0xe833, 0x5898, 0xf3d6, 0x3722, 0x9c6c, 0x2cc7, 0x8789, 0x00e8, 0xaba6,
    0x1b0d, 0xb043, 0x58b6, 0xf3f8, 0x4353, 0xe81d, 0x6f7c, 0xc432, 0x7499, 0xdfd7,
    0xe80a, 0x4344, 0xf3ef, 0x58a1, 0xdfc0, 0x748e, 0xc425, 0x6f6b, 0x879e, 0x2cd0,
    0x9c7b, 0x3735, 0xb054, 0x1b1a, 0xabb1, 0x00ff},
   {0x7c67, 0x65df, 0x4f17, 0x56af, 0x1a87, 0x033f, 0x29f7, 0x304f, 0xb1a7, 0xa81f,
    0x82d7, 0x9b6f, 0xd747, 0xceff, 0xe437, 0xfd8f, 0xaa9e, 0xb326, 0x99ee, 0x8056,
    0xcc7e, 0xd5c6, 0xff0e, 0xe6b6, 0x675e, 0x7ee6, 0x542e, 0x4d96, 0x01be, 0x1806,
    0x32ce, 0x2b76, 0x9cec, 0x8554, 0xaf9c, 0xb624, 0xfa0c, 0xe3b4, 0xc97c, 0xd0c4,
    0x512c, 0x4894, 0x625c, 0x7be4, 0x37cc, 0x2e74, 0x04bc, 0x1d04, 0x4a15, 0x53ad,
    0x7965, 0x60dd, 0x2cf5, 0x354d, 0x1f85, 0x063d, 0x87d5, 0x9e6d, 0xb4a5, 0xad1d,
    0xe135, 0xf88d, 0xd245, 0xcbfd, 0xf008, 0xe9b0, 0xc378, 0xdac0, 0x96e8, 0x8f50,
    0xa598, 0xbc20, 0x3dc8, 0x2470, 0x0eb8, 0x1700, 0x5b28, 0x4290, 0x6858, 0x71e0,
    0x26f1, 0x3f49, 0x1581, 0x0c39, 0x4011, 0x59a9, 0x7361, 0x6ad9, 0xeb31, 0xf289,
    0xd841, 0xc1f9, 0x8dd1, 0x9469, 0xbea1, 0xa719, 0x1083, 0x093b, 0x23f3, 0x3a4b,
    0x7663, 0x6fdb, 0x4513, 0x5cab, 0xdd43, 0xc4fb, 0xee33, 0xf78b, 0xbba3, 0xa21b,
    0x88d3, 0x916b, 0xc67a, 0xdfc2, 0xf50a, 0xecb2, 0xa09a, 0xb922, 0x93ea, 0x8a52,
    0x0bba, 0x1202, 0x38ca, 0x2172, 0x6d5a, 0x74e2, 0x5e2a, 0x4792, 0x29c0, 0x3078,
    0x1ab0, 0x0308, 0x4f20, 0x5698, 0x7c50, 0x65e8, 0xe400, 0xfdb8, 0xd770, 0xcec8,
    0x82e0, 0x9b58, 0xb190, 0xa828, 0xff39, 0xe681, 0xcc49, 0xd5f1, 0x99d9, 0x8061,
    0xaaa9, 0xb311, 0x32f9, 0x2b41, 0x0189, 0x1831, 0x5419, 0x4da1, 0x6769, 0x7ed1,
    0xc94b, 0xd0f3, 0xfa3b, 0xe383, 0xafab, 0xb613, 0x9cdb, 0x8563, 0x048b, 0x1d33,
    0x37fb, 0x2e43, 0x626b, 0x7bd3, 0x511b, 0x48a3, 0x1fb2, 0x060a, 0x2cc2, 0x357a,
    0x7952, 0x60ea, 0x4a22, 0x539a, 0xd272, 0xcbca, 0xe102, 0xf8ba, 0xb492, 0xad2a,
    0x87e2, 0x9e5a, 0xa5af, 0xbc17, 0x96df, 0x8f67, 0xc34f, 0xdaf7, 0xf03f, 0xe987,
    0x686f, 0x71d7, 0x5b1f, 0x42a7, 0x0e8f, 0x1737, 0x3dff, 0x2447, 0x7356, 0x6aee,
    0x4026, 0x599e, 0x15b6, 0x0c0e, 0x26c6, 0x3f7e, 0xbe96, 0xa72e, 0x8de6, 0x945e,
    0xd876, 0xc1ce, 0xeb06, 0xf2be, 0x4524, 0x5c9c, 0x7654, 0x6fec, 0x23c4, 0x3a7c,
    0x10b4, 0x090c, 0x88e4, 0x915c, 0xbb94, 0xa22c, 0xee04, 0xf7bc, 0xdd74, 0xc4cc,
    0x93dd, 0x8a65, 0xa0ad, 0xb915, 0xf53d, 0xec85, 0xc64d, 0xdff5, 0x5e1d, 0x47a5,
    0x6d6d, 0x74d5, 0x38fd, 0x2145, 0x0b8d, 0x1235},
   {0xf917, 0x3bff, 0x31be, 0xf356, 0x253c, 0xe7d4, 0xed95, 0x2f7d, 0x0c38, 0xced0,
    0xc491, 0x0679, 0xd013, 0x12fb, 0x18ba, 0xda52, 0x5e30, 0x9cd8, 0x9699, 0x5471,
    0x821b, 0x40f3, 0x4ab2, 0x885a, 0xab1f, 0x69f7, 0x63b6, 0xa15e, 0x7734, 0xb5dc,
    0xbf9d, 0x7d75, 0xfa20, 0x38c8, 0x3289, 0xf061, 0x260b, 0xe4e3, 0xeea2, 0x2c4a,
    0x0f0f, 0xcde7, 0xc7a6, 0x054e, 0xd324, 0x11cc, 0x1b8d, 0xd965, 0x5d07, 0x9fef,
    0x95ae, 0x5746, 0x812c, 0x43c4, 0x4985, 0x8b6d, 0xa828, 0x6ac0, 0x6081, 0xa269,
    0x7403, 0xb6eb, 0xbcaa, 0x7e42, 0xff79, 0x3d91, 0x37d0, 0xf538, 0x2352, 0xe1ba,
    0xebfb, 0x2913, 0x0a56, 0xc8be, 0xc2ff, 0x0017, 0xd67d, 0x1495, 0x1ed4, 0xdc3c,
    0x585e, 0x9ab6, 0x90f7, 0x521f, 0x8475, 0x469d, 0x4cdc, 0x8e34, 0xad71, 0x6f99,
    0x65d8, 0xa730, 0x715a, 0xb3b2, 0xb9f3, 0x7b1b, 0xfc4e, 0x3ea6, 0x34e7, 0xf60f,
    0x2065, 0xe28d, 0xe8cc, 0x2a24, 0x0961, 0xcb89, 0xc1c8, 0x0320, 0xd54a, 0x17a2,
    0x1de3, 0xdf0b, 0x5b69, 0x9981, 0x93c0, 0x5128, 0x8742, 0x45aa, 0x4feb, 0x8d03,
    0xae46, 0x6cae, 0x66ef, 0xa407, 0x726d, 0xb085, 0xbac4, 0x782c, 0xf5cb, 0x3723,
    0x3d62, 0xff8a, 0x29e0, 0xeb08, 0xe149, 0x23a1, 0x00e4, 0xc20c, 0xc84d, 0x0aa5,
    0xdccf, 0x1e27, 0x1466, 0xd68e, 0x52ec, 0x9004, 0x9a45, 0x58ad, 0x8ec7, 0x4c2f,
    0x466e, 0x8486, 0xa7c3, 0x652b, 0x6f6a, 0xad82, 0x7be8, 0xb900, 0xb341, 0x71a9,
    0xf6fc, 0x3414, 0x3e55, 0xfcbd, 0x2ad7, 0xe83f, 0xe27e, 0x2096, 0x03d3, 0xc13b,
    0xcb7a, 0x0992, 0xdff8, 0x1d10, 0x1751, 0xd5b9, 0x51db, 0x9333, 0x9972, 0x5b9a,
    0x8df0, 0x4f18, 0x4559, 0x87b1, 0xa4f4, 0x661c, 0x6c5d, 0xaeb5, 0x78df, 0xba37,
    0xb076, 0x729e, 0xf3a5, 0x314d, 0x3b0c, 0xf9e4, 0x2f8e, 0xed66, 0xe727, 0x25cf,
    0x068a, 0xc462, 0xce23, 0x0ccb, 0xdaa1, 0x1849, 0x1208, 0xd0e0, 0x5482, 0x966a,
    0x9c2b, 0x5ec3, 0x88a9, 0x4a41, 0x4000, 0x82e8, 0xa1ad, 0x6345, 0x6904, 0xabec,
    0x7d86, 0xbf6e, 0xb52f, 0x77c7, 0xf092, 0x327a, 0x383b, 0xfad3, 0x2cb9, 0xee51,
    0xe410, 0x26f8, 0x05bd, 0xc755, 0xcd14, 0x0ffc, 0xd996, 0x1b7e, 0x113f, 0xd3d7,
    0x57b5, 0x955d, 0x9f1c, 0x5df4, 0x8b9e, 0x4976, 0x4337, 0x81df, 0xa29a, 0x6072,
    0x6a33, 0xa8db, 0x7eb1, 0xbc59, 0xb618, 0x74f0},
   {0x3108, 0x120e, 0x7704, 0x5402, 0xbd10, 0x9e16, 0xfb1c, 0xd81a, 0x6441, 0x4747,
    0x224d, 0x014b, 0xe859, 0xcb5f, 0xae55, 0x8d53, 0x9b9a, 0xb89c, 0xdd96, 0xfe90,
    0x1782, 0x3484, 0x518e, 0x7288, 0xced3, 0xedd5, 0x88df, 0xabd9, 0x42cb, 0x61cd,
    0x04c7, 0x27c1, 0x2955, 0x0a53, 0x6f59, 0x4c5f, 0xa54d, 0x864b, 0xe341, 0xc047,
    0x7c1c, 0x5f1a, 0x3a10, 0x1916, 0xf004, 0xd302, 0xb608, 0x950e, 0x83c7, 0xa0c1,
    0xc5cb, 0xe6cd, 0x0fdf, 0x2cd9, 0x49d3, 0x6ad5, 0xd68e, 0xf588, 0x9082, 0xb384,
    0x5a96, 0x7990, 0x1c9a, 0x3f9c, 0x01b2, 0x22b4, 0x47be, 0x64b8, 0x8daa, 0xaeac,
    0xcba6, 0xe8a0, 0x54fb, 0x77fd, 0x12f7, 0x31f1, 0xd8e3, 0xfbe5, 0x9eef, 0xbde9,
    0xab20, 0x8826, 0xed2c, 0xce2a, 0x2738, 0x043e, 0x6134, 0x4232, 0xfe69, 0xdd6f,
    0xb865, 0x9b63, 0x7271, 0x5177, 0x347d, 0x177b, 0x19ef, 0x3ae9, 0x5fe3, 0x7ce5,
    0x95f7, 0xb6f1, 0xd3fb, 0xf0fd, 0x4ca6, 0x6fa0, 0x0aaa, 0x29ac, 0xc0be, 0xe3b8,
    0x86b2, 0xa5b4, 0xb37d, 0x907b, 0xf571, 0xd677, 0x3f65, 0x1c63, 0x7969, 0x5a6f,
    0xe634, 0xc532, 0xa038, 0x833e, 0x6a2c, 0x492a, 0x2c20, 0x0f26, 0x507c, 0x737a,
    0x1670, 0x3576, 0xdc64, 0xff62, 0x9a68, 0xb96e, 0x0535, 0x2633, 0x4339, 0x603f,
    0x892d, 0xaa2b, 0xcf21, 0xec27, 0xfaee, 0xd9e8, 0xbce2, 0x9fe4, 0x76f6, 0x55f0,
    0x30fa, 0x13fc, 0xafa7, 0x8ca1, 0xe9ab, 0xcaad, 0x23bf, 0x00b9, 0x65b3, 0x46b5,
    0x4821, 0x6b27, 0x0e2d, 0x2d2b, 0xc439, 0xe73f, 0x8235, 0xa133, 0x1d68, 0x3e6e,
    0x5b64, 0x7862, 0x9170, 0xb276, 0xd77c, 0xf47a, 0xe2b3, 0xc1b5, 0xa4bf, 0x87b9,
    0x6eab, 0x4dad, 0x28a7, 0x0ba1, 0xb7fa, 0x94fc, 0xf1f6, 0xd2f0, 0x3be2, 0x18e4,
    0x7dee, 0x5ee8, 0x60c6, 0x43c0, 0x26ca, 0x05cc, 0xecde, 0xcfd8, 0xaad2, 0x89d4,
    0x358f, 0x1689, 0x7383, 0x5085, 0xb997, 0x9a91, 0xff9b, 0xdc9d, 0xca54, 0xe952,
    0x8c58, 0xaf5e, 0x464c, 0x654a, 0x0040, 0x2346, 0x9f1d, 0xbc1b, 0xd911, 0xfa17,
    0x1305, 0x3003, 0x5509, 0x760f, 0x789b, 0x5b9d, 0x3e97, 0x1d91, 0xf483, 0xd785,
    0xb28f, 0x9189, 0x2dd2, 0x0ed4, 0x6bde, 0x48d8, 0xa1ca, 0x82cc, 0xe7c6, 0xc4c0,
    0xd209, 0xf10f, 0x9405, 0xb703, 0x5e11, 0x7d17, 0x181d, 0x3b1b, 0x8740, 0xa446,
    0xc14c, 0xe24a, 0x0b58, 0x285e, 0x4d54, 0x6e52},
   {0xffb8, 0x4a5f, 0xd90f, 0x6ce8, 0xb2d6, 0x0731, 0x9461, 0x2186, 0x6564, 0xd083,
    0x43d3, 0xf634, 0x280a, 0x9ded, 0x0ebd, 0xbb5a, 0x8779, 0x329e, 0xa1ce, 0x1429,
    0xca17, 0x7ff0, 0xeca0, 0x5947, 0x1da5, 0xa842, 0x3b12, 0x8ef5, 0x50cb, 0xe52c,
    0x767c, 0xc39b, 0x0e3a, 0xbbdd, 0x288d, 0x9d6a, 0x4354, 0xf6b3, 0x65e3, 0xd004,
    0x94e6, 0x2101, 0xb251, 0x07b6, 0xd988, 0x6c6f, 0xff3f, 0x4ad8, 0x76fb, 0xc31c,
    0x504c, 0xe5ab, 0x3b95, 0x8e72, 0x1d22, 0xa8c5, 0xec27, 0x59c0, 0xca90, 0x7f77,
    0xa149, 0x14ae, 0x87fe, 0x3219, 0x51c5, 0xe422, 0x7772, 0xc295, 0x1cab, 0xa94c,
    0x3a1c, 0x8ffb, 0xcb19, 0x7efe, 0xedae, 0x5849, 0x8677, 0x3390, 0xa0c0, 0x1527,
    0x2904, 0x9ce3, 0x0fb3, 0xba54, 0x646a, 0xd18d, 0x42dd, 0xf73a, 0xb3d8, 0x063f,
    0x956f, 0x2088, 0xfeb6, 0x4b51, 0xd801, 0x6de6, 0xa047, 0x15a0, 0x86f0, 0x3317,
    0xed29, 0x58ce, 0xcb9e, 0x7e79, 0x3a9b, 0x8f7c, 0x1c2c, 0xa9cb, 0x77f5, 0xc212,
    0x5142, 0xe4a5, 0xd886, 0x6d61, 0xfe31, 0x4bd6, 0x95e8, 0x200f, 0xb35f, 0x06b8,
    0x425a, 0xf7bd, 0x64ed, 0xd10a, 0x0f34, 0xbad3, 0x2983, 0x9c64, 0xee3b, 0x5bdc,
    0xc88c, 0x7d6b, 0xa355, 0x16b2, 0x85e2, 0x3005, 0x74e7, 0xc100, 0x5250, 0xe7b7,
    0x3989, 0x8c6e, 0x1f3e, 0xaad9, 0x96fa, 0x231d, 0xb04d, 0x05aa, 0xdb94, 0x6e73,
    0xfd23, 0x48c4, 0x0c26, 0xb9c1, 0x2a91, 0x9f76, 0x4148, 0xf4af, 0x67ff, 0xd218,
    0x1fb9, 0xaa5e, 0x390e, 0x8ce9, 0x52d7, 0xe730, 0x7460, 0xc187, 0x8565, 0x3082,
    0xa3d2, 0x1635, 0xc80b, 0x7dec, 0xeebc, 0x5b5b, 0x6778, 0xd29f, 0x41cf, 0xf428,
    0x2a16, 0x9ff1, 0x0ca1, 0xb946, 0xfda4, 0x4843, 0xdb13, 0x6ef4, 0xb0ca, 0x052d,
    0x967d, 0x239a, 0x4046, 0xf5a1, 0x66f1, 0xd316, 0x0d28, 0xb8cf, 0x2b9f, 0x9e78,
    0xda9a, 0x6f7d, 0xfc2d, 0x49ca, 0x97f4, 0x2213, 0xb143, 0x04a4, 0x3887, 0x8d60,
    0x1e30, 0xabd7, 0x75e9, 0xc00e, 0x535e, 0xe6b9, 0xa25b, 0x17bc, 0x84ec, 0x310b,
    0xef35, 0x5ad2, 0xc982, 0x7c65, 0xb1c4, 0x0423, 0x9773, 0x2294, 0xfcaa, 0x494d,
    0xda1d, 0x6ffa, 0x2b18, 0x9eff, 0x0daf, 0xb848, 0x6676, 0xd391, 0x40c1, 0xf526,
    0xc905, 0x7ce2, 0xefb2, 0x5a55, 0x846b, 0x318c, 0xa2dc, 0x173b, 0x53d9, 0xe63e,
    0x756e, 0xc089, 0x1eb7, 0xab50, 0x3800, 0x8de7},
   {0xc20e, 0x9d6c, 0x7cca, 0x23a8, 0xf2ff, 0xad9d, 0x4c3b, 0x1359, 0xa3ec, 0xfc8e,
    0x1d28, 0x424a, 0x931d, 0xcc7f, 0x2dd9, 0x72bb, 0x01ca, 0x5ea8, 0xbf0e, 0xe06c,
    0x313b, 0x6e59, 0x8fff, 0xd09d, 0x6028, 0x3f4a, 0xdeec, 0x818e, 0x50d9, 0x0fbb,
    0xee1d, 0xb17f, 0x08ff, 0x579d, 0xb63b, 0xe959, 0x380e, 0x676c, 0x86ca, 0xd9a8,
    0x691d, 0x367f, 0xd7d9, 0x88bb, 0x59ec, 0x068e, 0xe728, 0xb84a, 0xcb3b, 0x9459,
    0x75ff, 0x2a9d, 0xfbca, 0xa4a8, 0x450e, 0x1a6c, 0xaad9, 0xf5bb, 0x141d, 0x4b7f,
    0x9a28, 0xc54a, 0x24ec, 0x7b8e, 0x1a95, 0x45f7, 0xa451, 0xfb33, 0x2a64, 0x7506,
    0x94a0, 0xcbc2, 0x7b77, 0x2415, 0xc5b3, 0x9ad1, 0x4b86, 0x14e4, 0xf542, 0xaa20,
    0xd951, 0x8633, 0x6795, 0x38f7, 0xe9a0, 0xb6c2, 0x5764, 0x0806, 0xb8b3, 0xe7d1,
    0x0677, 0x5915, 0x8842, 0xd720, 0x3686, 0x69e4, 0xd064, 0x8f06, 0x6ea0, 0x31c2,
    0xe095, 0xbff7, 0x5e51, 0x0133, 0xb186, 0xeee4, 0x0f42, 0x5020, 0x8177, 0xde15,
    0x3fb3, 0x60d1, 0x13a0, 0x4cc2, 0xad64, 0xf206, 0x2351, 0x7c33, 0x9d95, 0xc2f7,
    0x7242, 0x2d20, 0xcc86, 0x93e4, 0x42b3, 0x1dd1, 0xfc77, 0xa315, 0x3e41, 0x6123,
    0x8085, 0xdfe7, 0x0eb0, 0x51d2, 0xb074, 0xef16, 0x5fa3, 0x00c1, 0xe167, 0xbe05,
    0x6f52, 0x3030, 0xd196, 0x8ef4, 0xfd85, 0xa2e7, 0x4341, 0x1c23, 0xcd74, 0x9216,
    0x73b0, 0x2cd2, 0x9c67, 0xc305, 0x22a3, 0x7dc1, 0xac96, 0xf3f4, 0x1252, 0x4d30,
    0xf4b0, 0xabd2, 0x4a74, 0x1516, 0xc441, 0x9b23, 0x7a85, 0x25e7, 0x9552, 0xca30,
    0x2b96, 0x74f4, 0xa5a3, 0xfac1, 0x1b67, 0x4405, 0x3774, 0x6816, 0x89b0, 0xd6d2,
    0x0785, 0x58e7, 0xb941, 0xe623, 0x5696, 0x09f4, 0xe852, 0xb730, 0x6667, 0x3905,
    0xd8a3, 0x87c1, 0xe6da, 0xb9b8, 0x581e, 0x077c, 0xd62b, 0x8949, 0x68ef, 0x378d,
    0x8738, 0xd85a, 0x39fc, 0x669e, 0xb7c9, 0xe8ab, 0x090d, 0x566f, 0x251e, 0x7a7c,
    0x9bda, 0xc4b8, 0x15ef, 0x4a8d, 0xab2b, 0xf449, 0x44fc, 0x1b9e, 0xfa38, 0xa55a,
    0x740d, 0x2b6f, 0xcac9, 0x95ab, 0x2c2b, 0x7349, 0x92ef, 0xcd8d, 0x1cda, 0x43b8,
    0xa21e, 0xfd7c, 0x4dc9, 0x12ab, 0xf30d, 0xac6f, 0x7d38, 0x225a, 0xc3fc, 0x9c9e,
    0xefef, 0xb08d, 0x512b, 0x0e49, 0xdf1e, 0x807c, 0x61da, 0x3eb8, 0x8e0d, 0xd16f,
    0x30c9, 0x6fab, 0xbefc, 0xe19e, 0x0038, 0x5f5a},
   {0x4a8f, 0x5c9d, 0x66ab, 0x70b9, 0x12c7, 0x04d5, 0x3ee3, 0x28f1, 0xfa1f, 0xec0d,
    0xd63b, 0xc029, 0xa257, 0xb445, 0x8e73, 0x9861, 0x66d6, 0x70c4, 0x4af2, 0x5ce0,
    0x3e9e, 0x288c, 0x12ba, 0x04a8, 0xd646, 0xc054, 0xfa62, 0xec70, 0x8e0e, 0x981c,
    0xa22a, 0xb438, 0x123d, 0x042f, 0x3e19, 0x280b, 0x4a75, 0x5c67, 0x6651, 0x7043,
    0xa2ad, 0xb4bf, 0x8e89, 0x989b, 0xfae5, 0xecf7, 0xd6c1, 0xc0d3, 0x3e64, 0x2876,
    0x1240, 0x0452, 0x662c, 0x703e, 0x4a08, 0x5c1a, 0x8ef4, 0x98e6, 0xa2d0, 0xb4c2,
    0xd6bc, 0xc0ae, 0xfa98, 0xec8a, 0xfbeb, 0xedf9, 0xd7cf, 0xc1dd, 0xa3a3, 0xb5b1,
    0x8f87, 0x9995, 0x4b7b, 0x5d69, 0x675f, 0x714d, 0x1333, 0x0521, 0x3f17, 0x2905,
    0xd7b2, 0xc1a0, 0xfb96, 0xed84, 0x8ffa, 0x99e8, 0xa3de, 0xb5cc, 0x6722, 0x7130,
    0x4b06, 0x5d14, 0x3f6a, 0x2978, 0x134e, 0x055c, 0xa359, 0xb54b, 0x8f7d, 0x996f,
    0xfb11, 0xed03, 0xd735, 0xc127, 0x13c9, 0x05db, 0x3fed, 0x29ff, 0x4b81, 0x5d93,
    0x67a5, 0x71b7, 0x8f00, 0x9912, 0xa324, 0xb536, 0xd748, 0xc15a, 0xfb6c, 0xed7e,
    0x3f90, 0x2982, 0x13b4, 0x05a6, 0x67d8, 0x71ca, 0x4bfc, 0x5dee, 0x653e, 0x732c,
    0x491a, 0x5f08, 0x3d76, 0x2b64, 0x1152, 0x0740, 0xd5ae, 0xc3bc, 0xf98a, 0xef98,
    0x8de6, 0x9bf4, 0xa1c2, 0xb7d0, 0x4967, 0x5f75, 0x6543, 0x7351, 0x112f, 0x073d,
    0x3d0b, 0x2b19, 0xf9f7, 0xefe5, 0xd5d3, 0xc3c1, 0xa1bf, 0xb7ad, 0x8d9b, 0x9b89,
    0x3d8c, 0x2b9e, 0x11a8, 0x07ba, 0x65c4, 0x73d6, 0x49e0, 0x5ff2, 0x8d1c, 0x9b0e,
    0xa138, 0xb72a, 0xd554, 0xc346, 0xf970, 0xef62, 0x11d5, 0x07c7, 0x3df1, 0x2be3,
    0x499d, 0x5f8f, 0x65b9, 0x73ab, 0xa145, 0xb757, 0x8d61, 0x9b73, 0xf90d, 0xef1f,
    0xd529, 0xc33b, 0xd45a, 0xc248, 0xf87e, 0xee6c, 0x8c12, 0x9a00, 0xa036, 0xb624,
    0x64ca, 0x72d8, 0x48ee, 0x5efc, 0x3c82, 0x2a90, 0x10a6, 0x06b4, 0xf803, 0xee11,
    0xd427, 0xc235, 0xa04b, 0xb659, 0x8c6f, 0x9a7d, 0x4893, 0x5e81, 0x64b7, 0x72a5,
    0x10db, 0x06c9, 0x3cff, 0x2aed, 0x8ce8, 0x9afa, 0xa0cc, 0xb6de, 0xd4a0, 0xc2b2,
    0xf884, 0xee96, 0x3c78, 0x2a6a, 0x105c, 0x064e, 0x6430, 0x7222, 0x4814, 0x5e06,
    0xa0b1, 0xb6a3, 0x8c95, 0x9a87, 0xf8f9, 0xeeeb, 0xd4dd, 0xc2cf, 0x1021, 0x0633,
    0x3c05, 0x2a17, 0x4869, 0x5e7b, 0x644d, 0x725f}
};

unsigned crc16dnp_byte(unsigned crc, void const *mem, size_t len) {
    unsigned char const *data = mem;
    if (data == NULL)
        return 0xffff;
    crc &= 0xffff;
    while (len--)
        crc = (crc >> 8) ^
              table_byte[(crc ^ *data++) & 0xff];
    return crc;
}

// This code assumes that integers are stored little-endian.

unsigned crc16dnp_word(unsigned crc, void const *mem, size_t len) {
    unsigned char const *data = mem;
    if (data == NULL)
        return 0xffff;
    crc &= 0xffff;
    while (len && ((ptrdiff_t)data & 0x7)) {
        crc = (crc >> 8) ^
              table_byte[(crc ^ *data++) & 0xff];
        len--;
    }
    if (len >= 8) {
        do {
            uintmax_t word = crc ^ *(uintmax_t const *)data;
            crc = table_word[7][word & 0xff] ^
                  table_word[6][(word >> 8) & 0xff] ^
                  table_word[5][(word >> 16) & 0xff] ^
                  table_word[4][(word >> 24) & 0xff] ^
                  table_word[3][(word >> 32) & 0xff] ^
                  table_word[2][(word >> 40) & 0xff] ^
                  table_word[1][(word >> 48) & 0xff] ^
                  table_word[0][word >> 56];
            data += 8;
            len -= 8;
        } while (len >= 8);
    }
    while (len--)
        crc = (crc >> 8) ^
              table_byte[(crc ^ *data++) & 0xff];
    return crc;
}

div with dynamic min-height based on browser window height

No hack or js needed. Just apply the following rule to your root element:

min-height: 100%;
height: auto;

It will automatically choose the bigger one from the two as its height, which means if the content is longer than the browser, it will be the height of the content, otherwise, the height of the browser. This is standard css.

Algorithm to randomly generate an aesthetically-pleasing color palette

An answer that shouldn't be overlooked, because it's simple and presents advantages, is sampling of real life photos and paintings. sample as many random pixels as you want random colors on thumbnails of modern art pics, cezanne, van gogh, monnet, photos... the advantage is that you can get colors by theme and that they are organic colors. just put 20 - 30 pics in a folder and random sample a random pic every time.

Conversion to HSV values is a widespread code algorithm for psychologically based palette. hsv is easier to randomize.

How to add a fragment to a programmatically generated layout?

Below is a working code to add a fragment e.g 3 times to a vertical LinearLayout (xNumberLinear). You can change number 3 with any other number or take a number from a spinner!

for (int i = 0; i < 3; i++) {
            LinearLayout linearDummy = new LinearLayout(getActivity());
            linearDummy.setOrientation(LinearLayout.VERTICAL);
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {

                Toast.makeText(getActivity(), "This function works on newer versions of android", Toast.LENGTH_LONG).show();

            } else {
                linearDummy.setId(View.generateViewId());
            }
            fragmentManager.beginTransaction().add(linearDummy.getId(), new SomeFragment(),"someTag1").commit();

            xNumberLinear.addView(linearDummy);
        }

Values of disabled inputs will not be submitted

Disabled controls cannot be successful, and a successful control is "valid" for submission. This is the reason why disabled controls don't submit with the form.

The difference in months between dates in MySQL

As many of the answers here show, the 'right' answer depends on exactly what you need. In my case, I need to round to the closest whole number.

Consider these examples: 1st January -> 31st January: It's 0 whole months, and almost 1 month long. 1st January -> 1st February? It's 1 whole month, and exactly 1 month long.

To get the number of whole (complete) months, use:

SELECT TIMESTAMPDIFF(MONTH, '2018-01-01', '2018-01-31');  => 0
SELECT TIMESTAMPDIFF(MONTH, '2018-01-01', '2018-02-01');  => 1

To get a rounded duration in months, you could use:

SELECT ROUND(TIMESTAMPDIFF(DAY, '2018-01-01', '2018-01-31')*12/365.24); => 1
SELECT ROUND(TIMESTAMPDIFF(DAY, '2018-01-01', '2018-01-31')*12/365.24); => 1

This is accurate to +/- 5 days and for ranges over 1000 years. Zane's answer is obviously more accurate, but it's too verbose for my liking.

In SQL how to compare date values?

Uh, WHERE mydate<='2008-11-25' is the way to do it. That should work.

Do you get an error message? Are you using an ancient version of MySQL?

Edit: The following works fine for me on MySQL 5.x

create temporary table foo(d datetime);
insert into foo(d) VALUES ('2000-01-01');
insert into foo(d) VALUES ('2001-01-01');
select * from foo where d <= '2000-06-01';

Setting up Vim for Python

Re: the dead "Turning Vim Into A Modern Python IDE" link, back in 2013 I saved a copy, that I converted to a HTML page as well as a PDF copy:

http://persagen.com/files/misc/Turning_vim_into_a_modern_Python_IDE.html

http://persagen.com/files/misc/Turning_vim_into_a_modern_Python_IDE.pdf

Edit (Sep 08, 2017) updated URLs.

How to solve error "Missing `secret_key_base` for 'production' environment" (Rails 4.1)

I had the same problem after I used the .gitignore file from https://github.com/github/gitignore/blob/master/Rails.gitignore

Everything worked out fine after I commented the following lines in the .gitignore file.

config/initializers/secret_token.rb
config/secrets.yml

Accessing dict keys like an attribute?

Here's a short example of immutable records using built-in collections.namedtuple:

def record(name, d):
    return namedtuple(name, d.keys())(**d)

and a usage example:

rec = record('Model', {
    'train_op': train_op,
    'loss': loss,
})

print rec.loss(..)

In NetBeans how do I change the Default JDK?

If I remember correctly, you'll need to set the netbeans_jdkhome property in your netbeans config file. Should be in your etc/netbeans.conf file.

Using %f with strftime() in Python to get microseconds

If you want speed, try this:

def _timestamp(prec=0):
    t = time.time()
    s = time.strftime("%H:%M:%S", time.localtime(t))
    if prec > 0:
        s += ("%.9f" % (t % 1,))[1:2+prec]
    return s

Where prec is precision -- how many decimal places you want. Please note that the function does not have issues with leading zeros in fractional part like some other solutions presented here.

How Do I Take a Screen Shot of a UIView?

Apple does not allow:

CGImageRef UIGetScreenImage();

Applications should take a screenshot using the drawRect method as specified in: http://developer.apple.com/library/ios/#qa/qa2010/qa1703.html

Apache shutdown unexpectedly

That is because IIS is automatically running on your machine. IIS occupied both port 80 and 443.

I uninstalled IIS for using Apache httpd.

Checking if an object is a number in C#

You will simply need to do a type check for each of the basic numeric types.

Here's an extension method that should do the job:

public static bool IsNumber(this object value)
{
    return value is sbyte
            || value is byte
            || value is short
            || value is ushort
            || value is int
            || value is uint
            || value is long
            || value is ulong
            || value is float
            || value is double
            || value is decimal;
}

This should cover all numeric types.

Update

It seems you do actually want to parse the number from a string during deserialisation. In this case, it would probably just be best to use double.TryParse.

string value = "123.3";
double num;
if (!double.TryParse(value, out num))
    throw new InvalidOperationException("Value is not a number.");

Of course, this wouldn't handle very large integers/long decimals, but if that is the case you just need to add additional calls to long.TryParse / decimal.TryParse / whatever else.

XPath: select text node

your xpath should work . i have tested your xpath and mine in both MarkLogic and Zorba Xquery/ Xpath implementation.

Both should work.

/node/child::text()[1] - should return Text1
/node/child::text()[2] - should return text2


/node/text()[1] - should return Text1
/node/text()[2] - should return text2

SQL Server 2012 column identity increment jumping from 6 to 1000+ on 7th entry

This is all perfectly normal. Microsoft added sequences in SQL Server 2012, finally, i might add and changed the way identity keys are generated. Have a look here for some explanation.

If you want to have the old behaviour, you can:

  1. use trace flag 272 - this will cause a log record to be generated for each generated identity value. The performance of identity generation may be impacted by turning on this trace flag.
  2. use a sequence generator with the NO CACHE setting (http://msdn.microsoft.com/en-us/library/ff878091.aspx)

File to import not found or unreadable: compass

I was uninstalled compass 1.0.1 and install compass 0.12.7, this fix problem for me

$ sudo gem uninstall compass
$ sudo gem install compass -v 0.12.7