Programs & Examples On #Executable path

How to simulate a button click using code?

Just to clarify what moonlightcheese stated: To trigger a button click event through code in Android provide the following:

buttonName.performClick();

docker mounting volumes on host

Let me add my own answer, because I believe the others are missing the point of Docker.

Using VOLUME in the Dockerfile is the Right Way™, because you let Docker know that a certain directory contains permanent data. Docker will create a volume for that data and never delete it, even if you remove all the containers that use it.

It also bypasses the union file system, so that the volume is in fact an actual directory that gets mounted (read-write or readonly) in the right place in all the containers that share it.

Now, in order to access that data from the host, you only need to inspect your container:

# docker inspect myapp
[{
    .
    .
    .
    "Volumes": {
        "/var/www": "/var/lib/docker/vfs/dir/b3ef4bc28fb39034dd7a3aab00e086e6...",
        "/var/cache/nginx": "/var/lib/docker/vfs/dir/62499e6b31cb3f7f59bf00d8a16b48d2...",
        "/var/log/nginx": "/var/lib/docker/vfs/dir/71896ce364ef919592f4e99c6e22ce87..."
    },
    "VolumesRW": {
        "/var/www": false,
        "/var/cache/nginx": true,
        "/var/log/nginx": true
    }
}]

What I usually do is make symlinks in some standard place such as /srv, so that I can easily access the volumes and manage the data they contain (only for the volumes you care about):

ln -s /var/lib/docker/vfs/dir/b3ef4bc28fb39034dd7a3aab00e086e6... /srv/myapp-www
ln -s /var/lib/docker/vfs/dir/71896ce364ef919592f4e99c6e22ce87... /srv/myapp-log

How to force C# .net app to run only one instance in Windows?

This is what I use in my application:

static void Main()
{
  bool mutexCreated = false;
  System.Threading.Mutex mutex = new System.Threading.Mutex( true, @"Local\slimCODE.slimKEYS.exe", out mutexCreated );

  if( !mutexCreated )
  {
    if( MessageBox.Show(
      "slimKEYS is already running. Hotkeys cannot be shared between different instances. Are you sure you wish to run this second instance?",
      "slimKEYS already running",
      MessageBoxButtons.YesNo,
      MessageBoxIcon.Question ) != DialogResult.Yes )
    {
      mutex.Close();
      return;
    }
  }

  // The usual stuff with Application.Run()

  mutex.Close();
}

Create list of object from another using Java 8 Streams

If you want to iterate over a list and create a new list with "transformed" objects, you should use the map() function of stream + collect(). In the following example I find all people with the last name "l1" and each person I'm "mapping" to a new Employee instance.

public class Test {

    public static void main(String[] args) {
        List<Person> persons = Arrays.asList(
                new Person("e1", "l1"),
                new Person("e2", "l1"),
                new Person("e3", "l2"),
                new Person("e4", "l2")
        );

        List<Employee> employees = persons.stream()
                .filter(p -> p.getLastName().equals("l1"))
                .map(p -> new Employee(p.getName(), p.getLastName(), 1000))
                .collect(Collectors.toList());

        System.out.println(employees);
    }

}

class Person {

    private String name;
    private String lastName;

    public Person(String name, String lastName) {
        this.name = name;
        this.lastName = lastName;
    }

    // Getter & Setter
}

class Employee extends Person {

    private double salary;

    public Employee(String name, String lastName, double salary) {
        super(name, lastName);
        this.salary = salary;
    }

    // Getter & Setter
}

Oracle: SQL query to find all the triggers belonging to the tables?

The following will work independent of your database privileges:

select * from all_triggers
where table_name = 'YOUR_TABLE'

The following alternate options may or may not work depending on your assigned database privileges:

select * from DBA_TRIGGERS

or

select * from USER_TRIGGERS

Update elements in a JSONObject

Generic way to update the any JSONObjet with new values.

private static void updateJsonValues(JsonObject jsonObj) {
    for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {
        JsonElement element = entry.getValue();
        if (element.isJsonArray()) {
            parseJsonArray(element.getAsJsonArray());
        } else if (element.isJsonObject()) {
            updateJsonValues(element.getAsJsonObject());
        } else if (element.isJsonPrimitive()) {
            jsonObj.addProperty(entry.getKey(), "<provide new value>");
        }

    }
}

private static void parseJsonArray(JsonArray asJsonArray) {
    for (int index = 0; index < asJsonArray.size(); index++) {
        JsonElement element = asJsonArray.get(index);
        if (element.isJsonArray()) {
            parseJsonArray(element.getAsJsonArray());
        } else if (element.isJsonObject()) {
            updateJsonValues(element.getAsJsonObject());
        }

    }
}

Opacity of div's background without affecting contained element in IE 8?

It affects the whole child divs when you use the opacity feature with positions other than absolute. So another way to achieve it not to put divs inside each other and then use the position absolute for the divs. Dont use any background color for the upper div.

OWIN Security - How to Implement OAuth2 Refresh Tokens

I don't think that you should be using an array to maintain tokens. Neither you need a guid as a token.

You can easily use context.SerializeTicket().

See my below code.

public class RefreshTokenProvider : IAuthenticationTokenProvider
{
    public async Task CreateAsync(AuthenticationTokenCreateContext context)
    {
        Create(context);
    }

    public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
    {
        Receive(context);
    }

    public void Create(AuthenticationTokenCreateContext context)
    {
        object inputs;
        context.OwinContext.Environment.TryGetValue("Microsoft.Owin.Form#collection", out inputs);

        var grantType = ((FormCollection)inputs)?.GetValues("grant_type");

        var grant = grantType.FirstOrDefault();

        if (grant == null || grant.Equals("refresh_token")) return;

        context.Ticket.Properties.ExpiresUtc = DateTime.UtcNow.AddDays(Constants.RefreshTokenExpiryInDays);

        context.SetToken(context.SerializeTicket());
    }

    public void Receive(AuthenticationTokenReceiveContext context)
    {
        context.DeserializeTicket(context.Token);

        if (context.Ticket == null)
        {
            context.Response.StatusCode = 400;
            context.Response.ContentType = "application/json";
            context.Response.ReasonPhrase = "invalid token";
            return;
        }

        if (context.Ticket.Properties.ExpiresUtc <= DateTime.UtcNow)
        {
            context.Response.StatusCode = 401;
            context.Response.ContentType = "application/json";
            context.Response.ReasonPhrase = "unauthorized";
            return;
        }

        context.Ticket.Properties.ExpiresUtc = DateTime.UtcNow.AddDays(Constants.RefreshTokenExpiryInDays);
        context.SetTicket(context.Ticket);
    }
}

How do I monitor the computer's CPU, memory, and disk usage in Java?

The following supposedly gets you CPU and RAM. See ManagementFactory for more details.

import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

private static void printUsage() {
  OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
  for (Method method : operatingSystemMXBean.getClass().getDeclaredMethods()) {
    method.setAccessible(true);
    if (method.getName().startsWith("get")
        && Modifier.isPublic(method.getModifiers())) {
            Object value;
        try {
            value = method.invoke(operatingSystemMXBean);
        } catch (Exception e) {
            value = e;
        } // try
        System.out.println(method.getName() + " = " + value);
    } // if
  } // for
}

What's the best free C++ profiler for Windows?

You can use EmbeddedProfiler, it's free for both Linux and Windwos.

The profiler is intrusive (by functionality) but it doens't require any code modifications. Just add a specific compiler flag (-finstrument-functios for gcc/MinGW or /GH for MSVC) and link the profiler's library. It can provide you a full call tree or just a funciton list. It has it's own analyzer GUI.

How to extract text from a PDF file?

Look at this code:

import PyPDF2
pdf_file = open('sample.pdf', 'rb')
read_pdf = PyPDF2.PdfFileReader(pdf_file)
number_of_pages = read_pdf.getNumPages()
page = read_pdf.getPage(0)
page_content = page.extractText()
print page_content.encode('utf-8')

The output is:

!"#$%#$%&%$&'()*%+,-%./01'*23%4
5'%1$#26%3/%7/))/8%&)/26%8#3"%3"*%313/9#&)
%

Using the same code to read a pdf from 201308FCR.pdf .The output is normal.

Its documentation explains why:

def extractText(self):
    """
    Locate all text drawing commands, in the order they are provided in the
    content stream, and extract the text.  This works well for some PDF
    files, but poorly for others, depending on the generator used.  This will
    be refined in the future.  Do not rely on the order of text coming out of
    this function, as it will change if this function is made more
    sophisticated.
    :return: a unicode string object.
    """

How to find the Git commit that introduced a string in any branch?

While this doesn't directly answer you question, I think it might be a good solution for you in the future. I saw a part of my code, which was bad. Didn't know who wrote it or when. I could see all changes from the file, but it was clear that the code had been moved from some other file to this one. I wanted to find who actually added it in the first place.

To do this, I used Git bisect, which quickly let me find the sinner.

I ran git bisect start and then git bisect bad, because the revision checked out had the issue. Since I didn't know when the problem occured, I targetted the first commit for the "good", git bisect good <initial sha>.

Then I just kept searching the repo for the bad code. When I found it, I ran git bisect bad, and when it wasn't there: git bisect good.

In ~11 steps, I had covered ~1000 commits and found the exact commit, where the issue was introduced. Pretty great.

Getting visitors country from their IP

Try this simple one line code, You will get country and city of visitors from their ip remote address.

$tags = get_meta_tags('http://www.geobytes.com/IpLocator.htm?GetLocation&template=php3.txt&IpAddress=' . $_SERVER['REMOTE_ADDR']);
echo $tags['country'];
echo $tags['city'];

Maven and Spring Boot - non resolvable parent pom - repo.spring.io (Unknown host)

If all above stuffs not works. try this. If you are using IntelliJ. Check below setting: enter image description here

May be ~/.m2/settings.xml is restricting to connect to internet.

How to use CMAKE_INSTALL_PREFIX

There are two ways to use this variable:

  • passing it as a command line argument just like Job mentioned:

    cmake -DCMAKE_INSTALL_PREFIX=< install_path > ..

  • assigning value to it in CMakeLists.txt:

    SET(CMAKE_INSTALL_PREFIX < install_path >)

    But do remember to place it BEFORE PROJECT(< project_name>) command, otherwise it will not work!

PHP call Class method / function

As th function is not using $this at all, you can add a static keyword just after public and then call

Functions::filter($_GET['params']);

Avoiding the creation of an object just for one method call

What is the difference between resource and endpoint?

Possibly mine isn't a great answer but here goes.

Since working more with truly RESTful web services over HTTP, I've tried to steer people away from using the term endpoint since it has no clear definition, and instead use the language of REST which is resources and resource locations.

To my mind, endpoint is a TCP term. It's conflated with HTTP because part of the URL identifies a listening server.

So resource isn't a newer term, I don't think, I think endpoint was always misappropriated and we're realising that as we're getting our heads around REST as a style of API.

Edit

I blogged about this.

https://medium.com/@lukepuplett/stop-saying-endpoints-92c19e33e819

How to cast or convert an unsigned int to int in C?

Unsigned int can be converted to signed (or vice-versa) by simple expression as shown below :

unsigned int z;
int y=5;
z= (unsigned int)y;   

Though not targeted to the question, you would like to read following links :

C# Dictionary get item by index

Is it useful to look beyond the exact question asked to alternatives that might better suit the need? Create your own class or struct, then make an array of those to operate on instead of being stuck with the operation of the KeyValuePair collection behavior of the Dictionary type.

Using a struct instead of a class will allow equality comparison of two different cards without implementing your own comparison code.

public struct Card
{
  public string Name;
  public int Value;

}

private int random()
{
  // Whatever
  return 1;
}

private static Card[] Cards = new Card[]
{
    new Card() { Name = "7", Value = 7 },
    new Card() { Name = "8", Value = 8 },
    new Card() { Name = "9", Value = 9 },
    new Card() { Name = "10", Value = 10 },
    new Card() { Name = "J", Value = 1 },
    new Card() { Name = "Q", Value = 1 },
    new Card() { Name = "K", Value = 1 },
    new Card() { Name = "A", Value = 1 }
};

private void CardDemo()
{
  int value, maxVal;
  string name;
  Card card, card2;
  List<Card> lowCards;

  value = Cards[random()].Value;
  name = Cards[random()].Name;
  card = Cards[random()];
  card2 = Cards[1];
  // card.Equals(card2) returns true
  lowCards = Cards.Where(x => x.Value == 1).ToList();
  maxVal = Cards.Max(x => x.Value);

}

writing to existing workbook using xlwt

You need xlutils.copy. Try something like this:

from xlutils.copy import copy
w = copy('book1.xls')
w.get_sheet(0).write(0,0,"foo")
w.save('book2.xls')

Keep in mind you can't overwrite cells by default as noted in this question.

Is there any sed like utility for cmd.exe?

sed (and its ilk) are contained within several packages of Unix commands.

If you don't want to install anything and your system ain't a Windows Server one, then you could use a scripting language (VBScript e.g.) for that. Below is a gross, off-the-cuff stab at it. Your command line would look like

cscript //NoLogo sed.vbs s/(oldpat)/(newpat)/ < inpfile.txt > outfile.txt

where oldpat and newpat are Microsoft vbscript regex patterns. Obviously I've only implemented the substitute command and assumed some things, but you could flesh it out to be smarter and understand more of the sed command-line.

Dim pat, patparts, rxp, inp
pat = WScript.Arguments(0)
patparts = Split(pat,"/")
Set rxp = new RegExp
rxp.Global = True
rxp.Multiline = False
rxp.Pattern = patparts(1)
Do While Not WScript.StdIn.AtEndOfStream
  inp = WScript.StdIn.ReadLine()
  WScript.Echo rxp.Replace(inp, patparts(2))
Loop

How to add Google Maps Autocomplete search box?

A significant portion of this code can be eliminated.

HTML excerpt:

<head>
  ...
  <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
  ...
</head>
<body>
  ...
  <input id="searchTextField" type="text" size="50">
  ...
</body>

Javascript:

function initialize() {
  var input = document.getElementById('searchTextField');
  new google.maps.places.Autocomplete(input);
}

google.maps.event.addDomListener(window, 'load', initialize);

Division in Python 2.7. and 3.3

In python 2.7, the / operator is integer division if inputs are integers.

If you want float division (which is something I always prefer), just use this special import:

from __future__ import division

See it here:

>>> 7 / 2
3
>>> from __future__ import division
>>> 7 / 2
3.5
>>>

Integer division is achieved by using //, and modulo by using %

>>> 7 % 2
1
>>> 7 // 2
3
>>>

EDIT

As commented by user2357112, this import has to be done before any other normal import.

Deserialize JSON array(or list) in C#

This code works for me:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;

namespace Json
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(DeserializeNames());
            Console.ReadLine();
        }

        public static string DeserializeNames()
        {
            var jsonData = "{\"name\":[{\"last\":\"Smith\"},{\"last\":\"Doe\"}]}";

            JavaScriptSerializer ser = new JavaScriptSerializer();

            nameList myNames = ser.Deserialize<nameList>(jsonData);

            return ser.Serialize(myNames);
        }

        //Class descriptions

        public class name
        {
            public string last { get; set; }
        }

        public class nameList
        {
            public List<name> name { get; set; }
        }
    }
}

Text in HTML Field to disappear when clicked?

This is as simple I think the solution that should solve all your problems:

<input name="myvalue" id="valueText" type="text" value="ENTER VALUE">

This is your submit button:

<input type="submit" id= "submitBtn" value="Submit">

then put this small jQuery in a js file:

//this will submit only if the value is not default
$("#submitBtn").click(function () {
    if ($("#valueText").val() === "ENTER VALUE")
    {
        alert("please insert a valid value");
        return false;
    }
});

//this will put default value if the field is empty
$("#valueText").blur(function () {
    if(this.value == ''){ 
        this.value = 'ENTER VALUE';
    }
}); 

 //this will empty the field is the value is the default one
 $("#valueText").focus(function () {
    if (this.value == 'ENTER VALUE') {
        this.value = ''; 
    }
});

And it works also in older browsers. Plus it can easily be converted to normal javascript if you need.

How to select last child element in jQuery?

Hi all Please try this property

$( "p span" ).last().addClass( "highlight" );

Thanks

Script parameters in Bash

Use the variables "$1", "$2", "$3" and so on to access arguments. To access all of them you can use "$@", or to get the count of arguments $# (might be useful to check for too few or too many arguments).

What are the differences between "=" and "<-" assignment operators in R?

According to John Chambers, the operator = is only allowed at "the top level," which means it is not allowed in control structures like if, making the following programming error illegal.

> if(x = 0) 1 else x
Error: syntax error

As he writes, "Disallowing the new assignment form [=] in control expressions avoids programming errors (such as the example above) that are more likely with the equal operator than with other S assignments."

You can manage to do this if it's "isolated from surrounding logical structure, by braces or an extra pair of parentheses," so if ((x = 0)) 1 else x would work.

See http://developer.r-project.org/equalAssign.html

Run ScrollTop with offset of element by ID

var top = ($(".apps_intro_wrapper_inner").offset() || { "top": NaN }).top;   
if (!isNaN(top)) {
$("#app_scroler").click(function () {   
$('html, body').animate({
            scrollTop: top
        }, 100);
    });
}

if you want to scroll a little above or below from specific div that add value to the top like this.....like I add 800

var top = ($(".apps_intro_wrapper_inner").offset() || { "top": NaN }).top + 800;

Why does typeof array with objects return "object" and not "array"?

Quoting the spec

15.4 Array Objects

Array objects give special treatment to a certain class of property names. A property name P (in the form of a String value) is an array index if and only if ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal to 2^32-1. A property whose property name is an array index is also called an element. Every Array object has a length property whose value is always a nonnegative integer less than 2^32. The value of the length property is numerically greater than the name of every property whose name is an array index; whenever a property of an Array object is created or changed, other properties are adjusted as necessary to maintain this invariant. Specifically, whenever a property is added whose name is an array index, the length property is changed, if necessary, to be one more than the numeric value of that array index; and whenever the length property is changed, every property whose name is an array index whose value is not smaller than the new length is automatically deleted. This constraint applies only to own properties of an Array object and is unaffected by length or array index properties that may be inherited from its prototypes.

And here's a table for typeof

enter image description here


To add some background, there are two data types in JavaScript:

  1. Primitive Data types - This includes null, undefined, string, boolean, number and object.
  2. Derived data types/Special Objects - These include functions, arrays and regular expressions. And yes, these are all derived from "Object" in JavaScript.

An object in JavaScript is similar in structure to the associative array/dictionary seen in most object oriented languages - i.e., it has a set of key-value pairs.

An array can be considered to be an object with the following properties/keys:

  1. Length - This can be 0 or above (non-negative).
  2. The array indices. By this, I mean "0", "1", "2", etc are all properties of array object.

Hope this helped shed more light on why typeof Array returns an object. Cheers!

Docker how to change repository name or rename image?

The accepted answer is great for single renames, but here is a way to rename multiple images that have the same repository all at once (and remove the old images).

If you have old images of the form:

$ docker images
REPOSITORY               TAG                 IMAGE ID            CREATED             SIZE
old_name/image_name_1    latest              abcdefghijk1        5 minutes ago      1.00GB
old_name/image_name_2    latest              abcdefghijk2        5 minutes ago      1.00GB

And you want:

new_name/image_name_1
new_name/image_name_2

Then you can use this (subbing in OLD_REPONAME, NEW_REPONAME, and TAG as appropriate):

OLD_REPONAME='old_name'
NEW_REPONAME='new_name'
TAG='latest'

# extract image name, e.g. "old_name/image_name_1"
for image in $(docker images | awk '{ if( FNR>1 ) { print $1 } }' | grep $OLD_REPONAME)
do \
  OLD_NAME="${image}:${TAG}" && \
  NEW_NAME="${NEW_REPONAME}${image:${#OLD_REPONAME}:${#image}}:${TAG}" && \
  docker image tag $OLD_NAME $NEW_NAME && \
  docker rmi $image:${TAG}  # omit this line if you want to keep the old image
done

How to have Ellipsis effect on Text

<Text ellipsizeMode='tail' numberOfLines={2} style={{width:100}}>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam at cursus 
</Text>

Result: Lorem ipsum...

What's a clean way to stop mongod on Mac OS X?

If you installed mongodb with homebrew, there's an easier way:

List mongo job with launchctl:

launchctl list | grep mongo

Stop mongo job:

launchctl stop <job label>

(For me this is launchctl stop homebrew.mxcl.mongodb)

Start mongo job:

launchctl start <job label>

how does multiplication differ for NumPy Matrix vs Array classes?

Reference from http://docs.scipy.org/doc/scipy/reference/tutorial/linalg.html

..., the use of the numpy.matrix class is discouraged, since it adds nothing that cannot be accomplished with 2D numpy.ndarray objects, and may lead to a confusion of which class is being used. For example,

>>> import numpy as np
>>> from scipy import linalg
>>> A = np.array([[1,2],[3,4]])
>>> A
    array([[1, 2],
           [3, 4]])
>>> linalg.inv(A)
array([[-2. ,  1. ],
      [ 1.5, -0.5]])
>>> b = np.array([[5,6]]) #2D array
>>> b
array([[5, 6]])
>>> b.T
array([[5],
      [6]])
>>> A*b #not matrix multiplication!
array([[ 5, 12],
      [15, 24]])
>>> A.dot(b.T) #matrix multiplication
array([[17],
      [39]])
>>> b = np.array([5,6]) #1D array
>>> b
array([5, 6])
>>> b.T  #not matrix transpose!
array([5, 6])
>>> A.dot(b)  #does not matter for multiplication
array([17, 39])

scipy.linalg operations can be applied equally to numpy.matrix or to 2D numpy.ndarray objects.

Should I use px or rem value units in my CSS?

Yes, REM and PX are relative yet other answers have suggested to go for REM over PX, I would also like to back this up using an accessibility example.
When user sets different font-size on browser, REM automatically scale up and down elements like fonts, images etc on the webpage which is not the case with PX.


In the below gif left side text is set using font size REM unit while right side font is set by PX unit.

enter image description here

As you can see that REM is scaling up/down automatically when I resize the default font-size of webpage.(bottom-right side)

Default font-size of a webpage is 16px which is equal to 1 rem (only for default html page i.e. html{font-size:100%}), so, 1.25rem is equal to 20px.

P.S: who else is using REM? CSS Frameworks! like Bootstrap 4, Bulma CSS etc, so better get along with it.

How do I filter ForeignKey choices in a Django ModelForm?

So, I've really tried to understand this, but it seems that Django still doesn't make this very straightforward. I'm not all that dumb, but I just can't see any (somewhat) simple solution.

I find it generally pretty ugly to have to override the Admin views for this sort of thing, and every example I find never fully applies to the Admin views.

This is such a common circumstance with the models I make that I find it appalling that there's no obvious solution to this...

I've got these classes:

# models.py
class Company(models.Model):
    # ...
class Contract(models.Model):
    company = models.ForeignKey(Company)
    locations = models.ManyToManyField('Location')
class Location(models.Model):
    company = models.ForeignKey(Company)

This creates a problem when setting up the Admin for Company, because it has inlines for both Contract and Location, and Contract's m2m options for Location are not properly filtered according to the Company that you're currently editing.

In short, I would need some admin option to do something like this:

# admin.py
class LocationInline(admin.TabularInline):
    model = Location
class ContractInline(admin.TabularInline):
    model = Contract
class CompanyAdmin(admin.ModelAdmin):
    inlines = (ContractInline, LocationInline)
    inline_filter = dict(Location__company='self')

Ultimately I wouldn't care if the filtering process was placed on the base CompanyAdmin, or if it was placed on the ContractInline. (Placing it on the inline makes more sense, but it makes it hard to reference the base Contract as 'self'.)

Is there anyone out there who knows of something as straightforward as this badly needed shortcut? Back when I made PHP admins for this sort of thing, this was considered basic functionality! In fact, it was always automatic, and had to be disabled if you really didn't want it!

Read all contacts' phone numbers in android

Load contacts in background using CursorLoader:

  CursorLoader cursor = new CursorLoader(this, ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
            Cursor managedCursor = cursor.loadInBackground();

            int number = managedCursor.getColumnIndex(ContactsContract.Contacts.Data.DATA1);
            int name = managedCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
            int index = 0;
            while (managedCursor.moveToNext()) {
                String phNumber = managedCursor.getString(number);
                String phName = managedCursor.getString(name);
            }

View more than one project/solution in Visual Studio

You can have multiple projects in one instance of Visual Studio. The point of a VS solution is to bring together all the projects you want to work with in one place, so you can't have multiple solutions in one instance. You'd have to open each solution separately.

Please explain about insertable=false and updatable=false in reference to the JPA @Column annotation

Defining insertable=false, updatable=false is useful when you need to map a field more than once in an entity, typically:

This is IMO not a semantical thing, but definitely a technical one.

reading and parsing a TSV file, then manipulating it for saving as CSV (*efficiently*)

You should use the csv module to read the tab-separated value file. Do not read it into memory in one go. Each row you read has all the information you need to write rows to the output CSV file, after all. Keep the output file open throughout.

import csv

with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
    tsvin = csv.reader(tsvin, delimiter='\t')
    csvout = csv.writer(csvout)

    for row in tsvin:
        count = int(row[4])
        if count > 0:
            csvout.writerows([row[2:4] for _ in range(count)])

or, using the itertools module to do the repeating with itertools.repeat():

from itertools import repeat
import csv

with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
    tsvin = csv.reader(tsvin, delimiter='\t')
    csvout = csv.writer(csvout)

    for row in tsvin:
        count = int(row[4])
        if count > 0:
            csvout.writerows(repeat(row[2:4], count))

Possible to perform cross-database queries with PostgreSQL?

I have checked and tried to create a foreign key relationships between 2 tables in 2 different databases using both dblink and postgres_fdw but with no result.

Having read the other peoples feedback on this, for example here and here and in some other sources it looks like there is no way to do that currently:

The dblink and postgres_fdw indeed enable one to connect to and query tables in other databases, which is not possible with the standard Postgres, but they do not allow to establish foreign key relationships between tables in different databases.

How to return only the Date from a SQL Server DateTime datatype

select convert(getdate() as date)

select CONVERT(datetime,CONVERT(date, getdate()))

PHPExcel How to apply styles and set cell width and cell height to cell generated dynamically

You can use

$objWorksheet->getActiveSheet()->getRowDimension('1')->setRowHeight(40);
$objWorksheet->getActiveSheet()->getColumnDimension('A')->setWidth(100);

or define auto-size:

$objWorksheet->getRowDimension('1')->setRowHeight(-1);

How to check if internet connection is present in Java?

1) Figure out where your application needs to be connecting to.

2) Set up a worker process to check InetAddress.isReachable to monitor the connection to that address.

base_url() function not working in codeigniter

I think you haven't edited codeigniter files to enable base_url(). you try to assign it in url_helper.php you also can do the same config/autoload.php file. you can add this code in your autoload.php

$autoload['helper'] = array('url');

Than You will be able to ue base_url() like this

<link rel="stylesheet" href="<?php echo base_url();?>/css/template/default.css" type="text/css" />

Creating a "logical exclusive or" operator in Java

Logical exclusive-or in Java is called !=. You can also use ^ if you want to confuse your friends.

PHP mPDF save file as PDF

The mPDF docs state that the first argument of Output() is the file path, second is the saving mode - you need to set it to 'F'.

$mpdf->Output('filename.pdf','F');

Missing Microsoft RDLC Report Designer in Visual Studio

In addition to previous answers, here is a link to the latest SQL Server Data Tools. Note that the download link for Visual Studio 2015 is broken. ISO is available from here, links at the bottom of the page:

https://msdn.microsoft.com/en-us/library/mt204009.aspx

MSDN Subscriber Downloads do not list the VS 2015 compatible version at the time of writing.

However, even with the latest tools (February 2015), I can't open previous version of .rptproj files.

Why do we have to override the equals() method in Java?

To answer your question, firstly I would strongly recommend looking at the Documentation.

Without overriding the equals() method, it will act like "==". When you use the "==" operator on objects, it simply checks to see if those pointers refer to the same object. Not if their members contain the same value.

We override to keep our code clean, and abstract the comparison logic from the If statement, into the object. This is considered good practice and takes advantage of Java's heavily Object Oriented Approach.

Convert 4 bytes to int

You can also use BigInteger for variable length bytes. You can convert it to Long, Integer or Short, whichever suits your needs.

new BigInteger(bytes).intValue();

or to denote polarity:

new BigInteger(1, bytes).intValue();

How to check how many letters are in a string in java?

A)

String str = "a string";
int length = str.length( ); // length == 8

http://download.oracle.com/javase/7/docs/api/java/lang/String.html#length%28%29

edit

If you want to count the number of a specific type of characters in a String, then a simple method is to iterate through the String checking each index against your test case.

int charCount = 0;
char temp;

for( int i = 0; i < str.length( ); i++ )
{
    temp = str.charAt( i );

    if( temp.TestCase )
        charCount++;
}

where TestCase can be isLetter( ), isDigit( ), etc.

Or if you just want to count everything but spaces, then do a check in the if like temp != ' '

B)

String str = "a string";
char atPos0 = str.charAt( 0 ); // atPos0 == 'a'

http://download.oracle.com/javase/7/docs/api/java/lang/String.html#charAt%28int%29

Where is the documentation for the values() method of Enum?

The method is implicitly defined (i.e. generated by the compiler).

From the JLS:

In addition, if E is the name of an enum type, then that type has the following implicitly declared static methods:

/**
* Returns an array containing the constants of this enum 
* type, in the order they're declared.  This method may be
* used to iterate over the constants as follows:
*
*    for(E c : E.values())
*        System.out.println(c);
*
* @return an array containing the constants of this enum 
* type, in the order they're declared
*/
public static E[] values();

/**
* Returns the enum constant of this type with the specified
* name.
* The string must match exactly an identifier used to declare
* an enum constant in this type.  (Extraneous whitespace 
* characters are not permitted.)
* 
* @return the enum constant with the specified name
* @throws IllegalArgumentException if this enum type has no
* constant with the specified name
*/
public static E valueOf(String name);

JQuery select2 set default value from an option in list?

If you are using an array data source you can do something like below -

$(".select").select2({
    data: data_names
});
data_names.forEach(function(name) {
    if (name.selected) {
        $(".select").select2('val', name.id);
    }
});

This assumes that out of your data set the one item which you want to set as default has an additional attribute called selected and we use that to set the value.

The forked VM terminated without saying properly goodbye. VM crash or System.exit called

I experienced this error after a static member variable in my test class called a method to create an object (which was used in test cases throughout the class), and the method caused an exception.

// Object created inside test class by calling a static getter.
// Exception thrown in getter:
private static Object someObject = SomeObject.getObject(...);

// ... <Object later used in class>

Some fixes include recreating the object inside each test case and catching any exceptions accordingly. Or by initializing the object inside an @BeforeTest method and ensuring that it is built properly.

Generating Random Number In Each Row In Oracle Query

If you just use round then the two end numbers (1 and 9) will occur less frequently, to get an even distribution of integers between 1 and 9 then:

SELECT MOD(Round(DBMS_RANDOM.Value(1, 99)), 9) + 1 FROM DUAL

How to check postgres user and password?

You may change the pg_hba.conf and then reload the postgresql. something in the pg_hba.conf may be like below:

# "local" is for Unix domain socket connections only
local   all             all                                     trust
# IPv4 local connections:
host    all             all             127.0.0.1/32            trust

then you change your user to postgresql, you may login successfully.

su postgresql

How to load a model from an HDF5 file in Keras?

I done in this way

from keras.models import Sequential
from keras_contrib.losses import import crf_loss
from keras_contrib.metrics import crf_viterbi_accuracy

# To save model
model.save('my_model_01.hdf5')

# To load the model
custom_objects={'CRF': CRF,'crf_loss': crf_loss,'crf_viterbi_accuracy':crf_viterbi_accuracy}

# To load a persisted model that uses the CRF layer 
model1 = load_model("/home/abc/my_model_01.hdf5", custom_objects = custom_objects)

Should I use `import os.path` or `import os`?

os.path works in a funny way. It looks like os should be a package with a submodule path, but in reality os is a normal module that does magic with sys.modules to inject os.path. Here's what happens:

  • When Python starts up, it loads a bunch of modules into sys.modules. They aren't bound to any names in your script, but you can access the already-created modules when you import them in some way.

    • sys.modules is a dict in which modules are cached. When you import a module, if it already has been imported somewhere, it gets the instance stored in sys.modules.
  • os is among the modules that are loaded when Python starts up. It assigns its path attribute to an os-specific path module.

  • It injects sys.modules['os.path'] = path so that you're able to do "import os.path" as though it was a submodule.

I tend to think of os.path as a module I want to use rather than a thing in the os module, so even though it's not really a submodule of a package called os, I import it sort of like it is one and I always do import os.path. This is consistent with how os.path is documented.


Incidentally, this sort of structure leads to a lot of Python programmers' early confusion about modules and packages and code organization, I think. This is really for two reasons

  1. If you think of os as a package and know that you can do import os and have access to the submodule os.path, you may be surprised later when you can't do import twisted and automatically access twisted.spread without importing it.

  2. It is confusing that os.name is a normal thing, a string, and os.path is a module. I always structure my packages with empty __init__.py files so that at the same level I always have one type of thing: a module/package or other stuff. Several big Python projects take this approach, which tends to make more structured code.

Dropping a connected user from an Oracle 10g database schema

my proposal is this simple anonymous block:

DECLARE
   lc_username   VARCHAR2 (32) := 'user-name-to-kill-here';
BEGIN
   FOR ln_cur IN (SELECT sid, serial# FROM v$session WHERE username = lc_username)
   LOOP
      EXECUTE IMMEDIATE ('ALTER SYSTEM KILL SESSION ''' || ln_cur.sid || ',' || ln_cur.serial# || ''' IMMEDIATE');
   END LOOP;
END;
/

ERROR Error: No value accessor for form control with unspecified name attribute on switch

Have you tried moving your [(ngModel)] to the div instead of the switch in your HTML? I had the same error appear in my code and it was because I bound the model to a <mat-option> instead of a <mat-select>. Though I am not using form control.

How to get current timestamp in string format in Java? "yyyy.MM.dd.HH.mm.ss"

Use java.util.Date class instead of Timestamp.

String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());

This will get you the current date in the format specified.

CSS word-wrapping in div

It's pretty hard to say definitively without seeing what the rendered html looks like and what styles are being applied to the elements within the treeview div, but the thing that jumps out at me right away is the

overflow-x: scroll;

What happens if you remove that?

remove all variables except functions

Here's a pretty convenient function I picked up somewhere and adjusted a little. Might be nice to keep in the directory.

list.objects <- function(env = .GlobalEnv) 
{
    if(!is.environment(env)){
        env <- deparse(substitute(env))
        stop(sprintf('"%s" must be an environment', env))
    }
    obj.type <- function(x) class(get(x, envir = env))
    foo <- sapply(ls(envir = env), obj.type)
    object.name <- names(foo)
    names(foo) <- seq(length(foo))
    dd <- data.frame(CLASS = foo, OBJECT = object.name, 
                     stringsAsFactors = FALSE)
    dd[order(dd$CLASS),]
}

> x <- 1:5
> d <- data.frame(x)
> list.objects()
#        CLASS       OBJECT
# 1 data.frame            d
# 2   function list.objects
# 3    integer            x 
> list.objects(env = x)
# Error in list.objects(env = x) : "x" must be an environment

How can I convert a series of images to a PDF from the command line on linux?

Use convert from http://www.imagemagick.org. (Readily supplied as a package in most Linux distributions.)

Execute a SQL Stored Procedure and process the results

My Stored Procedure Requires 2 Parameters and I needed my function to return a datatable here is 100% working code

Please make sure that your procedure return some rows

Public Shared Function Get_BillDetails(AccountNumber As String) As DataTable
    Try
        Connection.Connect()
        debug.print("Look up account number " & AccountNumber)
        Dim DP As New SqlDataAdapter("EXEC SP_GET_ACCOUNT_PAYABLES_GROUP  '" & AccountNumber & "' , '" & 08/28/2013 &"'", connection.Con)
        Dim DST As New DataSet
        DP.Fill(DST)
        Return DST.Tables(0)      
    Catch ex As Exception
        Return Nothing
    End Try
End Function

Linq UNION query to select two elements

EDIT:

Ok I found why the int.ToString() in LINQtoEF fails, please read this post: Problem with converting int to string in Linq to entities

This works on my side :

        List<string> materialTypes = (from u in result.Users
                                      select u.LastName)
                       .Union(from u in result.Users
                               select SqlFunctions.StringConvert((double) u.UserId)).ToList();

On yours it should be like this:

    IList<String> materialTypes = ((from tom in context.MaterialTypes
                                       where tom.IsActive == true
                                       select tom.Name)
                                       .Union(from tom in context.MaterialTypes
                                       where tom.IsActive == true
                                       select SqlFunctions.StringConvert((double)tom.ID))).ToList();

Thanks, i've learnt something today :)

Hibernate: flush() and commit()

One common case for explicitly flushing is when you create a new persistent entity and you want it to have an artificial primary key generated and assigned to it, so that you can use it later on in the same transaction. In that case calling flush would result in your entity being given an id.

Another case is if there are a lot of things in the 1st-level cache and you'd like to clear it out periodically (in order to reduce the amount of memory used by the cache) but you still want to commit the whole thing together. This is the case that Aleksei's answer covers.

How do you check what version of SQL Server for a database using TSQL?

There is another extended Stored Procedure which can be used to see the Version info:

exec [master].sys.[xp_msver]

Creating an XmlNode/XmlElement in C# without an XmlDocument?

Why not consider creating your data class(es) as just a subclassed XmlDocument, then you get all of that for free. You don't need to serialize or create any off-doc nodes at all, and you get structure you want.

If you want to make it more sophisticated, write a base class that is a subclass of XmlDocument, then give it basic accessors, and you're set.

Here's a generic type I put together for a project...

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.IO;

namespace FWFWLib {
    public abstract class ContainerDoc : XmlDocument {

        protected XmlElement root = null;
        protected const string XPATH_BASE = "/$DATA_TYPE$";
        protected const string XPATH_SINGLE_FIELD = "/$DATA_TYPE$/$FIELD_NAME$";

        protected const string DOC_DATE_FORMAT = "yyyyMMdd";
        protected const string DOC_TIME_FORMAT = "HHmmssfff";
        protected const string DOC_DATE_TIME_FORMAT = DOC_DATE_FORMAT + DOC_TIME_FORMAT;

        protected readonly string datatypeName = "containerDoc";
        protected readonly string execid = System.Guid.NewGuid().ToString().Replace( "-", "" );

        #region startup and teardown
        public ContainerDoc( string execid, string datatypeName ) {
            root = this.DocumentElement;
            this.datatypeName = datatypeName;
            this.execid = execid;
            if( null == datatypeName || "" == datatypeName.Trim() ) {
                throw new InvalidDataException( "Data type name can not be blank" );
            }
            Init();
        }

        public ContainerDoc( string datatypeName ) {
            root = this.DocumentElement;
            this.datatypeName = datatypeName;
            if( null == datatypeName || "" == datatypeName.Trim() ) {
                throw new InvalidDataException( "Data type name can not be blank" );
            }
            Init();
        }

        private ContainerDoc() { /*...*/ }

        protected virtual void Init() {
            string basexpath = XPATH_BASE.Replace( "$DATA_TYPE$", datatypeName );
            root = (XmlElement)this.SelectSingleNode( basexpath );
            if( null == root ) {
                root = this.CreateElement( datatypeName );
                this.AppendChild( root );
            }
            SetFieldValue( "createdate", DateTime.Now.ToString( DOC_DATE_FORMAT ) );
            SetFieldValue( "createtime", DateTime.Now.ToString( DOC_TIME_FORMAT ) );
        }
        #endregion

        #region setting/getting data fields
        public virtual void SetFieldValue( string fieldname, object val ) {
            if( null == fieldname || "" == fieldname.Trim() ) {
                return;
            }
            fieldname = fieldname.Replace( " ", "_" ).ToLower();
            string xpath = XPATH_SINGLE_FIELD.Replace( "$FIELD_NAME$", fieldname ).Replace( "$DATA_TYPE$", datatypeName );
            XmlNode node = this.SelectSingleNode( xpath );
            if( null != node ) {
                if( null != val ) {
                    node.InnerText = val.ToString();
                }
            } else {
                node = this.CreateElement( fieldname );
                if( null != val ) {
                    node.InnerText = val.ToString();
                }
                root.AppendChild( node );
            }
        }

        public virtual string FieldValue( string fieldname ) {
            if( null == fieldname ) {
                fieldname = "";
            }
            fieldname = fieldname.ToLower().Trim();
            string rtn = "";
            XmlNode node = this.SelectSingleNode( XPATH_SINGLE_FIELD.Replace( "$FIELD_NAME$", fieldname ).Replace( "$DATA_TYPE$", datatypeName ) );
            if( null != node ) {
                rtn = node.InnerText;
            }
            return rtn.Trim();
        }

        public virtual string ToXml() {
            return this.OuterXml;
        }

        public override string ToString() {
            return ToXml();
        }
        #endregion

        #region io
        public void WriteTo( string filename ) {
            TextWriter tw = new StreamWriter( filename );
            tw.WriteLine( this.OuterXml );
            tw.Close();
            tw.Dispose();
        }

        public void WriteTo( Stream strm ) {
            TextWriter tw = new StreamWriter( strm );
            tw.WriteLine( this.OuterXml );
            tw.Close();
            tw.Dispose();
        }

        public void WriteTo( TextWriter writer ) {
            writer.WriteLine( this.OuterXml );
        }
        #endregion

    }
}

How do I get an animated gif to work in WPF?

Small improvement of GifImage.Initialize() method, which reads proper frame timing from GIF metadata.

    private void Initialize()
    {
        _gifDecoder = new GifBitmapDecoder(new Uri("pack://application:,,," + this.GifSource), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);

        int duration=0;
        _animation = new Int32AnimationUsingKeyFrames();
        _animation.KeyFrames.Add(new DiscreteInt32KeyFrame(0, KeyTime.FromTimeSpan(new TimeSpan(0))));
        foreach (BitmapFrame frame in _gifDecoder.Frames)
        {
            BitmapMetadata btmd = (BitmapMetadata)frame.Metadata;
            duration += (ushort)btmd.GetQuery("/grctlext/Delay");
            _animation.KeyFrames.Add(new DiscreteInt32KeyFrame(_gifDecoder.Frames.IndexOf(frame)+1, KeyTime.FromTimeSpan(new TimeSpan(duration*100000))));
        }            
         _animation.RepeatBehavior = RepeatBehavior.Forever;
        this.Source = _gifDecoder.Frames[0];            
        _isInitialized = true;
    }

Maximum length for MySQL type text

Type       | Approx. Length     | Exact Max. Length Allowed
-----------------------------------------------------------
TINYTEXT   | 256 Bytes          |           255 characters
TEXT       |  64 Kilobytes      |        65,535 characters
MEDIUMTEXT |  16 Megabytes      |    16,777,215 characters
LONGTEXT   |   4 Gigabytes      | 4,294,967,295 characters

Basically, it's like:

"Exact Max. Length Allowed" = "Approx. Length" in bytes - 1

Note: If using multibyte characters (like Arabic, where each Arabic character takes 2 bytes), the column "Exact Max. Length Allowed" for TINYTEXT can hold be up to 127 Arabic characters (Note: space, dash, underscore, and other such characters, are 1-byte characters).

What is the intended use-case for git stash?

Stash is just a convenience method. Since branches are so cheap and easy to manage in git, I personally almost always prefer creating a new temporary branch than stashing, but it's a matter of taste mostly.

The one place I do like stashing is if I discover I forgot something in my last commit and have already started working on the next one in the same branch:

# Assume the latest commit was already done
# start working on the next patch, and discovered I was missing something

# stash away the current mess I made
git stash save

# some changes in the working dir

# and now add them to the last commit:
git add -u
git commit --amend

# back to work!
git stash pop

How do I check if an HTML element is empty using jQuery?

Line breaks are considered as content to elements in FF.

<div>
</div>
<div></div>

Ex:

$("div:empty").text("Empty").css('background', '#ff0000');

In IE both divs are considered empty, in FF an Chrome only the last one is empty.

You can use the solution provided by @qwertymk

if(!/[\S]/.test($('#element').html())) { // for one element
    alert('empty');
}

or

$('.elements').each(function(){  // for many elements
    if(!/[\S]/.test($(this).html())) { 
        // is empty
    }
})

Python - Join with newline

You have to print it:

In [22]: "\n".join(['I', 'would', 'expect', 'multiple', 'lines'])
Out[22]: 'I\nwould\nexpect\nmultiple\nlines'

In [23]: print "\n".join(['I', 'would', 'expect', 'multiple', 'lines'])
I
would
expect
multiple
lines

Android: Difference between Parcelable and Serializable?

Parcelable much faster than serializable with Binder, because serializable use reflection and cause many GC. Parcelable is design to optimize to pass object.

Here's link to reference. http://www.developerphil.com/parcelable-vs-serializable/

How can I fix the Microsoft Visual Studio error: "package did not load correctly"?

  1. Find the ComponentModelCache folder
  2. Delete Microsoft.VisualStudio.Default.cache
  3. Restart Visual Studio

Enjoy using Visual Studio.

Adding 30 minutes to time formatted as H:i in PHP

Your current solution does not work because $time is a string - it needs to be a Unix timestamp. You can do this instead:

$unix_time = strtotime('January 1 2010 '.$time); // create a unix timestamp
$startTime date( "H:i", strtotime('-30 minutes', $unix_time) );
$endTime date( "H:i", strtotime('+30 minutes', $unix_time) );

Can we call the function written in one JavaScript in another JS file?

You can call the function created in another js file from the file you are working in. So for this firstly you need to add the external js file into the html document as-

<html>
<head>
    <script type="text/javascript" src='path/to/external/js'></script>
</head>
<body>
........

The function defined in the external javascript file -

$.fn.yourFunctionName = function(){
    alert('function called succesfully for - ' + $(this).html() );
}

To call this function in your current file, just call the function as -

......
<script type="text/javascript">
    $(function(){
        $('#element').yourFunctionName();
    });
</script>

If you want to pass the parameters to the function, then define the function as-

$.fn.functionWithParameters = function(parameter1, parameter2){
        alert('Parameters passed are - ' + parameter1 + ' , ' + parameter2);
}

And call this function in your current file as -

$('#element').functionWithParameters('some parameter', 'another parameter');

Math constant PI value in C

Depending on the library you are using the standard GNU C Predefined Mathematical Constants are here... https://www.gnu.org/software/libc/manual/html_node/Mathematical-Constants.html

You already have them so why redefine them? Your system desktop calculators probably have them and are even more accurate so you could but just be sure you're not conflicting with existing defined ones to save on compile warnings as they tend to get defaults for things like that. Enjoy!

How to display Woocommerce Category image?

Use this code this may help you.i have passed the cat id 17.pass woocommerce cat id and thats it

   <?php
      global $woocommerce;
      global $wp_query;
      $cat_id=17;
      $table_name = $wpdb->prefix . "woocommerce_termmeta";
      $query="SELECT meta_value FROM {$table_name} WHERE `meta_key`='thumbnail_id' and woocommerce_term_id ={$cat_id} LIMIT 0 , 30";
      $result =  $wpdb->get_results($query);

      foreach($result as $result1){
          $img_id= $result1->meta_value;
      }     

      echo '<img src="'.wp_get_attachment_url( $img_id ).'" alt="category image">';
   ?>

Bash scripting, multiple conditions in while loop

Try:

while [ $stats -gt 300 -o $stats -eq 0 ]

[ is a call to test. It is not just for grouping, like parentheses in other languages. Check man [ or man test for more information.

How to use onSaveInstanceState() and onRestoreInstanceState()?

  • onSaveInstanceState() is a method used to store data before pausing the activity.

Description : Hook allowing a view to generate a representation of its internal state that can later be used to create a new instance with that same state. This state should only contain information that is not persistent or can not be reconstructed later. For example, you will never store your current position on screen because that will be computed again when a new instance of the view is placed in its view hierarchy.

  • onRestoreInstanceState() is method used to retrieve that data back.

Description : This method is called after onStart() when the activity is being re-initialized from a previously saved state, given here in savedInstanceState. Most implementations will simply use onCreate(Bundle) to restore their state, but it is sometimes convenient to do it here after all of the initialization has been done or to allow subclasses to decide whether to use your default implementation. The default implementation of this method performs a restore of any view state that had previously been frozen by onSaveInstanceState(Bundle).

Consider this example here:
You app has 3 edit boxes where user was putting in some info , but he gets a call so if you didn't use the above methods what all he entered will be lost.
So always save the current data in onPause() method of Activity as a bundle & in onResume() method call the onRestoreInstanceState() method .

Please see :

How to use onSavedInstanceState example please

http://www.how-to-develop-android-apps.com/tag/onrestoreinstancestate/

Adding a newline into a string in C#

You can add a new line character after the @ symbol like so:

string newString = oldString.Replace("@", "@\n");  

You can also use the NewLine property in the Environment Class (I think it is Environment).

Django DB Settings 'Improperly Configured' Error

in my own case in django 1.10.1 running on python2.7.11, I was trying to start the server using django-admin runserver instead of manage.py runserver in my project directory.

What is difference between Implicit wait and Explicit wait in Selenium WebDriver?

My Thought,

Implicit Wait : If wait is set, it will wait for specified amount of time for each findElement/findElements call. It will throw an exception if action is not complete.

Explicit Wait : If wait is set, it will wait and move on to next step when the provided condition becomes true else it will throw an exception after waiting for specified time. Explicit wait is applicable only once wherever specified.

Warning - Build path specifies execution environment J2SE-1.4

I was getting project warning as "Build path specifies execution environment J2SE-1.5. There are no JREs installed in the workspace that are strictly compatible with this environment". I removed the J2SE1.5 library and added new JRE System Library which resolved my problem

Modifying the "Path to executable" of a windows service

Open Run(win+R) , type "Regedit.exe" , to open "Registry Editor", go to

HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services

find "Apache2.4" open the folder find the "ImagePath" in the right side, open "ImagePath" under "value Data" put the following path:

"C:\xampp\apache\bin\httpd.exe" -k runservice foe XAMPP for others point to the location where Apache is installed and inside locate the bin folder "C:(Apache installed location)\bin\httpd.exe" -k runservice

How to compile C++ under Ubuntu Linux?

g++ is the C++ compiler under linux. The code looks right. It is possible that you are missing a library reference which is used as such:

g++ -l{library name here (math fns use "m")} codefile.cpp

rbind error: "names do not match previous names"

check all the variables names in both of the combined files. Name of variables of both files to be combines should be exact same or else it will produce the above mentioned errors. I was facing the same problem as well, and after making all names same in both the file, rbind works accurately.

Thanks

calling Jquery function from javascript

    <script>

        // Instantiate your javascript function
        niceJavascriptRoutine = null;

        // Begin jQuery
        $(document).ready(function() {

            // Your jQuery function
            function niceJqueryRoutine() {
                // some code
            }
            // Point the javascript function to the jQuery function
            niceJavaScriptRoutine = niceJueryRoutine;

        });

    </script>

LINQ to SQL Left Outer Join

I'd like to add one more thing. In LINQ to SQL if your DB is properly built and your tables are related through foreign key constraints, then you do not need to do a join at all.

Using LINQPad I created the following LINQ query:

//Querying from both the CustomerInfo table and OrderInfo table
from cust in CustomerInfo
where cust.CustomerID == 123456
select new {cust, cust.OrderInfo}

Which was translated to the (slightly truncated) query below

 -- Region Parameters
 DECLARE @p0 Int = 123456
-- EndRegion
SELECT [t0].[CustomerID], [t0].[AlternateCustomerID],  [t1].[OrderID], [t1].[OnlineOrderID], (
    SELECT COUNT(*)
    FROM [OrderInfo] AS [t2]
    WHERE [t2].[CustomerID] = [t0].[CustomerID]
    ) AS [value]
FROM [CustomerInfo] AS [t0]
LEFT OUTER JOIN [OrderInfo] AS [t1] ON [t1].[CustomerID] = [t0].[CustomerID]
WHERE [t0].[CustomerID] = @p0
ORDER BY [t0].[CustomerID], [t1].[OrderID]

Notice the LEFT OUTER JOIN above.

how to implement Pagination in reactJs

I have implemented pagination + search in ReactJs, see the output: Pagination in React

View complete code on GitHub: https://github.com/navanathjadhav/generic-pagination

Also visit this article for step by step implementation of pagination: https://everblogs.com/react/3-simple-steps-to-add-pagination-in-react/

How to create roles in ASP.NET Core and assign them to users?

Update in 2020. Here is another way if you prefer.

 IdentityResult res = new IdentityResult();
 var _role = new IdentityRole();
 _role.Name = role.RoleName;
  res = await _roleManager.CreateAsync(_role);
  if (!res.Succeeded)
  {
        foreach (IdentityError er in res.Errors)
        {
             ModelState.AddModelError(string.Empty, er.Description);
         }
         ViewBag.UserMessage = "Error Adding Role";
         return View();
  }
  else
  {
        ViewBag.UserMessage = "Role Added";
        return View();
   }

Submit form on pressing Enter with AngularJS

Another approach would be using ng-keypress ,

<input type="text" ng-model="data" ng-keypress="($event.charCode==13)? myfunc() : return"> 

Submit an input on pressing Enter with AngularJS - jsfiddle

Entity Framework Core add unique constraint code-first

To use it in EF core via model configuration

public class ApplicationCompanyConfiguration : IEntityTypeConfiguration<Company>
{
    public void Configure(EntityTypeBuilder<Company> builder)
    {
        builder.ToTable("Company"); 
        builder.HasIndex(p => p.Name).IsUnique();
    }
}

How to delete from a table where ID is in a list of IDs?

delete from t
where id in (1, 4, 6, 7)

How to pass command line arguments to a shell alias?

An empty alias will execute its args:

alias DEBUG=

Is it possible to disable floating headers in UITableView with UITableViewStylePlain?

Another way to do it is to make an empty section right before the one you want the header on and put your header on that section. Because the section is empty the header will scroll immediately.

Import numpy on pycharm

It seems that each project may have a separate collection of python libraries in a project specific computing environment. To get this working with numpy I went to the terminal at the bottom of the pycharm window and ran pip install numpy and once the process finished running the install and indexing my python project was able to import numpy from the line of code import numpy as np. It seems you may need to do this for each project you setup in numpy.

Plotting a list of (x, y) coordinates in python matplotlib

If you want to plot a single line connecting all the points in the list

plt.plot(li[:])

plt.show()

This will plot a line connecting all the pairs in the list as points on a Cartesian plane from the starting of the list to the end. I hope that this is what you wanted.

Invoking Java main method with parameters from Eclipse

This answer is based on Eclipse 3.4, but should work in older versions of Eclipse.

When selecting Run As..., go into the run configurations.

On the Arguments tab of your Java run configuration, configure the variable ${string_prompt} to appear (you can click variables to get it, or copy that to set it directly).

Every time you use that run configuration (name it well so you have it for later), you will be prompted for the command line arguments.

SQL Server: combining multiple rows into one row

There are several methods.

If you want just the consolidated string value returned, this is a good quick and easy approach

DECLARE @combinedString VARCHAR(MAX)
SELECT @combinedString = COALESCE(@combinedString + ', ', '') + stringvalue
FROM jira.customfieldValue
WHERE customfield = 12534
    AND ISSUE = 19602

SELECT @combinedString as StringValue 

Which will return your combined string.

You can also try one of the XML methods e.g.

SELECT DISTINCT Issue, Customfield, StringValues
FROM Jira.customfieldvalue v1
CROSS APPLY ( SELECT StringValues + ',' 
              FROM jira.customfieldvalue v2
              WHERE v2.Customfield = v1.Customfield 
                  AND v2.Issue = v1.issue 
              ORDER BY ID 
                  FOR XML PATH('') )  D ( StringValues )
WHERE customfield = 12534
    AND ISSUE = 19602

How to create a fixed sidebar layout with Bootstrap 4?

I used this in my code:

<div class="sticky-top h-100">
    <nav id="sidebar" class="vh-100">
        ....

this cause your sidebar height become 100% and fixed at top.

How do I pass an object from one activity to another on Android?

It depends on the type of data you need access to. If you have some kind of data pool that needs to persist across Activitys then Erich's answer is the way to go. If you just need to pass a few objects from one activity to another then you can have them implement Serializable and pass them in the extras of the Intent to start the new Activity.

"unable to locate adb" using Android Studio

In Android Studio, Click on 'Tools' on the top tab bar of android studio

Tools >> Android >> SDK Manager >> Launch Standalone Sdk manager

there you can clearly see which platform tool is missing , then just install that and your adb will start working properly.In Image You Can see every thing

How to add additional libraries to Visual Studio project?

This description is very vague. What did you try, and how did it fail.

To include a library with your project, you have to include it in the modules passed to the linker. The exact steps to do this depend on the tools you are using. That part has nothing to do with the OS.

Now, if you are successfully compiling the library into your app and it doesn't run, that COULD be related to the OS.

How can I convert a date to GMT?

You can simply use the toUTCString (or toISOString) methods of the date object.

Example:

new Date("Fri Jan 20 2012 11:51:36 GMT-0500").toUTCString()

// Output:  "Fri, 20 Jan 2012 16:51:36 GMT"

If you prefer better control of the output format, consider using a library such as date-fns or moment.js.

Also, in your question, you've actually converted the time incorrectly. When an offset is shown in a timestamp string, it means that the date and time values in the string have already been adjusted from UTC by that value. To convert back to UTC, invert the sign before applying the offset.

11:51:36 -0300  ==  14:51:36Z

Intercept page exit event

Instead of an annoying confirmation popup, it would be nice to delay leaving just a bit (matter of milliseconds) to manage successfully posting the unsaved data to the server, which I managed for my site using writing dummy text to the console like this:

window.onbeforeunload=function(e){
  // only take action (iterate) if my SCHEDULED_REQUEST object contains data        
  for (var key in SCHEDULED_REQUEST){   
    postRequest(SCHEDULED_REQUEST); // post and empty SCHEDULED_REQUEST object
    for (var i=0;i<1000;i++){
      // do something unnoticable but time consuming like writing a lot to console
      console.log('buying some time to finish saving data'); 
    };
    break;
  };
}; // no return string --> user will leave as normal but data is send to server

Edit: See also Synchronous_AJAX and how to do that with jquery

How to set -source 1.7 in Android Studio and Gradle

Latest Android Studio 1.4.

Click File->Project Structure->SDK Location->JDK Location.

You could also set individual module JDK Version compatibility by going to the Module (below the SDK Location), and edit the Source Compatibility accordingly. (note, this only applies to Android Module).

Reading a .txt file using Scanner class in Java

here are some working and tested methods;

using Scanner

package io;

import java.io.File;
import java.util.Scanner;

public class ReadFromFileUsingScanner {
    public static void main(String[] args) throws Exception {
        File file=new File("C:\\Users\\pankaj\\Desktop\\test.java");
        Scanner sc=new Scanner(file);
        while(sc.hasNextLine()){
            System.out.println(sc.nextLine());
        }
    }
}


Here's another way to read entire file (without loop) using Scanner class

package io;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ReadingEntireFileWithoutLoop {
    public static void main(String[] args) throws FileNotFoundException {
        File file=new File("C:\\Users\\pankaj\\Desktop\\test.java");
        Scanner sc=new Scanner(file);
        sc.useDelimiter("\\Z");
        System.out.println(sc.next());
    }
}

using BufferedReader

 package io;
import java.io.*;
public class ReadFromFile2 {
    public static void main(String[] args)throws Exception {
        File file=new File("C:\\Users\\pankaj\\Desktop\\test.java");
        BufferedReader br=new BufferedReader(new FileReader(file));
        String st;
        while((st=br.readLine())!=null){
            System.out.println(st);
        }
    }
}

using FileReader

package io;
import java.io.*;
public class ReadingFromFile {
    public static void main(String[] args) throws Exception {
        FileReader fr=new FileReader("C:\\Users\\pankaj\\Desktop\\test.java");
        int i;
        while((i=fr.read())!=-1){
            System.out.print((char) i);
        }
    }
}

java.lang.ClassNotFoundException: org.apache.jsp.index_jsp

This was caused because of something like this in my case:

<jsp-config>
    <jsp-property-group>
        <url-pattern>*.jsp</url-pattern>
        <include-prelude>/headerfooter/header.jsp</include-prelude>
        <include-coda>/headerfooter/footer.jsp</include-coda>
    </jsp-property-group>
</jsp-config>

The problem was actually I did not have header.jsp in my project. However the error message was still saying index_jsp was not found.

How to validate an email address in PHP

If you want to check if provided domain from email address is valid, use something like:

/*
* Check for valid MX record for given email domain
*/
if(!function_exists('check_email_domain')){
    function check_email_domain($email) {
        //Get host name from email and check if it is valid
        $email_host = explode("@", $email);     
        //Add a dot to the end of the host name to make a fully qualified domain name and get last array element because an escaped @ is allowed in the local part (RFC 5322)
        $host = end($email_host) . "."; 
        //Convert to ascii (http://us.php.net/manual/en/function.idn-to-ascii.php)
        return checkdnsrr(idn_to_ascii($host), "MX"); //(bool)       
    }
}

This is handy way to filter a lot of invalid email addresses, along with standart email validation, because valid email format does not mean valid email.

Note that idn_to_ascii() (or his sister function idn_to_utf8()) function may not be available in your PHP installation, it requires extensions PECL intl >= 1.0.2 and PECL idn >= 0.1.

Also keep in mind that IPv4 or IPv6 as domain part in email (for example user@[IPv6:2001:db8::1]) cannot be validated, only named hosts can.

See more here.

update listview dynamically with adapter

I created a method just for that. I use it any time I need to manually update a ListView. Hopefully this gives you an idea of how to implement your own

public static void UpdateListView(List<SomeObject> SomeObjects, ListView ListVw)
{    
    if(ListVw != null)
    {
        final YourAdapter adapter = (YourAdapter) ListVw.getAdapter();

        //You'll have to create this method in your adapter class. It's a simple setter.
        adapter.SetList(SomeObjects);

        adapter.notifyDataSetChanged();
    }
}

I'm using an adapter that inherites from BaseAdapter. Should work for any other type of adapter.

How to declare a global variable in React?

I don't know what they're trying to say with this "React Context" stuff - they're talking Greek, to me, but here's how I did it:

Carrying values between functions, on the same page

In your constructor, bind your setter:

this.setSomeVariable = this.setSomeVariable.bind(this);

Then declare a function just below your constructor:

setSomeVariable(propertyTextToAdd) {
    this.setState({
        myProperty: propertyTextToAdd
    });
}

When you want to set it, call this.setSomeVariable("some value");

(You might even be able to get away with this.state.myProperty = "some value";)

When you want to get it, call var myProp = this.state.myProperty;

Using alert(myProp); should give you some value .

Extra scaffolding method to carry values across pages/components

You can assign a model to this (technically this.stores), so you can then reference it with this.state:

import Reflux from 'reflux'
import Actions from '~/actions/actions`

class YourForm extends Reflux.Store
{
    constructor()
    {
        super();
        this.state = {
            someGlobalVariable: '',
        };
        this.listenables = Actions;
        this.baseState = {
            someGlobalVariable: '',
        };
    }

    onUpdateFields(name, value) {
        this.setState({
            [name]: value,
        });
    }

    onResetFields() {
        this.setState({
           someGlobalVariable: '',
        });
    }
}
const reqformdata = new YourForm

export default reqformdata

Save this to a folder called stores as yourForm.jsx.

Then you can do this in another page:

import React from 'react'
import Reflux from 'reflux'
import {Form} from 'reactstrap'
import YourForm from '~/stores/yourForm.jsx'

Reflux.defineReact(React)

class SomePage extends Reflux.Component {
    constructor(props) {
        super(props);
        this.state = {
            someLocalVariable: '',
        }
        this.stores = [
            YourForm,
        ]
    }
    render() {

        const myVar = this.state.someGlobalVariable;
        return (
            <Form>
                <div>{myVar}</div>
            </Form>
        )
    }
}
export default SomePage

If you had set this.state.someGlobalVariable in another component using a function like:

setSomeVariable(propertyTextToAdd) {
    this.setState({
       myGlobalVariable: propertyTextToAdd
   });
}

that you bind in the constructor with:

this.setSomeVariable = this.setSomeVariable.bind(this);

the value in propertyTextToAdd would be displayed in SomePage using the code shown above.

Google Maps Android API v2 Authorization failure

I had same issue but it turned out that it was because I created two different map API keys with same SHA-1 fingerprint with nearly similar package name com.bla.bla and the other com.bla.bla.something.

Programmatically center TextView text

try this method

  public void centerTextView(LinearLayout linearLayout) {
    TextView textView = new TextView(context);
    textView.setText(context.getString(R.string.no_records));
    textView.setTypeface(Typeface.DEFAULT_BOLD);
    textView.setGravity(Gravity.CENTER);
    textView.setTextSize(18.0f);
    textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
    linearLayout.addView(textView);
}

Get docker container id from container name

You can try this:

docker inspect --format="{{.Id}}" container_name

This approach is OS independent.

How do I overload the [] operator in C#

public int this[int index]
{
    get => values[index];
}

how to draw directed graphs using networkx in python?

Fully fleshed out example with arrows for only the red edges:

import networkx as nx
import matplotlib.pyplot as plt

G = nx.DiGraph()
G.add_edges_from(
    [('A', 'B'), ('A', 'C'), ('D', 'B'), ('E', 'C'), ('E', 'F'),
     ('B', 'H'), ('B', 'G'), ('B', 'F'), ('C', 'G')])

val_map = {'A': 1.0,
           'D': 0.5714285714285714,
           'H': 0.0}

values = [val_map.get(node, 0.25) for node in G.nodes()]

# Specify the edges you want here
red_edges = [('A', 'C'), ('E', 'C')]
edge_colours = ['black' if not edge in red_edges else 'red'
                for edge in G.edges()]
black_edges = [edge for edge in G.edges() if edge not in red_edges]

# Need to create a layout when doing
# separate calls to draw nodes and edges
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos, cmap=plt.get_cmap('jet'), 
                       node_color = values, node_size = 500)
nx.draw_networkx_labels(G, pos)
nx.draw_networkx_edges(G, pos, edgelist=red_edges, edge_color='r', arrows=True)
nx.draw_networkx_edges(G, pos, edgelist=black_edges, arrows=False)
plt.show()

Red edges

Regular expression for excluding special characters

Here's all the french accented characters: àÀâÂäÄáÁéÉèÈêÊëËìÌîÎïÏòÒôÔöÖùÙûÛüÜçÇ’ñ

I would google a list of German accented characters. There aren't THAT many. You should be able to get them all.

For URLS I Replace accented URLs with regular letters like so:

string beforeConversion = "àÀâÂäÄáÁéÉèÈêÊëËìÌîÎïÏòÒôÔöÖùÙûÛüÜçÇ’ñ";
string afterConversion = "aAaAaAaAeEeEeEeEiIiIiIoOoOoOuUuUuUcC'n";
for (int i = 0; i < beforeConversion.Length; i++) {

     cleaned = Regex.Replace(cleaned, beforeConversion[i].ToString(), afterConversion[i].ToString());
}

There's probably a more efficient way, mind you.

taking input of a string word by word

getline is storing the entire line at once, which is not what you want. A simple fix is to have three variables and use cin to get them all. C++ will parse automatically at the spaces.

#include <iostream>
using namespace std;

int main() {
    string a, b, c;
    cin >> a >> b >> c;
    //now you have your three words
    return 0;
}

I don't know what particular "operation" you're talking about, so I can't help you there, but if it's changing characters, read up on string and indices. The C++ documentation is great. As for using namespace std; versus std:: and other libraries, there's already been a lot said. Try these questions on StackOverflow to start.

JSP : JSTL's <c:out> tag

c:out escapes HTML characters so that you can avoid cross-site scripting.

if person.name = <script>alert("Yo")</script>

the script will be executed in the second case, but not when using c:out

Why am I seeing "TypeError: string indices must be integers"?

data is a dict object. So, iterate over it like this:

Python 2

for key, value in data.iteritems():
    print key, value

Python 3

for key, value in data.items():
    print(key, value)

How to calculate probability in a normal distribution given mean & standard deviation?

Starting Python 3.8, the standard library provides the NormalDist object as part of the statistics module.

It can be used to get the probability density function (pdf - likelihood that a random sample X will be near the given value x) for a given mean (mu) and standard deviation (sigma):

from statistics import NormalDist

NormalDist(mu=100, sigma=12).pdf(98)
# 0.032786643008494994

Also note that the NormalDist object also provides the cumulative distribution function (cdf - probability that a random sample X will be less than or equal to x):

NormalDist(mu=100, sigma=12).cdf(98)
# 0.43381616738909634

Using if(isset($_POST['submit'])) to not display echo when script is open is not working

The $_post function need the name value like:

<input type="submit" value"Submit" name="example">

Call

$var = strip_tags($_POST['example']);
if (isset($var)){
    // your code here
}

How to make multiple divs display in one line but still retain width?

I used the property

display: table;

and

display: table-cell;

to achieve the same.Link to fiddle below shows 3 tables wrapped in divs and these divs are further wrapped in a parent div

<div id='content'>
   <div id='div-1'><!-- COntains table --></div>
   <div id='div-2'><!-- contains two more divs that require to be arranged one below other --></div>
</div>

Here is the jsfiddle: http://jsfiddle.net/vikikamath/QU6WP/1/ I thought this might be helpful to someone looking to set divs in same line without using display-inline

Is this very likely to create a memory leak in Tomcat?

Sometimes this has to do with configuration changes. When we upgraded from Tomncat 6.0.14 to 6.0.26, we had seen something similar. here is the solution http://www.skill-guru.com/blog/2010/08/22/tomcat-6-0-26-shutdown-reports-a-web-application-created-a-threadlocal-threadlocal-has-been-forcibly-removed/

How to use "Share image using" sharing Intent to share images in android?

Thanks all, I tried the few of the options given, but those seems not to work for the latest android releases, so adding the modified steps which work for the latest android releases. these are based on few of the answers above but with modifications & the solution is based on the use of File Provider :

Step:1

Add Following code in Manifest File:

<provider
    android:name="androidx.core.content.FileProvider"
    android:authorities="${applicationId}"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_provider_paths" />
</provider>

step:2 Create an XML File in res > xml

Create file_provider_paths file inside xml.

Note that this is the file which we include in the android:resource in the previous step.

Write following codes inside the file_provider_paths:

<?xml version="1.0" encoding="utf-8"?>
<paths>
        <cache-path name="cache" path="/" />
        <files-path name="files" path="/" />
</paths>

Step:3

After that go to your button Click:

Button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

       Bitmap bit = BitmapFactory.decodeResource(context.getResources(),  R.drawable.filename);
        File filesDir = context.getApplicationContext().getFilesDir();
        File imageFile = new File(filesDir, "birds.png");
        OutputStream os;
        try {
            os = new FileOutputStream(imageFile);
            bit.compress(Bitmap.CompressFormat.PNG, 100, os); 
            os.flush();
            os.close();
        } catch (Exception e) {
            Log.e(getClass().getSimpleName(), "Error writing bitmap", e);
        }

        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_SEND);
        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

        Uri imageUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID, imageFile);

        intent.putExtra(Intent.EXTRA_STREAM, imageUri);
        intent.setType("image/*");
        context.startActivity(intent);
    }
});

For More detailed explanation Visit https://droidlytics.wordpress.com/2020/08/04/use-fileprovider-to-share-image-from-recyclerview/

Remove blank values from array using C#

If you are using .NET 3.5+ you could use LINQ (Language INtegrated Query).

test = test.Where(x => !string.IsNullOrEmpty(x)).ToArray();

ERROR:'keytool' is not recognized as an internal or external command, operable program or batch file

  1. Go to My computer -> right click -> system properties -> environmental variables -> Path -> add you jdk/bin to this path

    C:\Program Files\Java\jdk1.8.0_211\bin
    

*if this not work then

  1. In cmd set the path by using the below command

    set PATH=C:\Program Files\Java\jdk1.8.0_211\bin
    

now the path is set now you can use the keytool

Maven is not working in Java 8 when Javadoc tags are incomplete

The best solution would be to fix the javadoc errors. If for some reason that is not possible (ie: auto generated source code) then you can disable this check.

DocLint is a new feature in Java 8, which is summarized as:

Provide a means to detect errors in Javadoc comments early in the development cycle and in a way that is easily linked back to the source code.

This is enabled by default, and will run a whole lot of checks before generating Javadocs. You need to turn this off for Java 8 as specified in this thread. You'll have to add this to your maven configuration:

<profiles>
  <profile>
    <id>java8-doclint-disabled</id>
    <activation>
      <jdk>[1.8,)</jdk>
    </activation>
    <properties>
      <javadoc.opts>-Xdoclint:none</javadoc.opts>
    </properties>
  </profile>
</profiles>
<build>
  <plugins>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-javadoc-plugin</artifactId>
        <version>2.9</version>
        <executions>
            <execution>
                <id>attach-javadocs</id>
                <goals>
                    <goal>jar</goal>
                </goals>
                <configuration>
                    <additionalparam>${javadoc.opts}</additionalparam>
                </configuration>
            </execution>
        </executions>
    </plugin>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-site-plugin</artifactId>
        <version>3.3</version>
        <configuration>
          <reportPlugins>
            <plugin>
              <groupId>org.apache.maven.plugins</groupId>
              <artifactId>maven-javadoc-plugin</artifactId>
              <configuration>
                <additionalparam>${javadoc.opts}</additionalparam>
              </configuration>
            </plugin>
          </reportPlugins>
        </configuration>
      </plugin>
   </plugins>
</build>

For maven-javadoc-plugin 3.0.0+: Replace

<additionalparam>-Xdoclint:none</additionalparam>

with

<doclint>none</doclint>

How do I parse JSON with Ruby on Rails?

Ruby's bundled JSON is capable of exhibiting a bit of magic on its own.

If you have a string containing JSON serialized data that you want to parse:

JSON[string_to_parse]

JSON will look at the parameter, see it's a String and try decoding it.

Similarly, if you have a hash or array you want serialized, use:

JSON[array_of_values]

Or:

JSON[hash_of_values]

And JSON will serialize it. You can also use the to_json method if you want to avoid the visual similarity of the [] method.

Here are some examples:

hash_of_values = {'foo' => 1, 'bar' => 2}
array_of_values = [hash_of_values]

JSON[hash_of_values] 
# => "{\"foo\":1,\"bar\":2}"

JSON[array_of_values] 
# => "[{\"foo\":1,\"bar\":2}]"

string_to_parse = array_of_values.to_json
JSON[string_to_parse]
# => [{"foo"=>1, "bar"=>2}]

If you root around in JSON you might notice it's a subset of YAML, and, actually the YAML parser is what's handling JSON. You can do this too:

require 'yaml'

YAML.load(string_to_parse)
# => [{"foo"=>1, "bar"=>2}]

If your app is parsing both YAML and JSON, you can let YAML handle both flavors of serialized data.

MomentJS getting JavaScript Date in UTC

Calling toDate will create a copy (the documentation is down-right wrong about it not being a copy), of the underlying JS Date object. JS Date object is stored in UTC and will always print to eastern time. Without getting into whether .utc() modifies the underlying object that moment wraps use the code below.

You don't need moment for this.

new Date().getTime()

This works, because JS Date at its core is in UTC from the Unix Epoch. It's extraordinarily confusing and I believe a big flaw in the interface to mix local and UTC times like this with no descriptions in the methods.

How can I restart a Java application?

Although this question is old and answered, I've stumbled across a problem with some of the solutions and decided to add my suggestion into the mix.

The problem with some of the solutions is that they build a single command string. This creates issues when some parameters contain spaces, especially java.home.

For example, on windows, the line

final String javaBin = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";

Might return something like this:C:\Program Files\Java\jre7\bin\java

This string has to be wrapped in quotes or escaped due to the space in Program Files. Not a huge problem, but somewhat annoying and error prone, especially in cross platform applications.

Therefore my solution builds the command as an array of commands:

public static void restart(String[] args) {

        ArrayList<String> commands = new ArrayList<String>(4 + jvmArgs.size() + args.length);
        List<String> jvmArgs = ManagementFactory.getRuntimeMXBean().getInputArguments();

        // Java
        commands.add(System.getProperty("java.home") + File.separator + "bin" + File.separator + "java");

        // Jvm arguments
        for (String jvmArg : jvmArgs) {
            commands.add(jvmArg);
        }

        // Classpath
        commands.add("-cp");
        commands.add(ManagementFactory.getRuntimeMXBean().getClassPath());

        // Class to be executed
        commands.add(BGAgent.class.getName());

        // Command line arguments
        for (String arg : args) {
            commands.add(arg);
        }

        File workingDir = null; // Null working dir means that the child uses the same working directory

        String[] env = null; // Null env means that the child uses the same environment

        String[] commandArray = new String[commands.size()];
        commandArray = commands.toArray(commandArray);

        try {
            Runtime.getRuntime().exec(commandArray, env, workingDir);
            System.exit(0);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Viewing localhost website from mobile device

To view localhost website from mobile device you have to follow thoses steps :

  • In your computer, you have to retrieve your IP address (Run > cmd > ipconfig)
  • If your localhost use a specific port (like localhost:12345 ), you have to open the port on your computer (Control Panel > System and Security > Firewall > Advanced settings and add Inbound rule)
  • Finally, you can access to your website from mobile device by navigate to : http://192.168.X.X:12345/

Hope it helps

Python pandas insert list into a cell

Also getting

ValueError: Must have equal len keys and value when setting with an iterable,

using .at rather than .loc did not make any difference in my case, but enforcing the datatype of the dataframe column did the trick:

df['B'] = df['B'].astype(object)

Then I could set lists, numpy array and all sorts of things as single cell values in my dataframes.

How do you strip a character out of a column in SQL Server?

This is done using the REPLACE function

To strip out "somestring" from "SomeColumn" in "SomeTable" in the SELECT query:

SELECT REPLACE([SomeColumn],'somestring','') AS [SomeColumn]  FROM [SomeTable]

To update the table and strip out "somestring" from "SomeColumn" in "SomeTable"

UPDATE [SomeTable] SET [SomeColumn] = REPLACE([SomeColumn], 'somestring', '')

How can I save application settings in a Windows Forms application?

public static class SettingsExtensions
{
    public static bool TryGetValue<T>(this Settings settings, string key, out T value)
    {
        if (settings.Properties[key] != null)
        {
            value = (T) settings[key];
            return true;
        }

        value = default(T);
        return false;
    }

    public static bool ContainsKey(this Settings settings, string key)
    {
        return settings.Properties[key] != null;
    }

    public static void SetValue<T>(this Settings settings, string key, T value)
    {
        if (settings.Properties[key] == null)
        {
            var p = new SettingsProperty(key)
            {
                PropertyType = typeof(T),
                Provider = settings.Providers["LocalFileSettingsProvider"],
                SerializeAs = SettingsSerializeAs.Xml
            };
            p.Attributes.Add(typeof(UserScopedSettingAttribute), new UserScopedSettingAttribute());
            var v = new SettingsPropertyValue(p);
            settings.Properties.Add(p);
            settings.Reload();
        }
        settings[key] = value;
        settings.Save();
    }
}

Android Get Current timestamp?

The solution is :

Long tsLong = System.currentTimeMillis()/1000;
String ts = tsLong.toString();

Calling another method java GUI

I'm not sure what you're trying to do, but here's something to consider: c(); won't do anything. c is an instance of the class checkbox and not a method to be called. So consider this:

public class FirstWindow extends JFrame {      public FirstWindow() {         checkbox c = new checkbox();         c.yourMethod(yourParameters); // call the method you made in checkbox     } }  public class checkbox extends JFrame {      public checkbox(yourParameters) {          // this is the constructor method used to initialize instance variables     }      public void yourMethod() // doesn't have to be void     {         // put your code here     } } 

How do I include a pipe | in my linux find -exec command?

If you are looking for a simple alternative, this can be done using a loop:

for i in $(find -name 'file_*' -follow -type f); do
  zcat $i | agrep -dEOE 'grep'
done

or, more general and easy to understand form:

for i in $(YOUR_FIND_COMMAND); do
  YOUR_EXEC_COMMAND_AND_PIPES
done

and replace any {} by $i in YOUR_EXEC_COMMAND_AND_PIPES

Pandas DataFrame column to list

The above solution is good if all the data is of same dtype. Numpy arrays are homogeneous containers. When you do df.values the output is an numpy array. So if the data has int and float in it then output will either have int or float and the columns will loose their original dtype. Consider df

a  b 
0  1  4
1  2  5 
2  3  6 

a    float64
b    int64 

So if you want to keep original dtype, you can do something like

row_list = df.to_csv(None, header=False, index=False).split('\n')

this will return each row as a string.

['1.0,4', '2.0,5', '3.0,6', '']

Then split each row to get list of list. Each element after splitting is a unicode. We need to convert it required datatype.

def f(row_str): 
  row_list = row_str.split(',')
  return [float(row_list[0]), int(row_list[1])]

df_list_of_list = map(f, row_list[:-1])

[[1.0, 4], [2.0, 5], [3.0, 6]]

What do the terms "CPU bound" and "I/O bound" mean?

IO bound processes: spend more time doing IO than computations, have many short CPU bursts. CPU bound processes: spend more time doing computations, few very long CPU bursts

How do I ALTER a PostgreSQL table and make a column unique?

I figured it out from the PostgreSQL docs, the exact syntax is:

ALTER TABLE the_table ADD CONSTRAINT constraint_name UNIQUE (thecolumn);

Thanks Fred.

How to set a ripple effect on textview or imageview on Android?

In addition to @Bikesh M Annur's answer, be sure to update your support libraries. Previously I was using 23.1.1 and nothing happened. Updating it to 23.3.0 did the trick.

How to send string from one activity to another?

You can use the GNLauncher, which is part of a utility library I wrote in cases where a lot of interaction with the Activity is required. With the library, it is almost as simple as calling a function on the Activity object with the required parameters. https://github.com/noxiouswinter/gnlib_android/wiki#gnlauncher

Having issues with a MySQL Join that needs to meet multiple conditions

also this should work (not tested):

SELECT u.* FROM room u JOIN facilities_r fu ON fu.id_uc = u.id_uc AND u.id_fu IN(4,3) WHERE 1 AND vizibility = 1 GROUP BY id_uc ORDER BY u_premium desc , id_uc desc

If u.id_fu is a numeric field then you can remove the ' around them. The same for vizibility. Only if the field is a text field (data type char, varchar or one of the text-datatype e.g. longtext) then the value has to be enclosed by ' or even ".

Also I and Oracle too recommend to enclose table and field names in backticks. So you won't get into trouble if a field name contains a keyword.

SQL Server Insert if not exists

Depending on your version (2012?) of SQL Server aside from the IF EXISTS you can also use MERGE like so:

ALTER PROCEDURE [dbo].[EmailsRecebidosInsert]
    ( @_DE nvarchar(50)
    , @_ASSUNTO nvarchar(50)
    , @_DATA nvarchar(30))
AS BEGIN
    MERGE [dbo].[EmailsRecebidos] [Target]
    USING (VALUES (@_DE, @_ASSUNTO, @_DATA)) [Source]([De], [Assunto], [Data])
         ON [Target].[De] = [Source].[De] AND [Target].[Assunto] = [Source].[Assunto] AND [Target].[Data] = [Source].[Data]
     WHEN NOT MATCHED THEN
        INSERT ([De], [Assunto], [Data])
        VALUES ([Source].[De], [Source].[Assunto], [Source].[Data]);
END

Call a Subroutine from a different Module in VBA

Prefix the call with Module2 (ex. Module2.IDLE). I'm assuming since you asked this that you have IDLE defined multiple times in the project, otherwise this shouldn't be necessary.

Create Setup/MSI installer in Visual Studio 2017

Other answers posted here for this question did not work for me using the latest Visual Studio 2017 Enterprise edition (as of 2018-09-18).

Instead, I used this method:

  1. Close all but one instance of Visual Studio.
  2. In the running instance, access the menu Tools->Extensions and Updates.
  3. In that dialog, choose Online->Visual Studio Marketplace->Tools->Setup & Deployment.
  4. From the list that appears, select Microsoft Visual Studio 2017 Installer Projects.

Once installed, close and restart Visual Studio. Go to File->New Project and search for the word Installer. You'll know you have the correct templates installed if you see a list that looks something like this:

enter image description here

WPF TemplateBinding vs RelativeSource TemplatedParent

They are used in a similar way but they have a few differences. Here is a link to the TemplateBinding documentation: http://msdn.microsoft.com/en-us/library/ms742882.aspx

HTML img tag: title attribute vs. alt attribute?

I would ALWAYS go with both the alt and the title attributes. Many developers have been using this pattern now for over 20 years to deal with IE and other issues. So this is not new knowledge. Its just been rediscovered by new developers that didn't bother to learn from the past.

In addition, in HTML5 you should start using the new HTML5 picture element wrapped in figure with full WPA-ARIA attributes for greater accessibility, as well as support of assistive technologies, screen readers, and the like. Because this element is not supported in many older browsers...BUT degrades gracefully...I recommend the following HTML design pattern now for images in HTML:

<figure aria-labelledby="picturecaption2">
    <picture id="picture2">
        <source srcset="image.webp" type="image/webp" media="(min-width: 800px)" />
        <source srcset="image.gif" type="image/gif" />
        <img id="image2" style="height:auto;max-width: 100%;" src="image.jpg" width="255" height="200" alt="image:The World Wide Web" title="The World Wide Web" loading="lazy" no-referrer="no-referrer" onerror="this.onerror=null;" />
    </picture>
    <figcaption id="picturecaption2"><small>"My Cool Picture" [<a href="http://creativecommons.org/licenses/" target="_blank">A License</a>] , via <a href="https://commons.wikimedia.org/wiki/" target="_blank">Wikimedia Commons</a></small></figcaption>
</figure>

The code above has many extra "goodies" beside alt and title, including ARIA attributes, support for WebP, a media query supporting higher resolution imagery, and a nice fallback pattern supporting older image formats. It shows a fully decorated image example that uses new technologies while still supporting old ones with progressive design patterns.

REMEMBER...ALWAYS SUPPORT THE OLD BROWSERS!

How do I get Month and Date of JavaScript in 2 digit format?

var net = require('net')

function zeroFill(i) {
  return (i < 10 ? '0' : '') + i
}

function now () {
  var d = new Date()
  return d.getFullYear() + '-'
    + zeroFill(d.getMonth() + 1) + '-'
    + zeroFill(d.getDate()) + ' '
    + zeroFill(d.getHours()) + ':'
    + zeroFill(d.getMinutes())
}

var server = net.createServer(function (socket) {
  socket.end(now() + '\n')
})

server.listen(Number(process.argv[2]))

How can I print to the same line?

First, I'd like to apologize for bringing this question back up, but I felt that it could use another answer.

Derek Schultz is kind of correct. The '\b' character moves the printing cursor one character backwards, allowing you to overwrite the character that was printed there (it does not delete the entire line or even the character that was there unless you print new information on top). The following is an example of a progress bar using Java though it does not follow your format, it shows how to solve the core problem of overwriting characters (this has only been tested in Ubuntu 12.04 with Oracle's Java 7 on a 32-bit machine, but it should work on all Java systems):

public class BackSpaceCharacterTest
{
    // the exception comes from the use of accessing the main thread
    public static void main(String[] args) throws InterruptedException
    {
        /*
            Notice the user of print as opposed to println:
            the '\b' char cannot go over the new line char.
        */
        System.out.print("Start[          ]");
        System.out.flush(); // the flush method prints it to the screen

        // 11 '\b' chars: 1 for the ']', the rest are for the spaces
        System.out.print("\b\b\b\b\b\b\b\b\b\b\b");
        System.out.flush();
        Thread.sleep(500); // just to make it easy to see the changes

        for(int i = 0; i < 10; i++)
        {
            System.out.print("."); //overwrites a space
            System.out.flush();
            Thread.sleep(100);
        }

        System.out.print("] Done\n"); //overwrites the ']' + adds chars
        System.out.flush();
    }
}

Declaring an HTMLElement Typescript

The type comes after the name in TypeScript, partly because types are optional.

So your line:

HTMLElement el = document.getElementById('content');

Needs to change to:

const el: HTMLElement = document.getElementById('content');

Back in 2013, the type HTMLElement would have been inferred from the return value of getElementById, this is still the case if you aren't using strict null checks (but you ought to be using the strict modes in TypeScript). If you are enforcing strict null checks you will find the return type of getElementById has changed from HTMLElement to HTMLElement | null. The change makes the type more correct, because you don't always find an element.

So when using type mode, you will be encouraged by the compiler to use a type assertion to ensure you found an element. Like this:

const el: HTMLElement | null = document.getElementById('content');

if (el) {
  const definitelyAnElement: HTMLElement = el;
}

I have included the types to demonstrate what happens when you run the code. The interesting bit is that el has the narrower type HTMLElement within the if statement, due to you eliminating the possibility of it being null.

You can do exactly the same thing, with the same resulting types, without any type annotations. They will be inferred by the compiler, thus saving all that extra typing:

const el = document.getElementById('content');

if (el) {
  const definitelyAnElement = el;
}

Can't use WAMP , port 80 is used by IIS 7.5

You can also uncheck the IIS services from control panel add or remove programs going for windows add or remove components.

How do I get a plist as a Dictionary in Swift?

Swift 2.0 : Accessing Info.Plist

I have a Dictionary named CoachMarksDictionary with a boolean value in Info.Plist . I want to access the bool value and make it true.

let path = NSBundle.mainBundle().pathForResource("Info", ofType: "plist")!
  let dict = NSDictionary(contentsOfFile: path) as! [String: AnyObject]

  if let CoachMarksDict = dict["CoachMarksDictionary"] {
       print("Info.plist : \(CoachMarksDict)")

   var dashC = CoachMarksDict["DashBoardCompleted"] as! Bool
    print("DashBoardCompleted state :\(dashC) ")
  }

Writing To Plist:

From a Custom Plist:- (Make from File-New-File-Resource-PropertyList. Added three strings named : DashBoard_New, DashBoard_Draft, DashBoard_Completed)

func writeToCoachMarksPlist(status:String?,keyName:String?)
 {
  let path1 = NSBundle.mainBundle().pathForResource("CoachMarks", ofType: "plist")
  let coachMarksDICT = NSMutableDictionary(contentsOfFile: path1!)! as NSMutableDictionary
  var coachMarksMine = coachMarksDICT.objectForKey(keyName!)

  coachMarksMine  = status
  coachMarksDICT.setValue(status, forKey: keyName!)
  coachMarksDICT.writeToFile(path1!, atomically: true)
 }

The method can be called as

self.writeToCoachMarksPlist(" true - means user has checked the marks",keyName: "the key in the CoachMarks dictionary").

convert from Color to brush

SolidColorBrush brush = new SolidColorBrush( Color.FromArgb(255,255,139,0) )

How to write JUnit test with Spring Autowire?

Make sure you have imported the correct package. If I remeber correctly there are two different packages for Autowiring. Should be :org.springframework.beans.factory.annotation.Autowired;

Also this looks wierd to me :

@ContextConfiguration("classpath*:conf/components.xml")

Here is an example that works fine for me :

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/applicationContext_mock.xml" })
public class OwnerIntegrationTest {

    @Autowired
    OwnerService ownerService;

    @Before
    public void setup() {

        ownerService.cleanList();

    }

    @Test
    public void testOwners() {

        Owner owner = new Owner("Bengt", "Karlsson", "Ankavägen 3");
        owner = ownerService.createOwner(owner);
        assertEquals("Check firstName : ", "Bengt", owner.getFirstName());
        assertTrue("Check that Id exist: ", owner.getId() > 0);

        owner.setLastName("Larsson");
        ownerService.updateOwner(owner);
        owner = ownerService.getOwner(owner.getId());
        assertEquals("Name is changed", "Larsson", owner.getLastName());

    }

Changing background color of selected item in recyclerview

A really simple way to achieve this would be:

//instance variable
List<View>itemViewList = new ArrayList<>();

//OnCreateViewHolderMethod
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {    
    final View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_row, parent, false);
    final MyViewHolder myViewHolder = new MyViewHolder(itemView);

    itemViewList.add(itemView); //to add all the 'list row item' views

    //Set on click listener for each item view
    itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            for(View tempItemView : itemViewList) {
                /** navigate through all the itemViews and change color
                of selected view to colorSelected and rest of the views to colorDefault **/
                if(itemViewList.get(myViewHolder.getAdapterPosition()) == tempItemView) {
                    tempItemView.setBackgroundResource(R.color.colorSelected);
                }
                else{
                    tempItemView.setBackgroundResource(R.color.colorDefault);
                }
            }
        }
    });
    return myViewHolder;
}

UPDATE

The method above may ruin some default attributes of the itemView, in my case, i was using CardView, and the corner radius of the card was getting removed on click.

Better solution:

//instance variable
List<CardView>cardViewList = new ArrayList<>();

public class MyViewHolder extends RecyclerView.ViewHolder {
        CardView cardView; //THIS IS MY ROOT VIEW
        ...

        public MyViewHolder(View view) {
            super(view);
            cardView = view.findViewById(R.id.row_item_card);
            ...
        }
}

@Override
    public void onBindViewHolder(final MyViewHolder holder, int position) {
        final OurLocationObject locationObject = locationsList.get(position);
        ...

        cardViewList.add(holder.cardView); //add all the cards to this list

        holder.cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //All card color is set to colorDefault
                for(CardView cardView : cardViewList){
                cardView.setCardBackgroundColor(context.getResources().getColor(R.color.colorDefault));
                }
                //The selected card is set to colorSelected
                holder.cardView.setCardBackgroundColor(context.getResources().getColor(R.color.colorSelected));
            }
        });
}

UPDATE 2 - IMPORTANT

onBindViewHolder method is called multiple times, and also every time the user scrolls the view out of sight and back in sight! This will cause the same view to be added to the list multiple times which may cause problems and minor delay in code executions!

To fix this, change

cardViewList.add(holder.cardView);

to

if (!cardViewList.contains(holder.cardView)) {
    cardViewList.add(holder.cardView);
}

FULL OUTER JOIN vs. FULL JOIN

Actually they are the same. LEFT OUTER JOIN is same as LEFT JOIN and RIGHT OUTER JOIN is same as RIGHT JOIN. It is more informative way to compare from INNER Join.

See this Wikipedia article for details.

Where does gcc look for C and C++ header files?

You can create a file that attempts to include a bogus system header. If you run gcc in verbose mode on such a source, it will list all the system include locations as it looks for the bogus header.

$ echo "#include <bogus.h>" > t.c; gcc -v t.c; rm t.c

[..]

#include "..." search starts here:
#include <...> search starts here:
 /usr/local/include
 /usr/lib/gcc/i686-apple-darwin9/4.0.1/include
 /usr/include
 /System/Library/Frameworks (framework directory)
 /Library/Frameworks (framework directory)
End of search list.

[..]

t.c:1:32: error: bogus.h: No such file or directory

Is it possible to declare two variables of different types in a for loop?

C++17: Yes! You should use a structured binding declaration. The syntax has been supported in gcc and clang since gcc-7 and clang-4.0 (clang live example). This allows us to unpack a tuple like so:

for (auto [i, f, s] = std::tuple{1, 1.0, std::string{"ab"}}; i < N; ++i, f += 1.5) {
    // ...
}

The above will give you:

  • int i set to 1
  • double f set to 1.0
  • std::string s set to "ab"

Make sure to #include <tuple> for this kind of declaration.

You can specify the exact types inside the tuple by typing them all out as I have with the std::string, if you want to name a type. For example:

auto [vec, i32] = std::tuple{std::vector<int>{3, 4, 5}, std::int32_t{12}}

A specific application of this is iterating over a map, getting the key and value,

std::unordered_map<K, V> m = { /*...*/ };
for (auto& [key, value] : m) {
   // ...
}

See a live example here


C++14: You can do the same as C++11 (below) with the addition of type-based std::get. So instead of std::get<0>(t) in the below example, you can have std::get<int>(t).


C++11: std::make_pair allows you to do this, as well as std::make_tuple for more than two objects.

for (auto p = std::make_pair(5, std::string("Hello World")); p.first < 10; ++p.first) {
    std::cout << p.second << std::endl;
}

std::make_pair will return the two arguments in a std::pair. The elements can be accessed with .first and .second.

For more than two objects, you'll need to use a std::tuple

for (auto t = std::make_tuple(0, std::string("Hello world"), std::vector<int>{});
        std::get<0>(t) < 10;
        ++std::get<0>(t)) {
    std::cout << std::get<1>(t) << std::endl; // cout Hello world
    std::get<2>(t).push_back(std::get<0>(t)); // add counter value to the vector
}

std::make_tuple is a variadic template that will construct a tuple of any number of arguments (with some technical limitations of course). The elements can be accessed by index with std::get<INDEX>(tuple_object)

Within the for loop bodies you can easily alias the objects, though you still need to use .first or std::get for the for loop condition and update expression

for (auto t = std::make_tuple(0, std::string("Hello world"), std::vector<int>{});
        std::get<0>(t) < 10;
        ++std::get<0>(t)) {
    auto& i = std::get<0>(t);
    auto& s = std::get<1>(t);
    auto& v = std::get<2>(t);
    std::cout << s << std::endl; // cout Hello world
    v.push_back(i); // add counter value to the vector
}

C++98 and C++03 You can explicitly name the types of a std::pair. There is no standard way to generalize this to more than two types though:

for (std::pair<int, std::string> p(5, "Hello World"); p.first < 10; ++p.first) {
    std::cout << p.second << std::endl;
}

How do I list / export private keys from a keystore?

If you don't need to do it programatically, but just want to manage your keys, then I've used IBM's free KeyMan tool for a long time now. Very nice for exporting a private key to a PFX file (then you can easily use OpenSSL to manipulate it, extract it, change pwds, etc).

https://www.ibm.com/developerworks/mydeveloperworks/groups/service/html/communityview?communityUuid=6fb00498-f6ea-4f65-bf0c-adc5bd0c5fcc

Select your keystore, select the private key entry, then File->Save to a pkcs12 file (*.pfx, typically). You can then view the contents with:

$ openssl pkcs12 -in mykeyfile.pfx -info

Compare and contrast REST and SOAP web services?

SOAP uses WSDL for communication btw consumer and provider, whereas REST just uses XML or JSON to send and receive data

WSDL defines contract between client and service and is static by its nature. In case of REST contract is somewhat complicated and is defined by HTTP, URI, Media Formats and Application Specific Coordination Protocol. It's highly dynamic unlike WSDL.

SOAP doesn't return human readable result, whilst REST result is readable with is just plain XML or JSON

This is not true. Plain XML or JSON are not RESTful at all. None of them define any controls(i.e. links and link relations, method information, encoding information etc...) which is against REST as far as messages must be self contained and coordinate interaction between agent/client and service.

With links + semantic link relations clients should be able to determine what is next interaction step and follow these links and continue communication with service.

It is not necessary that messages be human readable, it's possible to use cryptic format and build perfectly valid REST applications. It doesn't matter whether message is human readable or not.

Thus, plain XML(application/xml) or JSON(application/json) are not sufficient formats for building REST applications. It's always reasonable to use subset of these generic media types which have strong semantic meaning and offer enough control information(links etc...) to coordinate interactions between client and server.

REST is over only HTTP

Not true, HTTP is most widely used and when we talk about REST web services we just assume HTTP. HTTP defines interface with it's methods(GET, POST, PUT, DELETE, PATCH etc) and various headers which can be used uniformly for interacting with resources. This uniformity can be achieved with other protocols as well.

P.S. Very simple, yet very interesting explanation of REST: http://www.looah.com/source/view/2284

How to sort a HashSet?

1. Add all set element in list -> al.addAll(s);
2. Sort all the elements in list using -> Collections.sort(al);


 public class SortSetProblem {
 public static void main(String[] args) {
    ArrayList<String> al = new ArrayList();
    Set<String> s = new HashSet<>();
    s.add("ved");
    s.add("prakash");
    s.add("sharma");
    s.add("apple");
    s.add("ved");
    s.add("banana");
    System.out.println("Before Sorting");
    for (String s1 : s) {
        System.out.print("  " + s1);
    }

    System.out.println("After Sorting");
    al.addAll(s);
    Collections.sort(al);
    for (String set : al) {
        System.out.print(" " + set);
    }
  }
 }

input - ved prakash sharma apple ved banana

Output - apple banana prakash sharma ved

How to change package name in flutter?

Change App Package Name easily using change_app_package_name package

just add the above package in dev dependencies

dev_dependencies:
  flutter_test:
    sdk: flutter
  change_app_package_name: ^0.1.2

and run the following command, replace "com.new.package.name" with your new package name

flutter pub run change_app_package_name:main com.new.package.name

Package Link on Pub Dev

screenshot of Package

How to build a Debian/Ubuntu package from source?

For what you want to do, you probably want to use the debian source diff, so your package is similar to the official one apart from the upstream version used. You can download the source diff from packages.debian.org, or can get it along with the .dsc and the original source archive by using "apt-get source".

Then you unpack your new version of the upstream source, change into that directory, and apply the diff you downloaded by doing

zcat ~/downloaded.diff.gz | patch -p1
chmod +x debian/rules

Then make the changes you wanted to compile options, and build the package by doing

dpkg-buildpackage -rfakeroot -us -uc

LINQ Inner-Join vs Left-Join

I think if you want to use extension methods you need to use the GroupJoin

var query =
    people.GroupJoin(pets,
                     person => person,
                     pet => pet.Owner,
                     (person, petCollection) =>
                        new { OwnerName = person.Name,
                              Pet = PetCollection.Select( p => p.Name )
                                                 .DefaultIfEmpty() }
                    ).ToList();

You may have to play around with the selection expression. I'm not sure it would give you want you want in the case where you have a 1-to-many relationship.

I think it's a little easier with the LINQ Query syntax

var query = (from person in context.People
             join pet in context.Pets on person equals pet.Owner
             into tempPets
             from pets in tempPets.DefaultIfEmpty()
             select new { OwnerName = person.Name, Pet = pets.Name })
            .ToList();

Read user input inside a loop

echo "Enter the Programs you want to run:"
> ${PROGRAM_LIST}
while read PROGRAM_ENTRY
do
   if [ ! -s ${PROGRAM_ENTRY} ]
   then
      echo ${PROGRAM_ENTRY} >> ${PROGRAM_LIST}
   else
      break
   fi
done

Converting PKCS#12 certificate into PEM using OpenSSL

There is a free and open-source GUI tool KeyStore Explorer to work with crypto key containers. Using it you can export a certificate or private key into separate files or convert the container into another format (jks, pem, p12, pkcs12, etc)

enter image description here

access denied for user @ 'localhost' to database ''

Try this: Adding users to MySQL

You need grant privileges to the user if you want external acess to database(ie. web pages).

Best way to strip punctuation from a string

>>> s = "string. With. Punctuation?"
>>> s = re.sub(r'[^\w\s]','',s)
>>> re.split(r'\s*', s)


['string', 'With', 'Punctuation']

How to create a label inside an <input> element?

<input name="searchbox" onfocus="if (this.value=='search') this.value = ''" onblur="if (this.value=='') this.value = 'search'" type="text" value="search">

Add an onblur event too.

What does 'stale file handle' in Linux mean?

When the directory is deleted, the inode for that directory (and the inodes for its contents) are recycled. The pointer your shell has to that directory's inode (and its contents's inodes) are now no longer valid. When the directory is restored from backup, the old inodes are not (necessarily) reused; the directory and its contents are stored on random inodes. The only thing that stays the same is that the parent directory reuses the same name for the restored directory (because you told it to).

Now if you attempt to access the contents of the directory that your original shell is still pointing to, it communicates that request to the file system as a request for the original inode, which has since been recycled (and may even be in use for something entirely different now). So you get a stale file handle message because you asked for some nonexistent data.

When you perform a cd operation, the shell reevaluates the inode location of whatever destination you give it. Now that your shell knows the new inode for the directory (and the new inodes for its contents), future requests for its contents will be valid.

Git vs Team Foundation Server

If your team uses TFS and you want to use Git you might want to consider a "git to tfs" bridge. Essentially you work day to day using Git on your computer, then when you want to push your changes you push them to the TFS server.

There are a couple out there (on github). I used one at my last place (along with another developer) with some success. See:

https://github.com/spraints/git-tfs

https://github.com/git-tfs/git-tfs

While loop in batch

I have a trick for doing this!

I came up with this method because while on the CLI, it's not possible to use the methods provided in the other answers here and it had always bugged me.

I call this the "Do Until Break" or "Infinite" Loop:

Basic Example

FOR /L %L IN (0,0,1) DO @(
 ECHO. Counter always 0, See "%L" = "0" - Waiting a split second&ping -n 1 127.0.0.1>NUL )

This is truly an infinite loop!

This is useful for monitoring something in a CMD window, and allows you to use CTRL+C to break it when you're done.

Want to Have a counter?

Either use SET /A OR You can modify the FOR /L Loop to do the counting and still be infinite (Note, BOTH of these methods have a 32bit integer overflow)

SET /A Method:

FOR /L %L IN (0,0,1) DO @(
 SET /A "#+=1"&ECHO. L Still equals 0, See "%L = 0"!  - Waiting a split second &ping -n 1 127.0.0.1>NUL  )

Native FOR /L Counter:

FOR /L %L IN (-2147483648,1,2147483648) DO @(
 ECHO.Current value of L: %L - Waiting a split second &ping -n 1 127.0.0.1>NUL  )

Counting Sets of 4294967295 and Showing Current Value of L:

FOR /L %L IN (1,1,2147483648) DO @(
 (
  IF %L EQU 0 SET /A "#+=1">NUL
 )&SET /A "#+=0"&ECHO. Sets of 4294967295 - Current value of L: %L - Waiting a split second &ping -n 1 127.0.0.1>NUL )

However, what if:

  • You're interested in reviewing the output of the monitor, and concerned that I will pass the 9999 line buffer limit before I check it after it has completed.
  • You'd like to take some additional actions once the Thing I am monitoring is finished.

For this, I determined how to use a couple methods to break the FOR Loop prematurely effectively turning it into a "DO WHILE" or "DO UNTIL" Loop, which is otherwise sorely lacking in CMD.

NOTE: Most of the time a loop will continue to iterate past the condition you checked for, often this is a wanted behavior, but not in our case.

Turn the "infinite Loop" into a "DO WHILE" / "DO UNTIL" Loop

UPDATE: Due to wanting to use this code in CMD Scripts (and have them persist!) as well as CLI, and on thinking if there might be a "more Correct" method to achieve this I recommend using the New method!

New Method (Can be used inside CMD Scripts without exiting the script):

FOR /F %%A IN ('
  CMD /C "FOR /L %%L IN (0,1,2147483648) DO @( ECHO.%%L & IF /I %%L EQU 10 ( exit /b  ) )"
') DO @(
  ECHO %%~A
)

At CLI:

FOR /F %A IN ('
  CMD /C "FOR /L %L IN (0,1,2147483648) DO @( ECHO.%L & IF /I %L EQU 10 ( exit /b  ) )"
') DO @(
  ECHO %~A
)

Original Method (Will work on CLI just fine, but will kill a script.)

FOR /L %L IN (0,1,2147483648) DO @(
  ECHO.Current value of L: %L - Waiting a split second &ping -n 1 127.0.0.1>NUL&(
    IF /I %L EQU 10 (
      ECHO.Breaking the Loop! Because We have matched the condition!&DIR >&0
    )
  )
) 2>NUL

Older Post Stuff

Through chance I had hit upon some ways to exit loops prematurely that did not close the CMD prompt when trying to do other things which gave me this Idea.

NOTE:

While ECHO.>&3 >NUL had worked for me in some scenarios, I have played with this off and on over the years and found that DIR >&0 >NUL was much more consistent.

I am re-writing this answer from here forward to use that method instead as I recently found the old note to myself to use this method instead.

Edited Post with better Method Follows:

DIR >&0 >NUL

The >NUL is optional, I just prefer not to have it output the error.

I prefer to match inLine when possible, as you can see in this sanitized example of a Command I use to monitor LUN Migrations on our VNX.

for /l %L IN (0,0,1) DO @(
   ECHO.& ECHO.===========================================& (
     [VNX CMD] | FINDSTR /R /C:"Source LU Name" /C:"State:" /C:"Time " || DIR >&0 >NUL
   ) & Ping -n 10 1.1.1.1 -w 1000>NUL )

Also, I have another method I found in that note to myself which I just re-tested to confirm works just as well at the CLI as the other method.

Apparently, when I first posted here I posted an older iteration I was playing with instead of the two newer ones which work better:

In this method, we use EXIT /B to exit the For Loop, but we don't want to exit the CLI so we wrap it in a CMD session:

FOR /F %A IN ('CMD /C "FOR /L %L IN (0,1,10000000) DO @( ECHO.%L & IF /I %L EQU 10 ( exit /b  ) )" ') DO @(ECHO %~A)

Because the loop itself happens in the CMD session, we can use EXIT /B to exit the iteration of the loop without losing our CMD Session, and without waiting for the loop to complete, much the same as with the other method.

I would go so far as to say that this method is likely the "intended" method for the sort of scenario where you want to break a for loop at the CLI, as using CMD session is also the only way to get Delayed expansion working at the CLI for your loops, and the behavior and such behavior is clearly an intended workflow to leave a CMD session.

IE: Microsoft clearly made an intentional effort to have CMD Exit /B For loops behave this way, while the "Intended" way of doing this, as my other method, relies on having accidentally created just the right error to kick you out of the loop without letting the loop finish processing, which I only happenstantially discovered, and seems to only reliably work when using the DIR command which is fairly strange.

So that said, I think it's probably a better practice to use Method 2:

FOR /F %A IN ('CMD /C "FOR /L %L IN (0,1,10000000) DO @( ECHO.%L & IF /I %L EQU 10 ( exit /b  ) )" ') DO @(ECHO %~A)

Although I suspect Method 1 is going to be slightly faster:

FOR /L %L IN (0,1,10000000) DO @( ECHO.%L & IF /I %L EQU 10 ( DIR >&) >NUL ) )

And in either case, both should allow DO-While loops as you need for your purposes.

Compare DATETIME and DATE ignoring time portion

You can try this one

CONVERT(DATE, GETDATE()) = CONVERT(DATE,'2017-11-16 21:57:20.000')

I test that for MS SQL 2014 by following code

select case when CONVERT(DATE, GETDATE()) = CONVERT(DATE,'2017-11-16 21:57:20.000') then 'ok'
            else '' end

What does auto do in margin:0 auto?

From the CSS specification on Calculating widths and margins for Block-level, non-replaced elements in normal flow:

If both 'margin-left' and 'margin-right' are 'auto', their used values are equal. This horizontally centers the element with respect to the edges of the containing block.

Sum all the elements java arraylist

Two ways:

Use indexes:

double sum = 0;
for(int i = 0; i < m.size(); i++)
    sum += m.get(i);
return sum;

Use the "for each" style:

double sum = 0;
for(Double d : m)
    sum += d;
return sum;

PySpark: withColumn() with two conditions and three outcomes

There are a few efficient ways to implement this. Let's start with required imports:

from pyspark.sql.functions import col, expr, when

You can use Hive IF function inside expr:

new_column_1 = expr(
    """IF(fruit1 IS NULL OR fruit2 IS NULL, 3, IF(fruit1 = fruit2, 1, 0))"""
)

or when + otherwise:

new_column_2 = when(
    col("fruit1").isNull() | col("fruit2").isNull(), 3
).when(col("fruit1") == col("fruit2"), 1).otherwise(0)

Finally you could use following trick:

from pyspark.sql.functions import coalesce, lit

new_column_3 = coalesce((col("fruit1") == col("fruit2")).cast("int"), lit(3))

With example data:

df = sc.parallelize([
    ("orange", "apple"), ("kiwi", None), (None, "banana"), 
    ("mango", "mango"), (None, None)
]).toDF(["fruit1", "fruit2"])

you can use this as follows:

(df
    .withColumn("new_column_1", new_column_1)
    .withColumn("new_column_2", new_column_2)
    .withColumn("new_column_3", new_column_3))

and the result is:

+------+------+------------+------------+------------+
|fruit1|fruit2|new_column_1|new_column_2|new_column_3|
+------+------+------------+------------+------------+
|orange| apple|           0|           0|           0|
|  kiwi|  null|           3|           3|           3|
|  null|banana|           3|           3|           3|
| mango| mango|           1|           1|           1|
|  null|  null|           3|           3|           3|
+------+------+------------+------------+------------+

text box input height

Use CSS:

<input type="text" class="bigText"  name=" item" align="left" />

.bigText {
    height:30px;
}

Dreamweaver is a poor testing tool. It is not a browser.

.war vs .ear file

To make the project transport, deployment made easy. need to compressed into one file. JAR (java archive) group of .class files

WAR (web archive) - each war represents one web application - use only web related technologies like servlet, jsps can be used. - can run on Tomcat server - web app developed by web related technologies only jsp servlet html js - info representation only no transactions.

EAR (enterprise archive) - each ear represents one enterprise application - we can use anything from j2ee like ejb, jms can happily be used. - can run on Glassfish like server not on Tomcat server. - enterprise app devloped by any technology anything from j2ee like all web app plus ejbs jms etc. - does transactions with info representation. eg. Bank app, Telecom app

SASS and @font-face

For those looking for an SCSS mixin instead, including woff2:

@mixin fface($path, $family, $type: '', $weight: 400, $svg: '', $style: normal) {
  @font-face {
    font-family: $family;
    @if $svg == '' {
      // with OTF without SVG and EOT
      src: url('#{$path}#{$type}.otf') format('opentype'), url('#{$path}#{$type}.woff2') format('woff2'), url('#{$path}#{$type}.woff') format('woff'), url('#{$path}#{$type}.ttf') format('truetype');
    } @else {
      // traditional src inclusions
      src: url('#{$path}#{$type}.eot');
      src: url('#{$path}#{$type}.eot?#iefix') format('embedded-opentype'), url('#{$path}#{$type}.woff2') format('woff2'), url('#{$path}#{$type}.woff') format('woff'), url('#{$path}#{$type}.ttf') format('truetype'), url('#{$path}#{$type}.svg##{$svg}') format('svg');
    }
    font-weight: $weight;
    font-style: $style;
  }
}
// ========================================================importing
$dir: '/assets/fonts/';
$famatic: 'AmaticSC';
@include fface('#{$dir}amatic-sc-v11-latin-regular', $famatic, '', 400, $famatic);

$finter: 'Inter';
// adding specific types of font-weights
@include fface('#{$dir}#{$finter}', $finter, '-Thin-BETA', 100);
@include fface('#{$dir}#{$finter}', $finter, '-Regular', 400);
@include fface('#{$dir}#{$finter}', $finter, '-Medium', 500);
@include fface('#{$dir}#{$finter}', $finter, '-Bold', 700);
// ========================================================usage
.title {
  font-family: Inter;
  font-weight: 700; // Inter-Bold font is loaded
}
.special-title {
  font-family: AmaticSC;
  font-weight: 700; // default font is loaded
}

The $type parameter is useful for stacking related families with different weights.

The @if is due to the need of supporting the Inter font (similar to Roboto), which has OTF but doesn't have SVG and EOT types at this time.

If you get a can't resolve error, remember to double check your fonts directory ($dir).

How do I clear the content of a div using JavaScript?

You can do it the DOM way as well:

var div = document.getElementById('cart_item');
while(div.firstChild){
    div.removeChild(div.firstChild);
}

How to find a min/max with Ruby

You can do

[5, 10].min

or

[4, 7].max

They come from the Enumerable module, so anything that includes Enumerable will have those methods available.

v2.4 introduces own Array#min and Array#max, which are way faster than Enumerable's methods because they skip calling #each.

@nicholasklick mentions another option, Enumerable#minmax, but this time returning an array of [min, max].

[4, 5, 7, 10].minmax
=> [4, 10]

How to create a zip file in Java

Java 7 has ZipFileSystem built in, that can be used to create, write and read file from zip file.

Java Doc: ZipFileSystem Provider

Map<String, String> env = new HashMap<>();
// Create the zip file if it doesn't exist
env.put("create", "true");

URI uri = URI.create("jar:file:/codeSamples/zipfs/zipfstest.zip");

try (FileSystem zipfs = FileSystems.newFileSystem(uri, env)) {
    Path externalTxtFile = Paths.get("/codeSamples/zipfs/SomeTextFile.txt");
    Path pathInZipfile = zipfs.getPath("/SomeTextFile.txt");          
    // Copy a file into the zip file
    Files.copy(externalTxtFile, pathInZipfile, StandardCopyOption.REPLACE_EXISTING); 
}

What are some resources for getting started in operating system development?

When I started working on my basic operating systems I needed a basic guide like Stepping stones for a basic operating system. It helped me not loose my head.

That if you want to make it from absolutely nothing (pure assembly code)

Android toolbar center title and custom font

I solved this solution , And this is a following codes:

<android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Order History"
            android:layout_gravity="center"
            android:id="@+id/toolbar_title"
            android:textSize="17sp"
            android:textStyle="bold"
            android:textColor="@color/colorWhite"
            />

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

And you can change title/label , in Activity, write a below codes:

Toolbar toolbarTop = (Toolbar) findViewById(R.id.toolbar_top);

TextView mTitle = (TextView) toolbarTop.findViewById(R.id.toolbar_title); mTitle.setText("@string/....");

How using try catch for exception handling is best practice

The better approach is the second one (the one in which you specify the exception type). The advantage of this is that you know that this type of exception can occur in your code. You are handling this type of exception and you can resume. If any other exception came, then that means something is wrong which will help you find bugs in your code. The application will eventually crash, but you will come to know that there is something you missed (bug) which needs to be fixed.

Convert JS object to JSON string

Use the JSON.stringify() method:

const stringified = JSON.stringify({})  // pass object you want to convert in string format

How can I create tests in Android Studio?

Edit: As of 0.1.8 this is now supported in the IDE. Please follow the instructions in there, instead of using the instructions below.

Following the Android Gradle Plugin User Guide I was able to get tests working on the command line by performing the following steps on a newly created project (I used the default 'com.example.myapplication' package):

  1. Add a src/instrumentTest/java directory for the tests
  2. Add a test class (extending ActivityTestCase) in the package com.example.myapplication.test
  3. Start a virtual device
  4. On the command line (in the MyApplicationProject/MyApplication directory) use the command '../gradlew connectedInstrumentTest'

This ran my tests and placed the test results in MyApplicationProject/MyApplication/build/reports/instrumentTests/connected. I'm new to testing Android apps, but it seem to work fine.

From within the IDE, it's possible to try and run the same test class. You'll need to

  1. Update build.gradle to list Maven Central as a repo
  2. Update build.gradle add JUnit 3.8 as a instrumentTestCompile dependency e.g. instrumentTestCompile 'junit:junit:3.8'
  3. In 'Project Structure' manually move JUnit to be first in the dependency order

However this fails (the classpath used when running the tests is missing the test output directory). However, I'm not sure that this would work regardless as it's my understanding that an Android specific test runner is required.

Change bootstrap datepicker date format on select

  $(function () {
    $('.datetimepicker').datetimepicker(
      {
        format: 'Y-m-d h:m:s'
     }
    );
 });`

Arduino Nano - "avrdude: ser_open():system can't open device "\\.\COM1": the system cannot find the file specified"

Instead of changing the COM port in Device manager, if you're using the Arduino software, I had to set the port in Tools > Port menu.

enter image description here

Setting a property by reflection with a string value

You can use a type converter (no error checking):

Ship ship = new Ship();
string value = "5.5";
var property = ship.GetType().GetProperty("Latitude");
var convertedValue = property.Converter.ConvertFrom(value);
property.SetValue(self, convertedValue);

In terms of organizing the code, you could create a kind-of mixin that would result in code like this:

Ship ship = new Ship();
ship.SetPropertyAsString("Latitude", "5.5");

This would be achieved with this code:

public interface MPropertyAsStringSettable { }
public static class PropertyAsStringSettable {
  public static void SetPropertyAsString(
    this MPropertyAsStringSettable self, string propertyName, string value) {
    var property = TypeDescriptor.GetProperties(self)[propertyName];
    var convertedValue = property.Converter.ConvertFrom(value);
    property.SetValue(self, convertedValue);
  }
}

public class Ship : MPropertyAsStringSettable {
  public double Latitude { get; set; }
  // ...
}

MPropertyAsStringSettable can be reused for many different classes.

You can also create your own custom type converters to attach to your properties or classes:

public class Ship : MPropertyAsStringSettable {
  public Latitude Latitude { get; set; }
  // ...
}

[TypeConverter(typeof(LatitudeConverter))]
public class Latitude { ... }

Set default heap size in Windows

Try setting a Windows System Environment variable called _JAVA_OPTIONS with the heap size you want. Java should be able to find it and act accordingly.

iPhone 6 Plus resolution confusion: Xcode or Apple's website? for development

Check out this infographic: http://www.paintcodeapp.com/news/iphone-6-screens-demystified

It explains the differences between old iPhones, iPhone 6 and iPhone 6 Plus. You can see comparison of screen sizes in points, rendered pixels and physical pixels. You will also find answer to your question there:

iPhone 6 Plus - with Retina display HD. Scaling factor is 3 and the image is afterwards downscaled from rendered 2208 × 1242 pixels to 1920 × 1080 pixels.

The downscaling ratio is 1920 / 2208 = 1080 / 1242 = 20 / 23. That means every 23 pixels from the original render have to be mapped to 20 physical pixels. In other words the image is scaled down to approximately 87% of its original size.

Update:

There is an updated version of infographic mentioned above. It contains more detailed info about screen resolution differences and it covers all iPhone models so far, including 4 inch devices.

http://www.paintcodeapp.com/news/ultimate-guide-to-iphone-resolutions

Reverse each individual word of "Hello World" string with Java

    String input = "Hello World!";

    String temp = "";
    String result = "";

    for (int i = 0; i <= input.length(); i++) {
        if (i != input.length() && input.charAt(i) != ' ') {
            temp = input.charAt(i) + temp;
        } else {
            result = temp + " " + result;
            temp = "";
        }
    }

    System.out.println("the result is: " + result);