Programs & Examples On #Hashref

Is it possible to use JS to open an HTML select to show its option list?

Unfortunately there's a simple answer to this question, and it's "No"

You have not accepted the license agreements of the following SDK components

You can install and accept the license of the SDK & tools via 2 ways:

1. Open the Android SDK Manager GUI via command line

Open the Android SDK manager via the command line using:

# Android SDK Tools 25.2.3 and lower - Open the Android SDK GUI via the command line
cd ~/Library/Android/sdk/tools && ./android

# 'Android SDK Tools' 25.2.3 and higher - `sdkmanager` is located in android_sdk/tools/bin/.
cd ~/Library/Android/sdk/tools/bin && ./sdkmanager

View more details on the new sdkmanager.

Select and install the required tools. (your location may be different)

2. Install and accept android license via command line:

Update the packages via command line, you'll be presented with the terms and conditions which you'll need to accept.

- Install or update to the latest version

This will install the latest platform-tools at the time you run it.

# Android SDK Tools 25.2.3 and lower. Install the latest `platform-tools` for android-25
android update sdk --no-ui --all --filter platform-tools,android-25,extra-android-m2repository

# Android SDK Tools 25.2.3 and higher
sdkmanager --update

- Install a specific version (25.0.1, 24.0.1, 23.0.1)

You can also install a specific version like so:

# Build Tools 23.0.1, 24.0.1, 25.0.1
android update sdk --no-ui --all --filter build-tools-25.0.1,android-25,extra-android-m2repository
android update sdk --no-ui --all --filter build-tools-24.0.1,android-24,extra-android-m2repository
android update sdk --no-ui --all --filter build-tools-23.0.1,android-23,extra-android-m2repository
# Alter the versions as required                      ?               ?

# -u --no-ui  : Updates from command-line (does not display the GUI)
# -a --all    : Includes all packages (such as obsolete and non-dependent ones.)
# -t --filter : A filter that limits the update to the specified types of
#               packages in the form of a comma-separated list of
#               [platform, system-image, tool, platform-tool, doc, sample,
#               source]. This also accepts the identifiers returned by
#               'list sdk --extended'.

# List version and description of other available SDKs and tools
android list sdk --extended
sdkmanager --list

Import regular CSS file in SCSS file?

You can use a third-party importer to customise @import semantics.

node-sass-import-once, which works with node-sass (for Node.js) can inline import CSS files.

Example of direct usage:

var sass = require('node-sass');,
    importOnce = require('node-sass-import-once');

sass.render({
  file: "input.scss",
  importer: importOnce,
  importOnce: {
    css: true,
  }
});

Example grunt-sass config:

var importOnce = require("node-sass-import-once");
grunt.loadNpmTasks("grunt-sass");

grunt.initConfig({
  sass: {
    options: {
      sourceMap: true,
      importer: importOnce
    },
    dev: {
      files: {
        "dist/style.css": "scss/**/*.scss"
      }
    }
  });

Note that node-sass-import-once cannot currently import Sass partials without an explicit leading underscore. For example with the file partials/_partial.scss:

  • @import partials/_partial.scss succeeds
  • @import * partials/partial.scss fails

In general, be aware that a custom importer could change any import semantics. Read the docs before you start using it.

iPhone: Setting Navigation Bar Title

If you are working with Storyboards, you can click on the controller, switch to the properties tab, and set the title text there.

jQuery .css("margin-top", value) not updating in IE 8 (Standards mode)

The correct format for IE8 is:

  $("#ActionBox").css({ 'margin-top': '10px' });  

with this work.

How to get the unix timestamp in C#

I used this after struggling for a while, it caters to the timezone offset as well:

    public double Convert_DatTime_To_UNIXDATETIME(DateTime dt)
    {
        System.DateTime from_date = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
        double unix_time_since = dt.Subtract(from_date).TotalMilliseconds;

        TimeSpan ts_offset = TimeZoneInfo.Local.GetUtcOffset(DateTime.UtcNow);

        double offset = ts_offset.TotalMilliseconds;

        return unix_time_since - offset;
    }

How to simulate a button click using code?

Just write this simple line of code :-

button.performClick();

where button is the reference variable of Button class and defined as follows:-

private Button buttonToday ;
buttonToday = (Button) findViewById(R.id.buttonToday);

That's it.

How to encrypt a large file in openssl using public key

Solution for safe and high secured encode anyone file in OpenSSL and command-line:

You should have ready some X.509 certificate for encrypt files in PEM format.

Encrypt file:

openssl smime -encrypt -binary -aes-256-cbc -in plainfile.zip -out encrypted.zip.enc -outform DER yourSslCertificate.pem

What is what:

  • smime - ssl command for S/MIME utility (smime(1))
  • -encrypt - chosen method for file process
  • -binary - use safe file process. Normally the input message is converted to "canonical" format as required by the S/MIME specification, this switch disable it. It is necessary for all binary files (like a images, sounds, ZIP archives).
  • -aes-256-cbc - chosen cipher AES in 256 bit for encryption (strong). If not specified 40 bit RC2 is used (very weak). (Supported ciphers)
  • -in plainfile.zip - input file name
  • -out encrypted.zip.enc - output file name
  • -outform DER - encode output file as binary. If is not specified, file is encoded by base64 and file size will be increased by 30%.
  • yourSslCertificate.pem - file name of your certificate's. That should be in PEM format.

That command can very effectively a strongly encrypt big files regardless of its format.
Known issue: Something wrong happens when you try encrypt huge file (>600MB). No error thrown, but encrypted file will be corrupted. Always verify each file! (or use PGP - that has bigger support for files encryption with public key)

Decrypt file:

openssl smime -decrypt -binary -in encrypted.zip.enc -inform DER -out decrypted.zip -inkey private.key -passin pass:your_password

What is what:

  • -inform DER - same as -outform above
  • -inkey private.key - file name of your private key. That should be in PEM format and can be encrypted by password.
  • -passin pass:your_password - your password for private key encrypt. (passphrase arguments)

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

Changing "Managed Pipeline Mode" from "Classic" to "Integrated" worked for me. It can be changed at Application Pools -> Basic Settings

How to get all options of a select using jQuery?

    var arr = [], option='';
$('select#idunit').find('option').each(function(index) {
arr.push ([$(this).val(),$(this).text()]);
//option = '<option '+ ((result[0].idunit==arr[index][0])?'selected':'') +'  value="'+arr[index][0]+'">'+arr[index][1]+'</option>';
            });
console.log(arr);
//$('select#idunit').empty();
//$('select#idunit').html(option);

Index all *except* one item in python

If you don't know the index beforehand here is a function that will work

def reverse_index(l, index):
    try:
        l.pop(index)
        return l
    except IndexError:
        return False

C# how to convert File.ReadLines into string array?

Change string[] lines = File.ReadLines("c:\\file.txt"); to IEnumerable<string> lines = File.ReadLines("c:\\file.txt"); The rest of your code should work fine.

PHP Unset Session Variable

unset is a function, not an operator. Use it like unset($_SESSION['key']); to unset that session key. You can, however, use session_destroy(); as well. (Make sure to start the session with session_start(); as well)

Trying to detect browser close event

Following script will give message on Chrome and IE:

<script>
window.onbeforeunload = function (e) {
// Your logic to prepare for 'Stay on this Page' goes here 

    return "Please click 'Stay on this Page' and we will give you candy";
};
</script>

Chrome
enter image description here

IE
enter image description here

on Firefox you will get generic message

enter image description here

Mechanism is synchronous so no server calls to delay will work, you still can prepare a mechanism like modal window that is shown if user decides to stay on page, but no way to prevent him from leaving.

Response to question in comment

F5 will fire event again, so will Atl+F4.

Deep copy vs Shallow Copy

Shallow copy:

Some members of the copy may reference the same objects as the original:

class X
{
private:
    int i;
    int *pi;
public:
    X()
        : pi(new int)
    { }
    X(const X& copy)   // <-- copy ctor
        : i(copy.i), pi(copy.pi)
    { }
};

Here, the pi member of the original and copied X object will both point to the same int.


Deep copy:

All members of the original are cloned (recursively, if necessary). There are no shared objects:

class X
{
private:
    int i;
    int *pi;
public:
    X()
        : pi(new int)
    { }
    X(const X& copy)   // <-- copy ctor
        : i(copy.i), pi(new int(*copy.pi))  // <-- note this line in particular!
    { }
};

Here, the pi member of the original and copied X object will point to different int objects, but both of these have the same value.


The default copy constructor (which is automatically provided if you don't provide one yourself) creates only shallow copies.

Correction: Several comments below have correctly pointed out that it is wrong to say that the default copy constructor always performs a shallow copy (or a deep copy, for that matter). Whether a type's copy constructor creates a shallow copy, or deep copy, or something in-between the two, depends on the combination of each member's copy behaviour; a member's type's copy constructor can be made to do whatever it wants, after all.

Here's what section 12.8, paragraph 8 of the 1998 C++ standard says about the above code examples:

The implicitly defined copy constructor for class X performs a memberwise copy of its subobjects. [...] Each subobject is copied in the manner appropriate to its type: [...] [I]f the subobject is of scalar type, the builtin assignment operator is used.

Error: The processing instruction target matching "[xX][mM][lL]" is not allowed

Xerces-based tools will emit the following error

The processing instruction target matching "[xX][mM][lL]" is not allowed.

when an XML declaration is encountered anywhere other than at the top of an XML file.

This is a valid diagnostic message; other XML parsers should issue a similar error message in this situation.

To correct the problem, check the following possibilities:

  1. Some blank space or other visible content exists before the <?xml ?> declaration.

    Resolution: remove blank space or any other visible content before the XML declaration.

  2. Some invisible content exists before the <?xml ?> declaration. Most commonly this is a Byte Order Mark (BOM).

    Resolution: Remove the BOM using techniques such as those suggested by the W3C page on the BOM in HTML.

  3. A stray <?xml ?> declaration exists within the XML content. This can happen when XML files are combined programmatically or via cut-and-paste. There can only be one <?xml ?> declaration in an XML file, and it can only be at the top.

    Resolution: Search for <?xml in a case-insensitive manner, and remove all but the top XML declaration from the file.

How to recursively find and list the latest modified files in a directory with subdirectories and times

GNU find (see man find) has a -printf parameter for displaying the files in Epoch mtime and relative path name.

redhat> find . -type f -printf '%T@ %P\n' | sort -n | awk '{print $2}'

Mockito - difference between doReturn() and when()

The Mockito javadoc seems to tell why use doReturn() instead of when() Use doReturn() in those rare occasions when you cannot use Mockito.when(Object).

Beware that Mockito.when(Object) is always recommended for stubbing because it is argument type-safe and more readable (especially when stubbing consecutive calls).

Here are those rare occasions when doReturn() comes handy:

1. When spying real objects and calling real methods on a spy brings side effects

List list = new LinkedList(); List spy = spy(list);

//Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)

when(spy.get(0)).thenReturn("foo");

//You have to use doReturn() for stubbing: doReturn("foo").when(spy).get(0);

2. Overriding a previous exception-stubbing:

when(mock.foo()).thenThrow(new RuntimeException());

//Impossible: the exception-stubbed foo() method is called so RuntimeException is thrown. when(mock.foo()).thenReturn("bar");

//You have to use doReturn() for stubbing:

doReturn("bar").when(mock).foo(); Above scenarios shows a tradeoff of Mockito's elegant syntax. Note that the scenarios are very rare, though. Spying should be sporadic and overriding exception-stubbing is very rare. Not to mention that in general overridding stubbing is a potential code smell that points out too much stubbing.

How can I convert an HTML element to a canvas element?

You can use dom-to-image library (I'm the maintainer).
Here's how you could approach your problem:

var parent = document.getElementById('my-node-parent');
var node = document.getElementById('my-node');

var canvas = document.createElement('canvas');
canvas.width = node.scrollWidth;
canvas.height = node.scrollHeight;

domtoimage.toPng(node).then(function (pngDataUrl) {
    var img = new Image();
    img.onload = function () {
        var context = canvas.getContext('2d');

        context.translate(canvas.width, 0);
        context.scale(-1, 1);
        context.drawImage(img, 0, 0);

        parent.removeChild(node);
        parent.appendChild(canvas);
    };

    img.src = pngDataUrl;
});

And here is jsfiddle

Updating a java map entry

Use

table.put(key, val);

to add a new key/value pair or overwrite an existing key's value.

From the Javadocs:

V put(K key, V value): Associates the specified value with the specified key in this map (optional operation). If the map previously contained a mapping for the key, the old value is replaced by the specified value. (A map m is said to contain a mapping for a key k if and only if m.containsKey(k) would return true.)

Python Function to test ping

Try this

def ping(server='example.com', count=1, wait_sec=1):
    """

    :rtype: dict or None
    """
    cmd = "ping -c {} -W {} {}".format(count, wait_sec, server).split(' ')
    try:
        output = subprocess.check_output(cmd).decode().strip()
        lines = output.split("\n")
        total = lines[-2].split(',')[3].split()[1]
        loss = lines[-2].split(',')[2].split()[0]
        timing = lines[-1].split()[3].split('/')
        return {
            'type': 'rtt',
            'min': timing[0],
            'avg': timing[1],
            'max': timing[2],
            'mdev': timing[3],
            'total': total,
            'loss': loss,
        }
    except Exception as e:
        print(e)
        return None

Convert JSON String to JSON Object c#

This works for me using JsonConvert

var result = JsonConvert.DeserializeObject<Class>(responseString);

jQuery, simple polling example

function make_call()
{
  // do the request

  setTimeout(function(){ 
    make_call();
  }, 5000);
}

$(document).ready(function() {
  make_call();
});

2 column div layout: right column with fixed width, left fluid

Hey, What you can do is apply a fixed width to both the containers and then use another div class where clear:both, like

div#left {

width: 600px;
float: left;
}

div#right {

width: 240px;
float: right;

}

div.clear {

clear:both;

}

place a the clear div under left and right container.

How to check if directory exists in %PATH%?

You can accomplish this using PoweShell;

Test-Path $ENV:SystemRoot\YourDirectory
Test-Path C:\Windows\YourDirectory

This returns TRUE or FALSE

Short, simle and easy!

Difference between h:button and h:commandButton

h:button - clicking on a h:button issues a bookmarkable GET request.

h:commandbutton - Instead of a get request, h:commandbutton issues a POST request which sends the form data back to the server.

Include another JSP file

1.<a href="index.jsp?p=products">Products</a> when user clicks on Products link,you can directly call products.jsp.

I mean u can maintain name of the JSP file same as parameter Value.

<%
 if(request.getParameter("p")!=null)
 { 
   String contextPath="includes/";
   String p = request.getParameter("p");
   p=p+".jsp";
   p=contextPath+p;

%>    

<%@include file="<%=p%>" %>

<% 
 }
%>

or

2.you can maintain external resource file with key,value pairs. like below

products : products.jsp

customer : customers.jsp

you can programatically retrieve the name of JSP file from properies file.

this way you can easily change the name of JSP file

How to count how many values per level in a given factor?

Or using the dplyr library:

library(dplyr)
set.seed(1)
dat <- data.frame(ID = sample(letters,100,rep=TRUE))
dat %>% 
  group_by(ID) %>%
  summarise(no_rows = length(ID))

Note the use of %>%, which is similar to the use of pipes in bash. Effectively, the code above pipes dat into group_by, and the result of that operation is piped into summarise.

The result is:

Source: local data frame [26 x 2]

   ID no_rows
1   a       2
2   b       3
3   c       3
4   d       3
5   e       2
6   f       4
7   g       6
8   h       1
9   i       6
10  j       5
11  k       6
12  l       4
13  m       7
14  n       2
15  o       2
16  p       2
17  q       5
18  r       4
19  s       5
20  t       3
21  u       8
22  v       4
23  w       5
24  x       4
25  y       3
26  z       1

See the dplyr introduction for some more context, and the documentation for details regarding the individual functions.

ValidateRequest="false" doesn't work in Asp.Net 4

There is a way to turn the validation back to 2.0 for one page. Just add the below code to your web.config:

<configuration>
    <location path="XX/YY">
        <system.web>
            <httpRuntime requestValidationMode="2.0" />
        </system.web>
    </location>

    ...
    the rest of your configuration
    ...

</configuration>

MySql Error: 1364 Field 'display_name' doesn't have default value

MySQL is most likely in STRICT mode.

Try running SET GLOBAL sql_mode='' or edit your my.cnf to make sure you aren't setting STRICT_ALL_TABLES or the like.

highlight the navigation menu for the current page

Please Look at the following:

Here is what's working:

1.) top menu buttons are visible and highlight correctly

2.) sub menu buttons are not visible until top menu is clicked

Here is what needs work:

1.) when sub menu is clicked, looking for new page to keep the selected sub menu open (i will highlight the selected sub menu button for further clarification on navigation)

Please see code here: http://jsbin.com/ePawaju/1/edit

or here: http://www.ceramictilepro.com/_6testingonly.php#

<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>

Do I need to put this script in the head section? Where is the best place?

<div class="left">
<nav class="vmenu">
    <ul class="vnavmenu">
        <li data-ref="Top1"><a class="hiLite navBarButton2" href="#">Home</a>
        </li>
    </ul>
    <ul class="Top1 navBarTextSize">
        <li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">sub1</a>
        </li>
        <li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">sub2</a>
        </li>
        <li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">sub3</a>
        </li>
        <li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">sub4</a>
        </li>
    </ul>
    <ul class="vnavmenu">
        <li data-ref="Top2"><a class="hiLite navBarButton2" href="#">Repairs</a>
        </li>
    </ul>
    <ul class="Top2 navBarTextSize">
        <li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">1sub1</a>
        </li>
        <li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">2sub2</a>
        </li>
        <li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">3sub3</a>
        </li>
        <li><a class="hiLite navBarButton2_sub" href="http://www.ceramictilepro.com/_5testingonly.php">4sub4</a>
        </li>
    </ul>
</nav>

JQuery is new to me, any help would greatly be appreciated :) var submenu;

$('.vnavmenu li').click(function () {
var elems = $('.vmenu ul:not(.vnavmenu)').length;
var $refClass = $('.' + $(this).attr('data-ref'));
var visible = $refClass.is(':visible');

$('.vmenu ul:not(.vnavmenu)').slideUp(100, function () {

    if (elems == 1) {
        if (!visible) $refClass.slideDown('fast');
    }

    elems--;
});

if (visible) $('#breadcrumbs-pc').animate({
    'margin-top': '0rem'
}, 100);
else $('#breadcrumbs-pc').animate({
    'margin-top': '5rem'
}, 100);
});

What does the "assert" keyword do?

Assert does throw an AssertionError if you run your app with assertions turned on.

int a = 42;
assert a >= 0 && d <= 10;

If you run this with, say: java -ea -jar peiska.jar

It shall throw an java.lang.AssertionError

JavaScript blob filename without link

Working example of a download button, to save a cat photo from an url as "cat.jpg":

HTML:

<button onclick="downloadUrl('https://i.imgur.com/AD3MbBi.jpg', 'cat.jpg')">Download</button>

JavaScript:

function downloadUrl(url, filename) {
  let xhr = new XMLHttpRequest();
  xhr.open("GET", url, true);
  xhr.responseType = "blob";
  xhr.onload = function(e) {
    if (this.status == 200) {
      const blob = this.response;
      const a = document.createElement("a");
      document.body.appendChild(a);
      const blobUrl = window.URL.createObjectURL(blob);
      a.href = blobUrl;
      a.download = filename;
      a.click();
      setTimeout(() => {
        window.URL.revokeObjectURL(blobUrl);
        document.body.removeChild(a);
      }, 0);
    }
  };
  xhr.send();
}

How to convert std::string to lower case?

This is a follow-up to Stefan Mai's response: if you'd like to place the result of the conversion in another string, you need to pre-allocate its storage space prior to calling std::transform. Since STL stores transformed characters at the destination iterator (incrementing it at each iteration of the loop), the destination string will not be automatically resized, and you risk memory stomping.

#include <string>
#include <algorithm>
#include <iostream>

int main (int argc, char* argv[])
{
  std::string sourceString = "Abc";
  std::string destinationString;

  // Allocate the destination space
  destinationString.resize(sourceString.size());

  // Convert the source string to lower case
  // storing the result in destination string
  std::transform(sourceString.begin(),
                 sourceString.end(),
                 destinationString.begin(),
                 ::tolower);

  // Output the result of the conversion
  std::cout << sourceString
            << " -> "
            << destinationString
            << std::endl;
}

HTTP POST with URL query parameters -- good idea or not?

Everyone is right: stick with POST for non-idempotent requests.

What about using both an URI query string and request content? Well it's valid HTTP (see note 1), so why not?!

It is also perfectly logical: URLs, including their query string part, are for locating resources. Whereas HTTP method verbs (POST - and its optional request content) are for specifying actions, or what to do with resources. Those should be orthogonal concerns. (But, they are not beautifully orthogonal concerns for the special case of ContentType=application/x-www-form-urlencoded, see note 2 below.)

Note 1: HTTP specification (1.1) does not state that query parameters and content are mutually exclusive for a HTTP server that accepts POST or PUT requests. So any server is free to accept both. I.e. if you write the server there's nothing to stop you choosing to accept both (except maybe an inflexible framework). Generally, the server can interpret query strings according to whatever rules it wants. It can even interpret them with conditional logic that refers to other headers like Content-Type too, which leads to Note 2:

Note 2: if a web browser is the primary way people are accessing your web application, and application/x-www-form-urlencoded is the Content-Type they are posting, then you should follow the rules for that Content-Type. And the rules for application/x-www-form-urlencoded are much more specific (and frankly, unusual): in this case you must interpret the URI as a set of parameters, and not a resource location. [This is the same point of usefulness Powerlord raised; that it may be hard to use web forms to POST content to your server. Just explained a little differently.]

Note 3: what are query strings originally for? RFC 3986 defines HTTP query strings as an URI part that works as a non-hierarchical way of locating a resource.

In case readers asking this question wish to ask what is good RESTful architecture: the RESTful architecture pattern doesn't require URI schemes to work a specific way. RESTful architecture concerns itself with other properties of the system, like cacheability of resources, the design of the resources themselves (their behavior, capabilities, and representations), and whether idempotence is satisfied. Or in other words, achieving a design which is highly compatible with HTTP protocol and its set of HTTP method verbs. :-) (In other words, RESTful architecture is not very presciptive with how the resources are located.)

Final note: sometimes query parameters get used for yet other things, which are neither locating resources nor encoding content. Ever seen a query parameter like 'PUT=true' or 'POST=true'? These are workarounds for browsers that don't allow you to use PUT and POST methods. While such parameters are seen as part of the URL query string (on the wire), I argue that they are not part of the URL's query in spirit.

How to sort in-place using the merge sort algorithm?

The critical step is getting the merge itself to be in-place. It's not as difficult as those sources make out, but you lose something when you try.

Looking at one step of the merge:

[...list-sorted...|x...list-A...|y...list-B...]

We know that the sorted sequence is less than everything else, that x is less than everything else in A, and that y is less than everything else in B. In the case where x is less than or equal to y, you just move your pointer to the start of A on one. In the case where y is less than x, you've got to shuffle y past the whole of A to sorted. That last step is what makes this expensive (except in degenerate cases).

It's generally cheaper (especially when the arrays only actually contain single words per element, e.g., a pointer to a string or structure) to trade off some space for time and have a separate temporary array that you sort back and forth between.

Check if list<t> contains any of another list

You could use a nested Any() for this check which is available on any Enumerable:

bool hasMatch = myStrings.Any(x => parameters.Any(y => y.source == x));

Faster performing on larger collections would be to project parameters to source and then use Intersect which internally uses a HashSet<T> so instead of O(n^2) for the first approach (the equivalent of two nested loops) you can do the check in O(n) :

bool hasMatch = parameters.Select(x => x.source)
                          .Intersect(myStrings)
                          .Any(); 

Also as a side comment you should capitalize your class names and property names to conform with the C# style guidelines.

Remove a specific character using awk or sed

tr can be more concise for removing characters than sed or awk, especially when you want to remove different characters from a string.

Removing double quotes:

echo '"Hi"' | tr -d \"
# Produces Hi without quotes

Removing different kinds of brackets:

echo '[{Hi}]' | tr -d {}[]
# Produces Hi without brackets

-d stands for "delete".

Get line number while using grep

If you want only the line number do this:

grep -n Pattern file.ext | gawk '{print $1}' FS=":"

Example:

$ grep -n 9780545460262 EXT20130410.txt | gawk '{print $1}' FS=":" 
48793
52285
54023

Asp.Net MVC with Drop Down List, and SelectListItem Assistance

Step-1: Your Model class

public class RechargeMobileViewModel
    {
        public string CustomerFullName { get; set; }
        public string TelecomSubscriber { get; set; }
        public int TotalAmount { get; set; }
        public string MobileNumber { get; set; }
        public int Month { get; set; }
        public List<SelectListItem> getAllDaysList { get; set; }

        // Define the list which you have to show in Drop down List
        public List<SelectListItem> getAllWeekDaysList()
        {
            List<SelectListItem> myList = new List<SelectListItem>();
            var data = new[]{
                 new SelectListItem{ Value="1",Text="Monday"},
                 new SelectListItem{ Value="2",Text="Tuesday"},
                 new SelectListItem{ Value="3",Text="Wednesday"},
                 new SelectListItem{ Value="4",Text="Thrusday"},
                 new SelectListItem{ Value="5",Text="Friday"},
                 new SelectListItem{ Value="6",Text="Saturday"},
                 new SelectListItem{ Value="7",Text="Sunday"},
             };
            myList = data.ToList();
            return myList;
        }
}

Step-2: Call this method to fill Drop down in your controller Action

namespace MvcVariousApplication.Controllers
    {
        public class HomeController : Controller
        {
            public ActionResult Index()
            {
              RechargeMobileViewModel objModel = new RechargeMobileViewModel();
                objModel.getAllDaysList = objModel.getAllWeekDaysList();  
                return View(objModel);
            }
    }
    }

Step-3: Fill your Drop-Down List of View as follows

 @model MvcVariousApplication.Models.RechargeMobileViewModel
    @{
        ViewBag.Title = "Contact";
    }
    @Html.LabelFor(model=> model.CustomerFullName)
    @Html.TextBoxFor(model => model.CustomerFullName)

    @Html.LabelFor(model => model.MobileNumber)
    @Html.TextBoxFor(model => model.MobileNumber)

    @Html.LabelFor(model => model.TelecomSubscriber)
    @Html.TextBoxFor(model => model.TelecomSubscriber)

    @Html.LabelFor(model => model.TotalAmount)
    @Html.TextBoxFor(model => model.TotalAmount)

    @Html.LabelFor(model => model.Month)
    @Html.DropDownListFor(model => model.Month, new SelectList(Model.getAllDaysList, "Value", "Text"), "-Select Day-")

How to print the values of slices

You could use a for loop to print the []Project as shown in @VonC excellent answer.

package main

import "fmt"

type Project struct{ name string }

func main() {
    projects := []Project{{"p1"}, {"p2"}}
    for i := range projects {
        p := projects[i]
        fmt.Println(p.name) //p1, p2
    }
}

How to redirect stderr to null in cmd.exe

Your DOS command 2> nul

Read page Using command redirection operators. Besides the "2>" construct mentioned by Tanuki Software, it lists some other useful combinations.

android activity has leaked window com.android.internal.policy.impl.phonewindow$decorview Issue

The dialog needs to be started only after the window states of the Activity are initialized This happens only after onresume.

So call

runOnUIthread(new Runnable(){

    showInfoMessageDialog("Please check your network connection","Network Alert");
});

in your OnResume function. Do not create dialogs in OnCreate
Edit:

use this

Handler h = new Handler();

h.postDelayed(new Runnable(){

        showInfoMessageDialog("Please check your network connection","Network Alert");
    },500);

in your Onresume instead of showonuithread

CSS content property: is it possible to insert HTML instead of Text?

As almost noted in comments to @BoltClock's answer, in modern browsers, you can actually add some html markup to pseudo-elements using the (url()) in combination with svg's <foreignObject> element.

You can either specify an URL pointing to an actual svg file, or create it with a dataURI version (data:image/svg+xml; charset=utf8, + encodeURIComponent(yourSvgMarkup))

But note that it is mostly a hack and that there are a lot of limitations :

  • You can not load any external resources from this markup (no CSS, no images, no media etc.).
  • You can not execute script.
  • Since this won't be part of the DOM, the only way to alter it, is to pass the markup as a dataURI, and edit this dataURI in document.styleSheets. for this part, DOMParser and XMLSerializer may help.
  • While the same operation allows us to load url-encoded media in <img> tags, this won't work in pseudo-elements (at least as of today, I don't know if it is specified anywhere that it shouldn't, so it may be a not-yet implemented feature).

Now, a small demo of some html markup in a pseudo element :

_x000D_
_x000D_
/* _x000D_
**  original svg code :_x000D_
*_x000D_
*<svg width="200" height="60"_x000D_
*     xmlns="http://www.w3.org/2000/svg">_x000D_
*_x000D_
* <foreignObject width="100%" height="100%" x="0" y="0">_x000D_
* <div xmlns="http://www.w3.org/1999/xhtml" style="color: blue">_x000D_
*  I am <pre>HTML</pre>_x000D_
* </div>_x000D_
* </foreignObject>_x000D_
*</svg>_x000D_
*_x000D_
*/
_x000D_
#log::after {_x000D_
  content: url('data:image/svg+xml;%20charset=utf8,%20%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20height%3D%2260%22%20width%3D%22200%22%3E%0A%0A%20%20%3CforeignObject%20y%3D%220%22%20x%3D%220%22%20height%3D%22100%25%22%20width%3D%22100%25%22%3E%0A%09%3Cdiv%20style%3D%22color%3A%20blue%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F1999%2Fxhtml%22%3E%0A%09%09I%20am%20%3Cpre%3EHTML%3C%2Fpre%3E%0A%09%3C%2Fdiv%3E%0A%20%20%3C%2FforeignObject%3E%0A%3C%2Fsvg%3E');_x000D_
}
_x000D_
<p id="log">hi</p>
_x000D_
_x000D_
_x000D_

How to set background color of view transparent in React Native

Try to use transparent attribute value for making transparent background color.

backgroundColor: 'transparent'

angularjs getting previous route path

In your html :

<a href="javascript:void(0);" ng-click="go_back()">Go Back</a>

On your main controller :

$scope.go_back = function() { 
  $window.history.back();
};

When user click on Go Back link the controller function is called and it will go back to previous route.

Angular 6: How to set response type as text while making http call

On your backEnd, you should add:

@RequestMapping(value="/blabla",  produces="text/plain" , method = RequestMethod.GET)

On the frontEnd (Service):

methodBlabla() 
{
  const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');
  return this.http.get(this.url,{ headers, responseType: 'text'});
}

How to create .ipa file using Xcode?

At the time of Building select device as iOS device. Then build the application. Select Product->Archive then select Share and save the .ipa file. Rename the ipa file to .zip and double click on zip file and you will get .app file in the folder. then compress the .app file of the application and iTunesArtwork image. it will be in the format .zip rename .zip to .ipa file.

Android list view inside a scroll view

Update

<ScrollView
android:id="@+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="2"
android:fillViewport="true"
android:gravity="top" >

<LinearLayout
    android:id="@+id/foodItemActvity_linearLayout_fragments"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >
</LinearLayout>

to

<ScrollView
android:id="@+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="2"
android:fillViewport="true"
android:gravity="top" >

<LinearLayout
    android:id="@+id/foodItemActvity_linearLayout_fragments"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >
</LinearLayout>

The point here is you are trying to set height to 0dp (fixed)

Java Keytool error after importing certificate , "keytool error: java.io.FileNotFoundException & Access Denied"

If you are using windows8:

  1. Click start button
  2. In the search box, type command prompt
  3. From the result, right-click command prompt and click Run as administrator. Then execute the keytool command.

PHP errors NOT being displayed in the browser [Ubuntu 10.10]

After you edit /etc/php5/apache2/php.ini be sure to restart apache.

You can do so by running:

sudo service apache2 restart

Calendar.getInstance(TimeZone.getTimeZone("UTC")) is not returning UTC time

The System.out.println(cal_Two.getTime()) invocation returns a Date from getTime(). It is the Date which is getting converted to a string for println, and that conversion will use the default IST timezone in your case.

You'll need to explicitly use DateFormat.setTimeZone() to print the Date in the desired timezone.

EDIT: Courtesy of @Laurynas, consider this:

TimeZone timeZone = TimeZone.getTimeZone("UTC");
Calendar calendar = Calendar.getInstance(timeZone);
SimpleDateFormat simpleDateFormat = 
       new SimpleDateFormat("EE MMM dd HH:mm:ss zzz yyyy", Locale.US);
simpleDateFormat.setTimeZone(timeZone);

System.out.println("Time zone: " + timeZone.getID());
System.out.println("default time zone: " + TimeZone.getDefault().getID());
System.out.println();

System.out.println("UTC:     " + simpleDateFormat.format(calendar.getTime()));
System.out.println("Default: " + calendar.getTime());

WPF Timer Like C# Timer

The usual WPF timer is the DispatcherTimer, which is not a control but used in code. It basically works the same way like the WinForms timer:

System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += dispatcherTimer_Tick;
dispatcherTimer.Interval = new TimeSpan(0,0,1);
dispatcherTimer.Start();


private void dispatcherTimer_Tick(object sender, EventArgs e)
{
  // code goes here
}

More on the DispatcherTimer can be found here

When should I use Kruskal as opposed to Prim (and vice versa)?

The best time for Kruskal's is O(E logV). For Prim's using fib heaps we can get O(E+V lgV). Therefore on a dense graph, Prim's is much better.

Convert double to BigDecimal and set BigDecimal Precision

BigDecimal b = new BigDecimal(c).setScale(2,BigDecimal.ROUND_HALF_UP);

Format price in the current locale and currency

This is a charming answer. Work well on any currency which is selected for store.

$formattedPrice = Mage::helper('core')->currency($finalPrice, true, false);

How do I split an int into its digits?

#include <iostream>

using namespace std;

int main()

{


int n1 ;

cout <<"Please enter five digits number: ";
cin >> n1;

    cout << n1 / 10000 % 10 << " ";
    cout << n1 / 1000 % 10 << " ";
    cout << n1 / 100 % 10 << " ";
    cout << n1 / 10 % 10 << " ";
    cout << n1 % 10 << " :)";   

cout << endl;

return 0;
}

Find the server name for an Oracle database

If you don't have access to the v$ views (as suggested by Quassnoi) there are two alternatives

select utl_inaddr.get_host_name from dual

and

select sys_context('USERENV','SERVER_HOST') from dual

Personally I'd tend towards the last as it doesn't require any grants/privileges which makes it easier from stored procedures.

Iframe positioning

Try adding the css style property

position:relative;

to the div tag , it works ,

How do I connect C# with Postgres?

You want the NPGSQL library. Your only other alternative is ODBC.

Why use Gradle instead of Ant or Maven?

Gradle can be used for many purposes - it's a much better Swiss army knife than Ant - but it's specifically focused on multi-project builds.

First of all, Gradle is a dependency programming tool which also means it's a programming tool. With Gradle you can execute any random task in your setup and Gradle will make sure all declared dependecies are properly and timely executed. Your code can be spread across many directories in any kind of layout (tree, flat, scattered, ...).

Gradle has two distinct phases: evaluation and execution. Basically, during evaluation Gradle will look for and evaluate build scripts in the directories it is supposed to look. During execution Gradle will execute tasks which have been loaded during evaluation taking into account task inter-dependencies.

On top of these dependency programming features Gradle adds project and JAR dependency features by intergration with Apache Ivy. As you know Ivy is a much more powerful and much less opinionated dependency management tool than say Maven.

Gradle detects dependencies between projects and between projects and JARs. Gradle works with Maven repositories (download and upload) like the iBiblio one or your own repositories but also supports and other kind of repository infrastructure you might have.

In multi-project builds Gradle is both adaptable and adapts to the build's structure and architecture. You don't have to adapt your structure or architecture to your build tool as would be required with Maven.

Gradle tries very hard not to get in your way, an effort Maven almost never makes. Convention is good yet so is flexibility. Gradle gives you many more features than Maven does but most importantly in many cases Gradle will offer you a painless transition path away from Maven.

fastest MD5 Implementation in JavaScript

I've heard Joseph's Myers implementation is quite fast. Additionally, he has a lengthy article on Javascript optimization describing what he learned while writing his implementation. It's a good read for anyone interested in performant javascript.

http://www.webreference.com/programming/javascript/jkm3/

His MD5 implementation can be found here

How can I read Chrome Cache files?

EDIT: The below answer no longer works see here


Google Chrome cache file format description.

Cache files list, see URLs (copy and paste to your browser address bar):

  • chrome://cache/
  • chrome://view-http-cache/

Cache folder in Linux: $~/.cache/google-chrome/Default/Cache

Let's determine in file GZIP encoding:

$ head f84358af102b1064_0 | hexdump -C | grep --before-context=100 --after-context=5 "1f 8b 08"

Extract Chrome cache file by one line on PHP (without header, CRC32 and ISIZE block):

$ php -r "echo gzinflate(substr(strchr(file_get_contents('f84358af102b1064_0'), \"\x1f\x8b\x08\"), 10,
-8));"

How to remove item from a JavaScript object

_x000D_
_x000D_
var test = {'red':'#FF0000', 'blue':'#0000FF'};_x000D_
delete test.blue; // or use => delete test['blue'];_x000D_
console.log(test);
_x000D_
_x000D_
_x000D_

this deletes test.blue

How to set the default value of an attribute on a Laravel model

You can set Default attribute in Model also>

protected $attributes = [
        'status' => self::STATUS_UNCONFIRMED,
        'role_id' => self::ROLE_PUBLISHER,
    ];

You can find the details in these links

1.) How to set a default attribute value for a Laravel / Eloquent model?

2.) https://laracasts.com/index.php/discuss/channels/eloquent/eloquent-help-generating-attribute-values-before-creating-record


You can also Use Accessors & Mutators for this You can find the details in the Laravel documentation 1.) https://laravel.com/docs/4.2/eloquent#accessors-and-mutators

2.) https://scotch.io/tutorials/automatically-format-laravel-database-fields-with-accessors-and-mutators

3.) Universal accessors and mutators in Laravel 4

nano error: Error opening terminal: xterm-256color

I, too, have this problem on an older Mac that I upgraded to Lion.

Before reading the terminfo tip, I was able to get vi and less working by doing "export TERM=xterm".

After reading the tip, I grabbed /usr/share/terminfo from a newer Mac that has fresh install of Lion and does not exhibit this problem.

Now, even though echo $TERM still yields xterm-256color, vi and less now work fine.

What's a decent SFTP command-line client for windows?

This little application does the job for me. I could not find another CLI based client that would access my IIS based TLS/SSL secured ftp site: http://netwinsite.com/surgeftp/sslftp.htm

How to get cookie's expire time

It seems there's a list of all cookies sent to browser in array returned by php's headers_list() which among other data returns "Set-Cookie" elements as follows:

Set-Cookie: cooke_name=cookie_value; expires=expiration_time; Max-Age=age; path=path; domain=domain

This way you can also get deleted ones since their value is deleted:

Set-Cookie: cooke_name=deleted; expires=expiration_time; Max-Age=age; path=path; domain=domain

From there on it's easy to retrieve expiration time or age for particular cookie. Keep in mind though that this array is probably available only AFTER actual call to setcookie() has been made so it's valid for script that has already finished it's job. I haven't tested this in some other way(s) since this worked just fine for me.

This is rather old topic and I'm not sure if this is valid for all php builds but I thought it might be helpfull.

For more info see:

https://www.php.net/manual/en/function.headers-list.php
https://www.php.net/manual/en/function.headers-sent.php

Kotlin unresolved reference in IntelliJ

Another thing I would like to add is that you need to select View -> Tool Windows -> Gradle before you can run the project using the Gradle.

If using the Gradle the project builds and runs normally but using the IntelliJ it doesn't, then this can solve the matter.

Utils to read resource text file to String (Java)

Use Apache commons's FileUtils. It has a method readFileToString

mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc... expects parameter 1 to be resource

Include a connection string variable before the MySQL query. For example, $connt in this code:

$results = mysql_query($connt, "SELECT * FROM users");

How to check if an excel cell is empty using Apache POI?

Cell.getCellType() is deprecated in the latest POI API. If you are using POI API version 3.17, use the below code:

if (Cell.getCellTypeEnum() == CellType.BLANK) {
    //do your stuff here
}

Conversion failed when converting from a character string to uniqueidentifier

this fails:

 DECLARE @vPortalUID NVARCHAR(32)
 SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
 DECLARE @nPortalUID AS UNIQUEIDENTIFIER
 SET @nPortalUID = CAST(@vPortalUID AS uniqueidentifier)
 PRINT @nPortalUID

this works

 DECLARE @vPortalUID NVARCHAR(36)
 SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
 DECLARE @nPortalUID AS UNIQUEIDENTIFIER
 SET @nPortalUID = CAST(@vPortalUID AS UNIQUEIDENTIFIER)
 PRINT @nPortalUID

the difference is NVARCHAR(36), your input parameter is too small!

Remove all newlines from inside a string

Answering late since I recently had the same question when reading text from file; tried several options such as:

with open('verdict.txt') as f: 

First option below produces a list called alist, with '\n' stripped, then joins back into full text (optional if you wish to have only one text):

alist = f.read().splitlines()
jalist = " ".join(alist)

Second option below is much easier and simple produces string of text called atext replacing '\n' with space;

atext = f.read().replace('\n',' ')

It works; I have done it. This is clean, easier, and efficient.

How can I plot with 2 different y-axes?

If you can give up the scales/axis labels, you can rescale the data to (0, 1) interval. This works for example for different 'wiggle' trakcs on chromosomes, when you're generally interested in local correlations between the tracks and they have different scales (coverage in thousands, Fst 0-1).

# rescale numeric vector into (0, 1) interval
# clip everything outside the range 
rescale <- function(vec, lims=range(vec), clip=c(0, 1)) {
  # find the coeficients of transforming linear equation
  # that maps the lims range to (0, 1)
  slope <- (1 - 0) / (lims[2] - lims[1])
  intercept <- - slope * lims[1]

  xformed <- slope * vec + intercept

  # do the clipping
  xformed[xformed < 0] <- clip[1]
  xformed[xformed > 1] <- clip[2]

  xformed
}

Then, having a data frame with chrom, position, coverage and fst columns, you can do something like:

ggplot(d, aes(position)) + 
  geom_line(aes(y = rescale(fst))) + 
  geom_line(aes(y = rescale(coverage))) +
  facet_wrap(~chrom)

The advantage of this is that you're not limited to two trakcs.

How to get $HOME directory of different user in bash script?

In BASH, you can find a user's $HOME directory by prefixing the user's login ID with a tilde character. For example:

$ echo ~bob

This will echo out user bob's $HOME directory.

However, you say you want to be able to execute a script as a particular user. To do that, you need to setup sudo. This command allows you to execute particular commands as either a particular user. For example, to execute foo as user bob:

$ sudo -i -ubob -sfoo

This will start up a new shell, and the -i will simulate a login with the user's default environment and shell (which means the foo command will execute from the bob's$HOME` directory.)

Sudo is a bit complex to setup, and you need to be a superuser just to be able to see the shudders file (usually /etc/sudoers). However, this file usually has several examples you can use.

In this file, you can specify the commands you specify who can run a command, as which user, and whether or not that user has to enter their password before executing that command. This is normally the default (because it proves that this is the user and not someone who came by while the user was getting a Coke.) However, when you run a shell script, you usually want to disable this feature.

How to ensure that there is a delay before a service is started in systemd?

This answer on super user I think is a better answer. From https://superuser.com/a/573761/67952

"But since you asked for a way without using Before and After, you can use:

Type=idle

which as man systemd.service explains

Behavior of idle is very similar to simple; however, actual execution of the service program is delayed until all active jobs are dispatched. This may be used to avoid interleaving of output of shell services with the status output on the console. Note that this type is useful only to improve console output, it is not useful as a general unit ordering tool, and the effect of this service type is subject to a 5s time-out, after which the service program is invoked anyway. "

API Gateway CORS: no 'Access-Control-Allow-Origin' header

For me, the answer that FINALLY WORKED, was the comment from James Shapiro from Alex R's answer (second most upvoted). I got into this API Gateway problem in the first place, by trying to get a static webpage hosted in S3 to use lambda to process the contact-us page and send an email. Simply checking [ ] Default 4XX fixed the error message.

enter image description here

How do I work with a git repository within another repository?

I had issues with subtrees and submodules that the other answers suggest... mainly because I am using SourceTree and it seems fairly buggy.

Instead, I ended up using SymLinks and that seems to work well so I am posting it here as a possible alternative.

There is a complete guide here: http://www.howtogeek.com/howto/16226/complete-guide-to-symbolic-links-symlinks-on-windows-or-linux/

But basically you just need to mklink the two paths in an elevated command prompt. Make sure you use the /J hard link prefix. Something along these lines: mklink /J C:\projects\MainProject\plugins C:\projects\SomePlugin

You can also use relative folder paths and put it in a bat to be executed by each person when they first check out your project.

Example: mklink /J .\Assets\TaqtileTools ..\TaqtileHoloTools

Once the folder has been linked you may need to ignore the folder within your main repository that is referencing it. Otherwise you are good to go.

Note I've deleted my duplicate answer from another post as that post was marked as a duplicate question to this one.

How to create windows service from java jar?

Another option is winsw: https://github.com/kohsuke/winsw/

Configure an xml file to specify the service name, what to execute, any arguments etc. And use the exe to install. Example xml: https://github.com/kohsuke/winsw/tree/master/examples

I prefer this to nssm, because it is one lightweight exe; and the config xml is easy to share/commit to source code.

PS the service is installed by running your-service.exe install

sudo: docker-compose: command not found

If you have tried installing via the official docker-compose page, where you need to download the binary using curl:

curl -L https://github.com/docker/compose/releases/download/1.8.0/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose

Then do not forget to add executable flag to the binary:

chmod +x /usr/local/bin/docker-compose

If docker-compose is installed using python-pip

sudo apt-get -y install python-pip
sudo pip install docker-compose

try using pip show --files docker-compose to see where it is installed.

If docker-compose is installed in user path, then try:

sudo "PATH=$PATH" docker-compose

As I see from your updated post, docker-compose is installed in user path /home/user/.local/bin and if this path is not in your local path $PATH, then try:

sudo "PATH=$PATH:/home/user/.local/bin" docker-compose

How to remove old and unused Docker images

How to remove a tagged image

  1. docker rmi the tag first

  2. docker rmi the image.

    # that can be done in one docker rmi call e.g.: # docker rmi <repo:tag> <imageid>

(this works Nov 2016, Docker version 1.12.2)

e.g.

$ docker images 
REPOSITORY              TAG                 IMAGE ID            CREATED             SIZE
usrxx/the-application   16112805            011fd5bf45a2        12 hours ago        5.753 GB
usryy/the-application   vx.xx.xx            5af809583b9c        3 days ago          5.743 GB
usrzz/the-application   vx.xx.xx            eef00ce9b81f        10 days ago         5.747 GB
usrAA/the-application   vx.xx.xx            422ba91c71bb        3 weeks ago         5.722 GB
usrBB/the-application   v1.00.18            a877aec95006        3 months ago        5.589 GB

$ docker rmi usrxx/the-application:16112805 && docker rmi 011fd5bf45a2
$ docker rmi usryy/the-application:vx.xx.xx && docker rmi 5af809583b9c
$ docker rmi usrzz/the-application:vx.xx.xx eef00ce9b81f
$ docker rmi usrAA/the-application:vx.xx.xx 422ba91c71bb
$ docker rmi usrBB/the-application:v1.00.18 a877aec95006

e.g. Scripted remove anything older than 2 weeks.

IMAGESINFO=$(docker images --no-trunc --format '{{.ID}} {{.Repository}} {{.Tag}} {{.CreatedSince}}' |grep -E " (weeks|months|years)")
TAGS=$(echo "$IMAGESINFO" | awk '{ print $2 ":" $3 }' )
IDS=$(echo "$IMAGESINFO" | awk '{ print $1 }' )
echo remove old images TAGS=$TAGS IDS=$IDS
for t in $TAGS; do docker rmi $t; done
for i in $IDS; do docker rmi $i; done

jQuery "on create" event for dynamically-created elements

You can on the DOMNodeInserted event to get an event for when it's added to the document by your code.

$('body').on('DOMNodeInserted', 'select', function () {
      //$(this).combobox();
});

$('<select>').appendTo('body');
$('<select>').appendTo('body');

Fiddled here: http://jsfiddle.net/Codesleuth/qLAB2/3/

EDIT: after reading around I just need to double check DOMNodeInserted won't cause problems across browsers. This question from 2010 suggests IE doesn't support the event, so test it if you can.

See here: [link] Warning! the DOMNodeInserted event type is defined in this specification for reference and completeness, but this specification deprecates the use of this event type.

Why can't I use Docker CMD multiple times to run multiple services?

While I respect the answer from qkrijger explaining how you can work around this issue I think there is a lot more we can learn about what's going on here ...

To actually answer your question of "why" ... I think it would for helpful for you to understand how the docker stop command works and that all processes should be shutdown cleanly to prevent problems when you try to restart them (file corruption etc).

Problem: What if docker did start SSH from it's command and started RabbitMQ from your Docker file? "The docker stop command attempts to stop a running container first by sending a SIGTERM signal to the root process (PID 1) in the container." Which process is docker tracking as PID 1 that will get the SIGTERM? Will it be SSH or Rabbit?? "According to the Unix process model, the init process -- PID 1 -- inherits all orphaned child processes and must reap them. Most Docker containers do not have an init process that does this correctly, and as a result their containers become filled with zombie processes over time."

Answer: Docker simply takes that last CMD as the one that will get launched as the root process with PID 1 and get the SIGTERM from docker stop.

Suggested solution: You should use (or create) a base image specifically made for running more than one service, such as phusion/baseimage

It should be important to note that tini exists exactly for this reason, and as of Docker 1.13 and up, tini is officially part of Docker, which tells us that running more than one process in Docker IS VALID .. so even if someone claims to be more skilled regarding Docker, and insists that you absurd for thinking of doing this, know that you are not. There are perfectly valid situations for doing so.

Good to know:

Difference between app.use and app.get in express.js

app.use() is intended for binding middleware to your application. The path is a "mount" or "prefix" path and limits the middleware to only apply to any paths requested that begin with it. It can even be used to embed another application:

// subapp.js
var express = require('express');
var app = modules.exports = express();
// ...
// server.js
var express = require('express');
var app = express();

app.use('/subapp', require('./subapp'));

// ...

By specifying / as a "mount" path, app.use() will respond to any path that starts with /, which are all of them and regardless of HTTP verb used:

  • GET /
  • PUT /foo
  • POST /foo/bar
  • etc.

app.get(), on the other hand, is part of Express' application routing and is intended for matching and handling a specific route when requested with the GET HTTP verb:

  • GET /

And, the equivalent routing for your example of app.use() would actually be:

app.all(/^\/.*/, function (req, res) {
    res.send('Hello');
});

(Update: Attempting to better demonstrate the differences.)

The routing methods, including app.get(), are convenience methods that help you align responses to requests more precisely. They also add in support for features like parameters and next('route').

Within each app.get() is a call to app.use(), so you can certainly do all of this with app.use() directly. But, doing so will often require (probably unnecessarily) reimplementing various amounts of boilerplate code.

Examples:

  • For simple, static routes:

    app.get('/', function (req, res) {
      // ...
    });
    

    vs.

    app.use('/', function (req, res, next) {
      if (req.method !== 'GET' || req.url !== '/')
        return next();
    
      // ...
    });
    
  • With multiple handlers for the same route:

    app.get('/', authorize('ADMIN'), function (req, res) {
      // ...
    });
    

    vs.

    const authorizeAdmin = authorize('ADMIN');
    
    app.use('/', function (req, res, next) {
      if (req.method !== 'GET' || req.url !== '/')
        return next();
    
      authorizeAdmin(req, res, function (err) {
        if (err) return next(err);
    
        // ...
      });
    });
    
  • With parameters:

    app.get('/item/:id', function (req, res) {
      let id = req.params.id;
      // ...
    });
    

    vs.

    const pathToRegExp = require('path-to-regexp');
    
    function prepareParams(matches, pathKeys, previousParams) {
      var params = previousParams || {};
    
      // TODO: support repeating keys...
      matches.slice(1).forEach(function (segment, index) {
        let { name } = pathKeys[index];
        params[name] = segment;
      });
    
      return params;
    }
    
    const itemIdKeys = [];
    const itemIdPattern = pathToRegExp('/item/:id', itemIdKeys);
    
    app.use('/', function (req, res, next) {
      if (req.method !== 'GET') return next();
    
      var urlMatch = itemIdPattern.exec(req.url);
      if (!urlMatch) return next();
    
      if (itemIdKeys && itemIdKeys.length)
        req.params = prepareParams(urlMatch, itemIdKeys, req.params);
    
      let id = req.params.id;
      // ...
    });
    

Note: Express' implementation of these features are contained in its Router, Layer, and Route.

How can I print message in Makefile?

$(info your_text) : Information. This doesn't stop the execution.

$(warning your_text) : Warning. This shows the text as a warning.

$(error your_text) : Fatal Error. This will stop the execution.

how do I make a single legend for many subplots with matplotlib?

This answer is a complement to @Evert's on the legend position.

My first try on @Evert's solution failed due to overlaps of the legend and the subplot's title.

In fact, the overlaps are caused by fig.tight_layout(), which changes the subplots' layout without considering the figure legend. However, fig.tight_layout() is necessary.

In order to avoid the overlaps, we can tell fig.tight_layout() to leave spaces for the figure's legend by fig.tight_layout(rect=(0,0,1,0.9)).

Description of tight_layout() parameters.

Allow a div to cover the whole page instead of the area within the container

Try this

#dimScreen {
    width: 100%;
    height: 100%;
    background:rgba(255,255,255,0.5);
    position: fixed;
    top: 0;
    left: 0;
}

Javascript "Uncaught TypeError: object is not a function" associativity question

Try to have the function body before the function call in your JavaScript file.

How to create a QR code reader in a HTML5 website?

Reader they show at http://www.webqr.com/index.html works like a charm, but literaly, you need the one on the webpage, the github version it's really hard to make it work, however, it is possible. The best way to go is reverse-engineer the example shown at the webpage.

However, to edit and get the full potential out of it, it's not so easy. At some point I may post the stripped-down reverse-engineered QR reader, but in the meantime have some fun hacking the code.

Happy coding.

Where does Java's String constant pool live, the heap or the stack?

String pooling

String pooling (sometimes also called as string canonicalisation) is a process of replacing several String objects with equal value but different identity with a single shared String object. You can achieve this goal by keeping your own Map (with possibly soft or weak references depending on your requirements) and using map values as canonicalised values. Or you can use String.intern() method which is provided to you by JDK.

At times of Java 6 using String.intern() was forbidden by many standards due to a high possibility to get an OutOfMemoryException if pooling went out of control. Oracle Java 7 implementation of string pooling was changed considerably. You can look for details in http://bugs.sun.com/view_bug.do?bug_id=6962931 and http://bugs.sun.com/view_bug.do?bug_id=6962930.

String.intern() in Java 6

In those good old days all interned strings were stored in the PermGen – the fixed size part of heap mainly used for storing loaded classes and string pool. Besides explicitly interned strings, PermGen string pool also contained all literal strings earlier used in your program (the important word here is used – if a class or method was never loaded/called, any constants defined in it will not be loaded).

The biggest issue with such string pool in Java 6 was its location – the PermGen. PermGen has a fixed size and can not be expanded at runtime. You can set it using -XX:MaxPermSize=96m option. As far as I know, the default PermGen size varies between 32M and 96M depending on the platform. You can increase its size, but its size will still be fixed. Such limitation required very careful usage of String.intern – you’d better not intern any uncontrolled user input using this method. That’s why string pooling at times of Java 6 was mostly implemented in the manually managed maps.

String.intern() in Java 7

Oracle engineers made an extremely important change to the string pooling logic in Java 7 – the string pool was relocated to the heap. It means that you are no longer limited by a separate fixed size memory area. All strings are now located in the heap, as most of other ordinary objects, which allows you to manage only the heap size while tuning your application. Technically, this alone could be a sufficient reason to reconsider using String.intern() in your Java 7 programs. But there are other reasons.

String pool values are garbage collected

Yes, all strings in the JVM string pool are eligible for garbage collection if there are no references to them from your program roots. It applies to all discussed versions of Java. It means that if your interned string went out of scope and there are no other references to it – it will be garbage collected from the JVM string pool.

Being eligible for garbage collection and residing in the heap, a JVM string pool seems to be a right place for all your strings, isn’t it? In theory it is true – non-used strings will be garbage collected from the pool, used strings will allow you to save memory in case then you get an equal string from the input. Seems to be a perfect memory saving strategy? Nearly so. You must know how the string pool is implemented before making any decisions.

source.

How to check if mysql database exists

IF EXISTS (SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = N'YourDatabaseName')
BEGIN    
    -- Database exists, so do your stuff here.
END

If you are using MSSQL instead of MySQL, see this answer from a similar thread.

Run cURL commands from Windows console

I was able to use this site to easily download and install curl on my Windows machine. It took all of 30 seconds. I'm using Windows 7 (w/ Admin privelages), so I downloaded curl-7.37.0-win64.msi from http://curl.haxx.se/download.html.

Also, don't forget to restart your console/terminal after you install curl, otherwise you will get the same error messages.

Binary search (bisection) in Python

This code works with integer lists in a recursive way. Looks for the simplest case scenario, which is: list length less than 2. It means the answer is already there and a test is performed to check for the correct answer. If not, a middle value is set and tested to be the correct, if not bisection is performed by calling again the function, but setting middle value as the upper or lower limit, by shifting it to the left or right

def binary_search(intList, intValue, lowValue, highValue):
    if(highValue - lowValue) < 2:
        return intList[lowValue] == intValue or intList[highValue] == intValue
    middleValue = lowValue + ((highValue - lowValue)/2)
    if intList[middleValue] == intValue:
        return True
    if intList[middleValue] > intValue:
        return binary_search(intList, intValue, lowValue, middleValue - 1)
   return binary_search(intList, intValue, middleValue + 1, highValue)

Facebook database design?

Regarding the performance of a many-to-many table, if you have 2 32-bit ints linking user IDs, your basic data storage for 200,000,000 users averaging 200 friends apiece is just under 300GB.

Obviously, you would need some partitioning and indexing and you're not going to keep that in memory for all users.

How do you create nested dict in Python?

If you want to create a nested dictionary given a list (arbitrary length) for a path and perform a function on an item that may exist at the end of the path, this handy little recursive function is quite helpful:

def ensure_path(data, path, default=None, default_func=lambda x: x):
    """
    Function:

    - Ensures a path exists within a nested dictionary

    Requires:

    - `data`:
        - Type: dict
        - What: A dictionary to check if the path exists
    - `path`:
        - Type: list of strs
        - What: The path to check

    Optional:

    - `default`:
        - Type: any
        - What: The default item to add to a path that does not yet exist
        - Default: None

    - `default_func`:
        - Type: function
        - What: A single input function that takes in the current path item (or default) and adjusts it
        - Default: `lambda x: x` # Returns the value in the dict or the default value if none was present
    """
    if len(path)>1:
        if path[0] not in data:
            data[path[0]]={}
        data[path[0]]=ensure_path(data=data[path[0]], path=path[1:], default=default, default_func=default_func)
    else:
        if path[0] not in data:
            data[path[0]]=default
        data[path[0]]=default_func(data[path[0]])
    return data

Example:

data={'a':{'b':1}}
ensure_path(data=data, path=['a','c'], default=[1])
print(data) #=> {'a':{'b':1, 'c':[1]}}
ensure_path(data=data, path=['a','c'], default=[1], default_func=lambda x:x+[2])
print(data) #=> {'a': {'b': 1, 'c': [1, 2]}}

New line in Sql Query

-- Access: 
SELECT CHR(13) & CHR(10) 

-- SQL Server: 
SELECT CHAR(13) + CHAR(10)

How can we store into an NSDictionary? What is the difference between NSDictionary and NSMutableDictionary?

The NSDictionary and NSMutableDictionary docs are probably your best bet. They even have some great examples on how to do various things, like...

...create an NSDictionary

NSArray *keys = [NSArray arrayWithObjects:@"key1", @"key2", nil];
NSArray *objects = [NSArray arrayWithObjects:@"value1", @"value2", nil];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects 
                                                       forKeys:keys];

...iterate over it

for (id key in dictionary) {
    NSLog(@"key: %@, value: %@", key, [dictionary objectForKey:key]);
}

...make it mutable

NSMutableDictionary *mutableDict = [dictionary mutableCopy];

Note: historic version before 2010: [[dictionary mutableCopy] autorelease]

...and alter it

[mutableDict setObject:@"value3" forKey:@"key3"];

...then store it to a file

[mutableDict writeToFile:@"path/to/file" atomically:YES];

...and read it back again

NSMutableDictionary *anotherDict = [NSMutableDictionary dictionaryWithContentsOfFile:@"path/to/file"];

...read a value

NSString *x = [anotherDict objectForKey:@"key1"];

...check if a key exists

if ( [anotherDict objectForKey:@"key999"] == nil ) NSLog(@"that key is not there");

...use scary futuristic syntax

From 2014 you can actually just type dict[@"key"] rather than [dict objectForKey:@"key"]

Using GroupBy, Count and Sum in LINQ Lambda Expressions

var boxSummary = from b in boxes
                 group b by b.Owner into g
                 let nrBoxes = g.Count()
                 let totalWeight = g.Sum(w => w.Weight)
                 let totalVolume = g.Sum(v => v.Volume)
                 select new { Owner = g.Key, Boxes = nrBoxes,
                              TotalWeight = totalWeight,
                              TotalVolume = totalVolume }

How to hide Android soft keyboard on EditText

Three ways based on the same simple instruction:

a). Results as easy as locate (1):

android:focusableInTouchMode="true"

among the configuration of any precedent element in the layout, example:

if your whole layout is composed of:

<ImageView>

<EditTextView>

<EditTextView>

<EditTextView>

then you can write the (1) among ImageView parameters and this will grab android's attention to the ImageView instead of the EditText.

b). In case you have another precedent element than an ImageView you may need to add (2) to (1) as:

android:focusable="true"

c). you can also simply create an empty element at the top of your view elements:

<LinearLayout
  android:focusable="true"
  android:focusableInTouchMode="true"
  android:layout_width="0px"
  android:layout_height="0px" />

This alternative until this point results as the simplest of all I've seen. Hope it helps...

Deserialize JSON with C#

You can use this extensions

public static class JsonExtensions
{
   public static T ToObject<T>(this string jsonText)
   {
       return JsonConvert.DeserializeObject<T>(jsonText);
   }

   public static string ToJson<T>(this T obj)
   {
       return JsonConvert.SerializeObject(obj);
   }
}

How to pass command line arguments to a rake task

While passing parameters, it is better option is an input file, can this be a excel a json or whatever you need and from there read the data structure and variables you need from that including the variable name as is the need. To read a file can have the following structure.

  namespace :name_sapace_task do
    desc "Description task...."
      task :name_task  => :environment do
        data =  ActiveSupport::JSON.decode(File.read(Rails.root+"public/file.json")) if defined?(data)
    # and work whit yoour data, example is data["user_id"]

    end
  end

Example json

{
  "name_task": "I'm a task",
  "user_id": 389,
  "users_assigned": [389,672,524],
  "task_id": 3
}

Execution

rake :name_task 

How to compare different branches in Visual Studio Code

Update: As of November, 2020, Gitlens appears within VSCode's builtin Source Control Panel

I would recommend to use: Git Lens.

enter image description here

How to check if BigDecimal variable == 0 in java?

You would want to use equals() since they are objects, and utilize the built in ZERO instance:

if (selectPrice.equals(BigDecimal.ZERO))

Note that .equals() takes scale into account, so unless selectPrice is the same scale (0) as .ZERO then this will return false.

To take scale out of the equation as it were:

if (selectPrice.compareTo(BigDecimal.ZERO) == 0)

I should note that for certain mathematical situations, 0.00 != 0, which is why I imagine .equals() takes the scale into account. 0.00 gives precision to the hundredths place, whereas 0 is not that precise. Depending on the situation you may want to stick with .equals().

How do I execute a file in Cygwin?

just type ./a in the shell

How do I use a Boolean in Python?

Yes, there is a bool data type (which inherits from int and has only two values: True and False).

But also Python has the boolean-able concept for every object, which is used when function bool([x]) is called.

See more: object.nonzero and boolean-value-of-objects-in-python.

What is the __del__ method, How to call it?

As mentioned earlier, the __del__ functionality is somewhat unreliable. In cases where it might seem useful, consider using the __enter__ and __exit__ methods instead. This will give a behaviour similar to the with open() as f: pass syntax used for accessing files. __enter__ is automatically called when entering the scope of with, while __exit__ is automatically called when exiting it. See this question for more details.

Has been blocked by CORS policy: Response to preflight request doesn’t pass access control check

For anyone looking at this and had no result with adding the Access-Control-Allow-Origin try also adding the Access-Control-Allow-Headers. May safe somebody from a headache.

Android: how to refresh ListView contents?

To those still having problems, I solved it this way:

List<Item> newItems = databaseHandler.getItems();
ListArrayAdapter.clear();
ListArrayAdapter.addAll(newItems);
ListArrayAdapter.notifyDataSetChanged();
databaseHandler.close();

I first cleared the data from the adapter, then added the new collection of items, and only then set notifyDataSetChanged(); This was not clear for me at first, so I wanted to point this out. Take note that without calling notifyDataSetChanged() the view won't be updated.

Support for the experimental syntax 'classProperties' isn't currently enabled

Change

"plugins": [
    "@babel/plugin-proposal-class-properties"
  ]

To

"plugins": [
    [
      "@babel/plugin-proposal-class-properties",
      {
        "loose": true
      }
    ]
  ]

This worked for me

How can I submit a POST form using the <a href="..."> tag?

In case you use MVC to accomplish it - you will have to do something like this

 <form action="/ControllerName/ActionName" method="post">
        <a href="javascript:;" onclick="parentNode.submit();"><%=n%></a>
        <input type="hidden" name="mess" value=<%=n%>/>
    </form>

I just went through some examples here and did not see the MVC one figured it won't hurt to post it.

Then on your Action in the Controller I would just put <HTTPPost> On the top of it. I believe if you don't have <HTTPGET> on the top of it it would still work but explicitly putting it there feels a bit safer.

Activate a virtualenv with a Python script

The simplest solution to run your script under virtualenv's interpreter is to replace the default shebang line with path to your virtualenv's interpreter like so at the beginning of the script:

#!/path/to/project/venv/bin/python

Make the script executable:

chmod u+x script.py

Run the script:

./script.py

Voila!

How can I check if a directory exists?

According to man(2)stat you can use the S_ISDIR macro on the st_mode field:

bool isdir = S_ISDIR(st.st_mode);

Side note, I would recommend using Boost and/or Qt4 to make cross-platform support easier if your software can be viable on other OSs.

How to make Java work with SQL Server?

If you are use sqljdbc4.jar, use the following code

ResultSet objResultSet = objPreparedStatement.getResultSet();
if (objResultSet == null) {
  boolean bResult = false;
  while (!bResult){
    if (objPreparedStatement.getMoreResults()){
      objResultSet = objPreparedStatement.getResultSet();
      bResult = true;
    }
  } 
}
objCachedRowSet = new CachedRowSetImpl();
objCachedRowSet.populate(objResultSet);
if (CommonUtility.isValidObject(objResultSet)) objResultSet.close();
objResultSet = null;

How do I subtract minutes from a date in javascript?

Once you know this:

  • You can create a Date by calling the constructor with milliseconds since Jan 1, 1970.
  • The valueOf() a Date is the number of milliseconds since Jan 1, 1970
  • There are 60,000 milliseconds in a minute :-]

...it isn't so hard.

In the code below, a new Date is created by subtracting the appropriate number of milliseconds from myEndDateTime:

var MS_PER_MINUTE = 60000;
var myStartDate = new Date(myEndDateTime - durationInMinutes * MS_PER_MINUTE);

jquery stop child triggering parent event

The simplest solution is to add this CSS to the children:

.your-child {
    pointer-events: none;
}

How to refresh a page with jQuery by passing a parameter to URL

if window.location.hash is empty, you cant assign to location.href a new value without using a correct function (at least tested in chrome).

try the window.location.replace:

if (!window.location.hash) 
    {
        window.location.replace(window.location.href + "?single")
    } 

mysqli_connect(): (HY000/2002): No connection could be made because the target machine actively refused it

If you look at your XAMPP Control Panel, it's clearly stated that the port to the MySQL server is 3306 - you provided 3360. The 3306 is default, and thus doesn't need to be specified. Even so, the 5th parameter of mysqli_connect() is the port, which is where it should be specified.

You could just remove the port specification altogether, as you're using the default port, making it

$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$db     = 'test_db13';

References

Where can I find Android source code online?

Everything is mirrored on omapzoom.org. Some of the code is also mirrored on github.

Contacts is here for example.

Since December 2019, you can use the new official public code search tool for AOSP: cs.android.com. There's also the Android official source browser (based on Gitiles) has a web view of many of the different parts that make up android. Some of the projects (such as Kernel) have been removed and it now only points you to clonable git repositories.

To get all the code locally, you can use the repo helper program, or you can just clone individual repositories.

And others:

What is the purpose and uniqueness SHTML?

SHTML is a file extension that lets the web server know the file should be processed as using Server Side Includes (SSI).

(HTML is...you know what it is, and DHTML is Microsoft's name for Javascript+HTML+CSS or something).

You can use SSI to include a common header and footer in your pages, so you don't have to repeat code as much. Changing one included file updates all of your pages at once. You just put it in your HTML page as per normal.

It's embedded in a standard XML comment, and looks like this:

<!--#include virtual="top.shtml" -->

It's been largely superseded by other mechanisms, such as PHP includes, but some hosting packages still support it and nothing else.

You can read more in this Wikipedia article.

Renaming branches remotely in Git

Adding to the answers already given, here is a version that first checks whether the new branch already exists (so you can safely use it in a script)

if git ls-remote --heads "$remote" \
    | cut -f2 \
    | sed 's:refs/heads/::' \
    | grep -q ^"$newname"$; then
    echo "Error: $newname already exists"
    exit 1
fi
git push "$oldname" "$remote/$oldname:refs/heads/$newname" ":$oldname"

(the check is from this answer)

How to download/checkout a project from Google Code in Windows?

If you don't want to install TortoiseSVN, you can simply install 'Subversion for Windows' from here:

http://sourceforge.net/projects/win32svn/

After installing, just open up a command prompt, go the folder you want to download into, then past in the checkout command as indicated on the project's 'source' page. E.g.

svn checkout http://projectname.googlecode.com/svn/trunk/ projectname-read-only

Note the space between the URL and the last string is intentional, the last string is the folder name into which the source will be downloaded.

How to query as GROUP BY in django?

An easy solution, but not the proper way is to use raw SQL:

results = Members.objects.raw('SELECT * FROM myapp_members GROUP BY designation')

Another solution is to use the group_by property:

query = Members.objects.all().query
query.group_by = ['designation']
results = QuerySet(query=query, model=Members)

You can now iterate over the results variable to retrieve your results. Note that group_by is not documented and may be changed in future version of Django.

And... why do you want to use group_by? If you don't use aggregation, you can use order_by to achieve an alike result.

LINQ query to return a Dictionary<string, string>

Use the ToDictionary method directly.

var result = 
  // as Jon Skeet pointed out, OrderBy is useless here, I just leave it 
  // show how to use OrderBy in a LINQ query
  myClassCollection.OrderBy(mc => mc.SomePropToSortOn)
                   .ToDictionary(mc => mc.KeyProp.ToString(), 
                                 mc => mc.ValueProp.ToString(), 
                                 StringComparer.OrdinalIgnoreCase);

File Upload to HTTP server in iphone programming

I have made a lightweight backup method for the Mobile-AppSales app available at github

I wrote about it here http://memention.com/blog/2009/11/22/Lightweight-backup.html

Look for the - (void)startUpload method in ReportManager.m

How do I check that multiple keys are in a dict in a single pass?

>>> if 'foo' in foo and 'bar' in foo:
...     print 'yes'
... 
yes

Jason, () aren't necessary in Python.

How to load a resource from WEB-INF directory of a web archive

Use the getResourceAsStream() method on the ServletContext object, e.g.

servletContext.getResourceAsStream("/WEB-INF/myfile");

How you get a reference to the ServletContext depends on your application... do you want to do it from a Servlet or from a JSP?

EDITED: If you're inside a Servlet object, then call getServletContext(). If you're in JSP, use the predefined variable application.

Inserting a tab character into text using C#

Using Microsoft Winform controls, it is impossible to solve correctly your problem without an little workaround that I will explain below.

PROBLEM

The problem in using simply "\t" or vbTab is that when more than one TextBox are displayed and that alignment must be respected for all TextBox, the ONLY "\t" or vbTab solution will display something that is NOT ALWAYS correctly aligned.

Example in VB.Net:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    TextBox1.Text = "Bernard" + vbTab + "32"
    TextBox2.Text = "Luc" + vbTab + "47"
    TextBox3.Text = "François-Victor" + vbTab + "12"
End Sub

will display

enter image description here

as you can see, age value for François-Victor is shifted to the right and is not aligned with age value of two others TextBox.

SOLUTION

To solve this problem, you must set Tabs position using a specific SendMessage() user32.dll API function as shown below.

Public Class Form1

    Public Declare Function SendMessage _
        Lib "user32" Alias "SendMessageA" _
        ( ByVal hWnd As IntPtr _
        , ByVal wMsg As Integer _
        , ByVal wParam As Integer _
        , ByVal lParam() As Integer _
        ) As Integer

    Private Const EM_SETTABSTOPS As Integer = &HCB

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim tabs() As Integer = {4 * 25}

        TextBox1.Text = "Bernard" + vbTab + "32"
        SendMessage(TextBox1.Handle, EM_SETTABSTOPS, 1, tabs)
        TextBox2.Text = "Luc" + vbTab + "47"
        SendMessage(TextBox2.Handle, EM_SETTABSTOPS, 1, tabs)
        TextBox3.Text = "François-Victor" + vbTab + "12"
        SendMessage(TextBox3.Handle, EM_SETTABSTOPS, 1, tabs)
    End Sub

End Class

and following Form will be displayed

enter image description here

You can see that now, all value are correctly aligned :-)

REMARKS

Multiline property of the TextBox must be set to True. If this properties is set to False, the Tab is positioned as before.

How AcceptsTab property is assigned is not important (I have tested).

This question has already be treated on StackOverflow

Caution: the mesure Unit for Tab position is not character but something that seems to be 1/4 of character. That is why I multiply the length by 4.

C# SOLUTION

using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        [DllImport("User32.dll", CharSet = CharSet.Auto)]
        private static extern IntPtr SendMessage(IntPtr h, int msg, int wParam, uint[] lParam);
        private const int EM_SETTABSTOPS = 0x00CB;
        private const char vbTab = '\t';

        public Form1()
        {
            InitializeComponent();

            var tabs = new uint[] { 25 * 4 };

            textBox1.Text = "Bernard" + vbTab + "32";
            SendMessage(textBox1.Handle, EM_SETTABSTOPS, 1, tabs);
            textBox2.Text = "Luc" + vbTab + "47";
            SendMessage(textBox2.Handle, EM_SETTABSTOPS, 1, tabs);
            textBox3.Text = "François-Victor" + vbTab + "12";
            SendMessage(textBox3.Handle, EM_SETTABSTOPS, 1, tabs);
        }
    }
}

' << ' operator in verilog

1 << ADDR_WIDTH means 1 will be shifted 8 bits to the left and will be assigned as the value for RAM_DEPTH.

In addition, 1 << ADDR_WIDTH also means 2^ADDR_WIDTH.

Given ADDR_WIDTH = 8, then 2^8 = 256 and that will be the value for RAM_DEPTH

Iterating over JSON object in C#

dynamic dynJson = JsonConvert.DeserializeObject(json);
foreach (var item in dynJson)
{
    Console.WriteLine("{0} {1} {2} {3}\n", item.id, item.displayName, 
        item.slug, item.imageUrl);
}

or

var list = JsonConvert.DeserializeObject<List<MyItem>>(json);

public class MyItem
{
    public string id;
    public string displayName;
    public string name;
    public string slug;
    public string imageUrl;
}

VBA test if cell is in a range

I don't work with contiguous ranges all the time. My solution for non-contiguous ranges is as follows (includes some code from other answers here):

Sub test_inters()
    Dim rng1 As Range
    Dim rng2 As Range
    Dim inters As Range

    Set rng2 = Worksheets("Gen2").Range("K7")
    Set rng1 = ExcludeCell(Worksheets("Gen2").Range("K6:K8"), rng2)

    If (rng2.Parent.name = rng1.Parent.name) Then
        Dim ints As Range
        MsgBox rng1.Address & vbCrLf _
        & rng2.Address & vbCrLf _

        For Each cell In rng1
            MsgBox cell.Address
            Set ints = Application.Intersect(cell, rng2)
            If (Not (ints Is Nothing)) Then
                MsgBox "Yes intersection"
            Else
                MsgBox "No intersection"
            End If
        Next cell
    End If
End Sub

How to prevent robots from automatically filling up a form?

Its just an idea, id used that in my application and works well

you can create a cookie on mouse movement with javascript or jquery and in server side check if cookie exist, because only humans have mouse, cookie can be created only by them the cookie can be a timestamp or a token that can be validate

How do I remove all non-ASCII characters with regex and Notepad++?

In Notepad++, if you go to menu Search ? Find characters in range ? Non-ASCII Characters (128-255) you can then step through the document to each non-ASCII character.

Be sure to tick off "Wrap around" if you want to loop in the document for all non-ASCII characters.

screenshot "Find in Range"

Trigger a button click with JavaScript on the Enter key in a text box

In modern, undeprecated (without keyCode or onkeydown) Javascript:

<input onkeypress="if(event.key == 'Enter') {console.log('Test')}">

Mysql: Select all data between two dates

its very easy to handle this situation

You can use BETWEEN CLAUSE in combination with date_sub( now( ) , INTERVAL 30 DAY ) AND NOW( )

SELECT
    sc_cust_design.design_id as id,
    sc_cust_design.main_image,
    FROM
    sc_cust_design
WHERE
    sc_cust_design.publish = 1 
    AND **`datein`BETWEEN date_sub( now( ) , INTERVAL 30 DAY ) AND NOW( )**

Happy Coding :)

Locating child nodes of WebElements in selenium

According to JavaDocs, you can do this:

WebElement input = divA.findElement(By.xpath(".//input"));

How can I ask in xpath for "the div-tag that contains a span with the text 'hello world'"?

WebElement elem = driver.findElement(By.xpath("//div[span[text()='hello world']]"));

The XPath spec is a suprisingly good read on this.

jQuery Datepicker onchange event issue

Manual says:

apply.daterangepicker: Triggered when the apply button is clicked, or when a predefined range is clicked

So:

$('#daterange').daterangepicker({
  locale: { cancelLabel: 'Clear' }  
});

$('#daterange').on('apply.daterangepicker', function() {
  alert('worked!');
});

Works for me.

Why do some functions have underscores "__" before and after the function name?

From the Python PEP 8 -- Style Guide for Python Code:

Descriptive: Naming Styles

The following special forms using leading or trailing underscores are recognized (these can generally be combined with any case convention):

  • _single_leading_underscore: weak "internal use" indicator. E.g. from M import * does not import objects whose name starts with an underscore.

  • single_trailing_underscore_: used by convention to avoid conflicts with Python keyword, e.g.

    Tkinter.Toplevel(master, class_='ClassName')

  • __double_leading_underscore: when naming a class attribute, invokes name mangling (inside class FooBar, __boo becomes _FooBar__boo; see below).

  • __double_leading_and_trailing_underscore__: "magic" objects or attributes that live in user-controlled namespaces. E.g. __init__, __import__ or __file__. Never invent such names; only use them as documented.

Note that names with double leading and trailing underscores are essentially reserved for Python itself: "Never invent such names; only use them as documented".

Difference between clustered and nonclustered index

faster to read than non cluster as data is physically storted in index order we can create only one per table.(cluster index)

quicker for insert and update operation than a cluster index. we can create n number of non cluster index.

Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 1, column 4 (Year)

My guess is it's an encoding problem, for instance your file is UTF-8 but SQL will not read it the way it should, so it attempts to insert 100ÿ or something along these lines into your table.

Possible fixes:

  1. Specify Codepage
  2. Change the Encoding of the source using Powershell

Code samples:

1.
BULK INSERT myTable FROM 'c:\Temp\myfile.csv' WITH (
  FIELDTERMINATOR = '£',
  ROWTERMINATOR = '\n',
  CODEPAGE = 'ACP' -- ACP corresponds to ANSI, also try UTF-8 or 65001 for Unicode
);

2.
get-content "myfile.csv" | Set-content -Path "myfile.csv" -Encoding String
# String = ANSI, also try Ascii, Oem, Unicode, UTF7, UTF8, UTF32

R dates "origin" must be supplied

I suspect you meant:

axis.Date(1, as.Date(sites$date, origin = "1970-01-01"))

as the 'x' argument to as.Date() has to be of type Date.

As an aside, this would have appropriate as a follow-up or edit of your previous question.

Is it possible to open developer tools console in Chrome on Android phone?

I you only want to see what was printed in the console you could simple add the "printed" part somewhere in your HTML so it will appear in on the webpage. You could do it for yourself, but there is a javascript file that does this for you. You can read about it here:

http://www.hnldesign.nl/work/code/mobileconsole-javascript-console-for-mobile-devices/

The code is available from Github; you can download it and paste it into a javascipt file and add it in to your HTML

I don't have "Dynamic Web Project" option in Eclipse new Project wizard

Fwiw, I downloaded the standard Java EE version of the Mars version of Eclipse, and ran into the same deal -- didn't see a Web option if I tried File >>> New >>> Project wizard.

The good news: Probably no extra installation needed.

It looks like what I wanted was to select the Other option rather than the Project item (strangely this is what comes up when you hit Ctrl-N, but that also lets us know we're probably on the right track):

Screenshot of the new project menu hierarchy with "Other" highlighted.

After you select "Other", you'll see the "Select a wizard" screen, where you can select "Dynamic Web Project" and profit.

Dynamic Web Project highlighted in Select a wizard screen.

How to check null objects in jQuery

What about using "undefined"?

if (value != undefined){ // do stuff } 

Error message "Forbidden You don't have permission to access / on this server"

Remember that the correct file to be configured in this situation is not the httpd.conf in the phpMyAdmin alias, but in bin/apache/your_version/conf/httpd.conf.

Look for the following line:

DocumentRoot "c:/wamp/www/"

#
# Each directory to which Apache has access can be configured with respect
# to which services and features are allowed and/or disabled in that
# directory (and its subdirectories).
#
# First, we configure the "default" to be a very restrictive set of
# features.
#
<Directory />
    Options FollowSymLinks
    AllowOverride None
    Order deny,allow
    Allow from all
</Directory>

Make sure it is set to Allow from all...

If not, phpMyAdmin might even work, but not your root and other folders under it. Also, remember to restart WAMP and then put online...

This solved my headache.

Android Fragment handle back button press

For Those Who Use Static Fragment

In a case if you have a static fragment then It would be preferable. Make an instance object of your fragment

private static MyFragment instance=null;

in onCreate() of MyFragment initialize that instance

  instance=this;

also make a function to get Instance

 public static MyFragment getInstance(){
   return instance;
}

also make functions

public boolean allowBackPressed(){
    if(allowBack==true){
        return true;
    }
    return false;
}


 //allowBack is a boolean variable that will be set to true at the action 
 //where you want that your backButton should not close activity. In my case I open 
 //Navigation Drawer then I set it to true. so when I press backbutton my 
 //drawer should be get closed

public void performSomeAction(){
    //.. Your code
    ///Here I have closed my drawer
}

In Your Activity You can do

@Override
public void onBackPressed() {

    if (MyFragment.getInstance().allowBackPressed()) { 
        MyFragment.getInstance().performSomeAction();
    }
    else{
        super.onBackPressed();
    }
}

Preview an image before it is uploaded

The answer of LeassTaTT works well in "standard" browsers like FF and Chrome. The solution for IE exists but looks different. Here description of cross-browser solution:

In HTML we need two preview elements, img for standard browsers and div for IE

HTML:

<img id="preview" 
     src="" 
     alt="" 
     style="display:none; max-width: 160px; max-height: 120px; border: none;"/>

<div id="preview_ie"></div>

In CSS we specify the following IE specific thing:

CSS:

#preview_ie {
  FILTER: progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)
}  

In HTML we include the standard and the IE-specific Javascripts:

<script type="text/javascript">
  {% include "pic_preview.js" %}
</script>  
<!--[if gte IE 7]> 
<script type="text/javascript">
  {% include "pic_preview_ie.js" %}
</script>

The pic_preview.js is the Javascript from the LeassTaTT's answer. Replace the $('#blah') whith the $('#preview') and add the $('#preview').show()

Now the IE specific Javascript (pic_preview_ie.js):

function readURL (imgFile) {    
  var newPreview = document.getElementById('preview_ie');
  newPreview.filters.item('DXImageTransform.Microsoft.AlphaImageLoader').src = imgFile.value;
  newPreview.style.width = '160px';
  newPreview.style.height = '120px';
}    

That's is. Works in IE7, IE8, FF and Chrome. Please test in IE9 and report. The idea of IE preview was found here: http://forums.asp.net/t/1320559.aspx

http://msdn.microsoft.com/en-us/library/ms532969(v=vs.85).aspx

How to resume Fragment from BackStack if exists

getFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {

    @Override
    public void onBackStackChanged() {

        if(getFragmentManager().getBackStackEntryCount()==0) {
            onResume();
        }    
    }
});

How can I compare strings in C using a `switch` statement?

There is a way to perform the string search faster. Assumptions: since we are talking about a switch statement, I can assume that the values won't be changing during runtime.

The idea is to use the C stdlib's qsort and bsearch.

I'll be working on xtofl's code.

struct stringcase { char* string; void (*func)(void); };

void funcB1();
void funcAzA();

struct stringcase cases [] = 
{ { "B1", funcB1 }
, { "AzA", funcAzA }
};

struct stringcase work_cases* = NULL;
int work_cases_cnt = 0;

// prepare the data for searching
void prepare() {
  // allocate the work_cases and copy cases values from it to work_cases
  qsort( cases, i, sizeof( struct stringcase ), stringcase_cmp );
}

// comparator function
int stringcase_cmp( const void *p1, const void *p2 )
{
  return strcasecmp( ((struct stringcase*)p1)->string, ((struct stringcase*)p2)->string);
}

// perform the switching
void myswitch( char* token ) {
  struct stringcase val;
  val.string=token;
  void* strptr = bsearch( &val, work_cases, work_cases_cnt, sizeof( struct stringcase), stringcase_cmp );
  if (strptr) {
    struct stringcase* foundVal = (struct stringcase*)strptr;
    (*foundVal->func)();
    return OK;
  }
  return NOT_FOUND;
}

Download single files from GitHub

To follow up with what thomasfuchs said but instead for GitHub Enterprise users here's what you can use.

curl -H 'Authorization: token INSERTACCESSTOKENHERE' -H 'Accept: application/vnd.github.v3.raw' -O -L https://your_domain/api/v3/repos/owner/repo/contents/path

Also here's the API documentation https://developer.github.com/v3/repos/contents

How to get the list of properties of a class?

That's my solution

public class MyObject
{
    public string value1 { get; set; }
    public string value2 { get; set; }

    public PropertyInfo[] GetProperties()
    {
        try
        {
            return this.GetType().GetProperties();
        }
        catch (Exception ex)
        {

            throw ex;
        }
    }

    public PropertyInfo GetByParameterName(string ParameterName)
    {
        try
        {
            return this.GetType().GetProperties().FirstOrDefault(x => x.Name == ParameterName);
        }
        catch (Exception ex)
        {

            throw ex;
        }
    }

    public static MyObject SetValue(MyObject obj, string parameterName,object parameterValue)
    {
        try
        {
            obj.GetType().GetProperties().FirstOrDefault(x => x.Name == parameterName).SetValue(obj, parameterValue);
            return obj;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}

WebRTC vs Websockets: If WebRTC can do Video, Audio, and Data, why do I need Websockets?

WebSockets:

  • Ratified IETF standard (6455) with support across all modern browsers and even legacy browsers using web-socket-js polyfill.

  • Uses HTTP compatible handshake and default ports making it much easier to use with existing firewall, proxy and web server infrastructure.

  • Much simpler browser API. Basically one constructor with a couple of callbacks.

  • Client/browser to server only.

  • Only supports reliable, in-order transport because it is built On TCP. This means packet drops can delay all subsequent packets.

WebRTC:

  • Just beginning to be supported by Chrome and Firefox. MS has proposed an incompatible variant. The DataChannel component is not yet compatible between Firefox and Chrome.

  • WebRTC is browser to browser in ideal circumstances but even then almost always requires a signaling server to setup the connections. The most common signaling server solutions right now use WebSockets.

  • Transport layer is configurable with application able to choose if connection is in-order and/or reliable.

  • Complex and multilayered browser API. There are JS libs to provide a simpler API but these are young and rapidly changing (just like WebRTC itself).

How can I display the current branch and folder path in terminal?

For Mac Catilina 10.15.5 and later version:

add in your ~/.zshrc file

function parse_git_branch() {
    git branch 2> /dev/null | sed -n -e 's/^\* \(.*\)/[\1]/p'
}

setopt PROMPT_SUBST
export PROMPT='%F{grey}%n%f %F{cyan}%~%f %F{green}$(parse_git_branch)%f %F{normal}$%f '

How do I draw a set of vertical lines in gnuplot?

To elaborate on previous answers about the "every x units" part, here is what I came up with:

# Draw 5 vertical lines
n = 5

# ... evenly spaced between x0 and x1
x0 = 1.0
x1 = 2.0
dx = (x1-x0)/(n-1.0)

# ... each line going from y0 to y1
y0 = 0
y1 = 10

do for [i = 0:n-1] {
    x = x0 + i*dx
    set arrow from x,y0 to x,y1 nohead linecolor "blue" # add other styling options if needed
}

Git Clone from GitHub over https with two-factor authentication

As per @Nitsew's answer, Create your personal access token and use your token as your username and enter with blank password.

Later you won't need any credentials to access all your private repo(s).

python: create list of tuples from lists

You're after the zip function.

Taken directly from the question: How to merge lists into a list of tuples in Python?

>>> list_a = [1, 2, 3, 4]
>>> list_b = [5, 6, 7, 8]
>>> zip(list_a,list_b)
[(1, 5), (2, 6), (3, 7), (4, 8)]

Selecting specific rows and columns from NumPy array

Using np.ix_ is the most convenient way to do it (as answered by others), but here is another interesting way to do it:

>>> rows = [0, 1, 3]
>>> cols = [0, 2]

>>> a[rows].T[cols].T

array([[ 0,  2],
       [ 4,  6],
       [12, 14]])

Display JSON Data in HTML Table

Please use datatable if you want to get result from json object. Datatable also works in the same manner of converting the json result into table format with the facility of searchable and sortable columns automatically.

Adding images to an HTML document with javascript

With a little research i found that javascript does not know that a Document Object Exist unless the Object has Already loaded before the script code (As javascript reads down a page).

<head>
    <script type="text/javascript">
        function insert(){
            var src = document.getElementById("gamediv");
            var img = document.createElement("img");
            img.src = "img/eqp/"+this.apparel+"/"+this.facing+"_idle.png";
            src.appendChild(img);
        }
     </script>
 </head>
 <body>
     <div id="gamediv">
         <script type="text/javascript">
             insert();
         </script>
     </div>
 </body>

Merge some list items in a Python List

That example is pretty vague, but maybe something like this?

items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
items[3:6] = [''.join(items[3:6])]

It basically does a splice (or assignment to a slice) operation. It removes items 3 to 6 and inserts a new list in their place (in this case a list with one item, which is the concatenation of the three items that were removed.)

For any type of list, you could do this (using the + operator on all items no matter what their type is):

items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
items[3:6] = [reduce(lambda x, y: x + y, items[3:6])]

This makes use of the reduce function with a lambda function that basically adds the items together using the + operator.

Can the "IN" operator use LIKE-wildcards (%) in Oracle?

Select * from myTable m
where m.status not like 'Done%' 
and m.status not like 'Finished except%'
and m.status not like 'In Progress%'

offsetting an html anchor to adjust for fixed header

how about hidden span tags with linkable IDs that provide the height of the navbar:

#head1 {
  padding-top: 60px;
  height: 0px;
  visibility: hidden;
}


<span class="head1">somecontent</span>
<h5 id="headline1">This Headline is not obscured</h5>

heres the fiddle: http://jsfiddle.net/N6f2f/7

How can I get argv[] as int?

/*

    Input from command line using atoi, and strtol 
*/

#include <stdio.h>//printf, scanf
#include <stdlib.h>//atoi, strtol 

//strtol - converts a string to a long int 
//atoi - converts string to an int 

int main(int argc, char *argv[]){

    char *p;//used in strtol 
    int i;//used in for loop

    long int longN = strtol( argv[1],&p, 10);
    printf("longN = %ld\n",longN);

    //cast (int) to strtol
    int N = (int) strtol( argv[1],&p, 10);
    printf("N = %d\n",N);

    int atoiN;
    for(i = 0; i < argc; i++)
    {
        //set atoiN equal to the users number in the command line 
        //The C library function int atoi(const char *str) converts the string argument str to an integer (type int).
        atoiN = atoi(argv[i]);
    }

    printf("atoiN = %d\n",atoiN);
    //-----------------------------------------------------//
    //Get string input from command line 
    char * charN;

    for(i = 0; i < argc; i++)
    {
        charN = argv[i];
    }

    printf("charN = %s\n", charN); 

}

Hope this helps. Good luck!

How to present popover properly in iOS 8

The following has a pretty comprehensive guide on how to configure and present popovers. https://www.appcoda.com/presentation-controllers-tutorial/

In summary, a viable implementation (with some updates from the original article syntax for Swift 4.2), to then be called from elsewhere, would be something like the following:

func showPopover(ofViewController popoverViewController: UIViewController, originView: UIView) {
    popoverViewController.modalPresentationStyle = UIModalPresentationStyle.popover
    if let popoverController = popoverViewController.popoverPresentationController {
        popoverController.delegate = self
        popoverController.sourceView = originView
        popoverController.sourceRect = originView.bounds
        popoverController.permittedArrowDirections = UIPopoverArrowDirection.any
    }
    self.present(popoverViewController, animated: true)
}

A lot of this was already covered in the answer from @mmc, but the article helps to explain some of those code elements used, and also show how it could be expanded.

It also provides a lot of additional detail about using delegation to handle the presentation style for iPhone vs. iPad, and to allow dismissal of the popover if it's ever shown full-screen. Again, updated for Swift 4.2:

func adaptivePresentationStyle(for: UIPresentationController) -> UIModalPresentationStyle {
    //return UIModalPresentationStyle.fullScreen
    return UIModalPresentationStyle.none
}

func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
    if traitCollection.horizontalSizeClass == .compact {
        return UIModalPresentationStyle.none
        //return UIModalPresentationStyle.fullScreen
    }
    //return UIModalPresentationStyle.fullScreen
    return UIModalPresentationStyle.none
}

func presentationController(_ controller: UIPresentationController, viewControllerForAdaptivePresentationStyle style: UIModalPresentationStyle) -> UIViewController? {
    switch style {
    case .fullScreen:
        let navigationController = UINavigationController(rootViewController: controller.presentedViewController)
        let doneButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.done, target: self, action: #selector(doneWithPopover))
        navigationController.topViewController?.navigationItem.rightBarButtonItem = doneButton
        return navigationController
    default:
        return controller.presentedViewController
    }
}

// As of Swift 4, functions used in selectors must be declared as @objc
@objc private func doneWithPopover() {
    self.dismiss(animated: true, completion: nil)
}

Hope this helps.

SQL Server datetime LIKE select?

There is a very flaky coverage of the LIKE operator for dates in SQL Server. It only works using American date format. As an example you could try:

... WHERE register_date LIKE 'oct 10 2009%'

I've tested this in SQL Server 2005 and it works, but you'll really need to try different combinations. Odd things I have noticed are:

  • You only seem to get all or nothing for different sub fields within the date, for instance, if you search for 'apr 2%' you only get anything in the 20th's - it omits 2nd's.

  • Using a single underscore '_' to represent a single (wildcard) character does not wholly work, for instance, WHERE mydate LIKE 'oct _ 2010%' will not return all dates before the 10th - it returns nothing at all, in fact!

  • The format is rigid American: 'mmm dd yyyy hh:mm'

I have found it difficult to nail down a process for LIKEing seconds, so if anyone wants to take this a bit further, be my guest!

Hope this helps.

Why does this CSS margin-top style not work?

Not exactly sure why, but changing the inner CSS to

display: inline-block;

seems to work.

How to sort an array of objects by multiple fields?

Here's an extensible way to sort by multiple fields.

homes.sort(function(left, right) {
    var city_order = left.city.localeCompare(right.city);
    var price_order = parseInt(left.price) - parseInt(right.price);
    return city_order || -price_order;
});

Notes

  • A function passed to array sort is expected to return negative, zero, positive to indicate less, equal, greater.
  • a.localeCompare(b) is universally supported for strings, and returns -1,0,1 if a<b,a==b,a>b.
  • Subtraction works on numeric fields, because a - b gives -,0,+ if a<b,a==b,a>b.
  • || in the last line gives city priority over price.
  • Negate to reverse order in any field, as in -price_order
  • Date comparison, var date_order = new Date(left.date) - new Date(right.date); works like numerics because date math turns into milliseconds since 1970.
  • Add fields into the or-chain, return city_order || -price_order || date_order;
  • Subtraction works on boolean. I suggest you make it explicit, var goodness_order = Boolean(left.is_good) - Boolean(right.is_good)

Client on Node.js: Uncaught ReferenceError: require is not defined

ES6: In HTML, include the main JavaScript file using attribute type="module" (browser support):

<script type="module" src="script.js"></script>

And in the script.js file, include another file like this:

import { hello } from './module.js';
...
// alert(hello());

Inside the included file (module.js), you must export the function/class that you will import:

export function hello() {
    return "Hello World";
}

A working example is here. More information is here.

Array Length in Java

First of all, length is a property, so it would be arr.length instead of arr.length().

And it will return 10, the declared size. The elements that you do not declare explicitely are initialized with 0.

How do I retrieve the number of columns in a Pandas data frame?

df.info() function will give you result something like as below. If you are using read_csv method of Pandas without sep parameter or sep with ",".

raw_data = pd.read_csv("a1:\aa2/aaa3/data.csv")
raw_data.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 5144 entries, 0 to 5143
Columns: 145 entries, R_fighter to R_age

What data type to use for hashed password field and what length?

Update: Simply using a hash function is not strong enough for storing passwords. You should read the answer from Gilles on this thread for a more detailed explanation.

For passwords, use a key-strengthening hash algorithm like Bcrypt or Argon2i. For example, in PHP, use the password_hash() function, which uses Bcrypt by default.

$hash = password_hash("rasmuslerdorf", PASSWORD_DEFAULT);

The result is a 60-character string similar to the following (but the digits will vary, because it generates a unique salt).

$2y$10$.vGA1O9wmRjrwAVXD98HNOgsNpDczlqm3Jq7KnEd1rVAGv3Fykk1a

Use the SQL data type CHAR(60) to store this encoding of a Bcrypt hash. Note this function doesn't encode as a string of hexadecimal digits, so we can't as easily unhex it to store in binary.

Other hash functions still have uses, but not for storing passwords, so I'll keep the original answer below, written in 2008.


It depends on the hashing algorithm you use. Hashing always produces a result of the same length, regardless of the input. It is typical to represent the binary hash result in text, as a series of hexadecimal digits. Or you can use the UNHEX() function to reduce a string of hex digits by half.

  • MD5 generates a 128-bit hash value. You can use CHAR(32) or BINARY(16)
  • SHA-1 generates a 160-bit hash value. You can use CHAR(40) or BINARY(20)
  • SHA-224 generates a 224-bit hash value. You can use CHAR(56) or BINARY(28)
  • SHA-256 generates a 256-bit hash value. You can use CHAR(64) or BINARY(32)
  • SHA-384 generates a 384-bit hash value. You can use CHAR(96) or BINARY(48)
  • SHA-512 generates a 512-bit hash value. You can use CHAR(128) or BINARY(64)
  • BCrypt generates an implementation-dependent 448-bit hash value. You might need CHAR(56), CHAR(60), CHAR(76), BINARY(56) or BINARY(60)

As of 2015, NIST recommends using SHA-256 or higher for any applications of hash functions requiring interoperability. But NIST does not recommend using these simple hash functions for storing passwords securely.

Lesser hashing algorithms have their uses (like internal to an application, not for interchange), but they are known to be crackable.

Could not find folder 'tools' inside SDK

My solution was to remove the Eclipse ADT plugin via menu "Help > About Eclipse SDK > Installation Details". Eclipse will restart.

Next go to Menu "Help > Install New Software", then add the ADT plugin url "https://dl-ssl.google.com/android/eclipse" (or select the existing link from the dropdown).

This will re-install the latest ADT, including the DDMS files.

Bridged networking not working in Virtualbox under Windows 10

WINDOWS FIX: Ive' Fixed it by downloading a new VMbox installer from the Official Website Here.

  • Just run the installer and install it to override your current VMBox version, that should fix it.

Dont worry about your VM's they will not disappear if you override your current installation.

NOTE: If you already have the latest version, you need to export all your VM's, unninstall your current VMBox and install it from new installer.

How to implement common bash idioms in Python?

pythonpy is a tool that provides easy access to many of the features from awk and sed, but using python syntax:

$ echo me2 | py -x 're.sub("me", "you", x)'
you2

Converting an array to a function arguments list

@bryc - yes, you could do it like this:

Element.prototype.setAttribute.apply(document.body,["foo","bar"])

But that seems like a lot of work and obfuscation compared to:

document.body.setAttribute("foo","bar")

Python Inverse of a Matrix

If you hate numpy, get out RPy and your local copy of R, and use it instead.

(I would also echo to make you you really need to invert the matrix. In R, for example, linalg.solve and the solve() function don't actually do a full inversion, since it is unnecessary.)

Evaluate a string with a switch in C++

A switch statement can only be used for integral values, not for values of user-defined type. And even if it could, your input operation doesn't work, either.

You might want this:

#include <string>
#include <iostream>


std::string input;

if (!std::getline(std::cin, input)) { /* error, abort! */ }

if (input == "Option 1")
{
    // ... 
}
else if (input == "Option 2")
{ 
   // ...
}

// etc.

Posting array from form

Why are you sending it through a post if you already have it on the server (PHP) side?

Why not just save the array to the $_SESSION variable so you can use it when the form gets submitted, that might make it more "secure" since then the client cannot change the variables by editing the source.

It will depend upon how you really want to do.

Curl to return http status code along with the response

I was able to get a solution by looking at the curl doc which specifies to use - for the output to get the output to stdout.

curl -o - http://localhost

To get the response with just the http return code, I could just do

curl -o /dev/null -s -w "%{http_code}\n" http://localhost

React: trigger onChange if input value is changing by state?

you must do 4 following step :

  1. create event

    var event = new Event("change",{
        detail: {
            oldValue:yourValueVariable,
            newValue:!yourValueVariable
        },
        bubbles: true,
        cancelable: true
    });
    event.simulated = true;
    let tracker = this.yourComponentDomRef._valueTracker;
    if (tracker) {
        tracker.setValue(!yourValueVariable);
    }
    
  2. bind value to component dom

    this.yourComponentDomRef.value = !yourValueVariable;
    
  3. bind element onchange to react onChange function

     this.yourComponentDomRef.onchange = (e)=>this.props.onChange(e);
    
  4. dispatch event

    this.yourComponentDomRef.dispatchEvent(event);
    

in above code yourComponentDomRef refer to master dom of your React component for example <div className="component-root-dom" ref={(dom)=>{this.yourComponentDomRef= dom}}>

Programmatically shut down Spring Boot application

The simplest way would be to inject the following object where you need to initiate the shutdown

ShutdownManager.java

import org.springframework.context.ApplicationContext;
import org.springframework.boot.SpringApplication;

@Component
class ShutdownManager {

    @Autowired
    private ApplicationContext appContext;

    /*
     * Invoke with `0` to indicate no error or different code to indicate
     * abnormal exit. es: shutdownManager.initiateShutdown(0);
     **/
    public void initiateShutdown(int returnCode){
        SpringApplication.exit(appContext, () -> returnCode);
    }
}

JavaFX Location is not set error message

I've had the same issue in my JavaFX Application. Even more weird: In my Windows developement environment everything worked fine with the fxml loader. But when I executed the exact same code on my Debian maschine, I got similar errors with "location not set".

I read all answers here, but none seemed to really "solve" the problem. My solution was easy and I hope it helps some of you:

Maybe Java gets confused, by the getClass() method. If something runs in different threads or your class implements any interfaces, it may come to the point, that a different class than yours is returned by the getClass() method. In this case, your relative path to creatProduct.fxml will be wrong, because your "are" not in the path you think you are...

So to be on the save side: Be more specific and try use the static class field on your Class (Note the YourClassHere.class).

@FXML
public void gotoCreateProduct(ActionEvent event) throws IOException {
   Stage stage = new Stage();
    stage.setTitle("Shop Management");
    FXMLLoader myLoader = new FXMLLoader(YourClassHere.class.getResource("creatProduct.fxml"));
    Pane myPane = (Pane) myLoader.load();            
    Scene scene = new Scene(myPane);
    stage.setScene(scene);
    prevStage.close();
    setPrevStage(stage);
    stage.show();      
}

After realizing this, I will ALWAYS do it like this. Hope that helps!

PHP: If internet explorer 6, 7, 8 , or 9

PHP has a function called get_browser() that will return an object (or array if you so choose) with details about the users' browser and what it can do.

A simple look through gave me this code:

$browser = get_browser( null, true );
if( $browser['name'] == "Firefox" )
    if( $browser['majorversion'] == 4 )
        echo "You're using Firefox version 4!";

This is not a surefire way (as it reads from HTTP_USER_AGENT, which can be spoofed, and will sometimes be analyzed wrong by php), but it's the easiest one that you can find as far as I know.

Stopping a JavaScript function when a certain condition is met

The return statement exits a function from anywhere within the function:

function something(x)
{
    if (x >= 10)
        // this leaves the function if x is at least 10.
        return;

    // this message displays only if x is less than 10.
    alert ("x is less than 10!");
}

Where can I find a list of escape characters required for my JSON ajax return type?

As explained in the section 9 of the official ECMA specification (http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf) in JSON, the following chars have to be escaped:

  • U+0022 (", the quotation mark)
  • U+005C (\, the backslash or reverse solidus)
  • U+0000 to U+001F (the ASCII control characters)

In addition, in order to safely embed JSON in HTML, the following chars have to be also escaped:

  • U+002F (/)
  • U+0027 (')
  • U+003C (<)
  • U+003E (>)
  • U+0026 (&)
  • U+0085 (Next Line)
  • U+2028 (Line Separator)
  • U+2029 (Paragraph Separator)

Some of the above characters can be escaped with the following short escape sequences defined in the standard:

  • \" represents the quotation mark character (U+0022).
  • \\ represents the reverse solidus character (U+005C).
  • \/ represents the solidus character (U+002F).
  • \b represents the backspace character (U+0008).
  • \f represents the form feed character (U+000C).
  • \n represents the line feed character (U+000A).
  • \r represents the carriage return character (U+000D).
  • \t represents the character tabulation character (U+0009).

The other characters which need to be escaped will use the \uXXXX notation, that is \u followed by the four hexadecimal digits that encode the code point.

The \uXXXX can be also used instead of the short escape sequence, or to optionally escape any other character from the Basic Multilingual Plane (BMP).

Omitting one Setter/Getter in Lombok

According to @Data description you can use:

All generated getters and setters will be public. To override the access level, annotate the field or class with an explicit @Setter and/or @Getter annotation. You can also use this annotation (by combining it with AccessLevel.NONE) to suppress generating a getter and/or setter altogether.

Combining two lists and removing duplicates, without removing duplicates in original list

resulting_list = first_list + [i for i in second_list if i not in first_list]

intellij idea - Error: java: invalid source release 1.9

intellij-invalid-source

You've to set the JAVA SDK and appropriate language level in the project settings. Click to enlarge.

src absolute path problem

I think because C would be seen the C drive on the client pc, it wont let you. And if it could do this, it would be a big security hole.

How to change menu item text dynamically in Android

I use this code to costum my bottom navigation item

BottomNavigationView navigation = this.findViewById(R.id.my_bottom_navigation);
Menu menu = navigation.getMenu();
menu.findItem(R.id.nav_wall_see).setTitle("Hello");

add commas to a number in jQuery

Number(10000).toLocaleString('en');  // "10,000"

What is the proper way to display the full InnerException?

Just use exception.ToString()

http://msdn.microsoft.com/en-us/library/system.exception.tostring.aspx

The default implementation of ToString obtains the name of the class that threw the current exception, the message, the result of calling ToString on the inner exception, and the result of calling Environment.StackTrace. If any of these members is null, its value is not included in the returned string.

If there is no error message or if it is an empty string (""), then no error message is returned. The name of the inner exception and the stack trace are returned only if they are not null.

exception.ToString() will also call .ToString() on that exception's inner exception, and so on...

Make a simple fade in animation in Swift?

The problem is that you're trying start the animation too early in the view controller's lifecycle. In viewDidLoad, the view has just been created, and hasn't yet been added to the view hierarchy, so attempting to animate one of its subviews at this point produces bad results.

What you really should be doing is continuing to set the alpha of the view in viewDidLoad (or where you create your views), and then waiting for the viewDidAppear: method to be called. At this point, you can start your animations without any issue.

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    UIView.animate(withDuration: 1.5) {
        self.myFirstLabel.alpha = 1.0
        self.myFirstButton.alpha = 1.0
        self.mySecondButton.alpha = 1.0
    }
}

How can I get a precise time, for example in milliseconds in Objective-C?

For those we need the Swift version of the answer of @Jeff Thompson:

// Get a current time for where you want to start measuring from
var date = NSDate()

// do work...

// Find elapsed time and convert to milliseconds
// Use (-) modifier to conversion since receiver is earlier than now
var timePassed_ms: Double = date.timeIntervalSinceNow * -1000.0

I hope this help you.

Server cannot set status after HTTP headers have been sent IIS7.5

We were getting the same error - so this may be useful to some.

For us the cause was super simple. An interface change confused an end user and they were pressing the back button in the browser at a 'bad' time after a form submission (sure we should probably have used a PRG pattern, but we didn't).

We fixed the issue and the user is no longer pressing the back button. Problem solved.

I'm trying to use python in powershell

To be able to use Python immediately without restarting the shell window you need to change the path for the machine, the process and the user.

Function Get-EnvVariableNameList {
    [cmdletbinding()]
    $allEnvVars = Get-ChildItem Env:
    $allEnvNamesArray = $allEnvVars.Name
    $pathEnvNamesList = New-Object System.Collections.ArrayList
    $pathEnvNamesList.AddRange($allEnvNamesArray)
    return ,$pathEnvNamesList
}

Function Add-EnvVarIfNotPresent {
Param (
[string]$variableNameToAdd,
[string]$variableValueToAdd
   ) 
    $nameList = Get-EnvVariableNameList
    $alreadyPresentCount = ($nameList | Where{$_ -like $variableNameToAdd}).Count
    #$message = ''
    if ($alreadyPresentCount -eq 0)
    {
    [System.Environment]::SetEnvironmentVariable($variableNameToAdd, $variableValueToAdd, [System.EnvironmentVariableTarget]::Machine)
    [System.Environment]::SetEnvironmentVariable($variableNameToAdd, $variableValueToAdd, [System.EnvironmentVariableTarget]::Process)
    [System.Environment]::SetEnvironmentVariable($variableNameToAdd, $variableValueToAdd, [System.EnvironmentVariableTarget]::User)
        $message = "Enviromental variable added to machine, process and user to include $variableNameToAdd"
    }
    else
    {
        $message = 'Environmental variable already exists. Consider using a different function to modify it'
    }
    Write-Information $message
}


Function Get-EnvExtensionList {
    $pathExtArray =  ($env:PATHEXT).Split("{;}")
    $pathExtList = New-Object System.Collections.ArrayList
    $pathExtList.AddRange($pathExtArray)
    return ,$pathExtList
}


Function Add-EnvExtension {
Param (
[string]$pathExtToAdd
   ) 
    $pathList = Get-EnvExtensionList
    $alreadyPresentCount = ($pathList | Where{$_ -like $pathToAdd}).Count
    if ($alreadyPresentCount -eq 0)
    {
        $pathList.Add($pathExtToAdd)
        $returnPath = $pathList -join ";"
        [System.Environment]::SetEnvironmentVariable('pathext', $returnPath, [System.EnvironmentVariableTarget]::Machine)
        [System.Environment]::SetEnvironmentVariable('pathext', $returnPath, [System.EnvironmentVariableTarget]::Process)
        [System.Environment]::SetEnvironmentVariable('pathext', $returnPath, [System.EnvironmentVariableTarget]::User)
        $message = "Path extension added to machine, process and user paths to include $pathExtToAdd"
    }
    else
    {
        $message = 'Path extension already exists'
    }
    Write-Information $message
}

Function Get-EnvPathList {
    [cmdletbinding()]
    $pathArray =  ($env:PATH).Split("{;}")
    $pathList = New-Object System.Collections.ArrayList
    $pathList.AddRange($pathArray)
    return ,$pathList
}

Function Add-EnvPath {
Param (
[string]$pathToAdd
   ) 
    $pathList = Get-EnvPathList
    $alreadyPresentCount = ($pathList | Where{$_ -like $pathToAdd}).Count
    if ($alreadyPresentCount -eq 0)
    {
        $pathList.Add($pathToAdd)
        $returnPath = $pathList -join ";"
        [System.Environment]::SetEnvironmentVariable('path', $returnPath, [System.EnvironmentVariableTarget]::Machine)
        [System.Environment]::SetEnvironmentVariable('path', $returnPath, [System.EnvironmentVariableTarget]::Process)
        [System.Environment]::SetEnvironmentVariable('path', $returnPath, [System.EnvironmentVariableTarget]::User)
        $message = "Path added to machine, process and user paths to include $pathToAdd"
    }
    else
    {
        $message = 'Path already exists'
    }
    Write-Information $message
}

Add-EnvExtension '.PY'
Add-EnvExtension '.PYW'
Add-EnvPath 'C:\Python27\'

How to sort an array in Bash

Another solution that uses external sort and copes with any special characters (except for NULs :)). Should work with bash-3.2 and GNU or BSD sort (sadly, POSIX doesn't include -z).

local e new_array=()
while IFS= read -r -d '' e; do
    new_array+=( "${e}" )
done < <(printf "%s\0" "${array[@]}" | LC_ALL=C sort -z)

First look at the input redirection at the end. We're using printf built-in to write out the array elements, zero-terminated. The quoting makes sure array elements are passed as-is, and specifics of shell printf cause it to reuse the last part of format string for each remaining parameter. That is, it's equivalent to something like:

for e in "${array[@]}"; do
    printf "%s\0" "${e}"
done

The null-terminated element list is then passed to sort. The -z option causes it to read null-terminated elements, sort them and output null-terminated as well. If you needed to get only the unique elements, you can pass -u since it is more portable than uniq -z. The LC_ALL=C ensures stable sort order independently of locale — sometimes useful for scripts. If you want the sort to respect locale, remove that.

The <() construct obtains the descriptor to read from the spawned pipeline, and < redirects the standard input of the while loop to it. If you need to access the standard input inside the pipe, you may use another descriptor — exercise for the reader :).

Now, back to the beginning. The read built-in reads output from the redirected stdin. Setting empty IFS disables word splitting which is unnecessary here — as a result, read reads the whole 'line' of input to the single provided variable. -r option disables escape processing that is undesired here as well. Finally, -d '' sets the line delimiter to NUL — that is, tells read to read zero-terminated strings.

As a result, the loop is executed once for every successive zero-terminated array element, with the value being stored in e. The example just puts the items in another array but you may prefer to process them directly :).

Of course, that's just one of the many ways of achieving the same goal. As I see it, it is simpler than implementing complete sorting algorithm in bash and in some cases it will be faster. It handles all special characters including newlines and should work on most of the common systems. Most importantly, it may teach you something new and awesome about bash :).