Programs & Examples On #Alt.net

How to run a shell script on a Unix console or Mac terminal?

To run a non-executable sh script, use:

sh myscript

To run a non-executable bash script, use:

bash myscript

To start an executable (which is any file with executable permission); you just specify it by its path:

/foo/bar
/bin/bar
./bar

To make a script executable, give it the necessary permission:

chmod +x bar
./bar

When a file is executable, the kernel is responsible for figuring out how to execte it. For non-binaries, this is done by looking at the first line of the file. It should contain a hashbang:

#! /usr/bin/env bash

The hashbang tells the kernel what program to run (in this case the command /usr/bin/env is ran with the argument bash). Then, the script is passed to the program (as second argument) along with all the arguments you gave the script as subsequent arguments.

That means every script that is executable should have a hashbang. If it doesn't, you're not telling the kernel what it is, and therefore the kernel doesn't know what program to use to interprete it. It could be bash, perl, python, sh, or something else. (In reality, the kernel will often use the user's default shell to interprete the file, which is very dangerous because it might not be the right interpreter at all or it might be able to parse some of it but with subtle behavioural differences such as is the case between sh and bash).

A note on /usr/bin/env

Most commonly, you'll see hash bangs like so:

#!/bin/bash

The result is that the kernel will run the program /bin/bash to interpret the script. Unfortunately, bash is not always shipped by default, and it is not always available in /bin. While on Linux machines it usually is, there are a range of other POSIX machines where bash ships in various locations, such as /usr/xpg/bin/bash or /usr/local/bin/bash.

To write a portable bash script, we can therefore not rely on hard-coding the location of the bash program. POSIX already has a mechanism for dealing with that: PATH. The idea is that you install your programs in one of the directories that are in PATH and the system should be able to find your program when you want to run it by name.

Sadly, you cannot just do this:

#!bash

The kernel won't (some might) do a PATH search for you. There is a program that can do a PATH search for you, though, it's called env. Luckily, nearly all systems have an env program installed in /usr/bin. So we start env using a hardcoded path, which then does a PATH search for bash and runs it so that it can interpret your script:

#!/usr/bin/env bash

This approach has one downside: According to POSIX, the hashbang can have one argument. In this case, we use bash as the argument to the env program. That means we have no space left to pass arguments to bash. So there's no way to convert something like #!/bin/bash -exu to this scheme. You'll have to put set -exu after the hashbang instead.

This approach also has another advantage: Some systems may ship with a /bin/bash, but the user may not like it, may find it's buggy or outdated, and may have installed his own bash somewhere else. This is often the case on OS X (Macs) where Apple ships an outdated /bin/bash and users install an up-to-date /usr/local/bin/bash using something like Homebrew. When you use the env approach which does a PATH search, you take the user's preference into account and use his preferred bash over the one his system shipped with.

Convert nested Python dict to object?

How about this:

from functools import partial
d2o=partial(type, "d2o", ())

This can then be used like this:

>>> o=d2o({"a" : 5, "b" : 3})
>>> print o.a
5
>>> print o.b
3

Xcode 6: Keyboard does not show up in simulator

While testing in the ios8 beta simulator, you may toggle between the "software keyboard" and "hardware keyboard" with ?+K.

UPDATE: Since iOS Simulator 8.0, the shortcut is ?+?+K.

mongodb, replicates and error: { "$err" : "not master and slaveOk=false", "code" : 13435 }

To avoid typing rs.slaveOk() every time, do this:

Create a file named replStart.js, containing one line: rs.slaveOk()

Then include --shell replStart.js when you launch the Mongo shell. Of course, if you're connecting locally to a single instance, this doesn't save any typing.

Use HTML5 to resize an image before upload

if any interested I've made a typescript version:

interface IResizeImageOptions {
  maxSize: number;
  file: File;
}
const resizeImage = (settings: IResizeImageOptions) => {
  const file = settings.file;
  const maxSize = settings.maxSize;
  const reader = new FileReader();
  const image = new Image();
  const canvas = document.createElement('canvas');
  const dataURItoBlob = (dataURI: string) => {
    const bytes = dataURI.split(',')[0].indexOf('base64') >= 0 ?
        atob(dataURI.split(',')[1]) :
        unescape(dataURI.split(',')[1]);
    const mime = dataURI.split(',')[0].split(':')[1].split(';')[0];
    const max = bytes.length;
    const ia = new Uint8Array(max);
    for (var i = 0; i < max; i++) ia[i] = bytes.charCodeAt(i);
    return new Blob([ia], {type:mime});
  };
  const resize = () => {
    let width = image.width;
    let height = image.height;

    if (width > height) {
        if (width > maxSize) {
            height *= maxSize / width;
            width = maxSize;
        }
    } else {
        if (height > maxSize) {
            width *= maxSize / height;
            height = maxSize;
        }
    }

    canvas.width = width;
    canvas.height = height;
    canvas.getContext('2d').drawImage(image, 0, 0, width, height);
    let dataUrl = canvas.toDataURL('image/jpeg');
    return dataURItoBlob(dataUrl);
  };

  return new Promise((ok, no) => {
      if (!file.type.match(/image.*/)) {
        no(new Error("Not an image"));
        return;
      }

      reader.onload = (readerEvent: any) => {
        image.onload = () => ok(resize());
        image.src = readerEvent.target.result;
      };
      reader.readAsDataURL(file);
  })    
};

and here's the javascript result:

var resizeImage = function (settings) {
    var file = settings.file;
    var maxSize = settings.maxSize;
    var reader = new FileReader();
    var image = new Image();
    var canvas = document.createElement('canvas');
    var dataURItoBlob = function (dataURI) {
        var bytes = dataURI.split(',')[0].indexOf('base64') >= 0 ?
            atob(dataURI.split(',')[1]) :
            unescape(dataURI.split(',')[1]);
        var mime = dataURI.split(',')[0].split(':')[1].split(';')[0];
        var max = bytes.length;
        var ia = new Uint8Array(max);
        for (var i = 0; i < max; i++)
            ia[i] = bytes.charCodeAt(i);
        return new Blob([ia], { type: mime });
    };
    var resize = function () {
        var width = image.width;
        var height = image.height;
        if (width > height) {
            if (width > maxSize) {
                height *= maxSize / width;
                width = maxSize;
            }
        } else {
            if (height > maxSize) {
                width *= maxSize / height;
                height = maxSize;
            }
        }
        canvas.width = width;
        canvas.height = height;
        canvas.getContext('2d').drawImage(image, 0, 0, width, height);
        var dataUrl = canvas.toDataURL('image/jpeg');
        return dataURItoBlob(dataUrl);
    };
    return new Promise(function (ok, no) {
        if (!file.type.match(/image.*/)) {
            no(new Error("Not an image"));
            return;
        }
        reader.onload = function (readerEvent) {
            image.onload = function () { return ok(resize()); };
            image.src = readerEvent.target.result;
        };
        reader.readAsDataURL(file);
    });
};

usage is like:

resizeImage({
    file: $image.files[0],
    maxSize: 500
}).then(function (resizedImage) {
    console.log("upload resized image")
}).catch(function (err) {
    console.error(err);
});

or (async/await):

const config = {
    file: $image.files[0],
    maxSize: 500
};
const resizedImage = await resizeImage(config)
console.log("upload resized image")

Git: How to squash all commits on branch

In case you are okay with an answer involving another branch, try git checkout --orphan <new_branch> It allowed me to simply commit ALL files from previous branch as one commit.

This is something like a git merge squash but not quite the same.

Running java with JAVA_OPTS env variable has no effect

I don't know of any JVM that actually checks the JAVA_OPTS environment variable. Usually this is used in scripts which launch the JVM and they usually just add it to the java command-line.

The key thing to understand here is that arguments to java that come before the -jar analyse.jar bit will only affect the JVM and won't be passed along to your program. So, modifying the java line in your script to:

java $JAVA_OPTS -jar analyse.jar $*

Should "just work".

How do I set combobox read-only or user cannot write in a combo box only can select the given items?

Make the DropDownStyle to DropDownList

stateComboBox.DropDownStyle = ComboBoxStyle.DropDownList;

How to disable postback on an asp Button (System.Web.UI.WebControls.Button)

You don't say which version of the .NET framework you are using.

If you are using v2.0 or greater you could use the OnClientClick property to execute a Javascript function when the button's onclick event is raised.

All you have to do to prevent a server postback occuring is return false from the called JavaScript function.

No process is on the other end of the pipe (SQL Server 2012)

The server was set to Windows Authentication only by default. There isn't any notification, that the origin of the errors is that, so it's hard to figure it out. The SQL Management studio dont alert, even if you create a user with SQL Authentication only.

So the answer is: Switch from Windows to SQL Authentication:

  1. Right click on the server name and select properties;
  2. Select security tab;
  3. Enable the SQL Server and Windows Authentication mode;
  4. Restart the SQL Server service.

You can now connect with your login/password.

How to reset (clear) form through JavaScript?

form.reset() is a DOM element method (not one on the jQuery object), so you need:

$("#client.frm")[0].reset();
//faster version:
$("#client")[0].reset();

Or without jQuery:

document.getElementById("client").reset();

How to select the first element of a set with JSTL?

Since i have have just one element in my Set the order is not important So I can access to the first element like this :

${ attachments.iterator().next().id }

Rails: How to list database tables/objects using the Rails console?

Its a start, it can list:

models = Dir.new("#{RAILS_ROOT}/app/models").entries

Looking some more...

Why do we need virtual functions in C++?

Why do we need Virtual Methods in C++?

Quick Answer:

  1. It provides us with one of the needed "ingredients"1 for object oriented programming.

In Bjarne Stroustrup C++ Programming: Principles and Practice, (14.3):

The virtual function provides the ability to define a function in a base class and have a function of the same name and type in a derived class called when a user calls the base class function. That is often called run-time polymorphism, dynamic dispatch, or run-time dispatch because the function called is determined at run time based on the type of the object used.

  1. It is the fastest more efficient implementation if you need a virtual function call 2.

To handle a virtual call, one needs one or more pieces of data related to the derived object 3. The way that is usually done is to add the address of table of functions. This table is usually referred to as virtual table or virtual function table and its address is often called the virtual pointer. Each virtual function gets a slot in the virtual table. Depending of the caller's object (derived) type, the virtual function, in its turn, invokes the respective override.


1.The use of inheritance, run-time polymorphism, and encapsulation is the most common definition of object-oriented programming.

2. You can't code functionality to be any faster or to use less memory using other language features to select among alternatives at run time. Bjarne Stroustrup C++ Programming: Principles and Practice.(14.3.1).

3. Something to tell which function is really invoked when we call the base class containing the virtual function.

Passing struct to function

You need to specify a type on person:

void addStudent(struct student person) {
...
}

Also, you can typedef your struct to avoid having to type struct every time you use it:

typedef struct student{
...
} student_t;

void addStudent(student_t person) {
...
}

How to change a single value in a NumPy array?

Is this what you are after? Just index the element and assign a new value.

A[2,1]=150

A
Out[345]: 
array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 150, 11, 12],
       [13, 14, 15, 16]])

Codeigniter: does $this->db->last_query(); execute a query?

The query execution happens on all get methods like

$this->db->get('table_name');
$this->db->get_where('table_name',$array);

While last_query contains the last query which was run

$this->db->last_query();

If you want to get query string without execution you will have to do this. Go to system/database/DB_active_rec.php Remove public or protected keyword from these functions

public function _compile_select($select_override = FALSE)
public function _reset_select()

Now you can write query and get it in a variable

$this->db->select('trans_id');
$this->db->from('myTable');
$this->db->where('code','B');
$subQuery = $this->db->_compile_select();

Now reset query so if you want to write another query the object will be cleared.

$this->db->_reset_select();

And the thing is done. Cheers!!! Note : While using this way you must use

$this->db->from('myTable')

instead of

$this->db->get('myTable')

which runs the query.

Take a look at this example

How to get just the parent directory name of a specific file

If you have just String path and don't want to create new File object you can use something like:

public static String getParentDirPath(String fileOrDirPath) {
    boolean endsWithSlash = fileOrDirPath.endsWith(File.separator);
    return fileOrDirPath.substring(0, fileOrDirPath.lastIndexOf(File.separatorChar, 
            endsWithSlash ? fileOrDirPath.length() - 2 : fileOrDirPath.length() - 1));
}

How do I get an Excel range using row and column numbers in VSTO / C#?

UsedRange work fine with "virgins" cells, but if your cells are filled in the past, then UsedRange will deliver to you the old value.

For example:

"Think in a Excel sheet that have cells A1 to A5 filled with text". In this scenario, UsedRange must be implemented as:

Long SheetRows;
SheetRows = ActiveSheet.UsedRange.Rows.Count;

A watch to SheetRows variable must display a value of 5 after the execution of this couple of lines.

Q1: But, what happen if the value of A5 is deleted?

A1: The value of SheetRows would be 5

Q2: Why this?

A2: Because MSDN define UsedRange property as:

Gets a Microsoft.Office.Interop.Excel.Range object that represents all the cells that have contained a value at any time.


So, the question is: Exist some/any workaround for this behavior?

I think in 2 alternatives:

  1. Avoid deleting the content of the cell, preferring deletion of the whole row (right click in the row number, then "delete row".
  2. Use CurrentRegion instead of UsedRange property as follow:

Long SheetRows;
SheetRows = ActiveSheet.Range("A1").CurrentRegion.Rows.Count;

HTTP Error 503. The service is unavailable. App pool stops on accessing website

For my situation is that my login password changed, while the application pool still uses the old one. So just click the "Advanced Settings" of your application pool and reset your "Identity".

href="file://" doesn't work

%20 is the space between AmberCRO SOP.

Try -

href="http://file:///K:/AmberCRO SOP/2011-07-05/SOP-SOP-3.0.pdf"

Or rename the folder as AmberCRO-SOP and write it as -

href="http://file:///K:/AmberCRO-SOP/2011-07-05/SOP-SOP-3.0.pdf"

Steps to upload an iPhone application to the AppStore

Apple provides detailed, illustrated instructions covering every step of the process. Log in to the iPhone developer site and click the "program portal" link. In the program portal you'll find a link to the program portal user's guide, which is a really good reference and guide on this topic.

Going through a text file line by line in C

In addition to the other answers, on a recent C library (Posix 2008 compliant), you could use getline. See this answer (to a related question).

Converting String To Float in C#

You can use parsing with double instead of float to get more precision value.

how to get date of yesterday using php?

Another OOP method for DateTime with setting the exact hour:

$yesterday = new DateTime("yesterday 09:00:59", new DateTimeZone('Europe/London'));
echo $yesterday->format('Y-m-d H:i:s') . "\n";

Extract time from date String

Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2010-07-14 09:00:02");
String time = new SimpleDateFormat("H:mm").format(date);

http://download.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html

How to replace all spaces in a string

Simple code for replace all spaces

var str = 'How are you';
var replaced = str.split(' ').join('');

Out put: Howareyou

HTML 5 Video "autoplay" not automatically starting in CHROME

Extremeandy has mentioned as of Chrome 66 autoplay video has been disabled.

After looking into this I found that muted videos are still able to be autoplayed. In my case the video didn't have any audio, but adding muted to the video tag has fixed it:

Hopefully this will help others also.

Organizing a multiple-file Go project

Let's explorer how the go get repository_remote_url command manages the project structure under $GOPATH. If we do a go get github.com/gohugoio/hugo It will clone the repository under

$GOPATH/src/repository_remote/user_name/project_name


$GOPATH/src/github.com/gohugoio/hugo

This is a nice way to create your initial project path. Now let's explorer what are the project types out there and how their inner structures are organized. All golang projects in the community can be categorized under

  • Libraries (no executable binaries)
  • Single Project (contains only 1 executable binary)
  • Tooling Projects (contains multiple executable binaries)

Generally golang project files can be packaged under any design principles such as DDD, POD

Most of the available go projects follows this Package Oriented Design

Package Oriented Design encourage the developer to keeps the implementation only inside it's own packages, other than the /internal package those packages can't can communicate with each other


Libraries

  • Projects such as database drivers, qt can put under this category.
  • Some libraries such as color, now follows a flat structure without any other packages.
  • Most of these library projects manages a package called internal.
  • /internal package is mainly used to hide the implementation from other projects.
  • Don't have any executable binaries, so no files that contains the main func.

 ~/$GOPATH/
    bin/
    pkg/
    src/
      repository_remote/
        user_name/
            project_name/
              internal/
              other_pkg/

Single Project

  • Projects such as hugo, etcd has a single main func in root level and.
  • Target is to generate one single binary

Tooling Projects

  • Projects such as kubernetes, go-ethereum has multiple main func organized under a package called cmd
  • cmd/ package manages the number of binaries (tools) that we want to build

 ~/$GOPATH/
    bin/
    pkg/
    src/
      repository_remote/
        user_name/
            project_name/
              cmd/
                binary_one/
                   main.go
                binary_two/
                   main.go
                binary_three/
                   main.go
              other_pkg/

Angular 2 @ViewChild annotation returns undefined

My solution to this was to replace *ngIf with [hidden]. Downside was all the child components were present in the code DOM. But worked for my requirements.

What processes are using which ports on unix?

Try pfiles PID to show all open files for a process.

How to uninstall Python 2.7 on a Mac OS X 10.6.4?

If you're thinking about manually removing Apple's default Python 2.7, I'd suggest you hang-fire and do-noting: Looks like Apple will very shortly do it for you:

Python 2.7 Deprecated in OSX 10.15 Catalina

Python 2.7- as well as Ruby & Perl- are deprecated in Catalina: (skip to section "Scripting Language Runtimes" > "Deprecations")

https://developer.apple.com/documentation/macos_release_notes/macos_catalina_10_15_release_notes

Apple To Remove Python 2.7 in OSX 10.16

Indeed, if you do nothing at all, according to The Mac Observer, by OSX version 10.16, Python 2.7 will disappear from your system:

https://www.macobserver.com/analysis/macos-catalina-deprecates-unix-scripting-languages/

Given this revelation, I'd suggest the best course of action is do nothing and wait for Apple to wipe it for you. As Apple is imminently about to remove it for you, doesn't seem worth the risk of tinkering with your Python environment.

NOTE: I see the question relates specifically to OSX v 10.6.4, but it appears this question has become a pivot-point for all OSX folks interested in removing Python 2.7 from their systems, whatever version they're running.

How to remove old and unused Docker images

The other answers are great, specifically:

docker system prune # doesn't clean out old images
docker system prune --all # cleans out too much

But I needed something in the middle of the two commands so the filter option was what I needed:

docker image prune --all --filter "until=4320h" # delete images older than 6 months ago; 4320h = 24 hour/day * 30 days/month * 6 months

Hope that helps :)

For reference: https://docs.docker.com/config/pruning/#prune-images

Sending emails in Node.js?

@JimBastard's accepted answer appears to be dated, I had a look and that mailer lib hasn't been touched in over 7 months, has several bugs listed, and is no longer registered in npm.

nodemailer certainly looks like the best option, however the url provided in other answers on this thread are all 404'ing.

nodemailer claims to support easy plugins into gmail, hotmail, etc. and also has really beautiful documentation.

std::cin input with spaces?

The Standard Library provides an input function called ws, which consumes whitespace from an input stream. You can use it like this:

std::string s;
std::getline(std::cin >> std::ws, s);

How to picture "for" loop in block representation of algorithm

The Algorithm for given flow chart :

enter image description here

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

Step :01

  • Start

Step :02 [Variable initialization]

  • Set counter: i<----K [Where K:Positive Number]

Step :03[Condition Check]

  • If condition True then Do your task, set i=i+N and go to Step :03 [Where N:Positive Number]
  • If condition False then go to Step :04

Step:04

  • Stop

How to cin to a vector

If you know the size use this

No temporary variable used just to store user input

int main()
{
    cout << "Hello World!\n"; 
    int n;//input size
    cin >> n;
    vector<int>a(n);
    for (int i = 0; i < n; i++) {
        cin >> a[i];
    }

//to verify output user input printed below

    for (auto x : a) {
        cout << x << " ";
    }
    return 0;
}

Intel X86 emulator accelerator (HAXM installer) VT/NX not enabled

You might be running an older version of Intel HAXM (or haven't installed it at all). Go to https://software.intel.com/en-us/android/articles/intel-hardware-accelerated-execution-manager and download/install the latest Intel HAXM package for MAC OS X.

EDIT: according to https://software.intel.com/en-us/forums/topic/506790 you should also make sure that Virtual PC/Parallel/VMWare is not running.

jQuery - Getting the text value of a table cell in the same row as a clicked element

This will also work

$(this).parent().parent().find('td').text()

How can I convert a comma-separated string to an array?

The split() method is used to split a string into an array of substrings, and returns the new array.

var array = string.split(',');

How do I encode and decode a base64 string?

A slight variation on andrew.fox answer, as the string to decode might not be a correct base64 encoded string:

using System;

namespace Service.Support
{
    public static class Base64
    {
        public static string ToBase64(this System.Text.Encoding encoding, string text)
        {
            if (text == null)
            {
                return null;
            }

            byte[] textAsBytes = encoding.GetBytes(text);
            return Convert.ToBase64String(textAsBytes);
        }

        public static bool TryParseBase64(this System.Text.Encoding encoding, string encodedText, out string decodedText)
        {
            if (encodedText == null)
            {
                decodedText = null;
                return false;
            }

            try
            {
                byte[] textAsBytes = Convert.FromBase64String(encodedText);
                decodedText = encoding.GetString(textAsBytes);
                return true;
            }
            catch (Exception)
            {
                decodedText = null;
                return false;   
            }
        }
    }
}

Conversion failed when converting date and/or time from character string while inserting datetime

The conversion in SQL server fails sometimes not because of the Date or Time formats used, It is Merely because you are trying to store wrong data that is not acceptable to the system.

Example:

Create Table MyTable (MyDate);

Insert Into MyTable(MyDate) Values ('2015-02-29');

The SQL server will throw the following error:

Conversion failed when converting date and/or time from character string.

The reason for this error is simply there is no such date (Feb-29) in Year (2015).

Creating a simple XML file using python

For the simplest choice, I'd go with minidom: http://docs.python.org/library/xml.dom.minidom.html . It is built in to the python standard library and is straightforward to use in simple cases.

Here's a pretty easy to follow tutorial: http://www.boddie.org.uk/python/XML_intro.html

Remove characters before character "."

You could try this:

string input = "lala.bla";
output = input.Split('.').Last();

bootstrap 3 wrap text content within div for horizontal alignment

Add the following style to your h3 elements:

word-wrap: break-word;

This will cause the long URLs in them to wrap. The default setting for word-wrap is normal, which will wrap only at a limited set of split tokens (e.g. whitespaces, hyphens), which are not present in a URL.

How to merge lists into a list of tuples?

The output which you showed in problem statement is not the tuple but list

list_c = [(1,5), (2,6), (3,7), (4,8)]

check for

type(list_c)

considering you want the result as tuple out of list_a and list_b, do

tuple(zip(list_a,list_b)) 

Serialize an object to XML

I will start with the copy answer of Ben Gripka:

public void Save(string FileName)
{
    using (var writer = new System.IO.StreamWriter(FileName))
    {
        var serializer = new XmlSerializer(this.GetType());
        serializer.Serialize(writer, this);
        writer.Flush();
    }
}

I used this code earlier. But reality showed that this solution is a bit problematic. Usually most of programmers just serialize setting on save and deserialize settings on load. This is an optimistic scenario. Once the serialization failed, because of some reason, the file is partly written, XML file is not complete and it is invalid. In consequence XML deserialization does not work and your application may crash on start. If the file is not huge, I suggest first serialize object to MemoryStream then write the stream to the File. This case is especially important if there is some complicated custom serialization. You can never test all cases.

public void Save(string fileName)
{
    //first serialize the object to memory stream,
    //in case of exception, the original file is not corrupted
    using (MemoryStream ms = new MemoryStream())
    {
        var writer = new System.IO.StreamWriter(ms);    
        var serializer = new XmlSerializer(this.GetType());
        serializer.Serialize(writer, this);
        writer.Flush();

        //if the serialization succeed, rewrite the file.
        File.WriteAllBytes(fileName, ms.ToArray());
    }
}

The deserialization in real world scenario should count with corrupted serialization file, it happens sometime. Load function provided by Ben Gripka is fine.

public static [ObjectType] Load(string fileName)
{
    using (var stream = System.IO.File.OpenRead(fileName))
    {
        var serializer = new XmlSerializer(typeof([ObjectType]));
        return serializer.Deserialize(stream) as [ObjectType];        
    }    
}

And it could be wrapped by some recovery scenario. It is suitable for settings files or other files which can be deleted in case of problems.

public static [ObjectType] LoadWithRecovery(string fileName)
{
    try
    {
        return Load(fileName);
    }
    catch(Excetion)
    {
        File.Delete(fileName); //delete corrupted settings file
        return GetFactorySettings();
    }
}

Can I pass variable to select statement as column name in SQL Server

You can't use variable names to bind columns or other system objects, you need dynamic sql

DECLARE @value varchar(10)  
SET @value = 'intStep'  
DECLARE @sqlText nvarchar(1000); 

SET @sqlText = N'SELECT ' + @value + ' FROM dbo.tblBatchDetail'
Exec (@sqlText)

How to convert timestamps to dates in Bash?

date -r <number>

works for me on Mac OS X.

What's the simplest way to extend a numpy array in 2 dimensions?

Another elegant solution to the first question may be the insert command:

p = np.array([[1,2],[3,4]])
p = np.insert(p, 2, values=0, axis=1) # insert values before column 2

Leads to:

array([[1, 2, 0],
       [3, 4, 0]])

insert may be slower than append but allows you to fill the whole row/column with one value easily.

As for the second question, delete has been suggested before:

p = np.delete(p, 2, axis=1)

Which restores the original array again:

array([[1, 2],
       [3, 4]])

find filenames NOT ending in specific extensions on Unix?

Or without ( and the need to escape it:

find . -not -name "*.exe" -not -name "*.dll"

and to also exclude the listing of directories

find . -not -name "*.exe" -not -name "*.dll" -not -type d

or in positive logic ;-)

find . -not -name "*.exe" -not -name "*.dll" -type f

Child element click event trigger the parent click event

Click event Bubbles, now what is meant by bubbling, a good point to starts is here. you can use event.stopPropagation(), if you don't want that event should propagate further.

Also a good link to refer on MDN

MongoDB query multiple collections at once

Perform multiple queries or use embedded documents or look at "database references".

Represent space and tab in XML tag

If you are talking about the issue where multiple and non-space whitespace characters are stripped specifically from attribute values, then yes, encoding them as character references such as &#9; will fix it.

Jquery bind double click and single click separately

I found that John Strickler's answer did not quite do what I was expecting. Once the alert is triggered by a second click within the two-second window, every subsequent click triggers another alert until you wait two seconds before clicking again. So with John's code, a triple click acts as two double clicks where I would expect it to act like a double click followed by a single click.

I have reworked his solution to function in this way and to flow in a way my mind can better comprehend. I dropped the delay down from 2000 to 700 to better simulate what I would feel to be a normal sensitivity. Here's the fiddle: http://jsfiddle.net/KpCwN/4/.

Thanks for the foundation, John. I hope this alternate version is useful to others.

var DELAY = 700, clicks = 0, timer = null;

$(function(){

    $("a").on("click", function(e){

        clicks++;  //count clicks

        if(clicks === 1) {

            timer = setTimeout(function() {

                alert("Single Click");  //perform single-click action    
                clicks = 0;             //after action performed, reset counter

            }, DELAY);

        } else {

            clearTimeout(timer);    //prevent single-click action
            alert("Double Click");  //perform double-click action
            clicks = 0;             //after action performed, reset counter
        }

    })
    .on("dblclick", function(e){
        e.preventDefault();  //cancel system double-click event
    });

});

Git push results in "Authentication Failed"

I tried the token verification method and got it to work ~3 times and wasted around 2 hours of time for that. For some reason it does not work very well for our company.

My solution was to change the authentication method from HTTPS to SSH. Here is a Github guide (https://help.github.com/en/github/authenticating-to-github/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent).

After you have created the SSH key, remember to change the SSH address origin:

git remote add origin [email protected]:user/repo.git

Found shared references to a collection org.hibernate.HibernateException

I too got the same issue, someone used BeanUtils.copyProperties(source, target). Here both source and target, are using the same collection as attribute.

So i just used the deep copy as below..

How to Clone Collection in Java - Deep copy of ArrayList and HashSet

Why does Lua have no "continue" statement?

Why is there no continue?

Because it's unnecessary¹. There's very few situations where a dev would need it.

A) When you have a very simple loop, say a 1- or 2-liner, then you can just turn the loop condition around and it's still plenty readable.

B) When you're writing simple procedural code (aka. how we wrote code in the last century), you should also be applying structured programming (aka. how we wrote better code in the last century)

C) If you're writing object-oriented code, your loop body should consist of no more than one or two method calls unless it can be expressed in a one- or two-liner (in which case, see A)

D) If you're writing functional code, just return a plain tail-call for the next iteration.

The only case when you'd want to use a continue keyword is if you want to code Lua like it's python, which it just isn't.²

What workarounds are there for it?

Unless A) applies, in which case there's no need for any workarounds, you should be doing Structured, Object-Oriented or Functional programming. Those are the paradigms that Lua was built for, so you'd be fighting against the language if you go out of your way to avoid their patterns.³


Some clarification:

¹ Lua is a very minimalistic language. It tries to have as few features as it can get away with, and a continue statement isn't an essential feature in that sense.

I think this philosophy of minimalism is captured well by Roberto Ierusalimschy in this 2019 interview:

add that and that and that, put that out, and in the end we understand the final conclusion will not satisfy most people and we will not put all the options everybody wants, so we don’t put anything. In the end, strict mode is a reasonable compromise.

² There seems to be a large ammount of programmers coming to Lua from other languages because whatever program they're trying to script for happens to use it, and many of them want don't seem to want to write anything other than their language of choice, which leads to many questions like "Why doesn't Lua have X feature?"

Matz described a similar situation with Ruby in a recent interview:

The most popular question is: "I’m from the language X community; can’t you introduce a feature from the language X to Ruby?", or something like that. And my usual answer to these requests is… "no, I wouldn’t do that", because we have different language design and different language development policies.

³ There's a few ways to hack your way around this; some users have suggested using goto, which is a good enough aproximation in most cases, but gets very ugly very quickly and breaks completely with nested loops. Using gotos also puts you in danger of having a copy of SICP thrown at you whenever you show your code to anybody else.

javascript regex for special characters

// Regex for special symbols

var regex_symbols= /[-!$%^&*()_+|~=`{}\[\]:\/;<>?,.@#]/;

Change default text in input type="file"?

Use "for" attribute of label for input.

<div>
  <label for="files" class="btn">Select Image</label>
  <input id="files" style="visibility:hidden;" type="file">
</div>
Below is the code to fetch name of the uploaded file

_x000D_
_x000D_
$("#files").change(function() {_x000D_
  filename = this.files[0].name_x000D_
  console.log(filename);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div>_x000D_
      <label for="files" class="btn">Select Image</label>_x000D_
      <input id="files" style="visibility:hidden;" type="file">_x000D_
    </div>
_x000D_
_x000D_
_x000D_

How do I get the absolute directory of a file in bash?

Take a look at realpath which is available on GNU/Linux, FreeBSD and NetBSD, but not OpenBSD 6.8. I use something like:

CONTAININGDIR=$(realpath ${FILEPATH%/*})

to do what it sounds like you're trying to do.

How to create a directory in Java?

Though this question has been answered. I would like to put something extra, i.e. if there is a file exist with the directory name that you are trying to create than it should prompt an error. For future visitors.

public static void makeDir()
{
    File directory = new File(" dirname ");
    if (directory.exists() && directory.isFile())
    {
        System.out.println("The dir with name could not be" +
        " created as it is a normal file");
    }
    else
    {
        try
        {
            if (!directory.exists())
            {
                directory.mkdir();
            }
            String username = System.getProperty("user.name");
            String filename = " path/" + username + ".txt"; //extension if you need one

        }
        catch (IOException e)
        {
            System.out.println("prompt for error");
        }
    }
}

How do I convert a javascript object array to a string array of the object attribute I want?

You can do this to only monitor own properties of the object:

var arr = [];

for (var key in p) {
    if (p.hasOwnProperty(key)) {
        arr.push(p[key]);
    }
}

Update statement with inner join on Oracle

Using description instead of desc for table2,

update
  table1
set
  value = (select code from table2 where description = table1.value)
where
  exists (select 1 from table2 where description = table1.value)
  and
  table1.updatetype = 'blah'
;

AngularJs ReferenceError: angular is not defined

In case you'd happen to be using rails and the angular-rails gem then the problem is easily corrected by adding this missing line to application.js (or what ever is applicable in your situation):

//= require angular-resource

How to remove "rows" with a NA value?

dat <- data.frame(x1 = c(1,2,3, NA, 5), x2 = c(100, NA, 300, 400, 500))

na.omit(dat)
  x1  x2
1  1 100
3  3 300
5  5 500

Canvas width and height in HTML5

Thank you very much! Finally I solved the blurred pixels problem with this code:

<canvas id="graph" width=326 height=240 style='width:326px;height:240px'></canvas>

With the addition of the 'half-pixel' does the trick to unblur lines.

How to set the font size in Emacs?

It all depends what you mean by change the font size. This EmacsWiki section provides the best and most complete information. It distinguishes the various cases (text scaling, frame font, buffer/frame, etc.): Changing Font Size.

What is the Windows equivalent of the diff command?

The windows equivalent to the diff command is the fc (File Comapre) command.

Here are the basic steps to do so:
1. Keep the two files in a folder (Example file1.html and file2.html)
2. Launch command prompt
3. Type fc file1Location file2Location

Have found a detailed tutorial on the same:

http://www.howtogeek.com/206123/how-to-use-fc-file-compare-from-the-windows-command-prompt/

Prevent Android activity dialog from closing on outside touch

Simply,

alertDialog.setCancelable(false);

prevent user from click outside of Dialog Box.

Add class to an element in Angular 4

Use [ngClass] and conditionally apply class based on the id.

In your HTML file:

<li>
    <img [ngClass]="{'this-is-a-class': id === 1 }" id="1"  
         src="../../assets/images/1.jpg" (click)="addClass(id=1)"/>
</li>
<li>
    <img [ngClass]="{'this-is-a-class': id === 2 }" id="2"  
         src="../../assets/images/2.png" (click)="addClass(id=2)"/>
</li>

In your TypeScript file:

addClass(id: any) {
    this.id = id;
}

What are database constraints?

To understand why we need constraints, you must first understand the value of data integrity.

Data Integrity refers to the validity of data. Are your data valid? Are your data representing what you have designed them to?

What weird questions I ask you might think, but sadly enough all too often, databases are filled with garbage data, invalid references to rows in other tables, that are long gone... and values that doesn't mean anything to the business logic of your solution any longer.

All this garbage is not alone prone to reduce your performance, but is also a time-bomb under your application logic that eventually will retreive data that it is not designed to understand.

Constraints are rules you create at design-time that protect your data from becoming corrupt. It is essential for the long time survival of your heart child of a database solution. Without constraints your solution will definitely decay with time and heavy usage.

You have to acknowledge that designing your database design is only the birth of your solution. Here after it must live for (hopefully) a long time, and endure all kinds of (strange) behaviour by its end-users (ie. client applications). But this design-phase in development is crucial for the long-time success of your solution! Respect it, and pay it the time and attention it requires.

A wise man once said: "Data must protect itself!". And this is what constraints do. It is rules that keep the data in your database as valid as possible.

There are many ways of doing this, but basically they boil down to:

  • Foreign key constraints is probably the most used constraint, and ensures that references to other tables are only allowed if there actually exists a target row to reference. This also makes it impossible to break such a relationship by deleting the referenced row creating a dead link.
  • Check constraints can ensure that only specific values are allowed in certain column. You could create a constraint only allowing the word 'Yellow' or 'Blue' in a VARCHAR column. All other values would yield an error. Get ideas for usage of check constraints check the sys.check_constraints view in the AdventureWorks sample database
  • Rules in SQL Server are just reusable Check Constraints (allows you to maintain the syntax from a single place, and making it easier to deploy your constraints to other databases)

As I've hinted here, it takes some thorough considerations to construct the best and most defensive constraint approach for your database design. You first need to know the possibilities and limitations of the different constraint types above. Further reading could include:

FOREIGN KEY Constraints - Microsoft

Foreign key constraint - w3schools

CHECK Constraints

Good luck! ;)

Browser detection in JavaScript?

Here is how I do custom CSS for Internet Explorer:

In my JavaScript file:

function isIE () {
      var myNav = navigator.userAgent.toLowerCase();
      return (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : false;
}

jQuery(document).ready(function(){
    if(var_isIE){
            if(var_isIE == 10){
                jQuery("html").addClass("ie10");
            }
            if(var_isIE == 8){
                jQuery("html").addClass("ie8");
                // you can also call here some function to disable things that 
                //are not supported in IE, or override browser default styles.
            }
        }
    });

And then in my CSS file, y define each different style:

.ie10 .some-class span{
    .......
}
.ie8 .some-class span{
    .......
}

adding multiple event listeners to one element

This is my solution in which I deal with multiple events in my workflow.

_x000D_
_x000D_
let h2 = document.querySelector("h2");_x000D_
_x000D_
function addMultipleEvents(eventsArray, targetElem, handler) {_x000D_
        eventsArray.map(function(event) {_x000D_
            targetElem.addEventListener(event, handler, false);_x000D_
        }_x000D_
    );_x000D_
}_x000D_
let counter = 0;_x000D_
function countP() {_x000D_
    counter++;_x000D_
    h2.innerHTML = counter;_x000D_
}_x000D_
_x000D_
// magic starts over here..._x000D_
addMultipleEvents(['click', 'mouseleave', 'mouseenter'], h2, countP);
_x000D_
<h1>MULTI EVENTS DEMO - If you click, move away or enter the mouse on the number, it counts...</h1>_x000D_
_x000D_
<h2 style="text-align:center; font: bold 3em comic; cursor: pointer">0</h2>
_x000D_
_x000D_
_x000D_

How do I turn off Oracle password expiration?

To alter the password expiry policy for a certain user profile in Oracle first check which profile the user is using:

select profile from DBA_USERS where username = '<username>';

Then you can change the limit to never expire using:

alter profile <profile_name> limit password_life_time UNLIMITED;

If you want to previously check the limit you may use:

select resource_name,limit from dba_profiles where profile='<profile_name>';

How to obtain a Thread id in Python?

I saw examples of thread IDs like this:

class myThread(threading.Thread):
    def __init__(self, threadID, name, counter):
        self.threadID = threadID
        ...

The threading module docs lists name attribute as well:

...

A thread has a name. 
The name can be passed to the constructor, 
and read or changed through the name attribute.

...

Thread.name

A string used for identification purposes only. 
It has no semantics. Multiple threads may
be given the same name. The initial name is set by the constructor.

SQL How to remove duplicates within select query?

Do you need any other information except the date? If not:

SELECT DISTINCT start_date FROM table;

Printing pointers in C

"s" is not a "char*", it's a "char[4]". And so, "&s" is not a "char**", but actually "a pointer to an array of 4 characater". Your compiler may treat "&s" as if you had written "&s[0]", which is roughly the same thing, but is a "char*".

When you write "char** p = &s;" you are trying to say "I want p to be set to the address of the thing which currently points to "asd". But currently there is nothing which points to "asd". There is just an array which holds "asd";

char s[] = "asd";
char *p = &s[0];  // alternately you could use the shorthand char*p = s;
char **pp = &p;

How to get the process ID to kill a nohup process?

when you create a job in nohup it will tell you the process ID !

nohup sh test.sh &

the output will show you the process ID like

25013

you can kill it then :

kill 25013

How do I vertically align something inside a span tag?

Set padding-top to be an appropriate value to push the x down, then subtract the value you have for padding-top from the height.

How do I make case-insensitive queries on Mongodb?

I have solved it like this.

 var thename = 'Andrew';
 db.collection.find({'name': {'$regex': thename,$options:'i'}});

If you want to query on 'case-insensitive exact matchcing' then you can go like this.

var thename =  '^Andrew$';
db.collection.find({'name': {'$regex': thename,$options:'i'}});

Uncaught TypeError: Cannot set property 'onclick' of null

Does document.getElementById("blue") exist? if it doesn't then blue_box will be equal to null. you can't set a onclick on something that's null

Creating a Jenkins environment variable using Groovy

The Jenkins EnvInject Plugin might be able to help you. It allows injecting environment variables into the build environment.

I know it has some ability to do scripting, so it might be able to do what you want. I have only used it to set simple properties (e.g. "LOG_PATH=${WORKSPACE}\logs").

Getting a slice of keys from a map

A nicer way to do this would be to use append:

keys = []int{}
for k := range mymap {
    keys = append(keys, k)
}

Other than that, you’re out of luck—Go isn’t a very expressive language.

Detect current device with UI_USER_INTERFACE_IDIOM() in Swift

Made a couple of additions to the above answers so that you get returned a type instead of string value.

I figured that this is primarily going to be used for UI adjustments so I didn't think it relevant to include all the sub models i.e. iPhone 5s but this could be easily extended by adding in model tests to the isDevice Array

Tested working in Swift 3.1 Xcode 8.3.2 with physical and simulator devices

Implementation:

UIDevice.whichDevice()

public enum SVNDevice {
  case isiPhone4, isIphone5, isIphone6or7, isIphone6por7p, isIphone, isIpad, isIpadPro
}

extension UIDevice {
  class func whichDevice() -> SVNDevice? {
    let isDevice = { (comparision: Array<(Bool, SVNDevice)>) -> SVNDevice? in
      var device: SVNDevice?
      comparision.forEach({
        device = $0.0 ? $0.1 : device
      })
      return device
    }

    return isDevice([
      (UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH < 568.0, SVNDevice.isiPhone4),
      (UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 568.0, SVNDevice.isIphone5),
      (UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 667.0, SVNDevice.isIphone6or7),
      (UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 736.0, SVNDevice.isIphone6por7p),
      (UIDevice.current.userInterfaceIdiom == .pad && ScreenSize.SCREEN_MAX_LENGTH == 1024.0, SVNDevice.isIpad),
      (UIDevice.current.userInterfaceIdiom == .pad && ScreenSize.SCREEN_MAX_LENGTH == 1366.0, SVNDevice.isIpadPro)])
  }
}



private struct ScreenSize {
  static let SCREEN_WIDTH         = UIScreen.main.bounds.size.width
  static let SCREEN_HEIGHT        = UIScreen.main.bounds.size.height
  static let SCREEN_MAX_LENGTH    = max(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT)
  static let SCREEN_MIN_LENGTH    = min(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT)
}

I've created a framework called SVNBootstaper which includes this and some other helper protocols, it's public and available through Carthage.

How to define unidirectional OneToMany relationship in JPA

My bible for JPA work is the Java Persistence wikibook. It has a section on unidirectional OneToMany which explains how to do this with a @JoinColumn annotation. In your case, i think you would want:

@OneToMany
@JoinColumn(name="TXTHEAD_CODE")
private Set<Text> text;

I've used a Set rather than a List, because the data itself is not ordered.

The above is using a defaulted referencedColumnName, unlike the example in the wikibook. If that doesn't work, try an explicit one:

@OneToMany
@JoinColumn(name="TXTHEAD_CODE", referencedColumnName="DATREG_META_CODE")
private Set<Text> text;

Eclipse Java error: This selection cannot be launched and there are no recent launches

It happens when sometimes we copy or import the project from somewhere. The source folder is a big thing to concern about.

One simple technique is, create a new project, inside the source folder, create a new class and paste the content over there.

It will work...

Hope it helps.

Downcasting in Java

Using your example, you could do:

public void doit(A a) {
    if(a instanceof B) {
        // needs to cast to B to access draw2 which isn't present in A
        // note that this is probably not a good OO-design, but that would
        // be out-of-scope for this discussion :)
        ((B)a).draw2();
    }
    a.draw();
}

Root password inside a Docker container

I had exactly this problem of not being able to su to root because I was running in the container as an unprivileged user.

But I didn't want to rebuild a new image as the previous answers suggest.

Instead I have found that I could access the container as root using 'nsenter', see: https://github.com/jpetazzo/nsenter

First determine the PID of your container on the host:

docker inspect --format {{.State.Pid}} <container_name_or_ID>

Then use nsenter to enter the container as root

nsenter --target <PID> --mount --uts --ipc --net --pid

GDB: break if variable equal value

in addition to a watchpoint nested inside a breakpoint you can also set a single breakpoint on the 'filename:line_number' and use a condition. I find it sometimes easier.

(gdb) break iter.c:6 if i == 5
Breakpoint 2 at 0x4004dc: file iter.c, line 6.
(gdb) c
Continuing.
0
1
2
3
4

Breakpoint 2, main () at iter.c:6
6           printf("%d\n", i);

If like me you get tired of line numbers changing, you can add a label then set the breakpoint on the label like so:

#include <stdio.h>
main()
{ 
     int i = 0;
     for(i=0;i<7;++i) {
       looping:
        printf("%d\n", i);
     }
     return 0;
}

(gdb) break main:looping if i == 5

How to check if a "lateinit" variable has been initialized?

You can easily do this by:

::variableName.isInitialized

or

this::variableName.isInitialized

But if you are inside a listener or inner class, do this:

this@OuterClassName::variableName.isInitialized

Note: The above statements work fine if you are writing them in the same file(same class or inner class) where the variable is declared but this will not work if you want to check the variable of other class (which could be a superclass or any other class which is instantiated), for ex:

class Test {
    lateinit var str:String
}

And to check if str is initialized:

enter image description here

What we are doing here: checking isInitialized for field str of Test class in Test2 class. And we get an error backing field of var is not accessible at this point. Check a question already raised about this.

How can we print line numbers to the log in java

I am compelled to answer by not answering your question. I'm assuming that you are looking for the line number solely to support debugging. There are better ways. There are hackish ways to get the current line. All I've seen are slow. You are better off using a logging framework like that in java.util.logging package or log4j. Using these packages you can configure your logging information to include context down to the class name. Then each log message would be unique enough to know where it came from. As a result, your code will have a 'logger' variable that you call via

logger.debug("a really descriptive message")

instead of

System.out.println("a really descriptive message")

How to handle AccessViolationException

You can try using AppDomain.UnhandledException and see if that lets you catch it.

**EDIT*

Here is some more information that might be useful (it's a long read).

How do I pull my project from github?

Run these commands:

cd /pathToYourLocalProjectFolder

git pull origin master

"unadd" a file to svn before commit

Use svn revert --recursive folder_name


Warning

svn revert is inherently dangerous, since its entire purpose is to throw away data — namely, your uncommitted changes. Once you've reverted, Subversion provides no way to get back those uncommitted changes.

http://svnbook.red-bean.com/en/1.7/svn.ref.svn.c.revert.html

What is the worst programming language you ever worked with?

I haven't yet worked with many languages and deal mostly with scripting languages; out of these VBScript is the one I like least. Although it has some handy features, some things really piss me off:

  • Object assignments are made using the Set keyword:

    Set foo = Nothing
    

    Omitting Set is one of the most common causes of run-time errors.

  • No such thing as structured exception handling. Error checking is like this:

    On Error Resume Next
    
    ' Do something
    
    If Err.Number <> 0
      ' Handle error
      Err.Clear
    End If
    
    ' And so on
    
  • Enclosing the procedure call parameters in parentheses requires using the Call keyword:

    Call Foo (a, b)
    
  • Its English-like syntax is way too verbose. (I'm a fan of curly braces.)

  • Logical operators are long-circuit. If you need to test a compound condition where the subsequent condition relies on the success of the previous one, you need to put conditions into separate If statements.

  • Lack of parameterized class constructors.

  • To wrap a statement into several lines, you have to use an underscore:

    str = "Hello, " & _
          "world!"
    
  • Lack of multiline comments.


Edit: found this article: The Flangy Guide to Hating VBScript. The author sums up his complaints as "VBS isn't Python" :)

What's the difference between the atomic and nonatomic attributes?

The default is atomic, this means it does cost you performance whenever you use the property, but it is thread safe. What Objective-C does, is set a lock, so only the actual thread may access the variable, as long as the setter/getter is executed.

Example with MRC of a property with an ivar _internal:

[_internal lock]; //lock
id result = [[value retain] autorelease];
[_internal unlock];
return result;

So these last two are the same:

@property(atomic, retain) UITextField *userName;

@property(retain) UITextField *userName; // defaults to atomic

On the other hand does nonatomic add nothing to your code. So it is only thread safe if you code security mechanism yourself.

@property(nonatomic, retain) UITextField *userName;

The keywords doesn't have to be written as first property attribute at all.

Don't forget, this doesn't mean that the property as a whole is thread-safe. Only the method call of the setter/getter is. But if you use a setter and after that a getter at the same time with 2 different threads, it could be broken too!

How do I get a UTC Timestamp in JavaScript?

This will return the timestamp in UTC:

_x000D_
_x000D_
var utc = new Date(new Date().toUTCString()).getTime();
_x000D_
_x000D_
_x000D_

How do you overcome the svn 'out of date' error?

Upgrade your server and client to Subversion 1.9.

If the out of date error randomly occurs when it normally should not, when you run commit, it may indicate that you are using an outdated and unsupported Subversion 1.7 or older client or server.

You should upgrade the server and clients in order to solve the problem. See the relevant Subversion 1.9 Release Notes entry: "Out of date" errors when committing over HTTPv1.

Getting Error 800a0e7a "Provider cannot be found. It may not be properly installed."

Got this exception when maintaining very old application on Server 2003 using Asp classic on IIS6 with Oracle 9.2.0.1. The fix is by updating oracle to 9.2.0.6.

Is there a WebSocket client implemented for Python?

http://pypi.python.org/pypi/websocket-client/

Ridiculously easy to use.

 sudo pip install websocket-client

Sample client code:

#!/usr/bin/python

from websocket import create_connection
ws = create_connection("ws://localhost:8080/websocket")
print "Sending 'Hello, World'..."
ws.send("Hello, World")
print "Sent"
print "Receiving..."
result =  ws.recv()
print "Received '%s'" % result
ws.close()

Sample server code:

#!/usr/bin/python
import websocket
import thread
import time

def on_message(ws, message):
    print message

def on_error(ws, error):
    print error

def on_close(ws):
    print "### closed ###"

def on_open(ws):
    def run(*args):
        for i in range(30000):
            time.sleep(1)
            ws.send("Hello %d" % i)
        time.sleep(1)
        ws.close()
        print "thread terminating..."
    thread.start_new_thread(run, ())


if __name__ == "__main__":
    websocket.enableTrace(True)
    ws = websocket.WebSocketApp("ws://echo.websocket.org/",
                                on_message = on_message,
                                on_error = on_error,
                                on_close = on_close)
    ws.on_open = on_open

    ws.run_forever()

How to check Network port access and display useful message?

Actually Shay levy's answer is almost correct but i got an weird issue as i mentioned in his comment column. So i split the command into two lines and it works fine.

$Ipaddress= Read-Host "Enter the IP address:"
$Port= Read-host "Enter the port number to access:"

$t = New-Object Net.Sockets.TcpClient
$t.Connect($Ipaddress,$Port)
    if($t.Connected)
    {
        "Port $Port is operational"
    }
    else
    {
        "Port $Port is closed, You may need to contact your IT team to open it. "
    }

Substring in excel

I believe we can start from basic to achieve desired result.

For example, I had a situation to extract data after "/". The given excel field had a value of 2rko6xyda14gdl7/VEERABABU%20MATCHA%20IN131621.jpg . I simply wanted to extract the text from "I5" cell after slash symbol. So firstly I want to find where "/" symbol is (FIND("/",I5). This gives me the position of "/". Then I should know the length of text, which i can get by LEN(I5).so total length minus the position of "/" . which is LEN(I5)-(FIND("/",I5)) . This will first find the "/" position and then get me the total text that needs to be extracted. The RIGHT function is RIGHT(I5,12) will simply extract all the values of last 12 digits starting from right most character. So I will replace the above function "LEN(I5)-(FIND("/",I5))" for 12 number in the RIGHT function to get me dynamically the number of characters I need to extract in any given cell and my solution is presented as given below

The approach was

=RIGHT(I5,LEN(I5)-(FIND("/",I5))) will give me out as VEERABABU%20MATCHA%20IN131621.jpg . I think I am clear.

NPM vs. Bower vs. Browserify vs. Gulp vs. Grunt vs. Webpack

Webpack is a bundler. Like Browserfy it looks in the codebase for module requests (require or import) and resolves them recursively. What is more, you can configure Webpack to resolve not just JavaScript-like modules, but CSS, images, HTML, literally everything. What especially makes me excited about Webpack, you can combine both compiled and dynamically loaded modules in the same app. Thus one get a real performance boost, especially over HTTP/1.x. How exactly you you do it I described with examples here http://dsheiko.com/weblog/state-of-javascript-modules-2017/ As an alternative for bundler one can think of Rollup.js (https://rollupjs.org/), which optimizes the code during compilation, but stripping all the found unused chunks.

For AMD, instead of RequireJS one can go with native ES2016 module system, but loaded with System.js (https://github.com/systemjs/systemjs)

Besides, I would point that npm is often used as an automating tool like grunt or gulp. Check out https://docs.npmjs.com/misc/scripts. I personally go now with npm scripts only avoiding other automation tools, though in past I was very much into grunt. With other tools you have to rely on countless plugins for packages, that often are not good written and not being actively maintained. npm knows its packages, so you call to any of locally installed packages by name like:

{
  "scripts": {
    "start": "npm http-server"
  },
  "devDependencies": {
    "http-server": "^0.10.0"
  }
}

Actually you as a rule do not need any plugin if the package supports CLI.

DropdownList DataSource

Refer to example at this link. It may be help to you.

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.dropdownlist.aspx

void Page_Load(Object sender, EventArgs e)
  {

     // Load data for the DropDownList control only once, when the 
     // page is first loaded.
     if(!IsPostBack)
     {

        // Specify the data source and field names for the Text 
        // and Value properties of the items (ListItem objects) 
        // in the DropDownList control.
        ColorList.DataSource = CreateDataSource();
        ColorList.DataTextField = "ColorTextField";
        ColorList.DataValueField = "ColorValueField";

        // Bind the data to the control.
        ColorList.DataBind();

        // Set the default selected item, if desired.
        ColorList.SelectedIndex = 0;

     }

  }

void Selection_Change(Object sender, EventArgs e)
  {

     // Set the background color for days in the Calendar control
     // based on the value selected by the user from the 
     // DropDownList control.
     Calendar1.DayStyle.BackColor = 
         System.Drawing.Color.FromName(ColorList.SelectedItem.Value);

  }

Qt c++ aggregate 'std::stringstream ss' has incomplete type and cannot be defined

Like it's written up there, you forget to type #include <sstream>

#include <sstream>
using namespace std;

QString Stats_Manager::convertInt(int num)
{
   stringstream ss;
   ss << num;
   return ss.str();
}

You can also use some other ways to convert int to string, like

char numstr[21]; // enough to hold all numbers up to 64-bits
sprintf(numstr, "%d", age);
result = name + numstr;

check this!

COLLATION 'utf8_general_ci' is not valid for CHARACTER SET 'latin1'

Firstly run this query

SHOW VARIABLES LIKE '%char%';

You have character_set_server='latin1'

If so,go into your config file,my.cnf and add or uncomment these lines:

character-set-server = utf8
collation-server = utf8_unicode_ci

Restart the server. Yes late to the party,just encountered the same issue.

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

If you are thinking about using floating-point to help with integer arithmetics, you have to be careful.

I usually try to avoid FP calculations whenever possible.

Floating-point operations are not exact. You can never know for sure what will (int)(Math.log(65536)/Math.log(2)) evaluate to. For example, Math.ceil(Math.log(1<<29) / Math.log(2)) is 30 on my PC where mathematically it should be exactly 29. I didn't find a value for x where (int)(Math.log(x)/Math.log(2)) fails (just because there are only 32 "dangerous" values), but it does not mean that it will work the same way on any PC.

The usual trick here is using "epsilon" when rounding. Like (int)(Math.log(x)/Math.log(2)+1e-10) should never fail. The choice of this "epsilon" is not a trivial task.

More demonstration, using a more general task - trying to implement int log(int x, int base):

The testing code:

static int pow(int base, int power) {
    int result = 1;
    for (int i = 0; i < power; i++)
        result *= base;
    return result;
}

private static void test(int base, int pow) {
    int x = pow(base, pow);
    if (pow != log(x, base))
        System.out.println(String.format("error at %d^%d", base, pow));
    if(pow!=0 && (pow-1) != log(x-1, base))
        System.out.println(String.format("error at %d^%d-1", base, pow));
}

public static void main(String[] args) {
    for (int base = 2; base < 500; base++) {
        int maxPow = (int) (Math.log(Integer.MAX_VALUE) / Math.log(base));
        for (int pow = 0; pow <= maxPow; pow++) {
            test(base, pow);
        }
    }
}

If we use the most straight-forward implementation of logarithm,

static int log(int x, int base)
{
    return (int) (Math.log(x) / Math.log(base));
}

this prints:

error at 3^5
error at 3^10
error at 3^13
error at 3^15
error at 3^17
error at 9^5
error at 10^3
error at 10^6
error at 10^9
error at 11^7
error at 12^7
...

To completely get rid of errors I had to add epsilon which is between 1e-11 and 1e-14. Could you have told this before testing? I definitely could not.

How to calculate an angle from three points?

      Atan2        output in degrees
       PI/2              +90
         |                | 
         |                |    
   PI ---.--- 0   +180 ---.--- 0       
         |                |
         |                |
       -PI/2             +270

public static double CalculateAngleFromHorizontal(double startX, double startY, double endX, double endY)
{
    var atan = Math.Atan2(endY - startY, endX - startX); // Angle in radians
    var angleDegrees = atan * (180 / Math.PI);  // Angle in degrees (can be +/-)
    if (angleDegrees < 0.0)
    {
        angleDegrees = 360.0 + angleDegrees;
    }
    return angleDegrees;
}

// Angle from point2 to point 3 counter clockwise
public static double CalculateAngle0To360(double centerX, double centerY, double x2, double y2, double x3, double y3)
{
    var angle2 = CalculateAngleFromHorizontal(centerX, centerY, x2, y2);
    var angle3 = CalculateAngleFromHorizontal(centerX, centerY, x3, y3);
    return (360.0 + angle3 - angle2)%360;
}

// Smaller angle from point2 to point 3
public static double CalculateAngle0To180(double centerX, double centerY, double x2, double y2, double x3, double y3)
{
    var angle = CalculateAngle0To360(centerX, centerY, x2, y2, x3, y3);
    if (angle > 180.0)
    {
        angle = 360 - angle;
    }
    return angle;
}

}

Backporting Python 3 open(encoding="utf-8") to Python 2

I think

from io import open

should do.

Go to beginning of line without opening new line in VI

A simple 0 takes you to the beginning of a line.

:help 0 for more information

How to use Object.values with typescript?

Simplest way is to cast the Object to any, like this:

const data = {"Ticket-1.pdf":"8e6e8255-a6e9-4626-9606-4cd255055f71.pdf","Ticket-2.pdf":"106c3613-d976-4331-ab0c-d581576e7ca1.pdf"};
const obj = <any>Object;
const values = obj.values(data).map(x => x.substr(0, x.length - 4));
const commaJoinedValues = values.join(',');
console.log(commaJoinedValues);

And voila – no compilation errors ;)

what does mysql_real_escape_string() really do?

Say you want to save the string I'm a "foobar" in the database.
Your query will look something like INSERT INTO foos (text) VALUES ("$text").
With the $text variable replaced, this will look like this:

INSERT INTO foos (text) VALUES ("I'm a "foobar"")

Now, where exactly does the string end? You may know, an SQL parser doesn't. Not only will this simply break this query, it can also be abused to inject SQL commands you didn't intend.

mysql_real_escape_string makes sure such ambiguities do not occur by escaping characters which have special meaning to an SQL parser:

mysql_real_escape_string($text)  =>  I\'m a \"foobar\"

This becomes:

INSERT INTO foos (text) VALUES ("I\'m a \"foobar\"")

This makes the statement unambiguous and safe. The \ signals that the following character is not to be taken by its special meaning as string terminator. There are a few such characters that mysql_real_escape_string takes care of.

Escaping is a pretty universal thing in programming languages BTW, all along the same lines. If you want to type the above sentence literally in PHP, you need to escape it as well for the same reasons:

$text = 'I\'m a "foobar"';
// or
$text = "I'm a \"foobar\"";

What is the (best) way to manage permissions for Docker shared volumes?

For secure and change root for docker container an docker host try use --uidmap and --private-uids options

https://github.com/docker/docker/pull/4572#issuecomment-38400893

Also you may remove several capabilities (--cap-drop) in docker container for security

http://opensource.com/business/14/9/security-for-docker

UPDATE support should come in docker > 1.7.0

UPDATE Version 1.10.0 (2016-02-04) add --userns-remap flag https://github.com/docker/docker/blob/master/CHANGELOG.md#security-2

Passing $_POST values with cURL

Check out this page which has an example of how to do it.

bash export command

if u cant use " export " cmd
then Just use:

setenv path /dir

like this

setenv ORACLE_HOME /data/u01/apps/oracle/11.2.0.3.0

how to get the host url using javascript from the current page

Depending on your needs, you can use one of the window.location properties. In your question you are asking about the host, which may be retrieved using window.location.hostname (e.g. www.example.com). In your example you are showing something what is called origin, which may be retrieved using window.location.origin (e.g. http://www.example.com).

var path = window.location.origin + "/";

//result = "http://localhost:60470/"

WMI "installed" query different from add/remove programs list?

You can get it in one line with powershell and batch file :

@echo off
Powershell /command "Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate | Format-List"
Pause

Python: Tuples/dictionaries as keys, select, sort

Database, dict of dicts, dictionary of list of dictionaries, named tuple (it's a subclass), sqlite, redundancy... I didn't believe my eyes. What else ?

"It might well be that dictionaries with tuples as keys are not the proper way to handle this situation."

"my gut feeling is that a database is overkill for the OP's needs; "

Yeah! I thought

So, in my opinion, a list of tuples is plenty enough :

from operator import itemgetter

li = [  ('banana',     'blue'   , 24) ,
        ('apple',      'green'  , 12) ,
        ('strawberry', 'blue'   , 16 ) ,
        ('banana',     'yellow' , 13) ,
        ('apple',      'gold'   , 3 ) ,
        ('pear',       'yellow' , 10) ,
        ('strawberry', 'orange' , 27) ,
        ('apple',      'blue'   , 21) ,
        ('apple',      'silver' , 0 ) ,
        ('strawberry', 'green'  , 4 ) ,
        ('banana',     'brown'  , 14) ,
        ('strawberry', 'yellow' , 31) ,
        ('apple',      'pink'   , 9 ) ,
        ('strawberry', 'gold'   , 0 ) ,
        ('pear',       'gold'   , 66) ,
        ('apple',      'yellow' , 9 ) ,
        ('pear',       'brown'  , 5 ) ,
        ('strawberry', 'pink'   , 8 ) ,
        ('apple',      'purple' , 7 ) ,
        ('pear',       'blue'   , 51) ,
        ('chesnut',    'yellow',  0 )   ]


print set( u[1] for u in li ),': all potential colors'
print set( c for f,c,n in li if n!=0),': all effective colors'
print [ c for f,c,n in li if f=='banana' ],': all potential colors of bananas'
print [ c for f,c,n in li if f=='banana' and n!=0],': all effective colors of bananas'
print

print set( u[0] for u in li ),': all potential fruits'
print set( f for f,c,n in li if n!=0),': all effective fruits'
print [ f for f,c,n in li if c=='yellow' ],': all potential fruits being yellow'
print [ f for f,c,n in li if c=='yellow' and n!=0],': all effective fruits being yellow'
print

print len(set( u[1] for u in li )),': number of all potential colors'
print len(set(c for f,c,n in li if n!=0)),': number of all effective colors'
print len( [c for f,c,n in li if f=='strawberry']),': number of potential colors of strawberry'
print len( [c for f,c,n in li if f=='strawberry' and n!=0]),': number of effective colors of strawberry'
print

# sorting li by name of fruit
print sorted(li),'  sorted li by name of fruit'
print

# sorting li by number 
print sorted(li, key = itemgetter(2)),'  sorted li by number'
print

# sorting li first by name of color and secondly by name of fruit
print sorted(li, key = itemgetter(1,0)),'  sorted li first by name of color and secondly by name of fruit'
print

result

set(['blue', 'brown', 'gold', 'purple', 'yellow', 'pink', 'green', 'orange', 'silver']) : all potential colors
set(['blue', 'brown', 'gold', 'purple', 'yellow', 'pink', 'green', 'orange']) : all effective colors
['blue', 'yellow', 'brown'] : all potential colors of bananas
['blue', 'yellow', 'brown'] : all effective colors of bananas

set(['strawberry', 'chesnut', 'pear', 'banana', 'apple']) : all potential fruits
set(['strawberry', 'pear', 'banana', 'apple']) : all effective fruits
['banana', 'pear', 'strawberry', 'apple', 'chesnut'] : all potential fruits being yellow
['banana', 'pear', 'strawberry', 'apple'] : all effective fruits being yellow

9 : number of all potential colors
8 : number of all effective colors
6 : number of potential colors of strawberry
5 : number of effective colors of strawberry

[('apple', 'blue', 21), ('apple', 'gold', 3), ('apple', 'green', 12), ('apple', 'pink', 9), ('apple', 'purple', 7), ('apple', 'silver', 0), ('apple', 'yellow', 9), ('banana', 'blue', 24), ('banana', 'brown', 14), ('banana', 'yellow', 13), ('chesnut', 'yellow', 0), ('pear', 'blue', 51), ('pear', 'brown', 5), ('pear', 'gold', 66), ('pear', 'yellow', 10), ('strawberry', 'blue', 16), ('strawberry', 'gold', 0), ('strawberry', 'green', 4), ('strawberry', 'orange', 27), ('strawberry', 'pink', 8), ('strawberry', 'yellow', 31)]   sorted li by name of fruit

[('apple', 'silver', 0), ('strawberry', 'gold', 0), ('chesnut', 'yellow', 0), ('apple', 'gold', 3), ('strawberry', 'green', 4), ('pear', 'brown', 5), ('apple', 'purple', 7), ('strawberry', 'pink', 8), ('apple', 'pink', 9), ('apple', 'yellow', 9), ('pear', 'yellow', 10), ('apple', 'green', 12), ('banana', 'yellow', 13), ('banana', 'brown', 14), ('strawberry', 'blue', 16), ('apple', 'blue', 21), ('banana', 'blue', 24), ('strawberry', 'orange', 27), ('strawberry', 'yellow', 31), ('pear', 'blue', 51), ('pear', 'gold', 66)]   sorted li by number

[('apple', 'blue', 21), ('banana', 'blue', 24), ('pear', 'blue', 51), ('strawberry', 'blue', 16), ('banana', 'brown', 14), ('pear', 'brown', 5), ('apple', 'gold', 3), ('pear', 'gold', 66), ('strawberry', 'gold', 0), ('apple', 'green', 12), ('strawberry', 'green', 4), ('strawberry', 'orange', 27), ('apple', 'pink', 9), ('strawberry', 'pink', 8), ('apple', 'purple', 7), ('apple', 'silver', 0), ('apple', 'yellow', 9), ('banana', 'yellow', 13), ('chesnut', 'yellow', 0), ('pear', 'yellow', 10), ('strawberry', 'yellow', 31)]   sorted li first by name of color and secondly by name of fruit

Install an apk file from command prompt?

Open Terminal in Android Studio

You might see

C:\Users\nikhil\AppData\Local\Android\Sdk\platform-tools>

copy and paste your apk which you want to install on above path inside platform-tools. In my case app-qa-debug.apk I kept inside platform-tools folder.

install command

adb install app-qa-debug.apk

so in the terminal you could see something

C:\Users\nikhil\AppData\Local\Android\Sdk\platform-tools>adb install app-qa-debug.apk

post-installation you could get the message as

Performing Streamed

Install Success

Using ORDER BY and GROUP BY together

Just you need to desc with asc. Write the query like below. It will return the values in ascending order.

SELECT * FROM table GROUP BY m_id ORDER BY m_id asc;

Mysql error 1452 - Cannot add or update a child row: a foreign key constraint fails

I'd the same problem, I checked rows of my tables and found there was some incompatibility with the value of fields that I wanted to define a foreign key. I corrected those value, tried again and the problem was solved.

How do I convert a String to an InputStream in Java?

I find that using Apache Commons IO makes my life much easier.

String source = "This is the source of my input stream";
InputStream in = org.apache.commons.io.IOUtils.toInputStream(source, "UTF-8");

You may find that the library also offer many other shortcuts to commonly done tasks that you may be able to use in your project.

How to See the Contents of Windows library (*.lib)

DUMPBIN /EXPORTS Will get most of that information and hitting MSDN will get the rest.

Get one of the Visual Studio packages; C++

Singletons vs. Application Context in Android?

My 2 cents:

I did notice that some singleton / static fields were reseted when my activity was destroyed. I noticed this on some low end 2.3 devices.

My case was very simple : I just have a private filed "init_done" and a static method "init" that I called from activity.onCreate(). I notice that the method init was re-executing itself on some re-creation of the activity.

While I cannot prove my affirmation, It may be related to WHEN the singleton/class was created/used first. When the activity get destroyed/recycled, it seem that all class that only this activity refer are recycled too.

I moved my instance of singleton to a sub class of Application. I acces them from the application instance. and, since then, did not notice the problem again.

I hope this can help someone.

JOptionPane Yes or No window

You are writing if(true) so it will always show "Hello " message.

You should take decision on the basis of value of n returned.

How to upload a file from Windows machine to Linux machine using command lines via PuTTy?

Better and quicker approach without any software to download.

  • Open command prompt and follow steps mentioned below
  • cd path/from/where/file/istobe/copied
  • ftp (serverip or name)
  • It will ask for Server(AIX) User: (username)
  • It will ask for password : (password)
  • cd path/where/file/istobe/copied
  • pwd (to check current path)
  • mput (directory name which is to be copied)

This should work.

Array of strings in groovy

If you really want to create an array rather than a list use either

String[] names = ["lucas", "Fred", "Mary"]

or

def names = ["lucas", "Fred", "Mary"].toArray()

remote rejected master -> master (pre-receive hook declined)

Check the following

  1. Make sure you add all the files and directories needed to be tracked are added using git status [You have done this]

    $ git status

  2. If not added then add them using **git add . ** [You have done this]

    $ git add .

  3. Bundle all gems and you will have Gemfile.lock

    $ bundle install
    $ git add Gemfile.lock
    $ git commit -am "Added Gemfile.lock"

  4. Push it to heroku

$ git push heroku master

Your push should work

How to fix "namespace x already contains a definition for x" error? Happened after converting to VS2010

I had a similar problem (Universal project, Visual Studio 2015), I solved it with the following changes:

In App.xml.cs was (it was ok):

namespace Test.Main {

Wrong, old version of App.xml:

x:Class="Test.Main"

Good, new version of App.xml:

x:Class="Test.Main.App"

Python: Select subset from list based on index set

I see 2 options.

  1. Using numpy:

    property_a = numpy.array([545., 656., 5.4, 33.])
    property_b = numpy.array([ 1.2,  1.3, 2.3, 0.3])
    good_objects = [True, False, False, True]
    good_indices = [0, 3]
    property_asel = property_a[good_objects]
    property_bsel = property_b[good_indices]
    
  2. Using a list comprehension and zip it:

    property_a = [545., 656., 5.4, 33.]
    property_b = [ 1.2,  1.3, 2.3, 0.3]
    good_objects = [True, False, False, True]
    good_indices = [0, 3]
    property_asel = [x for x, y in zip(property_a, good_objects) if y]
    property_bsel = [property_b[i] for i in good_indices]
    

What charset does Microsoft Excel use when saving files?

cp1250 is used extensively in Microsoft Office documents, including Word and Excel 2003.

http://en.wikipedia.org/wiki/Windows-1250

A simple way to confirm this would be to:

  1. Create a spreadsheet with higher order characters, e.g. "Veszprém" in one of the cells;
  2. Use your favourite scripting language to parse and decode the spreadsheet;
  3. Look at what your script produces when you print out the decoded data.

Example perl script:

#!perl

use strict;

use Spreadsheet::ParseExcel::Simple;
use Encode qw( decode );

my $file    = "my_spreadsheet.xls";

my $xls     = Spreadsheet::ParseExcel::Simple->read( $file );
my $sheet   = [ $xls->sheets ]->[0];

while ($sheet->has_data) {

    my @data = $sheet->next_row;

    for my $datum ( @data ) {
        print decode( 'cp1250', $datum );
    }

}

What is tempuri.org?

Probably to guarantee that public webservices will be unique.

It always makes me think of delicious deep fried treats...

Java Web Service client basic authentication

To make your life simpler, you may want to consider using JAX-WS framework such as Apache CXF or Apache Axis2.

Here is the link that describes how to setup WS-Security for Apache CXF -> http://cxf.apache.org/docs/ws-security.html

EDIT By the way, the Authorization field just uses simple Base64 encoding. According to this ( http://www.motobit.com/util/base64-decoder-encoder.asp ), the decoded value is german:german.

Convert DataTable to List<T>

Create a list with type<DataRow> by extend the datatable with AsEnumerable call.

var mylist = dt.AsEnumerable().ToList();

Cheers!! Happy Coding

UPDATE if exists else INSERT in SQL Server 2008

Many people will suggest you use MERGE, but I caution you against it. By default, it doesn't protect you from concurrency and race conditions any more than multiple statements, but it does introduce other dangers:

http://www.mssqltips.com/sqlservertip/3074/use-caution-with-sql-servers-merge-statement/

Even with this "simpler" syntax available, I still prefer this approach (error handling omitted for brevity):

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
UPDATE dbo.table SET ... WHERE PK = @PK;
IF @@ROWCOUNT = 0
BEGIN
  INSERT dbo.table(PK, ...) SELECT @PK, ...;
END
COMMIT TRANSACTION;

A lot of folks will suggest this way:

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
IF EXISTS (SELECT 1 FROM dbo.table WHERE PK = @PK)
BEGIN
  UPDATE ...
END
ELSE
BEGIN
  INSERT ...
END
COMMIT TRANSACTION;

But all this accomplishes is ensuring you may need to read the table twice to locate the row(s) to be updated. In the first sample, you will only ever need to locate the row(s) once. (In both cases, if no rows are found from the initial read, an insert occurs.)

Others will suggest this way:

BEGIN TRY
  INSERT ...
END TRY
BEGIN CATCH
  IF ERROR_NUMBER() = 2627
    UPDATE ...
END CATCH

However, this is problematic if for no other reason than letting SQL Server catch exceptions that you could have prevented in the first place is much more expensive, except in the rare scenario where almost every insert fails. I prove as much here:

Not sure what you think you gain by having a single statement; I don't think you gain anything. MERGE is a single statement but it still has to really perform multiple operations anyway - even though it makes you think it doesn't.

Enable the display of line numbers in Visual Studio

In VS 2010:

Tools > Settings > Expert Settings

Then:

Tools > Options > Show all settings > Text editor > C# > General > Check Line Numbers (checkbox)

IOError: [Errno 32] Broken pipe: Python

To bring Alex L.'s helpful answer, akhan's helpful answer, and Blckknght's helpful answer together with some additional information:

  • Standard Unix signal SIGPIPE is sent to a process writing to a pipe when there's no process reading from the pipe (anymore).

    • This is not necessarily an error condition; some Unix utilities such as head by design stop reading prematurely from a pipe, once they've received enough data.
  • By default - i.e., if the writing process does not explicitly trap SIGPIPE - the writing process is simply terminated, and its exit code is set to 141, which is calculated as 128 (to signal termination by signal in general) + 13 (SIGPIPE's specific signal number).

  • By design, however, Python itself traps SIGPIPE and translates it into a Python IOError instance with errno value errno.EPIPE, so that a Python script can catch it, if it so chooses - see Alex L.'s answer for how to do that.

  • If a Python script does not catch it, Python outputs error message IOError: [Errno 32] Broken pipe and terminates the script with exit code 1 - this is the symptom the OP saw.

  • In many cases this is more disruptive than helpful, so reverting to the default behavior is desirable:

    • Using the signal module allows just that, as stated in akhan's answer; signal.signal() takes a signal to handle as the 1st argument and a handler as the 2nd; special handler value SIG_DFL represents the system's default behavior:

      from signal import signal, SIGPIPE, SIG_DFL
      signal(SIGPIPE, SIG_DFL) 
      

How do you overcome the HTML form nesting limitation?

This discussion is still of interest to me. Behind the original post are "requirements" which the OP seems to share - i.e. a form with backward compatibility. As someone whose work at the time of writing must sometimes support back to IE6 (and for years to come), I dig that.

Without pushing the framework (all organizations are going to want to reassure themselves on compatibility/robustness, and I'm not using this discussion as justification for the framework), the Drupal solutions to this issue are interesting. Drupal is also directly relevant because the framework has had a long time policy of "it should work without Javascript (only if you want)" i.e. the OP's issue.

Drupal uses it's rather extensive form.inc functions to find the triggering_element (yes, that's the name in code). See the bottom of the code listed on the API page for form_builder (if you'd like to dig into details, the source is recommended - drupal-x.xx/includes/form.inc). The builder uses automatic HTML attribute generation and, via that, can on return detect which button was pressed, and act accordingly (these can be set up to run separate processes too).

Beyond the form builder, Drupal splits data 'delete' actions into separate URLs/forms, likely for the reasons mentioned in the original post. This needs some sort of search/listing step (groan another form! but is user-friendly) as a preliminary. But this has the advantage of eliminating the "submit everything" issue. The big form with the data is used for it's intended purpose, data creation/updating (or even a 'merge' action).

In other words, one way of working around the problem is to devolve the form into two, then the problem vanishes (and the HTML methods can be corrected through a POST too).

Error - Android resource linking failed (AAPT2 27.0.3 Daemon #0)

In case you run into this: in my case I had a translated string, but the string did not yet appear in the default strings.xml. Added the missing string to strings.xml and it got resolved.

Select top 1 result using JPA

The easiest way is by using @Query with NativeQuery option like below:

@Query(value="SELECT 1 * FROM table ORDER BY anyField DESC LIMIT 1", nativeQuery = true)

How to create named and latest tag in Docker?

Variation of Aaron's answer. Using sed without temporary files

#!/bin/bash
VERSION=1.0.0
IMAGE=company/image
ID=$(docker build  -t ${IMAGE}  .  | tail -1 | sed 's/.*Successfully built \(.*\)$/\1/')

docker tag ${ID} ${IMAGE}:${VERSION}
docker tag -f ${ID} ${IMAGE}:latest

How to dynamically update labels captions in VBA form?

Use Controls object

For i = 1 To X
    Controls("Label" & i).Caption =  MySheet.Cells(i + 1, i).Value
Next

How to print an exception in Python 3?

Try

try:
    print undefined_var
except Exception as e:
    print(e)

this will print the representation given by e.__str__():

"name 'undefined_var' is not defined"

you can also use:

print(repr(e))

which will include the Exception class name:

"NameError("name 'undefined_var' is not defined",)"

Check for special characters (/*-+_@&$#%) in a string?

string s = @"$KUH% I*$)OFNlkfn$";
var withoutSpecial = new string(s.Where(c => Char.IsLetterOrDigit(c) 
                                            || Char.IsWhiteSpace(c)).ToArray());

if (s != withoutSpecial)
{
    Console.WriteLine("String contains special chars");
}

How do I build an import library (.lib) AND a DLL in Visual C++?

Does your DLL project have any actual exports? If there are no exports, the linker will not generate an import library .lib file.

In the non-Express version of VS, the import libray name is specfied in the project settings here:

Configuration Properties/Linker/Advanced/Import Library

I assume it's the same in Express (if it even provides the ability to configure the name).

Why can I not create a wheel in python?

I also ran into this all of a sudden, after it had previously worked, and it was because I was inside a virtualenv, and wheel wasn’t installed in the virtualenv.

Print time in a batch file (milliseconds)

You have to be careful with what you want to do, because it is not just about to get the time.

The batch has internal variables to represent the date and the tme: %DATE% %TIME%. But they dependent on the Windows Locale.

%Date%:

  • dd.MM.yyyy
  • dd.MM.yy
  • d.M.yy
  • dd/MM/yy
  • yyyy-MM-dd

%TIME%:

  • H:mm:ss,msec
  • HH:mm:ss,msec

Now, how long your script will work and when? For example, if it will be longer than a day and does pass the midnight it will definitely goes wrong, because difference between 2 timestamps between a midnight is a negative value! You need the date to find out correct distance between days, but how you do that if the date format is not a constant? Things with %DATE% and %TIME% might goes worser and worser if you continue to use them for the math purposes.

The reason is the %DATE% and %TIME% are exist is only to show a date and a time to user in the output, not to use them for calculations. So if you want to make correct distance between some time values or generate some unique value dependent on date and time then you have to use something different and accurate than %DATE% and %TIME%.

I am using the wmic windows builtin utility to request such things (put it in a script file):

for /F "usebackq tokens=1,2 delims==" %%i in (`wmic os get LocalDateTime /VALUE`) do if "%%i" == "LocalDateTime" echo.%%j

or type it in the cmd.exe console:

for /F "usebackq tokens=1,2 delims==" %i in (`wmic os get LocalDateTime /VALUE`) do @if "%i" == "LocalDateTime" echo.%j

The disadvantage of this is a slow performance in case of frequent calls. On mine machine it is about 12 calls per second.

If you want to continue use this then you can write something like this (get_datetime.bat):

@echo off

rem Description:
rem   Independent to Windows locale date/time request.

rem Drop last error level
cd .

rem drop return value
set "RETURN_VALUE="

for /F "usebackq tokens=1,2 delims==" %%i in (`wmic os get LocalDateTime /VALUE 2^>NUL`) do if "%%i" == "LocalDateTime" set "RETURN_VALUE=%%j"

if not "%RETURN_VALUE%" == "" (
  set "RETURN_VALUE=%RETURN_VALUE:~0,18%"
  exit /b 0
)

exit /b 1

Now, you can parse %RETURN_VALUE% somethere in your script:

call get_datetime.bat
set "FILE_SUFFIX=%RETURN_VALUE:.=_%"
set "FILE_SUFFIX=%FILE_SUFFIX:~8,2%_%FILE_SUFFIX:~10,2%_%FILE_SUFFIX:~12,6%"
echo.%FILE_SUFFIX%

Compiling an application for use in highly radioactive environments

How about running many instances of your application. If crashes are due to random memory bit changes, chances are some of your app instances will make it through and produce accurate results. It's probably quite easy (for someone with statistical background) to calculate how many instances do you need given bit flop probability to achieve as tiny overall error as you wish.

Git stash pop- needs merge, unable to refresh index

If anyone is having this issue outside of a merge/conflict/action, then it could be the git lock file for your project causing the issue.

git reset
     fatal: Unable to create '/PATH_TO_PROJECT/.git/index.lock': File exists.
rm -f /PATH_TO_PROJECT/.git/index.lock
git reset
git stash pop

Start script missing error when running npm start

should avoid using unstable npm version.

I observed one thing that is npm version based issue, npm version 4.6.1 is the stable one but 5.x is unstable because package.json will be configured perfectly while creating with default template if it's a stable version and so we manually don't need to add that scripts.

I got the below issue on the npm 5 so I downgraded to npm 4.6.1 then its worked for me,


ERROR: npm 5 is not supported yet


It looks like you're using npm 5 which was recently released.

Create React Native App doesn't work with npm 5 yet, unfortunately. We recommend using npm 4 or yarn until some bugs are resolved.

You can follow the known issues with npm 5 at: https://github.com/npm/npm/issues/16991


Devas-MacBook-Air:SampleTestApp deva$ npm start npm ERR! missing script: start

What is the difference between Bootstrap .container and .container-fluid classes?

Use .container-fluid when you want your page to shapeshift with every little difference in its viewport size.

Use .container when you want your page to shapeshift to only 4 kinds of sizes, which are also known as "breakpoints".

The breakpoints corresponding to their sizes are:

  • Extra Small: (Only Mobile Resolution)
  • Small: 768px (Tablets)
  • Medium: 992px (Laptops)
  • Large: 1200px (Laptops/Desktops)

Static methods in Python?

You don't really need to use the @staticmethod decorator. Just declaring a method (that doesn't expect the self parameter) and call it from the class. The decorator is only there in case you want to be able to call it from an instance as well (which was not what you wanted to do)

Mostly, you just use functions though...

Storing and retrieving datatable from session

To store DataTable in Session:

DataTable dtTest = new DataTable();
Session["dtTest"] = dtTest; 

To retrieve DataTable from Session:

DataTable dt = (DataTable) Session["dtTest"];

What is the difference between DAO and Repository patterns?

In the spring framework, there is an annotation called the repository, and in the description of this annotation, there is useful information about the repository, which I think it is useful for this discussion.

Indicates that an annotated class is a "Repository", originally defined by Domain-Driven Design (Evans, 2003) as "a mechanism for encapsulating storage, retrieval, and search behavior which emulates a collection of objects".

Teams implementing traditional Java EE patterns such as "Data Access Object" may also apply this stereotype to DAO classes, though care should be taken to understand the distinction between Data Access Object and DDD-style repositories before doing so. This annotation is a general-purpose stereotype and individual teams may narrow their semantics and use as appropriate.

A class thus annotated is eligible for Spring DataAccessException translation when used in conjunction with a PersistenceExceptionTranslationPostProcessor. The annotated class is also clarified as to its role in the overall application architecture for the purpose of tooling, aspects, etc.

"Adaptive Server is unavailable or does not exist" error connecting to SQL Server from PHP

I had the same issue, my problem was that the firewall on the server wasn't open from the current ip address.

How to make bootstrap column height to 100% row height?

@Alan's answer will do what you're looking for, but this solution fails when you use the responsive capabilities of Bootstrap. In your case, you're using the xs sizes so you won't notice, but if you used anything else (e.g. col-sm, col-md, etc), you'd understand.

Another approach is to play with margins and padding. See the updated fiddle: http://jsfiddle.net/jz8j247x/1/

.left-side {
  background-color: blue;
  padding-bottom: 1000px;
  margin-bottom: -1000px;
  height: 100%;
}
.something {
  height: 100%;
  background-color: red;
  padding-bottom: 1000px;
  margin-bottom: -1000px;
  height: 100%;
}
.row {
  background-color: green;
  overflow: hidden;
}

Converting a POSTMAN request to Curl

Starting from Postman 8 you need to visit here

enter image description here

Comparing two strings in C?

To compare two C strings (char *), use strcmp(). The function returns 0 when the strings are equal, so you would need to use this in your code:

if (strcmp(namet2, nameIt2) != 0)

If you (wrongly) use

if (namet2 != nameIt2)

you are comparing the pointers (addresses) of both strings, which are unequal when you have two different pointers (which is always the case in your situation).

ruby 1.9: invalid byte sequence in UTF-8

attachment = file.read

begin
   # Try it as UTF-8 directly
   cleaned = attachment.dup.force_encoding('UTF-8')
   unless cleaned.valid_encoding?
     # Some of it might be old Windows code page
     cleaned = attachment.encode( 'UTF-8', 'Windows-1252' )
   end
   attachment = cleaned
 rescue EncodingError
   # Force it to UTF-8, throwing out invalid bits
   attachment = attachment.force_encoding("ISO-8859-1").encode("utf-8", replace: nil)
 end

How to get rid of the "No bootable medium found!" error in Virtual Box?

Try this:

Go to virtual box > right click the OS > settings > under one of the many tab that I don't remember(sorry for this, i dont have vbox installed)> locate the VDI (virtual box disk image) file..

and save the settings.. then try to start the OS..

Apache giving 403 forbidden errors

restorecon command works as below :

restorecon -v -R /var/www/html/

python: restarting a loop

You may want to consider using a different type of loop where that logic is applicable, because it is the most obvious answer.

perhaps a:

i=2
while i < n:
    if something:
       do something
       i += 1
    else: 
       do something else  
       i = 2 #restart the loop  

Byte and char conversion in Java

A character in Java is a Unicode code-unit which is treated as an unsigned number. So if you perform c = (char)b the value you get is 2^16 - 56 or 65536 - 56.

Or more precisely, the byte is first converted to a signed integer with the value 0xFFFFFFC8 using sign extension in a widening conversion. This in turn is then narrowed down to 0xFFC8 when casting to a char, which translates to the positive number 65480.

From the language specification:

5.1.4. Widening and Narrowing Primitive Conversion

First, the byte is converted to an int via widening primitive conversion (§5.1.2), and then the resulting int is converted to a char by narrowing primitive conversion (§5.1.3).


To get the right point use char c = (char) (b & 0xFF) which first converts the byte value of b to the positive integer 200 by using a mask, zeroing the top 24 bits after conversion: 0xFFFFFFC8 becomes 0x000000C8 or the positive number 200 in decimals.


Above is a direct explanation of what happens during conversion between the byte, int and char primitive types.

If you want to encode/decode characters from bytes, use Charset, CharsetEncoder, CharsetDecoder or one of the convenience methods such as new String(byte[] bytes, Charset charset) or String#toBytes(Charset charset). You can get the character set (such as UTF-8 or Windows-1252) from StandardCharsets.

How do I select the parent form based on which submit button is clicked?

You can select the form like this:

$("#submit").click(function(){
    var form = $(this).parents('form:first');
    ...
});

However, it is generally better to attach the event to the submit event of the form itself, as it will trigger even when submitting by pressing the enter key from one of the fields:

$('form#myform1').submit(function(e){
     e.preventDefault(); //Prevent the normal submission action
     var form = this;
     // ... Handle form submission
});

To select fields inside the form, use the form context. For example:

$("input[name='somename']",form).val();

How do you run a command for each line of a file?

if you have a nice selector (for example all .txt files in a dir) you could do:

for i in *.txt; do chmod 755 "$i"; done

bash for loop

or a variant of yours:

while read line; do chmod 755 "$line"; done < file.txt

How do I print colored output with Python 3?

Try this way, without import modules, just use colors code numbers, defined as constants:

BLUE = '34m'
message = 'hello friends'


def display_colored_text(color, text):
    colored_text = f"\033[{color}{text}\033[00m"
    return colored_text

Example:

>>> print(display_colored_text(BLUE, message))
hello friends

How to get full REST request body using Jersey?

It does seem you would have to use a MessageBodyReader here. Here's an example, using jdom:

import org.jdom.Document;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.Provider;
import javax.ws.rs.ext.MediaType;
import javax.ws.rs.ext.MultivaluedMap;
import java.lang.reflect.Type;
import java.lang.annotation.Annotation;
import java.io.InputStream;

@Provider // this annotation is necessary!
@ConsumeMime("application/xml") // this is a hint to the system to only consume xml mime types
public class XMLMessageBodyReader implements MessageBodyReader<Document> {
  private SAXBuilder builder = new SAXBuilder();

  public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) {
    // check if we're requesting a jdom Document
    return Document.class.isAssignableFrom(type);
  }

  public Document readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) {
    try {
      return builder.build(entityStream);
    }
    catch (Exception e) {
      // handle error somehow
    }
  } 
}

Add this class to the list of resources your jersey deployment will process (usually configured via web.xml, I think). You can then use this reader in one of your regular resource classes like this:

@Path("/somepath") @POST
public void handleXMLData(Document doc) {
  // do something with the document
}

I haven't verified that this works exactly as typed, but that's the gist of it. More reading here:

Timestamp conversion in Oracle for YYYY-MM-DD HH:MM:SS format

INSERT INTO AM_PROGRAM_TUNING_EVENT_TMP1 
VALUES(TO_DATE('2012-03-28 11:10:00','yyyy/mm/dd hh24:mi:ss'));

http://www.sqlfiddle.com/#!4/22115/1

Which loop is faster, while or for?

I was wondering the same thing so i googled and ended up here. I did a small test in python (extremely simple) just to see and this is what I got:

For:

def for_func(n = 0):
    for n in range(500):
        n = n + 1

python -m timeit "import for_func; for_func.for_func()" > for_func.txt

10000 loops, best of 3: 40.5 usec per loop

While:

def while_func(n = 0):
    while n < 500:
        n = n + 1

python -m timeit "import while_func; while_func.while_func()" > while_func.txt

10000 loops, best of 3: 45 usec per loop

How do I change Eclipse to use spaces instead of tabs?

For Default Editor:

Window » Preferences » Editors » Text Editors » Insert spaces for tabs

enter image description here

For Java editor

Window » Preferences » Java » Code Style » Formatter » Edit » Indentation » Tab policy "Spaces Only"

enter image description here

Spring @Transactional read-only propagation

By default transaction propagation is REQUIRED, meaning that the same transaction will propagate from a transactional caller to transactional callee. In this case also the read-only status will propagate. E.g. if a read-only transaction will call a read-write transaction, the whole transaction will be read-only.

Could you use the Open Session in View pattern to allow lazy loading? That way your handle method does not need to be transactional at all.

Add values to app.config and retrieve them

sorry for late answer but may be my code may help u.

I placed 3 buttons on the winform surface. button1 & 2 will set different value and button3 will retrieve current value. so when run my code first add the reference System.configuration

and click on first button and then click on 3rd button to see what value has been set. next time again click on second & 3rd button to see again what value has been set after change.

so here is the code.

using System.Configuration;

 private void button1_Click(object sender, EventArgs e)
{
    Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
    config.AppSettings.Settings.Remove("DBServerName");
    config.AppSettings.Settings.Add("DBServerName", "FirstAddedValue1");
    config.Save(ConfigurationSaveMode.Modified);
}

private void button2_Click(object sender, EventArgs e)
{
    Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
    config.AppSettings.Settings.Remove("DBServerName");
    config.AppSettings.Settings.Add("DBServerName", "SecondAddedValue1");
    config.Save(ConfigurationSaveMode.Modified);
}

private void button3_Click(object sender, EventArgs e)
{
    Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
          MessageBox.Show(config.AppSettings.Settings["DBServerName"].Value);
}

How to install PyQt4 in anaconda?

Updated version of @Alaaedeen's answer. You can specify any part of the version of any package you want to install. This may cause other package versions to change. For example, if you don't care about which specific version of PyQt4 you want, do:

conda install pyqt=4

This would install the latest minor version and release of PyQt 4. You can specify any portion of the version that you want, not just the major number. So, for example

conda install pyqt=4.11

would install the latest (or last) release of version 4.11.

Keep in mind that installing a different version of a package may cause the other packages that depend on it to be rolled forward or back to where they support the version you want.

Is there a keyboard shortcut (hotkey) to open Terminal in macOS?

I tested the following procedure under macOS Mojave 10.14.6 (18G3020).

Launch Automator. Create a document of type “Quick Action”:

quick action template

(In older versions of macOS, use the “Service” template.)

In the new Automator document, add a “Run AppleScript” action. (You can type “run applescript” into the search field at the top of the action list to find it.) Here's the AppleScript to paste into the action:

on run {input, parameters}
    tell application "Terminal"
        if it is running then
            do script ""
        end if
        activate
    end tell
end run

Set the “Workflow receives” popup to “no input”. It should look like this overall:

workflow with applescript

Save the document with the name “New Terminal”. Then go to the Automator menu (or the app menu in any running application) and open the Services submenu. You should now see the “New Terminal” quick action:

New Terminal service menu item

If you click the “New Terminal” menu item, you'll get a dialog box:

permission dialog

Click OK to allow the action to run. You'll see this dialog once in each application that's frontmost when you use the action. In other words, the first time you use the action while Finder is frontmost, you'll see the dialog. And the first time you use the action while Safari is frontmost, you'll see the dialog. And so on.

After you click OK in the dialog, Terminal should open a new window.

To assign a keyboard shortcut to the quick action, choose the “Services Preferences…” item from the Services menu. (Or launch System Preferences, choose the Keyboard pane, then choose the Shortcuts tab, then choose Services from the left-hand list.) Scroll to the bottom of the right-hand list and find the New Terminal service. Click it and you should see an “Add Shortcut” button:

add shortcut button

Click the button and press your preferred keyboard shortcut. Then, scratch your head, because (when I tried it) the Add Shortcut button reappears. But click the button again and you should see your shortcut:

keyboard shortcut set

Now you should be able to press your keyboard shortcut in most circumstances to get a new terminal window.

momentJS date string add 5 days

UPDATED: January 19, 2016

As of moment 2.8.4 - use .add(5, 'd') (or .add(5, 'days')) instead of .add('d', 5)

var new_date = moment(startdate, "DD-MM-YYYY").add(5, 'days');

Thanks @Bala for the information.

UPDATED: March 21, 2014

This is what you'd have to do to get that format.

Here's an updated fiddle

startdate = "20.03.2014";
var new_date = moment(startdate, "DD-MM-YYYY").add('days', 5);

var day = new_date.format('DD');
var month = new_date.format('MM');
var year = new_date.format('YYYY');

alert(day + '.' + month + '.' + year);

ORIGINAL: March 20, 2014

You're not telling it how/what unit to add. Use -

 var new_date = moment(startdate, "DD-MM-YYYY").add('days', 5);

How can I verify if a Windows Service is running

I guess something like this would work:

Add System.ServiceProcess to your project references (It's on the .NET tab).

using System.ServiceProcess;

ServiceController sc = new ServiceController(SERVICENAME);

switch (sc.Status)
{
    case ServiceControllerStatus.Running:
        return "Running";
    case ServiceControllerStatus.Stopped:
        return "Stopped";
    case ServiceControllerStatus.Paused:
        return "Paused";
    case ServiceControllerStatus.StopPending:
        return "Stopping";
    case ServiceControllerStatus.StartPending:
        return "Starting";
    default:
        return "Status Changing";
}

Edit: There is also a method sc.WaitforStatus() that takes a desired status and a timeout, never used it but it may suit your needs.

Edit: Once you get the status, to get the status again you will need to call sc.Refresh() first.

Reference: ServiceController object in .NET.

How to call a JavaScript function within an HTML body

First include the file in head tag of html , then call the function in script tags under body tags e.g.

Js file function to be called

function tryMe(arg) {
    document.write(arg);
}

HTML FILE

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src='object.js'> </script>
    <title>abc</title><meta charset="utf-8"/>
</head>
<body>
    <script>
    tryMe('This is me vishal bhasin signing in');
    </script>
</body>
</html>

finish

Pandas: Setting no. of max rows

Set display.max_rows:

pd.set_option('display.max_rows', 500)

For older versions of pandas (<=0.11.0) you need to change both display.height and display.max_rows.

pd.set_option('display.height', 500)
pd.set_option('display.max_rows', 500)

See also pd.describe_option('display').

You can set an option only temporarily for this one time like this:

from IPython.display import display
with pd.option_context('display.max_rows', 100, 'display.max_columns', 10):
    display(df) #need display to show the dataframe when using with in jupyter
    #some pandas stuff

You can also reset an option back to its default value like this:

pd.reset_option('display.max_rows')

And reset all of them back:

pd.reset_option('all')

How to check is Apache2 is stopped in Ubuntu?

You can also type "top" and look at the list of running processes.

Java constant examples (Create a java file having only constants)

Both are valid but I normally choose interfaces. A class (abstract or not) is not needed if there is no implementations.

As an advise, try to choose the location of your constants wisely, they are part of your external contract. Do not put every single constant in one file.

For example, if a group of constants is only used in one class or one method put them in that class, the extended class or the implemented interfaces. If you do not take care you could end up with a big dependency mess.

Sometimes an enumeration is a good alternative to constants (Java 5), take look at: http://docs.oracle.com/javase/1.5.0/docs/guide/language/enums.html

How to test if a string contains one of the substrings in a list, in pandas?

You can use str.contains alone with a regex pattern using OR (|):

s[s.str.contains('og|at')]

Or you could add the series to a dataframe then use str.contains:

df = pd.DataFrame(s)
df[s.str.contains('og|at')] 

Output:

0 cat
1 hat
2 dog
3 fog 

Setting a property with an EventTrigger

As much as I love XAML, for this kinds of tasks I switch to code behind. Attached behaviors are a good pattern for this. Keep in mind, Expression Blend 3 provides a standard way to program and use behaviors. There are a few existing ones on the Expression Community Site.

What does a (+) sign mean in an Oracle SQL WHERE clause?

This is an Oracle-specific notation for an outer join. It means that it will include all rows from t1, and use NULLS in the t0 columns if there is no corresponding row in t0.

In standard SQL one would write:

SELECT t0.foo, t1.bar
  FROM FIRST_TABLE t0
 RIGHT OUTER JOIN SECOND_TABLE t1;

Oracle recommends not to use those joins anymore if your version supports ANSI joins (LEFT/RIGHT JOIN) :

Oracle recommends that you use the FROM clause OUTER JOIN syntax rather than the Oracle join operator. Outer join queries that use the Oracle join operator (+) are subject to the following rules and restrictions […]

Simple PowerShell LastWriteTime compare

I can't fault any of the answers here for the OP accepted one of them as resolving their problem. However, I found them flawed in one respect. When you output the result of the assignment to the variable, it contains numerous blank lines, not just the sought after answer. Example:

PS C:\brh> [datetime](Get-ItemProperty -Path .\deploy.ps1 -Name LastWriteTime).LastWriteTime

Friday, December 12, 2014 2:33:09 PM



PS C:\brh> 

I'm a fan of two things in code, succinctness and correctness. brianary has the right of it for succinctness with a tip of the hat to Roger Lipscombe but both miss correctness due to the extra lines in the result. Here's what I think the OP was looking for since it's what got me over the finish line.

PS C:\brh> (ls .\deploy.ps1).LastWriteTime.DateTime
Friday, December 12, 2014 2:33:09 PM

PS C:\brh> 

Note the lack of extra lines, only the one that PowerShell uses to separate prompts. Now this can be assigned to a variable for comparison or, as in my case, stored in a file for reading and comparison in a later session.

Set TextView text from html-formatted string resource in XML

As the top answer here is suggesting something wrong (or at least too complicated), I feel this should be updated, although the question is quite old:

When using String resources in Android, you just have to call getString(...) from Java code or use android:text="@string/..." in your layout XML.

Even if you want to use HTML markup in your Strings, you don't have to change a lot:

The only characters that you need to escape in your String resources are:

  • double quotation mark: " becomes \"
  • single quotation mark: ' becomes \'
  • ampersand: & becomes &#38; or &amp;

That means you can add your HTML markup without escaping the tags:

<string name="my_string"><b>Hello World!</b> This is an example.</string>

However, to be sure, you should only use <b>, <i> and <u> as they are listed in the documentation.

If you want to use your HTML strings from XML, just keep on using android:text="@string/...", it will work fine.

The only difference is that, if you want to use your HTML strings from Java code, you have to use getText(...) instead of getString(...) now, as the former keeps the style and the latter will just strip it off.

It's as easy as that. No CDATA, no Html.fromHtml(...).

You will only need Html.fromHtml(...) if you did encode your special characters in HTML markup. Use it with getString(...) then. This can be necessary if you want to pass the String to String.format(...).

This is all described in the docs as well.

Edit:

There is no difference between getText(...) with unescaped HTML (as I've proposed) or CDATA sections and Html.fromHtml(...).

See the following graphic for a comparison:

enter image description here

How to suppress Pandas Future warning ?

Warnings are annoying. As mentioned in other answers, you can suppress them using:

import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)

But if you want to handle them one by one and you are managing a bigger codebase, it will be difficult to find the line of code which is causing the warning. Since warnings unlike errors don't come with code traceback. In order to trace warnings like errors, you can write this at the top of the code:

import warnings
warnings.filterwarnings("error")

But if the codebase is bigger and it is importing bunch of other libraries/packages, then all sort of warnings will start to be raised as errors. In order to raise only certain type of warnings (in your case, its FutureWarning) as error, you can write:

import warnings
warnings.simplefilter(action='error', category=FutureWarning)

How can I initialise a static Map?

One advantage to the second method is that you can wrap it with Collections.unmodifiableMap() to guarantee that nothing is going to update the collection later:

private static final Map<Integer, String> CONSTANT_MAP = 
    Collections.unmodifiableMap(new HashMap<Integer, String>() {{ 
        put(1, "one");
        put(2, "two");
    }});

 // later on...

 CONSTANT_MAP.put(3, "three"); // going to throw an exception!

XML Schema Validation : Cannot find the declaration of element

cvc-elt.1: Cannot find the declaration of element 'Root'. [7]

Your schemaLocation attribute on the root element should be xsi:schemaLocation, and you need to fix it to use the right namespace.

You should probably change the targetNamespace of the schema and the xmlns of the document to http://myNameSpace.com (since namespaces are supposed to be valid URIs, which Test.Namespace isn't, though urn:Test.Namespace would be ok). Once you do that it should find the schema. The point is that all three of the schema's target namespace, the document's namespace, and the namespace for which you're giving the schema location must be the same.

(though it still won't validate as your <element2> contains an <element3> in the document where the schema expects item)

JOptionPane Input to int

// sample code for addition using JOptionPane

import javax.swing.JOptionPane;

public class Addition {

    public static void main(String[] args) {

        String firstNumber = JOptionPane.showInputDialog("Input <First Integer>");

        String secondNumber = JOptionPane.showInputDialog("Input <Second Integer>");

        int num1 = Integer.parseInt(firstNumber);
        int num2 = Integer.parseInt(secondNumber);
        int sum = num1 + num2;
        JOptionPane.showMessageDialog(null, "Sum is" + sum, "Sum of two Integers", JOptionPane.PLAIN_MESSAGE);
    }
}

Caused by: java.security.UnrecoverableKeyException: Cannot recover key

I had the same error when we imported a key into a keystore that was build using a 64bit OpenSSL Version. When we followed the same procedure to import the key into a keystore that was build using a 32 bit OpenSSL version everything went fine.

How to use default Android drawables

As far as i remember, the documentation advises against using the menu icons from android.R.drawable directly and recommends copying them to your drawables folder. The main reason is that those icons and names can be subject to change and may not be available in future releases.

Warning: Because these resources can change between platform versions, you should not reference these icons using the Android platform resource IDs (i.e. menu icons under android.R.drawable). If you want to use any icons or other internal drawable resources, you should store a local copy of those icons or drawables in your application resources, then reference the local copy from your application code. In that way, you can maintain control over the appearance of your icons, even if the system's copy changes.

from: http://developer.android.com/guide/practices/ui_guidelines/icon_design_menu.html

Possible to change where Android Virtual Devices are saved?

Please take note of the following : modifying android.bat in the Android tools directory, as suggested in a previous answer, may lead to problems.

If you do so, in order to legitimately have your .android directory located to a non-default location then there may be an inconsistency between the AVDs listed by Android Studio (using "Tools > Android > AVD Manager") and the AVDs listed by sdk command line tool "android avd".

I suppose that Android Studio, with its internal AVD Manager, does not use the android.bat modified path ; it relies on the ANDROID_SDK_HOME variable to locate AVDs.

My own tests have shown that Android tools correctly use the ANDROID_SDK_HOME variable.

Therefore, there is no point, as far as I know, in modifying android.bat, and using the environment variable should be preferred.

Python object.__repr__(self) should be an expression?

>>> from datetime import date
>>>
>>> repr(date.today())        # calls date.today().__repr__()
'datetime.date(2009, 1, 16)'
>>> eval(_)                   # _ is the output of the last command
datetime.date(2009, 1, 16)

The output is a string that can be parsed by the python interpreter and results in an equal object.

If that's not possible, it should return a string in the form of <...some useful description...>.

How can I remove the decimal part from JavaScript number?

toFixed will behave like round.

For a floor like behavior use %:

var num = 3.834234;
var floored_num = num - (num % 1); // floored_num will be 3

Getting request URL in a servlet

The getRequestURL() omits the port when it is 80 while the scheme is http, or when it is 443 while the scheme is https.

So, just use getRequestURL() if all you want is obtaining the entire URL. This does however not include the GET query string. You may want to construct it as follows then:

StringBuffer requestURL = request.getRequestURL();
if (request.getQueryString() != null) {
    requestURL.append("?").append(request.getQueryString());
}
String completeURL = requestURL.toString();