Programs & Examples On #Transactionloganalysis

How do you append to a file?

Here's my script, which basically counts the number of lines, then appends, then counts them again so you have evidence it worked.

shortPath  = "../file_to_be_appended"
short = open(shortPath, 'r')

## this counts how many line are originally in the file:
long_path = "../file_to_be_appended_to" 
long = open(long_path, 'r')
for i,l in enumerate(long): 
    pass
print "%s has %i lines initially" %(long_path,i)
long.close()

long = open(long_path, 'a') ## now open long file to append
l = True ## will be a line
c = 0 ## count the number of lines you write
while l: 
    try: 
        l = short.next() ## when you run out of lines, this breaks and the except statement is run
        c += 1
        long.write(l)

    except: 
        l = None
        long.close()
        print "Done!, wrote %s lines" %c 

## finally, count how many lines are left. 
long = open(long_path, 'r')
for i,l in enumerate(long): 
    pass
print "%s has %i lines after appending new lines" %(long_path, i)
long.close()

How to add a boolean datatype column to an existing table in sql?

The answer given by P????? creates a nullable bool, not a bool, which may be fine for you. For example in C# it would create: bool? AdminApprovednot bool AdminApproved.

If you need to create a bool (defaulting to false):

    ALTER TABLE person
    ADD AdminApproved BIT
    DEFAULT 0 NOT NULL;

How to set background color in jquery

You actually got it. Just forgot some quotes.

$(this).css({backgroundColor: 'red'});

or

$(this).css('background-color', 'red');

You don't need to pass over a map/object to set only one property. You can just put pass it as string. Note that if passing an object you cannot use a -. All CSS properties which have such a character are mapped with capital letters.

Reference: .css()

split string only on first instance of specified character

Use capturing parentheses:

"good_luck_buddy".split(/_(.+)/)[1]
"luck_buddy"

They are defined as

If separator contains capturing parentheses, matched results are returned in the array.

So in this case we want to split at _.+ (i.e. split separator being a sub string starting with _) but also let the result contain some part of our separator (i.e. everything after _).

In this example our separator (matching _(.+)) is _luck_buddy and the captured group (within the separator) is lucky_buddy. Without the capturing parenthesis the luck_buddy (matching .+) would've not been included in the result array as it is the case with simple split that separators are not included in the result.

Cloud Firestore collection count

firebaseFirestore.collection("...").addSnapshotListener(new EventListener<QuerySnapshot>() {
        @Override
        public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {

            int Counter = documentSnapshots.size();

        }
    });

C# Foreach statement does not contain public definition for GetEnumerator

You should implement the IEnumerable interface (CarBootSaleList should impl it in your case).

http://msdn.microsoft.com/en-us/library/system.collections.ienumerable.getenumerator.aspx

But it is usually easier to subclass System.Collections.ObjectModel.Collection and friends

http://msdn.microsoft.com/en-us/library/system.collections.objectmodel.aspx

Your code also seems a bit strange, like you are nesting lists?

Is multiplication and division using shift operators in C actually faster?

Just tried on my machine compiling this :

int a = ...;
int b = a * 10;

When disassembling it produces output :

MOV EAX,DWORD PTR SS:[ESP+1C] ; Move a into EAX
LEA EAX,DWORD PTR DS:[EAX+EAX*4] ; Multiply by 5 without shift !
SHL EAX, 1 ; Multiply by 2 using shift

This version is faster than your hand-optimized code with pure shifting and addition.

You really never know what the compiler is going to come up with, so it's better to simply write a normal multiplication and let him optimize the way he wants to, except in very precise cases where you know the compiler cannot optimize.

How to input automatically when running a shell over SSH?

Also you can pipe the answers to the script:

printf "y\npassword\n" | sh test.sh

where \n is escape-sequence

Find nearest latitude/longitude with an SQL query

Try this, it show the nearest points to provided coordinates (within 50 km). It works perfectly:

SELECT m.name,
    m.lat, m.lon,
    p.distance_unit
             * DEGREES(ACOS(COS(RADIANS(p.latpoint))
             * COS(RADIANS(m.lat))
             * COS(RADIANS(p.longpoint) - RADIANS(m.lon))
             + SIN(RADIANS(p.latpoint))
             * SIN(RADIANS(m.lat)))) AS distance_in_km
FROM <table_name> AS m
JOIN (
      SELECT <userLat> AS latpoint, <userLon> AS longpoint,
             50.0 AS radius, 111.045 AS distance_unit
     ) AS p ON 1=1
WHERE m.lat
BETWEEN p.latpoint  - (p.radius / p.distance_unit)
    AND p.latpoint  + (p.radius / p.distance_unit)
    AND m.lon BETWEEN p.longpoint - (p.radius / (p.distance_unit * COS(RADIANS(p.latpoint))))
    AND p.longpoint + (p.radius / (p.distance_unit * COS(RADIANS(p.latpoint))))
ORDER BY distance_in_km

Just change <table_name>. <userLat> and <userLon>

You can read more about this solution here: http://www.plumislandmedia.net/mysql/haversine-mysql-nearest-loc/

<hr> tag in Twitter Bootstrap not functioning correctly?

I think it would look better if we add border-color : transparent as per below:

<hr style="width: 100%; background-color: black; height: 1px; border-color : transparent;" />

If you don't put the border transparent it will be white and i don't think that is good all time.

How do I auto size columns through the Excel interop objects?

Have a look at this article, it's not an exact match to your problem, but suits it:

How do I wait until Task is finished in C#?

I'm an async novice, so I can't tell you definitively what is happening here. I suspect that there's a mismatch in the method execution expectations, even though you are using tasks internally in the methods. I think you'd get the results you are expecting if you changed Print to return a Task<string>:

private static string Send(int id)
{
    Task<HttpResponseMessage> responseTask = client.GetAsync("aaaaa");
    Task<string> result;
    responseTask.ContinueWith(x => result = Print(x));
    result.Wait();
    responseTask.Wait(); // There's likely a better way to wait for both tasks without doing it in this awkward, consecutive way.
    return result.Result;
}

private static Task<string> Print(Task<HttpResponseMessage> httpTask)
{
    Task<string> task = httpTask.Result.Content.ReadAsStringAsync();
    string result = string.Empty;
    task.ContinueWith(t =>
    {
        Console.WriteLine("Result: " + t.Result);
        result = t.Result;
    });
    return task;
}

vector vs. list in STL

One special capability of std::list is splicing (linking or moving part of or a whole list into a different list).

Or perhaps if your contents are very expensive to copy. In such a case it might be cheaper, for example, to sort the collection with a list.

Also note that if the collection is small (and the contents are not particularly expensive to copy), a vector might still outperform a list, even if you insert and erase anywhere. A list allocates each node individually, and that might be much more costly than moving a few simple objects around.

I don't think there are very hard rules. It depends on what you mostly want to do with the container, as well as on how large you expect the container to be and the contained type. A vector generally trumps a list, because it allocates its contents as a single contiguous block (it is basically a dynamically allocated array, and in most circumstances an array is the most efficient way to hold a bunch of things).

How do I mount a remote Linux folder in Windows through SSH?

Dokan looks like a FUSE and sshfs implementation for Windows. If it works as expected and advertised, it would do exactly what you are looking for.

(Link updated and working 2015-10-15)

How to plot a function curve in R

As sjdh also mentioned, ggplot2 comes to the rescue. A more intuitive way without making a dummy data set is to use xlim:

library(ggplot2)
eq <- function(x){sin(x)}
base <- ggplot() + xlim(0, 30)
base + geom_function(fun=eq)

Additionally, for a smoother graph we can set the number of points over which the graph is interpolated using n:

base + geom_function(fun=eq, n=10000)

How to apply a CSS class on hover to dynamically generated submit buttons?

The most efficient selector you can use is an attribute selector.

 input[name="btnPage"]:hover {/*your css here*/}

Here's a live demo: http://tinkerbin.com/3G6B93Cb

Finding what methods a Python object has

To check if it has a particular method:

hasattr(object,"method")

NameError: uninitialized constant (rails)

If none of the above work, I also have a different approach, as it happened to me in a real scenario.

More specifically using auto-generated Ruby files from Thrift.


In my situation, I had a Module with several classes, so the order is important in this case:

Class A makes use of Class B in the same module. However, Class B was declared after Class A.

Simply making Class B to be declared before Class A solved the issue to me.

how to find seconds since 1970 in java

Another option is to use the TimeUtils utility method:

TimeUtils.millisToUnit(System.currentTimeMillis(), TimeUnit.SECONDS)

Java : Cannot format given Object as a Date

public static String showDate(){
    SimpleDateFormat df=new SimpleDateFormat("\nTime:yyyy-MM-dd HH:mm:ss");
    System.out.println(df.format(new Date()));
    String s=df.format(new Date());
    return s;
}

I think this code may solve your problem.

Can we cast a generic object to a custom object type in javascript?

This is just a wrap up of Sayan Pal answer in a shorter form, ES5 style :

var Foo = function(){
    this.bar = undefined;
    this.buzz = undefined;
}

var foo = Object.assign(new Foo(),{
    bar: "whatever",
    buzz: "something else"
});

I like it because it is the closest to the very neat object initialisation in .Net:

var foo = new Foo()
{
    bar: "whatever",
    ...

Interfaces with static fields in java for sharing 'constants'

There is a lot of hate for this pattern in Java. However, an interface of static constants does sometimes have value. You need to basically fulfill the following conditions:

  1. The concepts are part of the public interface of several classes.

  2. Their values might change in future releases.

  3. Its critical that all implementations use the same values.

For example, suppose that you are writing an extension to a hypothetical query language. In this extension you are going to expand the language syntax with some new operations, which are supported by an index. E.g. You are going to have a R-Tree supporting geospatial queries.

So you write a public interface with the static constant:

public interface SyntaxExtensions {
     // query type
     String NEAR_TO_QUERY = "nearTo";

     // params for query
     String POINT = "coordinate";
     String DISTANCE_KM = "distanceInKm";
}

Now later, a new developer thinks he needs to build a better index, so he comes and builds an R* implementation. By implementing this interface in his new tree he guarantees that the different indexes will have identical syntax in the query language. Moreover, if you later decided that "nearTo" was a confusing name, you could change it to "withinDistanceInKm", and know that the new syntax would be respected by all your index implementations.

PS: The inspiration for this example is drawn from the Neo4j spatial code.

Class Not Found: Empty Test Suite in IntelliJ

Deleting .idea and re-importing the SBT project solved this issue for me.

Is there a CSS selector for text nodes?

Text nodes cannot have margins or any other style applied to them, so anything you need style applied to must be in an element. If you want some of the text inside of your element to be styled differently, wrap it in a span or div, for example.

MVC ajax post to controller action method

Your Action is expecting string parameters, but you're sending a composite object.

You need to create an object that matches what you're sending.

public class Data
{
    public string username { get;set; }
    public string password { get;set; }
}

public JsonResult Login(Data data)
{
}

EDIT

In addition, toStringify() is probably not what you want here. Just send the object itself.

data: data,

Is there a minlength validation attribute in HTML5?

In my case, in which I validate the most manually and using Firefox (43.0.4), minlength and validity.tooShort are not available unfortunately.

Since I only need to have minimum lengths stored to proceed, an easy and handy way is to assign this value to another valid attribute of the input tag. In that case then, you can use min, max, and step properties from [type="number"] inputs.

Rather than storing those limits in an array it's easier to find it stored in the same input instead of getting the element id to match the array index.

What is "entropy and information gain"?

I can't give you graphics, but maybe I can give a clear explanation.

Suppose we have an information channel, such as a light that flashes once every day either red or green. How much information does it convey? The first guess might be one bit per day. But what if we add blue, so that the sender has three options? We would like to have a measure of information that can handle things other than powers of two, but still be additive (the way that multiplying the number of possible messages by two adds one bit). We could do this by taking log2(number of possible messages), but it turns out there's a more general way.

Suppose we're back to red/green, but the red bulb has burned out (this is common knowledge) so that the lamp must always flash green. The channel is now useless, we know what the next flash will be so the flashes convey no information, no news. Now we repair the bulb but impose a rule that the red bulb may not flash twice in a row. When the lamp flashes red, we know what the next flash will be. If you try to send a bit stream by this channel, you'll find that you must encode it with more flashes than you have bits (50% more, in fact). And if you want to describe a sequence of flashes, you can do so with fewer bits. The same applies if each flash is independent (context-free), but green flashes are more common than red: the more skewed the probability the fewer bits you need to describe the sequence, and the less information it contains, all the way to the all-green, bulb-burnt-out limit.

It turns out there's a way to measure the amount of information in a signal, based on the the probabilities of the different symbols. If the probability of receiving symbol xi is pi, then consider the quantity

-log pi

The smaller pi, the larger this value. If xi becomes twice as unlikely, this value increases by a fixed amount (log(2)). This should remind you of adding one bit to a message.

If we don't know what the symbol will be (but we know the probabilities) then we can calculate the average of this value, how much we will get, by summing over the different possibilities:

I = -Σ pi log(pi)

This is the information content in one flash.

Red bulb burnt out: pred = 0, pgreen=1, I = -(0 + 0)  = 0
Red and green equiprobable: pred = 1/2, pgreen = 1/2, I = -(2 * 1/2 * log(1/2)) = log(2)
Three colors, equiprobable: pi=1/3, I = -(3 * 1/3 * log(1/3)) = log(3)
Green and red, green twice as likely: pred=1/3, pgreen=2/3, I = -(1/3 log(1/3) + 2/3 log(2/3)) = log(3) - 2/3 log(2)

This is the information content, or entropy, of the message. It is maximal when the different symbols are equiprobable. If you're a physicist you use the natural log, if you're a computer scientist you use log2 and get bits.

get and set in TypeScript

Based on example you show, you want to pass a data object and get a property of that object by get(). for this you need to use generic type, since data object is generic, can be any object.

export class Attributes<T> {
    constructor(private data: T) {}
    get = <K extends keyof T>(key: K): T[K] => {
      return this.data[key];
    };
    set = (update: T): void => {
      //   this is like spread operator. it will take this.data obj and will overwrite with the update obj
      // ins tsconfig.json change target to Es6 to be able to use Object.assign()
      Object.assign(this.data, update);
    };
    getAll(): T {
      return this.data;
    }
  }

< T > refers to generic type. let's initialize an instance

 const myAttributes=new Attributes({name:"something",age:32})

 myAttributes.get("name")="something"

Notice this syntax

<K extends keyof T>

in order to be able to use this we should be aware of 2 things:

1- in typestring strings can be a type.

2- all object properties in javascript essentially are strings.

when we use get(), type of argument that it is receiving is a property of object that passed to constructor and since object properties are strings and strings are allowed to be a type in typescript, we could use this <K extends keyof T>

Programmatically Check an Item in Checkboxlist where text is equal to what I want

I tried adding dynamically created ListItem and assigning the selected value.

foreach(var item in yourListFromDB)
{
 ListItem listItem = new ListItem();
 listItem.Text = item.name;
 listItem.Value = Convert.ToString(item.value);
 listItem.Selected=item.isSelected;                 
  checkedListBox1.Items.Add(listItem);
}
checkedListBox1.DataBind();

avoid using binding the DataSource as it will not bind the checked/unchecked from DB.

In python, how do I cast a class object to a dict

Like many others, I would suggest implementing a to_dict() function rather than (or in addition to) allowing casting to a dictionary. I think it makes it more obvious that the class supports that kind of functionality. You could easily implement such a method like this:

def to_dict(self):
    class_vars = vars(MyClass)  # get any "default" attrs defined at the class level
    inst_vars = vars(self)  # get any attrs defined on the instance (self)
    all_vars = dict(class_vars)
    all_vars.update(inst_vars)
    # filter out private attributes
    public_vars = {k: v for k, v in all_vars.items() if not k.startswith('_')}
    return public_vars

Emulate Samsung Galaxy Tab

Go to this link ... https://github.com/bsodmike/android-avd-profiles-2016/blob/master/Samsung%20Galaxy%20Tab%20A%2010.1%20(2016).xml

Save as xml file in your computer. Go on Android Studio => Tools => AVD Manager => + Create Virtual Device => Import Hardware Profiles ... choose the saved file and the device will be available on the tablet's section.

Happy Android developments guys!!!

How do you decompile a swf file

Get the Sothink SWF decompiler. Not free, but worth it. Recently used it to decompile an SWF that I had lost the fla for, and I could completely round-trip swf-fla and back!
link text

How to pass all arguments passed to my bash script to a function of mine?

I needed a variation on this, which I expect will be useful to others:

function diffs() {
        diff "${@:3}" <(sort "$1") <(sort "$2")
}

The "${@:3}" part means all the members of the array starting at 3. So this function implements a sorted diff by passing the first two arguments to diff through sort and then passing all other arguments to diff, so you can call it similarly to diff:

diffs file1 file2 [other diff args, e.g. -y]

Convert integer to hexadecimal and back again

int to hex:

int a = 72;

Console.WriteLine("{0:X}", a);

hex to int:

int b = 0xB76;

Console.WriteLine(b);

INSERT with SELECT

Correct Syntax: select spelling was wrong

INSERT INTO courses (name, location, gid)
SELECT name, location, 'whatever you want' 
FROM courses 
WHERE cid = $ci 

C# Linq Group By on multiple columns

var consolidatedChildren =
    from c in children
    group c by new
    {
        c.School,
        c.Friend,
        c.FavoriteColor,
    } into gcs
    select new ConsolidatedChild()
    {
        School = gcs.Key.School,
        Friend = gcs.Key.Friend,
        FavoriteColor = gcs.Key.FavoriteColor,
        Children = gcs.ToList(),
    };

var consolidatedChildren =
    children
        .GroupBy(c => new
        {
            c.School,
            c.Friend,
            c.FavoriteColor,
        })
        .Select(gcs => new ConsolidatedChild()
        {
            School = gcs.Key.School,
            Friend = gcs.Key.Friend,
            FavoriteColor = gcs.Key.FavoriteColor,
            Children = gcs.ToList(),
        });

How to Add Stacktrace or debug Option when Building Android Studio Project

For Android Studio 3.1.3 it was under

File -> Settings -> Build, Execution, Deployment -> Compiler

MAC addresses in JavaScript

i was looking for the same problem and stumbled upon the following code.

How to get Client MAC address(Web):

To get the client MAC address only way we can rely on JavaScript and Active X control of Microsoft.It is only work in IE if Active X enable for IE. As the ActiveXObject is not available with the Firefox, its not working with the firefox and is working fine in IE.

This script is for IE only:

_x000D_
_x000D_
function showMacAddress() {_x000D_
    var obj = new ActiveXObject("WbemScripting.SWbemLocator");_x000D_
    var s = obj.ConnectServer(".");_x000D_
    var properties = s.ExecQuery("SELECT * FROM Win32_NetworkAdapterConfiguration");_x000D_
    var e = new Enumerator(properties);_x000D_
    var output;_x000D_
    output = '<table border="0" cellPadding="5px" cellSpacing="1px" bgColor="#CCCCCC">';_x000D_
    output = output + '<tr bgColor="#EAEAEA"><td>Caption</td><td>MACAddress</td></tr>';_x000D_
    while (!e.atEnd()) {_x000D_
        e.moveNext();_x000D_
        var p = e.item();_x000D_
        if (!p) continue;_x000D_
        output = output + '<tr bgColor="#FFFFFF">';_x000D_
        output = output + '<td>' + p.Caption; +'</td>';_x000D_
        output = output + '<td>' + p.MACAddress + '</td>';_x000D_
        output = output + '</tr>';_x000D_
    }_x000D_
    output = output + '</table>';_x000D_
    document.getElementById("box").innerHTML = output;_x000D_
}_x000D_
_x000D_
showMacAddress();
_x000D_
<div id='box'></div>
_x000D_
_x000D_
_x000D_

Java replace all square brackets in a string

_x000D_
_x000D_
   Use this line:) String result = strCurBal.replaceAll("[(" what ever u need to remove ")]", "");_x000D_
_x000D_
    String strCurBal = "(+)3428";_x000D_
    Log.e("Agilanbu before omit ", strCurBal);_x000D_
    String result = strCurBal.replaceAll("[()]", ""); // () removing special characters from string_x000D_
    Log.e("Agilanbu after omit ", result);_x000D_
   _x000D_
    o/p :_x000D_
    Agilanbu before omit : (+)3428_x000D_
    Agilanbu after omit :  +3428_x000D_
_x000D_
    String finalVal = result.replaceAll("[+]", ""); // + removing special characters from string_x000D_
    Log.e("Agilanbu finalVal  ", finalVal);_x000D_
    o/p_x000D_
    Agilanbu finalVal : 3428_x000D_
            _x000D_
    String finalVal1 = result.replaceAll("[+]", "-"); // insert | append | replace the special characters from string_x000D_
    Log.e("Agilanbu finalVal  ", finalVal1);_x000D_
    o/p_x000D_
    Agilanbu finalVal : -3428  // replacing the + symbol to -
_x000D_
_x000D_
_x000D_

How to create an empty array in Swift?

Initiating an array with a predefined count:

Array(repeating: 0, count: 10)

I often use this for mapping statements where I need a specified number of mock objects. For example,

let myObjects: [MyObject] = Array(repeating: 0, count: 10).map { _ in return MyObject() }

How to use bootstrap datepicker

Just add this below JS file

<script type="text/javascript">
    $(document).ready(function () {
        $('your input's id or class with # or .').datepicker({
            format: "dd/mm/yyyy"
        });
    });
</script>

Error in Process.Start() -- The system cannot find the file specified

I had the same problem, but none of the solutions worked for me, because the message The system cannot find the file specified can be misleading in some special cases.

In my case, I use Notepad++ in combination with the registry redirect for notepad.exe. Unfortunately my path to Notepad++ in the registry was wrong.

So in fact the message The system cannot find the file specified was telling me, that it cannot find the application (Notepad++) associated with the file type(*.txt), not the file itself.

How to split a string at the first `/` (slash) and surround part of it in a `<span>`?

use this

<div id="date">23/05/2013</div>
<script type="text/javascript">
$(document).ready(function(){
  var x = $("#date").text();
    x.text(x.substring(0, 2) + '<br />'+x.substring(3));     
});
</script>

Monitoring the Full Disclosure mailinglist

Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.

You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.

But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.

You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.

jQuery select element in parent window

why not both to be sure?

if(opener.document){
  $("#testdiv",opener.document).doStuff();
}else{
  $("#testdiv",window.opener).doStuff();
}

How to get substring from string in c#?

var data =" Retrieves a substring from this instance. The substring starts at a specified character position.";

var result = data.Split(new[] {'.'}, 1)[0];

Output:

Retrieves a substring from this instance. The substring starts at a specified character position.

What is the difference between dict.items() and dict.iteritems() in Python2?

dict.items() return list of tuples, and dict.iteritems() return iterator object of tuple in dictionary as (key,value). The tuples are the same, but container is different.

dict.items() basically copies all dictionary into list. Try using following code to compare the execution times of the dict.items() and dict.iteritems(). You will see the difference.

import timeit

d = {i:i*2 for i in xrange(10000000)}  
start = timeit.default_timer() #more memory intensive
for key,value in d.items():
    tmp = key + value #do something like print
t1 = timeit.default_timer() - start

start = timeit.default_timer()
for key,value in d.iteritems(): #less memory intensive
    tmp = key + value
t2 = timeit.default_timer() - start

Output in my machine:

Time with d.items(): 9.04773592949
Time with d.iteritems(): 2.17707300186

This clearly shows that dictionary.iteritems() is much more efficient.

Angular directive how to add an attribute to the element?

You can try this:

<div ng-app="app">
    <div ng-controller="AppCtrl">
        <a my-dir ng-repeat="user in users" ng-click="fxn()">{{user.name}}</a>
    </div>
</div>

<script>
var app = angular.module('app', []);

function AppCtrl($scope) {
        $scope.users = [{ name: 'John', id: 1 }, { name: 'anonymous' }];
        $scope.fxn = function () {
            alert('It works');
        };
    }

app.directive("myDir", function ($compile) {
    return {
        scope: {ngClick: '='}
    };
});
</script>

Why do we need virtual functions in C++?

When you have a function in the base class, you can Redefine or Override it in the derived class.

Redefining a method : A new implementation for the method of base class is given in the derived class. Does not facilitate Dynamic binding.

Overriding a method: Redefining a virtual method of the base class in the derived class. Virtual method facilitates Dynamic Binding.

So when you said :

But earlier in the book, when learning about basic inheritance, I was able to override base methods in derived classes without using 'virtual'.

you were not overriding it as the method in the base class was not virtual, rather you were redefining it

How do I copy the contents of one stream to another?

For .NET 3.5 and before try :

MemoryStream1.WriteTo(MemoryStream2);

Override intranet compatibility mode IE8

If you want your Web site to force IE 8 standards mode, then use this metatag along with a valid DOCTYPE:

<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />

Note the "EmulateIE8" value rather than the plain "IE8".

According to IE devs, this should, "Display Standards DOCTYPEs in IE8 Standards mode; Display Quirks DOCTYPEs in Quirks mode. Use this tag to override compatibility view on client machines and force Standards to IE8 Standards."

more info on this IE blog post: http://blogs.msdn.com/b/ie/archive/2008/08/27/introducing-compatibility-view.aspx

JNZ & CMP Assembly Instructions

JNZ is short for "Jump if not zero (ZF = 0)", and NOT "Jump if the ZF is set".

If it's any easier to remember, consider that JNZ and JNE (jump if not equal) are equivalent. Therefore, when you're doing cmp al, 47 and the content of AL is equal to 47, the ZF is set, ergo the jump (if Not Equal - JNE) should not be taken.

Check if a given key already exists in a dictionary and increment it

I prefer to do this in one line of code.

my_dict = {}

my_dict[some_key] = my_dict.get(some_key, 0) + 1

Dictionaries have a function, get, which takes two parameters - the key you want, and a default value if it doesn't exist. I prefer this method to defaultdict as you only want to handle the case where the key doesn't exist in this one line of code, not everywhere.

enum Values to NSString (iOS)

Here is working code https://github.com/ndpiparava/ObjcEnumString

//1st Approach
#define enumString(arg) (@""#arg)

//2nd Approach

+(NSString *)secondApproach_convertEnumToString:(StudentProgressReport)status {

    char *str = calloc(sizeof(kgood)+1, sizeof(char));
    int  goodsASInteger = NSSwapInt((unsigned int)kgood);
    memcpy(str, (const void*)&goodsASInteger, sizeof(goodsASInteger));
    NSLog(@"%s", str);
    NSString *enumString = [NSString stringWithUTF8String:str];
    free(str);

    return enumString;
}

//Third Approcah to enum to string
NSString *const kNitin = @"Nitin";
NSString *const kSara = @"Sara";


typedef NS_ENUM(NSUInteger, Name) {
    NameNitin,
    NameSara,
};

+ (NSString *)thirdApproach_convertEnumToString :(Name)weekday {

    __strong NSString **pointer = (NSString **)&kNitin;
    pointer +=weekday;
    return *pointer;
}

Is there a simple way to convert C++ enum to string?

QT is able to pull that of (thanks to the meta object compiler):

QNetworkReply::NetworkError error;

error = fetchStuff();

if (error != QNetworkReply::NoError) {

    QString errorValue;

    QMetaObject meta = QNetworkReply::staticMetaObject;

    for (int i=0; i < meta.enumeratorCount(); ++i) {

        QMetaEnum m = meta.enumerator(i);

        if (m.name() == QLatin1String("NetworkError")) {

            errorValue = QLatin1String(m.valueToKey(error));

            break;

        }

    }

    QMessageBox box(QMessageBox::Information, "Failed to fetch",

                "Fetching stuff failed with error '%1`").arg(errorValue),

                QMessageBox::Ok);

    box.exec();

    return 1;

}

In Qt every class that has the Q_OBJECT macro will automatically have a static member "staticMetaObject" of the type QMetaObject. You can then find all sorts of cool things like the properties, signals, slots and indeed enums.

Source

JQuery: detect change in input field

Same functionality i recently achieved using below function.

I wanted to enable SAVE button on edit.

  1. Change event is NOT advisable as it will ONLY be fired if after editing, mouse is clicked somewhere else on the page before clicking SAVE button.
  2. Key Press doesnt handle Backspace, Delete and Paste options.
  3. Key Up handles everything including tab, Shift key.

Hence i wrote below function combining keypress, keyup (for backspace, delete) and paste event for text fields.

Hope it helps you.

function checkAnyFormFieldEdited() {
    /*
     * If any field is edited,then only it will enable Save button
     */
    $(':text').keypress(function(e) { // text written
        enableSaveBtn();
    });

    $(':text').keyup(function(e) {
        if (e.keyCode == 8 || e.keyCode == 46) { //backspace and delete key
            enableSaveBtn();
        } else { // rest ignore
            e.preventDefault();
        }
    });
    $(':text').bind('paste', function(e) { // text pasted
        enableSaveBtn();
    });

    $('select').change(function(e) { // select element changed
        enableSaveBtn();
    });

    $(':radio').change(function(e) { // radio changed
        enableSaveBtn();
    });

    $(':password').keypress(function(e) { // password written
        enableSaveBtn();
    });
    $(':password').bind('paste', function(e) { // password pasted
        enableSaveBtn();
    });


}

TypeError: unsupported operand type(s) for -: 'str' and 'int'

  1. The reason this is failing is because (Python 3) input returns a string. To convert it to an integer, use int(some_string).

  2. You do not typically keep track of indices manually in Python. A better way to implement such a function would be

    def cat_n_times(s, n):
        for i in range(n):
            print(s) 
    
    text = input("What would you like the computer to repeat back to you: ")
    num = int(input("How many times: ")) # Convert to an int immediately.
    
    cat_n_times(text, num)
    
  3. I changed your API above a bit. It seems to me that n should be the number of times and s should be the string.

Java "user.dir" property - what exactly does it mean?

It's the directory where java was run from, where you started the JVM. Does not have to be within the user's home directory. It can be anywhere where the user has permission to run java.

So if you cd into /somedir, then run your program, user.dir will be /somedir.

A different property, user.home, refers to the user directory. As in /Users/myuser or /home/myuser or C:\Users\myuser.

See here for a list of system properties and their descriptions.

Filter object properties by key in ES6

The cleanest way you can find is with Lodash#pick

const _ = require('lodash');

const allowed = ['item1', 'item3'];

const obj = {
  item1: { key: 'sdfd', value:'sdfd' },
  item2: { key: 'sdfd', value:'sdfd' },
  item3: { key: 'sdfd', value:'sdfd' }
}

const filteredObj = _.pick(obj, allowed)

Is it possible to iterate through JSONArray?

You can use the opt(int) method and use a classical for loop.

How can I see the request headers made by curl when sending a request to the server?

The only way I managed to see my outgoing headers (curl with php) was using the following options:

curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);

Getting your debug info:

$data = curl_exec($ch);
var_dump($data);
var_dump(curl_getinfo($ch));

Retain precision with double in Java

When you input a double number, for example, 33.33333333333333, the value you get is actually the closest representable double-precision value, which is exactly:

33.3333333333333285963817615993320941925048828125

Dividing that by 100 gives:

0.333333333333333285963817615993320941925048828125

which also isn't representable as a double-precision number, so again it is rounded to the nearest representable value, which is exactly:

0.3333333333333332593184650249895639717578887939453125

When you print this value out, it gets rounded yet again to 17 decimal digits, giving:

0.33333333333333326

Android Studio not showing modules in project structure

First You Have To Add Name Of Your Module In setting.gradle(Project Setting) File Like This..

include ':app', ':simple-crop-image-lib'

Then You Need To Compile This Module Into build.gradle(Module app) File Like This..

implementation project(':simple-crop-image-lib')

That's all for adding module now it will be appear in android  section or project section as well.

If It's till did't appear rebuild or clean your project..

Change Row background color based on cell value DataTable

DataTables has functionality for this since v 1.10

https://datatables.net/reference/option/createdRow

Example:

$('#tid_css').DataTable({
  // ...
  "createdRow": function(row, data, dataIndex) {
    if (data["column_index"] == "column_value") {
      $(row).css("background-color", "Orange");
      $(row).addClass("warning");
    }
  },
  // ...
});

Implement a loading indicator for a jQuery AJAX call

There is a global configuration using jQuery. This code runs on every global ajax request.

<div id='ajax_loader' style="position: fixed; left: 50%; top: 50%; display: none;">
    <img src="themes/img/ajax-loader.gif"></img>
</div>

<script type="text/javascript">
    jQuery(function ($){
        $(document).ajaxStop(function(){
            $("#ajax_loader").hide();
         });
         $(document).ajaxStart(function(){
             $("#ajax_loader").show();
         });    
    });    
</script>

Here is a demo: http://jsfiddle.net/sd01fdcm/

Dynamically Add Variable Name Value Pairs to JSON Object

With ECMAScript 6 there is a better way.

You can use computed property names in object property definitions, for example:

var name1 = 'John'; 
var value1 = '42'; 
var name2 = 'Sarah'; 
var value2 = '35';

var ipID = { 
             [name1] : value1, 
             [name2] : value2 
           }

This is equivalent to the following, where you have variables for the property names.

var ipID = { 
             John: '42', 
             Sarah: '35' 
           }

get dictionary value by key

Why not just use key name on dictionary, C# has this:

 Dictionary<string, string> dict = new Dictionary<string, string>();
 dict.Add("UserID", "test");
 string userIDFromDictionaryByKey = dict["UserID"];

If you look at the tip suggestion:

enter image description here

Use jQuery to get the file input's selected filename without the path

How about something like this?

var pathArray = $('input[type=file]').val().split('\\');
alert(pathArray[pathArray.length - 1]);

SASS and @font-face

In case anyone was wondering - it was probably my css...

@font-face
  font-family: "bingo"
  src: url('bingo.eot')
  src: local('bingo')
  src: url('bingo.svg#bingo') format('svg')
  src: url('bingo.otf') format('opentype')

will render as

@font-face {
  font-family: "bingo";
  src: url('bingo.eot');
  src: local('bingo');
  src: url('bingo.svg#bingo') format('svg');
  src: url('bingo.otf') format('opentype'); }

which seems to be close enough... just need to check the SVG rendering

How can I flush GPU memory using CUDA (physical reset is unavailable)

for the ones using python:

import torch, gc
gc.collect()
torch.cuda.empty_cache()

Jquery: How to check if the element has certain css class/style

i've found one solution:

$("#someElement")[0].className.match("test")

but somehow i believe that there's a better way!

basic authorization command for curl

How do I set up the basic authorization?

All you need to do is use -u, --user USER[:PASSWORD]. Behind the scenes curl builds the Authorization header with base64 encoded credentials for you.

Example:

curl -u username:password -i -H 'Accept:application/json' http://example.com

ARM compilation error, VFP registers used by executable, not object file

Use the same compiler options for linking also.

Example:

gcc  -mfloat-abi=hard fpu=neon -c -o test.cpp test.o
gcc  -mfloat-abi=hard fpu=neon -c test1.cpp test1.o
gcc test.o test1.o mfloat-abi=hard fpu=neon HardTest

Type of expression is ambiguous without more context Swift

This happens when you have a function with wrong argument names.

Example:

functionWithArguments(argumentNameWrong: , argumentName2: )

and You declared your function as:

functionWithArguments(argumentName1: , argumentName2: ){}

This usually happens when you changed the name of a Variable. Make sure you refactor when you do that.

Dealing with "Xerces hell" in Java/Maven?

What would help, except for excluding, is modular dependencies.

With one flat classloading (standalone app), or semi-hierarchical (JBoss AS/EAP 5.x) this was a problem.

But with modular frameworks like OSGi and JBoss Modules, this is not so much pain anymore. The libraries may use whichever library they want, independently.

Of course, it's still most recommendable to stick with just a single implementation and version, but if there's no other way (using extra features from more libs), then modularizing might save you.

A good example of JBoss Modules in action is, naturally, JBoss AS 7 / EAP 6 / WildFly 8, for which it was primarily developed.

Example module definition:

<?xml version="1.0" encoding="UTF-8"?>
<module xmlns="urn:jboss:module:1.1" name="org.jboss.msc">
    <main-class name="org.jboss.msc.Version"/>
    <properties>
        <property name="my.property" value="foo"/>
    </properties>
    <resources>
        <resource-root path="jboss-msc-1.0.1.GA.jar"/>
    </resources>
    <dependencies>
        <module name="javax.api"/>
        <module name="org.jboss.logging"/>
        <module name="org.jboss.modules"/>
        <!-- Optional deps -->
        <module name="javax.inject.api" optional="true"/>
        <module name="org.jboss.threads" optional="true"/>
    </dependencies>
</module>

In comparison with OSGi, JBoss Modules is simpler and faster. While missing certain features, it's sufficient for most projects which are (mostly) under control of one vendor, and allow stunning fast boot (due to paralelized dependencies resolving).

Note that there's a modularization effort underway for Java 8, but AFAIK that's primarily to modularize the JRE itself, not sure whether it will be applicable to apps.

How to read multiple Integer values from a single line of input in Java?

When we want to take Integer as inputs
For just 3 inputs as in your case:

import java.util.Scanner;
Scanner scan = new Scanner(System.in);
int a,b,c;
a = scan.nextInt();
b = scan.nextInt();
c = scan.nextInt();

For more number of inputs we can use a loop:

import java.util.Scanner;
Scanner scan = new Scanner(System.in);
int a[] = new int[n]; //where n is the number of inputs
for(int i=0;i<n;i++){
    a[i] = scan.nextInt();    
}

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

My JSON response was like this:

{"items": 
  &nbsp;[
    &nbsp;&nbsp;{
      "index": 1,
      "name": "Samantha",
      "rarity": "Scarborough",
      "email": "[email protected]"
    },
    &nbsp;&nbsp;{
      "index": 2,
      "name": "Amanda",
      "rarity": "Vick",
      "email": "[email protected]"
    }]
}

So, I used ng-repeat = "item in variables.items" to display it.

IsNothing versus Is Nothing

I agree with "Is Nothing". As stated above, it's easy to negate with "IsNot Nothing".

I find this easier to read...

If printDialog IsNot Nothing Then
    'blah
End If

than this...

If Not obj Is Nothing Then
    'blah
End If

How to change Tkinter Button state from disabled to normal?

This is what worked for me. I am not sure why the syntax is different, But it was extremely frustrating trying every combination of activate, inactive, deactivated, disabled, etc. In lower case upper case in quotes out of quotes in brackets out of brackets etc. Well, here's the winning combination for me, for some reason.. different than everyone else?

import tkinter

class App(object):
    def __init__(self):
        self.tree = None
        self._setup_widgets()

    def _setup_widgets(self):
        butts = tkinter.Button(text = "add line", state="disabled")
        butts.grid()

def main():  
    root = tkinter.Tk()
    app = App()
    root.mainloop()

if __name__ == "__main__":
    main()

Marker in leaflet, click event

Additional relevant info: A common need is to pass the ID of the object represented by the marker to some ajax call for the purpose of fetching more info from the server.

It seems that when we do:

marker.on('click', function(e) {...

The e points to a MouseEvent, which does not let us get to the marker object. But there is a built-in this object which strangely, requires us to use this.options to get to the options object which let us pass anything we need. In the above case, we can pass some ID in an option, let's say objid then within the function above, we can get the value by invoking: this.options.objid

Postgresql - select something where date = "01/01/11"

I think you want to cast your dt to a date and fix the format of your date literal:

SELECT *
FROM table
WHERE dt::date = '2011-01-01' -- This should be ISO-8601 format, YYYY-MM-DD

Or the standard version:

SELECT *
FROM table
WHERE CAST(dt AS DATE) = '2011-01-01' -- This should be ISO-8601 format, YYYY-MM-DD

The extract function doesn't understand "date" and it returns a number.

Console app arguments, how arguments are passed to Main method

The main method of the runtime engine looks something like int main(int argc, char *argv[]), where argc is a count of the number of arguments and argv is an array of pointers to each. The runtime engine converts this into a form that is more natural to c#.

Prior to that main method being called, everything is in assembly language. It has access to the command line arguments (because the operating system makes that available to every process that starts), but that assembly language needs to convert a single string of the full command line into multiple substrings (using whitespace to separate them) before it's ready to pass them into main().

How to generate a core dump in Linux on a segmentation fault?

What I did at the end was attach gdb to the process before it crashed, and then when it got the segfault I executed the generate-core-file command. That forced generation of a core dump.

Compile a DLL in C/C++, then call it from another program

Here is how you do it:

In .h

#ifdef BUILD_DLL
#define EXPORT __declspec(dllexport)
#else
#define EXPORT __declspec(dllimport)
#endif

extern "C" // Only if you are using C++ rather than C
{    
  EXPORT int __stdcall add2(int num);
  EXPORT int __stdcall mult(int num1, int num2);
}

in .cpp

extern "C" // Only if you are using C++ rather than C
{    
EXPORT int __stdcall add2(int num)
{
  return num + 2;
}


EXPORT int __stdcall mult(int num1, int num2)
{
  int product;
  product = num1 * num2;
  return product;
}
}

The macro tells your module (i.e your .cpp files) that they are providing the dll stuff to the outside world. People who incude your .h file want to import the same functions, so they sell EXPORT as telling the linker to import. You need to add BUILD_DLL to the project compile options, and you might want to rename it to something obviously specific to your project (in case a dll uses your dll).

You might also need to create a .def file to rename the functions and de-obfuscate the names (C/C++ mangles those names). This blog entry might be an interesting launching off point about that.

Loading your own custom dlls is just like loading system dlls. Just ensure that the DLL is on your system path. C:\windows\ or the working dir of your application are an easy place to put your dll.

What Java FTP client library should I use?

Apache commons-nets get updates more frequently recently, while Enterprise DT library seems to update even more frequently.

git - Your branch is ahead of 'origin/master' by 1 commit

I resolved this by just running a simple:

git pull

Nothing more. Now it's showing:

# On branch master
nothing to commit, working directory clean

vagrant login as root by default

I had some troubles with provisioning when trying to login as root, even with PermitRootLogin yes. I made it so only the vagrant ssh command is affected:

# Login as root when doing vagrant ssh
if ARGV[0]=='ssh'
  config.ssh.username = 'root'
end

How can I make a button have a rounded border in Swift?

I think the easiest and the cleanest way, is to use protocol to avoid inherit and code repetition. You can change this properties directly from storyboard

protocol Traceable {
    var cornerRadius: CGFloat { get set }
    var borderColor: UIColor? { get set }
    var borderWidth: CGFloat { get set }
}

extension UIView: Traceable {

    @IBInspectable var cornerRadius: CGFloat {
        get { return layer.cornerRadius }
        set {
            layer.masksToBounds = true
            layer.cornerRadius = newValue
        }
    }

    @IBInspectable var borderColor: UIColor? {
        get {
            guard let cgColor = layer.borderColor else { return nil }
            return  UIColor(cgColor: cgColor)
        }
        set { layer.borderColor = newValue?.cgColor }
    }

    @IBInspectable var borderWidth: CGFloat {
        get { return layer.borderWidth }
        set { layer.borderWidth = newValue }
    }
}

Update

In this link you can find an example with the utility of Traceable protocol

enter image description here

Reading a text file with SQL Server

BULK INSERT dbo.temp 

FROM 'c:\temp\file.txt' --- path file in db server 

WITH 

  (
     ROWTERMINATOR ='\n'
  )

it work for me but save as by editplus to ansi encoding for multilanguage

How can I use JQuery to post JSON data?

I tried Ninh Pham's solution but it didn't work for me until I tweaked it - see below. Remove contentType and don't encode your json data

$.fn.postJSON = function(url, data) {
    return $.ajax({
            type: 'POST',
            url: url,
            data: data,
            dataType: 'json'
        });

Cycles in an Undirected Graph

Here is a simple implementation in C++ of algorithm that checks if a graph has cycle(s) in O(n) time (n is number of vertexes in the Graph). I do not show here the Graph data structure implementation (to keep answer short). The algorithms expects the class Graph to have public methods, vector<int> getAdj(int v) that returns vertexes adjacent to the v and int getV() that returns total number of vertexes. Additionally, the algorithms assumes the vertexes of the Graph are numbered from 0 to n - 1.

class CheckCycleUndirectedGraph
{
private:
    bool cyclic;
    vector<bool> visited;

    void depthFirstSearch(const Graph& g, int v, int u) {
        visited[v] = true;
        for (auto w : g.getAdj(v)) {
            if (!visited[w]) {
                depthFirstSearch(g, w, v);
            }
            else if (w != u) {
                cyclic = true;
                return;
            }
        }
    }

public:
    CheckCycleUndirectedGraph(const Graph& g) : cyclic(false) {
        visited = vector<bool>(g.getV(), false);
        for (int v = 0; v < g.getV(); v++) {
            if (!visited[v]){
                depthFirstSearch(g, v, v);
                if(cyclic)
                  break;
            }
        }
    }

    bool containsCycle() const {
        return cyclic;
    }
};

Keep in mind that Graph may consist of several not connected components and there may be cycles inside of the components. The shown algorithms detects cycles in such graphs as well.

Flatten List in LINQ

iList.SelectMany(x => x).ToArray()

Open Url in default web browser

In React 16.8+, using functional components, you would do

import React from 'react';
import { Button, Linking } from 'react-native';

const ExternalLinkBtn = (props) => {
  return <Button
            title={props.title}
            onPress={() => {
                Linking.openURL(props.url)
                .catch(err => {
                    console.error("Failed opening page because: ", err)
                    alert('Failed to open page')
                })}}
          />
}

export default function exampleUse() {
  return (
    <View>
      <ExternalLinkBtn title="Example Link" url="https://example.com" />
    </View>
  )
}

Is there a Java API that can create rich Word documents?

docx4j or poi, both of which are ASL v2

@wondersofcomputing: iText is actually free and open source

Concatenate two string literals

Your second example does not work because there is no operator + for two string literals. Note that a string literal is not of type string, but instead is of type const char *. Your second example will work if you revise it like this:

const string message = string("Hello") + ",world" + exclam;

jQuery Datepicker localization

datepicker in Finnish (Käännös suomeksi)

$.datepicker.regional['fi'] = {
  closeText: "Valmis", // Display text for close link
  prevText: "Edel", // Display text for previous month link
  nextText: "Seur", // Display text for next month link
  currentText: "Tänään", // Display text for current month link
  monthNames: [ "Tammikuu","Helmikuu","Maaliskuu","Huhtikuu","Toukokuu","Kesäkuu",
  "Heinäkuu","Elokuu","Syyskuu","Lokakuu","Marraskuu","Joulukuu" ], // Names of months for drop-down and formatting
  monthNamesShort: [ "Tam", "Hel", "Maa", "Huh", "Tou", "Kes", "Hei", "Elo", "Syy", "Lok", "Mar", "Jou" ], // For formatting
  dayNames: [ "Sunnuntai", "Maanantai", "Tiistai", "Keskiviikko", "Torstai", "Perjantai", "Lauantai" ], // For formatting
  dayNamesShort: [ "Sun", "Maa", "Tii", "Kes", "Tor", "Per", "Lau" ], // For formatting
  dayNamesMin: [ "Su","Ma","Ti","Ke","To","Pe","La" ], // Column headings for days starting at Sunday
  weekHeader: "Vk", // Column header for week of the year
  dateFormat: "mm/dd/yy", // See format options on parseDate
  firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ...
  isRTL: false, // True if right-to-left language, false if left-to-right
  showMonthAfterYear: false, // True if the year select precedes month, false for month then year
  yearSuffix: "" // Additional text to append to the year in the month headers
  };

How to cherry pick a range of commits and merge into another branch?

git cherry-pick FIRST^..LAST works only for simple scenarios.

To achieve a decent "merge it into the integration branch" while having the usal comfort with things like auto-skipping of already integrated picks, transplanting diamond-merges, interactive control ...) better use a rebase. One answer here pointed to that, however the protocol included a dicey git branch -f and a juggling with a temp branch. Here a straight robust method:

git rebase -i FIRST LAST~0 --onto integration
git rebase @ integration

The -i allows for interactive control. The ~0 ensures a detached rebase (not moving the / another branch) in case LAST is a branch name. It can be omitted otherwise. The second rebase command just moves the integration branch ref in safe manner forward to the intermediate detached head - it doesn't introduce new commits. To rebase a complex structure with merge diamonds etc. consider --rebase-merges or --rebase-merges=rebase-cousins in the first rebase.

What is the difference between vmalloc and kmalloc?

Linux Kernel Development by Robert Love (Chapter 12, page 244 in 3rd edition) answers this very clearly.

Yes, physically contiguous memory is not required in many of the cases. Main reason for kmalloc being used more than vmalloc in kernel is performance. The book explains, when big memory chunks are allocated using vmalloc, kernel has to map the physically non-contiguous chunks (pages) into a single contiguous virtual memory region. Since the memory is virtually contiguous and physically non-contiguous, several virtual-to-physical address mappings will have to be added to the page table. And in the worst case, there will be (size of buffer/page size) number of mappings added to the page table.

This also adds pressure on TLB (the cache entries storing recent virtual to physical address mappings) when accessing this buffer. This can lead to thrashing.

How to pass command line arguments to a shell alias?

You found the way: create a function instead of an alias. The C shell has a mechanism for doing arguments to aliases, but bash and the Korn shell don't, because the function mechanism is more flexible and offers the same capability.

How can I create a correlation matrix in R?

You could use 'corrplot' package.

d <- data.frame(x1=rnorm(10),
                 x2=rnorm(10),
                 x3=rnorm(10))
M <- cor(d) # get correlations

library('corrplot') #package corrplot
corrplot(M, method = "circle") #plot matrix

enter image description here

More information here: http://cran.r-project.org/web/packages/corrplot/vignettes/corrplot-intro.html

Formatting "yesterday's" date in python

To expand on the answer given by Chris

if you want to store the date in a variable in a specific format, this is the shortest and most effective way as far as I know

>>> from datetime import date, timedelta                   
>>> yesterday = (date.today() - timedelta(days=1)).strftime('%m%d%y')
>>> yesterday
'020817'

If you want it as an integer (which can be useful)

>>> yesterday = int((date.today() - timedelta(days=1)).strftime('%m%d%y'))
>>> yesterday
20817

How to tell if node.js is installed or not

(This is for windows OS but concept can be applied to other OS)

Running command node -v will be able to confirm if it is installed, however it will not be able to confirm if it is NOT installed. (Executable may not be on your PATH)

Two ways you can check if it is actually installed:

  1. Check default install location C:\Program Files\nodejs\

or

  1. Go to System Settings -> Add or Remove Programs and filter by node, it should show you if you have it installed. For me, it shows as title:"Node.js" and description "Node.js Foundation", with no version specified. Install size is 52.6MB

If you don't have it installed, get it from here https://nodejs.org/en/download/

PHP - remove <img> tag from string

$this->load->helper('security');
$h=mysql_real_escape_string(strip_image_tags($comment));

If user inputs

<img src="#">

In the database table just insert character this #

Works for me

How can I trigger the click event of another element in ng-click using angularjs?

If your input and button are siblings (and they are in your case OP):

<input id="upload"
    type="file"
    ng-file-select="onFileSelect($files)"
    style="display: none;">

<button type="button" uploadfile>Upload</button>

Use a directive to bind the click of your button to the file input like so:

app.directive('uploadfile', function () {
    return {
      restrict: 'A',
      link: function(scope, element) {

        element.bind('click', function(e) {
            angular.element(e.target).siblings('#upload').trigger('click');
        });
      }
    };
});

How to solve "Unresolved inclusion: <iostream>" in a C++ file in Eclipse CDT?

For those using a fresh install of Ubuntu, or another Linux distro, make sure your have at least the package "build-essential" before you try to compile Eclipse CDT projects.

At Terminal, type:

sudo apt-get install build-essential

It should be enough to compile and run your apps.

Of course, you can also perform full g++ install, using:

sudo apt-get install g++

Retrieving the text of the selected <option> in <select> element

Easy, simple way:

const select = document.getElementById('selectID');
const selectedOption = [...select.options].find(option => option.selected).text;

Add image in title bar

Add this in the head section of your html

<link rel="icon" type="image/gif/png" href="mouse_select_left.png">

REST API - why use PUT DELETE POST GET?

Basically REST is (wiki):

  1. Client–server architecture
  2. Statelessness
  3. Cacheability
  4. Layered system
  5. Code on demand (optional)
  6. Uniform interface

REST is not protocol, it is principles. Different uris and methods - somebody so called best practices.

How can I check if my Element ID has focus?

Use document.activeElement

Should work.

P.S getElementById("myID") not getElementById("#myID")

Make $JAVA_HOME easily changable in Ubuntu

I know this is a long cold question, but it comes up every time there is a new or recent major Java release. Now this would easily apply to 6 and 7 swapping.

I have done this in the past with update-java-alternatives: http://manpages.ubuntu.com/manpages/hardy/man8/update-java-alternatives.8.html

The most accurate way to check JS object's type?

The JavaScript specification gives exactly one proper way to determine the class of an object:

Object.prototype.toString.call(t);

http://bonsaiden.github.com/JavaScript-Garden/#types

jQuery $(document).ready and UpdatePanels?

FWIW, I experienced a similar issue w/mootools. Re-attaching my events was the correct move, but needed to be done at the end of the request..eg

var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function() {... 

Just something to keep in mind if beginRequest causes you to get null reference JS exceptions.

Cheers

working with negative numbers in python

How about something like that? (Uses no abs() nor mulitiplication)
Notes:

  • the abs() function is only used for the optimization trick. This snippet can either be removed or recoded.
  • the logic is less efficient since we're testing the sign of a and b with each iteration (price to pay to avoid both abs() and multiplication operator)

def multiply_by_addition(a, b):
""" School exercise: multiplies integers a and b, by successive additions.
"""
   if abs(a) > abs(b):
      a, b = b, a     # optimize by reducing number of iterations
   total = 0
   while a != 0:
      if a > 0:
         a -= 1
         total += b
      else:
         a += 1
         total -= b
   return total

multiply_by_addition(2,3)
6
multiply_by_addition(4,3)
12
multiply_by_addition(-4,3)
-12
multiply_by_addition(4,-3)
-12
multiply_by_addition(-4,-3)
12

Why is it bad practice to call System.gc()?

The reason everyone always says to avoid System.gc() is that it is a pretty good indicator of fundamentally broken code. Any code that depends on it for correctness is certainly broken; any that rely on it for performance are most likely broken.

You don't know what sort of garbage collector you are running under. There are certainly some that do not "stop the world" as you assert, but some JVMs aren't that smart or for various reasons (perhaps they are on a phone?) don't do it. You don't know what it's going to do.

Also, it's not guaranteed to do anything. The JVM may just entirely ignore your request.

The combination of "you don't know what it will do," "you don't know if it will even help," and "you shouldn't need to call it anyway" are why people are so forceful in saying that generally you shouldn't call it. I think it's a case of "if you need to ask whether you should be using this, you shouldn't"


EDIT to address a few concerns from the other thread:

After reading the thread you linked, there's a few more things I'd like to point out. First, someone suggested that calling gc() may return memory to the system. That's certainly not necessarily true - the Java heap itself grows independently of Java allocations.

As in, the JVM will hold memory (many tens of megabytes) and grow the heap as necessary. It doesn't necessarily return that memory to the system even when you free Java objects; it is perfectly free to hold on to the allocated memory to use for future Java allocations.

To show that it's possible that System.gc() does nothing, view:

http://bugs.sun.com/view_bug.do?bug_id=6668279

and in particular that there's a -XX:DisableExplicitGC VM option.

How to retrieve absolute path given relative

An improvement to @ernest-a's rather nice version:

absolute_path() {
    cd "$(dirname "$1")"
    case $(basename $1) in
        ..) echo "$(dirname $(pwd))";;
        .)  echo "$(pwd)";;
        *)  echo "$(pwd)/$(basename $1)";;
    esac
}

This deals correctly with the case where the last element of the path is .., in which case the "$(pwd)/$(basename "$1")" in @ernest-a's answer will come through as accurate_sub_path/spurious_subdirectory/...

how to detect search engine bots with php?

100% Working Bot detector. It is working on my website successfully.

function isBotDetected() {

    if ( preg_match('/abacho|accona|AddThis|AdsBot|ahoy|AhrefsBot|AISearchBot|alexa|altavista|anthill|appie|applebot|arale|araneo|AraybOt|ariadne|arks|aspseek|ATN_Worldwide|Atomz|baiduspider|baidu|bbot|bingbot|bing|Bjaaland|BlackWidow|BotLink|bot|boxseabot|bspider|calif|CCBot|ChinaClaw|christcrawler|CMC\/0\.01|combine|confuzzledbot|contaxe|CoolBot|cosmos|crawler|crawlpaper|crawl|curl|cusco|cyberspyder|cydralspider|dataprovider|digger|DIIbot|DotBot|downloadexpress|DragonBot|DuckDuckBot|dwcp|EasouSpider|ebiness|ecollector|elfinbot|esculapio|ESI|esther|eStyle|Ezooms|facebookexternalhit|facebook|facebot|fastcrawler|FatBot|FDSE|FELIX IDE|fetch|fido|find|Firefly|fouineur|Freecrawl|froogle|gammaSpider|gazz|gcreep|geona|Getterrobo-Plus|get|girafabot|golem|googlebot|\-google|grabber|GrabNet|griffon|Gromit|gulliver|gulper|hambot|havIndex|hotwired|htdig|HTTrack|ia_archiver|iajabot|IDBot|Informant|InfoSeek|InfoSpiders|INGRID\/0\.1|inktomi|inspectorwww|Internet Cruiser Robot|irobot|Iron33|JBot|jcrawler|Jeeves|jobo|KDD\-Explorer|KIT\-Fireball|ko_yappo_robot|label\-grabber|larbin|legs|libwww-perl|linkedin|Linkidator|linkwalker|Lockon|logo_gif_crawler|Lycos|m2e|majesticsEO|marvin|mattie|mediafox|mediapartners|MerzScope|MindCrawler|MJ12bot|mod_pagespeed|moget|Motor|msnbot|muncher|muninn|MuscatFerret|MwdSearch|NationalDirectory|naverbot|NEC\-MeshExplorer|NetcraftSurveyAgent|NetScoop|NetSeer|newscan\-online|nil|none|Nutch|ObjectsSearch|Occam|openstat.ru\/Bot|packrat|pageboy|ParaSite|patric|pegasus|perlcrawler|phpdig|piltdownman|Pimptrain|pingdom|pinterest|pjspider|PlumtreeWebAccessor|PortalBSpider|psbot|rambler|Raven|RHCS|RixBot|roadrunner|Robbie|robi|RoboCrawl|robofox|Scooter|Scrubby|Search\-AU|searchprocess|search|SemrushBot|Senrigan|seznambot|Shagseeker|sharp\-info\-agent|sift|SimBot|Site Valet|SiteSucker|skymob|SLCrawler\/2\.0|slurp|snooper|solbot|speedy|spider_monkey|SpiderBot\/1\.0|spiderline|spider|suke|tach_bw|TechBOT|TechnoratiSnoop|templeton|teoma|titin|topiclink|twitterbot|twitter|UdmSearch|Ukonline|UnwindFetchor|URL_Spider_SQL|urlck|urlresolver|Valkyrie libwww\-perl|verticrawl|Victoria|void\-bot|Voyager|VWbot_K|wapspider|WebBandit\/1\.0|webcatcher|WebCopier|WebFindBot|WebLeacher|WebMechanic|WebMoose|webquest|webreaper|webspider|webs|WebWalker|WebZip|wget|whowhere|winona|wlm|WOLP|woriobot|WWWC|XGET|xing|yahoo|YandexBot|YandexMobileBot|yandex|yeti|Zeus/i', $_SERVER['HTTP_USER_AGENT'])
    ) {
        return true; // 'Above given bots detected'
    }

    return false;

} // End :: isBotDetected()

d3.select("#element") not working when code above the html element

Please try this approach. It worked for me.

<head> 
<script  type="text/javascript" src='./d3.v4.min.js'></script>
</head> 

<body>
    <div id="jschart41448" style="color:red">
        Hi red
    </div>

    <div id="jschart41449" style="color:blueviolet">
        Hi blueviolet
    </div>

 <script type="text/javascript"   >
            d3.select("#jschart41448").style('color', 'green' , null);
            d3.select("#jschart41449").style('color', 'yellow', null);
</script>
</body>

Disable sorting for a particular column in jQuery DataTables

To update Bhavish's answer (which I think is for an older version of DataTables and didn't work for me). I think they changed the attribute name. Try this:

<thead>
    <tr>
        <td data-sortable="false">Requirements</td>
        <td data-sortable="false">Automated</td>
        <td>Created On</td>
    </tr>
</thead>
<tbody>
    <tr>
        <td>

How do I monitor all incoming http requests?

Use TcpView to see ports listening and connections. This will not give you the requests though.

In order to see requests, you need reverse of a proxy which I do not know of any such tools.

Use tracing to give you parts of the requests (first 1KB of the request).

How to place a JButton at a desired location in a JFrame using Java

Use child.setLocation(0, 0) on the button, and parent.setLayout(null). Instead of using setBounds(...) on the JFrame to size it, consider using just setSize(...) and letting the OS position the frame.

//JPanel
JPanel pnlButton = new JPanel();
//Buttons
JButton btnAddFlight = new JButton("Add Flight");

public Control() {

    //JFrame layout
    this.setLayout(null);

    //JPanel layout
    pnlButton.setLayout(null);

    //Adding to JFrame
    pnlButton.add(btnAddFlight);
    add(pnlButton);

    // postioning
    pnlButton.setLocation(0,0);

Email validation using jQuery

I would recommend Verimail.js, it also has a JQuery plugin.

Why? Verimail supports the following:

  • Syntax validation (according to RFC 822)
  • IANA TLD validation
  • Spelling suggestion for the most common TLDs and email domains
  • Deny temporary email account domains such as mailinator.com

So besides validation, Verimail.js also gives you suggestions. So if you type an email with the wrong TLD or domain that is very similar to a common email domain (hotmail.com, gmail.com, etc), it can detect this and suggest a correction.

Examples:

And so on..

To use it with jQuery, just include verimail.jquery.js on your site and run the function below:

$("input#email-address").verimail({
    messageElement: "p#status-message"
});

The message element is an element in which a message will be shown. This can be everything from "Your email is invalid" to "Did you mean ...?".

If you have a form and want to restrict it so that it cannot be submitted unless the email is valid, then you can check the status using the getVerimailStatus-function as shown below:

if($("input#email-address").getVerimailStatus() < 0){
    // Invalid
}else{
    // Valid
}

This function returns an integer status code according to the object Comfirm.AlphaMail.Verimail.Status. But the general rule of thumb is that any codes below 0 is codes indicating errors.

SQL Server: Is it possible to insert into two tables at the same time?

Before being able to do a multitable insert in Oracle, you could use a trick involving an insert into a view that had an INSTEAD OF trigger defined on it to perform the inserts. Can this be done in SQL Server?

How to use the new Material Design Icon themes: Outlined, Rounded, Two-Tone and Sharp?

I was unsatisfied that until know Google hasn't yet released their new designs as font or svg icon set. Therefore I put together a small npm package to solve the problem.

https://www.npmjs.com/package/ts-material-icons-svg

Simply import the icons you wanna use and add them to your registry. This also supports tree shaking since only those icons are added to your project that you really want and/or need.

npm i --save https://github.com/MarcusCalidus/ts-material-icons-svg.git

to use two tone icons for example

import {icon_edit} from 'ts-material-icons-svg/dist/twotone';

matIconRegistry.addSvgIcon(
            'edit',
            domSanitizer.bypassSecurityTrustResourceUrl(icon_edit),
        );

In your html template you now can use the new icon

<mat-icon svgIcon="edit"></mat-icon>

What's the proper way to compare a String to an enum value?

You can use equals().

enum.equals(String)

Attempted to read or write protected memory. This is often an indication that other memory is corrupt

I faced the same issue. My code was a .NET dll (AutoCAD extension) running inside AutoCAD 2012. I am also using Oracle.DataAccess and my code was throwing the same exception during ExecuteNonQuery(). I luckily solved this problem by changing the .net version of the ODP I was using (that is, 2.x of Oracle.DataAccess)

How to get the last characters in a String in Java, regardless of String size

org.apache.commons.lang3.StringUtils.substring(s, -7) 

gives you the answer. It returns the input if it is shorter than 7, and null if s == null. It never throws an exception.

See https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#substring-java.lang.String-int-int-

Spring-Boot: How do I set JDBC pool properties like maximum number of connections?

At the current version of Spring-Boot (1.4.1.RELEASE) , each pooling datasource implementation has its own prefix for properties.

For instance, if you are using tomcat-jdbc:

spring.datasource.tomcat.max-wait=10000

You can find the explanation out here

spring.datasource.max-wait=10000

this have no effect anymore.

how to make label visible/invisible?

Change visible="false" to style="visibility:hidden" on your tags..


or better use a class to show/hide the labels..

.hidden{
   visibility:hidden;
}

then on your labels add class="hidden"

and with your script remove the class

document.getElementById("endTimeLabel").className = 'hidden'; // to hide

and

document.getElementById("endTimeLabel").className = ''; // to show

Why I got " cannot be resolved to a type" error?

for some reason, my.demo.service has the same level as src/ in eclise project explorer view. After I move my.demo.service under src/, it is fine. Seems I should not create new package in "Project Explorer" view in Eclipse...

But thank you for your response:)

Clicking at coordinates without identifying element

import pyautogui
from selenium import webdriver

driver = webdriver.Chrome(chrome_options=options)
driver.maximize_window() #maximize the browser window
driver.implicitly_wait(30)
driver.get(url)
height=driver.get_window_size()['height']

#get browser navigation panel height
browser_navigation_panel_height = driver.execute_script('return window.outerHeight - window.innerHeight;')

act_y=y%height
scroll_Y=y/height

#scroll down page until y_off is visible
try:
    driver.execute_script("window.scrollTo(0, "+str(scroll_Y*height)+")")
except Exception as e:
    print "Exception"
#pyautogui used to generate click by passing x,y coordinates
pyautogui.FAILSAFE=False
pyautogui.moveTo(x,act_y+browser_navigation_panel_height)
pyautogui.click(x,act_y+browser_navigation_panel_height,clicks=1,interval=0.0,button="left")

This is worked for me. Hope, It will work for you guys :)...

Forbidden You don't have permission to access /wp-login.php on this server

I had a similar error, which was fixed by adding:

Options FollowSymLinks

... in the apps/[app-name]/conf/httpd-app.conf file. This is because, in my case, an .htaccess file wants to use rewrite rules, that are not allowed with FollowSymLinks AND SymLinksIfOwnerMatch turned off.

If your conf file already has a line with Options ..., you can just add FollowSymLinks to the list of options. You could end up with something like this:

Options Indexes MultiViews FollowSymLinks

The project description file (.project) for my project is missing

I created a new workspace and imported old projects. I just didn’t open this workspace for a long time, I don’t know why this problem happened

Rendering JSON in controller

For the instance of

render :json => @projects, :include => :tasks

You are stating that you want to render @projects as JSON, and include the association tasks on the Project model in the exported data.

For the instance of

render :json => @projects, :callback => 'updateRecordDisplay'

You are stating that you want to render @projects as JSON, and wrap that data in a javascript call that will render somewhat like:

updateRecordDisplay({'projects' => []})

This allows the data to be sent to the parent window and bypass cross-site forgery issues.

Is there a way to specify how many characters of a string to print out using printf()?

In addition to specify a fixed amount of characters, you can also use * which means that printf takes the number of characters from an argument:

#include <stdio.h>

int main(int argc, char *argv[])
{
        const char hello[] = "Hello world";
        printf("message: '%.3s'\n", hello);
        printf("message: '%.*s'\n", 3, hello);
        printf("message: '%.*s'\n", 5, hello);
        return 0;
}

Prints:

message: 'Hel'
message: 'Hel'
message: 'Hello'

What's the best strategy for unit-testing database-driven applications?

I'm using the first approach but a bit different that allows to address the problems you mentioned.

Everything that is needed to run tests for DAOs is in source control. It includes schema and scripts to create the DB (docker is very good for this). If the embedded DB can be used - I use it for speed.

The important difference with the other described approaches is that the data that is required for test is not loaded from SQL scripts or XML files. Everything (except some dictionary data that is effectively constant) is created by application using utility functions/classes.

The main purpose is to make data used by test

  1. very close to the test
  2. explicit (using SQL files for data make it very problematic to see what piece of data is used by what test)
  3. isolate tests from the unrelated changes.

It basically means that these utilities allow to declaratively specify only things essential for the test in test itself and omit irrelevant things.

To give some idea of what it means in practice, consider the test for some DAO which works with Comments to Posts written by Authors. In order to test CRUD operations for such DAO some data should be created in the DB. The test would look like:

@Test
public void savedCommentCanBeRead() {
    // Builder is needed to declaratively specify the entity with all attributes relevant
    // for this specific test
    // Missing attributes are generated with reasonable values
    // factory's responsibility is to create entity (and all entities required by it
    //  in our example Author) in the DB
    Post post = factory.create(PostBuilder.post());

    Comment comment = CommentBuilder.comment().forPost(post).build();

    sut.save(comment);

    Comment savedComment = sut.get(comment.getId());

    // this checks fields that are directly stored
    assertThat(saveComment, fieldwiseEqualTo(comment));
    // if there are some fields that are generated during save check them separately
    assertThat(saveComment.getGeneratedField(), equalTo(expectedValue));        
}

This has several advantages over SQL scripts or XML files with test data:

  1. Maintaining the code is much easier (adding a mandatory column for example in some entity that is referenced in many tests, like Author, does not require to change lots of files/records but only a change in builder and/or factory)
  2. The data required by specific test is described in the test itself and not in some other file. This proximity is very important for test comprehensibility.

Rollback vs Commit

I find it more convenient that tests do commit when they are executed. Firstly, some effects (for example DEFERRED CONSTRAINTS) cannot be checked if commit never happens. Secondly, when a test fails the data can be examined in the DB as it is not reverted by the rollback.

Of cause this has a downside that test may produce a broken data and this will lead to the failures in other tests. To deal with this I try to isolate the tests. In the example above every test may create new Author and all other entities are created related to it so collisions are rare. To deal with the remaining invariants that can be potentially broken but cannot be expressed as a DB level constraint I use some programmatic checks for erroneous conditions that may be run after every single test (and they are run in CI but usually switched off locally for performance reasons).

SQL update fields of one table from fields of another one

You can use the non-standard FROM clause.

UPDATE b
SET column1 = a.column1,
  column2 = a.column2,
  column3 = a.column3
FROM a
WHERE a.id = b.id
AND b.id = 1

"java.lang.OutOfMemoryError: PermGen space" in Maven build

Increase the size of your perm space, of course. Use the -XX:MaxPermSize=128m option. Set the value to something appropriate.

How to send custom headers with requests in Swagger UI?

Golang/go-swagger example: https://github.com/go-swagger/go-swagger/issues/1416

// swagger:parameters opid
type XRequestIdHeader struct {
    // in: header
    // required: true
    XRequestId string `json:"X-Request-Id"`
}

...
    // swagger:operation POST /endpoint/ opid
    // Parameters:
    // - $ref: #/parameters/XRequestIDHeader

How to select count with Laravel's fluent query builder?

$count = DB::table('category_issue')->count();

will give you the number of items.

For more detailed information check Fluent Query Builder section in beautiful Laravel Documentation.

Convert CString to const char*

Note: This answer predates the Unicode requirement; see the comments.

Just cast it:

CString s;
const TCHAR* x = (LPCTSTR) s;

It works because CString has a cast operator to do exactly this.

Using TCHAR makes your code Unicode-independent; if you're not concerned about Unicode you can simply use char instead of TCHAR.

How do you access a website running on localhost from iPhone browser

Steps:

I assume you have started the web server (apache tomcat on default port:8080).

On windows 10:

  1. Open your antivirus, go to the firewall section, and locate port section and add a Local TCP/IP Port : 8080 to allow access
  2. get the machine ip address from command prompt. (IPv4 Address)
  3. Launch chrome from iPhone and goto ip address:8080 address.

Hope this helps.

How do I change Android Studio editor's background color?

How do I change Android Studio editor's background color?

Changing Editor's Background

Open Preference > Editor (In IDE Settings Section) > Colors & Fonts > Darcula or Any item available there

IDE will display a dialog like this, Press 'No'

Darcula color scheme has been set for editors. Would you like to set Darcula as default Look and Feel?

Changing IDE's Theme

Open Preference > Appearance (In IDE Settings Section) > Theme > Darcula or Any item available there

Press OK. Android Studio will ask you to restart the IDE.

Running interactive commands in Paramiko

The full paramiko distribution ships with a lot of good demos.

In the demos subdirectory, demo.py and interactive.py have full interactive TTY examples which would probably be overkill for your situation.

In your example above ssh_stdin acts like a standard Python file object, so ssh_stdin.write should work so long as the channel is still open.

I've never needed to write to stdin, but the docs suggest that a channel is closed as soon as a command exits, so using the standard stdin.write method to send a password up probably won't work. There are lower level paramiko commands on the channel itself that give you more control - see how the SSHClient.exec_command method is implemented for all the gory details.

How to increase the distance between table columns in HTML?

You can just use padding. Like so:

http://jsfiddle.net/davidja/KG8Kv/

HTML

   <table>
        <tr>
            <td>item1</td>
            <td>item2</td>
            <td>item2</td>
        </tr>
    </table>

CSS

 td {padding:10px 25px 10px 25px;}

OR

 tr td:first-child {padding-left:0px;}
 td {padding:10px 0px 10px 50px;}

Should I use the Reply-To header when sending emails as a service to others?

You may want to consider placing the customer's name in the From header and your address in the Sender header:

From: Company A <[email protected]>
Sender: [email protected]

Most mailers will render this as "From [email protected] on behalf of Company A", which is accurate. And then a Reply-To of Company A's address won't seem out of sorts.

From RFC 5322:

The "From:" field specifies the author(s) of the message, that is, the mailbox(es) of the person(s) or system(s) responsible for the writing of the message. The "Sender:" field specifies the mailbox of the agent responsible for the actual transmission of the message. For example, if a secretary were to send a message for another person, the mailbox of the secretary would appear in the "Sender:" field and the mailbox of the actual author would appear in the "From:" field.

How to increase dbms_output buffer?

Here you go:

DECLARE
BEGIN
  dbms_output.enable(NULL); -- Disables the limit of DBMS
  -- Your print here !
END;

.autocomplete is not a function Error

I faced the same problem and try to solve, but unfortunately it wouldn't work anymore ! If you are facing the same problem and can't find the solution, it may help you.

If you configure jquery/jquery-ui globally in webpack, you need to import autocomplete like this

import { autocomplete } from 'webpack-jquery-ui';

And you must include jquery-ui.css in the head section of html, i don't understand why its not working without it!

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

Hope your problem will be solved.

And make sure you include/install the following three

  1. jquery-ui-css
  2. jquery-ui
  3. jquery

VBA: How to display an error message just like the standard error message which has a "Debug" button?

For Me I just wanted to see the error in my VBA application so in the function I created the below code..

Function Database_FileRpt
'-------------------------
On Error GoTo CleanFail
'-------------------------
'
' Create_DailyReport_Action and code


CleanFail:

'*************************************

MsgBox "********************" _

& vbCrLf & "Err.Number: " & Err.Number _

& vbCrLf & "Err.Description: " & Err.Description _

& vbCrLf & "Err.Source: " & Err.Source _

& vbCrLf & "********************" _

& vbCrLf & "...Exiting VBA Function: Database_FileRpt" _

& vbCrLf & "...Excel VBA Program Reset." _

, , "VBA Error Exception Raised!"

*************************************

 ' Note that the next line will reset the error object to 0, the variables 
above are used to remember the values
' so that the same error can be re-raised

Err.Clear

' *************************************

Resume CleanExit

CleanExit:

'cleanup code , if any, goes here. runs regardless of error state.

Exit Function  ' SUB  or Function    

End Function  ' end of Database_FileRpt

' ------------------

Why can't Visual Studio find my DLL?

Specifying the path to the DLL file in your project's settings does not ensure that your application will find the DLL at run-time. You only told Visual Studio how to find the files it needs. That has nothing to do with how the program finds what it needs, once built.

Placing the DLL file into the same folder as the executable is by far the simplest solution. That's the default search path for dependencies, so you won't need to do anything special if you go that route.
To avoid having to do this manually each time, you can create a Post-Build Event for your project that will automatically copy the DLL into the appropriate directory after a build completes.

Alternatively, you could deploy the DLL to the Windows side-by-side cache, and add a manifest to your application that specifies the location.

How does one add keyboard languages and switch between them in Linux Mint 16?

For Linux Mint 18 Cinnamon

Menu > Keyboard Preferences > Layouts > Options > Switching to another layout.

oracle varchar to number

select to_number(exception_value) from exception where to_number(exception_value) = 105

Create a folder if it doesn't already exist

This is the most up-to-date solution without error suppression:

if (!is_dir('path/to/directory')) {
    mkdir('path/to/directory');
}

How to close a window using jQuery

$(element).click(function(){
    window.close();
});

Note: you can not close any window that you didn't opened with window.open. Directly invoking window.close() will ask user with a dialogue box.

How to extract IP Address in Spring MVC Controller get call?

private static final String[] IP_HEADER_CANDIDATES = {
            "X-Forwarded-For",
            "Proxy-Client-IP",
            "WL-Proxy-Client-IP",
            "HTTP_X_FORWARDED_FOR",
            "HTTP_X_FORWARDED",
            "HTTP_X_CLUSTER_CLIENT_IP",
            "HTTP_CLIENT_IP",
            "HTTP_FORWARDED_FOR",
            "HTTP_FORWARDED",
            "HTTP_VIA",
            "REMOTE_ADDR"
    };

    public static String getIPFromRequest(HttpServletRequest request) {
        String ip = null;
        if (request == null) {
            if (RequestContextHolder.getRequestAttributes() == null) {
                return null;
            }
            request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        }

        try {
            ip = InetAddress.getLocalHost().getHostAddress();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (!StringUtils.isEmpty(ip))
            return ip;

        for (String header : IP_HEADER_CANDIDATES) {
            String ipList = request.getHeader(header);
            if (ipList != null && ipList.length() != 0 && !"unknown".equalsIgnoreCase(ipList)) {
                return ipList.split(",")[0];
            }
        }

        return request.getRemoteAddr();
    }

I combie the code above to this code work for most case. Pass the HttpServletRequest request you get from the api to the method

SQL where datetime column equals today's date?

Can you try this?

SELECT [Title], [Firstname], [Surname], [Company_name], [Interest] 
FROM [dbo].[EXTRANET_users] 
WHERE CAST(Submission_date AS DATE) = CAST(GETDATE() AS DATE)

T-SQL doesn't really have the "implied" casting like C# does - you need to explicitly use CAST (or CONVERT).

Also, use GETDATE() or CURRENT_TIMESTAMP to get the "now" date and time.

Update: since you're working against SQL Server 2000 - none of those approaches so far work. Try this instead:

SELECT [Title], [Firstname], [Surname], [Company_name], [Interest] 
FROM [dbo].[EXTRANET_users] 
WHERE DATEADD(dd, 0, DATEDIFF(dd, 0, submission_date)) = DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))

How to import cv2 in python3?

There is a problem with pylint, which I do not completely understood yet.

You can just import OpenCV with: from cv2 import cv2

enter image description here

fastest MD5 Implementation in JavaScript

Currently the fastest implementation of md5 (based on Joseph Myers' code):

https://github.com/iReal/FastMD5

jsPerf comparaison: http://jsperf.com/md5-shootout/63

How to prevent sticky hover effects for buttons on touch devices

From 4 ways to deal with sticky hover on mobile: Here's a way to dynamically add or remove a "can touch" class to the document based on the current input type of the user. It works with hybrid devices as well where the user may be switching between touch and a mouse/trackpad:

<script>

;(function(){
    var isTouch = false //var to indicate current input type (is touch versus no touch) 
    var isTouchTimer 
    var curRootClass = '' //var indicating current document root class ("can-touch" or "")

    function addtouchclass(e){
        clearTimeout(isTouchTimer)
        isTouch = true
        if (curRootClass != 'can-touch'){ //add "can-touch' class if it's not already present
            curRootClass = 'can-touch'
            document.documentElement.classList.add(curRootClass)
        }
        isTouchTimer = setTimeout(function(){isTouch = false}, 500) //maintain "istouch" state for 500ms so removetouchclass doesn't get fired immediately following a touch event
    }

    function removetouchclass(e){
        if (!isTouch && curRootClass == 'can-touch'){ //remove 'can-touch' class if not triggered by a touch event and class is present
            isTouch = false
            curRootClass = ''
            document.documentElement.classList.remove('can-touch')
        }
    }

    document.addEventListener('touchstart', addtouchclass, false) //this event only gets called when input type is touch
    document.addEventListener('mouseover', removetouchclass, false) //this event gets called when input type is everything from touch to mouse/ trackpad
})();

</script>

How do I run Google Chrome as root?

It no longer suffices to start Chrome with --user-data-dir=/root/.config/google-chrome. It simply prints Aborted and ends (Chrome 48 on Ubuntu 12.04).

You need actually to run it as a non-root user. This you can do with

gksu -wu chrome-user google-chrome

where chrome-user is some user you've decided should be the one to run Chrome. Your Chrome user profile will be found at ~chrome-user/.config/google-chrome.

BTW, the old hack of changing all occurrences of geteuid to getppid in the chrome binary no longer works.

Is it possible to pull just one file in Git?

Yes, here is the process:

# Navigate to a directory and initiate a local repository
git init        

# Add remote repository to be tracked for changes:   
git remote add origin https://github.com/username/repository_name.git

# Track all changes made on above remote repository
# This will show files on remote repository not available on local repository
git fetch

# Add file present in staging area for checkout
git check origin/master -m /path/to/file
# NOTE: /path/to/file is a relative path from repository_name
git add /path/to/file

# Verify track of file(s) being committed to local repository
git status

# Commit to local repository
git commit -m "commit message"

# You may perform a final check of the staging area again with git status

Call to undefined method mysqli_stmt::get_result

I realize that it's been a while since there has been any new activity on this question. But, as other posters have commented - get_result() is now only available in PHP by installing the MySQL native driver (mysqlnd), and in some cases, it may not be possible or desirable to install mysqlnd. So, I thought it would be helpful to post this answer with info on how get the functionality that get_result() offers - without using get_result().

get_result() is/was often combined with fetch_array() to loop through a result set and store the values from each row of the result set in a numerically-indexed or associative array. For example, the code below uses get_result() with fetch_array() to loop through a result set, storing the values from each row in the numerically-indexed $data[] array:

$c=1000;
$sql="select account_id, username from accounts where account_id<?";
$stmt = $mysqli->prepare($sql);                 
$stmt->bind_param('i', $c);                                             
$stmt->execute();
$result = $stmt->get_result();       
while($data = $result->fetch_array(MYSQLI_NUM)) {
   print $data[0] . ', ' . $data[1] . "<BR>\n"; 
}

However, if get_result() is not available (because mysqlnd is not installed), then this leads to the problem of how to store the values from each row of a result set in an array, without using get_result(). Or, how to migrate legacy code that uses get_result() to run without it (e.g. using bind_result() instead) - while impacting the rest of the code as little as possible.

It turns out that storing the values from each row in a numerically-indexed array is not so straight-forward using bind_result(). bind_result() expects a list of scalar variables (not an array). So, it takes some doing to make it store the values from each row of the result set in an array.

Of course, the code could easily be modified as follows:

$c=1000;
$sql="select account_id, username from accounts where account_id<?";
$stmt = $mysqli->prepare($sql);                 
$stmt->bind_param('i', $c);                                             
$stmt->execute();
$stmt->bind_result($data[0], $data[1]);
while ($stmt->fetch()) {
   print $data[0] . ', ' . $data[1] . "<BR>\n"; 
}

But, this requires us to explicitly list $data[0], $data[1], etc. individually in the call to bind_result(), which is not ideal. We want a solution that doesn't require us to have to explicitly list $data[0], $data[1], ... $data[N-1] (where N is the number of fields in the select statement) in the call to bind_results(). If we're migrating a legacy application that has a large number of queries, and each query may contain a different number of fields in the select clause, the migration will be very labor intensive and prone to error if we use a solution like the one above.

Ideally, we want a snippet of 'drop-in replacement' code - to replace just the line containing the get_result() function and the while() loop on the next line. The replacement code should have the same function as the code that it's replacing, without affecting any of the lines before, or any of the lines after - including the lines inside the while() loop. Ideally we want the replacement code to be as compact as possible, and we don't want to have to taylor the replacement code based on the number of fields in the select clause of the query.

Searching on the internet, I found a number of solutions that use bind_param() with call_user_func_array() (for example, Dynamically bind mysqli_stmt parameters and then bind result (PHP)), but most solutions that I found eventually lead to the results being stored in an associative array, not a numerically-indexed array, and many of these solutions were not as compact as I would like and/or were not suited as 'drop-in replacements'. However, from the examples that I found, I was able to cobble together this solution, which fits the bill:

$c=1000;
$sql="select account_id, username from accounts where account_id<?";
$stmt = $mysqli->prepare($sql);                 
$stmt->bind_param('i', $c);                                             
$stmt->execute();
$data=array();
for ($i=0;$i<$mysqli->field_count;$i++) { 
    $var = $i;
    $$var = null; 
    $data[$var] = &$$var; 
}
call_user_func_array(array($stmt,'bind_result'), $data);
while ($stmt->fetch()) {
   print $data[0] . ', ' . $data[1] . "<BR>\n"; 
}

Of course, the for() loop can be collapsed into one line to make it more compact.

I hope this helps anyone who is looking for a solution using bind_result() to store the values from each row in a numerically-indexed array and/or looking for a way to migrate legacy code using get_result(). Comments welcome.

VueJS conditionally add an attribute for an element

<input :required="condition">

You don't need <input :required="test ? true : false"> because if test is truthy you'll already get the required attribute, and if test is falsy you won't get the attribute. The true : false part is redundant, much like this...

if (condition) {
    return true;
} else {
    return false;
}
// or this...
return condition ? true : false;
// can *always* be replaced by...
return (condition); // parentheses generally not needed

The simplest way of doing this binding, then, is <input :required="condition">

Only if the test (or condition) can be misinterpreted would you need to do something else; in that case Syed's use of !! does the trick.
  <input :required="!!condition">

How to search for file names in Visual Studio?

Easily hit CTRL+SHIFT+T . This will look in the files' names.

How to find out which JavaScript events fired?

Just thought I'd add that you can do this in Chrome as well:

Ctrl + Shift + I (Developer Tools) > Sources> Event Listener Breakpoints (on the right).

You can also view all events that have already been attached by simply right clicking on the element and then browsing its properties (the panel on the right).

For example:

  • Right click on the upvote button to the left
  • Select inspect element
  • Collapse the styles section (section on the far right - double chevron)
  • Expand the event listeners option
  • Now you can see the events bound to the upvote
  • Not sure if it's quite as powerful as the firebug option, but has been enough for most of my stuff.

    Another option that is a bit different but surprisingly awesome is Visual Event: http://www.sprymedia.co.uk/article/Visual+Event+2

    It highlights all of the elements on a page that have been bound and has popovers showing the functions that are called. Pretty nifty for a bookmark! There's a Chrome plugin as well if that's more your thing - not sure about other browsers.

    AnonymousAndrew has also pointed out monitorEvents(window); here

    How to know a Pod's own IP address from inside a container in the Pod?

    The simplest answer is to ensure that your pod or replication controller yaml/json files add the pod IP as an environment variable by adding the config block defined below. (the block below additionally makes the name and namespace available to the pod)

    env:
    - name: MY_POD_NAME
      valueFrom:
        fieldRef:
          fieldPath: metadata.name
    - name: MY_POD_NAMESPACE
      valueFrom:
        fieldRef:
          fieldPath: metadata.namespace
    - name: MY_POD_IP
      valueFrom:
        fieldRef:
          fieldPath: status.podIP
    

    Recreate the pod/rc and then try

    echo $MY_POD_IP
    

    also run env to see what else kubernetes provides you with.

    Cheers

    sed command with -i option failing on Mac, but works on Linux

    Or, you can install the GNU version of sed in your Mac, called gsed, and use it using the standard Linux syntax.

    For that, install gsed using ports (if you don't have it, get it at http://www.macports.org/) by running sudo port install gsed. Then, you can run sed -i 's/old_link/new_link/g' *

    Python sockets error TypeError: a bytes-like object is required, not 'str' with send function

    An alternative solution is to introduce a method to the file instance that would do the explicit conversion.

    import types
    
    def _write_str(self, ascii_str):
        self.write(ascii_str.encode('ascii'))
    
    source_file = open("myfile.bin", "wb")
    source_file.write_str = types.MethodType(_write_str, source_file)
    

    And then you can use it as source_file.write_str("Hello World").

    How do I access command line arguments in Python?

    Python tutorial explains it:

    import sys
    
    print(sys.argv)
    

    More specifically, if you run python example.py one two three:

    >>> import sys
    >>> print(sys.argv)
    ['example.py', 'one', 'two', 'three']
    

    How do I force a DIV block to extend to the bottom of a page even if it has no content?

    Try:

    html, body {
        height: 102%;
    }
    .wrapper {
        position: relative;
        height: 100%;
        width: 100%;
    }
    .div {
        position: absolute;
        top: 0;
        bottom: 0;
        width: 1000px;
        min-height: 100%;
    }
    

    Haven't tested it yet...

    Can I force a page break in HTML printing?

    I was struggling this for some time, it never worked.

    In the end, the solution was to put a style element in the head.

    The page-break-after can't be in a linked CSS file, it must be in the HTML itself.

    How to identify numpy types in python?

    Note that the type(numpy.ndarray) is a type itself and watch out for boolean and scalar types. Don't be too discouraged if it's not intuitive or easy, it's a pain at first.

    See also: - https://docs.scipy.org/doc/numpy-1.15.1/reference/arrays.dtypes.html - https://github.com/machinalis/mypy-data/tree/master/numpy-mypy

    >>> import numpy as np
    >>> np.ndarray
    <class 'numpy.ndarray'>
    >>> type(np.ndarray)
    <class 'type'>
    >>> a = np.linspace(1,25)
    >>> type(a)
    <class 'numpy.ndarray'>
    >>> type(a) == type(np.ndarray)
    False
    >>> type(a) == np.ndarray
    True
    >>> isinstance(a, np.ndarray)
    True
    

    Fun with booleans:

    >>> b = a.astype('int32') == 11
    >>> b[0]
    False
    >>> isinstance(b[0], bool)
    False
    >>> isinstance(b[0], np.bool)
    False
    >>> isinstance(b[0], np.bool_)
    True
    >>> isinstance(b[0], np.bool8)
    True
    >>> b[0].dtype == np.bool
    True
    >>> b[0].dtype == bool  # python equivalent
    True
    

    More fun with scalar types, see: - https://docs.scipy.org/doc/numpy-1.15.1/reference/arrays.scalars.html#arrays-scalars-built-in

    >>> x = np.array([1,], dtype=np.uint64)
    >>> x[0].dtype
    dtype('uint64')
    >>> isinstance(x[0], np.uint64)
    True
    >>> isinstance(x[0], np.integer)
    True  # generic integer
    >>> isinstance(x[0], int)
    False  # but not a python int in this case
    
    # Try matching the `kind` strings, e.g.
    >>> np.dtype('bool').kind                                                                                           
    'b'
    >>> np.dtype('int64').kind                                                                                          
    'i'
    >>> np.dtype('float').kind                                                                                          
    'f'
    >>> np.dtype('half').kind                                                                                           
    'f'
    
    # But be weary of matching dtypes
    >>> np.integer
    <class 'numpy.integer'>
    >>> np.dtype(np.integer)
    dtype('int64')
    >>> x[0].dtype == np.dtype(np.integer)
    False
    
    # Down these paths there be dragons:
    
    # the .dtype attribute returns a kind of dtype, not a specific dtype
    >>> isinstance(x[0].dtype, np.dtype)
    True
    >>> isinstance(x[0].dtype, np.uint64)
    False  
    >>> isinstance(x[0].dtype, np.dtype(np.uint64))
    Traceback (most recent call last):
      File "<console>", line 1, in <module>
    TypeError: isinstance() arg 2 must be a type or tuple of types
    # yea, don't go there
    >>> isinstance(x[0].dtype, np.int_)
    False  # again, confusing the .dtype with a specific dtype
    
    
    # Inequalities can be tricky, although they might
    # work sometimes, try to avoid these idioms:
    
    >>> x[0].dtype <= np.dtype(np.uint64)
    True
    >>> x[0].dtype <= np.dtype(np.float)
    True
    >>> x[0].dtype <= np.dtype(np.half)
    False  # just when things were going well
    >>> x[0].dtype <= np.dtype(np.float16)
    False  # oh boy
    >>> x[0].dtype == np.int
    False  # ya, no luck here either
    >>> x[0].dtype == np.int_
    False  # or here
    >>> x[0].dtype == np.uint64
    True  # have to end on a good note!
    

    AngularJs .$setPristine to reset form

    Had a similar problem, where I had to set the form back to pristine, but also to untouched, since $invalid and $error were both used to show error messages. Only using setPristine() was not enough to clear the error messages.

    I solved it by using setPristine() and setUntouched(). (See Angular's documentation: https://docs.angularjs.org/api/ng/type/ngModel.NgModelController)

    So, in my controller, I used:

    $scope.form.setPristine(); 
    $scope.form.setUntouched();
    

    These two functions reset the complete form to $pristine and back to $untouched, so that all error messages were cleared.

    Get UserDetails object from Security Context in Spring MVC controller

    You can use below code to find out principal (user email who logged in)

      org.opensaml.saml2.core.impl.NameIDImpl principal =  
      (NameIDImpl) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    
      String email = principal.getValue();
    

    This code is written on top of SAML.

    Check if a varchar is a number (TSQL)

    you can check like this

    declare @vchar varchar(50)
    set @vchar ='34343';
    select case when @vchar not like '%[^0-9]%' then 'Number' else 'Not a Number' end
    

    How to set and reference a variable in a Jenkinsfile

    The error is due to that you're only allowed to use pipeline steps inside the steps directive. One workaround that I know is to use the script step and wrap arbitrary pipeline script inside of it and save the result in the environment variable so that it can be used later.

    So in your case:

    pipeline {
        agent any
        stages {
            stage("foo") {
                steps {
                    script {
                        env.FILENAME = readFile 'output.txt'
                    }
                    echo "${env.FILENAME}"
                }
            }
        }
    }
    

    How do SO_REUSEADDR and SO_REUSEPORT differ?

    Welcome to the wonderful world of portability... or rather the lack of it. Before we start analyzing these two options in detail and take a deeper look how different operating systems handle them, it should be noted that the BSD socket implementation is the mother of all socket implementations. Basically all other systems copied the BSD socket implementation at some point in time (or at least its interfaces) and then started evolving it on their own. Of course the BSD socket implementation was evolved as well at the same time and thus systems that copied it later got features that were lacking in systems that copied it earlier. Understanding the BSD socket implementation is the key to understanding all other socket implementations, so you should read about it even if you don't care to ever write code for a BSD system.

    There are a couple of basics you should know before we look at these two options. A TCP/UDP connection is identified by a tuple of five values:

    {<protocol>, <src addr>, <src port>, <dest addr>, <dest port>}

    Any unique combination of these values identifies a connection. As a result, no two connections can have the same five values, otherwise the system would not be able to distinguish these connections any longer.

    The protocol of a socket is set when a socket is created with the socket() function. The source address and port are set with the bind() function. The destination address and port are set with the connect() function. Since UDP is a connectionless protocol, UDP sockets can be used without connecting them. Yet it is allowed to connect them and in some cases very advantageous for your code and general application design. In connectionless mode, UDP sockets that were not explicitly bound when data is sent over them for the first time are usually automatically bound by the system, as an unbound UDP socket cannot receive any (reply) data. Same is true for an unbound TCP socket, it is automatically bound before it will be connected.

    If you explicitly bind a socket, it is possible to bind it to port 0, which means "any port". Since a socket cannot really be bound to all existing ports, the system will have to choose a specific port itself in that case (usually from a predefined, OS specific range of source ports). A similar wildcard exists for the source address, which can be "any address" (0.0.0.0 in case of IPv4 and :: in case of IPv6). Unlike in case of ports, a socket can really be bound to "any address" which means "all source IP addresses of all local interfaces". If the socket is connected later on, the system has to choose a specific source IP address, since a socket cannot be connected and at the same time be bound to any local IP address. Depending on the destination address and the content of the routing table, the system will pick an appropriate source address and replace the "any" binding with a binding to the chosen source IP address.

    By default, no two sockets can be bound to the same combination of source address and source port. As long as the source port is different, the source address is actually irrelevant. Binding socketA to ipA:portA and socketB to ipB:portB is always possible if ipA != ipB holds true, even when portA == portB. E.g. socketA belongs to a FTP server program and is bound to 192.168.0.1:21 and socketB belongs to another FTP server program and is bound to 10.0.0.1:21, both bindings will succeed. Keep in mind, though, that a socket may be locally bound to "any address". If a socket is bound to 0.0.0.0:21, it is bound to all existing local addresses at the same time and in that case no other socket can be bound to port 21, regardless which specific IP address it tries to bind to, as 0.0.0.0 conflicts with all existing local IP addresses.

    Anything said so far is pretty much equal for all major operating system. Things start to get OS specific when address reuse comes into play. We start with BSD, since as I said above, it is the mother of all socket implementations.

    BSD

    SO_REUSEADDR

    If SO_REUSEADDR is enabled on a socket prior to binding it, the socket can be successfully bound unless there is a conflict with another socket bound to exactly the same combination of source address and port. Now you may wonder how is that any different than before? The keyword is "exactly". SO_REUSEADDR mainly changes the way how wildcard addresses ("any IP address") are treated when searching for conflicts.

    Without SO_REUSEADDR, binding socketA to 0.0.0.0:21 and then binding socketB to 192.168.0.1:21 will fail (with error EADDRINUSE), since 0.0.0.0 means "any local IP address", thus all local IP addresses are considered in use by this socket and this includes 192.168.0.1, too. With SO_REUSEADDR it will succeed, since 0.0.0.0 and 192.168.0.1 are not exactly the same address, one is a wildcard for all local addresses and the other one is a very specific local address. Note that the statement above is true regardless in which order socketA and socketB are bound; without SO_REUSEADDR it will always fail, with SO_REUSEADDR it will always succeed.

    To give you a better overview, let's make a table here and list all possible combinations:

    SO_REUSEADDR       socketA        socketB       Result
    ---------------------------------------------------------------------
      ON/OFF       192.168.0.1:21   192.168.0.1:21    Error (EADDRINUSE)
      ON/OFF       192.168.0.1:21      10.0.0.1:21    OK
      ON/OFF          10.0.0.1:21   192.168.0.1:21    OK
       OFF             0.0.0.0:21   192.168.1.0:21    Error (EADDRINUSE)
       OFF         192.168.1.0:21       0.0.0.0:21    Error (EADDRINUSE)
       ON              0.0.0.0:21   192.168.1.0:21    OK
       ON          192.168.1.0:21       0.0.0.0:21    OK
      ON/OFF           0.0.0.0:21       0.0.0.0:21    Error (EADDRINUSE)
    

    The table above assumes that socketA has already been successfully bound to the address given for socketA, then socketB is created, either gets SO_REUSEADDR set or not, and finally is bound to the address given for socketB. Result is the result of the bind operation for socketB. If the first column says ON/OFF, the value of SO_REUSEADDR is irrelevant to the result.

    Okay, SO_REUSEADDR has an effect on wildcard addresses, good to know. Yet that isn't it's only effect it has. There is another well known effect which is also the reason why most people use SO_REUSEADDR in server programs in the first place. For the other important use of this option we have to take a deeper look on how the TCP protocol works.

    A socket has a send buffer and if a call to the send() function succeeds, it does not mean that the requested data has actually really been sent out, it only means the data has been added to the send buffer. For UDP sockets, the data is usually sent pretty soon, if not immediately, but for TCP sockets, there can be a relatively long delay between adding data to the send buffer and having the TCP implementation really send that data. As a result, when you close a TCP socket, there may still be pending data in the send buffer, which has not been sent yet but your code considers it as sent, since the send() call succeeded. If the TCP implementation was closing the socket immediately on your request, all of this data would be lost and your code wouldn't even know about that. TCP is said to be a reliable protocol and losing data just like that is not very reliable. That's why a socket that still has data to send will go into a state called TIME_WAIT when you close it. In that state it will wait until all pending data has been successfully sent or until a timeout is hit, in which case the socket is closed forcefully.

    At most, the amount of time the kernel will wait before it closes the socket, regardless if it still has data in flight or not, is called the Linger Time. The Linger Time is globally configurable on most systems and by default rather long (two minutes is a common value you will find on many systems). It is also configurable per socket using the socket option SO_LINGER which can be used to make the timeout shorter or longer, and even to disable it completely. Disabling it completely is a very bad idea, though, since closing a TCP socket gracefully is a slightly complex process and involves sending forth and back a couple of packets (as well as resending those packets in case they got lost) and this whole close process is also limited by the Linger Time. If you disable lingering, your socket may not only lose data in flight, it is also always closed forcefully instead of gracefully, which is usually not recommended. The details about how a TCP connection is closed gracefully are beyond the scope of this answer, if you want to learn more about, I recommend you have a look at this page. And even if you disabled lingering with SO_LINGER, if your process dies without explicitly closing the socket, BSD (and possibly other systems) will linger nonetheless, ignoring what you have configured. This will happen for example if your code just calls exit() (pretty common for tiny, simple server programs) or the process is killed by a signal (which includes the possibility that it simply crashes because of an illegal memory access). So there is nothing you can do to make sure a socket will never linger under all circumstances.

    The question is, how does the system treat a socket in state TIME_WAIT? If SO_REUSEADDR is not set, a socket in state TIME_WAIT is considered to still be bound to the source address and port and any attempt to bind a new socket to the same address and port will fail until the socket has really been closed, which may take as long as the configured Linger Time. So don't expect that you can rebind the source address of a socket immediately after closing it. In most cases this will fail. However, if SO_REUSEADDR is set for the socket you are trying to bind, another socket bound to the same address and port in state TIME_WAIT is simply ignored, after all its already "half dead", and your socket can bind to exactly the same address without any problem. In that case it plays no role that the other socket may have exactly the same address and port. Note that binding a socket to exactly the same address and port as a dying socket in TIME_WAIT state can have unexpected, and usually undesired, side effects in case the other socket is still "at work", but that is beyond the scope of this answer and fortunately those side effects are rather rare in practice.

    There is one final thing you should know about SO_REUSEADDR. Everything written above will work as long as the socket you want to bind to has address reuse enabled. It is not necessary that the other socket, the one which is already bound or is in a TIME_WAIT state, also had this flag set when it was bound. The code that decides if the bind will succeed or fail only inspects the SO_REUSEADDR flag of the socket fed into the bind() call, for all other sockets inspected, this flag is not even looked at.

    SO_REUSEPORT

    SO_REUSEPORT is what most people would expect SO_REUSEADDR to be. Basically, SO_REUSEPORT allows you to bind an arbitrary number of sockets to exactly the same source address and port as long as all prior bound sockets also had SO_REUSEPORT set before they were bound. If the first socket that is bound to an address and port does not have SO_REUSEPORT set, no other socket can be bound to exactly the same address and port, regardless if this other socket has SO_REUSEPORT set or not, until the first socket releases its binding again. Unlike in case of SO_REUESADDR the code handling SO_REUSEPORT will not only verify that the currently bound socket has SO_REUSEPORT set but it will also verify that the socket with a conflicting address and port had SO_REUSEPORT set when it was bound.

    SO_REUSEPORT does not imply SO_REUSEADDR. This means if a socket did not have SO_REUSEPORT set when it was bound and another socket has SO_REUSEPORT set when it is bound to exactly the same address and port, the bind fails, which is expected, but it also fails if the other socket is already dying and is in TIME_WAIT state. To be able to bind a socket to the same addresses and port as another socket in TIME_WAIT state requires either SO_REUSEADDR to be set on that socket or SO_REUSEPORT must have been set on both sockets prior to binding them. Of course it is allowed to set both, SO_REUSEPORT and SO_REUSEADDR, on a socket.

    There is not much more to say about SO_REUSEPORT other than that it was added later than SO_REUSEADDR, that's why you will not find it in many socket implementations of other systems, which "forked" the BSD code before this option was added, and that there was no way to bind two sockets to exactly the same socket address in BSD prior to this option.

    Connect() Returning EADDRINUSE?

    Most people know that bind() may fail with the error EADDRINUSE, however, when you start playing around with address reuse, you may run into the strange situation that connect() fails with that error as well. How can this be? How can a remote address, after all that's what connect adds to a socket, be already in use? Connecting multiple sockets to exactly the same remote address has never been a problem before, so what's going wrong here?

    As I said on the very top of my reply, a connection is defined by a tuple of five values, remember? And I also said, that these five values must be unique otherwise the system cannot distinguish two connections any longer, right? Well, with address reuse, you can bind two sockets of the same protocol to the same source address and port. That means three of those five values are already the same for these two sockets. If you now try to connect both of these sockets also to the same destination address and port, you would create two connected sockets, whose tuples are absolutely identical. This cannot work, at least not for TCP connections (UDP connections are no real connections anyway). If data arrived for either one of the two connections, the system could not tell which connection the data belongs to. At least the destination address or destination port must be different for either connection, so that the system has no problem to identify to which connection incoming data belongs to.

    So if you bind two sockets of the same protocol to the same source address and port and try to connect them both to the same destination address and port, connect() will actually fail with the error EADDRINUSE for the second socket you try to connect, which means that a socket with an identical tuple of five values is already connected.

    Multicast Addresses

    Most people ignore the fact that multicast addresses exist, but they do exist. While unicast addresses are used for one-to-one communication, multicast addresses are used for one-to-many communication. Most people got aware of multicast addresses when they learned about IPv6 but multicast addresses also existed in IPv4, even though this feature was never widely used on the public Internet.

    The meaning of SO_REUSEADDR changes for multicast addresses as it allows multiple sockets to be bound to exactly the same combination of source multicast address and port. In other words, for multicast addresses SO_REUSEADDR behaves exactly as SO_REUSEPORT for unicast addresses. Actually, the code treats SO_REUSEADDR and SO_REUSEPORT identically for multicast addresses, that means you could say that SO_REUSEADDR implies SO_REUSEPORT for all multicast addresses and the other way round.


    FreeBSD/OpenBSD/NetBSD

    All these are rather late forks of the original BSD code, that's why they all three offer the same options as BSD and they also behave the same way as in BSD.


    macOS (MacOS X)

    At its core, macOS is simply a BSD-style UNIX named "Darwin", based on a rather late fork of the BSD code (BSD 4.3), which was then later on even re-synchronized with the (at that time current) FreeBSD 5 code base for the Mac OS 10.3 release, so that Apple could gain full POSIX compliance (macOS is POSIX certified). Despite having a microkernel at its core ("Mach"), the rest of the kernel ("XNU") is basically just a BSD kernel, and that's why macOS offers the same options as BSD and they also behave the same way as in BSD.

    iOS / watchOS / tvOS

    iOS is just a macOS fork with a slightly modified and trimmed kernel, somewhat stripped down user space toolset and a slightly different default framework set. watchOS and tvOS are iOS forks, that are stripped down even further (especially watchOS). To my best knowledge they all behave exactly as macOS does.


    Linux

    Linux < 3.9

    Prior to Linux 3.9, only the option SO_REUSEADDR existed. This option behaves generally the same as in BSD with two important exceptions:

    1. As long as a listening (server) TCP socket is bound to a specific port, the SO_REUSEADDR option is entirely ignored for all sockets targeting that port. Binding a second socket to the same port is only possible if it was also possible in BSD without having SO_REUSEADDR set. E.g. you cannot bind to a wildcard address and then to a more specific one or the other way round, both is possible in BSD if you set SO_REUSEADDR. What you can do is you can bind to the same port and two different non-wildcard addresses, as that's always allowed. In this aspect Linux is more restrictive than BSD.

    2. The second exception is that for client sockets, this option behaves exactly like SO_REUSEPORT in BSD, as long as both had this flag set before they were bound. The reason for allowing that was simply that it is important to be able to bind multiple sockets to exactly to the same UDP socket address for various protocols and as there used to be no SO_REUSEPORT prior to 3.9, the behavior of SO_REUSEADDR was altered accordingly to fill that gap. In that aspect Linux is less restrictive than BSD.

    Linux >= 3.9

    Linux 3.9 added the option SO_REUSEPORT to Linux as well. This option behaves exactly like the option in BSD and allows binding to exactly the same address and port number as long as all sockets have this option set prior to binding them.

    Yet, there are still two differences to SO_REUSEPORT on other systems:

    1. To prevent "port hijacking", there is one special limitation: All sockets that want to share the same address and port combination must belong to processes that share the same effective user ID! So one user cannot "steal" ports of another user. This is some special magic to somewhat compensate for the missing SO_EXCLBIND/SO_EXCLUSIVEADDRUSE flags.

    2. Additionally the kernel performs some "special magic" for SO_REUSEPORT sockets that isn't found in other operating systems: For UDP sockets, it tries to distribute datagrams evenly, for TCP listening sockets, it tries to distribute incoming connect requests (those accepted by calling accept()) evenly across all the sockets that share the same address and port combination. Thus an application can easily open the same port in multiple child processes and then use SO_REUSEPORT to get a very inexpensive load balancing.


    Android

    Even though the whole Android system is somewhat different from most Linux distributions, at its core works a slightly modified Linux kernel, thus everything that applies to Linux should apply to Android as well.


    Windows

    Windows only knows the SO_REUSEADDR option, there is no SO_REUSEPORT. Setting SO_REUSEADDR on a socket in Windows behaves like setting SO_REUSEPORT and SO_REUSEADDR on a socket in BSD, with one exception:

    Prior to Windows 2003, a socket with SO_REUSEADDR could always been bound to exactly the same source address and port as an already bound socket, even if the other socket did not have this option set when it was bound. This behavior allowed an application "to steal" the connected port of another application. Needless to say that this has major security implications!

    Microsoft realized that and added another important socket option: SO_EXCLUSIVEADDRUSE. Setting SO_EXCLUSIVEADDRUSE on a socket makes sure that if the binding succeeds, the combination of source address and port is owned exclusively by this socket and no other socket can bind to them, not even if it has SO_REUSEADDR set.

    This default behavior was changed first in Windows 2003, Microsoft calls that "Enhanced Socket Security" (funny name for a behavior that is default on all other major operating systems). For more details just visit this page. There are three tables: The first one shows the classic behavior (still in use when using compatibility modes!), the second one shows the behavior of Windows 2003 and up when the bind() calls are made by the same user, and the third one when the bind() calls are made by different users.


    Solaris

    Solaris is the successor of SunOS. SunOS was originally based on a fork of BSD, SunOS 5 and later was based on a fork of SVR4, however SVR4 is a merge of BSD, System V, and Xenix, so up to some degree Solaris is also a BSD fork, and a rather early one. As a result Solaris only knows SO_REUSEADDR, there is no SO_REUSEPORT. The SO_REUSEADDR behaves pretty much the same as it does in BSD. As far as I know there is no way to get the same behavior as SO_REUSEPORT in Solaris, that means it is not possible to bind two sockets to exactly the same address and port.

    Similar to Windows, Solaris has an option to give a socket an exclusive binding. This option is named SO_EXCLBIND. If this option is set on a socket prior to binding it, setting SO_REUSEADDR on another socket has no effect if the two sockets are tested for an address conflict. E.g. if socketA is bound to a wildcard address and socketB has SO_REUSEADDR enabled and is bound to a non-wildcard address and the same port as socketA, this bind will normally succeed, unless socketA had SO_EXCLBIND enabled, in which case it will fail regardless the SO_REUSEADDR flag of socketB.


    Other Systems

    In case your system is not listed above, I wrote a little test program that you can use to find out how your system handles these two options. Also if you think my results are wrong, please first run that program before posting any comments and possibly making false claims.

    All that the code requires to build is a bit POSIX API (for the network parts) and a C99 compiler (actually most non-C99 compiler will work as well as long as they offer inttypes.h and stdbool.h; e.g. gcc supported both long before offering full C99 support).

    All that the program needs to run is that at least one interface in your system (other than the local interface) has an IP address assigned and that a default route is set which uses that interface. The program will gather that IP address and use it as the second "specific address".

    It tests all possible combinations you can think of:

    • TCP and UDP protocol
    • Normal sockets, listen (server) sockets, multicast sockets
    • SO_REUSEADDR set on socket1, socket2, or both sockets
    • SO_REUSEPORT set on socket1, socket2, or both sockets
    • All address combinations you can make out of 0.0.0.0 (wildcard), 127.0.0.1 (specific address), and the second specific address found at your primary interface (for multicast it's just 224.1.2.3 in all tests)

    and prints the results in a nice table. It will also work on systems that don't know SO_REUSEPORT, in which case this option is simply not tested.

    What the program cannot easily test is how SO_REUSEADDR acts on sockets in TIME_WAIT state as it's very tricky to force and keep a socket in that state. Fortunately most operating systems seems to simply behave like BSD here and most of the time programmers can simply ignore the existence of that state.

    Here's the code (I cannot include it here, answers have a size limit and the code would push this reply over the limit).

    Why doesn't list have safe "get" method like dictionary?

    This works if you want the first element, like my_list.get(0)

    >>> my_list = [1,2,3]
    >>> next(iter(my_list), 'fail')
    1
    >>> my_list = []
    >>> next(iter(my_list), 'fail')
    'fail'
    

    I know it's not exactly what you asked for but it might help others.

    How do you handle a "cannot instantiate abstract class" error in C++?

    In my case i declared a function in COM Control .idl file like

    [id(1)] HRESULT MyMethod([in]INT param);
    

    but not declared in my interface .h file like this

    STDMETHOD(MyMethod)(INT param);
    

    Problem solved by adding above line into my interface .h file

    this might help some one .

    How to save as a new file and keep working on the original one in Vim?

    After save new file press

    Ctrl-6
    

    This is shortcut to alternate file

    How can I prevent the textarea from stretching beyond his parent DIV element? (google-chrome issue only)

    textarea {
    width: 700px;  
    height: 100px;
    resize: none; }
    

    assign your required width and height for the textarea and then use. resize: none ; css property which will disable the textarea's stretchable property.

    @synthesize vs @dynamic, what are the differences?

    here is example of @dynamic

    #import <Foundation/Foundation.h>
    
    @interface Book : NSObject
    {
       NSMutableDictionary *data;
    }
    @property (retain) NSString *title;
    @property (retain) NSString *author;
    @end
    
    @implementation Book
    @dynamic title, author;
    
    - (id)init
    {
        if ((self = [super init])) {
            data = [[NSMutableDictionary alloc] init];
            [data setObject:@"Tom Sawyer" forKey:@"title"];
            [data setObject:@"Mark Twain" forKey:@"author"];
        }
        return self;
    }
    
    - (void)dealloc
    {
        [data release];
        [super dealloc];
    }
    
    - (NSMethodSignature *)methodSignatureForSelector:(SEL)selector
    {
        NSString *sel = NSStringFromSelector(selector);
        if ([sel rangeOfString:@"set"].location == 0) {
            return [NSMethodSignature signatureWithObjCTypes:"v@:@"];
        } else {
            return [NSMethodSignature signatureWithObjCTypes:"@@:"];
        }
     }
    
    - (void)forwardInvocation:(NSInvocation *)invocation
    {
        NSString *key = NSStringFromSelector([invocation selector]);
        if ([key rangeOfString:@"set"].location == 0) {
            key = [[key substringWithRange:NSMakeRange(3, [key length]-4)] lowercaseString];
            NSString *obj;
            [invocation getArgument:&obj atIndex:2];
            [data setObject:obj forKey:key];
        } else {
            NSString *obj = [data objectForKey:key];
            [invocation setReturnValue:&obj];
        }
    }
    
    @end
    
    int main(int argc, char **argv)
    {
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
        Book *book = [[Book alloc] init];
        printf("%s is written by %s\n", [book.title UTF8String], [book.author UTF8String]);
        book.title = @"1984";
        book.author = @"George Orwell";
        printf("%s is written by %s\n", [book.title UTF8String], [book.author UTF8String]);
    
       [book release];
       [pool release];
       return 0;
    }
    

    Make button width fit to the text

    If you are developing to a modern browser. https://caniuse.com/#search=fit%20content

    You can use:

    width: fit-content;
    

    How do I display the value of a Django form field in a template?

    This was a feature request that got fixed in Django 1.3.

    Here's the bug: https://code.djangoproject.com/ticket/10427

    Basically, if you're running something after 1.3, in Django templates you can do:

    {{ form.field.value|default_if_none:"" }}
    

    Or in Jinja2:

    {{ form.field.value()|default("") }}
    

    Note that field.value() is a method, but in Django templates ()'s are omitted, while in Jinja2 method calls are explicit.

    If you want to know what version of Django you're running, it will tell you when you do the runserver command.

    If you are on something prior to 1.3, you can probably use the fix posted in the above bug: https://code.djangoproject.com/ticket/10427#comment:24

    One line if in VB .NET

    One Line 'If Statement'

    Easier than you think, noticed no-one has put what I've got yet, so I'll throw in my 2-cents.

    In my testing you don't need the continuation? semi-colon, you can do without, also you can do it without the End If.

    <C#> = Condition.

    <R#> = True Return.

    <E> = Else Return.

    Single Condition

    If <C1> Then <R1> Else <E>
    

    Multiple Conditions

    If <C1> Then <R1> Else If <C2> Then <R2> Else <E>
    

    Infinite? Conditions

    If <C1> Then <R1> Else If <C2> Then <R2> If <C3> Then <R3> If <C4> Then <R4> Else...
    ' Just keep adding "If <C> Then <R> Else" to get more
    

    -Not really sure how to format this to make it more readable, so if someone could offer a edit, please do-

    What are the differences between using the terminal on a mac vs linux?

    If you did a new or clean install of OS X version 10.3 or more recent, the default user terminal shell is bash.

    Bash is essentially an enhanced and GNU freeware version of the original Bourne shell, sh. If you have previous experience with bash (often the default on GNU/Linux installations), this makes the OS X command-line experience familiar, otherwise consider switching your shell either to tcsh or to zsh, as some find these more user-friendly.

    If you upgraded from or use OS X version 10.2.x, 10.1.x or 10.0.x, the default user shell is tcsh, an enhanced version of csh('c-shell'). Early implementations were a bit buggy and the programming syntax a bit weird so it developed a bad rap.

    There are still some fundamental differences between mac and linux as Gordon Davisson so aptly lists, for example no useradd on Mac and ifconfig works differently.

    The following table is useful for knowing the various unix shells.

    sh      The original Bourne shell   Present on every unix system 
    ksh     Original Korn shell         Richer shell programming environment than sh 
    csh     Original C-shell            C-like syntax; early versions buggy 
    tcsh    Enhanced C-shell            User-friendly and less buggy csh implementation 
    bash    GNU Bourne-again shell      Enhanced and free sh implementation 
    zsh     Z shell                     Enhanced, user-friendly ksh-like shell
    

    You may also find these guides helpful:

    http://homepage.mac.com/rgriff/files/TerminalBasics.pdf

    http://guides.macrumors.com/Terminal
    http://www.ofb.biz/safari/article/476.html

    On a final note, I am on Linux (Ubuntu 11) and Mac osX so I use bash and the thing I like the most is customizing the .bashrc (source'd from .bash_profile on OSX) file with aliases, some examples below. I now placed all my aliases in a separate .bash_aliases file and include it with:

    if [ -f ~/.bash_aliases ]; then
        . ~/.bash_aliases
    fi
    

    in the .bashrc or .bash_profile file.

    Note that this is an example of a mac-linux difference because on a Mac you can't have the --color=auto. The first time I did this (without knowing) I redefined ls to be invalid which was a bit alarming until I removed --auto-color !

    You may also find https://unix.stackexchange.com/q/127799/10043 useful

    # ~/.bash_aliases
    # ls variants
    #alias l='ls -CF' 
    alias la='ls -A' 
    alias l='ls -alFtr' 
    alias lsd='ls -d .*' 
    # Various
    alias h='history | tail'
    alias hg='history | grep'
    alias mv='mv -i' 
    alias zap='rm -i'
    # One letter quickies:
    alias p='pwd'
    alias x='exit'
    alias {ack,ak}='ack-grep'
    # Directories
    alias s='cd ..'
    alias play='cd ~/play/'
    # Rails
    alias src='script/rails console'
    alias srs='script/rails server'
    alias raked='rake db:drop db:create db:migrate db:seed' 
    alias rvm-restart='source '\''/home/durrantm/.rvm/scripts/rvm'\'''
    alias rrg='rake routes | grep '
    alias rspecd='rspec --drb '
    #
    # DropBox - syncd
    WORKBASE="~/Dropbox/97_2012/work"
    alias work="cd $WORKBASE"
    alias code="cd $WORKBASE/ror/code"
    #
    # DropNot - NOT syncd !
    WORKBASE_GIT="~/Dropnot"
    alias {dropnot,not}="cd $WORKBASE_GIT"
    alias {webs,ww}="cd $WORKBASE_GIT/webs"
    alias {setups,docs}="cd $WORKBASE_GIT/setups_and_docs"
    alias {linker,lnk}="cd $WORKBASE_GIT/webs/rails_v3/linker"
    #
    # git
    alias {gsta,gst}='git status' 
    # Warning: gst conflicts with gnu-smalltalk (when used).
    alias {gbra,gb}='git branch'
    alias {gco,go}='git checkout'
    alias {gcob,gob}='git checkout -b '
    alias {gadd,ga}='git add '
    alias {gcom,gc}='git commit'
    alias {gpul,gl}='git pull '
    alias {gpus,gh}='git push '
    alias glom='git pull origin master'
    alias ghom='git push origin master'
    alias gg='git grep '
    #
    # vim
    alias v='vim'
    #
    # tmux
    alias {ton,tn}='tmux set -g mode-mouse on'
    alias {tof,tf}='tmux set -g mode-mouse off'
    #
    # dmc
    alias {dmc,dm}='cd ~/Dropnot/webs/rails_v3/dmc/'
    alias wf='cd ~/Dropnot/webs/rails_v3/dmc/dmWorkflow'
    alias ws='cd ~/Dropnot/webs/rails_v3/dmc/dmStaffing'
    

    Bootstrap - floating navbar button right

    You would need to use the following markup. If you want to float any menu items to the right, create a separate <ul class="nav navbar-nav"> with navbar-right class to it.

    _x000D_
    _x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
    <html>_x000D_
    _x000D_
    <head>_x000D_
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
      <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />_x000D_
    </head>_x000D_
    _x000D_
    <body>_x000D_
      <div class="navbar navbar-inverse navbar-fixed-top" role="navigation">_x000D_
        <div class="container">_x000D_
          <div class="navbar-header">_x000D_
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">_x000D_
                <span class="sr-only">Toggle navigation</span>_x000D_
                <span class="icon-bar"></span>_x000D_
                <span class="icon-bar"></span>_x000D_
                <span class="icon-bar"></span>_x000D_
              </button>_x000D_
            <a class="navbar-brand" href="#">Project name</a>_x000D_
          </div>_x000D_
          <div class="collapse navbar-collapse">_x000D_
            <ul class="nav navbar-nav">_x000D_
              <li class="active"><a href="#">Home</a></li>_x000D_
              <li><a href="#about">About</a></li>_x000D_
    _x000D_
            </ul>_x000D_
            <ul class="nav navbar-nav navbar-right">_x000D_
              <li><a href="#contact">Contact</a></li>_x000D_
            </ul>_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
    </body>_x000D_
    _x000D_
    </html>
    _x000D_
    _x000D_
    _x000D_

    C# version of java's synchronized keyword?

    Take note, with full paths the line: [MethodImpl(MethodImplOptions.Synchronized)] should look like

    [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.Synchronized)]

    How to get primary key column in Oracle?

    Save the following script as something like findPK.sql.

    set verify off
    accept TABLE_NAME char prompt 'Table name>'
    
    SELECT cols.column_name
    FROM all_constraints cons NATURAL JOIN all_cons_columns cols
    WHERE cons.constraint_type = 'P' AND table_name = UPPER('&TABLE_NAME');
    

    It can then be called using

    @findPK
    

    PHP Sort a multidimensional array by element containing date

    http://us2.php.net/manual/en/function.array-multisort.php see third example:

    <?php
    
    $data[] = array('volume' => 67, 'edition' => 2);
    $data[] = array('volume' => 86, 'edition' => 1);
    $data[] = array('volume' => 85, 'edition' => 6);
    $data[] = array('volume' => 98, 'edition' => 2);
    $data[] = array('volume' => 86, 'edition' => 6);
    $data[] = array('volume' => 67, 'edition' => 7);
    
    foreach ($data as $key => $row) {
        $volume[$key]  = $row['volume'];
        $edition[$key] = $row['edition'];
    }
    
    array_multisort($volume, SORT_DESC, $edition, SORT_ASC, $data);
    
    ?>
    

    fyi, using a unix (seconds from 1970) or mysql timestamp (YmdHis - 20100526014500) would be be easier for the parser but i think in your case it makes no difference.

    MessageBodyWriter not found for media type=application/json

    In my experience this error is pretty common, for some reason jersey sometimes has problems parsing custom java types. Usually all you have to do is make sure that you respect the following 3 conditions:

    1. you have jersey-media-json-jackson in you pom.xml if using maven or added to your build path;
    2. you have an empty constructor in the data type you are trying to de-/serialize;
    3. you have the relevant annotation at the class and field level for your custom data type (xmlelement and/or jsonproperty);

    However, I have ran into cases where this just was not enough. Then you can always wrap you custom data type in a GenericEntity and pass it as such to your ResponseBuilder:

    GenericEntity<CustomDataType> entity = new GenericEntity<CustomDataType>(myObj) {};
    return Response.status(httpCode).entity(entity).build();
    

    This way you are trying to help jersey to find the proper/relevant serialization provider for you object. Well, sometimes this also is not enough. In my case I was trying to produce a text/plain from a custom data type. Theoretically jersey should have used the StringMessageProvider, but for some reason that I did not manage to discover it was giving me this error:

    org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyWriter not found for media type=text/plain
    

    So what solved the problem for me was to do my own serialization with jackson's writeValueAsString(). I'm not proud of it but at the end of the day I can deliver an acceptable solution.

    get all the images from a folder in php

    Here is my some code

    $dir          = '/Images';
    $ImagesA = Get_ImagesToFolder($dir);
    print_r($ImagesA);
    
    function Get_ImagesToFolder($dir){
        $ImagesArray = [];
        $file_display = [ 'jpg', 'jpeg', 'png', 'gif' ];
    
        if (file_exists($dir) == false) {
            return ["Directory \'', $dir, '\' not found!"];
        } 
        else {
            $dir_contents = scandir($dir);
            foreach ($dir_contents as $file) {
                $file_type = pathinfo($file, PATHINFO_EXTENSION);
                if (in_array($file_type, $file_display) == true) {
                    $ImagesArray[] = $file;
                }
            }
            return $ImagesArray;
        }
    }
    

    Java 8 lambdas, Function.identity() or t->t

    As of the current JRE implementation, Function.identity() will always return the same instance while each occurrence of identifier -> identifier will not only create its own instance but even have a distinct implementation class. For more details, see here.

    The reason is that the compiler generates a synthetic method holding the trivial body of that lambda expression (in the case of x->x, equivalent to return identifier;) and tell the runtime to create an implementation of the functional interface calling this method. So the runtime sees only different target methods and the current implementation does not analyze the methods to find out whether certain methods are equivalent.

    So using Function.identity() instead of x -> x might save some memory but that shouldn’t drive your decision if you really think that x -> x is more readable than Function.identity().

    You may also consider that when compiling with debug information enabled, the synthetic method will have a line debug attribute pointing to the source code line(s) holding the lambda expression, therefore you have a chance of finding the source of a particular Function instance while debugging. In contrast, when encountering the instance returned by Function.identity() during debugging an operation, you won’t know who has called that method and passed the instance to the operation.

    Make multiple-select to adjust its height to fit options without scroll bar

    I had this requirement recently and used other posts from this question to create this script:

    $("select[multiple]").each(function() {
      $(this).css("height","100%")
        .attr("size",this.length);
    })
    

    What is useState() in React?

    The answers provided above are good but let me just chip in, useState is async so if your next state is dependent on your previous state it is best you pass useState a callback. See the example below:

    import { useState } from 'react';
    
    function Example() {
        const [count, setCount] = useState(0);
    
      return (
        <div>
          <p>You clicked {count} times</p>
          // passing a callback to useState to update count
          <button onClick={() => setCount(count => count + 1)}>
            Click me
          </button>
        </div>
      );
    }
    

    This is the recommended way if your new state depends on computation from the old state.

    How do I set a textbox's text to bold at run time?

     txtText.Font = new Font("Segoe UI", 8,FontStyle.Bold);
     //Font(Font Name,Font Size,Font.Style)
    

    What are all the common ways to read a file in Ruby?

    One simple method is to use readlines:

    my_array = IO.readlines('filename.txt')
    

    Each line in the input file will be an entry in the array. The method handles opening and closing the file for you.

    Warning: #1265 Data truncated for column 'pdd' at row 1

    You are most likely pushing a string 'NULL' to the table, rather then an actual NULL, but other things may be going on as well, an illustration:

    mysql> CREATE TABLE date_test (pdd DATE NOT NULL);
    Query OK, 0 rows affected (0.11 sec)
    
    mysql> INSERT INTO date_test VALUES (NULL);
    ERROR 1048 (23000): Column 'pdd' cannot be null
    mysql> INSERT INTO date_test VALUES ('NULL');
    Query OK, 1 row affected, 1 warning (0.05 sec)
    
    mysql> show warnings;
    +---------+------+------------------------------------------+
    | Level   | Code | Message                                  |
    +---------+------+------------------------------------------+
    | Warning | 1265 | Data truncated for column 'pdd' at row 1 |
    +---------+------+------------------------------------------+
    1 row in set (0.00 sec)
    
    mysql> SELECT * FROM date_test;
    +------------+
    | pdd        |
    +------------+
    | 0000-00-00 |
    +------------+
    1 row in set (0.00 sec)
    
    mysql> ALTER TABLE date_test MODIFY COLUMN pdd DATE NULL;
    Query OK, 1 row affected (0.15 sec)
    Records: 1  Duplicates: 0  Warnings: 0
    
    mysql> INSERT INTO date_test VALUES (NULL);
    Query OK, 1 row affected (0.06 sec)
    
    mysql> SELECT * FROM date_test;
    +------------+
    | pdd        |
    +------------+
    | 0000-00-00 |
    | NULL       |
    +------------+
    2 rows in set (0.00 sec)
    

    How do I create a folder in VB if it doesn't exist?

    Directory.CreateDirectory() should do it. http://msdn.microsoft.com/en-us/library/system.io.directory.createdirectory(VS.71).aspx

    Also, in Vista, you probably cannot write into C: directly unless you run it as an admin, so you might just want to bypass that and create the dir you want in a sub-dir of C: (which i'd say is a good practice to be followed anyways. -- its unbelievable how many people just dump crap onto C:

    Hope that helps.

    maxlength ignored for input type="number" in Chrome

    Try this,

    <input type="number" onkeypress="return this.value.length < 4;" oninput="if(this.value.length>=4) { this.value = this.value.slice(0,4); }" />