Programs & Examples On #Reflectionpermission

Error message 'java.net.SocketException: socket failed: EACCES (Permission denied)'

Uninstalling the app on device and then reinstalling fixed it for me.

Tried all the other options, nothing. Finally found this post. This is after adding permission (below) and cleaning build.

<uses-permission android:name="android.permission.INTERNET"/>

Strings and character with printf

The name of an array is the address of its first element, so name is a pointer to memory containing the string "siva".

Also you don't need a pointer to display a character; you are just electing to use it directly from the array in this case. You could do this instead:

char c = *name;
printf("%c\n", c);

How to convert enum value to int?

Sometime some C# approach makes the life easier in Java world..:

class XLINK {
static final short PAYLOAD = 102, ACK = 103, PAYLOAD_AND_ACK = 104;
}
//Now is trivial to use it like a C# enum:
int rcv = XLINK.ACK;

Base64 encoding and decoding in client-side Javascript

Here is a tightened up version of Sniper's post. It presumes well formed base64 string with no carriage returns. This version eliminates a couple of loops, adds the &0xff fix from Yaroslav, eliminates trailing nulls, plus a bit of code golf.

decodeBase64 = function(s) {
    var e={},i,b=0,c,x,l=0,a,r='',w=String.fromCharCode,L=s.length;
    var A="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    for(i=0;i<64;i++){e[A.charAt(i)]=i;}
    for(x=0;x<L;x++){
        c=e[s.charAt(x)];b=(b<<6)+c;l+=6;
        while(l>=8){((a=(b>>>(l-=8))&0xff)||(x<(L-2)))&&(r+=w(a));}
    }
    return r;
};

Virtual Memory Usage from Java under Linux, too much memory used

One way of reducing the heap sice of a system with limited resources may be to play around with the -XX:MaxHeapFreeRatio variable. This is usually set to 70, and is the maximum percentage of the heap that is free before the GC shrinks it. Setting it to a lower value, and you will see in eg the jvisualvm profiler that a smaller heap sice is usually used for your program.

EDIT: To set small values for -XX:MaxHeapFreeRatio you must also set -XX:MinHeapFreeRatio Eg

java -XX:MinHeapFreeRatio=10 -XX:MaxHeapFreeRatio=25 HelloWorld

EDIT2: Added an example for a real application that starts and does the same task, one with default parameters and one with 10 and 25 as parameters. I didn't notice any real speed difference, although java in theory should use more time to increase the heap in the latter example.

Default parameters

At the end, max heap is 905, used heap is 378

MinHeap 10, MaxHeap 25

At the end, max heap is 722, used heap is 378

This actually have some inpact, as our application runs on a remote desktop server, and many users may run it at once.

How to create an integer array in Python?

If you are not satisfied with lists (because they can contain anything and take up too much memory) you can use efficient array of integers:

import array
array.array('i')

See here

If you need to initialize it,

a = array.array('i',(0 for i in range(0,10)))

Rails: Default sort order for a rails model?

A quick update to Michael's excellent answer above.

For Rails 4.0+ you need to put your sort in a block like this:

class Book < ActiveRecord::Base
  default_scope { order('created_at DESC') }
end

Notice that the order statement is placed in a block denoted by the curly braces.

They changed it because it was too easy to pass in something dynamic (like the current time). This removes the problem because the block is evaluated at runtime. If you don't use a block you'll get this error:

Support for calling #default_scope without a block is removed. For example instead of default_scope where(color: 'red'), please use default_scope { where(color: 'red') }. (Alternatively you can just redefine self.default_scope.)

As @Dan mentions in his comment below, you can do a more rubyish syntax like this:

class Book < ActiveRecord::Base
  default_scope { order(created_at: :desc) }
end

or with multiple columns:

class Book < ActiveRecord::Base
  default_scope { order({begin_date: :desc}, :name) }
end

Thanks @Dan!

Setting max-height for table cell contents

What I found !!!, In tables CSS td{height:60px;} works same as CSS td{min-height:60px;}

I know that situation when cells height looks bad . This javascript solution don't need overflow hidden.

For Limiting max-height of all cells or rows in table with Javascript:

This script is good for horizontal overflow tables.

This script increase the table width 300px each time (maximum 4000px) until rows shrinks to max-height(160px) , and you can also edit numbers as your need.

var i = 0, row, table = document.getElementsByTagName('table')[0], j = table.offsetWidth;
while (row = table.rows[i++]) {
    while (row.offsetHeight > 160 && j < 4000) {
        j += 300;
        table.style.width = j + 'px';
    }
}

Source: HTML Table Solution Max Height Limit For Rows Or Cells By Increasing Table Width, Javascript

What is the correct syntax of ng-include?

Maybe this will help for beginners

<!doctype html>
<html lang="en" ng-app>
  <head>
    <meta charset="utf-8">
    <title></title>
    <link rel="icon" href="favicon.ico">
    <link rel="stylesheet" href="custom.css">
  </head>
  <body>
    <div ng-include src="'view/01.html'"></div>
    <div ng-include src="'view/02.html'"></div>
    <script src="angular.min.js"></script>
  </body>
</html>

Converting String To Float in C#

You can double.Parse("41.00027357629127");

How to execute shell command in Javascript

If you are using npm you can use the shelljs package

To install: npm install [-g] shelljs

var shell = require('shelljs');
shell.ls('*.js').forEach(function (file) {
// do something
});

See more: https://www.npmjs.com/package/shelljs

Which sort algorithm works best on mostly sorted data?

Bubble sort is definitely the winner The next one on the radar would be insertion sort.

How to export html table to excel or pdf in php

Either you can use CSV functions or PHPExcel

or you can try like below

<?php
$file="demo.xls";
$test="<table  ><tr><td>Cell 1</td><td>Cell 2</td></tr></table>";
header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=$file");
echo $test;
?>

The header for .xlsx files is Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

How to insert spaces/tabs in text using HTML/CSS

This worked for me:

In my CSS I have:

tab0  { position:absolute;left:25px;  }
tab1  { position:absolute;left:50px;  }
tab2  { position:absolute;left:75px;  }
tab3  { position:absolute;left:100px; }
tab4  { position:absolute;left:125px; }
tab5  { position:absolute;left:150px; }
tab6  { position:absolute;left:175px; }
tab7  { position:absolute;left:200px; }
tab8  { position:absolute;left:225px; }
tab9  { position:absolute;left:250px; }
tab10 { position:absolute;left:275px; }

Then in the HTML I just use my tabs:

Dog Food <tab3> :$30
Milk <tab3> :$3
Pizza Kit <tab3> :$5
Mt Dew <tab3> :$1.75

Does overflow:hidden applied to <body> work on iPhone Safari?

Here is what I did: I check the body y position , then make the body fixed and adjust the top to the negative of that position. On reverse, I make the body static and set the scroll to the value I recorded before.

var body_x_position = 0;

function disable_bk_scrl(){

    var elb = document.querySelector('body');

    body_x_position = elb.scrollTop;
    // get scroll position in px

    var body_x_position_m = body_x_position*(-1);
    console.log(body_x_position);

    document.body.style.position = "fixed";

    $('body').css({ top: body_x_position_m });

}

function enable_bk_scrl(){  

    document.body.style.position = "static";

    document.body.scrollTo(0, body_x_position);

    console.log(body_x_position);
}

Markdown: continue numbered list

I solved this problem on Github separating the indented sub-block with a newline, for instance, you write the item 1, then hit enter twice (like if it was a new paragraph), indent the block and write what you want (a block of code, text, etc). More information on Markdown lists and Markdown line breaks.

Example:

  1. item one
  2. item two

    this block acts as a new paragraph, above there is a blank line

  3. item three

    some other code

  4. item four

How to create a generic array?

checked :

public Constructor(Class<E> c, int length) {

    elements = (E[]) Array.newInstance(c, length);
}

or unchecked :

public Constructor(int s) {
    elements = new Object[s];
}

How to prevent SIGPIPEs (or handle them properly)

You cannot prevent the process on the far end of a pipe from exiting, and if it exits before you've finished writing, you will get a SIGPIPE signal. If you SIG_IGN the signal, then your write will return with an error - and you need to note and react to that error. Just catching and ignoring the signal in a handler is not a good idea -- you must note that the pipe is now defunct and modify the program's behaviour so it does not write to the pipe again (because the signal will be generated again, and ignored again, and you'll try again, and the whole process could go on for a long time and waste a lot of CPU power).

Moment.js - two dates difference in number of days

Here's how you can get the comprehensive full fledge difference of two dates.

 function diffYMDHMS(date1, date2) {

    let years = date1.diff(date2, 'year');
    date2.add(years, 'years');

    let months = date1.diff(date2, 'months');
    date2.add(months, 'months');

    let days = date1.diff(date2, 'days');
    date2.add(days, 'days');

    let hours = date1.diff(date2, 'hours');
    date2.add(hours, 'hours');

    let minutes = date1.diff(date2, 'minutes');
    date2.add(minutes, 'minutes');

    let seconds = date1.diff(date2, 'seconds');

    console.log(years + ' years ' + months + ' months ' + days + ' days ' + hours + ' 
    hours ' + minutes + ' minutes ' + seconds + ' seconds'); 

    return { years, months, days, hours, minutes, seconds};
}

Extract month and year from a zoo::yearmon object

For large vectors:

y = as.POSIXlt(date1)$year + 1900    # x$year : years since 1900
m = as.POSIXlt(date1)$mon + 1        # x$mon : 0–11

How to redirect single url in nginx?

Put this in your server directive:

location /issue {
   rewrite ^/issue(.*) http://$server_name/shop/issues/custom_issue_name$1 permanent;
 }

Or duplicate it:

location /issue1 {
   rewrite ^/.* http://$server_name/shop/issues/custom_issue_name1 permanent;
}
location /issue2 {
   rewrite ^.* http://$server_name/shop/issues/custom_issue_name2 permanent;
}
 ...

How do I speed up the gwt compiler?

The GWT compiler is doing a lot of code analysis so it is going to be difficult to speed it up. This session from Google IO 2008 will give you a good idea of what GWT is doing and why it does take so long.

My recommendation is for development use Hosted Mode as much as possible and then only compile when you want to do your testing. This does sound like the solution you've come to already, but basically that's why Hosted Mode is there (well, that and debugging).

You can speed up the GWT compile but only compiling for some browsers, rather than 5 kinds which GWT does by default. If you want to use Hosted Mode make sure you compile for at least two browsers; if you compile for a single browser then the browser detection code is optimised away and then Hosted Mode doesn't work any more.

An easy way to configure compiling for fewer browsers is to create a second module which inherits from your main module:

<module rename-to="myproject">
  <inherits name="com.mycompany.MyProject"/>
  <!-- Compile for IE and Chrome -->
  <!-- If you compile for only one browser, the browser detection javascript
       is optimised away and then Hosted Mode doesn't work -->
  <set-property name="user.agent" value="ie6,safari"/>
</module>

If the rename-to attribute is set the same then the output files will be same as if you did a full compile

How to Convert Boolean to String

function ToStr($Val=null,$T=0){

    return is_string($Val)?"$Val"
    :
    (
        is_numeric($Val)?($T?"$Val":$Val)
        :
        (
            is_null($Val)?"NULL"
            :
            (
                is_bool($Val)?($Val?"TRUE":"FALSE")
                :
                (
                    is_array($Val)?@StrArr($Val,$T)
                    :
                    false
                )
            )
        )
    );

}
function StrArr($Arr,$T=0)
{
    $Str="";
    $i=-1;
    if(is_array($Arr))
    foreach($Arr AS $K => $V)
    $Str.=((++$i)?", ":null).(is_string($K)?"\"$K\"":$K)." => ".(is_string($V)?"\"$V\"":@ToStr($V,$T+1));
    return "array( ".($i?@ToStr($Arr):$Str)." )".($T?null:";");
}

$A = array(1,2,array('a'=>'b'),array('a','b','c'),true,false,ToStr(100));
echo StrArr($A); // OR ToStr($A) // OR ToStr(true) // OR StrArr(true)

Add leading zeroes to number in Java?

Since Java 1.5 you can use the String.format method. For example, to do the same thing as your example:

String format = String.format("%0%d", digits);
String result = String.format(format, num);
return result;

In this case, you're creating the format string using the width specified in digits, then applying it directly to the number. The format for this example is converted as follows:

%% --> %
0  --> 0
%d --> <value of digits>
d  --> d

So if digits is equal to 5, the format string becomes %05d which specifies an integer with a width of 5 printing leading zeroes. See the java docs for String.format for more information on the conversion specifiers.

How do I install and use the ASP.NET AJAX Control Toolkit in my .NET 3.5 web applications?

you will also need to have a asp:ScriptManager control on every page that you want to use ajax controls on. you should be able to just drag the scriptmanager over from your toolbox one the toolkit is installed following Zack's instructions.

How do I use disk caching in Picasso?

1) Picasso by default has cache (see ahmed hamdy answer)

2) If your really must take image from disk cache and then network I recommend to write your own downloader:

public class OkHttpDownloaderDiskCacheFirst extends OkHttpDownloader {
    public OkHttpDownloaderDiskCacheFirst(OkHttpClient client) {
        super(client);
    }

    @Override
    public Response load(Uri uri, int networkPolicy) throws IOException {
        Response responseDiskCache = null;
        try {
            responseDiskCache = super.load(uri, 1 << 2); //NetworkPolicy.OFFLINE
        } catch (Exception ignored){} // ignore, handle null later

        if (responseDiskCache == null || responseDiskCache.getContentLength()<=0){
            return  super.load(uri, networkPolicy); //user normal policy
        } else {
            return responseDiskCache;
        }

    }
}

And in Application singleton in method OnCreate use it with picasso:

        OkHttpClient okHttpClient = new OkHttpClient();

        okHttpClient.setCache(new Cache(getCacheDir(), 100 * 1024 * 1024)); //100 MB cache, use Integer.MAX_VALUE if it is too low
        OkHttpDownloader downloader = new OkHttpDownloaderDiskCacheFirst(okHttpClient); 

        Picasso.Builder builder = new Picasso.Builder(this);

        builder.downloader(downloader);

        Picasso built = builder.build();

        Picasso.setSingletonInstance(built);

3) No permissions needed for defalut application cache folder

How to convert an int to string in C?

This is old but here's another way.

#include <stdio.h>

#define atoa(x) #x

int main(int argc, char *argv[])
{
    char *string = atoa(1234567890);
    printf("%s\n", string);
    return 0;
}

What's the difference between utf8_general_ci and utf8_unicode_ci?

In brief words:

If you need better sorting order - use utf8_unicode_ci (this is the preferred method),

but if you utterly interested in performance - use utf8_general_ci, but know that it is a little outdated.

The differences in terms of performance are very slight.

GET and POST methods with the same Action name in the same Controller

You received the good answer to this question, but I want to add my two cents. You could use one method and process requests according to request type:

public ActionResult Index()
{
    if("GET"==this.HttpContext.Request.RequestType)
    {
        Some Code--Some Code---Some Code for GET
    }
    else if("POST"==this.HttpContext.Request.RequestType)
    {
        Some Code--Some Code---Some Code for POST
    }
    else
    {
        //exception
    }

    return View();
}

Open a link in browser with java button?

I know that this is an old question but sometimes the Desktop.getDesktop() produces an unexpected crash like in Ubuntu 18.04. Therefore, I have to re-write my code like this:

public static void openURL(String domain)
{
    String url = "https://" + domain;
    Runtime rt = Runtime.getRuntime();
    try {
        if (MUtils.isWindows()) {
            rt.exec("rundll32 url.dll,FileProtocolHandler " + url).waitFor();
            Debug.log("Browser: " + url);
        } else if (MUtils.isMac()) {
            String[] cmd = {"open", url};
            rt.exec(cmd).waitFor();
            Debug.log("Browser: " + url);
        } else if (MUtils.isUnix()) {
            String[] cmd = {"xdg-open", url};
            rt.exec(cmd).waitFor();
            Debug.log("Browser: " + url);
        } else {
            try {
                throw new IllegalStateException();
            } catch (IllegalStateException e1) {
                MUtils.alertMessage(Lang.get("desktop.not.supported"), MainPn.getMainPn());
                e1.printStackTrace();
            }
        }
    } catch (IOException | InterruptedException e) {
        e.printStackTrace();
    }
}

public static boolean isWindows()
{
    return OS.contains("win");
}

public static boolean isMac()
{
    return OS.contains("mac");
}

public static boolean isUnix()
{
    return OS.contains("nix") || OS.contains("nux") || OS.indexOf("aix") > 0;
}

Then we can call this helper from the instance:

button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        MUtils.openURL("www.google.com"); // just what is the 'open' method?
    }
});

Creation timestamp and last update timestamp with Hibernate and MySQL

With Olivier's solution, during update statements you may run into:

com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'created' cannot be null

To solve this, add updatable=false to the @Column annotation of "created" attribute:

@Temporal(TemporalType.TIMESTAMP)
@Column(name = "created", nullable = false, updatable=false)
private Date created;

Best method to download image from url in Android

I'm still learning Android, so I cannot provide a rich context or reason for my suggestion, but this is what I am using to retrive files from both https and local urls. I am using this in my onActivity result (for both taking pictures and selecting from gallery), as well in an AsyncTask to retrieve the https urls.

InputStream input = new URL("your_url_string").openStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);

Retrieving Dictionary Value Best Practices

I imagine that trygetvalue is doing something more like:

if(myDict.ReallyOptimisedVersionofContains(someKey))
{ 
  someVal = myDict[someKey];
  return true;
}
return false;

So hopefully no try/catch anywhere.

I think it is just a method of convenience really. I generally use it as it saves a line of code or two.

Is it possible to cherry-pick a commit from another git repository?

My situation was that I have a bare repo that the team pushes to, and a clone of that sitting right next to it. This set of lines in a Makefile work correctly for me:

git reset --hard
git remote update --prune
git pull --rebase --all
git cherry-pick -n remotes/origin/$(BRANCH)

By keeping the master of the bare repo up to date, we are able to cherry-pick a proposed change published to the bare repo. We also have a (more complicated) way to cherry-pick multiple braches for consolidated review and testing.

If "knows nothing" means "can't be used as a remote", then this doesn't help, but this SO question came up as I was googling around to come up with this workflow so I thought I'd contribute back.

Check if string is upper, lower, or mixed case in Python

I want to give a shoutout for using re module for this. Specially in the case of case sensitivity.

We use the option re.IGNORECASE while compiling the regex for use of in production environments with large amounts of data.

>>> import re
>>> m = ['isalnum','isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'ISALNUM', 'ISALPHA', 'ISDIGIT', 'ISLOWER', 'ISSPACE', 'ISTITLE', 'ISUPPER']
>>>
>>>
>>> pattern = re.compile('is')
>>>
>>> [word for word in m if pattern.match(word)]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']

However try to always use the in operator for string comparison as detailed in this post

faster-operation-re-match-or-str

Also detailed in the one of the best books to start learning python with

idiomatic-python

What is the default value for enum variable?

You can use this snippet :-D

using System;
using System.Reflection;

public static class EnumUtils
{
    public static T GetDefaultValue<T>()
        where T : struct, Enum
    {
        return (T)GetDefaultValue(typeof(T));
    }

    public static object GetDefaultValue(Type enumType)
    {
        var attribute = enumType.GetCustomAttribute<DefaultValueAttribute>(inherit: false);
        if (attribute != null)
            return attribute.Value;

        var innerType = enumType.GetEnumUnderlyingType();
        var zero = Activator.CreateInstance(innerType);
        if (enumType.IsEnumDefined(zero))
            return zero;

        var values = enumType.GetEnumValues();
        return values.GetValue(0);
    }
}

Example:

using System;

public enum Enum1
{
    Foo,
    Bar,
    Baz,
    Quux
}
public enum Enum2
{
    Foo  = 1,
    Bar  = 2,
    Baz  = 3,
    Quux = 0
}
public enum Enum3
{
    Foo  = 1,
    Bar  = 2,
    Baz  = 3,
    Quux = 4
}
[DefaultValue(Enum4.Bar)]
public enum Enum4
{
    Foo  = 1,
    Bar  = 2,
    Baz  = 3,
    Quux = 4
}

public static class Program 
{
    public static void Main() 
    {
        var defaultValue1 = EnumUtils.GetDefaultValue<Enum1>();
        Console.WriteLine(defaultValue1); // Foo

        var defaultValue2 = EnumUtils.GetDefaultValue<Enum2>();
        Console.WriteLine(defaultValue2); // Quux

        var defaultValue3 = EnumUtils.GetDefaultValue<Enum3>();
        Console.WriteLine(defaultValue3); // Foo

        var defaultValue4 = EnumUtils.GetDefaultValue<Enum4>();
        Console.WriteLine(defaultValue4); // Bar
    }
}

GCC dump preprocessor defines

While working in a big project which has complex build system and where it is hard to get (or modify) the gcc/g++ command directly there is another way to see the result of macro expansion. Simply redefine the macro, and you will get output similiar to following:

file.h: note: this is the location of the previous definition
#define MACRO current_value

How to do multiple conditions for single If statement

Use the 'And' keyword for a logical and. Like this:

If Not ((filename = testFileName) And (fileName <> "")) Then

Error: No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'

Add "EntityFramework.SqlServer.dll" into your bin folder. Problem will get resolved.

Copy array by value

Make copy of multidimensional array/object:

function deepCopy(obj) {
   if (Object.prototype.toString.call(obj) === '[object Array]') {
      var out = [], i = 0, len = obj.length;
      for ( ; i < len; i++ ) {
         out[i] = arguments.callee(obj[i]);
      }
      return out;
   }
   if (typeof obj === 'object') {
      var out = {}, i;
      for ( i in obj ) {
         out[i] = arguments.callee(obj[i]);
      }
      return out;
   }
   return obj;
}

Thanks to James Padolsey for this function.

Source: Here

Cancel a UIView animation?

Simplest way to stop all animations on a particular view, immediately, is this:

Link the project to QuartzCore.framework. At the start of your code:

#import <QuartzCore/QuartzCore.h>

Now, when you want to stop all animations on a view dead in their tracks, say this:

[CATransaction begin];
[theView.layer removeAllAnimations];
[CATransaction commit];

The middle line would work all by itself, but there's a delay until the runloop finishes (the "redraw moment"). To prevent that delay, wrap the command in an explicit transaction block as shown. This works provided no other changes have been performed on this layer in the current runloop.

Use CSS3 transitions with gradient backgrounds

A solution is to use background-position to mimic the gradient transition. This solution was used in Twitter Bootstrap a few months ago.

Update

http://codersblock.blogspot.fr/2013/12/gradient-animation-trick.html?showComment=1390287622614

Here is a quick example:

Link state

 .btn {
  font-family: "Helvetica Neue", Arial, sans-serif;
  font-size: 12px;
  font-weight: 300;
  position: relative;
  display: inline-block;
  text-decoration: none;
  color: #fff;
  padding: 20px 40px;
  background-image: -moz-linear-gradient(top, #50abdf, #1f78aa);
  background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#50abdf), to(#1f78aa));
  background-image: -webkit-linear-gradient(top, #50abdf, #1f78aa);
  background-image: -o-linear-gradient(top, #50abdf, #1f78aa);
  background-image: linear-gradient(to bottom, #50abdf, #1f78aa);
  background-repeat: repeat-x;
  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff50abdf', endColorstr='#ff1f78aa', GradientType=0);
  background-repeat: repeat-y;
  background-size: 100% 90px;
  background-position: 0 -30px;
  -webkit-transition: all 0.2s linear;
     -moz-transition: all 0.2s linear;
       -o-transition: all 0.2s linear;
          transition: all 0.2s linear;
}

Hover state

.btn:hover {
   background-position: 0 0;
}

What is causing the error `string.split is not a function`?

maybe

string = document.location.href;
arrayOfStrings = string.toString().split('/');

assuming you want the current url

Socket send and receive byte array

You need to either have the message be a fixed size, or you need to send the size or you need to use some separator characters.

This is the easiest case for a known size (100 bytes):

in = new DataInputStream(server.getInputStream());
byte[] message = new byte[100]; // the well known size
in.readFully(message);

In this case DataInputStream makes sense as it offers readFully(). If you don't use it, you need to loop yourself until the expected number of bytes is read.

XmlSerializer: remove unnecessary xsi and xsd namespaces

There is an alternative - you can provide a member of type XmlSerializerNamespaces in the type to be serialized. Decorate it with the XmlNamespaceDeclarations attribute. Add the namespace prefixes and URIs to that member. Then, any serialization that does not explicitly provide an XmlSerializerNamespaces will use the namespace prefix+URI pairs you have put into your type.

Example code, suppose this is your type:

[XmlRoot(Namespace = "urn:mycompany.2009")]
public class Person {
  [XmlAttribute] 
  public bool Known;
  [XmlElement]
  public string Name;
  [XmlNamespaceDeclarations]
  public XmlSerializerNamespaces xmlns;
}

You can do this:

var p = new Person
  { 
      Name = "Charley",
      Known = false, 
      xmlns = new XmlSerializerNamespaces()
  }
p.xmlns.Add("",""); // default namespace is emoty
p.xmlns.Add("c", "urn:mycompany.2009");

And that will mean that any serialization of that instance that does not specify its own set of prefix+URI pairs will use the "p" prefix for the "urn:mycompany.2009" namespace. It will also omit the xsi and xsd namespaces.

The difference here is that you are adding the XmlSerializerNamespaces to the type itself, rather than employing it explicitly on a call to XmlSerializer.Serialize(). This means that if an instance of your type is serialized by code you do not own (for example in a webservices stack), and that code does not explicitly provide a XmlSerializerNamespaces, that serializer will use the namespaces provided in the instance.

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

1) To answer your question:

  String s="Java";
  System.out.println(s.length()); 

How to fix an UnsatisfiedLinkError (Can't find dependent libraries) in a JNI project

  • Short answer: for "can't find dependent library" error, check your $PATH (corresponds to bullet point #3 below)
  • Long answer:
    1. Pure java world: jvm uses "Classpath" to find class files
    2. JNI world (java/native boundary): jvm uses "java.library.path" (which defaults to $PATH) to find dlls
    3. pure native world: native code uses $PATH to load other dlls

Iterating through array - java

If you are using an array (and purely an array), the lookup of "contains" is O(N), because worst case, you must iterate the entire array. Now if the array is sorted you can use a binary search, which reduces the search time to log(N) with the overhead of the sort.

If this is something that is invoked repeatedly, place it in a function:

private boolean inArray(int[] array, int value)
{  
     for (int i = 0; i < array.length; i++)
     {
        if (array[i] == value) 
        {
            return true;
        }
     }
    return false;  
}  

ThreeJS: Remove object from scene

When you use : scene.remove(object); The object is removed from the scene, but the collision with it is still enabled !

To remove also the collsion with the object, you can use that (for an array) : objectsArray.splice(i, 1);

Example :

for (var i = 0; i < objectsArray.length; i++) {
//::: each object ::://
var object = objectsArray[i]; 
//::: remove all objects from the scene ::://
scene.remove(object); 
//::: remove all objects from the array ::://
objectsArray.splice(i, 1); 

}

Precision String Format Specifier In Swift

import Foundation

extension CGFloat {
    var string1: String {
        return String(format: "%.1f", self)
    }
    var string2: String {
        return String(format: "%.2f", self)
    }
}

Usage

let offset = CGPoint(1.23, 4.56)
print("offset: \(offset.x.string1) x \(offset.y.string1)")
// offset: 1.2 x 4.6

JavaScript Nested function

Functions are another type of variable in JavaScript (with some nuances of course). Creating a function within another function changes the scope of the function in the same way it would change the scope of a variable. This is especially important for use with closures to reduce total global namespace pollution.

The functions defined within another function won't be accessible outside the function unless they have been attached to an object that is accessible outside the function:

function foo(doBar)
{
  function bar()
  {
    console.log( 'bar' );
  }

  function baz()
  {
    console.log( 'baz' );
  }

  window.baz = baz;
  if ( doBar ) bar();
}

In this example, the baz function will be available for use after the foo function has been run, as it's overridden window.baz. The bar function will not be available to any context other than scopes contained within the foo function.

as a different example:

function Fizz(qux)
{
  this.buzz = function(){
    console.log( qux );
  };
}

The Fizz function is designed as a constructor so that, when run, it assigns a buzz function to the newly created object.

Terminal Multiplexer for Microsoft Windows - Installers for GNU Screen or tmux

As an alternative SuperPutty has tabs and the option to run the same command across many terminals... might be what someone is looking for.

https://code.google.com/p/superputty/

It imports your PuTTY sessions too.

Git - Pushing code to two remotes

To send to both remote with one command, you can create a alias for it:

git config alias.pushall '!git push origin devel && git push github devel'

With this, when you use the command git pushall, it will update both repositories.

How to get a jqGrid cell value when editing

Before i was getting : html tag of the textbox something like

but Here is the solution to get the value from that particular column, working and tested

function getValue(rowId, cellId) {
        var val = $("[rowId='"+rowId+"'][name='"+cellId+"']").val();
        return val;
       }

var values = getValue(rowId, 'cellid');

Show compose SMS view in Android

This allows to send text message through existing app. phoneNumber - is String. If you do not wish to specify phone number, use empty string "".

Intent sendIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("smsto", phoneNumber, null));
sendIntent.putExtra("sms_body", "text message");
startActivity(sendIntent);

Reading a text file in MATLAB line by line

Just read it in to MATLAB in one block

fid = fopen('file.csv');
data=textscan(fid,'%s %f %f','delimiter',',');
fclose(fid);

You can then process it using logical addressing

ind50 = data{2}>=50 ;

ind50 is then an index of the rows where column 2 is greater than 50. So

data{1}(ind50)

will list all the strings for the rows of interest. Then just use fprintf to write out your data to the new file

Combine [NgStyle] With Condition (if..else)

To add and simplify Günter Zöchbauer's the example incase using (if...else) to set something else than background image :

<p [ngStyle]="value == 10 && { 'font-weight': 'bold' }">

ldconfig error: is not a symbolic link

I have also faced the same issue, The solution for it is : the file for which you are getting the error is probably a duplicated file of the actual file with another version. So just the removal of a particular file on which errors are thrown can resolve the issue.

How to change the color of a CheckBox?

Most answers go through the xml file. If you find an active answer for most Android versions and are just one color for the two statuses Check an UnCheck: here is my solution:

Kotlin:

val colorFilter = PorterDuffColorFilter(Color.CYAN, PorterDuff.Mode.SRC_ATOP)
CompoundButtonCompat.getButtonDrawable(checkBox)?.colorFilter = colorFilter

Java:

ColorFilter colorFilter = new PorterDuffColorFilter(Color.CYAN, PorterDuff.Mode.SRC_ATOP);
Drawable drawable = CompoundButtonCompat.getButtonDrawable(checkBox);
if (drawable != null) {
    drawable.setColorFilter(colorFilter);
}

extract digits in a simple way from a python string

This regular expression handles floats as well

import re
re_float = re.compile(r'\d*\.?\d+')

You could also add a group to the expression that catches your weight units.

re_banana = re.compile(r'(?P<number>\d*\.?\d+)\s?(?P<uni>[a-zA-Z]+)')

You can access the named groups like this re_banana.match("200 kgm").group('number').

I think this should help you getting started.

jQuery fade out then fade in

After jQuery 1.6, using promise seems like a better option.

var $div1 = $('#div1');
var fadeOutDone = $div1.fadeOut().promise();
// do your logic here, e.g.fetch your 2nd image url
$.get('secondimageinfo.json').done(function(data){
  fadeoOutDone.then(function(){
    $div1.html('<img src="' + data.secondImgUrl + '" alt="'data.secondImgAlt'">');
    $div1.fadeIn();
  });
});

Calculating Page Load Time In JavaScript

The answer mentioned by @HaNdTriX is a great, but we are not sure if DOM is completely loaded in the below code:

var loadTime = window.performance.timing.domContentLoadedEventEnd- window.performance.timing.navigationStart; 

This works perfectly when used with onload as:

window.onload = function () {
    var loadTime = window.performance.timing.domContentLoadedEventEnd-window.performance.timing.navigationStart; 
    console.log('Page load time is '+ loadTime);
}

Edit 1: Added some context to answer

Note: loadTime is in milliseconds, you can divide by 1000 to get seconds as mentioned by @nycynik

What is the difference between rb and r+b modes in file objects

r opens for reading, whereas r+ opens for reading and writing. The b is for binary.

This is spelled out in the documentation:

The most commonly-used values of mode are 'r' for reading, 'w' for writing (truncating the file if it already exists), and 'a' for appending (which on some Unix systems means that all writes append to the end of the file regardless of the current seek position). If mode is omitted, it defaults to 'r'. The default is to use text mode, which may convert '\n' characters to a platform-specific representation on writing and back on reading. Thus, when opening a binary file, you should append 'b' to the mode value to open the file in binary mode, which will improve portability. (Appending 'b' is useful even on systems that don’t treat binary and text files differently, where it serves as documentation.) See below for more possible values of mode.

Modes 'r+', 'w+' and 'a+' open the file for updating (note that 'w+' truncates the file). Append 'b' to the mode to open the file in binary mode, on systems that differentiate between binary and text files; on systems that don’t have this distinction, adding the 'b' has no effect.

How to get an Array with jQuery, multiple <input> with the same name

Q:How to access name array text field

<input type="text" id="task" name="task[]" />

Answer - Using Input name array :

$('input[name="task\\[\\]"]').eq(0).val()
$('input[name="task\\[\\]"]').eq(index).val()

Count lines in large files

I know the question is a few years old now, but expanding on Ivella's last idea, this bash script estimates the line count of a big file within seconds or less by measuring the size of one line and extrapolating from it:

#!/bin/bash
head -2 $1 | tail -1 > $1_oneline
filesize=$(du -b $1 | cut -f -1)
linesize=$(du -b $1_oneline | cut -f -1)
rm $1_oneline
echo $(expr $filesize / $linesize)

If you name this script lines.sh, you can call lines.sh bigfile.txt to get the estimated number of lines. In my case (about 6 GB, export from database), the deviation from the true line count was only 3%, but ran about 1000 times faster. By the way, I used the second, not first, line as the basis, because the first line had column names and the actual data started in the second line.

Why do I need 'b' to encode a string with Base64?

base64 encoding takes 8-bit binary byte data and encodes it uses only the characters A-Z, a-z, 0-9, +, /* so it can be transmitted over channels that do not preserve all 8-bits of data, such as email.

Hence, it wants a string of 8-bit bytes. You create those in Python 3 with the b'' syntax.

If you remove the b, it becomes a string. A string is a sequence of Unicode characters. base64 has no idea what to do with Unicode data, it's not 8-bit. It's not really any bits, in fact. :-)

In your second example:

>>> encoded = base64.b64encode('data to be encoded')

All the characters fit neatly into the ASCII character set, and base64 encoding is therefore actually a bit pointless. You can convert it to ascii instead, with

>>> encoded = 'data to be encoded'.encode('ascii')

Or simpler:

>>> encoded = b'data to be encoded'

Which would be the same thing in this case.


* Most base64 flavours may also include a = at the end as padding. In addition, some base64 variants may use characters other than + and /. See the Variants summary table at Wikipedia for an overview.

SQL Server: Invalid Column Name

  • Refresh your tables.
  • Restart the SQL server.
  • Look out for the spelling mistakes in Query.

Convert a bitmap into a byte array

Try the following:

MemoryStream stream = new MemoryStream();
Bitmap bitmap = new Bitmap();
bitmap.Save(stream, ImageFormat.Jpeg);

byte[] byteArray = stream.GetBuffer();

Make sure you are using:

System.Drawing & using System.Drawing.Imaging;

Usage of @see in JavaDoc?

I use @see to annotate methods of an interface implementation class where the description of the method is already provided in the javadoc of the interface. When we do that I notice that Eclipse pulls up the interface's documentation even when I am looking up method on the implementation reference during code complete

How do you run a script on login in *nix?

When using Bash, the first of ~/.bash_profile, ~/.bash_login and ~/.profile will be run for an interactive login shell. I believe ~/.profile is generally run by Unix shells besides Bash. Bash will run ~/.bashrc for a non-login interactive shell.

I typically put everything I want to always set in .bashrc and then run it from .bash_profile, where I also set up a few things that should run only when I'm logging in, such as setting up ssh-agent or running screen.

an htop-like tool to display disk activity in linux

It is not htop-like, but you could use atop. However, to display disk activity per process, it needs a kernel patch (available from the site). These kernel patches are now obsoleted, only to show per-process network activity an optional module is provided.

How to overlay one div over another div

The new Grid CSS specification provides a far more elegant solution. Using position: absolute may lead to overlaps or scaling issues while Grid will save you from dirty CSS hacks.

Most minimal Grid Overlay example:

HTML

<div class="container">
  <div class="content">This is the content</div>
  <div class="overlay">Overlay - must be placed under content in the HTML</div>
</div>

CSS

.container {
  display: grid;
}

.content, .overlay {
  grid-area: 1 / 1;
}

That's it. If you don't build for Internet Explorer, your code will most probably work.

javascript /jQuery - For Loop

What about something like this?

var arr = [];

$('[id^=event]', response).each(function(){
    arr.push($(this).html());
});

The [attr^=selector] selector matches elements on which the attr attribute starts with the given string, that way you don't care about the numbers after "event".

How do I create directory if it doesn't exist to create a file?

An elegant way to move your file to an nonexistent directory is to create the following extension to native FileInfo class:

public static class FileInfoExtension
{
    //second parameter is need to avoid collision with native MoveTo
    public static void MoveTo(this FileInfo file, string destination, bool autoCreateDirectory) { 

        if (autoCreateDirectory)
        {
            var destinationDirectory = new DirectoryInfo(Path.GetDirectoryName(destination));

            if (!destinationDirectory.Exists)
                destinationDirectory.Create();
        }

        file.MoveTo(destination);
    }
}

Then use brand new MoveTo extension:

 using <namespace of FileInfoExtension>;
 ...
 new FileInfo("some path")
     .MoveTo("target path",true);

Check Methods extension documentation.

Return empty cell from formula in Excel

If you are using lookup functions like HLOOKUP and VLOOKUP to bring the data into your worksheet place the function inside brackets and the function will return an empty cell instead of a {0}. For Example,

This will return a zero value if lookup cell is empty:

    =HLOOKUP("Lookup Value",Array,ROW,FALSE)

This will return an empty cell if lookup cell is empty:

    =(HLOOKUP("Lookup Value",Array,ROW,FALSE))

I don't know if this works with other functions...I haven't tried. I am using Excel 2007 to achieve this.

Edit

To actually get an IF(A1="", , ) to come back as true there needs to be two lookups in the same cell seperated by an &. The easy way around this is to make the second lookup a cell that is at the end of the row and will always be empty.

Detect end of ScrollView

I found a simple way to detect this :

   scrollView.getViewTreeObserver()
       .addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
            @Override
            public void onScrollChanged() {
                if (scrollView.getChildAt(0).getBottom()
                     <= (scrollView.getHeight() + scrollView.getScrollY())) {
                    //scroll view is at bottom
                } else {
                    //scroll view is not at bottom
                }
            }
        });
  • Doesn't need to custom ScrollView.
  • Scrollview can host only one direct child, so scrollView.getChildAt(0) is okay.
  • This solution is right even the height of direct child of scroll view is match_parent or wrap_content.

Disable submit button on form submit

Your code actually works on FF, it doesn't work on Chrome.

This works on FF and Chrome.

$(document).ready(function() {
        // Solution for disabling the submit temporarily for all the submit buttons.
        // Avoids double form submit.
        // Doing it directly on the submit click made the form not to submit in Chrome.
        // This works in FF and Chrome.
        $('form').on('submit', function(e){
          //console.log('submit2', e, $(this).find('[clicked=true]'));
          var submit = $(this).find('[clicked=true]')[0];
          if (!submit.hasAttribute('disabled'))
          {
            submit.setAttribute('disabled', true);
            setTimeout(function(){
              submit.removeAttribute('disabled');
            }, 1000);
          }
          submit.removeAttribute('clicked');
          e.preventDefault();
        });
        $('[type=submit]').on('click touchstart', function(){
          this.setAttribute('clicked', true);
        });
      });
    </script>

What is LD_LIBRARY_PATH and how to use it?

Well, the error message tells you what to do: add the path where Jacob.dll resides to java.library.path. You can do that on the command line like this:

java -Djava.library.path="dlls" ...

(assuming Jacob.dll is in the "dlls" folder)

Also see java.lang.UnsatisfiedLinkError no *****.dll in java.library.path

INNER JOIN ON vs WHERE clause

Applying conditional statements in ON / WHERE

Here I have explained the logical query processing steps.


Reference: Inside Microsoft® SQL Server™ 2005 T-SQL Querying
Publisher: Microsoft Press
Pub Date: March 07, 2006
Print ISBN-10: 0-7356-2313-9
Print ISBN-13: 978-0-7356-2313-2
Pages: 640

Inside Microsoft® SQL Server™ 2005 T-SQL Querying

(8)  SELECT (9) DISTINCT (11) TOP <top_specification> <select_list>
(1)  FROM <left_table>
(3)       <join_type> JOIN <right_table>
(2)       ON <join_condition>
(4)  WHERE <where_condition>
(5)  GROUP BY <group_by_list>
(6)  WITH {CUBE | ROLLUP}
(7)  HAVING <having_condition>
(10) ORDER BY <order_by_list>

The first noticeable aspect of SQL that is different than other programming languages is the order in which the code is processed. In most programming languages, the code is processed in the order in which it is written. In SQL, the first clause that is processed is the FROM clause, while the SELECT clause, which appears first, is processed almost last.

Each step generates a virtual table that is used as the input to the following step. These virtual tables are not available to the caller (client application or outer query). Only the table generated by the final step is returned to the caller. If a certain clause is not specified in a query, the corresponding step is simply skipped.

Brief Description of Logical Query Processing Phases

Don't worry too much if the description of the steps doesn't seem to make much sense for now. These are provided as a reference. Sections that come after the scenario example will cover the steps in much more detail.

  1. FROM: A Cartesian product (cross join) is performed between the first two tables in the FROM clause, and as a result, virtual table VT1 is generated.

  2. ON: The ON filter is applied to VT1. Only rows for which the <join_condition> is TRUE are inserted to VT2.

  3. OUTER (join): If an OUTER JOIN is specified (as opposed to a CROSS JOIN or an INNER JOIN), rows from the preserved table or tables for which a match was not found are added to the rows from VT2 as outer rows, generating VT3. If more than two tables appear in the FROM clause, steps 1 through 3 are applied repeatedly between the result of the last join and the next table in the FROM clause until all tables are processed.

  4. WHERE: The WHERE filter is applied to VT3. Only rows for which the <where_condition> is TRUE are inserted to VT4.

  5. GROUP BY: The rows from VT4 are arranged in groups based on the column list specified in the GROUP BY clause. VT5 is generated.

  6. CUBE | ROLLUP: Supergroups (groups of groups) are added to the rows from VT5, generating VT6.

  7. HAVING: The HAVING filter is applied to VT6. Only groups for which the <having_condition> is TRUE are inserted to VT7.

  8. SELECT: The SELECT list is processed, generating VT8.

  9. DISTINCT: Duplicate rows are removed from VT8. VT9 is generated.

  10. ORDER BY: The rows from VT9 are sorted according to the column list specified in the ORDER BY clause. A cursor is generated (VC10).

  11. TOP: The specified number or percentage of rows is selected from the beginning of VC10. Table VT11 is generated and returned to the caller.



Therefore, (INNER JOIN) ON will filter the data (the data count of VT will be reduced here itself) before applying the WHERE clause. The subsequent join conditions will be executed with filtered data which improves performance. After that, only the WHERE condition will apply filter conditions.

(Applying conditional statements in ON / WHERE will not make much difference in few cases. This depends on how many tables you have joined and the number of rows available in each join tables)

How do I tell Maven to use the latest version of a dependency?

The truth is even in 3.x it still works, surprisingly the projects builds and deploys. But the LATEST/RELEASE keyword causing problems in m2e and eclipse all over the place, ALSO projects depends on the dependency which deployed through the LATEST/RELEASE fail to recognize the version.

It will also causing problem if you are try to define the version as property, and reference it else where.

So the conclusion is use the versions-maven-plugin if you can.

Parse string to DateTime in C#

Put the value of a human-readable string into a .NET DateTime with code like this:

DateTime.ParseExact("April 16, 2011 4:27 pm", "MMMM d, yyyy h:mm tt", null);

Alternating Row Colors in Bootstrap 3 - No Table

You can use this code :

.row :nth-child(odd){
  background-color:red;
}
.row :nth-child(even){
  background-color:green;
}

Demo : http://codepen.io/mouhammed/pen/rblsC

Get all parameters from JSP page

<%@ page import = "java.util.Map" %>
Map<String, String[]> parameters = request.getParameterMap();
for(String parameter : parameters.keySet()) {
    if(parameter.toLowerCase().startsWith("question")) {
        String[] values = parameters.get(parameter);
        //your code here
    }
}

Excel SUMIF between dates

this works, and can be adapted for weeks or anyother frequency i.e. weekly, quarterly etc...

=SUMIFS(B12:B11652,A12:A11652,">="&DATE(YEAR(C12),MONTH(C12),1),A12:A11652,"<"&DATE(YEAR(C12),MONTH(C12)+1,1))

How to convert FileInputStream to InputStream?

If you wrap one stream into another, you don't close intermediate streams, and very important: You don't close them before finishing using the outer streams. Because you would close the outer stream too.

How to run a javascript function during a mouseover on a div

Here's a jQuery solution.

<script type="text/javascript" src="/path/to/your/copy/of/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $("#sub1").mouseover(function() {
        $("#welcome").toggle();
    });
});
</script>

Using this markup:

<div id="sub1">some text</div>
<div id="welcome" style="display:none;">Welcome message</div>

You didn't really specify if (or when) you wanted to hide the welcome message, but this would toggle hiding or showing each time you moused over the text.

Cannot create Maven Project in eclipse

If you're behind a proxy, the very first thing to do is, add settings.xml with proxy configs under C:\Users\{username}\.m2 folder, and replicate same proxy configs under Window > Preferences > Network Connections (you may need to prefix your user name with domain eg. DOMAIN\username):

<settings>
  <proxies>
   <proxy>
      <active>true</active>
      <protocol>http</protocol>
      <host>webproxy.net</host>
      <port>8080</port>
      <username>username</username>
      <password>password</password>
      <nonProxyHosts>localhost|127.0.0.1</nonProxyHosts>
    </proxy>
   <proxy>
      <active>true</active>
      <protocol>https</protocol>
      <host>webproxy.net</host>
      <port>8080</port>
      <username>username</username>
      <password>password</password>
      <nonProxyHosts>localhost|127.0.0.1</nonProxyHosts>
    </proxy>    
  </proxies>

Delete C:\Users\{username}\.m2\repository folder as well.

MySQL Workbench: How to keep the connection alive

In my case after trying to set the SSH timeout on the command line and in the local server settings. @Ljubitel solution solved the issue form me.

One point to note is that in Workbench 6.2 the setting is now under advanced

enter image description here

How to Handle Button Click Events in jQuery?

<script type="text/javascript">

    $(document).ready(function() {

    $("#Button1").click(function() {

        alert("hello");

    });

    }
    );

</script>

batch/bat to copy folder and content at once

I've been interested in the original question here and related ones.

For an answer, this week I did some experiments with XCOPY.

To help answer the original question, here I post the results of my experiments.

I did the experiments on Windows 7 64 bit Professional SP1 with the copy of XCOPY that came with the operating system.

For the experiments, I wrote some code in the scripting language Open Object Rexx and the editor macro language Kexx with the text editor KEdit.

XCOPY was called from the Rexx code. The Kexx code edited the screen output of XCOPY to focus on the crucial results.

The experiments all had to do with using XCOPY to copy one directory with several files and subdirectories.

The experiments consisted of 10 cases. Each case adjusted the arguments to XCOPY and called XCOPY once. All 10 cases were attempting to do the same copying operation.

Here are the main results:

(1) Of the 10 cases, only three did copying. The other 7 cases right away, just from processing the arguments to XCOPY, gave error messages, e.g.,

Invalid path

Access denied

with no files copied.

Of the three cases that did copying, they all did the same copying, that is, gave the same results.

(2) If want to copy a directory X and all the files and directories in directory X, in the hierarchical file system tree rooted at directory X, then apparently XCOPY -- and this appears to be much of the original question -- just will NOT do that.

One consequence is that if using XCOPY to copy directory X and its contents, then CAN copy the contents but CANNOT copy the directory X itself; thus, lose the time-date stamp on directory X, its archive bit, data on ownership, attributes, etc.

Of course if directory X is a subdirectory of directory Y, an XCOPY of Y will copy all of the contents of directory Y WITH directory X. So in this way can get a copy of directory X. However, the copy of directory X will have its time-date stamp of the time of the run of XCOPY and NOT the time-date stamp of the original directory X.

This change in time-date stamps can be awkward for a copy of a directory with a lot of downloaded Web pages: The HTML file of the Web page will have its original time-date stamp, but the corresponding subdirectory for files used by the HTML file will have the time-date stamp of the run of XCOPY. So, when sorting the copy on time date stamps, all the subdirectories, the HTML files and the corresponding subdirectories, e.g.,

x.htm

x_files

can appear far apart in the sort on time-date.

Hierarchical file systems go way back, IIRC to Multics at MIT in 1969, and since then lots of people have recognized the two cases, given a directory X, (i) copy directory X and all its contents and (ii) copy all the contents of X but not directory X itself. Well, if only from the experiments, XCOPY does only (ii).

So, the results of the 10 cases are below. For each case, in the results the first three lines have the first three arguments to XCOPY. So, the first line has the tree name of the directory to be copied, the 'source'; the second line has the tree name of the directory to get the copies, the 'destination', and the third line has the options for XCOPY. The remaining 1-2 lines have the results of the run of XCOPY.

One big point about the options is that options /X and /O result in result

Access denied

To see this, compare case 8 with the other cases that were the same, did not have /X and /O, but did copy.

These experiments have me better understand XCOPY and contribute an answer to the original question.

======= case 1 ==================
"k:\software\dir_time-date\"
"k:\software\xcopy002_test\xcopy002_test_dirs\output_sub_dir_1\"
options = /E /F /G /H /K /O /R /V /X /Y
Result:  Invalid path
Result:  0 File(s) copied
======= case 2 ==================
"k:\software\dir_time-date\*"
"k:\software\xcopy002_test\xcopy002_test_dirs\output_sub_dir_2\"
options = /E /F /G /H /K /O /R /V /X /Y
Result:  Access denied
Result:  0 File(s) copied
======= case 3 ==================
"k:\software\dir_time-date"
"k:\software\xcopy002_test\xcopy002_test_dirs\output_sub_dir_3\"
options = /E /F /G /H /K /O /R /V /X /Y
Result:  Access denied
Result:  0 File(s) copied
======= case 4 ==================
"k:\software\dir_time-date\"
"k:\software\xcopy002_test\xcopy002_test_dirs\output_sub_dir_4\"
options = /E /F /G /H /K /R /V /Y
Result:  Invalid path
Result:  0 File(s) copied
======= case 5 ==================
"k:\software\dir_time-date\"
"k:\software\xcopy002_test\xcopy002_test_dirs\output_sub_dir_5\"
options = /E /F /G /H /K /O /R /S /X /Y
Result:  Invalid path
Result:  0 File(s) copied
======= case 6 ==================
"k:\software\dir_time-date"
"k:\software\xcopy002_test\xcopy002_test_dirs\output_sub_dir_6\"
options = /E /F /G /H /I /K /O /R /S /X /Y
Result:  Access denied
Result:  0 File(s) copied
======= case 7 ==================
"k:\software\dir_time-date"
"k:\software\xcopy002_test\xcopy002_test_dirs\output_sub_dir_7"
options = /E /F /G /H /I /K /R /S /Y
Result:  20 File(s) copied
======= case 8 ==================
"k:\software\dir_time-date"
"k:\software\xcopy002_test\xcopy002_test_dirs\output_sub_dir_8"
options = /E /F /G /H /I /K /O /R /S /X /Y
Result:  Access denied
Result:  0 File(s) copied
======= case 9 ==================
"k:\software\dir_time-date"
"k:\software\xcopy002_test\xcopy002_test_dirs\output_sub_dir_9"
options = /I /S
Result:  20 File(s) copied
======= case 10 ==================
"k:\software\dir_time-date"
"k:\software\xcopy002_test\xcopy002_test_dirs\output_sub_dir_10"
options = /E /I /S
Result:  20 File(s) copied

Setting SMTP details for php mail () function

Try from your dedicated server to telnet to smtp.gmail.com on port 465. It might be blocked by your internet provider

What is the proper way to check and uncheck a checkbox in HTML5?

<form name="myForm" method="post">
  <p>Activity</p> 
  skiing:  <input type="checkbox" name="activity" value="skiing"  checked="yes" /><br /> 
  skating: <input type="checkbox" name="activity" value="skating" /><br /> 
  running: <input type="checkbox" name="activity" value="running" /><br /> 
  hiking:  <input type="checkbox" name="activity" value="hiking"  checked="yes" />
</form>

How to convert all tables from MyISAM into InnoDB?

A plain MySQL Version.

You can simply start mysql executable, use database and copy-paste the query.

This will convert all MyISAM tables in the current Database into INNODB tables.

DROP PROCEDURE IF EXISTS convertToInnodb;
DELIMITER //
CREATE PROCEDURE convertToInnodb()
BEGIN
mainloop: LOOP
  SELECT TABLE_NAME INTO @convertTable FROM information_schema.TABLES
  WHERE `TABLE_SCHEMA` LIKE DATABASE()
  AND `ENGINE` LIKE 'MyISAM' ORDER BY TABLE_NAME LIMIT 1;
  IF @convertTable IS NULL THEN 
    LEAVE mainloop;
  END IF;
  SET @sqltext := CONCAT('ALTER TABLE `', DATABASE(), '`.`', @convertTable, '` ENGINE = INNODB');
  PREPARE convertTables FROM @sqltext;
  EXECUTE convertTables;
  DEALLOCATE PREPARE convertTables;
  SET @convertTable = NULL;
END LOOP mainloop;

END//
DELIMITER ;

CALL convertToInnodb();
DROP PROCEDURE IF EXISTS convertToInnodb;

How to check if a specific key is present in a hash or not?

While Hash#has_key? gets the job done, as Matz notes here, it has been deprecated in favour of Hash#key?.

hash.key?(some_key)

Java: convert seconds to minutes, hours and days

You can use the Java enum TimeUnit to perform your math and avoid any hard coded values. Then we can use String.format(String, Object...) and a pair of StringBuilder(s) as well as a DecimalFormat to build the requested output. Something like,

Scanner scanner = new Scanner(System.in);
System.out.println("Please enter a number of seconds:");
String str = scanner.nextLine().replace("\\,", "").trim();
long secondsIn = Long.parseLong(str);
long dayCount = TimeUnit.SECONDS.toDays(secondsIn);
long secondsCount = secondsIn - TimeUnit.DAYS.toSeconds(dayCount);
long hourCount = TimeUnit.SECONDS.toHours(secondsCount);
secondsCount -= TimeUnit.HOURS.toSeconds(hourCount);
long minutesCount = TimeUnit.SECONDS.toMinutes(secondsCount);
secondsCount -= TimeUnit.MINUTES.toSeconds(minutesCount);
StringBuilder sb = new StringBuilder();
sb.append(String.format("%d %s, ", dayCount, (dayCount == 1) ? "day"
        : "days"));
StringBuilder sb2 = new StringBuilder();
sb2.append(sb.toString());
sb2.append(String.format("%02d:%02d:%02d %s", hourCount, minutesCount,
        secondsCount, (hourCount == 1) ? "hour" : "hours"));
sb.append(String.format("%d %s, ", hourCount, (hourCount == 1) ? "hour"
        : "hours"));
sb.append(String.format("%d %s and ", minutesCount,
        (minutesCount == 1) ? "minute" : "minutes"));
sb.append(String.format("%d %s.", secondsCount,
        (secondsCount == 1) ? "second" : "seconds"));
System.out.printf("You entered %s seconds, which is %s (%s)%n",
        new DecimalFormat("#,###").format(secondsIn), sb, sb2);

Which, when I enter 500000 outputs the requested (manual line break added for post) -

You entered 500,000 seconds, which is 5 days, 18 hours, 
53 minutes and 20 seconds. (5 days, 18:53:20 hours)

What Language is Used To Develop Using Unity

When you build for iPhone in Unity it does Ahead of Time (AOT) compilation of your mono assembly (written in C# or JavaScript) to native ARM code.

The authoring tool also creates a stub xcode project and references that compiled lib. You can add objective C code to this xcode project if there is native stuff you want to do that isn't exposed in Unity's environment yet (e.g. accessing the compass and/or gyroscope).

How to split a string into a list?

shlex has a .split() function. It differs from str.split() in that it does not preserve quotes and treats a quoted phrase as a single word:

>>> import shlex
>>> shlex.split("sudo echo 'foo && bar'")
['sudo', 'echo', 'foo && bar']

NB: it works well for Unix-like command line strings. It doesn't work for natural-language processing.

How to install older version of node.js on Windows?

You can use Nodist for this purpose. Download it from here.

Usage:

nodist                         List all installed node versions.
nodist list
nodist ls

nodist <version>               Use the specified node version globally (downloads the executable, if necessary).
nodist latest                  Use the latest available node version globally (downloads the executable, if necessary).

nodist add <version>           Download the specified node version.

More Nodist commands here

Refresh Part of Page (div)

Let's assume that you have 2 divs inside of your html file.

<div id="div1">some text</div>
<div id="div2">some other text</div>

The java program itself can't update the content of the html file because the html is related to the client, meanwhile java is related to the back-end.

You can, however, communicate between the server (the back-end) and the client.

What we're talking about is AJAX, which you achieve using JavaScript, I recommend using jQuery which is a common JavaScript library.

Let's assume you want to refresh the page every constant interval, then you can use the interval function to repeat the same action every x time.

setInterval(function()
{
    alert("hi");
}, 30000);

You could also do it like this:

setTimeout(foo, 30000);

Whereea foo is a function.

Instead of the alert("hi") you can perform the AJAX request, which sends a request to the server and receives some information (for example the new text) which you can use to load into the div.

A classic AJAX looks like this:

var fetch = true;
var url = 'someurl.java';
$.ajax(
{
    // Post the variable fetch to url.
    type : 'post',
    url : url,
    dataType : 'json', // expected returned data format.
    data : 
    {
        'fetch' : fetch // You might want to indicate what you're requesting.
    },
    success : function(data)
    {
        // This happens AFTER the backend has returned an JSON array (or other object type)
        var res1, res2;

        for(var i = 0; i < data.length; i++)
        {
            // Parse through the JSON array which was returned.
            // A proper error handling should be added here (check if
            // everything went successful or not)

            res1 = data[i].res1;
            res2 = data[i].res2;

            // Do something with the returned data
            $('#div1').html(res1);
        }
    },
    complete : function(data)
    {
        // do something, not critical.
    }
});

Wherea the backend is able to receive POST'ed data and is able to return a data object of information, for example (and very preferrable) JSON, there are many tutorials out there with how to do so, GSON from Google is something that I used a while back, you could take a look into it.

I'm not professional with Java POST receiving and JSON returning of that sort so I'm not going to give you an example with that but I hope this is a decent start.

Using Python's ftplib to get a directory listing, portably

I happen to be stuck with an FTP server (Rackspace Cloud Sites virtual server) that doesn't seem to support MLSD. Yet I need several fields of file information, such as size and timestamp, not just the filename, so I have to use the DIR command. On this server, the output of DIR looks very much like the OP's. In case it helps anyone, here's a little Python class that parses a line of such output to obtain the filename, size and timestamp.

import datetime

class FtpDir:
    def parse_dir_line(self, line):
        words = line.split()
        self.filename = words[8]
        self.size = int(words[4])
        t = words[7].split(':')
        ts = words[5] + '-' + words[6] + '-' + datetime.datetime.now().strftime('%Y') + ' ' + t[0] + ':' + t[1]
        self.timestamp = datetime.datetime.strptime(ts, '%b-%d-%Y %H:%M')

Not very portable, I know, but easy to extend or modify to deal with various different FTP servers.

Modifying local variable from inside lambda

As the used variables from outside the lamda have to be (implicitly) final, you have to use something like AtomicInteger or write your own data structure.

See https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html#accessing-local-variables.

In Maven how to exclude resources from the generated jar?

This calls exactly for the using the Maven JAR Plugin

For example, if you want to exclude everything under src/test/resources/ from the final jar, put this:

<build>

        <plugins>
            <!-- configure JAR build -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.3.1</version>
                <configuration>
                    <excludes>
                        <exclude>src/test/resources/**</exclude>
                    </excludes>
                </configuration>
            </plugin>

...

Files under src/test/resources/ will still be available on class-path, they just won't be in resulting JAR.

MongoDB: How to query for records where field is null or not set?

If the sent_at field is not there when its not set then:

db.emails.count({sent_at: {$exists: false}})

If its there and null, or not there at all:

db.emails.count({sent_at: null})

Refer here for querying and null

return error message with actionResult

Inside Controller Action you can access HttpContext.Response. There you can set the response status as in the following listing.

[HttpPost]
public ActionResult PostViaAjax()
{
    var body = Request.BinaryRead(Request.TotalBytes);

    var result = Content(JsonError(new Dictionary<string, string>()
    {
        {"err", "Some error!"}
    }), "application/json; charset=utf-8");
    HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
    return result;
}

How to connect html pages to mysql database?

HTML are markup languages, basically they are set of tags like <html>, <body>, which is used to present a website using , and as a whole. All these, happen in the clients system or the user you will be browsing the website.

Now, Connecting to a database, happens on whole another level. It happens on server, which is where the website is hosted.

So, in order to connect to the database and perform various data related actions, you have to use server-side scripts, like , , etc.

Now, lets see a snippet of connection using MYSQLi Extension of PHP

$db = mysqli_connect('hostname','username','password','databasename');

This single line code, is enough to get you started, you can mix such code, combined with HTML tags to create a HTML page, which is show data based pages. For example:

<?php
    $db = mysqli_connect('hostname','username','password','databasename');
?>
<html>
    <body>
          <?php
                $query = "SELECT * FROM `mytable`;";
                $result = mysqli_query($db, $query);
                while($row = mysqli_fetch_assoc($result)) {
                      // Display your datas on the page
                }
          ?>
    </body>
</html>

In order to insert new data into the database, you can use phpMyAdmin or write a INSERT query and execute them.

What is the "N+1 selects problem" in ORM (Object-Relational Mapping)?

N+1 SELECT problem is really hard to spot, especially in projects with large domain, to the moment when it starts degrading the performance. Even if the problem is fixed i.e. by adding eager loading, a further development may break the solution and/or introduce N+1 SELECT problem again in other places.

I've created open source library jplusone to address those problems in JPA based Spring Boot Java applications. The library provides two major features:

  1. Generates reports correlating SQL statements with executions of JPA operations which triggered them and places in source code of your application which were involved in it
2020-10-22 18:41:43.236 DEBUG 14913 --- [           main] c.a.j.core.report.ReportGenerator        :
    ROOT
        com.adgadev.jplusone.test.domain.bookshop.BookshopControllerTest.shouldGetBookDetailsLazily(BookshopControllerTest.java:65)
        com.adgadev.jplusone.test.domain.bookshop.BookshopController.getSampleBookUsingLazyLoading(BookshopController.java:31)
        com.adgadev.jplusone.test.domain.bookshop.BookshopService.getSampleBookDetailsUsingLazyLoading [PROXY]
            SESSION BOUNDARY
                OPERATION [IMPLICIT]
                    com.adgadev.jplusone.test.domain.bookshop.BookshopService.getSampleBookDetailsUsingLazyLoading(BookshopService.java:35)
                    com.adgadev.jplusone.test.domain.bookshop.Author.getName [PROXY]
                    com.adgadev.jplusone.test.domain.bookshop.Author [FETCHING ENTITY]
                        STATEMENT [READ]
                            select [...] from
                                author author0_
                                left outer join genre genre1_ on author0_.genre_id=genre1_.id
                            where
                                author0_.id=1
                OPERATION [IMPLICIT]
                    com.adgadev.jplusone.test.domain.bookshop.BookshopService.getSampleBookDetailsUsingLazyLoading(BookshopService.java:36)
                    com.adgadev.jplusone.test.domain.bookshop.Author.countWrittenBooks(Author.java:53)
                    com.adgadev.jplusone.test.domain.bookshop.Author.books [FETCHING COLLECTION]
                        STATEMENT [READ]
                            select [...] from
                                book books0_
                            where
                                books0_.author_id=1
  1. Provides API which allows to write tests checking how effectively your application is using JPA (i.e. assert amount of lazy loading operations )
@SpringBootTest
class LazyLoadingTest {

    @Autowired
    private JPlusOneAssertionContext assertionContext;

    @Autowired
    private SampleService sampleService;

    @Test
    public void shouldBusinessCheckOperationAgainstJPlusOneAssertionRule() {
        JPlusOneAssertionRule rule = JPlusOneAssertionRule
                .within().lastSession()
                .shouldBe().noImplicitOperations().exceptAnyOf(exclusions -> exclusions
                        .loadingEntity(Author.class).times(atMost(2))
                        .loadingCollection(Author.class, "books")
                );

        // trigger business operation which you wish to be asserted against the rule,
        // i.e. calling a service or sending request to your API controller
        sampleService.executeBusinessOperation();

        rule.check(assertionContext);
    }
}

How to grep, excluding some patterns?

Question: search for 'loom' excluding 'gloom'.
Answer:

grep -w 'loom' ~/projects/**/trunk/src/**/*.@(h|cpp)

What is lazy loading in Hibernate?

Well it simply means loading data you need currently instead of loading whole bunch of data at once which you won't use now. Thereby making application load time faster than usual.

How to calculate the IP range when the IP address and the netmask is given?

I'll just post the code:

IPAddress ip = new IPAddress(new byte[] { 192, 168, 0, 1 });
int bits = 25;

uint mask = ~(uint.MaxValue >> bits);

// Convert the IP address to bytes.
byte[] ipBytes = ip.GetAddressBytes();

// BitConverter gives bytes in opposite order to GetAddressBytes().
byte[] maskBytes = BitConverter.GetBytes(mask).Reverse().ToArray();

byte[] startIPBytes = new byte[ipBytes.Length];
byte[] endIPBytes = new byte[ipBytes.Length];

// Calculate the bytes of the start and end IP addresses.
for (int i = 0; i < ipBytes.Length; i++)
{
    startIPBytes[i] = (byte)(ipBytes[i] & maskBytes[i]);
    endIPBytes[i] = (byte)(ipBytes[i] | ~maskBytes[i]);
}

// Convert the bytes to IP addresses.
IPAddress startIP = new IPAddress(startIPBytes);
IPAddress endIP = new IPAddress(endIPBytes);

How to add a primary key to a MySQL table?

After adding the column, you can always add the primary key:

ALTER TABLE goods ADD PRIMARY KEY(id)

As to why your script wasn't working, you need to specify PRIMARY KEY, not just the word PRIMARY:

alter table goods add column `id` int(10) unsigned primary KEY AUTO_INCREMENT;

Remove a specific character using awk or sed

Using just awk you could do (I also shortened some of your piping):

strings -a libAddressDoctor5.so | awk '/EngineVersion/ { if(NR==2) { gsub("\"",""); print $2 } }'

I can't verify it for you because I don't know your exact input, but the following works:

echo "Blah EngineVersion=\"123\"" | awk '/EngineVersion/ { gsub("\"",""); print $2 }'

See also this question on removing single quotes.

Capture Video of Android's Screen

If you are on a PC then you can run My Phone Explorer on the PC, the MyPhoneExplorer Client on the phone, set the screen capture to refresh continuously, and use Wink to capture a custom rectangular area of your screen over the My Phone Explorer window with your own capture rate. Then convert to a FLV in Wink, then convert from Flash video to MPG with WinFF.

How to set the custom border color of UIView programmatically?

Write the code in your viewDidLoad()

self.view.layer.borderColor = anyColor().CGColor

And you can set Color with RGB

func anyColor() -> UIColor {
    return UIColor(red: 0.0/255.0, green: 0.0/255.0, blue: 0.0/255.0, alpha: 1.0)
}

Learn something about CALayer in UIKit

How do I get the current Date/time in DD/MM/YYYY HH:MM format?

The formatting can be done like this (I assumed you meant HH:MM instead of HH:SS, but it's easy to change):

Time.now.strftime("%d/%m/%Y %H:%M")
#=> "14/09/2011 14:09"

Updated for the shifting:

d = DateTime.now
d.strftime("%d/%m/%Y %H:%M")
#=> "11/06/2017 18:11"
d.next_month.strftime("%d/%m/%Y %H:%M")
#=> "11/07/2017 18:11"

You need to require 'date' for this btw.

Getting absolute URLs using ASP.NET Core

After RC2 and 1.0 you no longer need to inject an IHttpContextAccessor to you extension class. It is immediately available in the IUrlHelper through the urlhelper.ActionContext.HttpContext.Request. You would then create an extension class following the same idea, but simpler since there will be no injection involved.

public static string AbsoluteAction(
    this IUrlHelper url,
    string actionName, 
    string controllerName, 
    object routeValues = null)
{
    string scheme = url.ActionContext.HttpContext.Request.Scheme;
    return url.Action(actionName, controllerName, routeValues, scheme);
}

Leaving the details on how to build it injecting the accesor in case they are useful to someone. You might also just be interested in the absolute url of the current request, in which case take a look at the end of the answer.


You could modify your extension class to use the IHttpContextAccessor interface to get the HttpContext. Once you have the context, then you can get the HttpRequest instance from HttpContext.Request and use its properties Scheme, Host, Protocol etc as in:

string scheme = HttpContextAccessor.HttpContext.Request.Scheme;

For example, you could require your class to be configured with an HttpContextAccessor:

public static class UrlHelperExtensions
{        
    private static IHttpContextAccessor HttpContextAccessor;
    public static void Configure(IHttpContextAccessor httpContextAccessor)
    {           
        HttpContextAccessor = httpContextAccessor;  
    }

    public static string AbsoluteAction(
        this IUrlHelper url,
        string actionName, 
        string controllerName, 
        object routeValues = null)
    {
        string scheme = HttpContextAccessor.HttpContext.Request.Scheme;
        return url.Action(actionName, controllerName, routeValues, scheme);
    }

    ....
}

Which is something you can do on your Startup class (Startup.cs file):

public void Configure(IApplicationBuilder app)
{
    ...

    var httpContextAccessor = app.ApplicationServices.GetRequiredService<IHttpContextAccessor>();
    UrlHelperExtensions.Configure(httpContextAccessor);

    ...
}

You could probably come up with different ways of getting the IHttpContextAccessor in your extension class, but if you want to keep your methods as extension methods in the end you will need to inject the IHttpContextAccessor into your static class. (Otherwise you will need the IHttpContext as an argument on each call)


Just getting the absoluteUri of the current request

If you just want to get the absolute uri of the current request, you can use the extension methods GetDisplayUrl or GetEncodedUrl from the UriHelper class. (Which is different from the UrLHelper)

GetDisplayUrl. Returns the combined components of the request URL in a fully un-escaped form (except for the QueryString) suitable only for display. This format should not be used in HTTP headers or other HTTP operations.

GetEncodedUrl. Returns the combined components of the request URL in a fully escaped form suitable for use in HTTP headers and other HTTP operations.

In order to use them:

  • Include the namespace Microsoft.AspNet.Http.Extensions.
  • Get the HttpContext instance. It is already available in some classes (like razor views), but in others you might need to inject an IHttpContextAccessor as explained above.
  • Then just use them as in this.Context.Request.GetDisplayUrl()

An alternative to those methods would be manually crafting yourself the absolute uri using the values in the HttpContext.Request object (Similar to what the RequireHttpsAttribute does):

var absoluteUri = string.Concat(
                        request.Scheme,
                        "://",
                        request.Host.ToUriComponent(),
                        request.PathBase.ToUriComponent(),
                        request.Path.ToUriComponent(),
                        request.QueryString.ToUriComponent());

What's the difference between getPath(), getAbsolutePath(), and getCanonicalPath() in Java?

Consider these filenames:

C:\temp\file.txt - This is a path, an absolute path, and a canonical path.

.\file.txt - This is a path. It's neither an absolute path nor a canonical path.

C:\temp\myapp\bin\..\\..\file.txt - This is a path and an absolute path. It's not a canonical path.

A canonical path is always an absolute path.

Converting from a path to a canonical path makes it absolute (usually tack on the current working directory so e.g. ./file.txt becomes c:/temp/file.txt). The canonical path of a file just "purifies" the path, removing and resolving stuff like ..\ and resolving symlinks (on unixes).

Also note the following example with nio.Paths:

String canonical_path_string = "C:\\Windows\\System32\\";
String absolute_path_string = "C:\\Windows\\System32\\drivers\\..\\";

System.out.println(Paths.get(canonical_path_string).getParent());
System.out.println(Paths.get(absolute_path_string).getParent());

While both paths refer to the same location, the output will be quite different:

C:\Windows
C:\Windows\System32\drivers

Is there a 'box-shadow-color' property?

Maybe this is new (I am also pretty crap at css3), but I have a page that uses exactly what you suggest:

-moz-box-shadow: 10px 10px 5px #384e69;
-webkit-box-shadow: 10px 10px 5px #384e69;
box-shadow: 10px 10px 5px #384e69;}

.. and it works fine for me (in Chrome at least).

Drag and drop elements from list into separate blocks

I wrote some test code to check JQueryUI drag/drop. The example shows how to drag an element from a container and drop it to another container.

Markup-

<div class="row">
    <div class="col-xs-3">
      <div class="panel panel-default">
        <div class="panel-heading">
          <h1 class="panel-title">Panel 1</h1>
        </div>
        <div id="container1" class="panel-body box-container">
          <div itemid="itm-1" class="btn btn-default box-item">Item 1</div>
          <div itemid="itm-2" class="btn btn-default box-item">Item 2</div>
          <div itemid="itm-3" class="btn btn-default box-item">Item 3</div>
          <div itemid="itm-4" class="btn btn-default box-item">Item 4</div>
          <div itemid="itm-5" class="btn btn-default box-item">Item 5</div>
        </div>
      </div>
    </div>
    <div class="col-xs-3">
      <div class="panel panel-default">
        <div class="panel-heading">
          <h1 class="panel-title">Panel 2</h1>
        </div>
        <div id="container2" class="panel-body box-container"></div>
      </div>
    </div>
  </div>

JQuery codes-

$(document).ready(function() {

$('.box-item').draggable({
    cursor: 'move',
    helper: "clone"
});

$("#container1").droppable({
  drop: function(event, ui) {
    var itemid = $(event.originalEvent.toElement).attr("itemid");
    $('.box-item').each(function() {
      if ($(this).attr("itemid") === itemid) {
        $(this).appendTo("#container1");
      }
    });
  }
});

$("#container2").droppable({
  drop: function(event, ui) {
    var itemid = $(event.originalEvent.toElement).attr("itemid");
    $('.box-item').each(function() {
      if ($(this).attr("itemid") === itemid) {
        $(this).appendTo("#container2");
      }
    });
  }
});

});

CSS-

.box-container {
    height: 200px;
}

.box-item {
    width: 100%;
    z-index: 1000
}

Check the plunker JQuery Drag Drop

Inversion of Control vs Dependency Injection

I found best example on Dzone.com which is really helpfull to understand the real different between IOC and DI

“IoC is when you have someone else create objects for you.” So instead of writing "new " keyword (For example, MyCode c=new MyCode())in your code, the object is created by someone else. This ‘someone else’ is normally referred to as an IoC container. It means we handover the rrsponsibility (control )to the container to get instance of object is called Inversion of Control., means instead of you are creating object using new operator, let the container do that for you.

   DI(Dependency Injection):  Way of injecting properties to an object is 
   called 
  Dependency injection.
   We have three types of Dependency injection
    1)  Constructor Injection
    2)  Setter/Getter Injection
    3)  Interface Injection
   Spring will support only Constructor Injection and Setter/Getter Injection.

Read full article IOC and Read Full article DI

MatPlotLib: Multiple datasets on the same scatter plot

I don't know, it works fine for me. Exact commands:

import scipy, pylab
ax = pylab.subplot(111)
ax.scatter(scipy.randn(100), scipy.randn(100), c='b')
ax.scatter(scipy.randn(100), scipy.randn(100), c='r')
ax.figure.show()

String Array object in Java

First off, the arrays are pointless, let's get rid of them: all they are doing is providing values for mock data. How you construct mock objects has been debated ad nauseum, but clearly, the code to create the fake Athletes should be inside of a unit test. I would use Joshua Bloch's static builder for the Athlete class, but you only have two attributes right now, so just pass those in a Constructor. Would look like this:

class Athlete {

    private String name;
    private String country;

    private List<Dive> dives;

    public Athlete(String name, String country){
       this.name = name;
       this.country = country;
    }

    public String getName(){
        return this.name;
    }

    public String getCountry(){
        return this.country;
    }

    public String getDives(){
        return this.dives;
    }

    public void addDive(Dive dive){
        this.dives.add(dive);
    }
}

Then for the Dive class:

class Dive {

    private Athlete athlete;
    private Date date;
    private double score;

    public Dive(Athlete athlete, double score){
        this.athlete = athlete;
        this.score = score;
        this.date = new Date();
    }

    public Athlete getAthlete(){
        return this.athlete;
    }

    public Athlete getAthlete(){
        return this.athlete;
    }

    public Athlete getAthlete(){
        return this.athlete;
    }

}

Then make a unit test and just construct the classes, and manipulate them, make sure that they are working. Right now they don't do anything so all you could do is assert that they are retaining the Dives that you are putting in them. Example:

@Test
public void testThatDivesRetainInformation(){
    Athlete art = new Athlete("Art", "Canada");
    Dive art1 = new Dive(art, 8.5);
    Dive art2 = new Dive(art, 8.0);
    Dive art3 = new Dive(art, 8.8);
    Dive art4 = new Dive(art, 9.2);

    assertThat(art.getDives().size(), is(5));
    }

Then you could go through and add tests for things like, making sure that you can't construct a dive without an athlete, etc.

You could move construction of the athletes into the setup method of the test so you could use it all over the place. Most IDEs have support for doing that with a refactoring.

How do I ignore all files in a folder with a Git repository in Sourcetree?

After beating my head on this for at least an hour, I offer this answer to try to expand on the comments some others have made. To ignore a folder/directory, do the following: if you don't have a .gitignore file in the root of your project (that name exactly ".gitignore"), create a dummy text file in the folder you want to exclude. Inside of Source Tree, right click on it and select Ignore. You'll get a popup that looks like this.

enter image description here

Select "Everything underneath" and select the folder you want to ignore from the drop-down list. This will create a .gitignore file in your root directory and put the folder specification in it.

If you do have a .gitignore folder already in your root folder, you could follow the same approach above, or you can just edit the .gitignore file and add the folder you want to exclude. It's just a text file. Note that it uses forward slashes in path names rather than backslashes, as we Windows users are accustomed to. I tried creating a .gitignore text file by hand in Windows Explorer, but it didn't let me create a file without a name (i.e. with only the extension).

Note that adding the .gitignore and the file specification will have no effect on files that are already being tracked. If you're already tracking these, you'll have to stop tracking them. (Right-click on the folder or file and select Stop Tracking.) You'll then see them change from having a green/clean or amber/changed icon to a red/removed icon. On your next commit the files will be removed from the repository and thereafter appear with a blue/ignored icon. Another contributor asked why Ignore was disabled for particular files and I believe it was because he was trying to ignore a file that was already being tracked. You can only ignore a file that has a blue question mark icon.

How to set up subdomains on IIS 7

If your computer can't find the IP address associated with SUBDOMAIN1.example.COM, it will not find the site.

You need to either change your hosts file (so you can at least test things - this will be a local change, only available to yourself), or update DNS so the name will resolve correctly (so the rest of the world can see it).

How do you save/store objects in SharedPreferences on Android?

You can use gson.jar to store class objects into SharedPreferences. You can download this jar from google-gson

Or add the GSON dependency in your Gradle file:

implementation 'com.google.code.gson:gson:2.8.5'

Creating a shared preference:

SharedPreferences  mPrefs = getPreferences(MODE_PRIVATE);

To save:

MyObject myObject = new MyObject;
//set variables of 'myObject', etc.

Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(myObject);
prefsEditor.putString("MyObject", json);
prefsEditor.commit();

To retrieve:

Gson gson = new Gson();
String json = mPrefs.getString("MyObject", "");
MyObject obj = gson.fromJson(json, MyObject.class);

json_encode(): Invalid UTF-8 sequence in argument

json_encode works only with UTF-8 data. You'll have to ensure that your data is in UTF-8. alternatively, you can use iconv() to convert your results to UTF-8 before feeding them to json_encode()

What programming language does facebook use?

Since nobody has mentioned it, I'd like to add that Facebook chat is written in Erlang.

Where is the user's Subversion config file stored on the major operating systems?

In windows 7, 8, and 10 you can find at the following location

C:\Users\<user>\AppData\Roaming\Subversion

If you enter the following in the Windows Explorer address bar, it will take you right there.

%appdata%\Subversion

Creating a .p12 file

The openssl documentation says that file supplied as the -in argument must be in PEM format.

Turns out that, contrary to the CA's manual, the certificate returned by the CA which I stored in myCert.cer is not PEM format rather it is PKCS7.

In order to create my .p12, I had to first convert the certificate to PEM:

openssl pkcs7 -in myCert.cer -print_certs -out certs.pem

and then execute

openssl pkcs12 -export -out keyStore.p12 -inkey myKey.pem -in certs.pem

Plot inline or a separate window using Matplotlib in Spyder IDE

type

%matplotlib qt

when you want graphs in a separate window and

%matplotlib inline

when you want an inline plot

How to set Grid row and column positions programmatically

Try this:

                Grid grid = new Grid(); //Define the grid
                for (int i = 0; i < 36; i++) //Add 36 rows
                {
                    ColumnDefinition columna = new ColumnDefinition()
                    {
                        Name = "Col_" + i,
                        Width = new GridLength(32.5),
                    };
                    grid.ColumnDefinitions.Add(columna);
                }

                for (int i = 0; i < 36; i++) //Add 36 columns
                {
                    RowDefinition row = new RowDefinition();
                    row.Height = new GridLength(40, GridUnitType.Pixel);
                    grid.RowDefinitions.Add(row);
                }

                for (int i = 0; i < 36; i++)
                {
                    for (int j = 0; j < 36; j++)
                    {
                        Label t1 = new Label()
                        {
                            FontSize = 10,
                            FontFamily = new FontFamily("consolas"),
                            FontWeight = FontWeights.SemiBold,
                            BorderBrush = Brushes.LightGray,
                            BorderThickness = new Thickness(2),
                            HorizontalContentAlignment = HorizontalAlignment.Center,
                            VerticalContentAlignment = VerticalAlignment.Center,
                        };
                        Grid.SetRow(t1, i);
                        Grid.SetColumn(t1, j);
                        grid.Children.Add(t1); //Add the Label Control to the Grid created
                    }
                }

How to change the port number for Asp.Net core app?

Yes this will be accesible from other machines if you bind on any external IP address. For example binding to http://*:80 . Note that binding to http://localhost:80 will only bind on 127.0.0.1 interface and therefore will not be accesible from other machines.

Visual Studio is overriding your port. You can change VS port editing this file Properties\launchSettings.json or else set it by code:

        var host = new WebHostBuilder()
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup<Startup>()
            .UseUrls("http://*:80") // <-----
            .Build();

        host.Run();

A step by step guide using an external config file is available here.

How do you decrease navbar height in Bootstrap 3?

Simply change the default 50px navbar-height by including this to your variable overrides.

You can find this default navbar-height on line 365 and 360 on bootstrap's SASS and LESS variables files respectively.

File location, SASS: bootstrap/assets/stylesheets/bootstrap/_variables.scss

File location, LESS: bootstrap/less/variable.less

How to show git log history (i.e., all the related commits) for a sub directory of a git repo?

You can use git log with the pathnames of the respective folders:

git log A B

The log will only show commits made in A and B. I usually throw in --stat to make things a little prettier, which helps for quick commit reviews.

SQL Server 2005 Using DateAdd to add a day to a date

Use the following function:

DATEADD(type, value, date)
  • date is the date you want to manipulate

  • value is the integere value you want to add (or subtract if you provide a negative number)

  • type is one of:

    • yy, yyyy: year
    • qq, q: quarter
    • mm, m: month
    • dy, y: day of year
    • dd, d: day
    • wk, ww: week
    • dw, w: weekday
    • hh: hour
    • mi, n: minute
    • ss or s: second
    • ms: millisecond
    • mcs: microsecond
    • ns: nanosecond

SELECT DATEADD(dd, 1, GETDATE()) will return a current date + 1 day

http://msdn.microsoft.com/en-us/library/ms186819.aspx

Why is it said that "HTTP is a stateless protocol"?

What is stateless??

Once the request is made and the response is rendered back to the client the connection will be dropped or terminated. The server will forget all about the requester.

Why stateless??

The web chooses to go for the stateless protocol. It was a genius choice because the original goal of the web was to allow documents(web pages) to be served to extremely large no. of people using very basic hardware for the server.

Maintaining a long-running connection would have been extremely resource-intensive.

If the web were chosen the stateful protocol then the load on the server would have been increased to maintain the visitor's connection.

.NET / C# - Convert char[] to string

Another alternative

char[] c = { 'R', 'o', 'c', 'k', '-', '&', '-', 'R', 'o', 'l', 'l' };
string s = String.Concat( c );

Debug.Assert( s.Equals( "Rock-&-Roll" ) );

JavaScript module pattern with example

Here https://toddmotto.com/mastering-the-module-pattern you can find the pattern thoroughly explained. I would add that the second thing about modular JavaScript is how to structure your code in multiple files. Many folks may advice you here to go with AMD, yet I can say from experience that you will end up on some point with slow page response because of numerous HTTP requests. The way out is pre-compilation of your JavaScript modules (one per file) into a single file following CommonJS standard. Take a look at samples here http://dsheiko.github.io/cjsc/

jQuery selector to get form by name

You have no combinator (space, >, +...) so no children will get involved, ever.

However, you could avoid the need for jQuery by using an ID and getElementById, or you could use the old getElementsByName("frmSave")[0] or the even older document.forms['frmSave']. jQuery is unnecessary here.

AngularJS Dropdown required validation

You need to add a name attribute to your dropdown list, then you need to add a required attribute, and then you can reference the error using myForm.[input name].$error.required:

HTML:

        <form name="myForm" ng-controller="Ctrl" ng-submit="save(myForm)" novalidate>
        <input type="text" name="txtServiceName" ng-model="ServiceName" required>
<span ng-show="myForm.txtServiceName.$error.required">Enter Service Name</span>
<br/>
          <select name="service_id" class="Sitedropdown" style="width: 220px;"          
                  ng-model="ServiceID" 
                  ng-options="service.ServiceID as service.ServiceName for service in services"
                  required> 
            <option value="">Select Service</option> 
          </select> 
          <span ng-show="myForm.service_id.$error.required">Select service</span>

        </form>

    Controller:

        function Ctrl($scope) {
          $scope.services = [
            {ServiceID: 1, ServiceName: 'Service1'},
            {ServiceID: 2, ServiceName: 'Service2'},
            {ServiceID: 3, ServiceName: 'Service3'}
          ];

    $scope.save = function(myForm) {
    console.log('Selected Value: '+ myForm.service_id.$modelValue);
    alert('Data Saved! without validate');
    };
        }

Here's a working plunker.

AttributeError: 'str' object has no attribute 'strftime'

you should change cr_date(str) to datetime object then you 'll change the date to the specific format:

cr_date = '2013-10-31 18:23:29.000227'
cr_date = datetime.datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f')
cr_date = cr_date.strftime("%m/%d/%Y")

How do I merge dictionaries together in Python?

Trey Hunner has a nice blog post outlining several options for merging multiple dictionaries, including (for python3.3+) ChainMap and dictionary unpacking.

How do I write a Windows batch script to copy the newest file from a directory?

I know you asked for Windows but thought I'd add this anyway,in Unix/Linux you could do:

cp `ls -t1 | head -1` /somedir/

Which will list all files in the current directory sorted by modification time and then cp the most recent to /somedir/

Download a working local copy of a webpage

wget is capable of doing what you are asking. Just try the following:

wget -p -k http://www.example.com/

The -p will get you all the required elements to view the site correctly (css, images, etc). The -k will change all links (to include those for CSS & images) to allow you to view the page offline as it appeared online.

From the Wget docs:

‘-k’
‘--convert-links’
After the download is complete, convert the links in the document to make them
suitable for local viewing. This affects not only the visible hyperlinks, but
any part of the document that links to external content, such as embedded images,
links to style sheets, hyperlinks to non-html content, etc.

Each link will be changed in one of the two ways:

    The links to files that have been downloaded by Wget will be changed to refer
    to the file they point to as a relative link.

    Example: if the downloaded file /foo/doc.html links to /bar/img.gif, also
    downloaded, then the link in doc.html will be modified to point to
    ‘../bar/img.gif’. This kind of transformation works reliably for arbitrary
    combinations of directories.

    The links to files that have not been downloaded by Wget will be changed to
    include host name and absolute path of the location they point to.

    Example: if the downloaded file /foo/doc.html links to /bar/img.gif (or to
    ../bar/img.gif), then the link in doc.html will be modified to point to
    http://hostname/bar/img.gif. 

Because of this, local browsing works reliably: if a linked file was downloaded,
the link will refer to its local name; if it was not downloaded, the link will
refer to its full Internet address rather than presenting a broken link. The fact
that the former links are converted to relative links ensures that you can move
the downloaded hierarchy to another directory.

Note that only at the end of the download can Wget know which links have been
downloaded. Because of that, the work done by ‘-k’ will be performed at the end
of all the downloads. 

C++ correct way to return pointer to array from function

A variable referencing an array is basically a pointer to its first element, so yes, you can legitimately return a pointer to an array, because thery're essentially the same thing. Check this out yourself:

#include <assert.h>

int main() {
  int a[] = {1, 2, 3, 4, 5}; 

  int* pArr = a;
  int* pFirstElem = &(a[0]);

  assert(a == pArr);
  assert(a == pFirstElem);

  return 0;
}

This also means that passing an array to a function should be done via pointer (and not via int in[5]), and possibly along with the length of the array:

int* test(int* in, int len) {
    int* out = in;
    return out;
}

That said, you're right that using pointers (without fully understanding them) is pretty dangerous. For example, referencing an array that was allocated on the stack and went out of scope yields undefined behavior:

#include <iostream>

using namespace std;

int main() {
  int* pArr = 0;
  {
    int a[] = {1, 2, 3, 4, 5};
    pArr = a; // or test(a) if you wish
  }
  // a[] went out of scope here, but pArr holds a pointer to it

  // all bets are off, this can output "1", output 1st chapter
  // of "Romeo and Juliet", crash the program or destroy the
  // universe
  cout << pArr[0] << endl; // WRONG!

  return 0;
}

So if you don't feel competent enough, just use std::vector.

[answer to the updated question]

The correct way to write your test function is either this:

void test(int* a, int* b, int* c, int len) {
  for (int i = 0; i < len; ++i) c[i] = a[i] + b[i];
}
...
int main() {
   int a[5] = {...}, b[5] = {...}, c[5] = {};
   test(a, b, c, 5);
   // c now holds the result
}

Or this (using std::vector):

#include <vector>

vector<int> test(const vector<int>& a, const vector<int>& b) {
  vector<int> result(a.size());
  for (int i = 0; i < a.size(); ++i) {
    result[i] = a[i] + b[i];
  }
  return result; // copy will be elided
}

Declare a const array

This is the only correct answer. You cannot currently do this.

All the other answers are suggesting using static read-only variables which are similar to, but not the same as a constant. A constant is hard coded into the assembly. A static read only variable is settable once, probably as an object is is initialized.

These are sometimes interchangeable, but not always.

PDF Blob - Pop up window not showing content

I use AngularJS v1.3.4

HTML:

<button ng-click="downloadPdf()" class="btn btn-primary">download PDF</button>

JS controller:

'use strict';
angular.module('xxxxxxxxApp')
    .controller('MathController', function ($scope, MathServicePDF) {
        $scope.downloadPdf = function () {
            var fileName = "test.pdf";
            var a = document.createElement("a");
            document.body.appendChild(a);
            MathServicePDF.downloadPdf().then(function (result) {
                var file = new Blob([result.data], {type: 'application/pdf'});
                var fileURL = window.URL.createObjectURL(file);
                a.href = fileURL;
                a.download = fileName;
                a.click();
            });
        };
});

JS services:

angular.module('xxxxxxxxApp')
    .factory('MathServicePDF', function ($http) {
        return {
            downloadPdf: function () {
            return $http.get('api/downloadPDF', { responseType: 'arraybuffer' }).then(function (response) {
                return response;
            });
        }
    };
});

Java REST Web Services - Spring MVC:

@RequestMapping(value = "/downloadPDF", method = RequestMethod.GET, produces = "application/pdf")
    public ResponseEntity<byte[]> getPDF() {
        FileInputStream fileStream;
        try {
            fileStream = new FileInputStream(new File("C:\\xxxxx\\xxxxxx\\test.pdf"));
            byte[] contents = IOUtils.toByteArray(fileStream);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.parseMediaType("application/pdf"));
            String filename = "test.pdf";
            headers.setContentDispositionFormData(filename, filename);
            ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(contents, headers, HttpStatus.OK);
            return response;
        } catch (FileNotFoundException e) {
           System.err.println(e);
        } catch (IOException e) {
            System.err.println(e);
        }
        return null;
    }

A method to count occurrences in a list

var wordCount =
    from word in words
    group word by word into g
    select new { g.Key, Count = g.Count() };    

This is taken from one of the examples in the linqpad

Delete files older than 3 months old in a directory using .NET

Alternatively, you can use the File.GetCreationTime Method if you need to delete files based on creation dates.

check if variable is dataframe

Use the built-in isinstance() function.

import pandas as pd

def f(var):
    if isinstance(var, pd.DataFrame):
        print("do stuff")

ASP.NET MVC: Custom Validation by DataAnnotation

A bit late to answer, but for who is searching. You can easily do this by using an extra property with the data annotation:

public string foo { get; set; }
public string bar { get; set; }

[MinLength(20, ErrorMessage = "too short")]
public string foobar 
{ 
    get
    {
        return foo + bar;
    }
}

That's all that is too it really. If you really want to display in a specific place the validation error as well, you can add this in your view:

@Html.ValidationMessage("foobar", "your combined text is too short")

doing this in the view can come in handy if you want to do localization.

Hope this helps!

How do I find all the files that were created today in Unix/Linux?

You can use find and ls to accomplish with this:

find . -type f -exec ls -l {} \; |  egrep "Aug 26";

It will find all files in this directory, display useful informations (-l) and filter the lines with some date you want... It may be a little bit slow, but still useful in some cases.

Is there a limit to the length of a GET request?

setFixedLengthStreamingMode(int) with contentLength parameters could set the fixed length of a HTTP request body.

Swift: Reload a View Controller

Whatever code you are writing in viewDidLoad, Add that in viewWillappear(). This will solve your problem.

C# DateTime to UTC Time without changing the time

Use the DateTime.ToUniversalTime method.

combining results of two select statements

While it is possible to combine the results, I would advise against doing so.

You have two fundamentally different types of queries that return a different number of rows, a different number of columns and different types of data. It would be best to leave it as it is - two separate queries.

What is SOA "in plain english"?

Have a listen to this week's edition of the Floss Weekly podcast, which covers SOA. The descriptions are pretty high level and don't delve into too many technical details (although more concrete and recognizable examples of SOA projects would have been helpful.

git diff file against its last change

This does exist, but it's actually a feature of git log:

git log -p [--follow] [-1] <path>

Note that -p can also be used to show the inline diff from a single commit:

git log -p -1 <commit>

Options used:

  • -p (also -u or --patch) is hidden deeeeeeeep in the git-log man page, and is actually a display option for git-diff. When used with log, it shows the patch that would be generated for each commit, along with the commit information—and hides commits that do not touch the specified <path>. (This behavior is described in the paragraph on --full-diff, which causes the full diff of each commit to be shown.)
  • -1 shows just the most recent change to the specified file (-n 1 can be used instead of -1); otherwise, all non-zero diffs of that file are shown.
  • --follow is required to see changes that occurred prior to a rename.

As far as I can tell, this is the only way to immediately see the last set of changes made to a file without using git log (or similar) to either count the number of intervening revisions or determine the hash of the commit.

To see older revisions changes, just scroll through the log, or specify a commit or tag from which to start the log. (Of course, specifying a commit or tag returns you to the original problem of figuring out what the correct commit or tag is.)

Credit where credit is due:

  • I discovered log -p thanks to this answer.
  • Credit to FranciscoPuga and this answer for showing me the --follow option.
  • Credit to ChrisBetti for mentioning the -n 1 option and atatko for mentioning the -1 variant.
  • Credit to sweaver2112 for getting me to actually read the documentation and figure out what -p "means" semantically.

event Action<> vs event EventHandler<>

Based on some of the previous answers, I'm going to break my answer down into three areas.

First, physical limitations of using Action<T1, T2, T2... > vs using a derived class of EventArgs. There are three: First, if you change the number or types of parameters, every method that subscribes to will have to be changed to conform to the new pattern. If this is a public facing event that 3rd party assemblies will be using, and there is any possiblity that the event args would change, this would be a reason to use a custom class derived from event args for consistencies sake (remember, you COULD still use an Action<MyCustomClass>) Second, using Action<T1, T2, T2... > will prevent you from passing feedback BACK to the calling method unless you have a some kind of object (with a Handled property for instance) that is passed along with the Action. Third, you don't get named parameters, so if you're passing 3 bool's an int, two string's, and a DateTime, you have no idea what the meaning of those values are. As a side note, you can still have a "Fire this event safely method while still using Action<T1, T2, T2... >".

Secondly, consistency implications. If you have a large system you're already working with, it's nearly always better to follow the way the rest of the system is designed unless you have an very good reason not too. If you have publicly facing events that need to be maintained, the ability to substitute derived classes can be important. Keep that in mind.

Thirdly, real life practice, I personally find that I tend to create a lot of one off events for things like property changes that I need to interact with (Particularly when doing MVVM with view models that interact with each other) or where the event has a single parameter. Most of the time these events take on the form of public event Action<[classtype], bool> [PropertyName]Changed; or public event Action SomethingHappened;. In these cases, there are two benefits. First, I get a type for the issuing class. If MyClass declares and is the only class firing the event, I get an explicit instance of MyClass to work with in the event handler. Secondly, for simple events such as property change events, the meaning of the parameters is obvious and stated in the name of the event handler and I don't have to create a myriad of classes for these kinds of events.

How do I set up Eclipse/EGit with GitHub?

Install Mylyn connector for GitHub from this update site, it provides great integration: you can directly import your repositories using Import > Projects from Git > GitHub. You can set the default repository folder in Preferences > Git.

How can I delete multiple lines in vi?

If you want to delete a range AFTER a specific line trigger you can use something like this

:g/^TMPDIR/ :.,+11d

That deletes 11 lines (inclusive) after every encounter of ^TMPDIR.

How to do parallel programming in Python?

In some cases, it's possible to automatically parallelize loops using Numba, though it only works with a small subset of Python:

from numba import njit, prange

@njit(parallel=True)
def prange_test(A):
    s = 0
    # Without "parallel=True" in the jit-decorator
    # the prange statement is equivalent to range
    for i in prange(A.shape[0]):
        s += A[i]
    return s

Unfortunately, it seems that Numba only works with Numpy arrays, but not with other Python objects. In theory, it might also be possible to compile Python to C++ and then automatically parallelize it using the Intel C++ compiler, though I haven't tried this yet.

Is it possible to save HTML page as PDF using JavaScript or jquery?

Yes, Use jspdf To create a pdf file.

You can then turn it into a data URI and inject a download link into the DOM

You will however need to write the HTML to pdf conversion yourself.

Just use printer friendly versions of your page and let the user choose how he wants to print the page.

Edit: Apparently it has minimal support

So the answer is write your own PDF writer or get a existing PDF writer to do it for you (on the server).

'innerText' works in IE, but not in Firefox

A really simple line of Javascript can get the "non-taggy" text in all main browsers...

var myElement = document.getElementById('anyElementId');
var myText = (myElement.innerText || myElement.textContent);

Why are C# 4 optional parameters defined on interface not enforced on implementing class?

Because default parameters are resolved at compile time, not runtime. So the default values does not belong to the object being called, but to the reference type that it is being called through.

How to use pip with Python 3.x alongside Python 2.x

This worked for me on OS X: (I say this because sometimes is a pain that mac has "its own" version of every open source tool, and you cannot remove it because "its improvements" make it unique for other apple stuff to work, and if you remove it things start falling appart)

I followed the steps provided by @Lennart Regebro to get pip for python 3, nevertheless pip for python 2 was still first on the path, so... what I did is to create a symbolic link to python 3 inside /usr/bin (in deed I did the same to have my 2 pythons running in peace):

ln -s /Library/Frameworks/Python.framework/Versions/3.4/bin/pip /usr/bin/pip3

Notice that I added a 3 at the end, so basically what you have to do is to use pip3 instead of just pip.

The post is old but I hope this helps someone someday. this should theoretically work for any LINUX system.

Removing all unused references from a project in Visual Studio projects

The following method does not depend on any 'add-on's and is not very painful.

Step through each of your source files and

  1. Select all (Ctrl-A)
  2. Toggle outline expansion (Ctrl-M, M). This will reduce the file to two lines.
  3. Click on the namespace's '+'. This will show each of the file's classes as a single line. Scan each class's reference count, looking for unreferenced classes.
  4. Click on each of the classes' '+'. This will show each of the class functions as a single line. Scan each function's reference count, looking for unreferenced functions.

Scanning each file looking for '0 reference' takes only a second.

Scanning an entire project takes only a couple of minutes.

java.lang.NoClassDefFoundError: org/apache/juli/logging/LogFactory

I ran into this problem when using tomcat-embed-core::7.0.47, from Maven. I'm not sure why they didn't add tomcat-util as a runtime dependency, so I added my own runtime dependency to my own project.

<dependency>
  <groupId>org.apache.tomcat</groupId>
  <artifactId>tomcat-util</artifactId>
  <version><!-- version from tomcat-embed-core --></version>
  <scope>runtime</scope>
</dependency>

Bootstrap: align input with button

style="padding-top: 8px"

Use this to shift your div up or down in your row. Works wonders for me.

How to change current Theme at runtime in Android

This had no effect for me:

public void changeTheme(int newTheme) {
    setTheme(newTheme);
    recreate();
}

But this worked:

int theme = R.style.default;

protected void onCreate(Bundle savedInstanceState) {
    setTheme(this.theme);
    super.onCreate(savedInstanceState);
}

public void changeTheme(int newTheme) {
    this.theme = newTheme;
    recreate();
}

std::queue iteration

In short: No.

There is a hack, use vector as underlaid container, so queue::front will return valid reference, convert it to pointer an iterate until <= queue::back

Control flow in T-SQL SP using IF..ELSE IF - are there other ways?

Also you can try to formulate your answer in the form of a SELECT CASE Statement. You can then later create simple if then's that use your results if needed as you have narrowed down the possibilities.

SELECT @Result =   
CASE @inputParam   
WHEN 1 THEN 1   
WHEN 2 THEN 2   
WHEN 3 THEN 1   
ELSE 4   
END  

IF @Result = 1   
BEGIN  
...  
END  

IF @Result = 2   
BEGIN   
....  
END  

IF @Result = 4   
BEGIN   
//Error handling code   
END   

How can I disable the default console handler, while using the java logging API?

You must instruct your logger not to send its messages on up to its parent logger:

...
import java.util.logging.*;
...
Logger logger = Logger.getLogger(this.getClass().getName());
logger.setUseParentHandlers(false);
...

However, this should be done before adding any more handlers to logger.

python: get directory two levels up

You can use this as a generic solution:

import os

def getParentDir(path, level=1):
  return os.path.normpath( os.path.join(path, *([".."] * level)) )

What's the difference between .bashrc, .bash_profile, and .environment?

A good place to look at is the man page of bash. Here's an online version. Look for "INVOCATION" section.

Is the sizeof(some pointer) always equal to four?

Just another exception to the already posted list. On 32-bit platforms, pointers can take 6, not 4, bytes:

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

int main() {
    char far* ptr; // note that this is a far pointer
    printf( "%d\n", sizeof( ptr));
    return EXIT_SUCCESS;
}

If you compile this program with Open Watcom and run it, you'll get 6, because far pointers that it supports consist of 32-bit offset and 16-bit segment values

Excel Formula: Count cells where value is date

A bit long winded but it works for me: try this::

=SUM(IF(OR(ISBLANK(AU2), NOT(ISERR(YEAR(AU2)))),0,1)
 +IF(OR(ISBLANK(AV2), NOT(ISERR(YEAR(AV2)))),0,1))

first part of if will allow cell to be blank or if there is something in the cell it tries to convert to a year, if there is an error or there is something other than a date result = 1, do the same for each cell and sum the result

How do I get the full path to a Perl script that is executing?

Getting the absolute path to $0 or __FILE__ is what you want. The only trouble is if someone did a chdir() and the $0 was relative -- then you need to get the absolute path in a BEGIN{} to prevent any surprises.

FindBin tries to go one better and grovel around in the $PATH for something matching the basename($0), but there are times when that does far-too-surprising things (specifically: when the file is "right in front of you" in the cwd.)

File::Fu has File::Fu->program_name and File::Fu->program_dir for this.

Excel: Can I create a Conditional Formula based on the Color of a Cell?

Unfortunately, there is not a direct way to do this with a single formula. However, there is a fairly simple workaround that exists.

On the Excel Ribbon, go to "Formulas" and click on "Name Manager". Select "New" and then enter "CellColor" as the "Name". Jump down to the "Refers to" part and enter the following:

=GET.CELL(63,OFFSET(INDIRECT("RC",FALSE),1,1))

Hit OK then close the "Name Manager" window.

Now, in cell A1 enter the following:

=IF(CellColor=3,"FQS",IF(CellColor=6,"SM",""))

This will return FQS for red and SM for yellow. For any other color the cell will remain blank.

***If the value in A1 doesn't update, hit 'F9' on your keyboard to force Excel to update the calculations at any point (or if the color in B2 ever changes).

Below is a reference for a list of cell fill colors (there are 56 available) if you ever want to expand things: http://www.smixe.com/excel-color-pallette.html

Cheers.

::Edit::

The formula used in Name Manager can be further simplified if it helps your understanding of how it works (the version that I included above is a lot more flexible and is easier to use in checking multiple cell references when copied around as it uses its own cell address as a reference point instead of specifically targeting cell B2).

Either way, if you'd like to simplify things, you can use this formula in Name Manager instead:

=GET.CELL(63,Sheet1!B2)

RegEx match open tags except XHTML self-contained tags

I like to parse HTML with regular expressions. I don't attempt to parse idiot HTML that is deliberately broken. This code is my main parser (Perl edition):

$_ = join "",<STDIN>; tr/\n\r \t/ /s; s/</\n</g; s/>/>\n/g; s/\n ?\n/\n/g;
s/^ ?\n//s; s/ $//s; print

It's called htmlsplit, splits the HTML into lines, with one tag or chunk of text on each line. The lines can then be processed further with other text tools and scripts, such as grep, sed, Perl, etc. I'm not even joking :) Enjoy.

It is simple enough to rejig my slurp-everything-first Perl script into a nice streaming thing, if you wish to process enormous web pages. But it's not really necessary.

HTML Split


Some better regular expressions:

/(<.*?>|[^<]+)\s*/g    # Get tags and text
/(\w+)="(.*?)"/g       # Get attibutes

They are good for XML / XHTML.

With minor variations, it can cope with messy HTML... or convert the HTML -> XHTML first.


The best way to write regular expressions is in the Lex / Yacc style, not as opaque one-liners or commented multi-line monstrosities. I didn't do that here, yet; these ones barely need it.

Why does sudo change the PATH?

I think it is in fact desirable to have sudo reset the PATH: otherwise an attacker having compromised your user account could put backdoored versions of all kinds of tools on your users' PATH, and they would be executed when using sudo.

(of course having sudo reset the PATH is not a complete solution to these kinds of problems, but it helps)

This is indeed what happens when you use

Defaults env_reset

in /etc/sudoers without using exempt_group or env_keep.

This is also convenient because you can add directories that are only useful for root (such as /sbin and /usr/sbin) to the sudo path without adding them to your users' paths. To specify the path to be used by sudo:

Defaults secure_path="/bin:/usr/bin:/usr/local/bin:/sbin:/usr/sbin"

How do I create a sequence in MySQL?

Check out this article. I believe it should help you get what you are wanting. If your table already exists, and it has data in it already, the error you are getting may be due to the auto_increment trying to assign a value that already exists for other records.

In short, as others have already mentioned in comments, sequences, as they are thought of and handled in Oracle, do not exist in MySQL. However, you can likely use auto_increment to accomplish what you want.

Without additional details on the specific error, it is difficult to provide more specific help.

UPDATE

CREATE TABLE ORD (
  ORDID INT NOT NULL AUTO_INCREMENT,
  //Rest of table code
  PRIMARY KEY (ordid)
)
AUTO_INCREMENT = 622;

This link is also helpful for describing usage of auto_increment. Setting the AUTO_INCREMENT value appears to be a table option, and not something that is specified as a column attribute specifically.

Also, per one of the links from above, you can alternatively set the auto increment start value via an alter to your table.

ALTER TABLE ORD AUTO_INCREMENT = 622;

UPDATE 2 Here is a link to a working sqlfiddle example, using auto increment.
I hope this info helps.

What is "android.R.layout.simple_list_item_1"?

As mentioned by Klap "android.R.layout.simple_list_item_1 is a reference to an built-in XML layout document that is part of the Android OS"
All the layouts are located in: sdk\platforms\android-xx\data\res\layout
To view the XML of layout :
Eclipse: Simply type android.R.layout.simple_list_item_1 somewhere in code, hold Ctrl, hover over simple_list_item_1, and from the dropdown that appears select "Open declaration in layout/simple_list_item_1.xml". It'll direct you to the contents of the XML.
Android Studio: Project Window -> External Libraries -> Android X Platform -> res -> layout, and here you will see a list of available layouts.
enter image description here

Java String new line

If you want to have your code os-unspecific you should use println for each word

System.out.println("I");
System.out.println("am");
System.out.println("a");
System.out.println("boy");

because Windows uses "\r\n" as newline and unixoid systems use just "\n"

println always uses the correct one

How to dynamically build a JSON object with Python?

  • json.loads take a string as input and returns a dictionary as output.
  • json.dumps take a dictionary as input and returns a string as output.

If you need to convert JSON data into a python object, it can do so with Python3, in one line without additional installations, using SimpleNamespace and object_hook:

from string

import json
from types import SimpleNamespace

string = '{"foo":3, "bar":{"x":1, "y":2}}'

# Parse JSON into an object with attributes corresponding to dict keys.
x = json.loads(string, object_hook=lambda d: SimpleNamespace(**d))

print(x.foo)
print(x.bar.x)
print(x.bar.y)

output:

3
1
2

from file:

JSON object: data.json

{
    "foo": 3,
    "bar": {
        "x": 1,
        "y": 2
    }
}
import json
from types import SimpleNamespace

with open("data.json") as fh:
    string = fh.read()

# Parse JSON into an object with attributes corresponding to dict keys.
x = json.loads(string, object_hook=lambda d: SimpleNamespace(**d))

print(x.foo)
print(x.bar.x)
print(x.bar.y)

output:

3
1
2

from requests

import json
from types import SimpleNamespace
import requests

r = requests.get('https://api.github.com/users/MilovanTomasevic')

# Parse JSON into an object with attributes corresponding to dict keys.
x = json.loads(r.text, object_hook=lambda d: SimpleNamespace(**d))

print(x.name)
print(x.company)
print(x.blog)

output:

Milovan Tomaševic
NLB
milovantomasevic.com

For more beautiful and faster access to JSON response from API, take a look at this response.

Convert text to columns in Excel using VBA

Try this

Sub Txt2Col()
    Dim rng As Range

    Set rng = [C7]
    Set rng = Range(rng, Cells(Rows.Count, rng.Column).End(xlUp))

    rng.TextToColumns Destination:=rng, DataType:=xlDelimited, ' rest of your settings

Update: button click event to act on another sheet

Private Sub CommandButton1_Click()
    Dim rng As Range
    Dim sh As Worksheet

    Set sh = Worksheets("Sheet2")
    With sh
        Set rng = .[C7]
        Set rng = .Range(rng, .Cells(.Rows.Count, rng.Column).End(xlUp))

        rng.TextToColumns Destination:=rng, DataType:=xlDelimited, _
        TextQualifier:=xlDoubleQuote,  _
        ConsecutiveDelimiter:=False, _
        Tab:=False, _
        Semicolon:=False, _
        Comma:=True, 
        Space:=False, 
        Other:=False, _
        FieldInfo:=Array(Array(1, xlGeneralFormat), Array(2, xlGeneralFormat), Array(3, xlGeneralFormat)), _
        TrailingMinusNumbers:=True
    End With
End Sub

Note the .'s (eg .Range) they refer to the With statement object

SQL Greater than, Equal to AND Less Than

declare @starttime datetime = '2012-03-07 22:58:00'

SELECT BookingId, StartTime
FROM Booking
WHERE ABS( DATEDIFF( minute, StartTime, @starttime ) ) <= 60

How to format a floating number to fixed width in Python

This will print 76.66:

print("Number: ", f"{76.663254: .2f}")

API vs. Webservice

An API (Application Programming Interface) is the means by which third parties can write code that interfaces with other code. A Web Service is a type of API, one that almost always operates over HTTP (though some, like SOAP, can use alternate transports, like SMTP). The official W3C definition mentions that Web Services don't necessarily use HTTP, but this is almost always the case and is usually assumed unless mentioned otherwise.

For examples of web services specifically, see SOAP, REST, and XML-RPC. For an example of another type of API, one written in C for use on a local machine, see the Linux Kernel API.

As far as the protocol goes, a Web service API almost always uses HTTP (hence the Web part), and definitely involves communication over a network. APIs in general can use any means of communication they wish. The Linux kernel API, for example, uses Interrupts to invoke the system calls that comprise its API for calls from user space.

How can my iphone app detect its own version number?

Read the info.plist file of your app and get the value for key CFBundleShortVersionString. Reading info.plist will give you an NSDictionary object

How to hide a button programmatically?

Hidde:

BUTTON.setVisibility(View.GONE);

Show:

BUTTON.setVisibility(View.VISIBLE);

How to install pandas from pip on windows cmd?

Please Ensure you are using a virtualEnv this is how :

virtualenv -p python3 envname

source env/bin/activate
pip install pandas

on windows you have to add scripts exe in the CLASSPATH in order to use pip command

C:\Python34\Scripts\pip3.exe

i suggest you to use MINGW he can gives you a better environment to work with python

How to use local docker images with Minikube?

one thing to remember regarding 'minikube' is that minikube's host is not the same as your local host, therefore, what i realized, that in order to use local images for testing with minikube you must build your docker image first locally or pull it locally and then add it using the command bellow into the minikube context which is, nothing else as another linux instance.

 minikube cache add <image>:<tag>

yet, don't forget to set the imagePullPolicy: Never in your kubernetes deployment yamls, as it will ensure using locally added images instead of trying pull it remotely from the registry.

Convert blob to base64

async function blobToBase64(blob) {
  return new Promise((resolve, _) => {
    const reader = new FileReader();
    reader.onloadend = () => resolve(reader.result);
    reader.readAsDataURL(blob);
  });
}

let blob = null; // <= your blob object goes here

blobToBase64(blob)
  .then(base64String => console.log(base64String));

See also:

How to return a class object by reference in C++?

You're probably returning an object that's on the stack. That is, return_Object() probably looks like this:

Object& return_Object()
{
    Object object_to_return;
    // ... do stuff ...

    return object_to_return;
}

If this is what you're doing, you're out of luck - object_to_return has gone out of scope and been destructed at the end of return_Object, so myObject refers to a non-existent object. You either need to return by value, or return an Object declared in a wider scope or newed onto the heap.