Programs & Examples On #Javaw

The javaw tool launches a Java application. It does this by starting a Java runtime environment, loading a specified class, and invoking that class's main method.

How to find where javaw.exe is installed?

To find "javaw.exe" in windows I would use (using batch)

for /f tokens^=2^ delims^=^" %%i in ('reg query HKEY_CLASSES_ROOT\jarfile\shell\open\command /ve') do set JAVAW_PATH=%%i

It should work in Windows XP and Seven, for JRE 1.6 and 1.7. Should catch the latest installed version.

What is the difference between 'java', 'javaw', and 'javaws'?

java.exe is associated with the console, whereas javaw.exe doesn't have any such association. So, when java.exe is run, it automatically opens a command prompt window where output and error streams are shown.

Difference between java.exe and javaw.exe

The difference is in the subsystem that each executable targets.

  • java.exe targets the CONSOLE subsystem.
  • javaw.exe targets the WINDOWS subsystem.

How to obtain a QuerySet of all rows, with specific fields for each one of them?

We can select required fields over values.

Employee.objects.all().values('eng_name','rank')

How to get a random number between a float range?

random.uniform(a, b) appears to be what your looking for. From the docs:

Return a random floating point number N such that a <= N <= b for a <= b and b <= N <= a for b < a.

See here.

Font is not available to the JVM with Jasper Reports

Create jasper report in multiple languages(Unicode)

1)Install font in ireport desginer

2)create extension of font(we will use it in applications classpath)

3)install font on os(optional)

4)paste all .ttf of font in jre->lib->fonts directory (otherwise web application will throw error font is not available to JVM)

How do I get the currently-logged username from a Windows service in .NET?

Just in case someone is looking for user Display Name as opposed to User Name, like me.

Here's the treat :

System.DirectoryServices.AccountManagement.UserPrincipal.Current.DisplayName.

Add Reference to System.DirectoryServices.AccountManagement in your project.

Make an image width 100% of parent div, but not bigger than its own width

Found this post on a Google search, and it solved my issue thanks to @jwal reply, but I made one addition to his solution.

img.content.x700 {
  width: auto !important; /*override the width below*/
  width: 100%;
  max-width: 678px;
  float: left;
  clear: both;
}

With the above I changed the max-width to the dimensions of the content container that my image is in. In this case it is: container width - padding - boarder = max width

This way my image won't break out of the containing div, and I can still float the image within the content div.

I've tested in IE 9, FireFox 18.0.2 and Chrome 25.0.1364.97, Safari iOS and seems to work.

Additional: I tested this on an image 1024px wide displayed at 678px (the max width), and an image 500px wide displayed at 500px (width of the image).

UIButton action in table view cell

With Swift 5 this is what, worked for me!!

Step 1. Created IBOutlet for UIButton in My CustomCell.swift

class ListProductCell: UITableViewCell {
@IBOutlet weak var productMapButton: UIButton!
//todo
}

Step 2. Added action method in CellForRowAtIndex method and provided method implementation in the same view controller

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ListProductCell") as! ListProductCell
cell.productMapButton.addTarget(self, action: #selector(ListViewController.onClickedMapButton(_:)), for: .touchUpInside)
return cell
    }

@objc func onClickedMapButton(_ sender: Any?) {

        print("Tapped")
    }

What is the iPad user agent?

iPad 2 under 4.3.5:

Mozilla/5.0 (iPad; U; CPU OS 4_3_5 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8L1 Safari/6533.18.5

Execute jar file with multiple classpath libraries from command prompt

You cannot use both -jar and -cp on the command line - see the java documentation that says that if you use -jar:

the JAR file is the source of all user classes, and other user class path settings are ignored.

You could do something like this:

java -cp lib\*.jar;. myproject.MainClass

Notice the ;. in the -cp argument, to work around a Java command-line bug. Also, please note that this is the Windows version of the command. The path separator on Unix is :.

What's the best way to set a single pixel in an HTML5 canvas?

function setPixel(imageData, x, y, r, g, b, a) {
    var index = 4 * (x + y * imageData.width);
    imageData.data[index+0] = r;
    imageData.data[index+1] = g;
    imageData.data[index+2] = b;
    imageData.data[index+3] = a;
}

Grep characters before and after match?

grep -E -o ".{0,5}test_pattern.{0,5}" test.txt 

This will match up to 5 characters before and after your pattern. The -o switch tells grep to only show the match and -E to use an extended regular expression. Make sure to put the quotes around your expression, else it might be interpreted by the shell.

insert data into database with codeigniter

Try this in your model:

function order_summary_insert()
    $OrderLines=$this->input->post('orderlines');
    $CustomerName=$this->input->post('customer');
    $data = array(
        'OrderLines'=>$OrderLines,
        'CustomerName'=>$CustomerName
    );

    $this->db->insert('Customer_Orders',$data);
}

Try to use controller just to control the view and models always post your values in model. it makes easy to understand. Your controller will be:

function new_blank_order_summary() {
    $this->sales_model->order_summary_insert($data);
    $this->load->view('sales/new_blank_order_summary');
}

Clear the entire history stack and start a new activity on Android

With Android's Newer Version >= API 16 use finishAffinity()

approach is suitable for >= API 16.

Intent mIntent = new Intent(mContext,MainActivity.class);
finishAffinity();
startActivity(mIntent);
  • Its is same as starting new Activity, and clear all stack.
  • OR Restart to MainActivity/FirstActivity.

Convert a string to a datetime

Try to use DateTime.ParseExact method, in which you can specify both of datetime mask and original parsed string. You can read about it here: MSDN: DateTime.ParseExact

How do I add a custom script to my package.json file that runs a javascript file?

I have created the following, and it's working on my system. Please try this:

package.json:

{
  "name": "test app",
  "version": "1.0.0",
  "scripts": {
    "start": "node script1.js"   
  }
}

script1.js:

console.log('testing')

From your command line run the following command:

npm start

Additional use case

My package.json file has generally the following scripts, which enable me to watch my files for typescript, sass compilations and running a server as well.

 "scripts": {
    "start": "concurrently \"sass --watch ./style/sass:./style/css\" \"npm run tsc:w\" \"npm run lite\" ",    
    "tsc": "tsc",
    "tsc:w": "tsc -w", 
    "lite": "lite-server",
    "typings": "typings",
    "postinstall": "typings install" 
  }

SQL UPDATE SET one column to be equal to a value in a related table referenced by a different column?

below works for mysql

update table1 INNER JOIN table2 on table1.col1 =  table2.col1
set table1.col1 =  table2.col2

Url.Action parameters?

The following is the correct overload (in your example you are missing a closing } to the routeValues anonymous object so your code will throw an exception):

<a href="<%: Url.Action("GetByList", "Listing", new { name = "John", contact = "calgary, vancouver" }) %>">
    <span>People</span>
</a>

Assuming you are using the default routes this should generate the following markup:

<a href="/Listing/GetByList?name=John&amp;contact=calgary%2C%20vancouver">
    <span>People</span>
</a>

which will successfully invoke the GetByList controller action passing the two parameters:

public ActionResult GetByList(string name, string contact) 
{
    ...
}

Run javascript script (.js file) in mongodb including another file inside js

Yes you can. The default location for script files is data/db

If you put any script there you can call it as

load("myjstest.js")      // or 
load("/data/db/myjstest.js")

Pass parameter from a batch file to a PowerShell script

Add the parameter declaration at the top of ps1 file

test.ps1

param(
  # Our preferred encoding
  [parameter(Mandatory=$false)]
  [ValidateSet("UTF8","Unicode","UTF7","ASCII","UTF32","BigEndianUnicode")]
  [string]$Encoding = "UTF8"
)

write ("Encoding : {0}" -f $Encoding)

Result

C:\temp> .\test.ps1 -Encoding ASCII
Encoding : ASCII

How to use ConfigurationManager

I found some answers, but I don't know if it is the right way.This is my solution for now. Fortunatelly it didn´t broke my design mode.

    `
    /// <summary>
    /// set config, if key is not in file, create
    /// </summary>
    /// <param name="key">Nome do parâmetro</param>
    /// <param name="value">Valor do parâmetro</param>
    public static void SetConfig(string key, string value)
    {
        var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        var settings = configFile.AppSettings.Settings;
        if (settings[key] == null)
        {
            settings.Add(key, value);
        }
        else
        {
            settings[key].Value = value;
        }
        configFile.Save(ConfigurationSaveMode.Modified);
        ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
    }

    /// <summary>
    /// Get key value, if not found, return null
    /// </summary>
    /// <param name="key"></param>
    /// <returns>null if key is not found, else string with value</returns>
    public static string GetConfig(string key)
    {
        return ConfigurationManager.AppSettings[key];
    }`

pthread_join() and pthread_exit()

The typical use is

void* ret = NULL;
pthread_t tid = something; /// change it suitably
if (pthread_join (tid, &ret)) 
   handle_error();
// do something with the return value ret

Why can't Visual Studio find my DLL?

To add to Oleg's answer:

I was able to find the DLL at runtime by appending Visual Studio's $(ExecutablePath) to the PATH environment variable in Configuration Properties->Debugging. This macro is exactly what's defined in the Configuration Properties->VC++ Directories->Executable Directories field*, so if you have that setup to point to any DLLs you need, simply adding this to your PATH makes finding the DLLs at runtime easy!

* I actually don't know if the $(ExecutablePath) macro uses the project's Executable Directories setting or the global Property Pages' Executable Directories setting. Since I have all of my libraries that I often use configured through the Property Pages, these directories show up as defaults for any new projects I create.

Node.js on multi-core machines

Multi-node harnesses all the cores that you may have.
Have a look at http://github.com/kriszyp/multi-node.

For simpler needs, you can start up multiple copies of node on different port numbers and put a load balancer in front of them.

How to view changes made to files on a certain revision in Subversion

With this command you will see all changes in the repository path/to/repo that were committed in revision <revision>:

svn diff -c <revision> path/to/repo

The -c indicates that you would like to look at a changeset, but there are many other ways you can look at diffs and changesets. For example, if you would like to know which files were changed (but not how), you can issue

svn log -v -r <revision>

Or, if you would like to show at the changes between two revisions (and not just for one commit):

svn diff -r <revA>:<revB> path/to/repo

Format Date output in JSF

If you use OmniFaces you can also use it's EL functions like of:formatDate() to format Date objects. You would use it like this:

<h:outputText value="#{of:formatDate(someBean.dateField, 'dd.MM.yyyy HH:mm')}" />

This way you can not only use it for output but also to pass it on to other JSF components.

Read Excel sheet in Powershell

There is the possibility of making something really more cool!

# Powershell 
$xl = new-object -ComObject excell.application
$doc=$xl.workbooks.open("Filepath")
$doc.Sheets.item(1).rows |
% { ($_.value2 | Select-Object -first 3 | Select-Object -last 2) -join "," }

adb is not recognized as internal or external command on windows

If you go to your android-sdk/tools folder I think you'll find a message :

The adb tool has moved to platform-tools/

If you don't see this directory in your SDK, launch the SDK and AVD Manager (execute the android tool) and install "Android SDK Platform-tools"

Please also update your PATH environment variable to include the platform-tools/ directory, so you can execute adb from any location.

So you should also add C:/android-sdk/platform-tools to you environment path. Also after you modify the PATH variable make sure that you start a new CommandPrompt window.

Cannot create PoolableConnectionFactory (Io exception: The Network Adapter could not establish the connection)

Most of the cases issue is due to problem with hostname . Please check the hostname ,some times database team will maintain many hostname for connecting same database . Please check with database team regarding this connection issue.

What is the most "pythonic" way to iterate over a list in chunks?

You can use partition or chunks function from funcy library:

from funcy import partition

for a, b, c, d in partition(4, ints):
    foo += a * b * c * d

These functions also has iterator versions ipartition and ichunks, which will be more efficient in this case.

You can also peek at their implementation.

How to convert string values from a dictionary, into int/float datatypes?

If that's your exact format, you can go through the list and modify the dictionaries.

for item in list_of_dicts:
    for key, value in item.iteritems():
        try:
            item[key] = int(value)
        except ValueError:
            item[key] = float(value)

If you've got something more general, then you'll have to do some kind of recursive update on the dictionary. Check if the element is a dictionary, if it is, use the recursive update. If it's able to be converted into a float or int, convert it and modify the value in the dictionary. There's no built-in function for this and it can be quite ugly (and non-pythonic since it usually requires calling isinstance).

What is the difference between Swing and AWT?

Several consequences result from this difference between AWT and Swing.

AWT is a thin layer of code on top of the OS, whereas Swing is much larger. Swing also has very much richer functionality. Using AWT, you have to implement a lot of things yourself, while Swing has them built in. For GUI-intensive work, AWT feels very primitive to work with compared to Swing. Because Swing implements GUI functionality itself rather than relying on the host OS, it can offer a richer environment on all platforms Java runs on. AWT is more limited in supplying the same functionality on all platforms because not all platforms implement the same-looking controls in the same ways.

Swing components are called "lightweight" because they do not require a native OS object to implement their functionality. JDialog and JFrame are heavyweight, because they do have a peer. So components like JButton, JTextArea, etc., are lightweight because they do not have an OS peer.

A peer is a widget provided by the operating system, such as a button object or an entry field object.

Multiple simultaneous downloads using Wget?

Consider using Regular Expressions or FTP Globbing. By that you could start wget multiple times with different groups of filename starting characters depending on their frequency of occurrence.

This is for example how I sync a folder between two NAS:

wget --recursive --level 0 --no-host-directories --cut-dirs=2 --no-verbose --timestamping --backups=0 --bind-address=10.0.0.10 --user=<ftp_user> --password=<ftp_password> "ftp://10.0.0.100/foo/bar/[0-9a-hA-H]*" --directory-prefix=/volume1/foo &
wget --recursive --level 0 --no-host-directories --cut-dirs=2 --no-verbose --timestamping --backups=0 --bind-address=10.0.0.11 --user=<ftp_user> --password=<ftp_password> "ftp://10.0.0.100/foo/bar/[!0-9a-hA-H]*" --directory-prefix=/volume1/foo &

The first wget syncs all files/folders starting with 0, 1, 2... F, G, H and the second thread syncs everything else.

This was the easiest way to sync between a NAS with one 10G ethernet port (10.0.0.100) and a NAS with two 1G ethernet ports (10.0.0.10 and 10.0.0.11). I bound the two wget threads through --bind-address to the different ethernet ports and called them parallel by putting & at the end of each line. By that I was able to copy huge files with 2x 100 MB/s = 200 MB/s in total.

How do I import modules or install extensions in PostgreSQL 9.1+?

The extensions available for each version of Postgresql vary. An easy way to check which extensions are available is, as has been already mentioned:

SELECT * FROM pg_available_extensions;

If the extension that you are looking for is available, you can install it using:

CREATE EXTENSION 'extensionName';

or if you want to drop it use:

DROP EXTENSION 'extensionName';

With psql you can additionally check if the extension has been successfully installed using \dx, and find more details about the extension using \dx+ extensioName. It returns additional information about the extension, like which packages are used with it.

If the extension is not available in your Postgres version, then you need to download the necessary binary files and libraries and locate it them at /usr/share/conrib

The value violated the integrity constraints for the column

It usually happens when Allow Nulls option is unchecked.

Solution:

  1. Look at the name of the column for this error/warning.
  2. Go to SSMS and find the table
  3. Allow Null for that Column
  4. Save the table
  5. Rerun the SSIS

Try these steps. It worked for me.

See this link

How to detect when an Android app goes to the background and come back to the foreground

What I did is make sure that all in-app activities are launched with startActivityForResult then checking if onActivityResult was called before onResume. If it wasn't, it means we just returned from somewhere outside our app.

boolean onActivityResultCalledBeforeOnResume;

@Override
public void startActivity(Intent intent) {
    startActivityForResult(intent, 0);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);
    onActivityResultCalledBeforeOnResume = true;
}

@Override
protected void onResume() {
    super.onResume();
    if (!onActivityResultCalledBeforeOnResume) {
        // here, app was brought to foreground
    }
    onActivityResultCalledBeforeOnResume = false;
}

SQL Left Join first match only

Turns out I was doing it wrong, I needed to perform a nested select first of just the important columns, and do a distinct select off that to prevent trash columns of 'unique' data from corrupting my good data. The following appears to have resolved the issue... but I will try on the full dataset later.

SELECT DISTINCT P2.*
FROM (
  SELECT
      IDNo
    , FirstName
    , LastName
  FROM people P
) P2

Here is some play data as requested: http://sqlfiddle.com/#!3/050e0d/3

CREATE TABLE people
(
       [entry] int
     , [IDNo] varchar(3)
     , [FirstName] varchar(5)
     , [LastName] varchar(7)
);

INSERT INTO people
    (entry,[IDNo], [FirstName], [LastName])
VALUES
    (1,'uqx', 'bob', 'smith'),
    (2,'abc', 'john', 'willis'),
    (3,'ABC', 'john', 'willis'),
    (4,'aBc', 'john', 'willis'),
    (5,'WTF', 'jeff', 'bridges'),
    (6,'Sss', 'bill', 'doe'),
    (7,'sSs', 'bill', 'doe'),
    (8,'ssS', 'bill', 'doe'),
    (9,'ere', 'sally', 'abby'),
    (10,'wtf', 'jeff', 'bridges')
;

Freemarker iterating over hashmap keys

FYI, it looks like the syntax for retrieving the values has changed according to:

http://freemarker.sourceforge.net/docs/ref_builtins_hash.html

<#assign h = {"name":"mouse", "price":50}>
<#assign keys = h?keys>
<#list keys as key>${key} = ${h[key]}; </#list>

CMake: How to build external projects and include their targets

cmake's ExternalProject_Add indeed can used, but what I did not like about it - is that it performs something during build, continuous poll, etc... I would prefer to build project during build phase, nothing else. I have tried to override ExternalProject_Add in several attempts, unfortunately without success.

Then I have tried also to add git submodule, but that drags whole git repository, while in certain cases I need only subset of whole git repository. What I have checked - it's indeed possible to perform sparse git checkout, but that require separate function, which I wrote below.

#-----------------------------------------------------------------------------
#
# Performs sparse (partial) git checkout
#
#   into ${checkoutDir} from ${url} of ${branch}
#
# List of folders and files to pull can be specified after that.
#-----------------------------------------------------------------------------
function (SparseGitCheckout checkoutDir url branch)
    if(EXISTS ${checkoutDir})
        return()
    endif()

    message("-------------------------------------------------------------------")
    message("sparse git checkout to ${checkoutDir}...")
    message("-------------------------------------------------------------------")

    file(MAKE_DIRECTORY ${checkoutDir})

    set(cmds "git init")
    set(cmds ${cmds} "git remote add -f origin --no-tags -t master ${url}")
    set(cmds ${cmds} "git config core.sparseCheckout true")

    # This command is executed via file WRITE
    # echo <file or folder> >> .git/info/sparse-checkout")

    set(cmds ${cmds} "git pull --depth=1 origin ${branch}")

    # message("In directory: ${checkoutDir}")

    foreach( cmd ${cmds})
        message("- ${cmd}")
        string(REPLACE " " ";" cmdList ${cmd})

        #message("Outfile: ${outFile}")
        #message("Final command: ${cmdList}")

        if(pull IN_LIST cmdList)
            string (REPLACE ";" "\n" FILES "${ARGN}")
            file(WRITE ${checkoutDir}/.git/info/sparse-checkout ${FILES} )
        endif()

        execute_process(
            COMMAND ${cmdList}
            WORKING_DIRECTORY ${checkoutDir}
            RESULT_VARIABLE ret
        )

        if(NOT ret EQUAL "0")
            message("error: previous command failed, see explanation above")
            file(REMOVE_RECURSE ${checkoutDir})
            break()
        endif()
    endforeach()

endfunction()


SparseGitCheckout(${CMAKE_BINARY_DIR}/catch_197 https://github.com/catchorg/Catch2.git v1.9.7 single_include)
SparseGitCheckout(${CMAKE_BINARY_DIR}/catch_master https://github.com/catchorg/Catch2.git master single_include)

I have added two function calls below just to illustrate how to use the function.

Someone might not like to checkout master / trunk, as that one might be broken - then it's always possible to specify specific tag.

Checkout will be performed only once, until you clear the cache folder.

How do I auto-hide placeholder text upon focus using css or jquery?

HTML:

<input type="text" name="name" placeholder="enter your text" id="myInput" />

jQuery:

$('#myInput').focus(function(){
  $(this).attr('placeholder','');
});
$('#myInput').focusout(function(){
  $(this).attr('placeholder','enter your text');
});

Laravel - Session store not set on request

Laravel [5.4]

My solution was to use global session helper: session()

Its functionality is a little bit harder than $request->session().

writing:

session(['key'=>'value']);

pushing:

session()->push('key', $notification);

retrieving:

session('key');

How to extract year and month from date in PostgreSQL without using to_char() function?

You can truncate all information after the month using date_trunc(text, timestamp):

select date_trunc('month',created_at)::date as date 
from orders 
order by date DESC;


Example:

Input:

created_at = '2019-12-16 18:28:13'

Output 1:

date_trunc('day',created_at)
// 2019-12-16 00:00:00

Output 2:

date_trunc('day',created_at)::date 
// 2019-12-16

Output 3:

date_trunc('month',created_at)::date 
// 2019-12-01

Output 4:

date_trunc('year',created_at)::date 
// 2019-01-01

How to get changes from another branch

You can use rebase, for instance, git rebase our-team when you are on your branch featurex

It will move the start point of the branch at the end of your our-team branch, merging all changes in your featurex branch.

How to align two elements on the same line without changing HTML

Using display:inline-block

#element1 {display:inline-block;margin-right:10px;} 
#element2 {display:inline-block;} 

Example

How do I fix a .NET windows application crashing at startup with Exception code: 0xE0434352?

It looks like this error 0xe0434352 applies to a number of different errors.

In case it helps anyone, I ran into this error when I was trying to install my application on a new Windows 10 installation. It worked on other machines, and looked like the app momentarily would start before dying. After much trial and error the problem turned out to be that the app required DirectX9. Though a later version of DirectX was present it had to have version 9. Hope that saves someone some frustration.

Calling stored procedure with return value

I see the other one is closed. So basically here's the rough of my code. I think you are missing the string cmd comment. For example if my store procedure is call:DBO.Test. I would need to write cmd="DBO.test". Then do command type equal to store procedure, and blah blah blah

Connection.open();
String cmd="DBO.test"; //the command
Sqlcommand mycommand;

Wait 5 seconds before executing next line

using angularjs:

$timeout(function(){
if(yourvariable===-1){
doSomeThingAfter5Seconds();
}
},5000)

Can I set variables to undefined or pass undefined as an argument?

The basic difference is that undefined and null represent different concepts.

If only null was available, you would not be able to determine whether null was set intentionally as the value or whether the value has not been set yet unless you used cumbersome error catching: eg

var a;

a == null; // This is true
a == undefined; // This is true;
a === undefined; // This is true;

However, if you intentionally set the value to null, strict equality with undefined fails, thereby allowing you to differentiate between null and undefined values:

var b = null;
b == null; // This is true
b == undefined; // This is true;
b === undefined; // This is false;

Check out the reference here instead of relying on people dismissively saying junk like "In summary, undefined is a JavaScript-specific mess, which confuses everyone". Just because you are confused, it does not mean that it is a mess.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined

This behaviour is also not specific to JavaScript and it completes the generalised concept that a boolean result can be true, false, unknown (null), no value (undefined), or something went wrong (error).

http://en.wikipedia.org/wiki/Undefined_value

Maintain image aspect ratio when changing height

To keep images from stretching in either axis inside a flex parent I have found a couple of solutions.

You can try using object-fit on the image which, e.g.

object-fit: contain;

http://jsfiddle.net/ykw3sfjd/

Or you can add flex-specfic rules which may work better in some cases.

align-self: center;
flex: 0 0 auto;

CSS blur on background image but not on content

jsfiddle

.blur-bgimage {
    overflow: hidden;
    margin: 0;
    text-align: left;
}
.blur-bgimage:before {
    content: "";
    position: absolute;
    width : 100%;
    height: 100%;
    background: inherit;
    z-index: -1;

    filter        : blur(10px);
    -moz-filter   : blur(10px);
    -webkit-filter: blur(10px);
    -o-filter     : blur(10px);

    transition        : all 2s linear;
    -moz-transition   : all 2s linear;
    -webkit-transition: all 2s linear;
    -o-transition     : all 2s linear;
}

You can blur the body background image by using the body's :before pseudo class to inherit the image and then blurring it. Wrap all that into a class and use javascript to add and remove the class to blur and unblur.

Transport security has blocked a cleartext HTTP

On 2015-09-25 (after Xcode updates on 2015-09-18):

I used a non-lazy method, but it didn't work. The followings are my tries.

First,

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>www.xxx.yyy.zzz</key>
        <dict>
            <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
            <true/>
            <key>NSTemporaryExceptionMinimumTLSVersion</key>
            <string>TLSv1.1</string>
            <key>NSIncludesSubdomains</key>
            <true/>
        </dict>
    </dict>
</dict>

And second,

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>www.xxx.yyy.zzz</key>
        <dict>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
            <key>NSExceptionMinimumTLSVersion</key>
            <string>TLSv1.1</string>
            <key>NSIncludesSubdomains</key>
            <true/>
        </dict>
    </dict>
</dict>

Finally, I used the lazy method:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

It might be a little insecure, but I couldn't find other solutions.

SQL how to make null values come last when sorting ascending

(A "bit" late, but this hasn't been mentioned at all)

You didn't specify your DBMS.

In standard SQL (and most modern DBMS like Oracle, PostgreSQL, DB2, Firebird, Apache Derby, HSQLDB and H2) you can specify NULLS LAST or NULLS FIRST:

Use NULLS LAST to sort them to the end:

select *
from some_table
order by some_column DESC NULLS LAST

Getting pids from ps -ef |grep keyword

ps -ef | grep KEYWORD | grep -v grep | awk '{print $2}'

How can I catch a ctrl-c event?

You have to catch the SIGINT signal (we are talking POSIX right?)

See @Gab Royer´s answer for sigaction.

Example:

#include <signal.h>
#include <stdlib.h>
#include <stdio.h>

void my_handler(sig_t s){
           printf("Caught signal %d\n",s);
           exit(1); 

}

int main(int argc,char** argv)
{
   signal (SIGINT,my_handler);

   while(1);
   return 0;

}

How do I check whether a checkbox is checked in jQuery?

1) If your HTML markup is:

<input type="checkbox"  />

attr used:

$(element).attr("checked"); // Will give you undefined as initial value of checkbox is not set

If prop is used:

$(element).prop("checked"); // Will give you false whether or not initial value is set

2) If your HTML markup is:

 <input type="checkbox"  checked="checked" />// May be like this also  checked="true"

attr used:

$(element).attr("checked") // Will return checked whether it is checked="true"

Prop used:

$(element).prop("checked") // Will return true whether checked="checked"

How to clear exisiting dropdownlist items when its content changes?

Using ddl.Items.Clear() will clear the dropdownlist however you must be sure that your dropdownlist is not set to:

AppendDataBoundItems="True"

This option will cause the rebound data to be appended to the existing list which will NOT be cleared prior to binding.

SOLUTION

Add AppendDataBoundItems="False" to your dropdownlist.

Now when data is rebound it will automatically clear all existing data beforehand.

Protected Sub ddl1_SelectedIndexChanged(sender As Object, e As EventArgs)
    ddl2.DataSource = sql2
    ddl2.DataBind()
End Sub

NOTE: This may not be suitable in all situations as appenddatbound items can cause your dropdown to append its own data on each change of the list.


TOP TIP

Still want a default list item adding to your dropdown but need to rebind data?

Use AppendDataBoundItems="False" to prevent duplication data on postback and then directly after binding your dropdownlist insert a new default list item.

ddl.Items.Insert(0, New ListItem("Select ...", ""))

How can I output leading zeros in Ruby?

Use String#next as the counter.

>> n = "000"
>> 3.times { puts "file_#{n.next!}" }
file_001
file_002
file_003

next is relatively 'clever', meaning you can even go for

>> n = "file_000"
>> 3.times { puts n.next! }
file_001
file_002
file_003

add new element in laravel collection object

If you want to add a product into the array you can use:

$item['product'] = $product;

Change Input to Upper Case

Solutions using value.toUpperCase seem to have the problem that typing text into the field resets the cursor position to the end of the text. Solutions using text-transform seem to have the problem that the text submitted to the server is still potentially lowercase. This solution avoids those problems:

_x000D_
_x000D_
function handleInput(e) {_x000D_
   var ss = e.target.selectionStart;_x000D_
   var se = e.target.selectionEnd;_x000D_
   e.target.value = e.target.value.toUpperCase();_x000D_
   e.target.selectionStart = ss;_x000D_
   e.target.selectionEnd = se;_x000D_
}
_x000D_
<input type="text" id="txtTest" oninput="handleInput(event)" />
_x000D_
_x000D_
_x000D_

Php, wait 5 seconds before executing an action

In Jan2018 the only solution worked for me:

<?php

if (ob_get_level() == 0) ob_start();
for ($i = 0; $i<10; $i++){

    echo "<br> Line to show.";
    echo str_pad('',4096)."\n";    

    ob_flush();
    flush();
    sleep(2);
}

echo "Done.";

ob_end_flush();

?>

What is the difference between Views and Materialized Views in Oracle?

Views are essentially logical table-like structures populated on the fly by a given query. The results of a view query are not stored anywhere on disk and the view is recreated every time the query is executed. Materialized views are actual structures stored within the database and written to disk. They are updated based on the parameters defined when they are created.

Can not run Java Applets in Internet Explorer 11 using JRE 7u51

If you are running Windows 7 64-bit, I would strongly suggest you download the 64-bit Java installer. There is no sense in downloading the x86 installer on an x64 based OS.

That corrected the problem for me.

What GRANT USAGE ON SCHEMA exactly do?

GRANTs on different objects are separate. GRANTing on a database doesn't GRANT rights to the schema within. Similiarly, GRANTing on a schema doesn't grant rights on the tables within.

If you have rights to SELECT from a table, but not the right to see it in the schema that contains it then you can't access the table.

The rights tests are done in order:

Do you have `USAGE` on the schema? 
    No:  Reject access. 
    Yes: Do you also have the appropriate rights on the table? 
        No:  Reject access. 
        Yes: Check column privileges.

Your confusion may arise from the fact that the public schema has a default GRANT of all rights to the role public, which every user/group is a member of. So everyone already has usage on that schema.

The phrase:

(assuming that the objects' own privilege requirements are also met)

Is saying that you must have USAGE on a schema to use objects within it, but having USAGE on a schema is not by itself sufficient to use the objects within the schema, you must also have rights on the objects themselves.

It's like a directory tree. If you create a directory somedir with file somefile within it then set it so that only your own user can access the directory or the file (mode rwx------ on the dir, mode rw------- on the file) then nobody else can list the directory to see that the file exists.

If you were to grant world-read rights on the file (mode rw-r--r--) but not change the directory permissions it'd make no difference. Nobody could see the file in order to read it, because they don't have the rights to list the directory.

If you instead set rwx-r-xr-x on the directory, setting it so people can list and traverse the directory but not changing the file permissions, people could list the file but could not read it because they'd have no access to the file.

You need to set both permissions for people to actually be able to view the file.

Same thing in Pg. You need both schema USAGE rights and object rights to perform an action on an object, like SELECT from a table.

(The analogy falls down a bit in that PostgreSQL doesn't have row-level security yet, so the user can still "see" that the table exists in the schema by SELECTing from pg_class directly. They can't interact with it in any way, though, so it's just the "list" part that isn't quite the same.)

What is the meaning of "POSIX"?

The most important things POSIX 7 defines

  1. C API

    Greatly extends ANSI C with things like:

    • more file operations: mkdir, dirname, symlink, readlink, link (hardlinks), poll(), stat, sync, nftw()
    • process and threads: fork, execl, wait, pipe, semaphors sem_*, shared memory (shm_*), kill, scheduling parameters (nice, sched_*), sleep, mkfifo, setpgid()
    • networking: socket()
    • memory management: mmap, mlock, mprotect, madvise, brk()
    • utilities: regular expressions (reg*)

    Those APIs also determine underlying system concepts on which they depend, e.g. fork requires a concept of a process.

    Many Linux system calls exist to implement a specific POSIX C API function and make Linux compliant, e.g. sys_write, sys_read, ... Many of those syscalls also have Linux-specific extensions however.

    Major Linux desktop implementation: glibc, which in many cases just provides a shallow wrapper to system calls.

  2. CLI utilities

    E.g.: cd, ls, echo, ...

    Many utilities are direct shell front ends for a corresponding C API function, e.g. mkdir.

    Major Linux desktop implementation: GNU Coreutils for the small ones, separate GNU projects for the big ones: sed, grep, awk, ... Some CLI utilities are implemented by Bash as built-ins.

  3. Shell language

    E.g., a=b; echo "$a"

    Major Linux desktop implementation: GNU Bash.

  4. Environment variables

    E.g.: HOME, PATH.

    PATH search semantics are specified, including how slashes prevent PATH search.

  5. Program exit status

    ANSI C says 0 or EXIT_SUCCESS for success, EXIT_FAILURE for failure, and leaves the rest implementation defined.

    POSIX adds:

  6. Regular expression

    There are two types: BRE (Basic) and ERE (Extended). Basic is deprecated and only kept to not break APIs.

    Those are implemented by C API functions, and used throughout CLI utilities, e.g. grep accepts BREs by default, and EREs with -E.

    E.g.: echo 'a.1' | grep -E 'a.[[:digit:]]'

    Major Linux implementation: glibc implements the functions under regex.h which programs like grep can use as backend.

  7. Directory structure

    E.g.: /dev/null, /tmp

    The Linux FHS greatly extends POSIX.

  8. Filenames

    • / is the path separator
    • NUL cannot be used
    • . is cwd, .. parent
    • portable filenames
      • use at most max 14 chars and 256 for the full path
      • can only contain: a-zA-Z0-9._-

    See also: what is posix compliance for filesystem?

  9. Command line utility API conventions

    Not mandatory, used by POSIX, but almost nowhere else, notably not in GNU. But true, it is too restrictive, e.g. single letter flags only (e.g. -a), no double hyphen long versions (e.g. --all).

    A few widely used conventions:

    • - means stdin where a file is expected
    • -- terminates flags, e.g. ls -- -l to list a directory named -l

    See also: Are there standards for Linux command line switches and arguments?

  10. "POSIX ACLs" (Access Control Lists), e.g. as used as backend for setfacl.

    This was withdrawn but it was implemented in several OSes, including in Linux with setxattr.

Who conforms to POSIX?

Many systems follow POSIX closely, but few are actually certified by the Open Group which maintains the standard. Notable certified ones include:

  • OS X (Apple) X stands for both 10 and UNIX. Was the first Apple POSIX system, released circa 2001. See also: Is OSX a POSIX OS?
  • AIX (IBM)
  • HP-UX (HP)
  • Solaris (Oracle)

Most Linux distros are very compliant, but not certified because they don't want to pay the compliance check. Inspur's K-UX and Huawei's EulerOS are two certified examples.

The official list of certified systems be found at: https://www.opengroup.org/openbrand/register/ and also at the wiki page.

Windows

Windows implemented POSIX on some of its professional distributions.

Since it was an optional feature, programmers could not rely on it for most end user applications.

Support was deprecated in Windows 8:

In 2016 a new official Linux-like API called "Windows Subsystem for Linux" was announced. It includes Linux system calls, ELF running, parts of the /proc filesystem, Bash, GCC, (TODO likely glibc?), apt-get and more: https://channel9.msdn.com/Events/Build/2016/P488 so I believe that it will allow Windows to run much, if not all, of POSIX. However, it is focused on developers / deployment instead of end users. In particular, there were no plans to allow access to the Windows GUI.

Historical overview of the official Microsoft POSIX compatibility: http://brianreiter.org/2010/08/24/the-sad-history-of-the-microsoft-posix-subsystem/

Cygwin is a well known GPL third-party project for that "provides substantial POSIX API functionality" for Windows, but requires that you "rebuild your application from source if you want it to run on Windows". MSYS2 is a related project that seems to add more functionality on top of Cygwin.

Android

Android has its own C library (Bionic) which does not fully support POSIX as of Android O: Is Android POSIX-compatible?

Bonus level

The Linux Standard Base further extends POSIX.

Use the non-frames indexes, they are much more readable and searchable: http://pubs.opengroup.org/onlinepubs/9699919799/nfindex.html

Get a full zipped version of the HTML pages for grepping: Where is the list of the POSIX C API functions?

Angular 2 select option (dropdown) - how to get the value on change so it can be used in a function?

Template/HTML File (component.ts)

<select>
 <option *ngFor="let v of values" [value]="v" (ngModelChange)="onChange($event)">  
    {{v.name}}
  </option>
</select>

Typescript File (component.ts)

values = [
  { id: 3432, name: "Recent" },
  { id: 3442, name: "Most Popular" },
  { id: 3352, name: "Rating" }
];

onChange(cityEvent){
    console.log(cityEvent); // It will display the select city data
}

(ngModelChange) is the @Output of the ngModel directive. It fires when the model changes. You cannot use this event without the ngModel directive

Debug message "Resource interpreted as other but transferred with MIME type application/javascript"

It seems like a bug in Safari's cache handling policies.

Workaround in apache:

Header unset ETag
Header unset Last-Modified

Configuring diff tool with .gitconfig

Reproducing my answer from this thread which was more specific to setting beyond compare as diff tool for Git. All the details that I've shared are equally useful for any diff tool in general so sharing it here:

The first command that we run is as below:

git config --global diff.tool bc3

The above command creates below entry in .gitconfig found in %userprofile% directory:

[diff]
    tool = bc3

Then you run below command (Running this command is redundant in this particular case and is required in some specialized cases only. You will know it in a short while):

git config --global difftool.bc3.path "c:/program files/beyond compare 3/bcomp.exe"

Above command creates below entry in .gitconfig file:

[difftool "bc3"]
    path = c:/program files/Beyond Compare 3/bcomp.exe

The thing to know here is the key bc3. This is a well known key to git corresponding to a particular version of well known comparison tools available in market (bc3 corresponds to 3rd version of Beyond Compare tool). If you want to see all pre-defined keys just run git difftool --tool-help command on git bash. It returns below list:

vimdiff
vimdiff2
vimdiff3
araxis
bc
bc3
codecompare
deltawalker
diffmerge
diffuse
ecmerge
emerge
examdiff
gvimdiff
gvimdiff2
gvimdiff3
kdiff3
kompare
meld
opendiff
p4merge
tkdiff
winmerge
xxdiff

You can use any of the above keys or define a custom key of your own. If you want to setup a new tool altogether(or a newly released version of well-known tool) which doesn't map to any of the keys listed above then you are free to map it to any of keys listed above or to a new custom key of your own.

What if you have to setup a comparison tool which is

  • Absolutely new in market

OR

  • A new version of an existing well known tool has got released which is not mapped to any pre-defined keys in git?

Like in my case, I had installed beyond compare 4. beyond compare is a well-known tool to git but its version 4 release is not mapped to any of the existing keys by default. So you can follow any of the below approaches:

  1. I can map beyond compare 4 tool to already existing key bc3 which corresponds to beyond compare 3 version. I didn't have beyond compare version 3 on my computer so I didn't care. If I wanted I could have mapped it to any of the pre-defined keys in the above list also e.g. examdiff.

    If you map well known version of tools to appropriate already existing/well- known key then you would not need to run the second command as their install path is already known to git.

    For e.g. if I had installed beyond compare version 3 on my box then having below configuration in my .gitconfig file would have been sufficient to get going:

    [diff]
    tool = bc3
    

    But if you want to change the default associated tool then you end up mentioning the path attribute separately so that git gets to know the path from where you new tool's exe has to be launched. Here is the entry which foxes git to launch beyond compare 4 instead. Note the exe's path:

    [difftool "bc3"]
    path = c:/program files/Beyond Compare 4/bcomp.exe
    
  2. Most cleanest approach is to define a new key altogether for the new comparison tool or a new version of an well known tool. Like in my case I defined a new key bc4 so that it is easy to remember. In such a case you have to run two commands in all but your second command will not be setting path of your new tool's executable. Instead you have to set cmd attribute for your new tool as shown below:

    git config --global diff.tool bc4
    
    git config --global difftool.bc4.cmd "\"C:\\Program Files\\Beyond Compare 4\\bcomp.exe\" -s \"\$LOCAL\" -d \"\$REMOTE\""
    

    Running above commands creates below entries in your .gitconfig file:

    [diff]
    tool = bc4
    [difftool "bc4"]
    cmd = \"C:\\Program Files\\Beyond Compare 4\\bcomp.exe\" -s \"$LOCAL\" -d \"$REMOTE\"
    

I would strongly recommend you to follow approach # 2 to avoid any confusion for yourself in future.

How to split one string into multiple strings separated by at least one space in bash shell?

Did you try just passing the string variable to a for loop? Bash, for one, will split on whitespace automatically.

sentence="This is   a sentence."
for word in $sentence
do
    echo $word
done

 

This
is
a
sentence.

Android difference between Two Dates

I arranged a little. This works great.

@SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd MM yyyy");
    Date date = new Date();
    String dateOfDay = simpleDateFormat.format(date);

    String timeofday = android.text.format.DateFormat.format("HH:mm:ss", new Date().getTime()).toString();

    @SuppressLint("SimpleDateFormat") SimpleDateFormat dateFormat = new SimpleDateFormat("dd MM yyyy hh:mm:ss");
    try {
        Date date1 = dateFormat.parse(06 09 2018 + " " + 10:12:56);
        Date date2 = dateFormat.parse(dateOfDay + " " + timeofday);

        printDifference(date1, date2);

    } catch (ParseException e) {
        e.printStackTrace();
    }

@SuppressLint("SetTextI18n")
private void printDifference(Date startDate, Date endDate) {
    //milliseconds
    long different = endDate.getTime() - startDate.getTime();

    long secondsInMilli = 1000;
    long minutesInMilli = secondsInMilli * 60;
    long hoursInMilli = minutesInMilli * 60;
    long daysInMilli = hoursInMilli * 24;

    long elapsedDays = different / daysInMilli;
    different = different % daysInMilli;

    long elapsedHours = different / hoursInMilli;
    different = different % hoursInMilli;

    long elapsedMinutes = different / minutesInMilli;
    different = different % minutesInMilli;

    long elapsedSeconds = different / secondsInMilli;

Toast.makeText(context, elapsedDays + " " + elapsedHours + " " + elapsedMinutes + " " + elapsedSeconds, Toast.LENGTH_SHORT).show();
}

Unable to copy ~/.ssh/id_rsa.pub

The following is also working for me:

ssh <user>@<host>  "cat <filepath>"|pbcopy 

How do I make a textbox that only accepts numbers?

Sorry to wake the dead, but I thought someone might find this useful for future reference.

Here is how I handle it. It handles floating point numbers, but can easily be modified for integers.

Basically you can only press 0 - 9 and .

You can only have one 0 before the .

All other characters are ignored and the cursor position maintained.

    private bool _myTextBoxChanging = false;

    private void myTextBox_TextChanged(object sender, EventArgs e)
    {
        validateText(myTextBox);
    }

    private void validateText(TextBox box)
    {
        // stop multiple changes;
        if (_myTextBoxChanging)
            return;
        _myTextBoxChanging = true;

        string text = box.Text;
        if (text == "")
            return;
        string validText = "";
        bool hasPeriod = false;
        int pos = box.SelectionStart;
        for (int i = 0; i < text.Length; i++ )
        {
            bool badChar = false;
            char s = text[i];
            if (s == '.')
            {
                if (hasPeriod)
                    badChar = true;
                else
                    hasPeriod = true;
            }
            else if (s < '0' || s > '9')
                badChar = true;

            if (!badChar)
                validText += s;
            else
            {
                if (i <= pos)
                    pos--;
            }
        }

        // trim starting 00s
        while (validText.Length >= 2 && validText[0] == '0')
        {
            if (validText[1] != '.')
            {
                validText = validText.Substring(1);
                if (pos < 2)
                    pos--;
            }
            else
                break;
        }

        if (pos > validText.Length)
            pos = validText.Length;
        box.Text = validText;
        box.SelectionStart = pos;
        _myTextBoxChanging = false;
    }

Here is a quickly modified int version:

    private void validateText(TextBox box)
    {
        // stop multiple changes;
        if (_myTextBoxChanging)
            return;
        _myTextBoxChanging = true;

        string text = box.Text;
        if (text == "")
            return;
        string validText = "";
        int pos = box.SelectionStart;
        for (int i = 0; i < text.Length; i++ )
        {
            char s = text[i];
            if (s < '0' || s > '9')
            {
                if (i <= pos)
                    pos--;
            }
            else
                validText += s;
        }

        // trim starting 00s 
        while (validText.Length >= 2 && validText.StartsWith("00")) 
        { 
            validText = validText.Substring(1); 
            if (pos < 2) 
                pos--; 
        } 

        if (pos > validText.Length)
            pos = validText.Length;
        box.Text = validText;
        box.SelectionStart = pos;
        _myTextBoxChanging = false;
    }

How to save a Seaborn plot into a file

Remove the get_figure and just use sns_plot.savefig('output.png')

df = sns.load_dataset('iris')
sns_plot = sns.pairplot(df, hue='species', height=2.5)
sns_plot.savefig("output.png")

CSS3 animate border color

You can try this also...

_x000D_
_x000D_
button {
  background: none;
  border: 0;
  box-sizing: border-box;
  margin: 1em;
  padding: 1em 2em;
  box-shadow: inset 0 0 0 2px #f45e61;
  color: #f45e61;
  font-size: inherit;
  font-weight: 700;
  vertical-align: middle;
  position: relative;
}
button::before, button::after {
  box-sizing: inherit;
  content: '';
  position: absolute;
  width: 100%;
  height: 100%;
}

.draw {
  -webkit-transition: color 0.25s;
  transition: color 0.25s;
}
.draw::before, .draw::after {
  border: 2px solid transparent;
  width: 0;
  height: 0;
}
.draw::before {
  top: 0;
  left: 0;
}
.draw::after {
  bottom: 0;
  right: 0;
}
.draw:hover {
  color: #60daaa;
}
.draw:hover::before, .draw:hover::after {
  width: 100%;
  height: 100%;
}
.draw:hover::before {
  border-top-color: #60daaa;
  border-right-color: #60daaa;
  -webkit-transition: width 0.25s ease-out, height 0.25s ease-out 0.25s;
  transition: width 0.25s ease-out, height 0.25s ease-out 0.25s;
}
.draw:hover::after {
  border-bottom-color: #60daaa;
  border-left-color: #60daaa;
  -webkit-transition: border-color 0s ease-out 0.5s, width 0.25s ease-out 0.5s, height 0.25s ease-out 0.75s;
  transition: border-color 0s ease-out 0.5s, width 0.25s ease-out 0.5s, height 0.25s ease-out 0.75s;
}
_x000D_
<section class="buttons">
  <button class="draw">Draw</button>
</section>
_x000D_
_x000D_
_x000D_

Maven Jacoco Configuration - Exclude classes/packages from report not working

you can configure the coverage exclusion in the sonar properties, outside of the configuration of the jacoco plugin:

...
<properties>
    ....
    <sonar.exclusions>
        **/generated/**/*,
        **/model/**/*
    </sonar.exclusions>
    <sonar.test.exclusions>
        src/test/**/*
    </sonar.test.exclusions>
    ....
    <sonar.java.coveragePlugin>jacoco</sonar.java.coveragePlugin>
    <sonar.jacoco.reportPath>${project.basedir}/../target/jacoco.exec</sonar.jacoco.reportPath>
    <sonar.coverage.exclusions>
        **/generated/**/*,
        **/model/**/*
    </sonar.coverage.exclusions>
    <jacoco.version>0.7.5.201505241946</jacoco.version>
    ....
</properties>
....

and remember to remove the exclusion settings from the plugin

Error "The goal you specified requires a project to execute but there is no POM in this directory" after executing maven command

Adding one more answer for Windows users. If none of this solves the problems.

Do not add space before or after =

-DgroupId= com.company.module //Wrong , Watch the space after the equal to 
-DgroupId=com.company.module //Right 

Its better to put everything inside double quotes, like "-DgroupId=com.." This will give you exact error rather than some random error.

Weird that , maven does not even care to mention this in the documentation.

Windows 7, 64 bit, DLL problems

I also ran into this problem, but the solution that seems to be a common thread here, and I saw elsewhere on the web, is "[re]install the redistributable package". However, for me that does not work, as the problem arose when running the installer for our product (which installs the redistributable package) to test our shiny new Visual Studio 2015 builds.

The issue came up because the DLL files listed are not located in the Visual Studio install path (for example, C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\redist) and thus had not been added to the install. These api-ms-win-* dlls get installed to a Windows 10 SDK install path as part of the Visual Studio 2015 install (e.g. C:\Program Files (x86)\Windows Kits\10\Redist).

Installing on Windows 10 worked fine, but installing on Windows 7 required adding these DLL files to our product install. For more information, see Update for Universal C Runtime in Windows which describes the addition of these dependencies caused by Visual Studio 2015 and provides downloads for various Windows platforms; also see Introducing the Universal CRT which describes the redesign of the CRT libraries. Of particular interest is item 6 under the section titled Distributing Software that uses the Universal CRT:

Updated September 11, 2015: App-local deployment of the Universal CRT is supported. To obtain the binaries for app-local deployment, install the Windows Software Development Kit (SDK) for Windows 10. The binaries will be installed to C:\Program Files (x86)\Windows Kits\10\Redist\ucrt. You will need to copy all of the DLLs with your app (note that the set of DLL files are necessary is different on different versions of Windows, so you must include all of the DLL files in order for your program to run on all supported versions of Windows).

How can I get Docker Linux container information from within the container itself?

Use docker inspect.

$ docker ps # get conteiner id
$ docker inspect 4abbef615af7
[{
    "ID": "4abbef615af780f24991ccdca946cd50d2422e75f53fb15f578e14167c365989",
    "Created": "2014-01-08T07:13:32.765612597Z",
    "Path": "/bin/bash",
    "Args": [
        "-c",
        "/start web"
    ],
    "Config": {
        "Hostname": "4abbef615af7",
...

Can get ip as follows.

$ docker inspect -format="{{ .NetworkSettings.IPAddress }}" 2a5624c52119
172.17.0.24

Adding text to ImageView in Android

    <FrameLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="center_horizontal"
        android:layout_weight="30" >

        <ImageButton
            android:id="@+id/imgbtnUploadPendingPods"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:contentDescription="@string/hello_world"
            android:src="@drawable/upload_icon" />

        <TextView
            android:id="@+id/textView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:paddingTop="30dp"
            android:text="@string/pendingpods"
            android:textAppearance="?android:attr/textAppearanceSmall" />
    </FrameLayout>

How do I shutdown, restart, or log off Windows via a bat file?

If you are on a remote machine, you may also want to add the -f option to force the reboot. Otherwise your session may close and a stubborn app can hang the system.

I use this whenever I want to force an immediate reboot:

shutdown -t 0 -r -f

For a more friendly "give them some time" option, you can use this:

shutdown -t 30 -r

As you can see in the comments, the -f is implied by the timeout.

Brutus 2006 is a utility that provides a GUI for these options.

Replace string within file contents

#!/usr/bin/python

with open(FileName) as f:
    newText=f.read().replace('A', 'Orange')

with open(FileName, "w") as f:
    f.write(newText)

"The POM for ... is missing, no dependency information available" even though it exists in Maven Repository

If the POM missing warning is of project's self module, the reason is that you are trying to mistakenly build from a sub-module directory. You need to run the build and install command from root directory of the project.

How to convert an int to string in C?

After having looked at various versions of itoa for gcc, the most flexible version I have found that is capable of handling conversions to binary, decimal and hexadecimal, both positive and negative is the fourth version found at http://www.strudel.org.uk/itoa/. While sprintf/snprintf have advantages, they will not handle negative numbers for anything other than decimal conversion. Since the link above is either off-line or no longer active, I've included their 4th version below:

/**
 * C++ version 0.4 char* style "itoa":
 * Written by Lukás Chmela
 * Released under GPLv3.
 */
char* itoa(int value, char* result, int base) {
    // check that the base if valid
    if (base < 2 || base > 36) { *result = '\0'; return result; }

    char* ptr = result, *ptr1 = result, tmp_char;
    int tmp_value;

    do {
        tmp_value = value;
        value /= base;
        *ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)];
    } while ( value );

    // Apply negative sign
    if (tmp_value < 0) *ptr++ = '-';
    *ptr-- = '\0';
    while(ptr1 < ptr) {
        tmp_char = *ptr;
        *ptr--= *ptr1;
        *ptr1++ = tmp_char;
    }
    return result;
}

How do I convert a long to a string in C++?

   #include <sstream>


   ....

    std::stringstream ss;
    ss << a_long_int;  // or any other type
    std::string result=ss.str();   // use .str() to get a string back

How to compare arrays in C#?

You're comparing the object references, and they are not the same. You need to compare the array contents.

.NET2 solution

An option is iterating through the array elements and call Equals() for each element. Remember that you need to override the Equals() method for the array elements, if they are not the same object reference.

An alternative is using this generic method to compare two generic arrays:

static bool ArraysEqual<T>(T[] a1, T[] a2)
{
    if (ReferenceEquals(a1, a2))
        return true;

    if (a1 == null || a2 == null)
        return false;

    if (a1.Length != a2.Length)
        return false;

    var comparer = EqualityComparer<T>.Default;
    for (int i = 0; i < a1.Length; i++)
    {
        if (!comparer.Equals(a1[i], a2[i])) return false;
    }
    return true;
}

.NET 3.5 or higher solution

Or use SequenceEqual if Linq is available for you (.NET Framework >= 3.5)

What does the M stand for in C# Decimal literal notation?

A real literal suffixed by M or m is of type decimal (money). For example, the literals 1m, 1.5m, 1e10m, and 123.456M are all of type decimal. This literal is converted to a decimal value by taking the exact value, and, if necessary, rounding to the nearest representable value using banker's rounding. Any scale apparent in the literal is preserved unless the value is rounded or the value is zero (in which latter case the sign and scale will be 0). Hence, the literal 2.900m will be parsed to form the decimal with sign 0, coefficient 2900, and scale 3.

Read more about real literals

Set Focus After Last Character in Text Box

You should code like this.

var num = $('#Number').val();        
$('#Number').focus().val('').val(num);    

How can I copy columns from one sheet to another with VBA in Excel?

Private Sub Worksheet_Change(ByVal Target As Range)
  Dim rng As Range, r As Range
  Set rng = Intersect(Target, Range("a2:a" & Rows.Count))
  If rng Is Nothing Then Exit Sub
    For Each r In rng
      If Not IsEmpty(r.Value) Then
        r.Copy Destination:=Sheets("sheet2").Range("a2")
      End If
    Next
  Set rng = Nothing
End Sub

Change arrow colors in Bootstraps carousel

With Font Awesome icons:

<!-- Controls -->
<a class="carousel-control-prev" href="#carousel-example-generic" role="button" data-slide="prev">
  <span class="fa fa-chevron-left fa-lg" style="color:red;"></span>
  <span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#carousel-example-generic" role="button" data-slide="next">
  <span class="fa fa-chevron-right fa-lg" style="color:red;"></span>
  <span class="sr-only">Next</span>
</a>

How to Alter a table for Identity Specification is identity SQL Server

You cannot "convert" an existing column into an IDENTITY column - you will have to create a new column as INT IDENTITY:

ALTER TABLE ProductInProduct 
ADD NewId INT IDENTITY (1, 1);

Update:

OK, so there is a way of converting an existing column to IDENTITY. If you absolutely need this - check out this response by Martin Smith with all the gory details.

How do I change the default application icon in Java?

You can simply go Netbeans, in the design view, go to JFrame property, choose icon image property, Choose Set Form's iconImage property using: "Custom code" and then in the Form.SetIconImage() function put the following code:

Toolkit.getDefaultToolkit().getImage(name_of_your_JFrame.class.getResource("image.png"))

Do not forget to import:

import java.awt.Toolkit;

in the source code!

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2

I was running into a similar error in pywikipediabot. The .decode method is a step in the right direction but for me it didn't work without adding 'ignore':

ignore_encoding = lambda s: s.decode('utf8', 'ignore')

Ignoring encoding errors can lead to data loss or produce incorrect output. But if you just want to get it done and the details aren't very important this can be a good way to move faster.

What is the !! (not not) operator in JavaScript?

It's a horribly obscure way to do a type conversion.

! is NOT. So !true is false, and !false is true. !0 is true, and !1 is false.

So you're converting a value to a boolean, then inverting it, then inverting it again.

// Maximum Obscurity:
val.enabled = !!userId;

// Partial Obscurity:
val.enabled = (userId != 0) ? true : false;

// And finally, much easier to understand:
val.enabled = (userId != 0);

Using JQuery to open a popup window and print

Got it! I found an idea here

http://www.mail-archive.com/[email protected]/msg18410.html

In this example, they loaded a blank popup window into an object, cloned the contents of the element to be displayed, and appended it to the body of the object. Since I already knew what the contents of view-details (or any page I load in the lightbox), I just had to clone that content instead and load it into an object. Then, I just needed to print that object. The final outcome looks like this:

$('.printBtn').bind('click',function() {
    var thePopup = window.open( '', "Customer Listing", "menubar=0,location=0,height=700,width=700" );
    $('#popup-content').clone().appendTo( thePopup.document.body );
    thePopup.print();
});

I had one small drawback in that the style sheet I was using in view-details.php was using a relative link. I had to change it to an absolute link. The reason being that the window didn't have a URL associated with it, so it had no relative position to draw on.

Works in Firefox. I need to test it in some other major browsers too.

I don't know how well this solution works when you're dealing with images, videos, or other process intensive solutions. Although, it works pretty well in my case, since I'm just loading tables and text values.

Thanks for the input! You gave me some ideas of how to get around this.

How to change color and font on ListView

Even better, you do not need to create separate android xml layout for list cell view. You can just use "android.R.layout.simple_list_item_1" if the list only contains textview.

private class ExampleAdapter extends ArrayAdapter<String>{

    public ExampleAdapter(Context context, int textViewResourceId, String[] objects) {
        super(context, textViewResourceId, objects);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {


        View view =  super.getView(position, convertView, parent);

        TextView tv = (TextView) view.findViewById(android.R.id.text1);
        tv.setTextColor(0);

        return view;
    }

How exactly does __attribute__((constructor)) work?

Here is a "concrete" (and possibly useful) example of how, why, and when to use these handy, yet unsightly constructs...

Xcode uses a "global" "user default" to decide which XCTestObserver class spews it's heart out to the beleaguered console.

In this example... when I implicitly load this psuedo-library, let's call it... libdemure.a, via a flag in my test target á la..

OTHER_LDFLAGS = -ldemure

I want to..

  1. At load (ie. when XCTest loads my test bundle), override the "default" XCTest "observer" class... (via the constructor function) PS: As far as I can tell.. anything done here could be done with equivalent effect inside my class' + (void) load { ... } method.

  2. run my tests.... in this case, with less inane verbosity in the logs (implementation upon request)

  3. Return the "global" XCTestObserver class to it's pristine state.. so as not to foul up other XCTest runs which haven't gotten on the bandwagon (aka. linked to libdemure.a). I guess this historically was done in dealloc.. but I'm not about to start messing with that old hag.

So...

#define USER_DEFS NSUserDefaults.standardUserDefaults

@interface      DemureTestObserver : XCTestObserver @end
@implementation DemureTestObserver

__attribute__((constructor)) static void hijack_observer() {

/*! here I totally hijack the default logging, but you CAN
    use multiple observers, just CSV them, 
    i.e. "@"DemureTestObserverm,XCTestLog"
*/
  [USER_DEFS setObject:@"DemureTestObserver" 
                forKey:@"XCTestObserverClass"];
  [USER_DEFS synchronize];
}

__attribute__((destructor)) static void reset_observer()  {

  // Clean up, and it's as if we had never been here.
  [USER_DEFS setObject:@"XCTestLog" 
                forKey:@"XCTestObserverClass"];
  [USER_DEFS synchronize];
}

...
@end

Without the linker flag... (Fashion-police swarm Cupertino demanding retribution, yet Apple's default prevails, as is desired, here)

enter image description here

WITH the -ldemure.a linker flag... (Comprehensible results, gasp... "thanks constructor/destructor"... Crowd cheers) enter image description here

Error handling in C code

When I write programs, during initialization, I usually spin off a thread for error handling, and initialize a special structure for errors, including a lock. Then, when I detect an error, through return values, I enter in the info from the exception into the structure and send a SIGIO to the exception handling thread, then see if I can't continue execution. If I can't, I send a SIGURG to the exception thread, which stops the program gracefully.

SVN checkout the contents of a folder, not the folder itself

Just add a . to it:

svn checkout file:///home/landonwinters/svn/waterproject/trunk .

That means: check out to current directory.

What data type to use in MySQL to store images?

This can be done from the command line. This will create a column for your image with a NOT NULL property.

CREATE TABLE `test`.`pic` (
`idpic` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
`caption` VARCHAR(45) NOT NULL,
`img` LONGBLOB NOT NULL,
PRIMARY KEY(`idpic`)
)
TYPE = InnoDB; 

From here

Sublime Text 2 - Show file navigation in sidebar

I added the Context Menu item for Folders to open in Sublime Text. In windows, you can right click on any Folder and open the structure in Sublime. You could also create a service (?) for Mac OS - I'm just not familiar with the process.

The following could be saved to a File (OpenFolderWithSublime.reg) to merge to the registry. Be Sure to modify the directory structure to appropriately point to your Sublime installation. Alternatively, you can use REGEDIT and browse to HKCR\Folder\shell and create the values manually.

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\Folder\shell\Open with Sublime Text]

[HKEY_CLASSES_ROOT\Folder\shell\Open with Sublime Text\command]
@="C:\\Program Files\\Sublime Text 2\\sublime_text \"%1\""

What’s the best way to load a JSONObject from a json text file?

try this:

import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import org.apache.commons.io.IOUtils; 

    public class JsonParsing {

        public static void main(String[] args) throws Exception {
            InputStream is = 
                    JsonParsing.class.getResourceAsStream( "sample-json.txt");
            String jsonTxt = IOUtils.toString( is );

            JSONObject json = (JSONObject) JSONSerializer.toJSON( jsonTxt );        
            double coolness = json.getDouble( "coolness" );
            int altitude = json.getInt( "altitude" );
            JSONObject pilot = json.getJSONObject("pilot");
            String firstName = pilot.getString("firstName");
            String lastName = pilot.getString("lastName");

            System.out.println( "Coolness: " + coolness );
            System.out.println( "Altitude: " + altitude );
            System.out.println( "Pilot: " + lastName );
        }
    }

and this is your sample-json.txt , should be in json format

{
 'foo':'bar',
 'coolness':2.0,
 'altitude':39000,
 'pilot':
     {
         'firstName':'Buzz',
         'lastName':'Aldrin'
     },
 'mission':'apollo 11'
}

How do I improve ASP.NET MVC application performance?

Code Climber and this blog entry provide detailed ways of increasing application's performance.

Compiled query will increase performance of your application, but it has nothing in common with ASP.NET MVC. It will speed up every db application, so it is not really about MVC.

How to examine processes in OS X's Terminal?

Try the top command. It's an interactive command that will display the running processes.

You may also use the Apple's "Activity Monitor" application (located in /Applications/Utilities/).

It provides an actually quite nice GUI. You can see all the running processes, filter them by users, get extended informations about them (CPU, memory, network, etc), monitor them, etc...

Probably your best choice, unless you want to stick with the terminal (in such a case, read the top or ps manual, as those commands have a bunch of options).

Is it possible to return empty in react render function?

for those developers who came to this question about checking where they can return null from component instead of checking in ternary mode to render or not render the component, the answer is YES, You Can!

i mean instead of this junk ternary condition inside your jsx in render part of your component:

// some component body
return(
  <section>
   {/* some ui */}
   
   { someCondition && <MyComponent /> }
   or
   { someCondition ? <MyComponent /> : null }

   {/* more ui */}
  </section>
)

you can check than condition inside your component like:

const MyComponent:React.FC = () => {
  
  // get someCondition from context at here before any thing


  if(someCondition) return null; // i mean this part , checking inside component! 
  
  return (
    <section>   
     // some ui...
    </section>
  )
}

Just Consider that in my case i provide the someCondition variable from a context in upper level component ( for example, just consider in your mind ) and i don't need to prop drill the someCondition inside MyComponent.

Just look how clean view your code gets after that, i mean you don't need to user ternary operator inside your JSX, and your parent component would like below:

// some component body
return(
  <section>
   {/* some ui */}
   
   <MyComponent />

   {/* more ui */}
  </section>
)

and MyComponent would handle the rest for you!

how to fix Cannot call sendRedirect() after the response has been committed?

The root cause of IllegalStateException exception is a java servlet is attempting to write to the output stream (response) after the response has been committed.

It is always better to ensure that no content is added to the response after the forward or redirect is done to avoid IllegalStateException. It can be done by including a ‘return’ statement immediately next to the forward or redirect statement.

JAVA 7 OFFICIAL LINK

ADDITIONAL INFO

How do you configure HttpOnly cookies in tomcat / java webapps?

httpOnly is supported as of Tomcat 6.0.19 and Tomcat 5.5.28.

See the changelog entry for bug 44382.

The last comment for bug 44382 states, "this has been applied to 5.5.x and will be included in 5.5.28 onwards." However, it does not appear that 5.5.28 has been released.

The httpOnly functionality can be enabled for all webapps in conf/context.xml:

<Context useHttpOnly="true">
...
</Context>

My interpretation is that it also works for an individual context by setting it on the desired Context entry in conf/server.xml (in the same manner as above).

How does a PreparedStatement avoid or prevent SQL injection?

The SQL used in a PreparedStatement is precompiled on the driver. From that point on, the parameters are sent to the driver as literal values and not executable portions of SQL; thus no SQL can be injected using a parameter. Another beneficial side effect of PreparedStatements (precompilation + sending only parameters) is improved performance when running the statement multiple times even with different values for the parameters (assuming that the driver supports PreparedStatements) as the driver does not have to perform SQL parsing and compilation each time the parameters change.

set the width of select2 input (through Angular-ui directive)

You can try like this. It works for me

$("#MISSION_ID").select2();

On hide/show or ajax request, we have to reinitialize the select2 plugin

For example:

$("#offialNumberArea").show();
$("#eventNameArea").hide();

$('.selectCriteria').change(function(){
    var thisVal = $(this).val();
    if(thisVal == 'sailor'){
        $("#offialNumberArea").show();
        $("#eventNameArea").hide();
    }
    else
    {
        $("#offialNumberArea").hide();
        $("#eventNameArea").show();
        $("#MISSION_ID").select2();
    }
});

Fastest way to list all primes below N

Sorry to bother but erat2() has a serious flaw in the algorithm.

While searching for the next composite, we need to test odd numbers only. q,p both are odd; then q+p is even and doesn't need to be tested, but q+2*p is always odd. This eliminates the "if even" test in the while loop condition and saves about 30% of the runtime.

While we're at it: instead of the elegant 'D.pop(q,None)' get and delete method use 'if q in D: p=D[q],del D[q]' which is twice as fast! At least on my machine (P3-1Ghz). So I suggest this implementation of this clever algorithm:

def erat3( ):
    from itertools import islice, count

    # q is the running integer that's checked for primeness.
    # yield 2 and no other even number thereafter
    yield 2
    D = {}
    # no need to mark D[4] as we will test odd numbers only
    for q in islice(count(3),0,None,2):
        if q in D:                  #  is composite
            p = D[q]
            del D[q]
            # q is composite. p=D[q] is the first prime that
            # divides it. Since we've reached q, we no longer
            # need it in the map, but we'll mark the next
            # multiple of its witnesses to prepare for larger
            # numbers.
            x = q + p+p        # next odd(!) multiple
            while x in D:      # skip composites
                x += p+p
            D[x] = p
        else:                  # is prime
            # q is a new prime.
            # Yield it and mark its first multiple that isn't
            # already marked in previous iterations.
            D[q*q] = q
            yield q

MongoDB Aggregation: How to get total records count?

Use this to find total count in resulting collection.

db.collection.aggregate( [
{ $match : { score : { $gt : 70, $lte : 90 } } },
{ $group: { _id: null, count: { $sum: 1 } } }
] );

Using two CSS classes on one element

If you want two classes on one element, do it this way:

<div class="social first"></div>

Reference it in css like so:

.social.first {}

Example:

https://jsfiddle.net/tybro0103/covbtpaq/

How to redirect output of an entire shell script within the script itself?

You can make the whole script a function like this:

main_function() {
  do_things_here
}

then at the end of the script have this:

if [ -z $TERM ]; then
  # if not run via terminal, log everything into a log file
  main_function 2>&1 >> /var/log/my_uber_script.log
else
  # run via terminal, only output to screen
  main_function
fi

Alternatively, you may log everything into logfile each run and still output it to stdout by simply doing:

# log everything, but also output to stdout
main_function 2>&1 | tee -a /var/log/my_uber_script.log

Angular 2 / 4 / 5 not working in IE11

If none of the other solutions work for you, it's worth investigating the source of the problem. It may be than an npm module directly inserts ES6 code, which cannot be transpiled.

In my case I had the

SCRIPT1002: Syntax error vendor.js (114536,27) at the following line:

const ucs2encode = array => String.fromCodePoint(...array);

I searched the node_modules folder and found from which file the line came. It turned out that the culprit was punycode.js which in it's 2.1.0 version uses ES6 directly.

After I downgraded it to 1.4.1, which uses ES5, the problem was solved.

How to request Administrator access inside a batch file

Another PowerShell Solution...

This is not about running a batch script as admin per, but rather how to elevate another program from batch...

I have a batch file "wrapper" for an exe. They have the same "root file name", but alternate extensions. I am able to launch the exe as admin, and set the working directory to the one containing the script, with the following one line powershell invocation:

@powershell "Start-Process -FilePath '%~n0.exe' -WorkingDirectory '%~dp0' -Verb RunAs"

More info

There are a whole slew of additional Start-Process options as well that you can apply! Check out: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/start-process?view=powershell-6

Note that I use the @ prefix. That's equivalent to @echo off for the one line. I use %~n0 here to get the "root name" of the batch script, then I concatenate the .exe to point it the adjancent binary. The use of %~dp0 provides the full path to the directory which the batch resides. And, of course, the -Verb RunAs parameter provides the elevation.

Psql could not connect to server: No such file or directory, 5432 error?

In my case it was the lockfile postmaster.id that was not deleted properly during the last system crash that caused the issue. Deleting it with sudo rm /usr/local/var/postgres/postmaster.pid and restarting Postgres solved the problem.

Which Android phones out there do have a gyroscope?

Since I have recently developed an Android application using gyroscope data (steady compass), I tried to collect a list with such devices. This is not an exhaustive list at all, but it is what I have so far:

*** Phones:

  • HTC Sensation
  • HTC Sensation XL
  • HTC Evo 3D
  • HTC One S
  • HTC One X
  • Huawei Ascend P1
  • Huawei Ascend X (U9000)
  • Huawei Honor (U8860)
  • LG Nitro HD (P930)
  • LG Optimus 2x (P990)
  • LG Optimus Black (P970)
  • LG Optimus 3D (P920)
  • Samsung Galaxy S II (i9100)
  • Samsung Galaxy S III (i9300)
  • Samsung Galaxy R (i9103)
  • Samsung Google Nexus S (i9020)
  • Samsung Galaxy Nexus (i9250)
  • Samsung Galaxy J3 (2017) model
  • Samsung Galaxy Note (n7000)
  • Sony Xperia P (LT22i)
  • Sony Xperia S (LT26i)

*** Tablets:

  • Acer Iconia Tab A100 (7")
  • Acer Iconia Tab A500 (10.1")
  • Asus Eee Pad Transformer (TF101)
  • Asus Eee Pad Transformer Prime (TF201)
  • Motorola Xoom (mz604)
  • Samsung Galaxy Tab (p1000)
  • Samsung Galaxy Tab 7 plus (p6200)
  • Samsung Galaxy Tab 10.1 (p7100)
  • Sony Tablet P
  • Sony Tablet S
  • Toshiba Thrive 7"
  • Toshiba Trhive 10"

Hope the list keeps growing and hope that gyros will be soon available on mid and low price smartphones.

Comparing floating point number to zero

2 + 2 = 5(*)

(for some floating-precision values of 2)

This problem frequently arises when we think of"floating point" as a way to increase precision. Then we run afoul of the "floating" part, which means there is no guarantee of which numbers can be represented.

So while we might easily be able to represent "1.0, -1.0, 0.1, -0.1" as we get to larger numbers we start to see approximations - or we should, except we often hide them by truncating the numbers for display.

As a result, we might think the computer is storing "0.003" but it may instead be storing "0.0033333333334".

What happens if you perform "0.0003 - 0.0002"? We expect .0001, but the actual values being stored might be more like "0.00033" - "0.00029" which yields "0.000004", or the closest representable value, which might be 0, or it might be "0.000006".

With current floating point math operations, it is not guaranteed that (a / b) * b == a.

#include <stdio.h>

// defeat inline optimizations of 'a / b * b' to 'a'
extern double bodge(int base, int divisor) {
    return static_cast<double>(base) / static_cast<double>(divisor);
}

int main() {
    int errors = 0;
    for (int b = 1; b < 100; ++b) {
        for (int d = 1; d < 100; ++d) {
            // b / d * d ... should == b
            double res = bodge(b, d) * static_cast<double>(d);
            // but it doesn't always
            if (res != static_cast<double>(b))
                ++errors;
        }
    }
    printf("errors: %d\n", errors);
}

ideone reports 599 instances where (b * d) / d != b using just the 10,000 combinations of 1 <= b <= 100 and 1 <= d <= 100 .

The solution described in the FAQ is essentially to apply a granularity constraint - to test if (a == b +/- epsilon).

An alternative approach is to avoid the problem entirely by using fixed point precision or by using your desired granularity as the base unit for your storage. E.g. if you want times stored with nanosecond precision, use nanoseconds as your unit of storage.

C++11 introduced std::ratio as the basis for fixed-point conversions between different time units.

How to have a default option in Angular.js select box

If you want to make sure your $scope.somethingHere value doesn't get overwritten when your view initializes, you'll want to coalesce (somethingHere = somethingHere || options[0].value) the value in your ng-init like so:

<select ng-model="somethingHere" 
        ng-init="somethingHere = somethingHere || options[0].value"
        ng-options="option.value as option.name for option in options">
</select>

Things possible in IntelliJ that aren't possible in Eclipse?

Idea 8.0 has the lovely ctrl+shift+space x 2 that does the following autocomplete:

 City city = customer.<ctrl-shift-space twice>

resolves to

 City city = customer.getAddress().getCity();

through any number of levels of getters/setters.

Opening a remote machine's Windows C drive

If you need a drive letter (some applications don't like UNC style paths that start with a machine-name) you can "map a drive" to a UNC path. Right-click on "My Computer" and select Map Network Drive... or use this command line:

NET USE z: \server\c$\folder1\folder2

NET USE y: \server\d$

Note that you can map drive-to-drive or drill down and map to sub-folder.

Using grep to help subset a data frame in R

It's pretty straightforward using [ to extract:

grep will give you the position in which it matched your search pattern (unless you use value = TRUE).

grep("^G45", My.Data$x)
# [1] 2

Since you're searching within the values of a single column, that actually corresponds to the row index. So, use that with [ (where you would use My.Data[rows, cols] to get specific rows and columns).

My.Data[grep("^G45", My.Data$x), ]
#      x y
# 2 G459 2

The help-page for subset shows how you can use grep and grepl with subset if you prefer using this function over [. Here's an example.

subset(My.Data, grepl("^G45", My.Data$x))
#      x y
# 2 G459 2

As of R 3.3, there's now also the startsWith function, which you can again use with subset (or with any of the other approaches above). According to the help page for the function, it's considerably faster than using substring or grepl.

subset(My.Data, startsWith(as.character(x), "G45"))
#      x y
# 2 G459 2

Find the last element of an array while using a foreach loop in PHP

foreach ($array as $key => $value) {

  $class = ( $key !== count( $array ) -1 ) ? " class='not-last'" : " class='last'";

  echo "<div{$class}>";
  echo "$value['the_title']";
  echo "</div>";

}

Reference

Directory.GetFiles: how to get only filename, not full path?

Try,

  string[] files =  new DirectoryInfo(dir).GetFiles().Select(o => o.Name).ToArray();

Above line may throw UnauthorizedAccessException. To handle this check out below link

C# Handle System.UnauthorizedAccessException in LINQ

How do I pass variables and data from PHP to JavaScript?

I quite like the way the WordPress works with its enqueue and localize functions, so following that model, I wrote a simple class for putting a scripts into page according to the script dependencies, and for making additional data available for the script.

class mHeader {

    private $scripts = array();

    /**
     * @param string $id        Unique script identifier
     * @param string $src      Script src attribute
     * @param array  $deps       An array of dependencies ( script identifiers ).
     * @param array  $data       An array, data that will be json_encoded and available to the script.
     */
    function enqueue_script($id, $src, $deps = array(), $data = array()) {
        $this->scripts[$id] = array('src' => $src, 'deps' => $deps, 'data' => $data);
    }

    private function dependencies($script) {
        if ($script['deps']) {
            return array_map(array($this, 'dependencies'), array_intersect_key($this->scripts, array_flip($script['deps'])));
        }
    }

    private function _unset($key, &$deps, &$out) {
        $out[$key] = $this->scripts[$key];
        unset($deps[$key]);
    }

    private function flattern(&$deps, &$out = array()) {

        foreach($deps as $key => $value) {
            empty($value) ? $this->_unset($key, $deps, $out) : $this->flattern( $deps[$key], $out);
        }
    }

    function print_scripts() {

        if (!$this->scripts)
            return;

        $deps = array_map(array($this, 'dependencies'), $this->scripts);
        while ($deps)
            $this->flattern($deps, $js);

        foreach($js as $key => $script) {
            $script['data'] && printf("<script> var %s = %s; </script>" . PHP_EOL, key($script['data']), json_encode(current( $script['data'])));
            echo "<script id=\"$key-js\" src=\"$script[src]\" type=\"text/javascript\"></script>" . PHP_EOL;
        }
    }
}

The call to the enqueue_script() function is for adding script, setting the source and dependencies on other scripts, and additional data needed for the script.

$header = new mHeader();

$header->enqueue_script('jquery-ui', '//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js', array('jquery'));
$header->enqueue_script('jquery', '//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js');
$header->enqueue_script('custom-script', '//custom-script.min.js', array('jquery-ui'), array('mydata' => array('value' => 20)));

$header->print_scripts();

And, print_scripts() method of the above example will send this output:

<script id="jquery-js" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" type="text/javascript"></script>
<script id="jquery-ui-js" src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js" type="text/javascript"></script>
<script> var mydata = {"value":20}; </script>
<script id="custom-script-js" src="//custom-script.min.js" type="text/javascript"></script>

Regardless the fact that the script 'jquery' is enqueued after the 'jquery-ui', it is printed before because it is defined in 'jquery-ui' that it depends on 'jquery'. Additional data for the 'custom-script' are inside a new script block and are placed in front of it, it contains mydata object that holds additional data, now available to 'custom-script'.

How do I get LaTeX to hyphenate a word that contains a dash?

I use package hyphenat and then write compound words like Finnish word Internet-yhteys (Eng. Internet connection) as Internet\hyp yhteys. Looks goofy but seems to be the most elegant way I've found.

How to fix HTTP 404 on Github Pages?

If you saw 404 even everything looks right, try switching https/http.

The original question has the url wrong, usually you can check repo settings and found the correct url for generated site.

However I have everything set up correctly, and the setting page said it's published, then I still saw 404.

Thanks for the comment of @Rohit Suthar (though that comment was to use https), I changed the url to http and it worked, then https worked too.

Jquery checking success of ajax post

The documentation is here: http://docs.jquery.com/Ajax/jQuery.ajax

But, to summarize, the ajax call takes a bunch of options. the ones you are looking for are error and success.

You would call it like this:

$.ajax({
  url: 'mypage.html',
  success: function(){
    alert('success');
  },
  error: function(){
    alert('failure');
  }
});

I have shown the success and error function taking no arguments, but they can receive arguments.

The error function can take three arguments: XMLHttpRequest, textStatus, and errorThrown.

The success function can take two arguments: data and textStatus. The page you requested will be in the data argument.

jQuery checkbox change and click event

Try

_x000D_
_x000D_
checkbox1.onclick= e => {
  if(!checkbox1.checked) checkbox1.checked = !confirm("Are you sure?");
  textbox1.value = checkbox1.checked;
}
_x000D_
<input type="checkbox" id="checkbox1" /><br />
<input type="text" id="textbox1" value='false'/>
_x000D_
_x000D_
_x000D_

How to resize the jQuery DatePicker control

The Jacob Tsui solution works perfect for me:

$('#event_date').datepicker({
    showButtonPanel: true,
    dateFormat: "mm/dd/yy",
    beforeShow: function(){ 
        $(".ui-datepicker").css('font-size', 12)
    }
});

jQuery loop over JSON result from AJAX Success?

I use .map for foreach. For example

success: function(data) {
  let dataItems = JSON.parse(data)
  dataItems = dataItems.map((item) => {
    return $(`<article>
                <h2>${item.post_title}</h2>
                <p>${item.post_excerpt}</p>
              </article>`)
  })
},

redistributable offline .NET Framework 3.5 installer for Windows 8

After several month without real solution for this problem, I suppose that the best solution is to upgrade the application to .NET framework 4.0, which is supported by Windows 8, Windows 10 and Windows 2012 Server by default and it is still available as offline installation for Windows XP.

Visual Studio 2010 shortcut to find classes and methods?

Ctrl+K,Ctrl+R opens the Object Browser in Visual Studio 2010. Find what you're looking for by searching and browsing and filtering the results. See also Ctrl+Alt+J. ^K ^R is better because it puts your caret right in the search box, ready to type your new search, even when the Object Browser is already open.

Set the Browse list on the top left to where you want to look to get started. From there you can use the search box (2nd text box from the top, goes all the way across the Object Browser window) or you can just go through everything from the tree on the left. Searches are temporary but the "selected components" set by the Browse list persists. Set a custom set with the little "..." button just to the right of the list.

Objects, packages, namespaces, types, etc. on the left; fields, methods, constants, etc. on the top right, docstrings on the lower right.

The display mode of a pane can be changed by right-clicking in the empty space of the window; tree organized by assembly/container or by namespace and other preferences.

Items can be right-clicked to find, copy and filter.

For keyboard navigation, use Ctrl+K,Ctrl+R from anywhere to start a new search, Enter to execute the search you just typed or pasted and Ctrl+F6 to make the Object Browser close. ALT+<-- to go back and ALT+--> to go forward through the search history. More can be set; search for "ObjectBrowser" in the keyboard shortcut config.

If the key shortcuts above don't work, Object Browser should be in the View menu somewhere with a different shortcut. If all else fails, search for "ObjectBrowser" under Tools->Options->Environment->Keyboard->"Show commands containing".

Check if a column contains text using SQL

Suppose STUDENTID contains some characters or numbers that you already know i.e. 'searchstring' then below query will work for you.

You could try this:

select * from STUDENTS where CHARINDEX('searchstring',STUDENTID)>0

I think this one is the fastest and easiest one.

Grant Select on all Tables Owned By Specific User

Well, it's not a single statement, but it's about as close as you can get with oracle:

BEGIN
   FOR R IN (SELECT owner, table_name FROM all_tables WHERE owner='TheOwner') LOOP
      EXECUTE IMMEDIATE 'grant select on '||R.owner||'.'||R.table_name||' to TheUser';
   END LOOP;
END; 

How Do I Get the Query Builder to Output Its Raw SQL Query as a String?

First way:

Simply you can do following stuff using toSql() method,

$query = DB::table('users')->get();

echo $query->toSql();

If it's not working you can set-up the thing from laravel documentation.

Second way:

Another way to do it is

DB::getQueryLog()

but if it's returns an empty array then by default it's disabled visit this,

just enable with DB::enableQueryLog() and it will work :)

for more info visit Github Issue to know more about it.

Hope it helps :)

how to write procedure to insert data in to the table in phpmyadmin?

Try this-

CREATE PROCEDURE simpleproc (IN name varchar(50),IN user_name varchar(50),IN branch varchar(50))
BEGIN
    insert into student (name,user_name,branch) values (name ,user_name,branch);
END

How to display (print) vector in Matlab?

You can use

x = [1, 2, 3]
disp(sprintf('Answer: (%d, %d, %d)', x))

This results in

Answer: (1, 2, 3)

For vectors of arbitrary size, you can use

disp(strrep(['Answer: (' sprintf(' %d,', x) ')'], ',)', ')'))

An alternative way would be

disp(strrep(['Answer: (' num2str(x, ' %d,') ')'], ',)', ')'))

pandas dataframe create new columns and fill with calculated values from same df

You can do this easily manually for each column like this:

df['A_perc'] = df['A']/df['sum']

If you want to do this in one step for all columns, you can use the div method (http://pandas.pydata.org/pandas-docs/stable/basics.html#matching-broadcasting-behavior):

ds.div(ds['sum'], axis=0)

And if you want this in one step added to the same dataframe:

>>> ds.join(ds.div(ds['sum'], axis=0), rsuffix='_perc')
          A         B         C         D       sum    A_perc    B_perc  \
1  0.151722  0.935917  1.033526  0.941962  3.063127  0.049532  0.305543   
2  0.033761  1.087302  1.110695  1.401260  3.633017  0.009293  0.299283   
3  0.761368  0.484268  0.026837  1.276130  2.548603  0.298739  0.190013   

     C_perc    D_perc  sum_perc  
1  0.337409  0.307517         1  
2  0.305722  0.385701         1  
3  0.010530  0.500718         1  

How to implement zoom effect for image view in android?

Below is the code for ImageFullViewActivity Class

 public class ImageFullViewActivity extends AppCompatActivity {

        private ScaleGestureDetector mScaleGestureDetector;
        private float mScaleFactor = 1.0f;
        private ImageView mImageView;

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

            mImageView = (ImageView) findViewById(R.id.imageView);
            mScaleGestureDetector = new ScaleGestureDetector(this, new ScaleListener());

        }

        @Override
        public boolean onTouchEvent(MotionEvent motionEvent) {
            mScaleGestureDetector.onTouchEvent(motionEvent);
            return true;
        }

        private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
            @Override
            public boolean onScale(ScaleGestureDetector scaleGestureDetector) {
                mScaleFactor *= scaleGestureDetector.getScaleFactor();
                mScaleFactor = Math.max(0.1f,
                        Math.min(mScaleFactor, 10.0f));
                mImageView.setScaleX(mScaleFactor);
                mImageView.setScaleY(mScaleFactor);
                return true;
            }
        }
    }

How do I redirect a user when a button is clicked?

You can easily wrap your button tag with tag.Using Url.Action() HTML Helper this will get to navigate to one page to another.

<a href='@Url.Action("YourAction", "YourController")'>
    <input type='button' value='Dummy Button' />
</a>

If you want to navigate with javascript onclick() function then use

<input type='button' value='Dummy Button' onclick='window.location = "@Url.Action("YourAction", "YourController")";' />

PHP/MySQL Insert null values

I think you need quotes around your {$row['null_field']}, so '{$row['null_field']}'

If you don't have the quotes, you'll occasionally end up with an insert statement that looks like this: insert into table2 (f1, f2) values ('val1',) which is a syntax error.

If that is a numeric field, you will have to do some testing above it, and if there is no value in null_field, explicitly set it to null..

How to set an environment variable from a Gradle build?

You can also "prepend" the environment variable setting by using 'environment' command:

run.doFirst { environment 'SPARK_LOCAL_IP', 'localhost' }

Non greedy (reluctant) regex matching in sed?

sed 's|(http:\/\/[^\/]+\/).*|\1|'

C#: Waiting for all threads to complete

I still think using Join is simpler. Record the expected completion time (as Now+timeout), then, in a loop, do

if(!thread.Join(End-now))
    throw new NotFinishedInTime();

What are the differences between virtual memory and physical memory?

See here: Physical Vs Virtual Memory

Virtual memory is stored on the hard drive and is used when the RAM is filled. Physical memory is limited to the size of the RAM chips installed in the computer. Virtual memory is limited by the size of the hard drive, so virtual memory has the capability for more storage.

How to custom switch button?

switch

 <androidx.appcompat.widget.SwitchCompat
     android:layout_centerVertical="true"
     android:layout_alignParentRight="true"
     app:track="@drawable/track"
     android:thumb="@drawable/thumb"
     android:id="@+id/switch1"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content" />

thumb.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_checked="false"
        android:drawable="@drawable/switch_thumb_false"/>

    <item android:state_checked="true"
        android:drawable="@drawable/switch_thumb_true"/>

</selector>

track.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">


    <item android:state_checked="false">
        <shape android:shape="rectangle">

            <size android:width="24dp" android:height="12dp" />
            <solid android:color="#EFE0BB" />
            <corners android:radius="6dp" />
        </shape>
    </item>

    <item android:state_checked="true">

        <shape android:shape="rectangle">

            <size android:width="24dp" android:height="12dp" />
            <solid android:color="@color/colorPrimary" />
            <corners android:radius="6dp" />
        </shape>
    </item>

</selector>

switch_thumb_true.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item>
        <shape android:shape="oval">
            <solid android:color="#EFE0BB" />
            <size
                android:width="10dp"
                android:height="10dp" />
            <stroke
                android:width="2dp"
                android:color="@color/colorPrimary" />
        </shape>
    </item>
</layer-list>

switch_thumb_false.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item >
        <shape android:shape="oval">
            <solid android:color="@color/colorPrimary"/>
            <size android:height="12dp"
                android:width="12dp"/>
            <stroke android:color="#EFE0BB"
                android:width="2dp"/>
        </shape>
    </item>

</layer-list>

Calculating Time Difference

Here is a piece of code to do so:

def(StringChallenge(str1)):

#str1 = str1[1:-1]
h1 = 0
h2 = 0
m1 = 0
m2 = 0

def time_dif(h1,m1,h2,m2):
    if(h1 == h2):
        return m2-m1
    else:
        return ((h2-h1-1)*60 + (60-m1) + m2)
count_min = 0

if str1[1] == ':':
    h1=int(str1[:1])
    m1=int(str1[2:4])
else:
    h1=int(str1[:2])
    m1=int(str1[3:5])

if str1[-7] == '-':
    h2=int(str1[-6])
    m2=int(str1[-4:-2])
else:
    h2=int(str1[-7:-5])
    m2=int(str1[-4:-2])

if h1 == 12:
    h1 = 0
if h2 == 12:
    h2 = 0

if "am" in str1[:8]:
    flag1 = 0
else:
    flag1= 1

if "am" in str1[7:]:
    flag2 = 0
else:
    flag2 = 1

if flag1 == flag2:
    if h2 > h1 or (h2 == h1 and m2 >= m1):
        count_min += time_dif(h1,m1,h2,m2)
    else:
        count_min += 1440 - time_dif(h2,m2,h1,m1)
else:
    count_min += (12-h1-1)*60
    count_min += (60 - m1)
    count_min += (h2*60)+m2


return count_min

How to run Pip commands from CMD

In my case I was trying to install Flask. I wanted to run pip install Flask command. But when I open command prompt it I goes to C:\Users[user]>. If you give here it will say pip is not recognized. I did below steps

On your desktop right click Computer and select Properties

Select Advanced Systems Settings

In popup which you see select Advanced tab and then click Environment Variables

In popup double click PATH and from popup copy variable value for variable name PATH and paste the variable value in notepad or so and look for an entry for Python.

In my case it was C:\Users\[user]\AppData\Local\Programs\Python\Python36-32

Now in my command prompt i moved to above location and gave pip install Flask

enter image description here

delete vs delete[] operators in C++

The operators delete and delete [] are used respectively to destroy the objects created with new and new[], returning to the allocated memory left available to the compiler's memory manager.

Objects created with new must necessarily be destroyed with delete, and that the arrays created with new[] should be deleted with delete[].

How does Junit @Rule work?

The explanation for how it works:

JUnit wraps your test method in a Statement object so statement and Execute() runs your test. Then instead of calling statement.Execute() directly to run your test, JUnit passes the Statement to a TestRule with the @Rule annotation. The TestRule's "apply" function returns a new Statement given the Statement with your test. The new Statement's Execute() method can call the test Statement's execute method (or not, or call it multiple times), and do whatever it wants before and after.

Now, JUnit has a new Statement that does more than just run the test, and it can again pass that to any more rules before finally calling Execute.

Copy files without overwrite

You can try this:

echo n | copy /-y <SOURCE> <DESTINATION>

-y simply prompts before overwriting and we can pipe n to all those questions. So this would in essence just copy non-existing files. :)

How can I remove the "No file chosen" tooltip from a file input in Chrome?

Across all browsers and simple. this did it for me

_x000D_
_x000D_
$(function () {_x000D_
     $('input[type="file"]').change(function () {_x000D_
          if ($(this).val() != "") {_x000D_
                 $(this).css('color', '#333');_x000D_
          }else{_x000D_
                 $(this).css('color', 'transparent');_x000D_
          }_x000D_
     });_x000D_
})
_x000D_
input[type="file"]{_x000D_
    color: transparent;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<input type="file" name="app_cvupload" class="fullwidth input rqd">
_x000D_
_x000D_
_x000D_

how to add script inside a php code?

You could use PHP's file_get_contents();

<?php

   $script = file_get_contents('javascriptFile.js');
   echo "<script>".$script."</script>";

?>

For more information on the function:

http://php.net/manual/en/function.file-get-contents.php

Reflection generic get field value

Like answered before, you should use:

Object value = field.get(objectInstance);

Another way, which is sometimes prefered, is calling the getter dynamically. example code:

public static Object runGetter(Field field, BaseValidationObject o)
{
    // MZ: Find the correct method
    for (Method method : o.getMethods())
    {
        if ((method.getName().startsWith("get")) && (method.getName().length() == (field.getName().length() + 3)))
        {
            if (method.getName().toLowerCase().endsWith(field.getName().toLowerCase()))
            {
                // MZ: Method found, run it
                try
                {
                    return method.invoke(o);
                }
                catch (IllegalAccessException e)
                {
                    Logger.fatal("Could not determine method: " + method.getName());
                }
                catch (InvocationTargetException e)
                {
                    Logger.fatal("Could not determine method: " + method.getName());
                }

            }
        }
    }


    return null;
}

Also be aware that when your class inherits from another class, you need to recursively determine the Field. for instance, to fetch all Fields of a given class;

    for (Class<?> c = someClass; c != null; c = c.getSuperclass())
    {
        Field[] fields = c.getDeclaredFields();
        for (Field classField : fields)
        {
            result.add(classField);
        }
    }

What are ABAP and SAP?

SAP is a company and offers a full Enterprise Resource Planning (ERP) system, business platform, and the associated modules (financials, general ledger, &c).

ABAP is the primary programming language used to write SAP software and customizations. It would do it injustice to think of it as COBOL and SQL on steroids, but that gives you an idea. ABAP runs within the SAP system.

SAP and ABAP abstract the DB and run atop various underlying DBMSs.

SAP produces other things as well and even publicly says they dabble in Java and even produce a J2EE container, but tried-and-true SAP is ABAP through-and-through.

How to check if a date is greater than another in Java?

You can use Date.before() or Date.after() or Date.equals() for date comparison.

Taken from here:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateDiff {

    public static void main( String[] args )
    {
        compareDates("2017-01-13 00:00:00", "2017-01-14 00:00:00");// output will be Date1 is before Date2
        compareDates("2017-01-13 00:00:00", "2017-01-12 00:00:00");//output will be Date1 is after Date2
        compareDates("2017-01-13 00:00:00", "2017-01-13 10:20:30");//output will be Date1 is before Date2 because date2 is ahead of date 1 by 10:20:30 hours
        compareDates("2017-01-13 00:00:00", "2017-01-13 00:00:00");//output will be Date1 is equal Date2 because both date and time are equal
    }

    public static void compareDates(String d1,String d2)
    {
        try{
            // If you already have date objects then skip 1

            //1
            // Create 2 dates starts
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date1 = sdf.parse(d1);
            Date date2 = sdf.parse(d2);

            System.out.println("Date1"+sdf.format(date1));
            System.out.println("Date2"+sdf.format(date2));System.out.println();

            // Create 2 dates ends
            //1

            // Date object is having 3 methods namely after,before and equals for comparing
            // after() will return true if and only if date1 is after date 2
            if(date1.after(date2)){
                System.out.println("Date1 is after Date2");
            }
            // before() will return true if and only if date1 is before date2
            if(date1.before(date2)){
                System.out.println("Date1 is before Date2");
            }

            //equals() returns true if both the dates are equal
            if(date1.equals(date2)){
                System.out.println("Date1 is equal Date2");
            }

            System.out.println();
        }
        catch(ParseException ex){
            ex.printStackTrace();
        }
    }

    public static void compareDates(Date date1,Date date2)
    {
        // if you already have date objects then skip 1
        //1

        //1

        //date object is having 3 methods namely after,before and equals for comparing
        //after() will return true if and only if date1 is after date 2
        if(date1.after(date2)){
            System.out.println("Date1 is after Date2");
        }

        //before() will return true if and only if date1 is before date2
        if(date1.before(date2)){
            System.out.println("Date1 is before Date2");
        }

        //equals() returns true if both the dates are equal
        if(date1.equals(date2)){
            System.out.println("Date1 is equal Date2");
        }

        System.out.println();
    }
}

Cannot inline bytecode built with JVM target 1.8 into bytecode that is being built with JVM target 1.6

In my case, I solved this by following these two steps

1. Go to android studio preferences -> other settings -> kotlin compiler -> set Target JVM version = 1.8 
   if it doesn't work then go to the second option.

2. In your module-level build.gradle file add 
   compileOptions {
        sourceCompatibility = 1.8
        targetCompatibility = 1.8
    }
    tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all {
        kotlinOptions {
            jvmTarget = "1.8"
        }
    }

How to check if all list items have the same value and return it, or return an “otherValue” if they don’t?

An alternative to using LINQ:

var set = new HashSet<int>(values);
return (1 == set.Count) ? values.First() : otherValue;

I have found using HashSet<T> is quicker for lists of up to ~ 6,000 integers compared with:

var value1 = items.First();
return values.All(v => v == value1) ? value1: otherValue;

How to tune Tomcat 5.5 JVM Memory settings without using the configuration program

Create a setenv.(sh|bat) file in the tomcat/bin directory with the environment variables that you want modified.

The catalina script checks if the setenv script exists and runs it to set the environment variables. This way you can change the parameters to only one instance of tomcat and is easier to copy it to another instance.

Probably your configuration app has created the setenv script and thats why tomcat is ignoring the environment variables.

How to solve munmap_chunk(): invalid pointer error in C++

This happens when the pointer passed to free() is not valid or has been modified somehow. I don't really know the details here. The bottom line is that the pointer passed to free() must be the same as returned by malloc(), realloc() and their friends. It's not always easy to spot what the problem is for a novice in their own code or even deeper in a library. In my case, it was a simple case of an undefined (uninitialized) pointer related to branching.

The free() function frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc() or realloc(). Otherwise, or if free(ptr) has already been called before, undefined behavior occurs. If ptr is NULL, no operation is performed. GNU 2012-05-10 MALLOC(3)

char *words; // setting this to NULL would have prevented the issue

if (condition) {
    words = malloc( 512 );

    /* calling free sometime later works here */

    free(words)
} else {

    /* do not allocate words in this branch */
}

/* free(words);  -- error here --
*** glibc detected *** ./bin: munmap_chunk(): invalid pointer: 0xb________ ***/

There are many similar questions here about the related free() and rellocate() functions. Some notable answers providing more details:

*** glibc detected *** free(): invalid next size (normal): 0x0a03c978 ***
*** glibc detected *** sendip: free(): invalid next size (normal): 0x09da25e8 ***
glibc detected, realloc(): invalid pointer


IMHO running everything in a debugger (Valgrind) is not the best option because errors like this are often caused by inept or novice programmers. It's more productive to figure out the issue manually and learn how to avoid it in the future.

Finding Number of Cores in Java

int cores = Runtime.getRuntime().availableProcessors();

If cores is less than one, either your processor is about to die, or your JVM has a serious bug in it, or the universe is about to blow up.

Formatting Numbers by padding with leading zeros in SQL Server

I am posting all at one place, all works for me to pad with 4 leading zero :)

declare @number int =  1;
print right('0000' + cast(@number as varchar(4)) , 4)
print right('0000' + convert(varchar(4), @number) , 4)
print right(replicate('0',4) + convert(varchar(4), @number) , 4)
print  cast(replace(str(@number,4),' ','0')as char(4))
print format(@number,'0000')

How to validate an OAuth 2.0 access token for a resource server?

An update on @Scott T.'s answer: the interface between Resource Server and Authorization Server for token validation was standardized in IETF RFC 7662 in October 2015, see: https://tools.ietf.org/html/rfc7662. A sample validation call would look like:

POST /introspect HTTP/1.1
Host: server.example.com
Accept: application/json
Content-Type: application/x-www-form-urlencoded
Authorization: Bearer 23410913-abewfq.123483

token=2YotnFZFEjr1zCsicMWpAA

and a sample response:

HTTP/1.1 200 OK
Content-Type: application/json

{
  "active": true,
  "client_id": "l238j323ds-23ij4",
  "username": "jdoe",
  "scope": "read write dolphin",
  "sub": "Z5O3upPC88QrAjx00dis",
  "aud": "https://protected.example.net/resource",
  "iss": "https://server.example.com/",
  "exp": 1419356238,
  "iat": 1419350238,
  "extension_field": "twenty-seven"
}

Of course adoption by vendors and products will have to happen over time.

what is trailing whitespace and how can I handle this?

I have got similar pep8 warning W291 trailing whitespace

long_text = '''Lorem Ipsum is simply dummy text  <-remove whitespace
of the printing and typesetting industry.'''

Try to explore trailing whitespaces and remove them. ex: two whitespaces at the end of Lorem Ipsum is simply dummy text

json_decode() expects parameter 1 to be string, array given

Set decoding to true

Your decoding is not set to true. If you don't have access to set the source to true. The code below will fix it for you.

$WorkingArray = json_decode(json_encode($data),true);

Is it possible to run .APK/Android apps on iPad/iPhone devices?

The app can't be run natively, but it could be run on an emulator. You can use ManyMo to embed them in a website and make users add your app to their home screen. This link should be useful for making the app more realistic. Users could then only press the share button and add the app to their home screen. All data will be deleted when the "app" is closed in their iOS devices so you should use the Internet/cloud for storage. It can't access camera or multi touch, but it may be useful.

Java Byte Array to String to Byte Array

You can't just take the returned string and construct a string from it... it's not a byte[] data type anymore, it's already a string; you need to parse it. For example :

String response = "[-47, 1, 16, 84, 2, 101, 110, 83, 111, 109, 101, 32, 78, 70, 67, 32, 68, 97, 116, 97]";      // response from the Python script

String[] byteValues = response.substring(1, response.length() - 1).split(",");
byte[] bytes = new byte[byteValues.length];

for (int i=0, len=bytes.length; i<len; i++) {
   bytes[i] = Byte.parseByte(byteValues[i].trim());     
}

String str = new String(bytes);

** EDIT **

You get an hint of your problem in your question, where you say "Whatever I seem to try I end up getting a byte array which looks as follows... [91, 45, ...", because 91 is the byte value for [, so [91, 45, ... is the byte array of the string "[-45, 1, 16, ..." string.

The method Arrays.toString() will return a String representation of the specified array; meaning that the returned value will not be a array anymore. For example :

byte[] b1 = new byte[] {97, 98, 99};

String s1 = Arrays.toString(b1);
String s2 = new String(b1);

System.out.println(s1);        // -> "[97, 98, 99]"
System.out.println(s2);        // -> "abc";

As you can see, s1 holds the string representation of the array b1, while s2 holds the string representation of the bytes contained in b1.

Now, in your problem, your server returns a string similar to s1, therefore to get the array representation back, you need the opposite constructor method. If s2.getBytes() is the opposite of new String(b1), you need to find the opposite of Arrays.toString(b1), thus the code I pasted in the first snippet of this answer.

How to read the Stock CPU Usage data

So far this has been the most helpful source of information regarding this I could find. Apparently the numbers do NOT reperesent load average in %: http://forum.xda-developers.com/showthread.php?t=1495763

How to connect to LocalDB in Visual Studio Server Explorer?

It worked for me.

  1. Open command prompt
  2. Run "SqlLocalDB.exe start"
  3. System response "LocalDB instance "mssqllocaldb" started."
  4. In VS, View/Server Explorer/(Right click) Data Connections/Add Connection
    • Data Source: Microsoft SQL Server (SqlClient)
    • Server name: (localdb)\MSSQLLocalDB
    • Log on to the server: Use Windows Authentication
  5. Press "Test Connection", Then OK.

How do I count the number of rows and columns in a file using bash?

For rows you can simply use wc -l file

-l stands for total line

for columns uou can simply use head -1 file | tr ";" "\n" | wc -l

Explanation
head -1 file
Grabbing the first line of your file, which should be the headers, and sending to it to the next cmd through the pipe
| tr ";" "\n"

tr stands for translate.
It will translate all ; characters into a newline character.
In this example ; is your delimiter.

Then it sends data to next command.

wc -l
Counts the total number of lines.

Installing Java on OS X 10.9 (Mavericks)

The right place to download the JDK for Java 7 is Java SE Downloads.

All the other links provided above, as far as I can tell, either provide the JRE or Java 6 downloads (incidentally, if you want to run Eclipse or other IDEs, like IntelliJ IDEA, you will need the JDK, not the JRE).

Regarding IntelliJ IDEA - that will still ask you to install Java 6 as it apparently needs an older class loader or something: just follow the instructions when the dialog pop-up appears and it will install the JDK 6 in the right place.

Afterwards, you will need to do the sudo ln -snf mentioned in the answer above:

sudo ln -nsf /Library/Java/JavaVirtualMachines/jdk1.7.0_45.jdk/Contents \
    /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK

(copied here as it was mentioned that "above" may eventually not make sense as answers are re-sorted).

I also set my JAVA_HOME to point to where jdk_1.7.0_xx.jdk was installed:

export JAVA_HOME="/Library/Java/JavaVirtualMachines/jdk1.7.0_45.jdk/Contents/Home"

Then add that to your PATH:

export PATH=$JAVA_HOME/bin:$PATH

The alternative is to fuzz around with Apple's insane maze of hyperlinks, but honestly life is too short to bother.

Ruby on Rails form_for select field with class

You can also add prompt option like this.

<%= f.select(:object_field, ['Item 1', 'Item 2'], {include_blank: "Select something"}, { :class => 'my_style_class' }) %>

File Upload using AngularJS

Above accepted answer is not browser compatible. If some one has compatibility issue try this.

Fiddle

View Code

 <div ng-controller="MyCtrl">
      <input type="file" id="file" name="file"/>
      <br>
      <button ng-click="add()">Add</button>
      <p>{{data}}</p>
    </div>

Controller code

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
    $scope.data = 'none';    
    $scope.add = function(){
      var f = document.getElementById('file').files[0],
          r = new FileReader();
      r.onloadend = function(e){        
          var binary = "";
var bytes = new Uint8Array(e.target.result);
var length = bytes.byteLength;

for (var i = 0; i < length; i++) 
{
    binary += String.fromCharCode(bytes[i]);
}

$scope.data = (binary).toString();

          alert($scope.data);
      }
      r.readAsArrayBuffer(f);
    }
}

How do I convert a date/time to epoch time (unix time/seconds since 1970) in Perl?

Possibly one of the better examples of 'There's More Than One Way To Do It", with or without the help of CPAN.

If you have control over what you get passed as a 'date/time', I'd suggest going the DateTime route, either by using a specific Date::Time::Format subclass, or using DateTime::Format::Strptime if there isn't one supporting your wacky date format (see the datetime FAQ for more details). In general, Date::Time is the way to go if you want to do anything serious with the result: few classes on CPAN are quite as anal-retentive and obsessively accurate.

If you're expecting weird freeform stuff, throw it at Date::Parse's str2time() method, which'll get you a seconds-since-epoch value you can then have your wicked way with, without the overhead of Date::Manip.

How to join two sets in one line without using "|"

You can do union or simple list comprehension

[A.add(_) for _ in B]

A would have all the elements of B

Auto-click button element on page load using jQuery

We should rather use Javascript.

    <button href="images/car.jpg" id="myButton">
        Here is the Button to be clicked
    </button>


    <script>

        $(document).ready(function(){
            document.getElementById("myButton").click();
        });

    </script>

How to change Screen buffer size in Windows Command Prompt from batch script

There is no "DOS command prompt". DOS fully died with Windows ME (7/11/2006). It's simply called the Command Prompt on Windows NT (which is NT, 2K, XP, Vista, 7).

There is no way to alter the screen buffer through built-in cmd.exe commands. It can be altered through Console API Functions, so you might be able to create a utility to modify it. I've never tried this myself.

Another suggestion would be to redirect output to both a file and to the screen so that you have a "hard copy" of it. Windows does not have a TEE command like Unix, but someone has remedied that.

How to fit Windows Form to any screen resolution?

int h = Screen.PrimaryScreen.WorkingArea.Height;
int w = Screen.PrimaryScreen.WorkingArea.Width;
this.ClientSize = new Size(w , h);

Getting "cannot find Symbol" in Java project in Intellij

I know this thread is old but, another solution was to run

$ mvn clean install -Dmaven.test.skip=true

And on IntelliJ do CMD + Shift + A (mac os) -> type "Reimport all Maven projects".

If that doesn't work, try forcing maven dependencies to be re-downloaded

$ mvn clean -U install -Dmaven.test.skip=true

DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") is returning AM time instead of PM time?

Use HH for 24 hour hours format:

DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")

Or the tt format specifier for the AM/PM part:

DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt")

Take a look at the custom Date and Time format strings documentation.

How to output oracle sql result into a file in windows?

Having the same chore on windows 10, and windows server 2012. I found the following solution:

echo quit |sqlplus schemaName/schemaPassword@sid @plsqlScript.sql > outputFile.log

Explanation

echo quit | send the quit command to exit sqlplus after the script completes

sqlplus schemaName/schemaPassword@sid @plsqlScript.sql execute plssql script plsqlScript.sql in schema schemaName with password schemaPassword connecting to SID sid

> outputFile.log redirect sqlplus output to log file outputFile.log

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: select * from `songs` where `id` = 5 limit 1)

Just Go to Model file of the corresponding Controller and check the primary key filed name

such as

protected $primaryKey = 'info_id';

here info id is field name available in database table

More info can be found at "Primary Keys" section of the docs.

How to convert a Java 8 Stream to an Array?

     Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6);

     Integer[] integers = stream.toArray(it->new Integer[it]);

What is ADT? (Abstract Data Type)

In programming languages, a type is some data and the associated operations. An ADT is a user defined data aggregate and the operations over these data and is characterized by encapsulation, the data and operations are represented, or at list declared, in a single syntactic unit, and information hiding, only the relevant operations are visible for the user of the ADT, the ADT interface, in the same way that a normal data type in the programming language. It's an abstraction because the internal representation of the data and implementation of the operations are of no concern to the ADT user.

Sql script to find invalid email addresses

MySQL

SELECT * FROM `emails` WHERE `email`
NOT REGEXP '[-a-z0-9~!$%^&*_=+}{\\\'?]+(\\.[-a-z0-9~!$%^&*_=+}{\\\'?]+)*@([a-z0-9_][-a-z0-9_]*(\\.[-a-z0-9_]+)*\\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}))(:[0-9]{1,5})?'

How do you force a makefile to rebuild a target

You could declare one or more of your targets to be phony.

A phony target is one that is not really the name of a file; rather it is just a name for a recipe to be executed when you make an explicit request. There are two reasons to use a phony target: to avoid a conflict with a file of the same name, and to improve performance.

...

A phony target should not be a prerequisite of a real target file; if it is, its recipe will be run every time make goes to update that file. As long as a phony target is never a prerequisite of a real target, the phony target recipe will be executed only when the phony target is a specified goal

Sanitizing strings to make them URL and filename safe?

I don't think having a list of chars to remove is safe. I would rather use the following:

For filenames: Use an internal ID or a hash of the filecontent. Save the document name in a database. This way you can keep the original filename and still find the file.

For url parameters: Use urlencode() to encode any special characters.

Positioning background image, adding padding

In case anyone else needs to add padding to something with background-image and background-size: contain or cover, I used the following which is a nice way of doing it. You can replace the border-width with 10% or 2vw or whatever you like.

.bg-image {
    background: url("/image/logo.png") no-repeat center #ffffff / contain;
    border: inset 10px transparent;
    box-sizing: border-box;
}

This means you don't have to define a width.

How to view log output using docker-compose run?

If you want to see output logs from all the services in your terminal.

docker-compose logs -t -f --tail <no of lines> 

Eg.: Say you would like to log output of last 5 lines from all service

docker-compose logs -t -f --tail 5

If you wish to log output from specific services then it can be done as below:

docker-compose logs -t -f --tail <no of lines> <name-of-service1> <name-of-service2> ... <name-of-service N>

Usage:

Eg. say you have API and portal services then you can do something like below :

docker-compose logs -t -f --tail 5 portal api

Where 5 represents last 5 lines from both logs.

Ref: https://docs.docker.com/v17.09/engine/admin/logging/view_container_logs/

Reading a key from the Web.Config using ConfigurationManager

Also you can try this line to get string value from app.config file.

var strName= ConfigurationManager.AppSettings["stringName"];

ConcurrentHashMap vs Synchronized HashMap

A simple performance test for ConcurrentHashMap vs Synchronized HashMap . The test flow is calling put in one thread and calling get in three threads on Map concurrently. As @trshiv said, ConcurrentHashMap has higher throughput and speed for whose reading operation without lock. The result is when operation times is over 10^7, ConcurrentHashMap is 2x faster than Synchronized HashMap.

How to divide flask app into multiple py files?

This task can be accomplished without blueprints and tricky imports using Centralized URL Map

app.py

import views
from flask import Flask

app = Flask(__name__)

app.add_url_rule('/', view_func=views.index)
app.add_url_rule('/other', view_func=views.other)

if __name__ == '__main__':
    app.run(debug=True, use_reloader=True)

views.py

from flask import render_template

def index():
    return render_template('index.html')

def other():
    return render_template('other.html')

CSS How to set div height 100% minus nPx

Use an outer wrapper div set to 100% and then your inner wrapper div 100% should be now relative to that.

I thought for sure this used to work for me, but apparently not:

<html>
<body>
<div id="outerwrapper" style="border : 1px solid red ; height : 100%">
<div id="header" style="border : 1px solid blue ; height : 60px"></div>
<div id="wrapper"  style="border : 1px solid green ; height : 100% ; overflow : scroll ;">
  <div id="left" style="height : 100% ; width : 50% ; overflow : scroll; float : left ; clear : left ;">Some text 

on the left</div>
  <div id="right" style="height : 100% ; width 50% ; overflow : scroll; float : left ;">Some Text on the 

right</div>
</div>
</div>
</body>
</html>

Sleep/Wait command in Batch

You want to use timeout. timeout 10 will sleep 10 seconds

'and' (boolean) vs '&' (bitwise) - Why difference in behavior with lists vs numpy arrays?

About list

First a very important point, from which everything will follow (I hope).

In ordinary Python, list is not special in any way (except having cute syntax for constructing, which is mostly a historical accident). Once a list [3,2,6] is made, it is for all intents and purposes just an ordinary Python object, like a number 3, set {3,7}, or a function lambda x: x+5.

(Yes, it supports changing its elements, and it supports iteration, and many other things, but that's just what a type is: it supports some operations, while not supporting some others. int supports raising to a power, but that doesn't make it very special - it's just what an int is. lambda supports calling, but that doesn't make it very special - that's what lambda is for, after all:).

About and

and is not an operator (you can call it "operator", but you can call "for" an operator too:). Operators in Python are (implemented through) methods called on objects of some type, usually written as part of that type. There is no way for a method to hold an evaluation of some of its operands, but and can (and must) do that.

The consequence of that is that and cannot be overloaded, just like for cannot be overloaded. It is completely general, and communicates through a specified protocol. What you can do is customize your part of the protocol, but that doesn't mean you can alter the behavior of and completely. The protocol is:

Imagine Python interpreting "a and b" (this doesn't happen literally this way, but it helps understanding). When it comes to "and", it looks at the object it has just evaluated (a), and asks it: are you true? (NOT: are you True?) If you are an author of a's class, you can customize this answer. If a answers "no", and (skips b completely, it is not evaluated at all, and) says: a is my result (NOT: False is my result).

If a doesn't answer, and asks it: what is your length? (Again, you can customize this as an author of a's class). If a answers 0, and does the same as above - considers it false (NOT False), skips b, and gives a as result.

If a answers something other than 0 to the second question ("what is your length"), or it doesn't answer at all, or it answers "yes" to the first one ("are you true"), and evaluates b, and says: b is my result. Note that it does NOT ask b any questions.

The other way to say all of this is that a and b is almost the same as b if a else a, except a is evaluated only once.

Now sit for a few minutes with a pen and paper, and convince yourself that when {a,b} is a subset of {True,False}, it works exactly as you would expect of Boolean operators. But I hope I have convinced you it is much more general, and as you'll see, much more useful this way.

Putting those two together

Now I hope you understand your example 1. and doesn't care if mylist1 is a number, list, lambda or an object of a class Argmhbl. It just cares about mylist1's answer to the questions of the protocol. And of course, mylist1 answers 5 to the question about length, so and returns mylist2. And that's it. It has nothing to do with elements of mylist1 and mylist2 - they don't enter the picture anywhere.

Second example: & on list

On the other hand, & is an operator like any other, like + for example. It can be defined for a type by defining a special method on that class. int defines it as bitwise "and", and bool defines it as logical "and", but that's just one option: for example, sets and some other objects like dict keys views define it as a set intersection. list just doesn't define it, probably because Guido didn't think of any obvious way of defining it.

numpy

On the other leg:-D, numpy arrays are special, or at least they are trying to be. Of course, numpy.array is just a class, it cannot override and in any way, so it does the next best thing: when asked "are you true", numpy.array raises a ValueError, effectively saying "please rephrase the question, my view of truth doesn't fit into your model". (Note that the ValueError message doesn't speak about and - because numpy.array doesn't know who is asking it the question; it just speaks about truth.)

For &, it's completely different story. numpy.array can define it as it wishes, and it defines & consistently with other operators: pointwise. So you finally get what you want.

HTH,

Best way to split string into lines

string[] lines = input.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);

Change width of select tag in Twitter Bootstrap

For me Pawan's css class combined with display: inline-block (so the selects don't stack) works best. And I wrap it in a media-query, so it stays Mobile Friendly:

@media (min-width: $screen-xs) {

    .selectwidthauto {
         width:auto !important;
         display: inline-block;
    }

}

Split string into individual words Java

This regex will split word by space like space, tab, line break:

String[] str = s.split("\\s+");

Best way to create unique token in Rails?

Ryan Bates uses a nice little bit of code in his Railscast on beta invitations. This produces a 40 character alphanumeric string.

Digest::SHA1.hexdigest([Time.now, rand].join)

How do I use modulus for float/double?

You probably had a typo when you first ran it.

evaluating 0.5 % 0.3 returns '0.2' (A double) as expected.

Mindprod has a good overview of how modulus works in Java.

Copying a HashMap in Java

In Java, when you write:

Object objectA = new Object();
Object objectB = objectA;

objectA and objectB are the same and point to the same reference. Changing one will change the other. So if you change the state of objectA (not its reference) objectB will reflect that change too.

However, if you write:

objectA = new Object()

Then objectB is still pointing to the first object you created (original objectA) while objectA is now pointing to a new Object.