Programs & Examples On #Darcs

A distributed source code management system, with a simple command-line UI and precise merging.

VBScript to send email without running Outlook

Yes. Blat or any other self contained SMTP mailer. Blat is a fairly full featured SMTP client that runs from command line

Blat is here

Implementing a simple file download servlet

Try with Resource

File file = new File("Foo.txt");
try (PrintStream ps = new PrintStream(file)) {
response.setContentLength((int) file.length());
response.setHeader( "Content-Disposition",
         String.format("attachment; filename=\"%s\"", file.getName()));

OutputStream out = response.getOutputStream();
try (FileInputStream in = new FileInputStream(file)) {
    byte[] buffer = new byte[4096];
    int length;
    while ((length = > 0) {
        out.write(buffer, 0, length);

How to change the background color on a input checkbox with css?

I always use pseudo elements :before and :after for changing the appearance of checkboxes and radio buttons. it's works like a charm.

Refer this link for more info



  1. Hide the default checkbox using css rules like visibility:hidden or opacity:0 or position:absolute;left:-9999px etc.
  2. Create a fake checkbox using :before element and pass either an empty or a non-breaking space '\00a0';
  3. When the checkbox is in :checked state, pass the unicode content: "\2713", which is a checkmark;
  4. Add :focus style to make the checkbox accessible.
  5. Done

Here is how I did it.

.box {_x000D_
  background: #666666;_x000D_
  color: #ffffff;_x000D_
  width: 250px;_x000D_
  padding: 10px;_x000D_
  margin: 1em auto;_x000D_
p {_x000D_
  margin: 1.5em 0;_x000D_
  padding: 0;_x000D_
input[type="checkbox"] {_x000D_
  visibility: hidden;_x000D_
label {_x000D_
  cursor: pointer;_x000D_
input[type="checkbox"] + label:before {_x000D_
  border: 1px solid #333;_x000D_
  content: "\00a0";_x000D_
  display: inline-block;_x000D_
  font: 16px/1em sans-serif;_x000D_
  height: 16px;_x000D_
  margin: 0 .25em 0 0;_x000D_
  padding: 0;_x000D_
  vertical-align: top;_x000D_
  width: 16px;_x000D_
input[type="checkbox"]:checked + label:before {_x000D_
  background: #fff;_x000D_
  color: #333;_x000D_
  content: "\2713";_x000D_
  text-align: center;_x000D_
input[type="checkbox"]:checked + label:after {_x000D_
  font-weight: bold;_x000D_
input[type="checkbox"]:focus + label::before {_x000D_
    outline: rgb(59, 153, 252) auto 5px;_x000D_
<div class="content">_x000D_
  <div class="box">_x000D_
      <input type="checkbox" id="c1" name="cb">_x000D_
      <label for="c1">Option 01</label>_x000D_
      <input type="checkbox" id="c2" name="cb">_x000D_
      <label for="c2">Option 02</label>_x000D_
      <input type="checkbox" id="c3" name="cb">_x000D_
      <label for="c3">Option 03</label>_x000D_

Much more stylish using :before and :after

  font-family: sans-serif;  _x000D_
.container {_x000D_
    margin-top: 50px;_x000D_
    margin-left: 20px;_x000D_
    margin-right: 20px;_x000D_
.checkbox {_x000D_
    width: 100%;_x000D_
    margin: 15px auto;_x000D_
    position: relative;_x000D_
    display: block;_x000D_
.checkbox input[type="checkbox"] {_x000D_
    width: auto;_x000D_
    opacity: 0.00000001;_x000D_
    position: absolute;_x000D_
    left: 0;_x000D_
    margin-left: -20px;_x000D_
.checkbox label {_x000D_
    position: relative;_x000D_
.checkbox label:before {_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    left: 0;_x000D_
    top: 0;_x000D_
    margin: 4px;_x000D_
    width: 22px;_x000D_
    height: 22px;_x000D_
    transition: transform 0.28s ease;_x000D_
    border-radius: 3px;_x000D_
    border: 2px solid #7bbe72;_x000D_
.checkbox label:after {_x000D_
  content: '';_x000D_
    display: block;_x000D_
    width: 10px;_x000D_
    height: 5px;_x000D_
    border-bottom: 2px solid #7bbe72;_x000D_
    border-left: 2px solid #7bbe72;_x000D_
    -webkit-transform: rotate(-45deg) scale(0);_x000D_
    transform: rotate(-45deg) scale(0);_x000D_
    transition: transform ease 0.25s;_x000D_
    will-change: transform;_x000D_
    position: absolute;_x000D_
    top: 12px;_x000D_
    left: 10px;_x000D_
.checkbox input[type="checkbox"]:checked ~ label::before {_x000D_
    color: #7bbe72;_x000D_
.checkbox input[type="checkbox"]:checked ~ label::after {_x000D_
    -webkit-transform: rotate(-45deg) scale(1);_x000D_
    transform: rotate(-45deg) scale(1);_x000D_
.checkbox label {_x000D_
    min-height: 34px;_x000D_
    display: block;_x000D_
    padding-left: 40px;_x000D_
    margin-bottom: 0;_x000D_
    font-weight: normal;_x000D_
    cursor: pointer;_x000D_
    vertical-align: sub;_x000D_
.checkbox label span {_x000D_
    position: absolute;_x000D_
    top: 50%;_x000D_
    -webkit-transform: translateY(-50%);_x000D_
    transform: translateY(-50%);_x000D_
.checkbox input[type="checkbox"]:focus + label::before {_x000D_
    outline: 0;_x000D_
<div class="container"> _x000D_
  <div class="checkbox">_x000D_
     <input type="checkbox" id="checkbox" name="" value="">_x000D_
     <label for="checkbox"><span>Checkbox</span></label>_x000D_
  <div class="checkbox">_x000D_
     <input type="checkbox" id="checkbox2" name="" value="">_x000D_
     <label for="checkbox2"><span>Checkbox</span></label>_x000D_

Convert a number into a Roman Numeral in javaScript

var romanNumerals = [
  ['M', 1000],['CM', 900],['D', 500],['CD', 400],['C', 100],['XC', 90],['L', 50],['XL', 40],['X', 10],['IX', 9],['V', 5],['IV', 4],['I', 1]];

RomanNumerals = {
  romerate: function(foo) {
    var bar = '';
    romanNumerals.forEach(function(buzz) {
      while (foo >= buzz[1]) {
        bar += buzz[0];
        foo -= buzz[1]; 
    return bar;
  numerate: function(x) {
    var y = 0;
    romanNumerals.forEach(function(z) {
      while (x.substr(0, z[0].length) == z[0]) {
        x = x.substr(z[0].length);
        y += z[1];
    return y;

Check if list<t> contains any of another list

If both the list are too big and when we use lamda expression then it will take a long time to fetch . Better to use linq in this case to fetch parameters list:

var items = (from x in parameters
                join y in myStrings on x.Source equals y
                select x)

Materialize CSS - Select Doesn't Seem to Render

First, make sure you initialize it in document.ready like this:

$(document).ready(function () {

Then, populate it with your data in the way you want. My example:

    function FillMySelect(myCustomData) {

        $.each(myCustomData, function (key, value) {
           $("#mySelect").append("<option value='" + "'>" + + "</option>");

Make sure after you are done with the population, to trigger this contentChanged like this:


How can I create keystore from an existing certificate (abc.crt) and abc.key files?

Adding to @MK Yung and @Bruno's answer.. Do enter a password for the destination keystore. I saw my console hanging when I entered the command without a password.

openssl pkcs12 -export -in abc.crt -inkey abc.key -out abc.p12 -name localhost  -passout pass:changeit

Convert unsigned int to signed int C

To answer the question posted in the comment above - try something like this:

unsigned short int x = 65529U;
short int y = (short int)x;

printf("%d\n", y);


unsigned short int x = 65529U;
short int y = 0;

memcpy(&y, &x, sizeof(short int);
printf("%d\n", y);

OnChange event using React JS for drop down

The change event is triggered on the <select> element, not the <option> element. However, that's not the only problem. The way you defined the change function won't cause a rerender of the component. It seems like you might not have fully grasped the concept of React yet, so maybe "Thinking in React" helps.

You have to store the selected value as state and update the state when the value changes. Updating the state will trigger a rerender of the component.

var MySelect = React.createClass({
     getInitialState: function() {
         return {
             value: 'select'
     change: function(event){
     render: function(){
               <select id="lang" onChange={this.change} value={this.state.value}>
                  <option value="select">Select</option>
                  <option value="Java">Java</option>
                  <option value="C++">C++</option>

React.render(<MySelect />, document.body);

Also note that <p> elements don't have a value attribute. React/JSX simply replicates the well-known HTML syntax, it doesn't introduce custom attributes (with the exception of key and ref). If you want the selected value to be the content of the <p> element then simply put inside of it, like you would do with any static content.

Learn more about event handling, state and form controls:

Is there a command line command for verifying what version of .NET is installed

If you're going to run a little console app, you may as well install clrver.exe from the .NET SDK. I don't think you can get cleaner than that. This isn't my answer (but I happen to agree), I found it here.

MySQL connection not working: 2002 No such file or directory

Restarting the mysql server might help. In my case, restarting the server saved a lot of time.

service mysql restart

P.S.- use sudo service mysql restart for non-root user.

How to create a function in SQL Server

How about this?

CREATE FUNCTION dbo.StripWWWandCom (@input VARCHAR(250))
    DECLARE @Work VARCHAR(250)

    SET @Work = @Input

    SET @Work = REPLACE(@Work, 'www.', '')
    SET @Work = REPLACE(@Work, '.com', '')

    RETURN @work

and then use:

SELECT ID, dbo.StripWWWandCom (WebsiteName)
FROM dbo.YourTable .....

Of course, this is severely limited in that it will only strip www. at the beginning and .com at the end - nothing else (so it won't work on other host machine names like and other internet domains such as .org, .edu, .de and etc.)

How to convert InputStream to FileInputStream

Long story short: Don't use FileInputStream as a parameter or variable type. Use the abstract base class, in this case InputStream instead.

Calling Web API from MVC controller

Why don't you simply move the code you have in the ApiController calls - DocumentsController to a class that you can call from both your HomeController and DocumentController. Pull this out into a class you call from both controllers. This stuff in your question:

// All code to find the files are here and is working perfectly...

It doesn't make sense to call a API Controller from another controller on the same website.

This will also simplify the code when you come back to it in the future you will have one common class for finding the files and doing that logic there...

How to make Regular expression into non-greedy?

The non-greedy regex modifiers are like their greedy counter-parts but with a ? immediately following them:

*  - zero or more
*? - zero or more (non-greedy)
+  - one or more
+? - one or more (non-greedy)
?  - zero or one
?? - zero or one (non-greedy)

How can I put a database under git (version control)?

I've come across this question, as I've got a similar problem, where something approximating a DB based Directory structure, stores 'files', and I need git to manage it. It's distributed, across a cloud, using replication, hence it's access point will be via MySQL.

The gist of the above answers, seem to similarly suggest an alternative solution to the problem asked, which kind of misses the point, of using Git to manage something in a Database, so I'll attempt to answer that question.

Git is a system, which in essence stores a database of deltas (differences), which can be reassembled, in order, to reproduce a context. The normal usage of git assumes that context is a filesystem, and those deltas are diff's in that file system, but really all git is, is a hierarchical database of deltas (hierarchical, because in most cases each delta is a commit with at least 1 parents, arranged in a tree).

As long as you can generate a delta, in theory, git can store it. The problem is normally git expects the context, on which it's generating delta's to be a file system, and similarly, when you checkout a point in the git hierarchy, it expects to generate a filesystem.

If you want to manage change, in a database, you have 2 discrete problems, and I would address them separately (if I were you). The first is schema, the second is data (although in your question, you state data isn't something you're concerned about). A problem I had in the past, was a Dev and Prod database, where Dev could take incremental changes to the schema, and those changes had to be documented in CVS, and propogated to live, along with additions to one of several 'static' tables. We did that by having a 3rd database, called Cruise, which contained only the static data. At any point the schema from Dev and Cruise could be compared, and we had a script to take the diff of those 2 files and produce an SQL file containing ALTER statements, to apply it. Similarly any new data, could be distilled to an SQL file containing INSERT commands. As long as fields and tables are only added, and never deleted, the process could automate generating the SQL statements to apply the delta.

The mechanism by which git generates deltas is diff and the mechanism by which it combines 1 or more deltas with a file, is called merge. If you can come up with a method for diffing and merging from a different context, git should work, but as has been discussed you may prefer a tool that does that for you. My first thought towards solving that is this which details how to replace git's internal diff and merge tool. I'll update this answer, as I come up with a better solution to the problem, but in my case I expect to only have to manage data changes, in-so-far-as a DB based filestore may change, so my solution may not be exactly what you need.

SQL update from one Table to another based on a ID match

I'd like to add one extra thing.

Don't update a value with the same value, it generates extra logging and unnecessary overhead. See example below - it will only perform the update on 2 records despite linking on 3.

CREATE TABLE #TMP1(LeadID Int,AccountNumber NVarchar(50))
CREATE TABLE #TMP2(LeadID Int,AccountNumber NVarchar(50))



SET A.AccountNumber = B.AccountNumber
    #TMP1 A 
        INNER JOIN #TMP2 B
        A.LeadID = B.LeadID
    A.AccountNumber <> B.AccountNumber  --DON'T OVERWRITE A VALUE WITH THE SAME VALUE


How do I access store state in React Redux?

You should create separate component, which will be listening to state changes and updating on every state change:

import store from '../reducers/store';

class Items extends Component {
  constructor(props) {

    this.state = {
      items: [],

    store.subscribe(() => {
      // When state will be updated(in our case, when items will be fetched), 
      // we will update local component state and force component to rerender 
      // with new data.

        items: store.getState().items;

  render() {
    return (
        { => <p> {item.title} </p> )}

render(<Items />, document.getElementById('app'));

How to get the mouse position without events (without moving the mouse)?

Real answer: No, it's not possible.

OK, I have just thought of a way. Overlay your page with a div that covers the whole document. Inside that, create (say) 2,000 x 2,000 <a> elements (so that the :hover pseudo-class will work in IE 6, see), each 1 pixel in size. Create a CSS :hover rule for those <a> elements that changes a property (let's say font-family). In your load handler, cycle through each of the 4 million <a> elements, checking currentStyle / getComputedStyle() until you find the one with the hover font. Extrapolate back from this element to get the co-ordinates within the document.


how to get right offset of an element? - jQuery

Maybe I'm misunderstanding your question, but the offset is supposed to give you two variables: a horizontal and a vertical. This defines the position of the element. So what you're looking for is:




If you need to know where the right boundary of your element is, then you should use:

$("#whatever").offset().left + $("#whatever").outerWidth()

AngularJS - ng-if check string empty value

Probably your is undefined if you don't have a photo attribute on item in the first place and thus undefined != ''. But if you'd put some code to show how you provide values to item, it would help.

PS: Sorry to post this as an answer (I rather think it's more of a comment), but I don't have enough reputation yet.

How can I make a program wait for a variable change in javascript?

Edit 2018: Please look into Object getters and setters and Proxies. Old answer below:

a quick and easy solution goes like this:

var something=999;
var something_cachedValue=something;

function doStuff() {
    if(something===something_cachedValue) {//we want it to match
        setTimeout(doStuff, 50);//wait 50 millisecnds then recheck
    //real action


Angularjs ng-model doesn't work inside ng-if

You can do it like this and you mod function will work perfect let me know if you want a code pen

  <div ng-repeat="icon in icons">                   
                <div class="row" ng-if="$index % 3 == 0 ">
                    <i class="col col-33 {{icons[$index + n].icon}} custom-icon"></i>
                    <i class="col col-33 {{icons[$index + n + 1].icon}} custom-icon"></i>
                    <i class="col col-33 {{icons[$index + n + 2].icon}} custom-icon"></i>

Get a list of distinct values in List

Jon Skeet has written a library called morelinq which has a DistinctBy() operator. See here for the implementation. Your code would look like

IEnumerable<Note> distinctNotes = Notes.DistinctBy(note => note.Author);

Update: After re-reading your question, Kirk has the correct answer if you're just looking for a distinct set of Authors.

Added sample, several fields in DistinctBy:

res = res.DistinctBy(i => i.Name).DistinctBy(i => i.ProductId).ToList();

Fastest way to check if a string is JSON in PHP?

This is what I recommend

if (!in_array(substr($string, 0, 1), ['{', '[']) || !in_array(substr($string, -1), ['}', ']'])) {
  return false;
} else {
  return (json_last_error() === JSON_ERROR_NONE);

Group by month and year in MySQL

You cal also do this

SELECT  SUM(amnt) `value`,DATE_FORMAT(dtrg,'%m-%y') AS label FROM rentpay GROUP BY YEAR(dtrg) DESC, MONTH(dtrg) DESC LIMIT 12

to order by year and month. Lets say you want to order from this year and this month all the way back to 12 month

Getting the Username from the HKEY_USERS values

  1. Open Reg HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\

  2. make a loop to get all subkeys

  3. the subkeys you are interested with are those started with [S-1-5-21-] which means user (see key name [ProfileImagePath] they are always started with a path c:\Users)

  4. Those starting with [S-1-5-21-12] are all local users

  5. Those starting with [S-1-5-21-13] are all network users [if joined to Domained network] that are previously logged on the machine.

Remove border radius from Select tag in bootstrap 3

In addition to border-radius: 0, add -webkit-appearance: none;.

What is the difference between resource and endpoint?

Consider a server which has the information of users, missions and their reward points.

  1. Users and Reward Points are the resources
  2. An end point can relate to more than one resource
  3. Endpoints can be described using either a description or a full or partial URL

enter image description here

Source: API Endpoints vs Resources

Check if image exists on server using JavaScript?

If you are using React try this custom Image component:

import React, { useRef } from 'react';
import PropTypes from 'prop-types';

import defaultErrorImage from 'assets/images/default-placeholder-image.png';

const Image = ({ src, alt, className, onErrorImage }) => {
  const imageEl = useRef(null);
  return (
      onError={() => {
        imageEl.current.src = onErrorImage;

Image.defaultProps = {
  onErrorImage: defaultErrorImage,

Image.propTypes = {
  src: PropTypes.string.isRequired,
  alt: PropTypes.string.isRequired,
  className: PropTypes.string.isRequired,
  onErrorImage: PropTypes.string,

export default Image;

How to check is Apache2 is stopped in Ubuntu?

In the command line type service apache2 status then hit enter. The result should say:

Apache2 is running (pid xxxx)

Remove the title bar in Windows Forms

Set FormsBorderStyle of the Form to None.

If you do, it's up to you how to implement the dragging and closing functionality of the window.

How to specify the current directory as path in VBA?

I thought I had misunderstood but I was right. In this scenario, it will be ActiveWorkbook.Path

But the main issue was not here. The problem was with these 2 lines of code

strFile = Dir(strPath & "*.csv")

Which should have written as

strFile = Dir(strPath & "\*.csv")


With .QueryTables.Add(Connection:="TEXT;" & strPath & strFile, _

Which should have written as

With .QueryTables.Add(Connection:="TEXT;" & strPath & "\" & strFile, _

Violation of PRIMARY KEY constraint. Cannot insert duplicate key in object

What is the value you're passing to the primary key (presumably "pk_OrderID")? You can set it up to auto increment, and then there should never be a problem with duplicating the value - the DB will take care of that. If you need to specify a value yourself, you'll need to write code to determine what the max value for that field is, and then increment that.

If you have a column named "ID" or such that is not shown in the query, that's fine as long as it is set up to autoincrement - but it's probably not, or you shouldn't get that err msg. Also, you would be better off writing an easier-on-the-eye query and using params. As the lad of nine years hence inferred, you're leaving your database open to SQL injection attacks if you simply plop in user-entered values. For example, you could have a method like this:

internal static int GetItemIDForUnitAndItemCode(string qry, string unit, string itemCode)
    int itemId;
    using (SqlConnection sqlConn = new SqlConnection(ReportRunnerConstsAndUtils.CPSConnStr))
        using (SqlCommand cmd = new SqlCommand(qry, sqlConn))
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.Add("@Unit", SqlDbType.VarChar, 25).Value = unit;
            cmd.Parameters.Add("@ItemCode", SqlDbType.VarChar, 25).Value = itemCode;
            itemId = Convert.ToInt32(cmd.ExecuteScalar());
    return itemId;

...that is called like so:

int itemId = SQLDBHelper.GetItemIDForUnitAndItemCode(GetItemIDForUnitAndItemCodeQuery, _unit, itemCode);

You don't have to, but I store the query separately:

public static readonly String GetItemIDForUnitAndItemCodeQuery = "SELECT PoisonToe FROM Platypi WHERE Unit = @Unit AND ItemCode = @ItemCode";

You can verify that you're not about to insert an already-existing value by (pseudocode):

bool alreadyExists = IDAlreadyExists(query, value) > 0;

The query is something like "SELECT COUNT FROM TABLE WHERE BLA = @CANDIDATEIDVAL" and the value is the ID you're potentially about to insert:

if (alreadyExists) // keep inc'ing and checking until false, then use that id value

Justin wants to know if this will work:

string exists = "SELECT 1 from AC_Shipping_Addresses where pk_OrderID = " _Order.OrderNumber; if (exists > 0)...

What seems would work to me is:

string existsQuery = string.format("SELECT 1 from AC_Shipping_Addresses where pk_OrderID = {0}", _Order.OrderNumber); 
// Or, better yet:
string existsQuery = "SELECT COUNT(*) from AC_Shipping_Addresses where pk_OrderID = @OrderNumber"; 
// Now run that query after applying a value to the OrderNumber query param (use code similar to that above); then, if the result is > 0, there is such a record.

Creating a custom JButton in Java

When I was first learning Java we had to make Yahtzee and I thought it would be cool to create custom Swing components and containers instead of just drawing everything on one JPanel. The benefit of extending Swing components, of course, is to have the ability to add support for keyboard shortcuts and other accessibility features that you can't do just by having a paint() method print a pretty picture. It may not be done the best way however, but it may be a good starting point for you.

Edit 8/6 - If it wasn't apparent from the images, each Die is a button you can click. This will move it to the DiceContainer below. Looking at the source code you can see that each Die button is drawn dynamically, based on its value.

alt text
alt text
alt text

Here are the basic steps:

  1. Create a class that extends JComponent
  2. Call parent constructor super() in your constructors
  3. Make sure you class implements MouseListener
  4. Put this in the constructor:

  5. Override these methods:

    public Dimension getPreferredSize()  
    public Dimension getMinimumSize()  
    public Dimension getMaximumSize()
  6. Override this method:

    public void paintComponent(Graphics g)

The amount of space you have to work with when drawing your button is defined by getPreferredSize(), assuming getMinimumSize() and getMaximumSize() return the same value. I haven't experimented too much with this but, depending on the layout you use for your GUI your button could look completely different.

And finally, the source code. In case I missed anything.

Msg 102, Level 15, State 1, Line 1 Incorrect syntax near ' '

For the OP's command:

select compid,2, convert(datetime, '01/01/' + CONVERT(char(4),cal_yr) ,101) ,0,  Update_dt, th1, th2, th3_pc , Update_id, Update_dt,1
from  #tmp_CTF** 

I get this error:

Msg 102, Level 15, State 1, Line 2
Incorrect syntax near '*'.

when debugging something like this split the long line up so you'll get a better row number:

select compid
, convert(datetime
, '01/01/' 
+ CONVERT(char(4)
,  Update_dt
, th1
, th2
, th3_pc 
, Update_id
, Update_dt
from  #tmp_CTF** 

this now results in:

Msg 102, Level 15, State 1, Line 16
Incorrect syntax near '*'.

which is probably just from the OP not putting the entire command in the question, or use [ ] braces to signify the table name:

from [#tmp_CTF**]

if that is the table name.

Best way to deploy Visual Studio application that can run without installing

It is possible and is deceptively easy:

  1. "Publish" the application (to, say, some folder on drive C), either from menu Build or from the project's properties ? Publish. This will create an installer for a ClickOnce application.
  2. But instead of using the produced installer, find the produced files (the EXE file and the .config, .manifest, and .application files, along with any DLL files, etc.) - they are all in the same folder and typically in the bin\Debug folder below the project file (.csproj).
  3. Zip that folder (leave out any *.vhost.* files and the app.publish folder (they are not needed), and the .pdb files unless you foresee debugging directly on your user's system (for example, by remote control)), and provide it to the users.

An added advantage is that, as a ClickOnce application, it does not require administrative privileges to run (if your application follows the normal guidelines for which folders to use for application data, etc.).

As for .NET, you can check for the minimum required version of .NET being installed (or at all) in the application (most users will already have it installed) and present a dialog with a link to the download page on the Microsoft website (or point to one of your pages that could redirect to the Microsoft page - this makes it more robust if the Microsoft URL change). As it is a small utility, you could target .NET 2.0 to reduce the probability of a user to have to install .NET.

It works. We use this method during development and test to avoid having to constantly uninstall and install the application and still being quite close to how the final application will run.

Auto Resize Image in CSS FlexBox Layout and keeping Aspect Ratio?


<div class="container">
    <div class="box">
        <img src="" alt="">


.container {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: stretch;

  width: 100%;
  height: 100%;

  border-radius: 4px;
  background-color: hsl(0, 0%, 96%);

.box {
  border-radius: 4px;
  display: flex;

.box img {
  width: 100%;
  object-fit: contain;
  border-radius: 4px;

jQuery Ajax simple call

You could also make the ajax call more generic, reusable, so you can call it from different CRUD(create, read, update, delete) tasks for example and treat the success cases from those calls.

makePostCall = function (url, data) { // here the data and url are not hardcoded anymore
   var json_data = JSON.stringify(data);

    return $.ajax({
        type: "POST",
        url: url,
        data: json_data,
        dataType: "json",
        contentType: "application/json;charset=utf-8"

// and here a call example
makePostCall("index.php?action=READUSERS", {'city' : 'Tokio'})
               // treat the READUSERS data returned
    .fail(function(sender, message, details){
           alert("Sorry, something went wrong!");

How do I join two lists in Java?

We can join 2 lists using java8 with 2 approaches.

    List<String> list1 = Arrays.asList("S", "T");
    List<String> list2 = Arrays.asList("U", "V");

1) Using concat :

    List<String> collect2 = Stream.concat(,;
    System.out.println("collect2 = " + collect2); // collect2 = [S, T, U, V]

2) Using flatMap :

    List<String> collect3 = Stream.of(list1, list2).flatMap(Collection::stream).collect(toList());
    System.out.println("collect3 = " + collect3); // collect3 = [S, T, U, V]

How to navigate a few folders up?

Maybe you could use a function if you want to declare the number of levels and put it into a function?

private String GetParents(Int32 noOfLevels, String currentpath)
     String path = "";
     for(int i=0; i< noOfLevels; i++)
         path += @"..\";
     path += currentpath;
     return path;

And you could call it like this:

String path = this.GetParents(4, currentpath);

Delaying AngularJS route change until model loaded to prevent flicker

I liked above answers and learned a lot from them but there is something that is missing in most of the above answers.

I was stuck in a similar scenario where I was resolving url with some data that is fetched in the first request from the server. Problem I faced was what if the promise is rejected.

I was using a custom provider which used to return a Promise which was resolved by the resolve of $routeProvider at the time of config phase.

What I want to stress here is the concept of when it does something like this.

It sees the url in url bar and then respective when block in called controller and view is referred so far so good.

Lets say I have following config phase code.

App.when('/', {
   templateUrl: '/assets/campaigns/index.html',
   controller: 'CampaignListCtr',
   resolve : {
      Auth : function(){
         return AuthServiceProvider.auth('campaign');
// Default route
   redirectTo: '/segments'

On root url in browser first block of run get called otherwise otherwise gets called.

Let's imagine a scenario I hit rootUrl in address bar AuthServicePrivider.auth() function gets called.

Lets say Promise returned is in reject state what then???

Nothing gets rendered at all.

Otherwise block will not get executed as it is for any url which is not defined in the config block and is unknown to angularJs config phase.

We will have to handle the event that gets fired when this promise is not resolved. On failure $routeChangeErorr gets fired on $rootScope.

It can be captured as shown in code below.

$rootScope.$on('$routeChangeError', function(event, current, previous, rejection){
    // Use params in redirection logic.
    // event is the routeChangeEvent
    // current is the current url
    // previous is the previous url

IMO It's generally a good idea to put event tracking code in run block of application. This code run just after the config phase of the application.['$routeParams', '$rootScope', '$location', function($routeParams, $rootScope, $location){
   $rootScope.rootPath = "my custom path";
   // Event to listen to all the routeChangeErrors raised
   // by the resolve in config part of application
   $rootScope.$on('$routeChangeError', function(event, current, previous, rejection){
       // I am redirecting to rootPath I have set above.

This way we can handle promise failure at the time of config phase.

Current date and time - Default in MVC razor

Before you return your model from the controller, set your ReturnDate property to DateTime.Now()

myModel.ReturnDate = DateTime.Now()

return View(myModel)

Your view is not the right place to set values on properties so the controller is the better place for this.

You could even have it so that the getter on ReturnDate returns the current date/time.

private DateTime _returnDate = DateTime.MinValue;
public DateTime ReturnDate{
     return (_returnDate == DateTime.MinValue)? DateTime.Now() : _returnDate;
   set{_returnDate = value;}

How to undo the last commit in git

I think you haven't messed up yet. Try:

git reset HEAD^

This will bring the dir to state before you've made the commit, HEAD^ means the parent of the current commit (the one you don't want anymore), while keeping changes from it (unstaged).

phpMyAdmin + CentOS 6.0 - Forbidden

None of the configuration above worked for me on my CentOS 7 server. After hours of searching, that's what worked for me:

Edit file phpMyAdmin.conf

sudo nano /etc/httpd/conf.d/phpMyAdmin.conf

And replace this at the top:

<Directory /usr/share/phpMyAdmin/>
   AddDefaultCharset UTF-8

   <IfModule mod_authz_core.c>
     # Apache 2.4
       #Require ip
       #Require ip ::1
       Require all granted
   <IfModule !mod_authz_core.c>
     # Apache 2.2
     Order Deny,Allow
     Deny from All
     Allow from
     Allow from ::1

Add two textbox values and display the sum in a third textbox automatically

In below code i have done operation of sum and subtraction: because of using JavaScript if you want to call function, then you have to put your below code outside of document.ready(function{ }); and outside the script end tag.

I have taken one another script tag for this operation.And put below code between script starting tag // your code // script ending tag.

 function operation() 


   var txtFirstNumberValue = parseInt(document.getElementById('basic').value);
   var txtSecondNumberValue =parseInt(document.getElementById('hra').value);
   var txtThirdNumberValue =parseInt(document.getElementById('transport').value);
   var txtFourthNumberValue =parseInt(document.getElementById('pt').value);
   var txtFiveNumberValue = parseInt(document.getElementById('pf').value);

   if (txtFirstNumberValue == "")
       txtFirstNumberValue = 0;
   if (txtSecondNumberValue == "")
       txtSecondNumberValue = 0;
   if (txtThirdNumberValue == "")
       txtThirdNumberValue = 0;
   if (txtFourthNumberValue == "")
       txtFourthNumberValue = 0;
   if (txtFiveNumberValue == "")
       txtFiveNumberValue = 0;

   var result = ((txtFirstNumberValue + txtSecondNumberValue + 
  txtThirdNumberValue) - (txtFourthNumberValue + txtFiveNumberValue));
   if (!isNaN(result)) {
       document.getElementById('total').value = result;

And put onkeyup="operation();" inside all 5 textboxes in your html form. This code running in both Firefox and Chrome.

Replace X-axis with own values

Yo could also set labels = FALSE inside axis(...) and print the labels in a separate command with Text. With this option you can rotate the text the text in case you need it

axis(1, at=seq(1, 10, by=1), labels = FALSE)
text(seq(1, 10, by=1), par("usr")[3] - 0.2, labels = lablist, srt = 45, pos = 1, xpd = TRUE)

Detailed explanation here

Image with rotated labels

Print newline in PHP in single quotes

I wonder why no one added the alternative of using the function chr():

echo 'Hello World!' . chr(10);

or, more efficient if you're going to repeat it a million times:

define('C_NewLine', chr(10));
echo 'Hello World!' . C_NewLine;

This avoids the silly-looking notation of concatenating a single- and double-quoted string.

Is there any way I can define a variable in LaTeX?

I think you probably want to use a token list for this purpose: to set up the token list \newtoks\packagename to assign the name: \packagename={New Name for the package} to put the name into your output: \the\packagename.

What is the { get; set; } syntax in C#?

So as I understand it { get; set; } is an "auto property" which just like @Klaus and @Brandon said is shorthand for writing a property with a "backing field." So in this case:

public class Genre
    private string name; // This is the backing field
    public string Name   // This is your property
        get => name;
        set => name = value;

However if you're like me - about an hour or so ago - you don't really understand what properties and accessors are, and you don't have the best understanding of some basic terminologies either. MSDN is a great tool for learning stuff like this but it's not always easy to understand for beginners. So I'm gonna try to explain this more in-depth here.

get and set are accessors, meaning they're able to access data and info in private fields (usually from a backing field) and usually do so from public properties (as you can see in the above example).

There's no denying that the above statement is pretty confusing, so let's go into some examples. Let's say this code is referring to genres of music. So within the class Genre, we're going to want different genres of music. Let's say we want to have 3 genres: Hip Hop, Rock, and Country. To do this we would use the name of the Class to create new instances of that class.

Genre g1 = new Genre(); //Here we're creating a new instance of the class "Genre"
                        //called g1. We'll create as many as we need (3)
Genre g2 = new Genre();
Genre g3 = new Genre();

//Note the () following new Genre. I believe that's essential since we're creating a
//new instance of a class (Like I said, I'm a beginner so I can't tell you exactly why
//it's there but I do know it's essential)

Now that we've created the instances of the Genre class we can set the genre names using the 'Name' property that was set way up above.

public string Name //Again, this is the 'Name' property
{ get; set; } //And this is the shorthand version the process we're doing right now 

We can set the name of 'g1' to Hip Hop by writing the following

g1.Name = "Hip Hop";

What's happening here is sort of complex. Like I said before, get and set access information from private fields that you otherwise wouldn't be able to access. get can only read information from that private field and return it. set can only write information in that private field. But by having a property with both get and set we're able do both of those functions. And by writing g1.Name = "Hip Hop"; we are specifically using the set function from our Name property

set uses an implicit variable called value. Basically what this means is any time you see "value" within set, it's referring to a variable; the "value" variable. When we write g1.Name = we're using the = to pass in the value variable which in this case is "Hip Hop". So you can essentially think of it like this:

public class g1 //We've created an instance of the Genre Class called "g1"
    private string name;
    public string Name
        get => name;
        set => name = "Hip Hop"; //instead of 'value', "Hip Hop" is written because 
                              //'value' in 'g1' was set to "Hip Hop" by previously
                              //writing 'g1.Name = "Hip Hop"'

It's Important to note that the above example isn't actually written in the code. It's more of a hypothetical code that represents what's going on in the background.

So now that we've set the Name of the g1 instance of Genre, I believe we can get the name by writing

console.WriteLine (g1.Name); //This uses the 'get' function from our 'Name' Property 
                             //and returns the field 'name' which we just set to
                             //"Hip Hop"

and if we ran this we would get "Hip Hop" in our console.

So for the purpose of this explanation I'll complete the example with outputs as well

using System;
public class Genre
    public string Name { get; set; }

public class MainClass
    public static void Main()
        Genre g1 = new Genre();
        Genre g2 = new Genre();
        Genre g3 = new Genre();

        g1.Name = "Hip Hop";
        g2.Name = "Rock";
        g3.Name = "Country";

        Console.WriteLine ("Genres: {0}, {1}, {2}", g1.Name, g2.Name, g3.Name);


"Genres: Hip Hop, Rock, Country"

Proxy setting for R

On Mac OS, I found the best solution here. Quoting the author, two simple steps are:

1) Open Terminal and do the following:

export http_proxy=
export HTTP_PROXY=

2) Run R and do the following:


double-check this with:


I am behind university proxy, and this solution worked perfectly. The major issue is to export the items in Terminal before running R, both in upper- and lower-case.

Coding Conventions - Naming Enums

In our codebase; we typically declare enums in the class that they belong to.

So for your Fruit example, We would have a Fruit class, and inside that an Enum called Fruits.

Referencing it in the code looks like this: Fruit.Fruits.Apple, Fruit.Fruits.Pear, etc.

Constants follow along the same line, where they either get defined in the class to which they're relevant (so something like Fruit.ORANGE_BUSHEL_SIZE); or if they apply system-wide (i.e. an equivalent "null value" for ints) in a class named "ConstantManager" (or equivalent; like ConstantManager.NULL_INT). (side note; all our constants are in upper case)

As always, your coding standards probably differ from mine; so YMMV.

Convert 24 Hour time to 12 Hour plus AM/PM indication Oracle SQL

For the 24-hour time, you need to use HH24 instead of HH.

For the 12-hour time, the AM/PM indicator is written as A.M. (if you want periods in the result) or AM (if you don't). For example:

SELECT invoice_date,
       TO_CHAR(invoice_date, 'DD-MM-YYYY HH24:MI:SS') "Date 24Hr",
       TO_CHAR(invoice_date, 'DD-MM-YYYY HH:MI:SS AM') "Date 12Hr"
  FROM invoices

For more information on the format models you can use with TO_CHAR on a date, see

Post request in Laravel - Error - 419 Sorry, your session/ 419 your page has expired

I also had a problem like this and I've discovered that the session files were locked for writing. So, I don't know if you are running your Laravel via stuff like vagrant or Docker, but I advise you to try to change the rights of the session directory (and files of course) (When you run Laravel in a VM you should change the rights locally and in the VM (like, when you share the files via NFS)

Like this:

chmod -R 777 storage/framework/sessions
chmod -R 777 storage/logs

I know, a 777 permission is the worst disaster that you can ever imagine. But they are handy for troubleshooting.

To be sure that I never forgot this I made a bash script. (Called it lalog, just because I wanted to clear the log files and set permissions)

Note: Make sure that you use this on the session directory. In config/session.php there is a files key declared with the location. In my case:

'files' => storage_path('framework/sessions'),

Location: /usr/bin/lalog (This is a file, not a directory)
Execute in shell as lalog

rm -rf /home/username/Projects/x/storage/logs/laravel.log
echo "Laravel log removed"
touch /home/username/Projects/x/storage/logs/laravel.log
echo "Laravel log created"
chmod -R 777 /home/username/Projects/x/storage/
echo "CHMOD 777 on Storage dir"

Warning! This will allow write access for everyone, so be carefull with it! Also, maybe there is some usefull information in the log file of Laravel. (be sure to look in that log file before running my bash script)

Also, I know that it's already mentioned. But, be totally sure that you always

  1. Allow cookies in the browser, so the token can be set in the cookies
  2. Check if you are using the @csrf in your blade file

The form should be something like this

<form method="POST" action="{{ route('login') }}">

When to use RDLC over RDL reports?

If we have fewer number of reports which are less complex and consumed by web pages. It's better to go with rdlc,reason is we can avoid maintaing reports on RS instance. but we have to fetch the data from DB manually and bind it to rdlc.

Cons:designing rdlc in visual studio is little difficult compared to SSrs designer.

Pro:Maintenance is easy. while exporting the report from we page,observed that performance gain compared to server side reports.

How do I iterate through children elements of a div using jQuery?

It can be done this way as well:

$('input', '#div').each(function () {
    console.log($(this)); //log every element found to console output

What is the `data-target` attribute in Bootstrap 3?

The toggle tells Bootstrap what to do and the target tells Bootstrap which element is going to open. So whenever a link like that is clicked, a modal with an id of “basicModal” will appear.

How to open in default browser in C#

My default browser is Google Chrome and the accepted answer is giving the following error:

The system cannot find the file specified.

I solved the problem and managed to open an URL with the default browser by using this code:

System.Diagnostics.Process.Start("explorer.exe", "");

Uploading an Excel sheet and importing the data into SQL Server database

 protected void btnUpload_Click(object sender, EventArgs e)
        divStatusMsg.Style.Add("display", "none");
        divStatusMsg.Attributes.Add("class", "alert alert-danger alert-dismissable");
        divStatusMsg.InnerText = "";
        ViewState["Fuletypeidlist"] = "0";
        grdExcel.DataSource = null;

        if (Page.IsValid)
            bool logval = true;
            if (logval == true)
                String img_1 = fuUploadExcelName.PostedFile.FileName;
                String img_2 = System.IO.Path.GetFileName(img_1);
                string extn = System.IO.Path.GetExtension(img_1);

                string frstfilenamepart = "";
                frstfilenamepart = "DateExcel" + DateTime.Now.ToString("ddMMyyyyhhmmss"); ;
                UploadExcelName.Value = frstfilenamepart + extn;
                fuUploadExcelName.SaveAs(Server.MapPath("~/Emp/DateExcel/") + "/" + UploadExcelName.Value);
                string PathName = Server.MapPath("~/Emp/DateExcel/") + "\\" + UploadExcelName.Value;
                GetExcelSheetForEmp(PathName, UploadExcelName.Value);
                if ((grdExcel.HeaderRow.Cells[0].Text.ToString() == "CODE") && grdExcel.HeaderRow.Cells[1].Text.ToString() == "SAL")
                    divStatusMsg.Style.Add("display", "");
                    divStatusMsg.Attributes.Add("class", "alert alert-danger alert-dismissable");
                    divStatusMsg.InnerText = "ERROR !!...Please Upload Excel Sheet in header Defined Format ";



    private void GetExcelSheetForEmployeeCode(string filename)
        int count = 0;
        int selectedcheckbox = 0;
        string empcodeexcel = "";
        string empcodegrid = "";
        string excelFile = "Employee/DateExcel" + filename;
        OleDbConnection objConn = null;
        System.Data.DataTable dt = null;
            DataSet ds = new DataSet();
            String connString = "Provider=Microsoft.ACE.OLEDB.12.0;Persist Security Info=True;Extended Properties=Excel 12.0 Xml;Data Source=" + filename;
            // Create connection. 
            objConn = new OleDbConnection(connString);
            // Opens connection with the database. 
            if (objConn.State == ConnectionState.Closed)
            // Get the data table containing the schema guid, and also sheet names. 
            dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            if (dt == null)
            String[] excelSheets = new String[dt.Rows.Count];
            int i = 0;
            // Add the sheet name to the string array. 
            // And respective data will be put into dataset table 
            foreach (DataRow row in dt.Rows)
                if (i == 0)
                    excelSheets[i] = row["TABLE_NAME"].ToString();
                    OleDbCommand cmd = new OleDbCommand("SELECT DISTINCT * FROM [" + excelSheets[i] + "]", objConn);
                    OleDbDataAdapter oleda = new OleDbDataAdapter();
                    oleda.SelectCommand = cmd;
                    oleda.Fill(ds, "TABLE");
                    if (ds.Tables[0].ToString() != null)
                        for (int j = 0; j < ds.Tables[0].Rows.Count; j++)
                            for (int k = 0; k < GrdEmplist.Rows.Count; k++)
                                empcodeexcel = ds.Tables[0].Rows[j][0].ToString();
                                date.Value = ds.Tables[0].Rows[j][1].ToString();

                                Label lbl_EmpCode = (Label)GrdEmplist.Rows[k].FindControl("lblGrdCode");
                                empcodegrid = lbl_Code.Text;
                                CheckBox chk = (CheckBox)GrdEmplist.Rows[k].FindControl("chkSingle");
                                TextBox txt_Sal = (TextBox)GrdEmplist.Rows[k].FindControl("txtSal");

                                if ((empcodegrid == empcodeexcel) && (date.Value != ""))
                                    chk.Checked = true;
                                    txt_Sal.Text = date.Value;
                                    selectedcheckbox = selectedcheckbox + 1;
                                    lblSelectedRecord.InnerText = selectedcheckbox.ToString();
                                if (chk.Checked == true)




        catch (Exception ex)
            ShowMessage(ex.Message.ToString(), 0);
            // Clean up. 
            if (objConn != null)
            if (dt != null)

    private void GetExcelSheetForEmp(string PathName, string UploadExcelName)
        string excelFile = "DateExcel/" + PathName;
        OleDbConnection objConn = null;
        System.Data.DataTable dt = null;

            DataSet dss = new DataSet();
            String connString = "Provider=Microsoft.ACE.OLEDB.12.0;Persist Security Info=True;Extended Properties=Excel 12.0 Xml;Data Source=" + PathName;
            objConn = new OleDbConnection(connString);
            dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            if (dt == null)
            String[] excelSheets = new String[dt.Rows.Count];
            int i = 0;
            foreach (DataRow row in dt.Rows)
                if (i == 0)
                    excelSheets[i] = row["TABLE_NAME"].ToString();
                    OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + excelSheets[i] + "]", objConn);
                    OleDbDataAdapter oleda = new OleDbDataAdapter();
                    oleda.SelectCommand = cmd;
                    oleda.Fill(dss, "TABLE");

            grdExcel.DataSource = dss.Tables[0].DefaultView;
            lblTotalRec.InnerText = Convert.ToString(grdExcel.Rows.Count);


        catch (Exception ex)
            ViewState["Fuletypeidlist"] = "0";
            grdExcel.DataSource = null;
            if (objConn != null)
            if (dt != null)


Select rows which are not present in other table

There are basically 4 techniques for this task, all of them standard SQL.


Often fastest in Postgres.

FROM   login_log l 
   SELECT  -- SELECT list mostly irrelevant; can just be empty in Postgres
   FROM   ip_location
   WHERE  ip = l.ip

Also consider:


Sometimes this is fastest. Often shortest. Often results in the same query plan as NOT EXISTS.

SELECT l.ip 
FROM   login_log l 
LEFT   JOIN ip_location i USING (ip)  -- short for: ON i.ip = l.ip


Short. Not as easily integrated in more complex queries.

FROM   login_log

EXCEPT ALL  -- "ALL" keeps duplicates and makes it faster
FROM   ip_location;

Note that (per documentation):

duplicates are eliminated unless EXCEPT ALL is used.

Typically, you'll want the ALL keyword. If you don't care, still use it because it makes the query faster.


Only good without NULL values or if you know to handle NULL properly. I would not use it for this purpose. Also, performance can deteriorate with bigger tables.

FROM   login_log
   SELECT DISTINCT ip  -- DISTINCT is optional
   FROM   ip_location

NOT IN carries a "trap" for NULL values on either side:

Similar question on dba.SE targeted at MySQL:

Wheel file installation

you can follow the below command to install using the wheel file at your local

pip install /users/arpansaini/Downloads/h5py-3.0.0-cp39-cp39-macosx_10_9_x86_64.whl

Android center view in FrameLayout doesn't work

We can align a view in center of the FrameLayout by setting the layout_gravity of the child view.



In Java code:

FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.CENTER;

Note: use FrameLayout.LayoutParams not the others existing LayoutParams

Setting max width for body using Bootstrap

You don't have to modify bootstrap-responsive by removing @media (max-width:1200px) ...

My application has a max-width of 1600px. Here's how it worked for me:

  1. Create bootstrap-custom.css - As much as possible, I don't want to override my original bootstrap css.

  2. Inside bootstrap-custom.css, override the container-fluid by including this code:

Like this:

/* set a max-width for horizontal fluid layout and make it centered */
.container-fluid {
  margin-right: auto;
  margin-left: auto;
  max-width: 1600px; /* or 950px */

How to determine whether a given Linux is 32 bit or 64 bit?

First you have to download Virtual Box. Then select new and a 32-bit Linux. Then boot the linux using it. If it boots then it is 32 bit if it doesn't then it is a 64 bit.

How to get a Char from an ASCII Character Code in c#

It is important to notice that in C# the char type is stored as Unicode UTF-16.

From ASCII equivalent integer to char

char c = (char)88;


char c = Convert.ToChar(88)

From char to ASCII equivalent integer

int asciiCode = (int)'A';

The literal must be ASCII equivalent. For example:

string str = "X?????????";

will print


Extended ASCII ranges from 0 to 255.

From default UTF-16 literal to char

Using the Symbol

char c = 'X';

Using the Unicode code

char c = '\u0058';

Using the Hexadecimal

char c = '\x0058';

What is the function __construct used for?

Note: Parent constructors are not called implicitly if the child class defines a constructor. In order to run a parent constructor, a call to parent::__construct() within the child constructor is required. If the child does not define a constructor then it may be inherited from the parent class just like a normal class method (if it was not declared as private).

keycode and charcode

It is a conditional statement.

If browser supprts e.keyCode then take e.keyCode else e.charCode.

It is similar to

var code = event.keyCode || event.charCode

event.keyCode: Returns the Unicode value of a non-character key in a keypress event or any key in any other type of keyboard event.

event.charCode: Returns the Unicode value of a character key pressed during a keypress event.

How to secure MongoDB with username and password

This answer is for Mongo 3.2.1 Reference

Terminal 1:

$ mongod --auth

Terminal 2:

db.createUser({user:"admin_name", pwd:"1234",roles:["readWrite","dbAdmin"]})

if you want to add without roles (optional):

db.createUser({user:"admin_name", pwd:"1234", roles:[]})

to check if authenticated or not:

db.auth("admin_name", "1234")

it should give you:


else :

Error: Authentication failed.

Vertical divider CSS

.headerDivider {
     border-left:1px solid #38546d; 
     border-right:1px solid #16222c; 

<div class="headerDivider"></div>

Android on-screen keyboard auto popping up

Add this in your AndroidManifest.xml :


It works perfectly. :)

Get only specific attributes with from Laravel Collection

I had a similar issue where I needed to select values from a large array, but I wanted the resulting collection to only contain values of a single value.

pluck() could be used for this purpose (if only 1 key item is required)

you could also use reduce(). Something like this with reduce:

$result = $items->reduce(function($carry, $item) {
    return $carry->push($item->getCode());
}, collect());

HTML5 File API read as text and binary

Note in 2018: readAsBinaryString is outdated. For use cases where previously you'd have used it, these days you'd use readAsArrayBuffer (or in some cases, readAsDataURL) instead.

readAsBinaryString says that the data must be represented as a binary string, where:

...every byte is represented by an integer in the range [0..255].

JavaScript originally didn't have a "binary" type (until ECMAScript 5's WebGL support of Typed Array* (details below) -- it has been superseded by ECMAScript 2015's ArrayBuffer) and so they went with a String with the guarantee that no character stored in the String would be outside the range 0..255. (They could have gone with an array of Numbers instead, but they didn't; perhaps large Strings are more memory-efficient than large arrays of Numbers, since Numbers are floating-point.)

If you're reading a file that's mostly text in a western script (mostly English, for instance), then that string is going to look a lot like text. If you read a file with Unicode characters in it, you should notice a difference, since JavaScript strings are UTF-16** (details below) and so some characters will have values above 255, whereas a "binary string" according to the File API spec wouldn't have any values above 255 (you'd have two individual "characters" for the two bytes of the Unicode code point).

If you're reading a file that's not text at all (an image, perhaps), you'll probably still get a very similar result between readAsText and readAsBinaryString, but with readAsBinaryString you know that there won't be any attempt to interpret multi-byte sequences as characters. You don't know that if you use readAsText, because readAsText will use an encoding determination to try to figure out what the file's encoding is and then map it to JavaScript's UTF-16 strings.

You can see the effect if you create a file and store it in something other than ASCII or UTF-8. (In Windows you can do this via Notepad; the "Save As" as an encoding drop-down with "Unicode" on it, by which looking at the data they seem to mean UTF-16; I'm sure Mac OS and *nix editors have a similar feature.) Here's a page that dumps the result of reading a file both ways:

<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Show File Data</title>
<style type='text/css'>
body {
    font-family: sans-serif;
<script type='text/javascript'>

    function loadFile() {
        var input, file, fr;

        if (typeof window.FileReader !== 'function') {
            bodyAppend("p", "The file API isn't supported on this browser yet.");

        input = document.getElementById('fileinput');
        if (!input) {
            bodyAppend("p", "Um, couldn't find the fileinput element.");
        else if (!input.files) {
            bodyAppend("p", "This browser doesn't seem to support the `files` property of file inputs.");
        else if (!input.files[0]) {
            bodyAppend("p", "Please select a file before clicking 'Load'");
        else {
            file = input.files[0];
            fr = new FileReader();
            fr.onload = receivedText;

        function receivedText() {
            showResult(fr, "Text");

            fr = new FileReader();
            fr.onload = receivedBinary;

        function receivedBinary() {
            showResult(fr, "Binary");

    function showResult(fr, label) {
        var markup, result, n, aByte, byteStr;

        markup = [];
        result = fr.result;
        for (n = 0; n < result.length; ++n) {
            aByte = result.charCodeAt(n);
            byteStr = aByte.toString(16);
            if (byteStr.length < 2) {
                byteStr = "0" + byteStr;
        bodyAppend("p", label + " (" + result.length + "):");
        bodyAppend("pre", markup.join(" "));

    function bodyAppend(tagName, innerHTML) {
        var elm;

        elm = document.createElement(tagName);
        elm.innerHTML = innerHTML;

<form action='#' onsubmit="return false;">
<input type='file' id='fileinput'>
<input type='button' id='btnLoad' value='Load' onclick='loadFile();'>

If I use that with a "Testing 1 2 3" file stored in UTF-16, here are the results I get:

Text (13):

54 65 73 74 69 6e 67 20 31 20 32 20 33

Binary (28):

ff fe 54 00 65 00 73 00 74 00 69 00 6e 00 67 00 20 00 31 00 20 00 32 00 20 00 33 00

As you can see, readAsText interpreted the characters and so I got 13 (the length of "Testing 1 2 3"), and readAsBinaryString didn't, and so I got 28 (the two-byte BOM plus two bytes for each character).

* XMLHttpRequest.response with responseType = "arraybuffer" is supported in HTML 5.

** "JavaScript strings are UTF-16" may seem like an odd statement; aren't they just Unicode? No, a JavaScript string is a series of UTF-16 code units; you see surrogate pairs as two individual JavaScript "characters" even though, in fact, the surrogate pair as a whole is just one character. See the link for details.

PHP - auto refreshing page

Try out this as well. Your page will refresh every 10sec


  <meta http-equiv="refresh" content="10; url="<?php echo $_SERVER['PHP_SELF']; ?>">


ng-change not working on a text input

When you want to edit something in Angular you need to insert an ngModel in your html

try this in your sample:

    <input type="text" name="abc" class="color" ng-model="myStyle.color">

You don't need to watch the change at all!

What does "ulimit -s unlimited" do?

When you call a function, a new "namespace" is allocated on the stack. That's how functions can have local variables. As functions call functions, which in turn call functions, we keep allocating more and more space on the stack to maintain this deep hierarchy of namespaces.

To curb programs using massive amounts of stack space, a limit is usually put in place via ulimit -s. If we remove that limit via ulimit -s unlimited, our programs will be able to keep gobbling up RAM for their evergrowing stack until eventually the system runs out of memory entirely.

int eat_stack_space(void) { return eat_stack_space(); }
// If we compile this with no optimization and run it, our computer could crash.

Usually, using a ton of stack space is accidental or a symptom of very deep recursion that probably should not be relying so much on the stack. Thus the stack limit.

Impact on performace is minor but does exist. Using the time command, I found that eliminating the stack limit increased performance by a few fractions of a second (at least on 64bit Ubuntu).

Change CSS class properties with jQuery

Here's a bit of an improvement on the excellent answer provided by Mathew Wolf. This one appends the main container as a style tag to the head element and appends each new class to that style tag. a little more concise and I find it works well.

function changeCss(className, classValue) {
    var cssMainContainer = $('#css-modifier-container');

    if (cssMainContainer.length == 0) {
        var cssMainContainer = $('<style id="css-modifier-container"></style>');

    cssMainContainer.append(className + " {" + classValue + "}\n");

How to set cookie value with AJAX request?

Basically, ajax request as well as synchronous request sends your document cookies automatically. So, you need to set your cookie to document, not to request. However, your request is cross-domain, and things became more complicated. Basing on this answer, additionally to set document cookie, you should allow its sending to cross-domain environment:

type: "GET",    
url: "",
cache: false,
// NO setCookies option available, set cookie to document
//setCookies: "lkfh89asdhjahska7al446dfg5kgfbfgdhfdbfgcvbcbc dfskljvdfhpl",
crossDomain: true,
dataType: 'json',
xhrFields: {
    withCredentials: true
success: function (data) {

redirect to current page in ASP.Net

The most common way to implement this pattern in ASP.Net is to use Response.Redirect(Request.RawUrl)

Consider the differences between Redirect and Transfer. Transfer really isn't telling the browser to forward to a clear form, it's simply returning a cleared form. That may or may not be what you want.

Response.Redirect() does not a waste round trip. If you post to a script that clears the form by Server.Transfer() and reload you will be asked to repost by most browsers since the last action was a HTTP POST. This may cause your users to unintentionally repeat some action, eg. place a second order which will have to be voided later.

How do I check if a Socket is currently connected in Java?

Assuming you have some level of control over the protocol, I'm a big fan of sending heartbeats to verify that a connection is active. It's proven to be the most fail proof method and will often give you the quickest notification when a connection has been broken.

TCP keepalives will work, but what if the remote host is suddenly powered off? TCP can take a long time to timeout. On the other hand, if you have logic in your app that expects a heartbeat reply every x seconds, the first time you don't get them you know the connection no longer works, either by a network or a server issue on the remote side.

See Do I need to heartbeat to keep a TCP connection open? for more discussion.

Insert data into a view (SQL Server)

Go to design for that table. Now, on the right, set the ID column as the column in question. It will now auto populate without specification.

How to convert a pymongo.cursor.Cursor into a dict?


import pymongo
conn = pymongo.MongoClient()
db = conn.test #test is my database
col = db.spam #Here spam is my collection
array = list(col.find())

print array

There you go

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

Node.js uses the environmental variable NODE_PATH to allow for specifying additional directories to include in the module search path. You can use npm itself to tell you where global modules are stored with the npm root -g command. So putting those two together, you can make sure global modules are included in your search path with the following command (on Linux-ish)

export NODE_PATH=$(npm root --quiet -g)

MS Access - execute a saved query by name in VBA

To use CurrentDb.Execute, your query must be an action query, AND in quotes.

CurrentDb.Execute "queryname"

No matching client found for package name (Google Analytics) - multiple productFlavors & buildTypes

if none of it worked for one of you guys, my problem was with a package name that didn't start with a 'com'. changed it, now it works.

hope that helps

Can I use jQuery with Node.js?

Yes, jQuery can be used with Node.js.

Steps to include jQuery in node project:-

npm i jquery --save Include jquery in codes

import jQuery from 'jquery';

const $ = jQuery;

I do use jquery in node.js projects all the time specifically in the chrome extension's project.


How to save an image locally using Python whose URL address I already know?

Version for Python 3

I adjusted the code of @madprops for Python 3

# python2 script to download all images in a given url
# use: python http://url.where.images.are

from bs4 import BeautifulSoup
import urllib.request
import shutil
import requests
from urllib.parse import urljoin
import sys
import time

def make_soup(url):
    req = urllib.request.Request(url, headers={'User-Agent' : "Magic Browser"}) 
    html = urllib.request.urlopen(req)
    return BeautifulSoup(html, 'html.parser')

def get_images(url):
    soup = make_soup(url)
    images = [img for img in soup.findAll('img')]
    print (str(len(images)) + " images found.")
    print('Downloading images to current working directory.')
    image_links = [each.get('src') for each in images]
    for each in image_links:
            filename = each.strip().split('/')[-1].strip()
            src = urljoin(url, each)
            print('Getting: ' + filename)
            response = requests.get(src, stream=True)
            # delay to avoid corrupted previews
            with open(filename, 'wb') as out_file:
                shutil.copyfileobj(response.raw, out_file)
            print('  An error occured. Continuing.')

if __name__ == '__main__':

Making HTML page zoom by default

A better solution is not to make your page dependable on zoom settings. If you set limits like the one you are proposing, you are limiting accessibility. If someone cannot read your text well, they just won't be able to change that. I would use proper CSS to make it look nice in any zoom.

If your really insist, take a look at this question on how to detect zoom level using JavaScript (nightmare!): How to detect page zoom level in all modern browsers?

How to validate an Email in PHP?

I always use this:

function validEmail($email){
    // First, we check that there's one @ symbol, and that the lengths are right
    if (!preg_match("/^[^@]{1,64}@[^@]{1,255}$/", $email)) {
        // Email invalid because wrong number of characters in one section, or wrong number of @ symbols.
        return false;
    // Split it into sections to make life easier
    $email_array = explode("@", $email);
    $local_array = explode(".", $email_array[0]);
    for ($i = 0; $i < sizeof($local_array); $i++) {
        if (!preg_match("/^(([A-Za-z0-9!#$%&'*+\/=?^_`{|}~-][A-Za-z0-9!#$%&'*+\/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$/", $local_array[$i])) {
            return false;
    if (!preg_match("/^\[?[0-9\.]+\]?$/", $email_array[1])) { // Check if domain is IP. If not, it should be valid domain name
        $domain_array = explode(".", $email_array[1]);
        if (sizeof($domain_array) < 2) {
            return false; // Not enough parts to domain
        for ($i = 0; $i < sizeof($domain_array); $i++) {
            if (!preg_match("/^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$/", $domain_array[$i])) {
                return false;

    return true;

How to pass data between fragments

IN my case i had to send the data backwards from FragmentB->FragmentA hence Intents was not an option as the fragment would already be initialised All though all of the above answers sounds good it takes a lot of boiler plate code to implement, so i went with a much simpler approach of using LocalBroadcastManager, it exactly does the above said but without alll the nasty boilerplate code. An example is shared below.

In Sending Fragment(Fragment B)

public class FragmentB {

    private void sendMessage() {
      Intent intent = new Intent("custom-event-name");
      intent.putExtra("message", "your message");

And in the Message to be Received Fragment(FRAGMENT A)

  public class FragmentA {
    public void onCreate(Bundle savedInstanceState) {


      // Register receiver
          new IntentFilter("custom-event-name"));

//    This will be called whenever an Intent with an action named "custom-event-name" is broadcasted.
    private BroadcastReceiver receiver = new BroadcastReceiver() {
      public void onReceive(Context context, Intent intent) {
        String message = intent.getStringExtra("message");

Hope it helps someone

How to Execute SQL Server Stored Procedure in SQL Developer?

You need to add a ',' between the paramValue1 and paramValue2. You missed it.

EXEC proc_name 'paramValue1','paramValue2'

Uninstall Node.JS using Linux command line?

if you want to just update node, there's a neat updater too

to use,

git clone git:// ~/.nvm

source ~/.nvm/

nvm install v0.4.1

Facebook user url by id

As of now (NOV-2019), graph.api V5.0

graph API says, refer graph api

A link to the person's Timeline. The link will only resolve if the person clicking the link is logged into Facebook and is a friend of the person whose profile is being viewed.


How to find the operating system version using JavaScript?

I fork @Ludwig code and remove necessity of swfobject.

I just use swfobject code for detect flash version.

 * JavaScript Client Detection
 * (C) viazenetti GmbH (Christian Ludwig)
(function (window) {
    var unknown = '-';

    // screen
    var screenSize = '';
    if (screen.width) {
        width = (screen.width) ? screen.width : '';
        height = (screen.height) ? screen.height : '';
        screenSize += '' + width + " x " + height;

    var nVer = navigator.appVersion;
    var nAgt = navigator.userAgent;
    var browser = navigator.appName;
    var version = '' + parseFloat(navigator.appVersion);
    var majorVersion = parseInt(navigator.appVersion, 10);
    var nameOffset, verOffset, ix;

    // Opera
    if ((verOffset = nAgt.indexOf('Opera')) != -1) {
        browser = 'Opera';
        version = nAgt.substring(verOffset + 6);
        if ((verOffset = nAgt.indexOf('Version')) != -1) {
        version = nAgt.substring(verOffset + 8);
    // MSIE
    else if ((verOffset = nAgt.indexOf('MSIE')) != -1) {
        browser = 'Microsoft Internet Explorer';
        version = nAgt.substring(verOffset + 5);
    // Chrome
    else if ((verOffset = nAgt.indexOf('Chrome')) != -1) {
        browser = 'Chrome';
        version = nAgt.substring(verOffset + 7);
    // Safari
    else if ((verOffset = nAgt.indexOf('Safari')) != -1) {
        browser = 'Safari';
        version = nAgt.substring(verOffset + 7);
        if ((verOffset = nAgt.indexOf('Version')) != -1) {
        version = nAgt.substring(verOffset + 8);
    // Firefox
    else if ((verOffset = nAgt.indexOf('Firefox')) != -1) {
        browser = 'Firefox';
        version = nAgt.substring(verOffset + 8);
    // MSIE 11+
    else if (nAgt.indexOf('Trident/') != -1) {
        browser = 'Microsoft Internet Explorer';
        version = nAgt.substring(nAgt.indexOf('rv:') + 3);
    // Other browsers
    else if ((nameOffset = nAgt.lastIndexOf(' ') + 1) < (verOffset = nAgt.lastIndexOf('/'))) {
        browser = nAgt.substring(nameOffset, verOffset);
        version = nAgt.substring(verOffset + 1);
        if (browser.toLowerCase() == browser.toUpperCase()) {
        browser = navigator.appName;
    // trim the version string
    if ((ix = version.indexOf(';')) != -1) version = version.substring(0, ix);
    if ((ix = version.indexOf(' ')) != -1) version = version.substring(0, ix);
    if ((ix = version.indexOf(')')) != -1) version = version.substring(0, ix);

    majorVersion = parseInt('' + version, 10);
    if (isNaN(majorVersion)) {
        version = '' + parseFloat(navigator.appVersion);
        majorVersion = parseInt(navigator.appVersion, 10);

    // mobile version
    var mobile = /Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(nVer);

    // cookie
    var cookieEnabled = (navigator.cookieEnabled) ? true : false;

    if (typeof navigator.cookieEnabled == 'undefined' && !cookieEnabled) {
        document.cookie = 'testcookie';
        cookieEnabled = (document.cookie.indexOf('testcookie') != -1) ? true : false;

    // system
    var os = unknown;
    var clientStrings = [
        {s:'Windows 10', r:/(Windows 10.0|Windows NT 10.0)/},
        {s:'Windows 8.1', r:/(Windows 8.1|Windows NT 6.3)/},
        {s:'Windows 8', r:/(Windows 8|Windows NT 6.2)/},
        {s:'Windows 7', r:/(Windows 7|Windows NT 6.1)/},
        {s:'Windows Vista', r:/Windows NT 6.0/},
        {s:'Windows Server 2003', r:/Windows NT 5.2/},
        {s:'Windows XP', r:/(Windows NT 5.1|Windows XP)/},
        {s:'Windows 2000', r:/(Windows NT 5.0|Windows 2000)/},
        {s:'Windows ME', r:/(Win 9x 4.90|Windows ME)/},
        {s:'Windows 98', r:/(Windows 98|Win98)/},
        {s:'Windows 95', r:/(Windows 95|Win95|Windows_95)/},
        {s:'Windows NT 4.0', r:/(Windows NT 4.0|WinNT4.0|WinNT|Windows NT)/},
        {s:'Windows CE', r:/Windows CE/},
        {s:'Windows 3.11', r:/Win16/},
        {s:'Android', r:/Android/},
        {s:'Open BSD', r:/OpenBSD/},
        {s:'Sun OS', r:/SunOS/},
        {s:'Linux', r:/(Linux|X11)/},
        {s:'iOS', r:/(iPhone|iPad|iPod)/},
        {s:'Mac OS X', r:/Mac OS X/},
        {s:'Mac OS', r:/(MacPPC|MacIntel|Mac_PowerPC|Macintosh)/},
        {s:'QNX', r:/QNX/},
        {s:'UNIX', r:/UNIX/},
        {s:'BeOS', r:/BeOS/},
        {s:'OS/2', r:/OS\/2/},
        {s:'Search Bot', r:/(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver)/}
    for (var id in clientStrings) {
        var cs = clientStrings[id];
        if (cs.r.test(nAgt)) {
        os = cs.s;

    var osVersion = unknown;

    if (/Windows/.test(os)) {
        osVersion = /Windows (.*)/.exec(os)[1];
        os = 'Windows';

    switch (os) {
        case 'Mac OS X':
        osVersion = /Mac OS X (10[\.\_\d]+)/.exec(nAgt)[1];

        case 'Android':
        osVersion = /Android ([\.\_\d]+)/.exec(nAgt)[1];

        case 'iOS':
        osVersion = /OS (\d+)_(\d+)_?(\d+)?/.exec(nVer);
        osVersion = osVersion[1] + '.' + osVersion[2] + '.' + (osVersion[3] | 0);

    var flashVersion = 'no check', d, fv = [];
    if (typeof navigator.plugins !== 'undefined' && typeof navigator.plugins["Shockwave Flash"] === "object") {
        d = navigator.plugins["Shockwave Flash"].description;
        if (d && !(typeof navigator.mimeTypes !== 'undefined' && navigator.mimeTypes["application/x-shockwave-flash"] && !navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin)) { // navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin indicates whether plug-ins are enabled or disabled in Safari 3+
        d = d.replace(/^.*\s+(\S+\s+\S+$)/, "$1");
        fv[0] = parseInt(d.replace(/^(.*)\..*$/, "$1"), 10);
        fv[1] = parseInt(d.replace(/^.*\.(.*)\s.*$/, "$1"), 10);
        fv[2] = /[a-zA-Z]/.test(d) ? parseInt(d.replace(/^.*[a-zA-Z]+(.*)$/, "$1"), 10) : 0;
    } else if (typeof window.ActiveXObject !== 'undefined') {
        try {
        var a = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
        if (a) { // a will return null when ActiveX is disabled
            d = a.GetVariable("$version");
            if (d) {
            d = d.split(" ")[1].split(",");
            fv = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
        catch(e) {}
    if (fv.length) {
        flashVersion = fv[0] + '.' + fv[1] + ' r' + fv[2];

    window.jscd = {
    screen: screenSize,
    browser: browser,
    browserVersion: version,
    mobile: mobile,
    os: os,
    osVersion: osVersion,
    cookies: cookieEnabled,
    flashVersion: flashVersion

    'OS: ' + jscd.os +' '+ jscd.osVersion + '\n'+
    'Browser: ' + jscd.browser +' '+ jscd.browserVersion + '\n' + 
    'Mobile: ' + + '\n' +
    'Flash: ' + jscd.flashVersion + '\n' +
    'Cookies: ' + jscd.cookies + '\n' +
    'Screen Size: ' + jscd.screen + '\n\n' +
    'Full User Agent: ' + navigator.userAgent

Create empty data frame with column names by assigning a string vector?

How about:

df <- data.frame(matrix(ncol = 3, nrow = 0))
x <- c("name", "age", "gender")
colnames(df) <- x

To do all these operations in one-liner:

setNames(data.frame(matrix(ncol = 3, nrow = 0)), c("name", "age", "gender"))

#[1] name   age    gender
#<0 rows> (or 0-length row.names)


data.frame(matrix(ncol=3,nrow=0, dimnames=list(NULL, c("name", "age", "gender"))))

Python: Split a list into sub-lists based on index ranges

In python, it's called slicing. Here is an example of python's slice notation:

>>> list1 = ['a','b','c','d','e','f','g','h', 'i', 'j', 'k', 'l']
>>> print list1[:5]
['a', 'b', 'c', 'd', 'e']
>>> print list1[-7:]
['f', 'g', 'h', 'i', 'j', 'k', 'l']

Note how you can slice either positively or negatively. When you use a negative number, it means we slice from right to left.

How to use the ProGuard in Android Studio?

You're probably not actually signing the release build of the APK via the signing wizard. You can either build the release APK from the command line with the command:

./gradlew assembleRelease

or you can choose the release variant from the Build Variants view and build it from the GUI:

IDE main window showing Build Variants

jQuery .find() on data from .ajax() call is returning "[object Object]" instead of div

This worked for me, you just need to put .html() on the end of - $(response).find("#result")

J2ME/Android/BlackBerry - driving directions, route between two locations

J2ME Map Route Provider has a navigation service which can provide you route information in KML format.

To get kml file we need to form url with start and destination locations:

public static String getUrl(double fromLat, double fromLon,
                            double toLat, double toLon) {// connect to map web service
    StringBuffer urlString = new StringBuffer();
    urlString.append("&saddr=");// from
    urlString.append("&daddr=");// to
    return urlString.toString();

Next you will need to parse xml (implemented with SAXParser) and fill data structures:

public class Point {
    String mName;
    String mDescription;
    String mIconUrl;
    double mLatitude;
    double mLongitude;

public class Road {
    public String mName;
    public String mDescription;
    public int mColor;
    public int mWidth;
    public double[][] mRoute = new double[][] {};
    public Point[] mPoints = new Point[] {};

Network connection is implemented in different ways on Android and Blackberry, so you will have to first form url:

 public static String getUrl(double fromLat, double fromLon,
     double toLat, double toLon)

then create connection with this url and get InputStream.
Then pass this InputStream and get parsed data structure:

 public static Road getRoute(InputStream is) 

Full source code


class MapPathScreen extends MainScreen {
    MapControl map;
    Road mRoad = new Road();
    public MapPathScreen() {
        double fromLat = 49.85, fromLon = 24.016667;
        double toLat = 50.45, toLon = 30.523333;
        String url = RoadProvider.getUrl(fromLat, fromLon, toLat, toLon);
        InputStream is = getConnection(url);
        mRoad = RoadProvider.getRoute(is);
        map = new MapControl();
        add(new LabelField(mRoad.mName));
        add(new LabelField(mRoad.mDescription));
    protected void onUiEngineAttached(boolean attached) {
        if (attached) {
    private InputStream getConnection(String url) {
        HttpConnection urlConnection = null;
        InputStream is = null;
        try {
            urlConnection = (HttpConnection);
            is = urlConnection.openInputStream();
        } catch (IOException e) {
        return is;

See full code on J2MEMapRouteBlackBerryEx on Google Code


Android G1 screenshot

public class MapRouteActivity extends MapActivity {
    LinearLayout linearLayout;
    MapView mapView;
    private Road mRoad;
    public void onCreate(Bundle savedInstanceState) {
        mapView = (MapView) findViewById(;
        new Thread() {
            public void run() {
                double fromLat = 49.85, fromLon = 24.016667;
                double toLat = 50.45, toLon = 30.523333;
                String url = RoadProvider
                        .getUrl(fromLat, fromLon, toLat, toLon);
                InputStream is = getConnection(url);
                mRoad = RoadProvider.getRoute(is);

    Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            TextView textView = (TextView) findViewById(;
            textView.setText(mRoad.mName + " " + mRoad.mDescription);
            MapOverlay mapOverlay = new MapOverlay(mRoad, mapView);
            List<Overlay> listOfOverlays = mapView.getOverlays();

    private InputStream getConnection(String url) {
        InputStream is = null;
        try {
            URLConnection conn = new URL(url).openConnection();
            is = conn.getInputStream();
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        return is;
    protected boolean isRouteDisplayed() {
        return false;

See full code on J2MEMapRouteAndroidEx on Google Code

JavaScript: How to get parent element by selector?

I thought I would provide a much more robust example, also in typescript, but it would be easy to convert to pure javascript. This function will query parents using either the ID like so "#my-element" or the class ".my-class" and unlike some of these answers will handle multiple classes. I found I named some similarly and so the examples above were finding the wrong things.

function queryParentElement(el:HTMLElement | null, selector:string) {
    let isIDSelector = selector.indexOf("#") === 0
    if (selector.indexOf('.') === 0 || selector.indexOf('#') === 0) {
        selector = selector.slice(1)
    while (el) {
        if (isIDSelector) {
            if ( === selector) {
                return el
        else if (el.classList.contains(selector)) {
            return el;
        el = el.parentElement;
    return null;

To select by class name:

let elementByClassName = queryParentElement(someElement,".my-class")

To select by ID:

let elementByID = queryParentElement(someElement,"#my-element")

SQL to search objects, including stored procedures, in Oracle

I would use DBA_SOURCE (if you have access to it) because if the object you require is not owned by the schema under which you are logged in you will not see it.

If you need to know the functions and Procs inside the packages try something like this:

select * from all_source
 where type = 'PACKAGE'
   and (upper(text) like '%FUNCTION%' or upper(text) like '%PROCEDURE%')
   and owner != 'SYS';

The last line prevents all the sys stuff (DBMS_ et al) from being returned. This will work in user_source if you just want your own schema stuff.

How can I right-align text in a DataGridView column?

I know this is old, but for those surfing this question, the answer by MUG4N will align all columns that use the same defaultcellstyle. I'm not using autogeneratecolumns so that is not acceptable. Instead I used:

e.Column.DefaultCellStyle = new DataGridViewCellStyle(e.Column.DefaultCellStyle);
e.Column.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

In this case e is from:

Grd_ColumnAdded(object sender, DataGridViewColumnEventArgs e)  

PHP - find entry by object property from an array of objects

I've found more elegant solution here. Adapted to the question it may look like:

$neededObject = array_filter(
    function ($e) use ($searchedValue) {
        return $e->id == $searchedValue;

No serializer found for class org.hibernate.proxy.pojo.javassist.Javassist?

it works for me



@Table(name = "user")
public class User {

    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    private Date created;


How do you calculate log base 2 in Java for integers?

you can use the identity

 log[b]x = ---------

so this would be applicable for log2.

 log[2]x = ----------

just plug this into the java Math log10 method....

Fastest way to Remove Duplicate Value from a list<> by lambda

List<long> distinctlongs = longs.Distinct().OrderBy(x => x).ToList();

What is the difference between range and xrange functions in Python 2.X?

Remember, use the timeit module to test which of small snippets of code is faster!

$ python -m timeit 'for i in range(1000000):' ' pass'
10 loops, best of 3: 90.5 msec per loop
$ python -m timeit 'for i in xrange(1000000):' ' pass'
10 loops, best of 3: 51.1 msec per loop

Personally, I always use range(), unless I were dealing with really huge lists -- as you can see, time-wise, for a list of a million entries, the extra overhead is only 0.04 seconds. And as Corey points out, in Python 3.0 xrange() will go away and range() will give you nice iterator behavior anyway.

C# 4.0: Convert pdf to byte[] and vice versa

// loading bytes from a file is very easy in C#. The built in System.IO.File.ReadAll* methods take care of making sure every byte is read properly.
// note that for Linux, you will not need the c: part
// just swap out the example folder here with your actual full file path
string pdfFilePath = "c:/pdfdocuments/myfile.pdf";
byte[] bytes = System.IO.File.ReadAllBytes(pdfFilePath);

// munge bytes with whatever pdf software you want, i.e.
// bytes = MungePdfBytes(bytes); // MungePdfBytes is your custom method to change the PDF data
// ...
// make sure to cleanup after yourself

// and save back - System.IO.File.WriteAll* makes sure all bytes are written properly - this will overwrite the file, if you don't want that, change the path here to something else
System.IO.File.WriteAllBytes(pdfFilePath, bytes);

How to convert a String to JsonObject using gson library

JsonObject jsonObject = (JsonObject) new JsonParser().parse("YourJsonString");

What is the difference between --save and --save-dev?

People use npm on production to do wicked cool stuff, Node.js is an example of this, so you don't want all your dev tools being run.

If you are using gulp (or similar) to create build files to put on your server then it doesn't really matter.

Usages of doThrow() doAnswer() doNothing() and doReturn() in mockito

It depends on the kind of test double you want to interact with:

  • If you don't use doNothing and you mock an object, the real method is not called
  • If you don't use doNothing and you spy an object, the real method is called

In other words, with mocking the only useful interactions with a collaborator are the ones that you provide. By default functions will return null, void methods do nothing.

"Submit is not a function" error in JavaScript

Use getElementById:

document.getElementById ('frmProduct').submit ()

What is http multipart request?

As the official specification says, "one or more different sets of data are combined in a single body". So when photos and music are handled as multipart messages as mentioned in the question, probably there is some plain text metadata associated as well, thus making the request containing different types of data (binary, text), which implies the usage of multipart.

Setting graph figure size

A different approach.
On the figure() call specify properties or modify the figure handle properties after h = figure().

This creates a full screen figure based on normalized units.
figure('units','normalized','outerposition',[0 0 1 1])

The units property can be adjusted to inches, centimeters, pixels, etc.

See figure documentation.

How to convert index of a pandas dataframe into a column?

For MultiIndex you can extract its subindex using

df['si_name'] = R.index.get_level_values('si_name') 

where si_name is the name of the subindex.

fatal: 'origin' does not appear to be a git repository

This does not answer your question, but I faced a similar error message but due to a different reason. Allow me to make my post for the sake of information collection.

I have a git repo on a network drive. Let's call this network drive RAID. I cloned this repo on my local machine (LOCAL) and on my number crunching cluster (CRUNCHER). For convenience I mounted the user directory of my account on CRUNCHER on my local machine. So, I can manipulate files on CRUNCHER without the need to do the work in an SSH terminal.

Today, I was modifying files in the repo on CRUNCHER via my local machine. At some point I decided to commit the files, so a did a commit. Adding the modified files and doing the commit worked as I expected, but when I called git push I got an error message similar to the one posted in the question.

The reason was, that I called push from within the repo on CRUNCHER on LOCAL. So, all paths in the config file were plain wrong.

When I realized my fault, I logged onto CRUNCHER via Terminal and was able to push the commit.

Feel free to comment if my explanation can't be understood, or you find my post superfluous.

iOS download and save image inside app

Here is a Swift 5 solution for downloading and saving an image or in general a file to the documents directory by using Alamofire:

func dowloadAndSaveFile(from url: URL) {
    let destination: DownloadRequest.DownloadFileDestination = { _, _ in
        var documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
        return (documentsURL, [.removePreviousFile])
    let request =, method: .get, to: destination)
    request.validate().responseData { response in
        switch response.result {
        case .success:
            if let destinationURL = response.destinationURL {
        case .failure(let error):

T-SQL query to show table definition?

The easiest and quickest way I can think of would be to use sp_help

sp_help 'TableName'

How to set a tkinter window to a constant size

There are 2 solutions for your problem:

  1. Either you set a fixed size of the Tkinter window; mw.geometry('500x500')


  1. Make the Frame adjust to the size of the window automatically; = 0, y = 0, relwidth = 1, relheight = 1)

*The second option should be used in place of back.pack()

Using Javamail to connect to Gmail smtp server ignores specified port and tries to use 25

In Java you would do something similar to:

Transport transport = session.getTransport("smtps");
transport.connect (smtp_host, smtp_port, smtp_username, smtp_password);
transport.sendMessage(msg, msg.getAllRecipients());

Note 'smtpS' protocol. Also socketFactory properties is no longer necessary in modern JVMs but you might need to set 'mail.smtps.auth' and 'mail.smtps.starttls.enable' to 'true' for Gmail. 'mail.smtps.debug' could be helpful too.

SQL Server : trigger how to read value for Insert, Update, Delete

Here is the syntax to create a trigger:

CREATE TRIGGER trigger_name
ON { table | view }
    { { FOR | AFTER | INSTEAD OF } { [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] }
        [ WITH APPEND ]
        [ { IF UPDATE ( column )
            [ { AND | OR } UPDATE ( column ) ]
                [ ...n ]
        | IF ( COLUMNS_UPDATED ( ) { bitwise_operator } updated_bitmask )
                { comparison_operator } column_bitmask [ ...n ]
        } ]
        sql_statement [ ...n ]

If you want to use On Update you only can do it with the IF UPDATE ( column ) section. That's not possible to do what you are asking.

Settings to Windows Firewall to allow Docker for Windows to share drive

Even after ensuring that the inbound firewall rule is set up properly and even after uninstalling and reinstalling the File and Printing Sharing Service it didn't work for me.

Solution: on top of that I also had to do a third thing. I had to deactivate the checkbox Prevent incoming connections when on a public network in the specific firewall settings for public networks. After doing that it started working for me as well. See screenshots attached at the end of this message.

Don't know how long this option has been there already. I'm currently working on Win 10 Pro 1709 16299.402.

1. Open specific firewall settings for public networks Open specific firewall settings for public networks

2. Uncheck this checkbox Uncheck this checkbox

Find the max of 3 numbers in Java with different data types

I have a very simple idea:

 int smallest = Math.min(a, Math.min(b, Math.min(c, d)));

Of course, if you have 1000 numbers, it's unusable, but if you have 3 or 4 numbers, its easy and fast.

Regards, Norbert

ArrayList initialization equivalent to array initialization

Arrays.asList can help here:

new ArrayList<Integer>(Arrays.asList(1,2,3,5,8,13,21));

How do I exclude all instances of a transitive dependency when using Gradle?

Ah, the following works and does what I want:

configurations {
  runtime.exclude group: "org.slf4j", module: "slf4j-log4j12"

It seems that an Exclude Rule only has two attributes - group and module. However, the above syntax doesn't prevent you from specifying any arbitrary property as a predicate. When trying to exclude from an individual dependency you cannot specify arbitrary properties. For example, this fails:

dependencies {
  compile ('') {
    exclude group: "org.slf4j", name: "slf4j-log4j12"


No such property: name for class: org.gradle.api.internal.artifacts.DefaultExcludeRule

So even though you can specify a dependency with a group: and name: you can't specify an exclusion with a name:!?!

Perhaps a separate question, but what exactly is a module then? I can understand the Maven notion of groupId:artifactId:version, which I understand translates to group:name:version in Gradle. But then, how do I know what module (in gradle-speak) a particular Maven artifact belongs to?

Difference between fprintf, printf and sprintf?

In C, a "stream" is an abstraction; from the program's perspective it is simply a producer (input stream) or consumer (output stream) of bytes. It can correspond to a file on disk, to a pipe, to your terminal, or to some other device such as a printer or tty. The FILE type contains information about the stream. Normally, you don't mess with a FILE object's contents directly, you just pass a pointer to it to the various I/O routines.

There are three standard streams: stdin is a pointer to the standard input stream, stdout is a pointer to the standard output stream, and stderr is a pointer to the standard error output stream. In an interactive session, the three usually refer to your console, although you can redirect them to point to other files or devices:

$ myprog < inputfile.dat > output.txt 2> errors.txt

In this example, stdin now points to inputfile.dat, stdout points to output.txt, and stderr points to errors.txt.

fprintf writes formatted text to the output stream you specify.

printf is equivalent to writing fprintf(stdout, ...) and writes formatted text to wherever the standard output stream is currently pointing.

sprintf writes formatted text to an array of char, as opposed to a stream.

How to handle change text of span

You could use the function that changes the text of span1 to change the text of the others.

As a work around, if you really want it to have a change event, then don't asign text to span 1. Instead asign an input variable in jQuery, write a change event to it, and whever ur changing the text of span1 .. instead change the value of your input variable, thus firing change event, like so:

var spanChange = $("<input />");
function someFuncToCalculateAndSetTextForSpan1() {
    //  do work

$(function() {
    spanChange.change(function(e) {
        var $val = $(this).val(),
            $newVal = some*calc-$val;

Though I really feel this "work-around", while useful in some aspects of creating a simple change event, is very overextended, and you'd best be making the changes to other spans at the same time you change span1.

Meaning of ${project.basedir} in pom.xml

${project.basedir} is the root directory of your project.

${} is equivalent to ${project.basedir}/target

as it is defined here:

What is the best open source help ticket system?

I recommend OTRS, its very easily customizable, and we also use it for hundreds of employees (University).

how to get docker-compose to use the latest image from repository

But -quiet-pull Pull without printing progress information

docker-compose up --quiet-pull

not work ?

How to get only time from date-time C#

You have many options for this:

DateTime dt = DateTime.Parse("6/22/2009 07:00:00 AM");

dt.ToString("HH:mm"); // 07:00 // 24 hour clock // hour is always 2 digits
dt.ToString("hh:mm tt"); // 07:00 AM // 12 hour clock // hour is always 2 digits
dt.ToString("H:mm"); // 7:00 // 24 hour clock
dt.ToString("h:mm tt"); // 7:00 AM // 12 hour clock

Helpful Link: DateTime.ToString() Patterns

Use SQL Server Management Studio to connect remotely to an SQL Server Express instance hosted on an Azure Virtual Machine

I too struggled with something similar. My guess is your actual problem is connecting to a SQL Express instance running on a different machine. The steps to do this can be summarized as follows:

  1. Ensure SQL Express is configured for SQL Authentication as well as Windows Authentication (the default). You do this via SQL Server Management Studio (SSMS) Server Properties/Security
  2. In SSMS create a new login called "sqlUser", say, with a suitable password, "sql", say. Ensure this new login is set for SQL Authentication, not Windows Authentication. SSMS Server Security/Logins/Properties/General. Also ensure "Enforce password policy" is unchecked
  3. Under Properties/Server Roles ensure this new user has the "sysadmin" role
  4. In SQL Server Configuration Manager SSCM (search for SQLServerManagerxx.msc file in Windows\SysWOW64 if you can't find SSCM) under SQL Server Network Configuration/Protocols for SQLExpress make sure TCP/IP is enabled. You can disable Named Pipes if you want
  5. Right-click protocol TCP/IP and on the IPAddresses tab, ensure every one of the IP addresses is set to Enabled Yes, and TCP Port 1433 (this is the default port for SQL Server)
  6. In Windows Firewall (WF.msc) create two new Inbound Rules - one for SQL Server and another for SQL Browser Service. For SQL Server you need to open TCP Port 1433 (if you are using the default port for SQL Server) and very importantly for the SQL Browser Service you need to open UDP Port 1434. Name these two rules suitably in your firewall
  7. Stop and restart the SQL Server Service using either SSCM or the Services.msc snap-in
  8. In the Services.msc snap-in make sure SQL Browser Service Startup Type is Automatic and then start this service

At this point you should be able to connect remotely, using SQL Authentication, user "sqlUser" password "sql" to the SQL Express instance configured as above. A final tip and easy way to check this out is to create an empty text file with the .UDL extension, say "Test.UDL" on your desktop. Double-clicking to edit this file invokes the Microsoft Data Link Properties dialog with which you can quickly test your remote SQL connection

Should I make HTML Anchors with 'name' or 'id'?

According to the HTML 5 specification, 5.9.8 Navigating to a fragment identifier:

For HTML documents (and the text/html MIME type), the following processing model must be followed to determine what the indicated part of the document is.

  1. Parse the URL, and let fragid be the <fragment> component of the URL.
  2. If fragid is the empty string, then the indicated part of the document is the top of the document.
  3. If there is an element in the DOM that has an ID exactly equal to fragid, then the first such element in tree order is the indicated part of the document; stop the algorithm here.
  4. If there is an a element in the DOM that has a name attribute whose value is exactly equal to fragid, then the first such element in tree order is the indicated part of the document; stop the algorithm here.
  5. Otherwise, there is no indicated part of the document.

So, it will look for id="foo", and then will follow to name="foo"

Edit: As pointed out by @hsivonen, in HTML5 the a element has no name attribute. However, the above rules still apply to other named elements.

ERROR 1130 (HY000): Host '' is not allowed to connect to this MySQL server

$mysql -u root --host= -p

mysql>use mysql

mysql>GRANT ALL ON *.* to root@'%' IDENTIFIED BY 'redhat@123';


mysql> SELECT host FROM mysql.user WHERE User = 'root';

How to set the text color of TextView in code?

if you want to give color code directly then use


or if you want to give color code from colors folder then use


CSS transition fade on hover

I recommend you to use an unordered list for your image gallery.

You should use my code unless you want the image to gain instantly 50% opacity after you hover out. You will have a smoother transition.

#photos li {
    opacity: .5;
    transition: opacity .5s ease-out;
    -moz-transition: opacity .5s ease-out;
    -webkit-transition: opacity .5s ease-out;
    -o-transition: opacity .5s ease-out;

#photos li:hover {
    opacity: 1;

How to convert java.lang.Object to ArrayList?

Rather Cast It to an Object Array.

Object obj2 = from some source . . ;
Object[] objects=(Object[])obj2;

Android: How to rotate a bitmap on a center point

I came back to this problem now that we are finalizing the game and I just thought to post what worked for me.

This is the method for rotating the Matrix:

this.matrix.setTranslate(this.floatXpos, this.floatYpos);
this.matrix.postRotate((float)this.direction, this.getCenterX(), this.getCenterY()); 

(this.getCenterX() is basically the bitmaps X position + the bitmaps width / 2)

And the method for Drawing the bitmap (called via a RenderManager Class):

canvas.drawBitmap(this.bitmap, this.matrix, null);

So it is prettey straight forward but I find it abit strange that I couldn't get it to work by setRotate followed by postTranslate. Maybe some knows why this doesn't work? Now all the bitmaps rotate properly but it is not without some minor decrease in bitmap quality :/

Anyways, thanks for your help!

How to combine date from one field with time from another field - MS SQL Server

SELECT CAST(your_date_column AS date) + CAST(your_time_column AS datetime) FROM your_table

Works like a charm

Operand type clash: uniqueidentifier is incompatible with int

Sounds to me like at least one of those tables has defined UserID as a uniqueidentifier, not an int. Did you check the data in each table? What does SELECT TOP 1 UserID FROM each table yield? An int or a GUID?


I think you have built a procedure based on all tables that contain a column named UserID. I think you should not have included the aspnet_Membership table in your script, since it's not really one of "your" tables.

If you meant to design your tables around the aspnet_Membership database, then why are the rest of the columns int when that table clearly uses a uniqueidentifier for the UserID column?

how to reset <input type = "file">

jQuery solution:

                $(this).get(0).value = '';
                $(this).get(0).type = '';
                $(this).get(0).type = 'file';

No connection string named 'MyEntities' could be found in the application config file

I have faced the same issue. I was missed to put connection string to startup project as I am performing data access operation from other layer. also if you don't have app.config in your startup project then add app.config file and then add a connection string to that config file.

What is a callback?

A callback is a function pointer that you pass in to another function. The function you are calling will 'callback' (execute) the other function when it has completed.

Check out this link.

How to "inverse match" with regex?

What language are you using? The capabilities and syntax of the regex implementation matter for this.

You could use look-ahead. Using python as an example

import re

not_andrea = re.compile('(?!Andrea)\w{6}', re.IGNORECASE)

To break that down:

(?!Andrea) means 'match if the next 6 characters are not "Andrea"'; if so then

\w means a "word character" - alphanumeric characters. This is equivalent to the class [a-zA-Z0-9_]

\w{6} means exactly 6 word characters.

re.IGNORECASE means that you will exclude "Andrea", "andrea", "ANDREA" ...

Another way is to use your program logic - use all lines not matching Andrea and put them through a second regex to check for 6 characters. Or first check for at least 6 word characters, and then check that it does not match Andrea.

Spring boot - Not a managed type

You can use @EntityScan annotation and provide your entity package for scanning all your jpa entities. You can use this annotation on your base application class where you have used @SpringBootApplication annotation.

e.g. @EntityScan("com.test.springboot.demo.entity")

How to center content in a bootstrap column?

If none of the above work (like in my case trying to center an input), I used Boostrap 4 offset:

<div class="row">
    <div class="col-6 offset-3">
        <input class="form-control" id="myInput" type="text" placeholder="Search..">

How do I declare a model class in my Angular 2 component using TypeScript?

I'd try this:

Split your Model into a separate file called model.ts:

export class Model {
    param1: string;

Import it into your component. This will give you the added benefit of being able to use it in other components:

Import { Model } from './model';

Initialize in the component:

export class testWidget {
   public model: Model;
       this.model = new Model();
       this.model.param1 = "your string value here";

Access it appropriately in the html:

      selector: "testWidget",
      template: "<div>This is a test and {{model.param1}} is my param.</div>"

I want to add to the answer a comment made by @PatMigliaccio because it's important to adapt to the latest tools and technologies:

If you are using angular-cli you can call ng g class model and it will generate it for you. model being replaced with whatever naming you desire.

Execute Python script via crontab

Put your script in a file starting with


Then give execute permission to that script using

chmod a+x

and use the full path of your file in your crontab.

See documentation of execve(2) which is handling the shebang.

release Selenium chromedriver.exe from memory

I have looked at all the responses and tested them all. I pretty much compiled them all into one as a 'Safety closure'. This in c#

NOTE you can change the param from IModule app to that of the actual driver.

 public class WebDriverCleaner

    public static void CloseWebDriver(IModule app)
            if (app?.GetDriver() != null)
                Thread.Sleep(3000); // Gives time for everything to close before quiting
                KillProcessAndChildren("chromedriver.exe"); // One more to make sure we get rid of them chromedrivers.
        catch (Exception e)

    public static void KillProcessAndChildren(string p_name)
        ManagementObjectSearcher searcher = new ManagementObjectSearcher
            ("Select * From Win32_Process Where Name = '" + p_name + "'");

        ManagementObjectCollection moc = searcher.Get();
        foreach (ManagementObject mo in moc)
            catch (ArgumentException)


    public static void KillProcessAndChildren(int pid)
        ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select * From Win32_Process Where ParentProcessID=" + pid);
        ManagementObjectCollection moc = searcher.Get();

        foreach (ManagementObject mo in moc)

            Process proc = Process.GetProcessById(pid);
        catch (ArgumentException)
            // Process already exited.


Excel 2013 VBA Clear All Filters macro

This works best for me.

I usually use the following before I save and close the files.

Sub remove_filters

ActiveSheet.AutofilterMode = False

End Sub

bootstrap initially collapsed element

I just added class hide to the div before "card-body" and it hidden by default.

<div id="collapseOne" class="collapse hide" aria-labelledby="headingOne" data-parent="#accordion">

JSONResult to String

json = " { \"success\" : false, \"errors\": { \"text\" : \"??????!\" } }";            
return new MemoryStream(Encoding.UTF8.GetBytes(json));

Reverse a string in Java

For Online Judges problems that does not allow StringBuilder or StringBuffer, you can do it in place using char[] as following:

public static String reverse(String input){
    char[] in = input.toCharArray();
    int begin=0;
    int end=in.length-1;
    char temp;
        temp = in[begin];
        in[end] = temp;
    return new String(in);

Calling Java from Python

I'm just beginning to use JPype (july 2011) and it looks like it's working nicely...
I'm on Xubuntu 10.04

php function mail() isn't working

I think you are not configured properly,

if you are using XAMPP then you can easily send mail from localhost.

for example you can configure C:\xampp\php\php.ini and c:\xampp\sendmail\sendmail.ini for gmail to send mail.

in C:\xampp\php\php.ini find extension=php_openssl.dll and remove the semicolon from the beginning of that line to make SSL working for gmail for localhost.

in php.ini file find [mail function] and change
sendmail_from = [email protected]
sendmail_path = "C:\xampp\sendmail\sendmail.exe -t"

(use the above send mail path only and it will work)

Now Open C:\xampp\sendmail\sendmail.ini. Replace all the existing code in sendmail.ini with following code

[email protected]
[email protected]

Now you have done!! create php file with mail function and send mail from localhost.


First, make sure you PHP installation has SSL support (look for an "openssl" section in the output from phpinfo()).

You can set the following settings in your PHP.ini:


Why is JavaFX is not included in OpenJDK 8 on Ubuntu Wily (15.10)?

According to the packages list in Ubuntu Wily Xenial Bionic there is a package named openjfx. This should be a candidate for what you're looking for:

JavaFX/OpenJFX 8 - Rich client application platform for Java

You can install it via:

sudo apt-get install openjfx

It provides the following JAR files to the OpenJDK installation on Ubuntu systems:


If you want to have sources available, for example for debugging, you can additionally install:

sudo apt-get install openjfx-source

How to include !important in jquery

Apparently it's possible to do this in jQuery:

$("#tabs").css("cssText", "height: 650px !important;");


What to put in a python module docstring?

Think about somebody doing help(yourmodule) at the interactive interpreter's prompt — what do they want to know? (Other methods of extracting and displaying the information are roughly equivalent to help in terms of amount of information). So if you have in

"""This module does blah blah."""

class Blah(object):
  """This class does blah blah."""


>>> import x; help(x)


Help on module x:

    x - This module does blah blah.



    class Blah(__builtin__.object)
     |  This class does blah blah.
     |  Data and other attributes defined here:
     |  __dict__ = <dictproxy object>
     |      dictionary for instance variables (if defined)
     |  __weakref__ = <attribute '__weakref__' of 'Blah' objects>
     |      list of weak references to the object (if defined)

As you see, the detailed information on the classes (and functions too, though I'm not showing one here) is already included from those components' docstrings; the module's own docstring should describe them very summarily (if at all) and rather concentrate on a concise summary of what the module as a whole can do for you, ideally with some doctested examples (just like functions and classes ideally should have doctested examples in their docstrings).

I don't see how metadata such as author name and copyright / license helps the module's user — it can rather go in comments, since it could help somebody considering whether or not to reuse or modify the module.

How to convert from int to string in objective c: example code

If you just need an int to a string as you suggest, I've found the easiest way is to do as below:

[NSString stringWithFormat:@"%d",numberYouAreTryingToConvert]

What is the worst programming language you ever worked with?

Good God, you mean no one has used PL/SQL? The spawn from the hell that is Oracle is interpreted, and lives in the context of the Oracle Server. All output is spooled, until the program is done. There is an absolute limit on the amount of output that it can display. It is nearly impossible to debug. Ga... I feel I'll just thinking about it.

"X does not name a type" error in C++

On a related note, if you had:

    class User; // let the compiler know such a class will be defined

    class MyMessageBox
        User* myUser;

    class User
        // also ok, since it's now defined
        MyMessageBox dataMsgBox;

Then that would also work, because the User is defined in MyMessageBox as a pointer

How do we download a blob url video

I posted this already at some other websites and though why not share it with guys/gals at stackoverflow.

  1. Install the Video DownloadHelper extension on Firefox browser.
  2. With DownloadHelper activated, navigate to the webpage containing the video that you want to download.
  3. Once the video is streaming, click on the DownloadHelper icon. It will give you a list of all file formats available on the current video.
  4. Scroll onto the file format that you wish to download
  5. On the right hand side, you will see an arrow
  6. Click on that arrow to get more information regarding the current video and the selected format
  7. From the displayed window at the end of that arrow, scroll down and select "Details"
  8. You now have all the details concerning the current video and the selected format. It is something like this.

Hit Details? _needsAggregate _needsCoapp actions bitrate chunked descrPrefix durationFloat extension frameId fromCache group
hls id isPrivate length masterManifest mediaManifest originalId referrer size status title topUrl url urlFilename

  1. Now, look at the specifics of the referrer in that Hit Details. That's the url you want. Copy it and paste on your favorite downloader.

Javascript : natural sort of alphanumerical strings

This is now possible in modern browsers using localeCompare. By passing the numeric: true option, it will smartly recognize numbers. You can do case-insensitive using sensitivity: 'base'. Tested in Chrome, Firefox, and IE11.

Here's an example. It returns 1, meaning 10 goes after 2:

'10'.localeCompare('2', undefined, {numeric: true, sensitivity: 'base'})

For performance when sorting large numbers of strings, the article says:

When comparing large numbers of strings, such as in sorting large arrays, it is better to create an Intl.Collator object and use the function provided by its compare property. Docs link

var collator = new Intl.Collator(undefined, {numeric: true, sensitivity: 'base'});_x000D_
var myArray = ['1_Document', '11_Document', '2_Document'];_x000D_

System.Data.OracleClient requires Oracle client software version 8.1.7

I've run into this error dozens of times:


Security permissions were not properly set when the Oracle client was installed on Windows with NTFS. The result of this is that content of the ORACLE_HOME directory is not visible to Authenticated Users on the machine; this causes an error while the System.Data.OracleClient is communicating with the Oracle Connectivity software from ASP.NET using Authenticated User privileges.


To fix the problem you have to give the Authenticated Users group privilege to the Oracle Home directory.

  • Log on to Windows as a user with Administrator privileges.
  • Start Windows Explorer and navigate to the ORACLE_HOME folder.
  • Choose properties on the ORACLE_HOME folder.
  • Click the Security tab of the Properties window.
  • Click on Authenticated Users item in the Name list.
  • Un-check the Read and Execute box in the Permissions list under the Allow column.
  • Re-check the Read and Execute box under the Allow column.
  • Click the Advanced button and in the Permission Entries verify that Authenticated Users are listed with permission: Read & Execute, and Apply To: This folder, subfolders and files. If not, edit that line and make sure that Apply To drop-down box is set to This folder, subfolders and files. This should already be set properly but it is important that you verify it.
  • Click the OK button until you close out all of the security properties windows. The cursor may present the hour glass for a few seconds as it applies the permissions you just changed to all subfolders and files.
  • Reboot, to assure that the changes have taken effect.

Try your application again.

How to find and return a duplicate value in array

a = ["A", "B", "C", "B", "A"]
a.detect{ |e| a.count(e) > 1 }

I know this isn't very elegant answer, but I love it. It's beautiful one liner code. And works perfectly fine unless you need to process huge data set.

Looking for faster solution? Here you go!

def find_one_using_hash_map(array)
  map = {}
  dup = nil
  array.each do |v|
    map[v] = (map[v] || 0 ) + 1

    if map[v] > 1
      dup = v

  return dup

It's linear, O(n), but now needs to manage multiple lines-of-code, needs test cases, etc.

If you need an even faster solution, maybe try C instead.

And here is the gist comparing different solutions:

PHP 7 RC3: How to install missing MySQL PDO

Had the same issue, resolved by actually enabling the extension in the php.ini with the right file name. It was listed as but the module name in /lib/php/modules was called just

So just remove the "php_" prefix from the php.ini file and then restart the httpd service and it worked like a charm.

Please note that I'm using Arch and thus path names and services may be different depending on your distrubution.

How can I use inverse or negative wildcards when pattern matching in a unix/linux shell?

Not in bash (that I know of), but:

cp `ls | grep -v Music` /target_directory

I know this is not exactly what you were looking for, but it will solve your example.

MD5 hashing in Android

A solution above using DigestUtils didn't work for me. In my version of Apache commons (the latest one for 2013) there is no such class.

I found another solution here in one blog. It works perfect and doesn't need Apache commons. It looks a little shorter than the code in accepted answer above.

public static String getMd5Hash(String input) {
    try {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] messageDigest = md.digest(input.getBytes());
        BigInteger number = new BigInteger(1, messageDigest);
        String md5 = number.toString(16);

        while (md5.length() < 32)
            md5 = "0" + md5;

        return md5;
    } catch (NoSuchAlgorithmException e) {
        Log.e("MD5", e.getLocalizedMessage());
        return null;

You will need these imports:

import java.math.BigInteger;

Removing empty rows of a data file in R

I assume you want to remove rows that are all NAs. Then, you can do the following :

data <- rbind(c(1,2,3), c(1, NA, 4), c(4,6,7), c(NA, NA, NA), c(4, 8, NA)) # sample data
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    1   NA    4
[3,]    4    6    7
[4,]   NA   NA   NA
[5,]    4    8   NA

data[rowSums( != ncol(data),]
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    1   NA    4
[3,]    4    6    7
[4,]    4    8   NA

If you want to remove rows that have at least one NA, just change the condition :

data[rowSums( == 0,]
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    6    7

"Debug only" code that should run only when "turned on"

You could try this if you only need the code to run when you have a debugger attached to the process.

if (Debugger.IsAttached)
     // do some stuff here

How do I capture response of form.submit

You can event.preventDefault() in the click handler for your submit button to ensure that the HTML form default submit event doesn't fire (which is what leads to the page refreshing).

Another alternative would be to use hackier form markup: It's the use of <form> and type="submit" that is getting in the way of the desired behavior here; as these ultimately lead to click events refreshing the page.

If you want to still use <form>, and you don't want to write custom click handlers, you can use jQuery's ajax method, which abstracts the entire problem away for you by exposing promise methods for success, error, etc.

To recap, you can solve your problem by either:

• preventing default behavior in the handling function by using event.preventDefault()

• using elements that don't have default behavior (e.g. <form>)

• using jQuery ajax

(i just noticed this question is from 2008, not sure why it showed up in my feed; at any rate, hopefully this is a clear answer)

Resolving require paths with webpack

Webpack >2.0

See wtk's answer.

Webpack 1.0

A more straightforward way to do this would be to use resolve.root.


The directory (absolute path) that contains your modules. May also be an array of directories. This setting should be used to add individual directories to the search path.

In your case:

webpack config

var path = require('path');

// ...

  resolve: {
    root: path.resolve('./mydir'),
    extensions: ['', '.js']

consuming module




see also:

Python re.sub replace with matched content

Simply use \1 instead of $1:

In [1]: import re

In [2]: method = 'images/:id/huge'

In [3]: re.sub(r'(:[a-z]+)', r'<span>\1</span>', method)
Out[3]: 'images/<span>:id</span>/huge'

Also note the use of raw strings (r'...') for regular expressions. It is not mandatory but removes the need to escape backslashes, arguably making the code slightly more readable.

SQL select everything in an array

SELECT * FROM products WHERE catid IN ('1', '2', '3', '4')

How to save S3 object to a file using boto3

If you wish to download a version of a file, you need to use get_object.

import boto3

bucket = 'bucketName'
prefix = 'path/to/file/'
filename = 'fileName.ext'

s3c = boto3.client('s3')
s3r = boto3.resource('s3')

if __name__ == '__main__':
    for version in s3r.Bucket(bucket).object_versions.filter(Prefix=prefix + filename):
        file = version.get()
        version_id = file.get('VersionId')
        obj = s3c.get_object(
            Key=prefix + filename,
        with open(f"{filename}.{version_id}", 'wb') as f:
            for chunk in obj['Body'].iter_chunks(chunk_size=4096):


Programmatically change the height and width of a UIImageView Xcode Swift

Hey i figured it out shortly after. For some reason I was just having a brain fart.

image.frame = CGRectMake(0 , 0, self.view.frame.width, self.view.frame.height * 0.2)

Reading a JSP variable from JavaScript




or full example

<script language="javascript"> 

function access(){ 
  <% String str="Hello World"; %>
   var s="<%=str%>"; 


<body onload="access()"> 


Note: sanitize the input before rendering it, it may open whole lot of XSS possibilities

Provide password to ssh command inside bash script, Without the usage of public keys and Expect

For security reasons you must avoid providing password on a command line otherwise anyone running ps command can see your password. Better to use sshpass utility like this:


export SSHPASS="your-password"
sshpass -e ssh -oBatchMode=no sshUser@remoteHost

You might be interested in How to run the sftp command with a password from Bash script?

How can two strings be concatenated?

Alternatively, if your objective is to output directly to a file or stdout, you can use cat:

cat(s1, s2, sep=", ")

How to sort with a lambda?

To much code, you can use it like this:


int main()
    std::array<int, 10> vec = { 1,2,3,4,5,6,7,8,9 };

              [](int a, int b) {return a > b; });

    for (auto item : vec)
      std::cout << item << " ";

    return 0;

Replace "vec" with your class and that's it.

How to increase font size in a plot in R?

For completeness, scaling text by 150% with cex = 1.5, here is a full solution:

cex <- 1.5
par(cex.lab=cex, cex.axis=cex, cex.main=cex)
par(cex.lab=1, cex.axis=1, cex.main=1)

I recommend wrapping things like this to reduce boilerplate, e.g.:

plot_cex <- function(x, y, cex=1.5, ...) {
  par(cex.lab=cex, cex.axis=cex, cex.main=cex)
  plot(x, y, ...)
  par(cex.lab=1, cex.axis=1, cex.main=1)

which you can then use like this:

plot_cex(x=1:5, y=rnorm(5), cex=1.3)

The ... are known as ellipses in R and are used to pass additional parameters on to functions. Hence, they are commonly used for plotting. So, the following works as expected:

plot_cex(x=1:5, y=rnorm(5), cex=1.5, ylim=c(-0.5,0.5))

How to find the sum of an array of numbers

ES6 for..of

let total = 0;

for (let value of [1,2,3,4]) {
    total += value; 

About .bash_profile, .bashrc, and where should alias be written in?

From the bash manpage:

When bash is invoked as an interactive login shell, or as a non-interactive shell with the --login option, it first reads and executes commands from the file /etc/profile, if that file exists. After reading that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile, in that order, and reads and executes commands from the first one that exists and is readable. The --noprofile option may be used when the shell is started to inhibit this behavior.

When a login shell exits, bash reads and executes commands from the file ~/.bash_logout, if it exists.

When an interactive shell that is not a login shell is started, bash reads and executes commands from ~/.bashrc, if that file exists. This may be inhibited by using the --norc option. The --rcfile file option will force bash to read and execute commands from file instead of ~/.bashrc.

Thus, if you want to get the same behavior for both login shells and interactive non-login shells, you should put all of your commands in either .bashrc or .bash_profile, and then have the other file source the first one.

How to create a number picker dialog?

For kotlin lovers.

fun numberPickerCustom() {
    val d = AlertDialog.Builder(context)
    val inflater = this.layoutInflater
    val dialogView = inflater.inflate(R.layout.number_picker_dialog, null)
    val numberPicker = dialogView.findViewById<NumberPicker>(
    numberPicker.maxValue = 15
    numberPicker.minValue = 1
    numberPicker.wrapSelectorWheel = false
    numberPicker.setOnValueChangedListener { numberPicker, i, i1 -> println("onValueChange: ") }
    d.setPositiveButton("Done") { dialogInterface, i ->
        println("onClick: " + numberPicker.value)       
    d.setNegativeButton("Cancel") { dialogInterface, i -> }
    val alertDialog = d.create()

and number_picker_dialog.xml



Where do I put my php files to have Xampp parse them?

I created my project folder 'phpproj' in



and it worked for me. I am using Win 7 & and using xampp-win32-1.8.1

I added a php file with the following code


// Show all information, defaults to INFO_ALL


was able to access the file using the following URL


Make sure you restart your Apache server using the control panel before accessing it using the above URL

jQuery detect if string contains something

use Contains of jquery Contains like this

if ($('.type:contains("> <")').length > 0)
 //do stuffs to change 

Convert IEnumerable to DataTable

I also came across this problem. In my case, I didn't know the type of the IEnumerable. So the answers given above wont work. However, I solved it like this:

public static DataTable CreateDataTable(IEnumerable source)
        var table = new DataTable();
        int index = 0;
        var properties = new List<PropertyInfo>();
        foreach (var obj in source)
            if (index == 0)
                foreach (var property in obj.GetType().GetProperties())
                    if (Nullable.GetUnderlyingType(property.PropertyType) != null)
                    table.Columns.Add(new DataColumn(property.Name, property.PropertyType));
            object[] values = new object[properties.Count];
            for (int i = 0; i < properties.Count; i++)
                values[i] = properties[i].GetValue(obj);
        return table;

Keep in mind that using this method, requires at least one item in the IEnumerable. If that's not the case, the DataTable wont create any columns.

onKeyPress Vs. onKeyUp and onKeyDown

The onkeypress event works for all the keys except ALT, CTRL, SHIFT, ESC in all browsers where as onkeydown event works for all keys. Means onkeydown event captures all the keys.

How can I convert String to Int?

You can use either,

int i = Convert.ToInt32(TextBoxD1.Text);


int i = int.Parse(TextBoxD1.Text);

Add button to navigationbar programmatically

Hello everyone !! I created the solution to the issue at hand where Two UIInterface orientations are wanted using the UIIMagePicker.. In my ViewController where I handle the segue to the UIImagePickerController

**I use a..

-(void) editButtonPressed:(id)sender {
   BOOL editPressed = YES;
    NSUserDefaults *boolDefaults = [NSUserDefaults standardUserDefaults];
    [boolDefaults setBool:editPressed forKey:@"boolKey"];
    [boolDefaults synchronize];

    [self performSegueWithIdentifier:@"photoSegue" sender:nil]; 



Then in the AppDelegate Class I do the following.

- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {

    BOOL appDelBool;
    NSUserDefaults *boolDefaults = [NSUserDefaults standardUserDefaults];
    appDelBool = [boolDefaults boolForKey:@"boolKey"];

       if (appDelBool == YES)
           return (UIInterfaceOrientationMaskPortrait);
            return UIInterfaceOrientationMaskLandscapeLeft;

How to select rows that have current day's timestamp?

This could be the easiest in my opinion:

SELECT * FROM `table` WHERE `timestamp` like concat(CURDATE(),'%');

How to add a named sheet at the end of all Excel sheets?

Try switching the order of your code. You must create the worksheet first in order to name it.

Private Sub CreateSheet()
    Dim ws As Worksheet
    Set ws = Sheets.Add(After:=Sheets(Sheets.Count))
    ws.Name = "Tempo"
End Sub


Anonymous method in Invoke call

Actually you do not need to use delegate keyword. Just pass lambda as parameter:

control.Invoke((MethodInvoker)(() => {this.Text = "Hi"; }));

How do I launch the Android emulator from the command line?

Go to the directory where emulator is located


Check emulator list from CLI

emulator -list-avds

Run a AVD from the list

emulator -avd {avd_name}

How to position absolute inside a div?

The problem is described (among other) in this article.

#box is relatively positioned, which makes it part of the "flow" of the page. Your other divs are absolutely positioned, so they are removed from the page's "flow".

Page flow means that the positioning of an element effects other elements in the flow.

In other words, as #box now sees the dom, .a and .b are no longer "inside" #box.

To fix this, you would want to make everything relative, or everything absolute.

One way would be:

.a {
   padding: 5px;

Find a private field with Reflection?

typeof(MyType).GetField("fieldName", BindingFlags.NonPublic | BindingFlags.Instance)

Python: Binary To Decimal Conversion

You can use int casting which allows the base specification.

int(b, 2)  # Convert a binary string to a decimal int.

Nested Git repositories?

You could add




that should prevent the nested repo to be included in the parent repo, and you can work with them independently.

But: If a user runs git clean -dfx in the parent repo, it will remove the ignored nested repo. Another way is to symlink the folder and ignore the symlink. If you then run git clean, the symlink is removed, but the 'nested' repo will remain intact as it really resides elsewhere.

Java LinkedHashMap get first or last entry

I know that I came too late but I would like to offer some alternatives, not something extraordinary but some cases that none mentioned here. In case that someone doesn't care so much for efficiency but he wants something with more simplicity(perhaps find the last entry value with one line of code), all this will get quite simplified with the arrival of Java 8 . I provide some useful scenarios.

For the sake of the completeness, I compare these alternatives with the solution of arrays that already mentioned in this post by others users. I sum up all the cases and i think they would be useful(when performance does matter or no) especially for new developers, always depends on the matter of each problem

Possible Alternatives

Usage of Array Method

I took it from the previous answer to to make the follow comparisons. This solution belongs @feresr.

  public static String FindLasstEntryWithArrayMethod() {
        return String.valueOf(linkedmap.entrySet().toArray()[linkedmap.size() - 1]);

Usage of ArrayList Method

Similar to the first solution with a little bit different performance

public static String FindLasstEntryWithArrayListMethod() {
        List<Entry<Integer, String>> entryList = new ArrayList<Map.Entry<Integer, String>>(linkedmap.entrySet());
        return entryList.get(entryList.size() - 1).getValue();

Reduce Method

This method will reduce the set of elements until getting the last element of stream. In addition, it will return only deterministic results

public static String FindLasstEntryWithReduceMethod() {
        return linkedmap.entrySet().stream().reduce((first, second) -> second).orElse(null).getValue();

SkipFunction Method

This method will get the last element of the stream by simply skipping all the elements before it

public static String FindLasstEntryWithSkipFunctionMethod() {
        final long count = linkedmap.entrySet().stream().count();
        return linkedmap.entrySet().stream().skip(count - 1).findFirst().get().getValue();

Iterable Alternative

Iterables.getLast from Google Guava. It has some optimization for Lists and SortedSets too

public static String FindLasstEntryWithGuavaIterable() {
        return Iterables.getLast(linkedmap.entrySet()).getValue();

Here is the full source code

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class PerformanceTest {

    private static long startTime;
    private static long endTime;
    private static LinkedHashMap<Integer, String> linkedmap;

    public static void main(String[] args) {
        linkedmap = new LinkedHashMap<Integer, String>();

        linkedmap.put(12, "Chaitanya");
        linkedmap.put(2, "Rahul");
        linkedmap.put(7, "Singh");
        linkedmap.put(49, "Ajeet");
        linkedmap.put(76, "Anuj");

        //call a useless action  so that the caching occurs before the jobs starts.
        linkedmap.entrySet().forEach(x -> {});

        startTime = System.nanoTime();
        endTime = System.nanoTime();
        System.out.println("FindLasstEntryWithArrayListMethod : " + "took " + new BigDecimal((endTime - startTime) / 1000000.000).setScale(3, RoundingMode.CEILING) + " milliseconds");

         startTime = System.nanoTime();
        endTime = System.nanoTime();
        System.out.println("FindLasstEntryWithArrayMethod : " + "took " + new BigDecimal((endTime - startTime) / 1000000.000).setScale(3, RoundingMode.CEILING) + " milliseconds");

        startTime = System.nanoTime();
        endTime = System.nanoTime();

        System.out.println("FindLasstEntryWithReduceMethod : " + "took " + new BigDecimal((endTime - startTime) / 1000000.000).setScale(3, RoundingMode.CEILING) + " milliseconds");

        startTime = System.nanoTime();
        endTime = System.nanoTime();

        System.out.println("FindLasstEntryWithSkipFunctionMethod : " + "took " + new BigDecimal((endTime - startTime) / 1000000.000).setScale(3, RoundingMode.CEILING) + " milliseconds");

        startTime = System.currentTimeMillis();
        endTime = System.currentTimeMillis();
        System.out.println("FindLasstEntryWithGuavaIterable : " + "took " + (endTime - startTime) + " milliseconds");


    public static String FindLasstEntryWithReduceMethod() {
        return linkedmap.entrySet().stream().reduce((first, second) -> second).orElse(null).getValue();

    public static String FindLasstEntryWithSkipFunctionMethod() {
        final long count = linkedmap.entrySet().stream().count();
        return linkedmap.entrySet().stream().skip(count - 1).findFirst().get().getValue();

    public static String FindLasstEntryWithGuavaIterable() {
        return Iterables.getLast(linkedmap.entrySet()).getValue();

    public static String FindLasstEntryWithArrayListMethod() {
        List<Entry<Integer, String>> entryList = new ArrayList<Map.Entry<Integer, String>>(linkedmap.entrySet());
        return entryList.get(entryList.size() - 1).getValue();

    public static String FindLasstEntryWithArrayMethod() {
        return String.valueOf(linkedmap.entrySet().toArray()[linkedmap.size() - 1]);

Here is the output with performance of each method

FindLasstEntryWithArrayListMethod : took 0.162 milliseconds
FindLasstEntryWithArrayMethod : took 0.025 milliseconds
FindLasstEntryWithReduceMethod : took 2.776 milliseconds
FindLasstEntryWithSkipFunctionMethod : took 3.396 milliseconds
FindLasstEntryWithGuavaIterable : took 11 milliseconds