Programs & Examples On #Qualified name

css overflow - only 1 line of text

if addition please, if you have a long text please you can use this css code bellow;

text-overflow: ellipsis;
overflow: visible;
white-space: nowrap;

make the whole line text visible.

creating json object with variables

It's called on Object Literal

I'm not sure what you want your structure to be, but according to what you have above, where you put the values in variables try this.

var formObject =  {"formObject": [
                {"firstName": firstName, "lastName": lastName},
                {"phoneNumber": phone},
                {"address": address},
                ]}

Although this seems to make more sense (Why do you have an array in the above literal?):

var formObject = {
   firstName: firstName
   ...
}

Necessary to add link tag for favicon.ico?

Please note that both the HTML5 specification of W3C and WhatWG standardize

<link rel="icon" href="/favicon.ico">

Note the value of the "rel" attribute!

The value shortcut icon for the rel attribute is a very old Internet Explorer specific extension and deprecated.

So please consider not using it any more and updating your files so they are standards compliant and are displayed correctly in all browsers.

You might also want to take a look at this great post: rel="shortcut icon" considered harmful

ArithmeticException: "Non-terminating decimal expansion; no exact representable decimal result"

Answer for BigDecimal throws ArithmeticException

public static void main(String[] args) {
        int age = 30;
        BigDecimal retireMentFund = new BigDecimal("10000.00");
        retireMentFund.setScale(2,BigDecimal.ROUND_HALF_UP);
        BigDecimal yearsInRetirement = new BigDecimal("20.00");
        String name = " Dennis";
        for ( int i = age; i <=65; i++){
            recalculate(retireMentFund,new BigDecimal("0.10"));
        }
        BigDecimal monthlyPension =   retireMentFund.divide(
                yearsInRetirement.divide(new BigDecimal("12"), new MathContext(2, RoundingMode.CEILING)), new MathContext(2, RoundingMode.CEILING));      
        System.out.println(name+ " will have £" + monthlyPension +" per month for retirement");
    }
public static void recalculate (BigDecimal fundAmount, BigDecimal rate){
        fundAmount.multiply(rate.add(new BigDecimal("1.00")));
    }

Add MathContext object in your divide method call and adjust precision and rounding mode. This should fix your problem

What does SQL clause "GROUP BY 1" mean?

In addition to grouping by the field name, you may also group by ordinal, or position of the field within the table. 1 corresponds to the first field (regardless of name), 2 is the second, and so on.

This is generally ill-advised if you're grouping on something specific, since the table/view structure may change. Additionally, it may be difficult to quickly comprehend what your SQL query is doing if you haven’t memorized the table fields.

If you are returning a unique set, or quickly performing a temporary lookup, this is nice shorthand syntax to reduce typing. If you plan to run the query again at some point, I’d recommend replacing those to avoid future confusion and unexpected complications (due to scheme changes).

Cannot find "Package Explorer" view in Eclipse

You might be in debug mode. If this is the problem, you can simply click on the "Java" button (next to the "Debug" button) in the upper-right hand corner, or click on "Open Perspective" and then select "Java (default)" from the "Open Perspective" window.

How do I use WPF bindings with RelativeSource?

Here's a more visual explanation in the context of a MVVM architecture:

enter image description here

How do we download a blob url video

I just came up with a general solution, which should work on most websites. I tried this on Chrome only, but this method should work with any other browser, though, as Dev Tools are pretty much the same in them all.

Steps:

  1. Open the browser's Dev Tools (usually F12, or Ctrl-Shift-I, or right-click and then Inspect in the popup menu) on the page with the video you are interested in.
  2. Go to Network tab and then reload the page. The tab will get populated with a list of requests (may be up to a hundred of them or even more).
  3. Search through the names of requests and find the request with .m3u8 extension. There may be many of them, but most likely the first you find is the one you are looking for. It may have any name, e.g. playlist.m3u8.
  4. Open the request and under Headers subsection you will see request's full URL in Request URL field. Copy it. enter image description here
  5. Extract the video from m3u8. There are many ways to do it, I'll give you those I tried, but you can google more by "download video from m3u8".
    • Option 1. If you have VLC player installed, feed the URL to VLC using "Open Network Stream..." menu option. I'm not going to go into details on this part here, there are a number of comprehensive guides in many places, for example, here. If the page doesn't work, you can always google another one by "vlc download online video".
    • Option 2. If you are more into command line, use FFMPEG or your own script, as directed in this SuperUser question.

Keep a line of text as a single line - wrap the whole line or none at all

You could also put non-breaking spaces (&nbsp;) in lieu of the spaces so that they're forced to stay together.

How do I wrap this line of text
-&nbsp;asked&nbsp;by&nbsp;Peter&nbsp;2&nbsp;days&nbsp;ago

Illegal mix of collations MySQL Error

I found that using cast() was the best solution for me:

cast(Format(amount, "Standard") AS CHAR CHARACTER SET utf8) AS Amount

There is also a convert() function. More details on it here

Another resource here

PHP mkdir: Permission denied problem

I have this problem just now, my best solution I can give to you right now (despite that you didn't include any of your code) would be:

  1. Check how you name your destination folder, eg: new_folder (sometimes this can cause error for permission as most hosts don't allow names using underscore, dash, etc to be created at run time). It worked for me.
  2. If you were using recursive command to create sub-folders don't forget to put 0755 (remember to include 0 at the start) to the mkdir command, eg:

    if(!file_exists($output)){
        if (!mkdir($output, 0755, true)) {//0755
            die('Failed to create folders...');
        }
    
    }
    

This is also worked for me just now.

how to generate public key from windows command prompt

Humm, what? ssh is not something built in to Windows like in most *nix cases.

You'd probably want to use Putty to begin with. And: http://kb.siteground.com/how_to_generate_an_ssh_key_on_windows_using_putty/

python pandas extract year from datetime: df['year'] = df['date'].year is not working

Probably already too late to answer but since you have already parse the dates while loading the data, you can just do this to get the day

df['date'] = pd.DatetimeIndex(df['date']).year

Batch: Remove file extension

I'm also a stranger to windows cmd, but try this:

echo %%~nf

Changing the width of Bootstrap popover

You can adjust the width of the popover with methods indicated above, but the best thing to do is to define the width of the content before Bootstrap sees is and does its math. For instance, I had a table, I defined it's width, then bootstrap built a popover to suit it. (Sometimes Bootstrap has trouble determining the width, and you need to step in and hold its hand)

android button selector

You can use this code:

<Button
android:id="@+id/img_sublist_carat"
android:layout_width="70dp"
android:layout_height="68dp"
android:layout_centerVertical="true"
android:layout_marginLeft="625dp"
android:contentDescription=""
android:background="@drawable/img_sublist_carat_selector"
android:visibility="visible" />

(Selector File) img_sublist_carat_selector.xml:

<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
 <item android:state_focused="true" 
       android:state_pressed="true"        
       android:drawable="@drawable/img_sublist_carat_highlight" />
 <item android:state_pressed="true" 
       android:drawable="@drawable/img_sublist_carat_highlight" />
 <item android:drawable="@drawable/img_sublist_carat_normal" />
</selector>

Error message "unreported exception java.io.IOException; must be caught or declared to be thrown"

The error message means that any method that calls showfile() must either declare that it, in turn, throws IOException, or the call must be inside a try block that catches IOException. When you call showfile(), you do neither of these; for example, your filecontent constructor neither declares IOException nor contains a try block.

The intent is that some method, somewhere, should contain a try block, and catch and handle this exception. The compiler is trying to force you to handle the exception somewhere.

By the way, this code is (sorry to be so blunt) horrible. You don't close any of the files you open, the BufferedReader always points to the first file, even though you seem to be trying to make it point to another, the loops contain off-by-one errors that will cause various exceptions, etc. When you do get this to compile, it will not work as you expect. I think you need to slow down a little.

How can I select item with class within a DIV?

Try:

$('#mydiv').find('.myclass');

JS Fiddle demo.

Or:

$('.myclass','#mydiv');

JS Fiddle demo.

Or:

$('#mydiv .myclass');

JS Fiddle demo.

References:


Good to learn from the find() documentation:

The .find() and .children() methods are similar, except that the latter only travels a single level down the DOM tree.

How do you get the file size in C#?

Size on disk might be different, if you move the file to another filesystem (FAT16, NTFS, EXT3, etc)

As other answerers have said, this will give you the size in bytes, not the size on disk.

Remove a cookie

See the sample labelled "Example #2 setcookie() delete example" from the PHP docs. To clear a cookie from the browser, you need to tell the browser that the cookie has expired... the browser will then remove it. unset as you've used it just removes the 'hello' cookie from the COOKIE array.

Return a "NULL" object if search result not found

You can easily create a static object that represents a NULL return.

class Attr;
extern Attr AttrNull;

class Node { 
.... 

Attr& getAttribute(const string& attribute_name) const { 
   //search collection 
   //if found at i 
        return attributes[i]; 
   //if not found 
        return AttrNull; 
} 

bool IsNull(const Attr& test) const {
    return &test == &AttrNull;
}

 private: 
   vector<Attr> attributes; 
};

And somewhere in a source file:

static Attr AttrNull;

How do format a phone number as a String in Java?

I'd have thought you need to use a MessageFormat rather than DecimalFormat. That should be more flexible.

Function overloading in Python: Missing

You can pass a mutable container datatype into a function, and it can contain anything you want.

If you need a different functionality, name the functions differently, or if you need the same interface, just write an interface function (or method) that calls the functions appropriately based on the data received.

It took a while to me to get adjusted to this coming from Java, but it really isn't a "big handicap".

How to launch html using Chrome at "--allow-file-access-from-files" mode?

That flag is dangerous!! Leaves your file system open for access. Documents originating from anywhere, local or web, should not, by default, have any access to local file:/// resources.

Much better solution is to run a little http server locally.

--- For Windows ---

The easiest is to install http-server globally using node's package manager:

npm install -g http-server

Then simply run http-server in any of your project directories:

Eg. d:\my_project> http-server

Starting up http-server, serving ./
Available on:
 http:169.254.116.232:8080
 http:192.168.88.1:8080
 http:192.168.0.7:8080
 http:127.0.0.1:8080
Hit CTRL-C to stop the server

Or as prusswan suggested, you can also install Python under windows, and follow the instructions below.

--- For Linux ---

Since Python is usually available in most linux distributions, just run python -m SimpleHTTPServer in your project directory, and you can load your page on http://localhost:8000

In Python 3 the SimpleHTTPServer module has been merged into http.server, so the new command is python3 -m http.server.

Easy, and no security risk of accidentally leaving your browser open vulnerable.

How to get the absolute path to the public_html folder?

with preg_replace function to find absolute path from __FILE__ you can easily find with anything home user. Here short my code :

$path_image_you_want = preg_replace('#/public_html/([^/]+?)/.*#', '/public_html/$1/images", __FILE__);

Can I fade in a background image (CSS: background-image) with jQuery?

This is what worked for my, and its pure css


css

html {
    padding: 0;
    margin: 0;
    width: 100%;
    height: 100%;
  }

  body {
    padding: 0;
    margin: 0;
    width: 100%;
    height: 100%;
  }

  #bg {
    width: 100%;
    height: 100%;
    background: url('/image.jpg/') no-repeat center center fixed;

    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;

    -webkit-animation: myfirst 5s ; /* Chrome, Safari, Opera */
    animation: myfirst 5s ;
  }

  /* Chrome, Safari, Opera */
  @-webkit-keyframes myfirst {
    from {opacity: 0.2;}
    to {opacity: 1;}
  }

  /* Standard syntax */
  @keyframes myfirst {
    from {opacity: 0.2;}
    to {opacity: 1;}
  }

html

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
  <div id="bg">
    <!-- content here -->
  </div> <!-- end bg -->
</body>
</html>

Subtract minute from DateTime in SQL Server 2005

You want to use DATEADD, using a negative duration. e.g.

DATEADD(minute, -15, '2000-01-01 08:30:00') 

TypeError: method() takes 1 positional argument but 2 were given

In my case, I forgot to add the ()

I was calling the method like this

obj = className.myMethod

But it should be is like this

obj = className.myMethod()

Convert SVG image to PNG with PHP

I do not know of a standalone PHP / Apache solution, as this would require a PHP library that can read and render SVG images. I'm not sure such a library exists - I don't know any.

ImageMagick is able to rasterize SVG files, either through the command line or the PHP binding, IMagick, but seems to have a number of quirks and external dependencies as shown e.g. in this forum thread. I think it's still the most promising way to go, it's the first thing I would look into if I were you.

Package signatures do not match the previously installed version

If the version of the app that you have installed was not built with the same keystore/signing certificate it will have a different signature. By default each build machine will have a different debug certificate unless you specify how it should be signed according to the google documentation, which can be used to ensure that your app will be build with the same debug key regardless of which computer you build the application on.

In order to proceed with the installation you must uninstall the existing version and then try again.

Regular expression to match any character being repeated more than 10 times

A slightly more generic powershell example. In powershell 7, the match is highlighted including the last space (can you highlight in stack?).

'a b c d e f ' | select-string '([a-f] ){6,}'

a b c d e f 

Total number of items defined in an enum

From the previous answers just adding code sample.

 class Program
    {
        static void Main(string[] args)
        {
            int enumlen = Enum.GetNames(typeof(myenum)).Length;
            Console.Write(enumlen);
            Console.Read();
        }
        public enum myenum
        {
            value1,
            value2
        }
    }

Implement a loading indicator for a jQuery AJAX call

I solved the same problem following this example:

This example uses the jQuery JavaScript library.

First, create an Ajax icon using the AjaxLoad site.
Then add the following to your HTML :

<img src="/images/loading.gif" id="loading-indicator" style="display:none" />

And the following to your CSS file:

#loading-indicator {
  position: absolute;
  left: 10px;
  top: 10px;
}

Lastly, you need to hook into the Ajax events that jQuery provides; one event handler for when the Ajax request begins, and one for when it ends:

$(document).ajaxSend(function(event, request, settings) {
    $('#loading-indicator').show();
});

$(document).ajaxComplete(function(event, request, settings) {
    $('#loading-indicator').hide();
});

This solution is from the following link. How to display an animated icon during Ajax request processing

Convert data.frame column format from character to factor

I've doing it with a function. In this case I will only transform character variables to factor:

for (i in 1:ncol(data)){
    if(is.character(data[,i])){
        data[,i]=factor(data[,i])
    }
}

How to resolve merge conflicts in Git repository?

CoolAJ86's answer sums up pretty much everything. In case you have changes in both branches in the same piece of code you will have to do a manual merge. Open the file in conflict in any text editor and you should see following structure.

(Code not in Conflict)
>>>>>>>>>>>
(first alternative for conflict starts here)
Multiple code lines here
===========
(second alternative for conflict starts here)
Multiple code lines here too    
<<<<<<<<<<<
(Code not in conflict here)

Choose one of the alternatives or a combination of both in a way that you want new code to be, while removing equal signs and angle brackets.

git commit -a -m "commit message"
git push origin master

Difference between pre-increment and post-increment in a loop?

As this code shows (see the dissambled MSIL in the comments), the C# 3 compiler makes no distinction between i++ and ++i in a for loop. If the value of i++ or ++i were being taken, there would definitely be a difference (this was compiled in Visutal Studio 2008 / Release Build):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PreOrPostIncrement
{
    class Program
    {
        static int SomethingToIncrement;

        static void Main(string[] args)
        {
            PreIncrement(1000);
            PostIncrement(1000);
            Console.WriteLine("SomethingToIncrement={0}", SomethingToIncrement);
        }

        static void PreIncrement(int count)
        {
            /*
            .method private hidebysig static void  PreIncrement(int32 count) cil managed
            {
              // Code size       25 (0x19)
              .maxstack  2
              .locals init ([0] int32 i)
              IL_0000:  ldc.i4.0
              IL_0001:  stloc.0
              IL_0002:  br.s       IL_0014
              IL_0004:  ldsfld     int32 PreOrPostIncrement.Program::SomethingToIncrement
              IL_0009:  ldc.i4.1
              IL_000a:  add
              IL_000b:  stsfld     int32 PreOrPostIncrement.Program::SomethingToIncrement
              IL_0010:  ldloc.0
              IL_0011:  ldc.i4.1
              IL_0012:  add
              IL_0013:  stloc.0
              IL_0014:  ldloc.0
              IL_0015:  ldarg.0
              IL_0016:  blt.s      IL_0004
              IL_0018:  ret
            } // end of method Program::PreIncrement             
             */
            for (int i = 0; i < count; ++i)
            {
                ++SomethingToIncrement;
            }
        }

        static void PostIncrement(int count)
        {
            /*
                .method private hidebysig static void  PostIncrement(int32 count) cil managed
                {
                  // Code size       25 (0x19)
                  .maxstack  2
                  .locals init ([0] int32 i)
                  IL_0000:  ldc.i4.0
                  IL_0001:  stloc.0
                  IL_0002:  br.s       IL_0014
                  IL_0004:  ldsfld     int32 PreOrPostIncrement.Program::SomethingToIncrement
                  IL_0009:  ldc.i4.1
                  IL_000a:  add
                  IL_000b:  stsfld     int32 PreOrPostIncrement.Program::SomethingToIncrement
                  IL_0010:  ldloc.0
                  IL_0011:  ldc.i4.1
                  IL_0012:  add
                  IL_0013:  stloc.0
                  IL_0014:  ldloc.0
                  IL_0015:  ldarg.0
                  IL_0016:  blt.s      IL_0004
                  IL_0018:  ret
                } // end of method Program::PostIncrement
             */
            for (int i = 0; i < count; i++)
            {
                SomethingToIncrement++;
            }
        }
    }
}

Why do I get an UnsupportedOperationException when trying to remove an element from a List?

This UnsupportedOperationException comes when you try to perform some operation on collection where its not allowed and in your case, When you call Arrays.asList it does not return a java.util.ArrayList. It returns a java.util.Arrays$ArrayList which is an immutable list. You cannot add to it and you cannot remove from it.

Java 8 - Best way to transform a list: map or foreach?

If you use Eclipse Collections you can use the collectIf() method.

MutableList<Integer> source =
    Lists.mutable.with(1, null, 2, null, 3, null, 4, null, 5);

MutableList<String> result = source.collectIf(Objects::nonNull, String::valueOf);

Assert.assertEquals(Lists.immutable.with("1", "2", "3", "4", "5"), result);

It evaluates eagerly and should be a bit faster than using a Stream.

Note: I am a committer for Eclipse Collections.

Sending email with gmail smtp with codeigniter email library

Change it to the following:

$ci = get_instance();
$ci->load->library('email');
$config['protocol'] = "smtp";
$config['smtp_host'] = "ssl://smtp.gmail.com";
$config['smtp_port'] = "465";
$config['smtp_user'] = "[email protected]"; 
$config['smtp_pass'] = "yourpassword";
$config['charset'] = "utf-8";
$config['mailtype'] = "html";
$config['newline'] = "\r\n";

$ci->email->initialize($config);

$ci->email->from('[email protected]', 'Blabla');
$list = array('[email protected]');
$ci->email->to($list);
$this->email->reply_to('[email protected]', 'Explendid Videos');
$ci->email->subject('This is an email test');
$ci->email->message('It is working. Great!');
$ci->email->send();

Looping through list items with jquery

To solve this without jQuery .each() you'd have to fix your code like this:

var listItems = $("#productList").find("li");
var ind, len, product;

for ( ind = 0, len = listItems.length; ind < len; ind++ ) {
    product = $(listItems[ind]);

    // ...
}

Bugs in your original code:

  1. for ... in will also loop through all inherited properties; i.e. you will also get a list of all functions that are defined by jQuery.

  2. The loop variable li is not the list item, but the index to the list item. In that case the index is a normal array index (i.e. an integer)

Basically you are save to use .each() as it is more comfortable, but espacially when you are looping bigger arrays the code in this answer will be much faster.

For other alternatives to .each() you can check out this performance comparison: http://jsperf.com/browser-diet-jquery-each-vs-for-loop

How to retrieve an element from a set without removing it?

To provide some timing figures behind the different approaches, consider the following code. The get() is my custom addition to Python's setobject.c, being just a pop() without removing the element.

from timeit import *

stats = ["for i in xrange(1000): iter(s).next()   ",
         "for i in xrange(1000): \n\tfor x in s: \n\t\tbreak",
         "for i in xrange(1000): s.add(s.pop())   ",
         "for i in xrange(1000): s.get()          "]

for stat in stats:
    t = Timer(stat, setup="s=set(range(100))")
    try:
        print "Time for %s:\t %f"%(stat, t.timeit(number=1000))
    except:
        t.print_exc()

The output is:

$ ./test_get.py
Time for for i in xrange(1000): iter(s).next()   :       0.433080
Time for for i in xrange(1000):
        for x in s:
                break:   0.148695
Time for for i in xrange(1000): s.add(s.pop())   :       0.317418
Time for for i in xrange(1000): s.get()          :       0.146673

This means that the for/break solution is the fastest (sometimes faster than the custom get() solution).

Finding all positions of substring in a larger string in C#

@csam is correct in theory, although his code will not complie and can be refractored to

public static IEnumerable<int> IndexOfAll(this string sourceString, string matchString)
{
    matchString = Regex.Escape(matchString);
    return from Match match in Regex.Matches(sourceString, matchString) select match.Index;
}

Maven version with a property

Using a property for the version generates the following warning:

[WARNING]
[WARNING] Some problems were encountered while building the effective model for xxx.yyy.sandbox:Sandbox:war:0.1.0-SNAPSHOT
[WARNING] 'version' contains an expression but should be a constant. @ xxx.yyy.sandbox:Sandbox:${my.version}, C:\Users\xxx\development\gwtsandbox\pom.xml, line 8, column 14
[WARNING]
[WARNING] It is highly recommended to fix these problems because they threaten the stability of your build.
[WARNING]
[WARNING] For this reason, future Maven versions might no longer support building such malformed projects.
[WARNING]

If your problem is that you have to change the version in multiple places because you are switching versions, then the correct thing to do is to use the Maven Release Plugin that will do this for you automatically.

php implode (101) with quotes

$ids = sprintf("'%s'", implode("','", $ids ) );

More than 1 row in <Input type="textarea" />

Although <input> ignores the rows attribute, you can take advantage of the fact that <textarea> doesn't have to be inside <form> tags, but can still be a part of a form by referencing the form's id:

<form method="get" id="testformid">
    <input type="submit" />
</form> 
<textarea form ="testformid" name="taname" id="taid" cols="35" wrap="soft"></textarea>

Of course, <textarea> now appears below "submit" button, but maybe you'll find a way to reposition it.

CSS: how to position element in lower right?

Set the CSS position: relative; on the box. This causes all absolute positions of objects inside to be relative to the corners of that box. Then set the following CSS on the "Bet 5 days ago" line:

position: absolute;
bottom: 0;
right: 0;

If you need to space the text farther away from the edge, you could change 0 to 2px or similar.

How do I auto-submit an upload form when a file is selected?

If you already using jQuery simple:

<input type="file" onChange="$(this).closest('form').submit()"/>

Pandas: ValueError: cannot convert float NaN to integer

Also, even at the lastest versions of pandas if the column is object type you would have to convert into float first, something like:

df['column_name'].astype(np.float).astype("Int32")

NB: You have to go through numpy float first and then to nullable Int32, for some reason.

The size of the int if it's 32 or 64 depends on your variable, be aware you may loose some precision if your numbers are to big for the format.

Css pseudo classes input:not(disabled)not:[type="submit"]:focus

Instead of:

input:not(disabled)not:[type="submit"]:focus {}

Use:

input:not([disabled]):not([type="submit"]):focus {}

disabled is an attribute so it needs the brackets, and you seem to have mixed up/missing colons and parentheses on the :not() selector.

Demo: http://jsfiddle.net/HSKPx/

One thing to note: I may be wrong, but I don't think disabled inputs can normally receive focus, so that part may be redundant.

Alternatively, use :enabled

input:enabled:not([type="submit"]):focus { /* styles here */ }

Again, I can't think of a case where disabled input can receive focus, so it seems unnecessary.

Returning from a void function

The only reason to have a return in a void function would be to exit early due to some conditional statement:

void foo(int y)
{
    if(y == 0) return;

    // do stuff with y
}

As unwind said: when the code ends, it ends. No need for an explicit return at the end.

How do I get the RootViewController from a pushed controller?

A slightly less ugly version of the same thing mentioned in pretty much all these answers:

UIViewController *rootViewController = [[self.navigationController viewControllers] firstObject];

in your case, I'd probably do something like:

inside your UINavigationController subclass:

- (UIViewController *)rootViewController
{
    return [[self viewControllers] firstObject];
}

then you can use:

UIViewController *rootViewController = [self.navigationController rootViewController];

edit

OP asked for a property in the comments.

if you like, you can access this via something like self.navigationController.rootViewController by just adding a readonly property to your header:

@property (nonatomic, readonly, weak) UIViewController *rootViewController;

How to have multiple conditions for one if statement in python

Assuming you're passing in strings rather than integers, try casting the arguments to integers:

def example(arg1, arg2, arg3):
     if int(arg1) == 1 and int(arg2) == 2 and int(arg3) == 3:
          print("Example Text")

(Edited to emphasize I'm not asking for clarification; I was trying to be diplomatic in my answer. )

What is the difference between Bower and npm?

My team moved away from Bower and migrated to npm because:

  • Programmatic usage was painful
  • Bower's interface kept changing
  • Some features, like the url shorthand, are entirely broken
  • Using both Bower and npm in the same project is painful
  • Keeping bower.json version field in sync with git tags is painful
  • Source control != package management
  • CommonJS support is not straightforward

For more details, see "Why my team uses npm instead of bower".

base 64 encode and decode a string in angular (2+)

Use btoa() for encode and atob() for decode

text_val:any="your encoding text";

Encoded Text: console.log(btoa(this.text_val)); //eW91ciBlbmNvZGluZyB0ZXh0

Decoded Text: console.log(atob("eW91ciBlbmNvZGluZyB0ZXh0")); //your encoding text

Animate a custom Dialog

For right to left (entry animation) and left to right (exit animation):

styles.xml:

<style name="CustomDialog" parent="@android:style/Theme.Dialog">
    <item name="android:windowAnimationStyle">@style/CustomDialogAnimation</item>
</style>

<style name="CustomDialogAnimation">
    <item name="android:windowEnterAnimation">@anim/translate_left_side</item>
    <item name="android:windowExitAnimation">@anim/translate_right_side</item>
</style>

Create two files in res/anim/:

translate_right_side.xml:

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromXDelta="0%" android:toXDelta="100%"
    android:fromYDelta="0%" android:toYDelta="0%"
    android:duration="600"/>

translate_left_side.xml:

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="600"
    android:fromXDelta="100%"
    android:toXDelta="0%"/>

In you Fragment/Activity:

Dialog dialog = new Dialog(getActivity(), R.style.CustomDialog);

How to create custom spinner like border around the spinner with down triangle on the right side?

You could design a simple nine-patch png image and use it as the background of spinner. Using GIMP you can put both border and right triangle in image.

Plotting multiple curves same graph and same scale

My solution is to use ggplot2. It takes care of these types of things automatically. The biggest thing is to arrange the data appropriately.

y1 <- c(100, 200, 300, 400, 500)
y2 <- c(1, 2, 3, 4, 5)
x <- c(1, 2, 3, 4, 5)
df <- data.frame(x=rep(x,2), y=c(y1, y2), class=c(rep("y1", 5), rep("y2", 5)))

Then use ggplot2 to plot it

library(ggplot2)
ggplot(df, aes(x=x, y=y, color=class)) + geom_point()

This is saying plot the data in df, and separate the points by class.

The plot generated isenter image description here

How to insert blank lines in PDF?

You can also use

document.add(new Paragraph());
document.add(new Paragraph());

before seperator if you are using either it is fine.

onActivityResult is not being called in Fragment

Inside your fragment, call

this.startActivityForResult(intent, REQUEST_CODE);

where this is referring to the fragment. Otherwise do as @Clevester said:

Fragment fragment = this;
....
fragment.startActivityForResult(intent, REQUEST_CODE);

I also had to call

super.onActivityResult(requestCode, resultCode, data);

in the parent activity's onActivityResult to make it work.

(I adapted this answer from @Clevester's answer.)

Why can't radio buttons be "readonly"?

This is the trick you can go with.

<input type="radio" name="name" onclick="this.checked = false;" />

Vagrant stuck connection timeout retrying

From the virtualbox interface, I booted on a "CD" first, and disabled the hard drive boot. Hence it was booting on from a CD iso, and obviously not on the expected machine... I hope it helps. And I hope it made someone smile too... PEBCAK.

Simultaneously merge multiple data.frames in a list

You can do it using merge_all in the reshape package. You can pass parameters to merge using the ... argument

reshape::merge_all(list_of_dataframes, ...)

Here is an excellent resource on different methods to merge data frames.

Using LINQ to group a list of objects

var result = from cx in CustomerList
         group cx by cx.GroupID into cxGroup
     orderby cxGroup.Key
     select cxGroup; 

foreach (var cxGroup in result) { 
Console.WriteLine(String.Format("GroupID = {0}", cxGroup.Key)); 
  foreach (var cx in cxGroup) { 
    Console.WriteLine(String.Format("\tUserID = {0}, UserName = {1}, GroupID = {2}", 
      new object[] { cx.ID, cx.Name, cx.GroupID })); 
  }
}

Pass data from Activity to Service using an Intent

Another posibility is using intent.getAction:

In Service:

public class SampleService inherits Service{
    static final String ACTION_START = "com.yourcompany.yourapp.SampleService.ACTION_START";
    static final String ACTION_DO_SOMETHING_1 = "com.yourcompany.yourapp.SampleService.DO_SOMETHING_1";
    static final String ACTION_DO_SOMETHING_2 = "com.yourcompany.yourapp.SampleService.DO_SOMETHING_2";
    static final String ACTION_STOP_SERVICE = "com.yourcompany.yourapp.SampleService.STOP_SERVICE";

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String action = intent.getAction();
        //System.out.println("ACTION: "+action);
        switch (action){
            case ACTION_START:
                startingService(intent.getIntExtra("valueStart",0));
                break;
            case ACTION_DO_SOMETHING_1:
                int value1,value2;
                value1=intent.getIntExtra("value1",0);
                value2=intent.getIntExtra("value2",0);
                doSomething1(value1,value2);
                break;
            case ACTION_DO_SOMETHING_2:
                value1=intent.getIntExtra("value1",0);
                value2=intent.getIntExtra("value2",0);
                doSomething2(value1,value2);
                break;
            case ACTION_STOP_SERVICE:
                stopService();
                break;
        }
        return START_STICKY;
    }

    public void startingService(int value){
        //calling when start
    }

    public void doSomething1(int value1, int value2){
        //...
    }

    public void doSomething2(int value1, int value2){
        //...
    }

    public void stopService(){
        //...destroy/release objects
        stopself();
    }
}

In Activity:

public void startService(int value){
    Intent myIntent = new Intent(SampleService.ACTION_START);
    myIntent.putExtra("valueStart",value);
    startService(myIntent);
}

public void serviceDoSomething1(int value1, int value2){
    Intent myIntent = new Intent(SampleService.ACTION_DO_SOMETHING_1);
    myIntent.putExtra("value1",value1);
    myIntent.putExtra("value2",value2);
    startService(myIntent);
}

public void serviceDoSomething2(int value1, int value2){
    Intent myIntent = new Intent(SampleService.ACTION_DO_SOMETHING_2);
    myIntent.putExtra("value1",value1);
    myIntent.putExtra("value2",value2);
    startService(myIntent);
}

public void endService(){
    Intent myIntent = new Intent(SampleService.STOP_SERVICE);
    startService(myIntent);
}

Finally, In Manifest file:

<service android:name=".SampleService">
    <intent-filter>
        <action android:name="com.yourcompany.yourapp.SampleService.ACTION_START"/>
        <action android:name="com.yourcompany.yourapp.SampleService.DO_SOMETHING_1"/>
        <action android:name="com.yourcompany.yourapp.SampleService.DO_SOMETHING_2"/>
        <action android:name="com.yourcompany.yourapp.SampleService.STOP_SERVICE"/>
    </intent-filter>
</service>

Forward host port to docker container

You could also create an ssh tunnel.

docker-compose.yml:

---

version: '2'

services:
  kibana:
    image: "kibana:4.5.1"
    links:
      - elasticsearch
    volumes:
      - ./config/kibana:/opt/kibana/config:ro

  elasticsearch:
    build:
      context: .
      dockerfile: ./docker/Dockerfile.tunnel
    entrypoint: ssh
    command: "-N elasticsearch -L 0.0.0.0:9200:localhost:9200"

docker/Dockerfile.tunnel:

FROM buildpack-deps:jessie

RUN apt-get update && \
    DEBIAN_FRONTEND=noninteractive \
    apt-get -y install ssh && \
    apt-get clean && \
    rm -rf /var/lib/apt/lists/*

COPY ./config/ssh/id_rsa /root/.ssh/id_rsa
COPY ./config/ssh/config /root/.ssh/config
COPY ./config/ssh/known_hosts /root/.ssh/known_hosts
RUN chmod 600 /root/.ssh/id_rsa && \
    chmod 600 /root/.ssh/config && \
    chown $USER:$USER -R /root/.ssh

config/ssh/config:

# Elasticsearch Server
Host elasticsearch
    HostName jump.host.czerasz.com
    User czerasz
    ForwardAgent yes
    IdentityFile ~/.ssh/id_rsa

This way the elasticsearch has a tunnel to the server with the running service (Elasticsearch, MongoDB, PostgreSQL) and exposes port 9200 with that service.

What is the difference between C and embedded C?

Embedded environment, sometime, there is no MMU, less memory, less storage space. In C programming level, almost same, cross compiler do their job.

jQuery, get html of a whole element

Differences might not be meaningful in a typical use case, but using the standard DOM functionality

$("#el")[0].outerHTML

is about twice as fast as

$("<div />").append($("#el").clone()).html();

so I would go with:

/* 
 * Return outerHTML for the first element in a jQuery object,
 * or an empty string if the jQuery object is empty;  
 */
jQuery.fn.outerHTML = function() {
   return (this[0]) ? this[0].outerHTML : '';  
};

Changing the selected option of an HTML Select element

Excellent answers - here's the D3 version for anyone looking:

<select id="sel">
    <option>Cat</option>
    <option>Dog</option>
    <option>Fish</option>
</select>
<script>
    d3.select('#sel').property('value', 'Fish');
</script>

git push rejected: error: failed to push some refs

Just do

git pull origin [branch]

and then you should be able to push.

If you have commits on your own and didn't push it the branch yet, try

git pull --rebase origin [branch]

and then you should be able to push.

Read more about handling branches with Git.

Can I get image from canvas element and use it in img src tag?

Corrected the Fiddle - updated shows the Image duplicated into the Canvas...

And right click can be saved as a .PNG

http://jsfiddle.net/gfyWK/67/

<div style="text-align:center">
<img src="http://imgon.net/di-M7Z9.jpg" id="picture" style="display:none;" />
<br />
<div id="for_jcrop">here the image should apear</div>
<canvas id="rotate" style="border:5px double black; margin-top:5px; "></canvas>
</div>

Plus the JS on the fiddle page...

Cheers Si

Currently looking at saving this to File on the server --- ASP.net C# (.aspx web form page) Any advice would be cool....

Returning JSON from a PHP Script

A simple function to return a JSON response with the HTTP status code.

function json_response($data=null, $httpStatus=200)
{
    header_remove();

    header("Content-Type: application/json");

    http_response_code($httpStatus);

    echo json_encode($data);

    exit();
}

How should I make my VBA code compatible with 64-bit Windows?

To write for all versions of Office use a combination of the newer VBA7 and Win64 conditional Compiler Constants.

VBA7 determines if code is running in version 7 of the VB editor (VBA version shipped in Office 2010+).

Win64 determines which version (32-bit or 64-bit) of Office is running.

#If VBA7 Then
'Code is running VBA7 (2010 or later).

     #If Win64 Then
     'Code is running in 64-bit version of Microsoft Office.
     #Else
     'Code is running in 32-bit version of Microsoft Office.
     #End If

#Else
'Code is running VBA6 (2007 or earlier).

#End If

See Microsoft Support Article for more details.

Uncaught ReferenceError: <function> is not defined at HTMLButtonElement.onclick

Same Problem I had... I was writing all the script in a seperate file and was adding it through tag into the end of the HTML file after body tag. After moving the the tag inside the body tag it works fine. before :

</body>
<script>require('../script/viewLog.js')</script>

after :

<script>require('../script/viewLog.js')</script>
</body>

Set max-height on inner div so scroll bars appear, but not on parent div

If you make

overflow: hidden in the outer div and overflow-y: scroll in the inner div it will work.

http://jsfiddle.net/C8MuZ/11/

Using PropertyInfo to find out the property type

Use PropertyInfo.PropertyType to get the type of the property.

public bool ValidateData(object data)
{
    foreach (PropertyInfo propertyInfo in data.GetType().GetProperties())
    {
        if (propertyInfo.PropertyType == typeof(string))
        {
            string value = propertyInfo.GetValue(data, null);

            if value is not OK
            {
                return false;
            }
        }
    }            

    return true;
}

Unfamiliar symbol in algorithm: what does ? mean?

In math, ? means FOR ALL.

Unicode character (\u2200, ?).

How to change the colors of a PNG image easily?

This should be fairly straightforward in the gimp http://gimp.org/

First make sure your image is RGB (not indexed color) then use the "color to alpha" feature to turn the clubs/diamonds clear, then fill or set the background or whatever to get the color you want.

SELECT * FROM X WHERE id IN (...) with Dapper ORM

In my experience, the most friendly way of dealing with this is to have a function that converts a string into a table of values.

There are many splitter functions available on the web, you'll easily find one for whatever if your flavour of SQL.

You can then do...

SELECT * FROM table WHERE id IN (SELECT id FROM split(@list_of_ids))

Or

SELECT * FROM table INNER JOIN (SELECT id FROM split(@list_of_ids)) AS list ON list.id = table.id

(Or similar)

Add a new element to an array without specifying the index in Bash

If your array is always sequential and starts at 0, then you can do this:

array[${#array[@]}]='foo'

# gets the length of the array
${#array_name[@]}

If you inadvertently use spaces between the equal sign:

array[${#array[@]}] = 'foo'

Then you will receive an error similar to:

array_name[3]: command not found

find first sequence item that matches a criterion

a=[100,200,300,400,500]
def search(b):
 try:
  k=a.index(b)
  return a[k] 
 except ValueError:
    return 'not found'
print(search(500))

it'll return the object if found else it'll return "not found"

Failed to run sdkmanager --list with Java 9

When having java 11 in the system, the solutions provided are not valid.

This -XX:+IgnoreUnrecognizedVMOptions --add-modules java.se.ee or--add-modules java.xml.bind do not work with Java 11 on Mac OS.

For that reason you have to downgrade java version to version 8 from here: http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html

List Java versions installed

/usr/libexec/java_home -V

Java 11

export JAVA_HOME=$(/usr/libexec/java_home -v 11)

Java 1.8

export JAVA_HOME=$(/usr/libexec/java_home -v 1.8)

Then go to

cd ~/Library/Android/sdk/tools/bin

and

./sdkmanager --licenses

PreparedStatement setNull(..)

Finally I did a small test and while I was programming it it came to my mind, that without the setNull(..) method there would be no way to set null values for the Java primitives. For Objects both ways

setNull(..)

and

set<ClassName>(.., null)) 

behave the same way.

How do I format date and time on ssrs report?

In SSRS 2016 There is an option under the properties header "Localization" called "Calendar", if you click on this it gives you these 2 options:

  • Gregorian (dd/mm/yyyy)
  • GregorianUSEnglish (MM/dd/yyyy)

This works brilliantly when referencing data from a tables aswell

alternatively if this does not work for you, specify one of these formats under "Number" and in the cell "Format":

dd/MM/yyyy or MM/dd/yyyy

printscreen

RegEx: Grabbing values between quotation marks

If you're trying to find strings that only have a certain suffix, such as dot syntax, you can try this:

\"([^\"]*?[^\"]*?)\".localized

Where .localized is the suffix.

Example:

print("this is something I need to return".localized + "so is this".localized + "but this is not")

It will capture "this is something I need to return".localized and "so is this".localized but not "but this is not".

Convert object of any type to JObject with Json.NET

If you have an object and wish to become JObject you can use:

JObject o = (JObject)JToken.FromObject(miObjetoEspecial);

like this :

Pocion pocionDeVida = new Pocion{
tipo = "vida",
duracion = 32,
};

JObject o = (JObject)JToken.FromObject(pocionDeVida);
Console.WriteLine(o.ToString());
// {"tipo": "vida", "duracion": 32,}

Python __call__ special method practical example

One common example is the __call__ in functools.partial, here is a simplified version (with Python >= 3.5):

class partial:
    """New function with partial application of the given arguments and keywords."""

    def __new__(cls, func, *args, **kwargs):
        if not callable(func):
            raise TypeError("the first argument must be callable")
        self = super().__new__(cls)

        self.func = func
        self.args = args
        self.kwargs = kwargs
        return self

    def __call__(self, *args, **kwargs):
        return self.func(*self.args, *args, **self.kwargs, **kwargs)

Usage:

def add(x, y):
    return x + y

inc = partial(add, y=1)
print(inc(41))  # 42

How to get input text value on click in ReactJS

First of all, you can't pass to alert second argument, use concatenation instead

alert("Input is " + inputValue);

Example

However in order to get values from input better to use states like this

_x000D_
_x000D_
var MyComponent = React.createClass({_x000D_
  getInitialState: function () {_x000D_
    return { input: '' };_x000D_
  },_x000D_
_x000D_
  handleChange: function(e) {_x000D_
    this.setState({ input: e.target.value });_x000D_
  },_x000D_
_x000D_
  handleClick: function() {_x000D_
    console.log(this.state.input);_x000D_
  },_x000D_
_x000D_
  render: function() {_x000D_
    return (_x000D_
      <div>_x000D_
        <input type="text" onChange={ this.handleChange } />_x000D_
        <input_x000D_
          type="button"_x000D_
          value="Alert the text input"_x000D_
          onClick={this.handleClick}_x000D_
        />_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
});_x000D_
_x000D_
ReactDOM.render(_x000D_
  <MyComponent />,_x000D_
  document.getElementById('container')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="container"></div>
_x000D_
_x000D_
_x000D_

What is the difference between putting a property on application.yml or bootstrap.yml in spring boot?

This answer has been very beautifully explained in book "Microservices Interview Questions, For Java Developers (Spring Boot, Spring Cloud, Cloud Native Applications) by Munish Chandel, Version 1.30, 25.03.2018.

The following content has been taken from this book, and total credit for this answer goes to the Author of the book i.e. Munish Chandel

application.yml

application.yml/application.properties file is specific to Spring Boot applications. Unless you change the location of external properties of an application, spring boot will always load application.yml from the following location:

/src/main/resources/application.yml

You can store all the external properties for your application in this file. Common properties that are available in any Spring Boot project can be found at: https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html You can customize these properties as per your application needs. Sample file is shown below:

spring:
    application:
        name: foobar
    datasource:
        driverClassName: com.mysql.jdbc.Driver
        url: jdbc:mysql://localhost/test
server:
    port: 9000

bootstrap.yml

bootstrap.yml on the other hand is specific to spring-cloud-config and is loaded before the application.yml

bootstrap.yml is only needed if you are using Spring Cloud and your microservice configuration is stored on a remote Spring Cloud Config Server.

Important points about bootstrap.yml

  1. When used with Spring Cloud Config server, you shall specify the application-name and config git location using below properties.

spring.application.name: "application-name"
spring.cloud.config.server.git.uri: "git-uri-config"

  1. When used with microservices (other than cloud config server), we need to specify the application name and location of config server using below properties

spring.application.name: 
spring.cloud.config.uri: 
  1. This properties file can contain other configuration relevant to Spring Cloud environment for e.g. eureka server location, encryption/decryption related properties.

Upon startup, Spring Cloud makes an HTTP(S) call to the Spring Cloud Config Server with the name of the application and retrieves back that application’s configuration.

application.yml contains the default configuration for the microservice and any configuration retrieved (from cloud config server) during the bootstrap process will override configuration defined in application.yml

How to identify platform/compiler from preprocessor macros?

Here's what I use:

#ifdef _WIN32 // note the underscore: without it, it's not msdn official!
    // Windows (x64 and x86)
#elif __unix__ // all unices, not all compilers
    // Unix
#elif __linux__
    // linux
#elif __APPLE__
    // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though...
#endif

EDIT: Although the above might work for the basics, remember to verify what macro you want to check for by looking at the Boost.Predef reference pages. Or just use Boost.Predef directly.

How to access my localhost from another PC in LAN?

Actualy you don't need an internet connection to use ip address. Each computer in LAN has an internal IP address you can discover by runing

ipconfig /all

in cmd.

You can use the ip address of the server (probabily something like 192.168.0.x or 10.0.0.x) to access the website remotely.

If you found the ip and still cannot access the website, it means WAMP is not configured to respond to that name ( what did you call me? 192.168.0.3? That's not my name. I'm Localhost ) and you have to modify ....../apache/config/httpd.conf

Listen *:80

best practice font size for mobile

The whole thing to em is, that the size is relative to the base. So I would say you could keep the font sizes by altering the base.

Example: If you base is 16px, and p is .75em (which is 12px) you would have to raise the base to about 20px. In this case p would then equal about 15px which is the minimum I personally require for mobile phones.

How to create a new instance from a class object in Python

This is how you can dynamically create a class named Child in your code, assuming Parent already exists... even if you don't have an explicit Parent class, you could use object...

The code below defines __init__() and then associates it with the class.

>>> child_name = "Child"
>>> child_parents = (Parent,)
>>> child body = """
def __init__(self, arg1):
    # Initialization for the Child class
    self.foo = do_something(arg1)
"""
>>> child_dict = {}
>>> exec(child_body, globals(), child_dict)
>>> childobj = type(child_name, child_parents, child_dict)
>>> childobj.__name__
'Child'
>>> childobj.__bases__
(<type 'object'>,)
>>> # Instantiating the new Child object...
>>> childinst = childobj()
>>> childinst
<__main__.Child object at 0x1c91710>
>>>

How to round a number to significant figures in Python

I ran into this as well but I needed control over the rounding type. Thus, I wrote a quick function (see code below) that can take value, rounding type, and desired significant digits into account.

import decimal
from math import log10, floor

def myrounding(value , roundstyle='ROUND_HALF_UP',sig = 3):
    roundstyles = [ 'ROUND_05UP','ROUND_DOWN','ROUND_HALF_DOWN','ROUND_HALF_UP','ROUND_CEILING','ROUND_FLOOR','ROUND_HALF_EVEN','ROUND_UP']

    power =  -1 * floor(log10(abs(value)))
    value = '{0:f}'.format(value) #format value to string to prevent float conversion issues
    divided = Decimal(value) * (Decimal('10.0')**power) 
    roundto = Decimal('10.0')**(-sig+1)
    if roundstyle not in roundstyles:
        print('roundstyle must be in list:', roundstyles) ## Could thrown an exception here if you want.
    return_val = decimal.Decimal(divided).quantize(roundto,rounding=roundstyle)*(decimal.Decimal(10.0)**-power)
    nozero = ('{0:f}'.format(return_val)).rstrip('0').rstrip('.') # strips out trailing 0 and .
    return decimal.Decimal(nozero)


for x in list(map(float, '-1.234 1.2345 0.03 -90.25 90.34543 9123.3 111'.split())):
    print (x, 'rounded UP: ',myrounding(x,'ROUND_UP',3))
    print (x, 'rounded normal: ',myrounding(x,sig=3))

How to convert DateTime? to DateTime

You can also try Nullable(T) Properties:

DateTime UpdatedTime = _objHotelPackageOrder.UpdatedDate.HasValue 
    ? DateTime.Now : _objHotelPackageOrder.UpdatedDate.Value;

Is there a JSON equivalent of XQuery/XPath?

I think JSONQuery is a superset of JSONPath and thus replaces it in dojo. Then there's also RQL.

From Dojo documentation:

JSONQuery is an extended version of JSONPath with additional features for security, ease of use, and a comprehensive set of data querying tools including filtering, recursive search, sorting, mapping, range selection, and flexible expressions with wildcard string comparisons and various operators.

JSONselect has another point of view on the question (CSS selector-like, rather than XPath) and has a JavaScript implementation.

Convert StreamReader to byte[]

You can use this code: You shouldn't use this code:

byte[] bytes = streamReader.CurrentEncoding.GetBytes(streamReader.ReadToEnd());

Please see the comment to this answer as to why. I will leave the answer, so people know about the problems with this approach, because I didn't up till now.

TempData keep() vs peek()

don't they both keep a value for another request?

Yes they do, but when the first one is void, the second one returns and object:

public void Keep(string key)
{
    _retainedKeys.Add(key); // just adds the key to the collection for retention
}

public object Peek(string key)
{
    object value;
    _data.TryGetValue(key, out value);
    return value; // returns an object without marking it for deletion
}

Failure [INSTALL_FAILED_ALREADY_EXISTS] when I tried to update my application

If u still facing problem then try to uninstall application using command prompt. just add command adb uninstall com.example.yourpackagename then try to re-install again.It works!

How do you implement a good profanity filter?

If you can do something like Digg/Stackoverflow where the users can downvote/mark obscene content... do so.

Then all you need to do is review the "naughty" users, and block them if they break the rules.

How to change the playing speed of videos in HTML5?

(Tested in Chrome while playing videos on YouTube, but should work anywhere--especially useful for speeding up online training videos).

For anyone wanting to add these as "bookmarklets" (bookmarks) to your browser, use these browser bookmark names and URLs, and add each of the following bookmarks to the top of your browser:

enter image description here

Name: 0.5x
URL:

javascript:

document.querySelector('video').playbackRate = 0.5;

Name: 1.0x
URL:

javascript:

document.querySelector('video').playbackRate = 1.0;

Name: 1.5x
URL:

javascript:

document.querySelector('video').playbackRate = 1.5;

Name: 2.0x
URL:

javascript:

document.querySelector('video').playbackRate = 2.0;

References:

  1. The main answer by Jeremy Visser
  2. Copied from my GitHub gist here: https://gist.github.com/ElectricRCAircraftGuy/0a788876da1386ca0daecbe78b4feb44#other-bookmarklets
    1. Get other bookmarklets here too, such as for aiding you on GitHub.

java.nio.file.Path for a classpath resource

The most general solution is as follows:

interface IOConsumer<T> {
    void accept(T t) throws IOException;
}
public static void processRessource(URI uri, IOConsumer<Path> action) throws IOException {
    try {
        Path p=Paths.get(uri);
        action.accept(p);
    }
    catch(FileSystemNotFoundException ex) {
        try(FileSystem fs = FileSystems.newFileSystem(
                uri, Collections.<String,Object>emptyMap())) {
            Path p = fs.provider().getPath(uri);
            action.accept(p);
        }
    }
}

The main obstacle is to deal with the two possibilities, either, having an existing filesystem that we should use, but not close (like with file URIs or the Java 9’s module storage), or having to open and thus safely close the filesystem ourselves (like zip/jar files).

Therefore, the solution above encapsulates the actual action in an interface, handles both cases, safely closing afterwards in the second case, and works from Java 7 to Java 10. It probes whether there is already an open filesystem before opening a new one, so it also works in the case that another component of your application has already opened a filesystem for the same zip/jar file.

It can be used in all Java versions named above, e.g. to listing the contents of a package (java.lang in the example) as Paths, like this:

processRessource(Object.class.getResource("Object.class").toURI(), new IOConsumer<Path>() {
    public void accept(Path path) throws IOException {
        try(DirectoryStream<Path> ds = Files.newDirectoryStream(path.getParent())) {
            for(Path p: ds)
                System.out.println(p);
        }
    }
});

With Java 8 or newer, you can use lambda expressions or method references to represent the actual action, e.g.

processRessource(Object.class.getResource("Object.class").toURI(), path -> {
    try(Stream<Path> stream = Files.list(path.getParent())) {
        stream.forEach(System.out::println);
    }
});

to do the same.


The final release of Java 9’s module system has broken the above code example. The JRE inconsistently returns the path /java.base/java/lang/Object.class for Object.class.getResource("Object.class") whereas it should be /modules/java.base/java/lang/Object.class. This can be fixed by prepending the missing /modules/ when the parent path is reported as non-existent:

processRessource(Object.class.getResource("Object.class").toURI(), path -> {
    Path p = path.getParent();
    if(!Files.exists(p))
        p = p.resolve("/modules").resolve(p.getRoot().relativize(p));
    try(Stream<Path> stream = Files.list(p)) {
        stream.forEach(System.out::println);
    }
});

Then, it will again work with all versions and storage methods.

Reflection generic get field value

Like answered before, you should use:

Object value = field.get(objectInstance);

Another way, which is sometimes prefered, is calling the getter dynamically. example code:

public static Object runGetter(Field field, BaseValidationObject o)
{
    // MZ: Find the correct method
    for (Method method : o.getMethods())
    {
        if ((method.getName().startsWith("get")) && (method.getName().length() == (field.getName().length() + 3)))
        {
            if (method.getName().toLowerCase().endsWith(field.getName().toLowerCase()))
            {
                // MZ: Method found, run it
                try
                {
                    return method.invoke(o);
                }
                catch (IllegalAccessException e)
                {
                    Logger.fatal("Could not determine method: " + method.getName());
                }
                catch (InvocationTargetException e)
                {
                    Logger.fatal("Could not determine method: " + method.getName());
                }

            }
        }
    }


    return null;
}

Also be aware that when your class inherits from another class, you need to recursively determine the Field. for instance, to fetch all Fields of a given class;

    for (Class<?> c = someClass; c != null; c = c.getSuperclass())
    {
        Field[] fields = c.getDeclaredFields();
        for (Field classField : fields)
        {
            result.add(classField);
        }
    }

src absolute path problem

Use forward slashes. See explanation here

Use multiple custom fonts using @font-face?

If you are having a problem with the font working I have also had this in the past and the issue I found was down to the font-family: name. This had to match what font name was actually given.

The easiest way I found to find this out was to install the font and see what display name is given.

For example, I was using Gill Sans on one project, but the actual font was called Gill Sans MT. Spacing and capitlisation was also important to get right.

Hope that helps.

Nginx subdomain configuration

You could move the common parts to another configuration file and include from both server contexts. This should work:

server {
  listen 80;
  server_name server1.example;
  ...
  include /etc/nginx/include.d/your-common-stuff.conf;
}

server {
  listen 80;
  server_name another-one.example;
  ...
  include /etc/nginx/include.d/your-common-stuff.conf;
}

Edit: Here's an example that's actually copied from my running server. I configure my basic server settings in /etc/nginx/sites-enabled (normal stuff for nginx on Ubuntu/Debian). For example, my main server bunkus.org's configuration file is /etc/nginx/sites-enabled and it looks like this:

server {
  listen   80 default_server;
  listen   [2a01:4f8:120:3105::101:1]:80 default_server;

  include /etc/nginx/include.d/all-common;
  include /etc/nginx/include.d/bunkus.org-common;
  include /etc/nginx/include.d/bunkus.org-80;
}

server {
  listen   443 default_server;
  listen   [2a01:4f8:120:3105::101:1]:443 default_server;

  include /etc/nginx/include.d/all-common;
  include /etc/nginx/include.d/ssl-common;
  include /etc/nginx/include.d/bunkus.org-common;
  include /etc/nginx/include.d/bunkus.org-443;
}

As an example here's the /etc/nginx/include.d/all-common file that's included from both server contexts:

index index.html index.htm index.php .dirindex.php;
try_files $uri $uri/ =404;

location ~ /\.ht {
  deny all;
}

location = /favicon.ico {
  log_not_found off;
  access_log off;
}

location ~ /(README|ChangeLog)$ {
  types { }
  default_type text/plain;
}

Hash function that produces short hashes?

If you need "sub-10-character hash" you could use Fletcher-32 algorithm which produces 8 character hash (32 bits), CRC-32 or Adler-32.

CRC-32 is slower than Adler32 by a factor of 20% - 100%.

Fletcher-32 is slightly more reliable than Adler-32. It has a lower computational cost than the Adler checksum: Fletcher vs Adler comparison.

A sample program with a few Fletcher implementations is given below:

    #include <stdio.h>
    #include <string.h>
    #include <stdint.h> // for uint32_t

    uint32_t fletcher32_1(const uint16_t *data, size_t len)
    {
            uint32_t c0, c1;
            unsigned int i;

            for (c0 = c1 = 0; len >= 360; len -= 360) {
                    for (i = 0; i < 360; ++i) {
                            c0 = c0 + *data++;
                            c1 = c1 + c0;
                    }
                    c0 = c0 % 65535;
                    c1 = c1 % 65535;
            }
            for (i = 0; i < len; ++i) {
                    c0 = c0 + *data++;
                    c1 = c1 + c0;
            }
            c0 = c0 % 65535;
            c1 = c1 % 65535;
            return (c1 << 16 | c0);
    }

    uint32_t fletcher32_2(const uint16_t *data, size_t l)
    {
        uint32_t sum1 = 0xffff, sum2 = 0xffff;

        while (l) {
            unsigned tlen = l > 359 ? 359 : l;
            l -= tlen;
            do {
                sum2 += sum1 += *data++;
            } while (--tlen);
            sum1 = (sum1 & 0xffff) + (sum1 >> 16);
            sum2 = (sum2 & 0xffff) + (sum2 >> 16);
        }
        /* Second reduction step to reduce sums to 16 bits */
        sum1 = (sum1 & 0xffff) + (sum1 >> 16);
        sum2 = (sum2 & 0xffff) + (sum2 >> 16);
        return (sum2 << 16) | sum1;
    }

    int main()
    {
        char *str1 = "abcde";  
        char *str2 = "abcdef";

        size_t len1 = (strlen(str1)+1) / 2; //  '\0' will be used for padding 
        size_t len2 = (strlen(str2)+1) / 2; // 

        uint32_t f1 = fletcher32_1(str1,  len1);
        uint32_t f2 = fletcher32_2(str1,  len1);

        printf("%u %X \n",    f1,f1);
        printf("%u %X \n\n",  f2,f2);

        f1 = fletcher32_1(str2,  len2);
        f2 = fletcher32_2(str2,  len2);

        printf("%u %X \n",f1,f1);
        printf("%u %X \n",f2,f2);

        return 0;
    }

Output:

4031760169 F04FC729                                                                                                                                                                                                                              
4031760169 F04FC729                                                                                                                                                                                                                              

1448095018 56502D2A                                                                                                                                                                                                                              
1448095018 56502D2A                                                                                                                                                                                                                              

Agrees with Test vectors:

"abcde"  -> 4031760169 (0xF04FC729)
"abcdef" -> 1448095018 (0x56502D2A)

Adler-32 has a weakness for short messages with few hundred bytes, because the checksums for these messages have a poor coverage of the 32 available bits. Check this:

The Adler32 algorithm is not complex enough to compete with comparable checksums.

What causes a java.lang.StackOverflowError

Stack Overflow exceptions can occur when a thread stack continues to grow in size until reaching the maximum limit.

Adjusting the Stack Sizes (Xss and Xmso) options...

I suggest you see this link: http://www-01.ibm.com/support/docview.wss?uid=swg21162896 There are many possible causes to a StackOverflowError, as you can see in the link....

Git mergetool generates unwanted .orig files

You have to be a little careful with using kdiff3 as while git mergetool can be configured to save a .orig file during merging, the default behaviour for kdiff3 is to also save a .orig backup file independently of git mergetool.

You have to make sure that mergetool backup is off:

git config --global mergetool.keepBackup false

and also that kdiff3's settings are set to not create a backup:

Configure/Options => Directory Merge => Backup Files (*.orig)

Add legend to ggplot2 line plot

I really like the solution proposed by @Brian Diggs. However, in my case, I create the line plots in a loop rather than giving them explicitly because I do not know apriori how many plots I will have. When I tried to adapt the @Brian's code I faced some problems with handling the colors correctly. Turned out I needed to modify the aesthetic functions. In case someone has the same problem, here is the code that worked for me.

I used the same data frame as @Brian:

data <- structure(list(month = structure(c(1317452400, 1317538800, 1317625200, 1317711600, 
                                       1317798000, 1317884400, 1317970800, 1318057200, 
                                       1318143600, 1318230000, 1318316400, 1318402800, 
                                       1318489200, 1318575600, 1318662000, 1318748400, 
                                       1318834800, 1318921200, 1319007600, 1319094000), 
                                     class = c("POSIXct", "POSIXt"), tzone = ""),
                   TempMax = c(26.58, 27.78, 27.9, 27.44, 30.9, 30.44, 27.57, 25.71, 
                               25.98, 26.84, 33.58, 30.7, 31.3, 27.18, 26.58, 26.18, 
                               25.19, 24.19, 27.65, 23.92), 
                   TempMed = c(22.88, 22.87, 22.41, 21.63, 22.43, 22.29, 21.89, 20.52,
                                 19.71, 20.73, 23.51, 23.13, 22.95, 21.95, 21.91, 20.72, 
                                 20.45, 19.42, 19.97, 19.61), 
                   TempMin = c(19.34, 19.14, 18.34, 17.49, 16.75, 16.75, 16.88, 16.82, 
                               14.82, 16.01, 16.88, 17.55, 16.75, 17.22, 19.01, 16.95, 
                               17.55, 15.21, 14.22, 16.42)), 
              .Names = c("month", "TempMax", "TempMed", "TempMin"), 
              row.names = c(NA, 20L), class = "data.frame")  

In my case, I generate my.cols and my.names dynamically, but I don't want to make things unnecessarily complicated so I give them explicitly here. These three lines make the ordering of the legend and assigning colors easier.

my.cols <- heat.colors(3, alpha=1)
my.names <- c("TempMin", "TempMed", "TempMax")
names(my.cols) <- my.names

And here is the plot:

p <-  ggplot(data, aes(x = month))

for (i in 1:3){
  p <- p + geom_line(aes_(y = as.name(names(data[i+1])), colour = 
colnames(data[i+1])))#as.character(my.names[i])))
}
p + scale_colour_manual("", 
                        breaks = as.character(my.names),
                        values = my.cols)
p

enter image description here

RESTful API methods; HEAD & OPTIONS

OPTIONS method returns info about API (methods/content type)

HEAD method returns info about resource (version/length/type)

Server response

OPTIONS

HTTP/1.1 200 OK
Allow: GET,HEAD,POST,OPTIONS,TRACE
Content-Type: text/html; charset=UTF-8
Date: Wed, 08 May 2013 10:24:43 GMT
Content-Length: 0

HEAD

HTTP/1.1 200 OK
Accept-Ranges: bytes
Content-Type: text/html; charset=UTF-8
Date: Wed, 08 May 2013 10:12:29 GMT
ETag: "780602-4f6-4db31b2978ec0"
Last-Modified: Thu, 25 Apr 2013 16:13:23 GMT
Content-Length: 1270
  • OPTIONS Identifying which HTTP methods a resource supports, e.g. can we DELETE it or update it via a PUT?
  • HEAD Checking whether a resource has changed. This is useful when maintaining a cached version of a resource
  • HEAD Retrieving metadata about the resource, e.g. its media type or its size, before making a possibly costly retrieval
  • HEAD, OPTIONS Testing whether a resource exists and is accessible. For example, validating user-submitted links in an application

Here is nice and concise article about how HEAD and OPTIONS fit into RESTful architecture.

How does the communication between a browser and a web server take place?

Hyper Text Transfer Protocol (HTTP) is a protocol used for transferring web pages (like the one you're reading right now). A protocol is really nothing but a standard way of doing things. If you were to meet the President of the United States, or the king of a country, there would be specific procedures that you'd have to follow. You couldn't just walk up and say "hey dude". There would be a specific way to walk, to talk, a standard greeting, and a standard way to end the conversation. Protocols in the TCP/IP stack serve the same purpose.

The TCP/IP stack has four layers: Application, Transport, Internet, and Network. At each layer there are different protocols that are used to standardize the flow of information, and each one is a computer program (running on your computer) that's used to format the information into a packet as it's moving down the TCP/IP stack. A packet is a combination of the Application Layer data, the Transport Layer header (TCP or UDP), and the IP layer header (the Network Layer takes the packet and turns it into a frame).

The Application Layer

...consists of all applications that use the network to transfer data. It does not care about how the data gets between two points and it knows very little about the status of the network. Applications pass data to the next layer in the TCP/IP stack and then continue to perform other functions until a reply is received. The Application Layer uses host names (like www.dalantech.com) for addressing. Examples of application layer protocols: Hyper Text Transfer Protocol (HTTP -web browsing), Simple Mail Transfer Protocol (SMTP -electronic mail), Domain Name Services (DNS -resolving a host name to an IP address), to name just a few.

The main purpose of the Application Layer is to provide a common command language and syntax between applications that are running on different operating systems -kind of like an interpreter. The data that is sent by an application that uses the network is formatted to conform to one of several set standards. The receiving computer can understand the data that is being sent even if it is running a different operating system than the sender due to the standards that all network applications conform to.

The Transport Layer

...is responsible for assigning source and destination port numbers to applications. Port numbers are used by the Transport Layer for addressing and they range from 1 to 65,535. Port numbers from 0 to 1023 are called "well known ports". The numbers below 256 are reserved for public (standard) services that run at the Application Layer. Here are a few: 25 for SMTP, 53 for DNS (udp for domain resolution and tcp for zone transfers) , and 80 for HTTP. The port numbers from 256 to 1023 are assigned by the IANA to companies for the applications that they sell.

Port numbers from 1024 to 65,535 are used for client side applications -the web browser you are using to read this page, for example. Windows will only assign port numbers up to 5000 -more than enough port numbers for a Windows based PC. Each application has a unique port number assigned to it by the transport layer so that as data is received by the Transport Layer it knows which application to give the data to. An example is when you have more than one browser window running. Each window is a separate instance of the program that you use to surf the web, and each one has a different port number assigned to it so you can go to www.dalantech.com in one browser window and this site does not load into another browser window. Applications like FireFox that use tabbed windows simply have a unique port number assigned to each tab

The Internet Layer

...is the "glue" that holds networking together. It permits the sending, receiving, and routing of data.

The Network Layer

...consists of your Network Interface Card (NIC) and the cable connected to it. It is the physical medium that is used to transmit and receive data. The Network Layer uses Media Access Control (MAC) addresses, discussed earlier, for addressing. The MAC address is fixed at the time an interface was manufactured and cannot be changed. There are a few exceptions, like DSL routers that allow you to clone the MAC address of the NIC in your PC.

For more info:

Convert Xml to DataTable

DataSet ds = new DataSet();
ds.ReadXml(fileNamePath);

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

Modern HTTP is stateful. Old timey HTTP was stateless.

Before Netscape invented cookies and HTTPS in 1994 http could be considered stateless. As time progressed more and more stateful aspects were added for a myriad of reasons, including performance and security.

While HTTP 1 originally sought out to be stateless many HTTP/2 components are the very definition of stateful. HTTP/2 abandoned stateless goals.

No reasonable person can read the HTTP/2 RFC and think it is stateless. The errant "HTTP is stateless" old time dogma is false and far from the current reality of stateful HTTP.

Here's a limited, and not exhaustive list, of stateful HTTP/1 and HTTP/2 components:

  • Cookies, named "HTTP State Management Mechanism" by the RFC.
  • HTTPS, which stores keys thus state.
  • HTTP authentication requires state.
  • Web Storage.
  • HTTP caching is stateful.
  • The very purpose of the stream identifier is state. It's even in the name of the RFC section, "Stream States".
  • Header blocks, which establish stream identifiers, are stateful.
  • Frames which reference stream identifiers are stateful.
  • Header Compression, which the HTTP RFC explicitly says is stateful, is stateful.
  • Opportunistic encryption is stateful.

Section 5.1 of the HTTP/2 RFC is a great example of stateful mechanisms defined by the HTTP/2 standard.

Is it safe for web applications to consider HTTP/2 as a stateless protocol?

HTTP/2 is a stateful protocol, but that doesn't mean your HTTP/2 application can't be stateless. You can choose to not use certain stateful features for stateless HTTP/2 applications by using only a subset of HTTP/2 features.

Cookies and some other stateful mechanisms, or less obvious stateful mechanisms, are later HTTP additions. HTTP 1 is said to be stateless although in practice we use standardized stateful mechanisms, like cookies, TLS, and caching. Unlike HTTP/1, HTTP/2 defines stateful components in its standard from the very beginning. A particular HTTP/2 application can use a subset of HTTP/2 features to maintain statelessness, but the protocol itself anticipate state to be the norm, not the exception.

Existing applications, even HTTP 1 applications, needing state will break if trying to use them statelessly. It can be impossible to log into some HTTP/1.1 websites if cookies are disabled, thus breaking the application. It may not be safe to assume that a particular HTTP 1 application does not use state. This is no different for HTTP/2.

Say it with me one last time:

HTTP/2 is a stateful protocol.

Should image size be defined in the img tag height/width attributes or in CSS?

Definitely not both. Other than that I'd have to say it's a personal preference. I'd use css if I had many images the same size to reduce code.

.my_images img {width: 20px; height:20px}

In the long term CSS may win out due to HTML attribute deprecation and more likely due to the growth of vector image formats like SVG where it can actually make sense to scale images using non-pixel based units like % or em.

How to start up spring-boot application via command line?

1.Run Spring Boot app with java -jar command

To run your Spring Boot app from a command line in a Terminal window you can use java -jar command. This is provided your Spring Boot app was packaged as an executable jar file.

java -jar target/app-0.0.1-SNAPSHOT.jar

2.Run Spring Boot app using Maven

You can also use Maven plugin to run your Spring Boot app. Use the below command to run your Spring Boot app with Maven plugin:

mvn spring-boot:run

3.Run Spring Boot App with Gradle

And if you use Gradle you can run the Spring Boot app with the following command:

gradle bootRun

Editing legend (text) labels in ggplot

The tutorial @Henrik mentioned is an excellent resource for learning how to create plots with the ggplot2 package.

An example with your data:

# transforming the data from wide to long
library(reshape2)
dfm <- melt(df, id = "TY")

# creating a scatterplot
ggplot(data = dfm, aes(x = TY, y = value, color = variable)) + 
  geom_point(size=5) +
  labs(title = "Temperatures\n", x = "TY [°C]", y = "Txxx", color = "Legend Title\n") +
  scale_color_manual(labels = c("T999", "T888"), values = c("blue", "red")) +
  theme_bw() +
  theme(axis.text.x = element_text(size = 14), axis.title.x = element_text(size = 16),
        axis.text.y = element_text(size = 14), axis.title.y = element_text(size = 16),
        plot.title = element_text(size = 20, face = "bold", color = "darkgreen"))

this results in:

enter image description here

As mentioned by @user2739472 in the comments: If you only want to change the legend text labels and not the colours from ggplot's default palette, you can use scale_color_hue(labels = c("T999", "T888")) instead of scale_color_manual().

How to Uninstall RVM?

It’s easy; just do the following:

rvm implode

or

rm -rf ~/.rvm

And don’t forget to remove the script calls in the following files:

  • ~/.bashrc
  • ~/.bash_profile
  • ~/.profile

And maybe others depending on whatever shell you’re using.

LINQ .Any VS .Exists - What's the difference?

TLDR; Performance-wise Any seems to be slower (if I have set this up properly to evaluate both values at almost same time)

        var list1 = Generate(1000000);
        var forceListEval = list1.SingleOrDefault(o => o == "0123456789012");
        if (forceListEval != "sdsdf")
        {
            var s = string.Empty;
            var start2 = DateTime.Now;
            if (!list1.Exists(o => o == "0123456789012"))
            {
                var end2 = DateTime.Now;
                s += " Exists: " + end2.Subtract(start2);
            }

            var start1 = DateTime.Now;
            if (!list1.Any(o => o == "0123456789012"))
            {
                var end1 = DateTime.Now;
                s +=" Any: " +end1.Subtract(start1);
            }

            if (!s.Contains("sdfsd"))
            {

            }

testing list generator:

private List<string> Generate(int count)
    {
        var list = new List<string>();
        for (int i = 0; i < count; i++)
        {
            list.Add( new string(
            Enumerable.Repeat("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 13)
                .Select(s =>
                {
                    var cryptoResult = new byte[4];
                    new RNGCryptoServiceProvider().GetBytes(cryptoResult);
                    return s[new Random(BitConverter.ToInt32(cryptoResult, 0)).Next(s.Length)];
                })
                .ToArray())); 
        }

        return list;
    }

With 10M records

" Any: 00:00:00.3770377 Exists: 00:00:00.2490249"

With 5M records

" Any: 00:00:00.0940094 Exists: 00:00:00.1420142"

With 1M records

" Any: 00:00:00.0180018 Exists: 00:00:00.0090009"

With 500k, (I also flipped around order in which they get evaluated to see if there is no additional operation associated with whichever runs first.)

" Exists: 00:00:00.0050005 Any: 00:00:00.0100010"

With 100k records

" Exists: 00:00:00.0010001 Any: 00:00:00.0020002"

It would seem Any to be slower by magnitude of 2.

Edit: For 5 and 10M records I changed the way it generates the list and Exists suddenly became slower than Any which implies there's something wrong in the way I am testing.

New testing mechanism:

private static IEnumerable<string> Generate(int count)
    {
        var cripto = new RNGCryptoServiceProvider();
        Func<string> getString = () => new string(
            Enumerable.Repeat("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 13)
                .Select(s =>
                {
                    var cryptoResult = new byte[4];
                    cripto.GetBytes(cryptoResult);
                    return s[new Random(BitConverter.ToInt32(cryptoResult, 0)).Next(s.Length)];
                })
                .ToArray());

        var list = new ConcurrentBag<string>();
        var x = Parallel.For(0, count, o => list.Add(getString()));
        return list;
    }

    private static void Test()
    {
        var list = Generate(10000000);
        var list1 = list.ToList();
        var forceListEval = list1.SingleOrDefault(o => o == "0123456789012");
        if (forceListEval != "sdsdf")
        {
            var s = string.Empty;

            var start1 = DateTime.Now;
            if (!list1.Any(o => o == "0123456789012"))
            {
                var end1 = DateTime.Now;
                s += " Any: " + end1.Subtract(start1);
            }

            var start2 = DateTime.Now;
            if (!list1.Exists(o => o == "0123456789012"))
            {
                var end2 = DateTime.Now;
                s += " Exists: " + end2.Subtract(start2);
            }

            if (!s.Contains("sdfsd"))
            {

            }
        }

Edit2: Ok so to eliminate any influence from generating test data I wrote it all to file and now read it from there.

 private static void Test()
    {
        var list1 = File.ReadAllLines("test.txt").Take(500000).ToList();
        var forceListEval = list1.SingleOrDefault(o => o == "0123456789012");
        if (forceListEval != "sdsdf")
        {
            var s = string.Empty;
            var start1 = DateTime.Now;
            if (!list1.Any(o => o == "0123456789012"))
            {
                var end1 = DateTime.Now;
                s += " Any: " + end1.Subtract(start1);
            }

            var start2 = DateTime.Now;
            if (!list1.Exists(o => o == "0123456789012"))
            {
                var end2 = DateTime.Now;
                s += " Exists: " + end2.Subtract(start2);
            }

            if (!s.Contains("sdfsd"))
            {
            }
        }
    }

10M

" Any: 00:00:00.1640164 Exists: 00:00:00.0750075"

5M

" Any: 00:00:00.0810081 Exists: 00:00:00.0360036"

1M

" Any: 00:00:00.0190019 Exists: 00:00:00.0070007"

500k

" Any: 00:00:00.0120012 Exists: 00:00:00.0040004"

enter image description here

Select multiple columns from a table, but group by one

I had a similar problem to the OP. Then I saw the answer from @Urs Marian which helped a lot. But additionally what I was looking for is, when there are multiple values in a column and they will be grouped, how I can get the last submitted value (e.g. ordered by a date/id column).

Example:

We have following table structure:

CREATE TABLE tablename(
    [msgid] [int] NOT NULL,
    [userid] [int] NOT NULL,
    [username] [varchar](70) NOT NULL,
    [message] [varchar](5000) NOT NULL
) 

Now there are at least two datasets in the table:

+-------+--------+----------+---------+
| msgid | userid | username | message |
+-------+--------+----------+---------+
|     1 |      1 | userA    | hello   |
|     2 |      1 | userB    | world   |
+-------+--------+----------+---------+

Therefore following SQL script does work (checked on MSSQL) to group it, also if the same userid has different username values. In the example below, the username with the highest msgid will be shown:

SELECT m.userid, 
(select top 1 username from table where userid = m.userid order by msgid desc) as username,
count(*) as messages
FROM tablename m
GROUP BY m.userid
ORDER BY count(*) DESC

How can I make Flexbox children 100% height of their parent?

An idea would be that display:flex; with flex-direction: row; is filling the container div with .flex-1 and .flex-2, but that does not mean that .flex-2 has a default height:100%;, even if it is extended to full height.

And to have a child element (.flex-2-child) with height:100%;, you'll need to set the parent to height:100%; or use display:flex; with flex-direction: row; on the .flex-2 div too.

From what I know, display:flex will not extend all your child elements height to 100%.

A small demo, removed the height from .flex-2-child and used display:flex; on .flex-2: http://jsfiddle.net/2ZDuE/3/

Math.random() explanation

The Random class of Java located in the java.util package will serve your purpose better. It has some nextInt() methods that return an integer. The one taking an int argument will generate a number between 0 and that int, the latter not inclusive.

How to perform string interpolation in TypeScript?

Just use special `

var lyrics = 'Never gonna give you up';
var html = `<div>${lyrics}</div>`;

You can see more examples here.

How to use: while not in

In your case, ('AND' and 'OR' and 'NOT') evaluates to "NOT", which may or may not be in your list...

while 'AND' not in MyList and 'OR' not in MyList and 'NOT' not in MyList:
    print 'No Boolean Operator'

How to duplicate a git repository? (without forking)

I have noticed some of the other answers here use a bare clone and then mirror push to the new repository, however this does not work for me and when I open the new repository after that, the files look mixed up and not as I expect.

Here is a solution that definitely works for copying the files, although it does not preserve the original repository's revision history.

  1. git clone the repository onto your local machine.
  2. cd into the project directory and then run rm -rf .git to remove all the old git metadata including commit history, etc.
  3. Initialize a fresh git repository by running git init.
  4. Run git add . ; git commit -am "Initial commit" - Of course you can call this commit what you want.
  5. Set the origin to your new repository git remote add origin https://github.com/user/repo-name (replace the url with the url to your new repository)
  6. Push it to your new repository with git push origin master.

Python OpenCV2 (cv2) wrapper to get image size?

I'm afraid there is no "better" way to get this size, however it's not that much pain.

Of course your code should be safe for both binary/mono images as well as multi-channel ones, but the principal dimensions of the image always come first in the numpy array's shape. If you opt for readability, or don't want to bother typing this, you can wrap it up in a function, and give it a name you like, e.g. cv_size:

import numpy as np
import cv2

# ...

def cv_size(img):
    return tuple(img.shape[1::-1])

If you're on a terminal / ipython, you can also express it with a lambda:

>>> cv_size = lambda img: tuple(img.shape[1::-1])
>>> cv_size(img)
(640, 480)

Writing functions with def is not fun while working interactively.

Edit

Originally I thought that using [:2] was OK, but the numpy shape is (height, width[, depth]), and we need (width, height), as e.g. cv2.resize expects, so - we must use [1::-1]. Even less memorable than [:2]. And who remembers reverse slicing anyway?

Android overlay a view ontop of everything?

I have just made a solution for it. I made a library for this to do that in a reusable way that's why you don't need to recode in your XML. Here is documentation on how to use it in Java and Kotlin. First, initialize it from an activity from where you want to show the overlay-

AppWaterMarkBuilder.doConfigure()
                .setAppCompatActivity(MainActivity.this)
                .setWatermarkProperty(R.layout.layout_water_mark)
                .showWatermarkAfterConfig();

Then you can hide and show it from anywhere in your app -

  /* For hiding the watermark*/
  AppWaterMarkBuilder.hideWatermark() 

  /* For showing the watermark*/
  AppWaterMarkBuilder.showWatermark() 

Gif preview -

preview

Appending a byte[] to the end of another byte[]

Using System.arraycopy(), something like the following should work:

// create a destination array that is the size of the two arrays
byte[] destination = new byte[ciphertext.length + mac.length];

// copy ciphertext into start of destination (from pos 0, copy ciphertext.length bytes)
System.arraycopy(ciphertext, 0, destination, 0, ciphertext.length);

// copy mac into end of destination (from pos ciphertext.length, copy mac.length bytes)
System.arraycopy(mac, 0, destination, ciphertext.length, mac.length);

How to update a record using sequelize for node?

Using async and await in a modern javascript Es6

const title = "title goes here";
const id = 1;

    try{
    const result = await Project.update(
          { title },
          { where: { id } }
        )
    }.catch(err => console.log(err));

you can return result ...

SQLSTATE[HY000] [1045] Access denied for user 'username'@'localhost' using CakePHP

If you use MAMP, you might have to set the socket: unix_socket: /Applications/MAMP/tmp/mysql/mysql.sock

How to create a DB link between two oracle instances

Creation of DB Link

CREATE DATABASE LINK dblinkname
CONNECT TO $usename
IDENTIFIED BY $password
USING '$sid';

(Note: sid is being passed between single quotes above. )

Example Queries for above DB Link

select * from tableA@dblinkname;

insert into tableA(select * from tableA@dblinkname);

How to convert an enum type variable to a string?

In c++ like this:

enum OS_type{Linux, Apple, Windows};

std::string ToString( const OS_type v )
{
  const std::map< OS_type, std::string > lut =
    boost::assign::map_list_of( Linux, "Linux" )(Apple, "Apple )( Windows,"Windows");
  std::map< OS_type, std::string >::const_iterator it = lut.find( v );
  if ( lut.end() != it )
    return it->second;
  return "NOT FOUND";
}

Can I use DIV class and ID together in CSS?

Yes, why not? Then CSS that applies to class "x" AND CSS that applies to ID "y" applies to the div.

How can I post an array of string to ASP.NET MVC Controller without a form?

I modified my response to include the code for a test app I did.

Update: I have updated the jQuery to set the 'traditional' setting to true so this will work again (per @DustinDavis' answer).

First the javascript:

function test()
{
    var stringArray = new Array();
    stringArray[0] = "item1";
    stringArray[1] = "item2";
    stringArray[2] = "item3";
    var postData = { values: stringArray };

    $.ajax({
        type: "POST",
        url: "/Home/SaveList",
        data: postData,
        success: function(data){
            alert(data.Result);
        },
        dataType: "json",
        traditional: true
    });
}

And here's the code in my controller class:

public JsonResult SaveList(List<String> values)
{
    return Json(new { Result = String.Format("Fist item in list: '{0}'", values[0]) });
}

When I call that javascript function, I get an alert saying "First item in list: 'item1'". Hope this helps!

Retrieving Dictionary Value Best Practices

TryGetValue is slightly faster, because FindEntry will only be called once.

How much faster? It depends on the dataset at hand. When you call the Contains method, Dictionary does an internal search to find its index. If it returns true, you need another index search to get the actual value. When you use TryGetValue, it searches only once for the index and if found, it assigns the value to your variable.

FYI: It's not actually catching an error.

It's calling:

public bool TryGetValue(TKey key, out TValue value)
{
    int index = this.FindEntry(key);
    if (index >= 0)
    {
        value = this.entries[index].value;
        return true;
    }
    value = default(TValue);
    return false;
}

ContainsKey is this:

public bool ContainsKey(TKey key)
{
    return (this.FindEntry(key) >= 0);
}

Max value of Xmx and Xms in Eclipse?

I am guessing you are using a 32 bit eclipse with 32 bit JVM. It wont allow heapsize above what you have specified.

Using a 64-bit Eclipse with a 64-bit JVM helps you to start up eclipse with much larger memory. (I am starting with -Xms1024m -Xmx4000m)

Java, Check if integer is multiple of a number

//More Efficiently
public class Multiples {
    public static void main(String[]args) {

        int j = 5;

        System.out.println(j % 4 == 0);

    }
}

How can I change Eclipse theme?

The best way to Install new themes in any Eclipse platform is to use the Eclipse Marketplace.

1.Go to Help > Eclipse Marketplace

2.Search for "Color Themes"

3.Install and Restart

4.Go to Window > Preferences > General > Appearance > Color Themes

5.Select anyone and Apply. Restart.

3-dimensional array in numpy

No need to go in such deep technicalities, and get yourself blasted. Let me explain it in the most easiest way. We all have studied "Sets" during our school-age in Mathematics. Just consider 3D numpy array as the formation of "sets".

x = np.zeros((2,3,4)) 

Simply Means:

2 Sets, 3 Rows per Set, 4 Columns

Example:

Input

x = np.zeros((2,3,4))

Output

Set # 1 ---- [[[ 0.,  0.,  0.,  0.],  ---- Row 1
               [ 0.,  0.,  0.,  0.],  ---- Row 2
               [ 0.,  0.,  0.,  0.]], ---- Row 3 
    
Set # 2 ----  [[ 0.,  0.,  0.,  0.],  ---- Row 1
               [ 0.,  0.,  0.,  0.],  ---- Row 2
               [ 0.,  0.,  0.,  0.]]] ---- Row 3

Explanation: See? we have 2 Sets, 3 Rows per Set, and 4 Columns.

Note: Whenever you see a "Set of numbers" closed in double brackets from both ends. Consider it as a "set". And 3D and 3D+ arrays are always built on these "sets".

Capture key press without placing an input element on the page?

jQuery also has an excellent implementation that's incredibly easy to use. Here's how you could implement this functionality across browsers:

$(document).keypress(function(e){
    var checkWebkitandIE=(e.which==26 ? 1 : 0);
    var checkMoz=(e.which==122 && e.ctrlKey ? 1 : 0);

    if (checkWebkitandIE || checkMoz) $("body").append("<p>ctrl+z detected!</p>");
});

Tested in IE7,Firefox 3.6.3 & Chrome 4.1.249.1064

Another way of doing this is to use the keydown event and track the event.keyCode. However, since jQuery normalizes keyCode and charCode using event.which, their spec recommends using event.which in a variety of situations:

$(document).keydown(function(e){
if (e.keyCode==90 && e.ctrlKey)
    $("body").append("<p>ctrl+z detected!</p>");
});

Laravel 5: Retrieve JSON array from $request

Just a mention with jQuery v3.2.1 and Laravel 5.6.

Case 1: The JS object posted directly, like:

$.post("url", {name:'John'}, function( data ) {
});

Corresponding Laravel PHP code should be:

parse_str($request->getContent(),$data); //JSON will be parsed to object $data

Case 2: The JSON string posted, like:

$.post("url", JSON.stringify({name:'John'}), function( data ) {
});

Corresponding Laravel PHP code should be:

$data = json_decode($request->getContent(), true);

Identify if a string is a number

All the Answers are Useful. But while searching for a solution where the Numeric value is 12 digits or more (in my case), then while debugging, I found the following solution useful :

double tempInt = 0;
bool result = double.TryParse("Your_12_Digit_Or_more_StringValue", out tempInt);

Th result variable will give you true or false.

.htaccess - how to force "www." in a generic way?

This is an older question, and there are many different ways to do this. The most complete answer, IMHO, is found here: https://gist.github.com/vielhuber/f2c6bdd1ed9024023fe4 . (Pasting and formatting the code here didn't work for me)

How to Read and Write from the Serial Port

SerialPort (RS-232 Serial COM Port) in C# .NET
This article explains how to use the SerialPort class in .NET to read and write data, determine what serial ports are available on your machine, and how to send files. It even covers the pin assignments on the port itself.

Example Code:

using System;
using System.IO.Ports;
using System.Windows.Forms;

namespace SerialPortExample
{
  class SerialPortProgram
  {
    // Create the serial port with basic settings
    private SerialPort port = new SerialPort("COM1",
      9600, Parity.None, 8, StopBits.One);

    [STAThread]
    static void Main(string[] args)
    { 
      // Instatiate this class
      new SerialPortProgram();
    }

    private SerialPortProgram()
    {
      Console.WriteLine("Incoming Data:");

      // Attach a method to be called when there
      // is data waiting in the port's buffer
      port.DataReceived += new 
        SerialDataReceivedEventHandler(port_DataReceived);

      // Begin communications
      port.Open();

      // Enter an application loop to keep this thread alive
      Application.Run();
    }

    private void port_DataReceived(object sender,
      SerialDataReceivedEventArgs e)
    {
      // Show all the incoming data in the port's buffer
      Console.WriteLine(port.ReadExisting());
    }
  }
}

break/exit script

Not pretty, but here is a way to implement an exit() command in R which works for me.

exit <- function() {
  .Internal(.invokeRestart(list(NULL, NULL), NULL))
}

print("this is the last message")
exit()
print("you should not see this")

Only lightly tested, but when I run this, I see this is the last message and then the script aborts without any error message.

Implementing multiple interfaces with Java - is there a way to delegate?

There is one way to implement multiple interface.

Just extend one interface from another or create interface that extends predefined interface Ex:

public interface PlnRow_CallBack extends OnDateSetListener {
    public void Plan_Removed();
    public BaseDB getDB();
}

now we have interface that extends another interface to use in out class just use this new interface who implements two or more interfaces

public class Calculator extends FragmentActivity implements PlnRow_CallBack {

    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

    }

    @Override
    public void Plan_Removed() {

    }

    @Override
    public BaseDB getDB() {

    }
}

hope this helps

Is there an XSLT name-of element?

Nobody did point the subtle difference in the semantics of the functions name() and local-name().

  • name(someNode) returns the full name of the node, and that includes the prefix and colon in case the node is an element or an attribute.
  • local-name(someNode) returns only the local name of the node, and that doesn't include the prefix and colon in case the node is an element or an attribute.

Therefore, in situations where a name may belong to two different namespaces, one must use the name() function in order for these names to be still distinguished.

And, BTW, it is possible to specify both functions without any argument:

name() is an abbreviation for name(.)

local-name() is an abbreviation for local-name(.)

Finally, do remember that not only elements and attributes have names, these two functions can also be used on PIs and on these they are identical).

How to change background color in android app

android:background="#64B5F6"
You can change the value after '#' according to your own specification or need depending on how you want to use them.
Here is a sample code:

_x000D_
_x000D_
<TextView_x000D_
        android:text="Abir"_x000D_
        android:layout_width="match_parent"_x000D_
        android:layout_height="wrap_content"_x000D_
        android:textSize="24sp"_x000D_
        android:background="#D4E157"  />
_x000D_
_x000D_
_x000D_

Thank you :)

Maximum packet size for a TCP connection

The absolute limitation on TCP packet size is 64K (65535 bytes), but in practicality this is far larger than the size of any packet you will see, because the lower layers (e.g. ethernet) have lower packet sizes.

The MTU (Maximum Transmission Unit) for Ethernet, for instance, is 1500 bytes. Some types of networks (like Token Ring) have larger MTUs, and some types have smaller MTUs, but the values are fixed for each physical technology.

Is there a way to represent a directory tree in a Github README.md?

You can also check this tree-extended package. It can be used as a command line app by using node >= 6.x.

It is very similar to tree but also has the option of configuring the max deep in the tree, that is one of the awful things of it. Also you can filter by using .gitignore file.

enter image description here

JVM property -Dfile.encoding=UTF8 or UTF-8?

This is not a direct answer, but very useful if you don't have access to how java starts: you can set the environment variable JAVA_TOOLS_OPTIONS to -Dfile.encoding="UTF-8" and every time the jvm starts it will pick up that option.

How to create a numpy array of all True or all False?

numpy.full((2,2), True, dtype=bool)

How to hide close button in WPF window?

As stated in other answers, you can use WindowStyle="None" to remove the Title Bar altogether.

And, as stated in the comments to those other answers, this prevents the window from being draggable so it is hard to move it from its initial position.

However, you can overcome this by adding a single line of code to the Constructor in the Window's Code Behind file:

MouseDown += delegate { DragMove(); };

Or, if you prefer Lambda Syntax:

MouseDown += (sender, args) => DragMove();

This makes the entire Window draggable. Any interactive controls present in the Window, such as Buttons, will still work as normal and won't act as drag-handles for the Window.

JQuery .hasClass for multiple values in an if statement

This is in case you need both classes present. For either or logic just use ||

$('el').hasClass('first-class') || $('el').hasClass('second-class')

Feel free to optimize as needed

can't load package: package .: no buildable Go source files

You should check the $GOPATH directory. If there is an empty directory of the package name, go get doesn't download the package from the repository.

For example, If I want to get the github.com/googollee/go-socket.io package from it's github repository, and there is already an empty directory github.com/googollee/go-socket.io in the $GOPATH, go get doesn't download the package and then complains that there is no buildable Go source file in the directory. Delete any empty directory first of all.

Is true == 1 and false == 0 in JavaScript?

with == you are essentially comparing whether a variable is falsey when comparing to false or truthey when comparing to true. If you use ===, it will compare the exact value of the variables so true will not === 1

postgres, ubuntu how to restart service on startup? get stuck on clustering after instance reboot

I guess it would be best to fix the database startup script itself. But as a work around, you can add that line to /etc/rc.local, which is executed about last in init phase.

Python: call a function from string name

If it's in a class, you can use getattr:

class MyClass(object):
    def install(self):
          print "In install"

method_name = 'install' # set by the command line options
my_cls = MyClass()

method = None
try:
    method = getattr(my_cls, method_name)
except AttributeError:
    raise NotImplementedError("Class `{}` does not implement `{}`".format(my_cls.__class__.__name__, method_name))

method()

or if it's a function:

def install():
       print "In install"

method_name = 'install' # set by the command line options
possibles = globals().copy()
possibles.update(locals())
method = possibles.get(method_name)
if not method:
     raise NotImplementedError("Method %s not implemented" % method_name)
method()

UnsupportedClassVersionError: JVMCFRE003 bad major version in WebSphere AS 7

I was getting this error in websphere 8.5:

java.lang.UnsupportedClassVersionError: JVMCFRE003 bad major version; class=com/xxx/Whatever, offset=6

I had my project JDK level set at 1.7 in eclipse and was8 by default runs on JDK 1.6 so there was a clash. I had to install the optional SDK 1.7 to my websphere server and then the problem went away. I guess I could have also set my project level down to 1.6 in eclipse but I wanted to code to 1.7.

How do I do a HTTP GET in Java?

The simplest way that doesn't require third party libraries it to create a URL object and then call either openConnection or openStream on it. Note that this is a pretty basic API, so you won't have a lot of control over the headers.

how to install Lex and Yacc in Ubuntu?

Use the synaptic packet manager in order to install yacc / lex. If you are feeling more comfortable doing this on the console just do:

sudo apt-get install bison flex

There are some very nice articles on the net on how to get started with those tools. I found the article from CodeProject to be quite good and helpful (see here). But you should just try and search for "introduction to lex", there are plenty of good articles showing up.

Linux / Bash, using ps -o to get process by specific name?

This is a bit old, but I guess what you want is: ps -o pid -C PROCESS_NAME, for example:

ps -o pid -C bash

EDIT: Dependening on the sort of output you expect, pgrep would be more elegant. This, in my knowledge, is Linux specific and result in similar output as above. For example:

pgrep bash

Execute command on all files in a directory

One quick and dirty way which gets the job done sometimes is:

find directory/ | xargs  Command 

For example to find number of lines in all files in the current directory, you can do:

find . | xargs wc -l

ActionController::InvalidAuthenticityToken

Maybe you have your NGINX setup for HTTPS but your certificates are invalid? I've had a similar problem in the past and redirecting from http to https solved the problem

python: Appending a dictionary to a list - I see a pointer like behavior

Also with dict

a = []
b = {1:'one'}

a.append(dict(b))
print a
b[1]='iuqsdgf'
print a

result

[{1: 'one'}]
[{1: 'one'}]

Display TIFF image in all web browser

This comes down to browser image support; it looks like the only mainstream browser that supports tiff is Safari:

http://en.wikipedia.org/wiki/Comparison_of_web_browsers#Image_format_support

Where are you getting the tiff images from? Is it possible for them to be generated in a different format?

If you have a static set of images then I'd recommend using something like PaintShop Pro to batch convert them, changing the format.

If this isn't an option then there might be some mileage in looking for a pre-written Java applet (or another browser plugin) that can display the images in the browser.

What does ==$0 (double equals dollar zero) mean in Chrome Developer Tools?

The other answers here clearly explained what does it mean.I like to explain its use.

You can select an element in the elements tab and switch to console tab in chrome. Just type $0 or $1 or whatever number and press enter and the element will be displayed in the console for your use.

screenshot of chrome dev tools

Regular expression to find URLs within a string

Guess no regex is perfect for this use. I found a pretty solid one here

/(?:(?:https?|ftp|file):\/\/|www\.|ftp\.)(?:\([-A-Z0-9+&@#\/%=~_|$?!:,.]*\)|[-A-Z0-9+&@#\/%=~_|$?!:,.])*(?:\([-A-Z0-9+&@#\/%=~_|$?!:,.]*\)|[A-Z0-9+&@#\/%=~_|$])/igm

Some differences / advantages compared to the other ones posted here:

  • It does not match email addresses
  • It does match localhost:12345
  • It won't detect something like moo.com without http or www

See here for examples

How to permanently add a private key with ssh-add on Ubuntu?

A solution would be to force the key files to be kept permanently, by adding them in your ~/.ssh/config file:

IdentityFile ~/.ssh/gitHubKey
IdentityFile ~/.ssh/id_rsa_buhlServer

If you do not have a 'config' file in the ~/.ssh directory, then you should create one. It does not need root rights, so simply:

nano ~/.ssh/config

...and enter the lines above as per your requirements.

For this to work the file needs to have chmod 600. You can use the command chmod 600 ~/.ssh/config.

If you want all users on the computer to use the key put these lines into /etc/ssh/ssh_config and the key in a folder accessible to all.

Additionally if you want to set the key specific to one host, you can do the following in your ~/.ssh/config :

Host github.com
    User git
    IdentityFile ~/.ssh/githubKey

This has the advantage when you have many identities that a server doesn't reject you because you tried the wrong identities first. Only the specific identity will be tried.

How can I add a volume to an existing Docker container?

We don't have any way to add volume in running container, but to achieve this objective you may use the below commands:

Copy files/folders between a container and the local filesystem:

docker cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH

docker cp [OPTIONS] SRC_PATH CONTAINER:DEST_PATH

For reference see:

https://docs.docker.com/engine/reference/commandline/cp/

How to set Apache Spark Executor memory

spark-submit \

  --class org.apache.spark.examples.SparkPi \

  --master yarn \

  --deploy-mode cluster \  # can be client for client mode

  --executor-memory 2G \

  --num-executors 5 \

  /path/to/examples.jar \

  1000

How to download file from database/folder using php

here is the code to download file with how much % it is downloaded

<?php
$ch = curl_init();
$downloadFile = fopen( 'file name here', 'w' );
curl_setopt($ch, CURLOPT_URL, "file link here");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_BUFFERSIZE, 65536);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, 'downloadProgress'); 
curl_setopt($ch, CURLOPT_NOPROGRESS, false);
curl_setopt( $ch, CURLOPT_FILE, $downloadFile );
curl_exec($ch);
curl_close($ch);

function downloadProgress ($resource, $download_size, $downloaded_size, $upload_size, $uploaded_size) {

    if($download_size!=0){
    $percen= (($downloaded_size/$download_size)*100);
    echo $percen."<br>";

}

}
?>

Angular2 *ngIf check object array length in template

You could use *ngIf="teamMembers != 0" to check whether data is present

java.net.SocketTimeoutException: Read timed out under Tomcat

Server is trying to read data from the request, but its taking longer than the timeout value for the data to arrive from the client. Timeout here would typically be tomcat connector -> connectionTimeout attribute.

Correct.

Client has a read timeout set, and server is taking longer than that to respond.

No. That would cause a timeout at the client.

One of the threads i went through, said this can happen with high concurrency and if the keepalive is enabled.

That is obviously guesswork, and completely incorrect. It happens if and only if no data arrives within the timeout. Period. Load and keepalive and concurrency have nothing to do with it whatsoever.

It just means the client isn't sending. You don't need to worry about it. Browser clients come and go in all sorts of strange ways.

Formula to convert date to number

The Excel number for a modern date is most easily calculated as the number of days since 12/30/1899 on the Gregorian calendar.

Excel treats the mythical date 01/00/1900 (i.e., 12/31/1899) as corresponding to 0, and incorrectly treats year 1900 as a leap year. So for dates before 03/01/1900, the Excel number is effectively the number of days after 12/31/1899.

However, Excel will not format any number below 0 (-1 gives you ##########) and so this only matters for "01/00/1900" to 02/28/1900, making it easier to just use the 12/30/1899 date as a base.

A complete function in DB2 SQL that accounts for the leap year 1900 error:

SELECT
   DAYS(INPUT_DATE)                 
   - DAYS(DATE('1899-12-30'))
   - CASE                       
        WHEN INPUT_DATE < DATE('1900-03-01')  
           THEN 1               
           ELSE 0               
     END

How to set default text for a Tkinter Entry widget

Use Entry.insert. For example:

try:
    from tkinter import *  # Python 3.x
except Import Error:
    from Tkinter import *  # Python 2.x

root = Tk()
e = Entry(root)
e.insert(END, 'default text')
e.pack()
root.mainloop()

Or use textvariable option:

try:
    from tkinter import *  # Python 3.x
except Import Error:
    from Tkinter import *  # Python 2.x

root = Tk()
v = StringVar(root, value='default text')
e = Entry(root, textvariable=v)
e.pack()
root.mainloop()

How to execute a Ruby script in Terminal?

Just call: ruby your_program.rb

or

  • start your program with #!/usr/bin/env ruby,
  • make your file executable by running chmod +x your_program.rb
  • and do ./your_program.rb some_param

Changing ViewPager to enable infinite page scrolling

Actually, I've been looking at the various ways to do this "infinite" pagination, and even though the human notion of time is that it is infinite (even though we have a notion of the beginning and end of time), computers deal in the discrete. There is a minimum and maximum time (that can be adjusted as time goes on, remember the basis of the Y2K scare?).

Anyways, the point of this discussion is that it is/should be sufficient to support a relatively infinite date range through an actually finite date range. A great example of this is the Android framework's CalendarView implementation, and the WeeksAdapter within it. The default minimum date is in 1900 and the default maximum date is in 2100, this should cover 99% of the calendar use of anyone within a 10 year radius around today easily.

What they do in their implementation (focused on weeks) is compute the number of weeks between the minimum and maximum date. This becomes the number of pages in the pager. Remember that the pager doesn't need to maintain all of these pages simultaneously (setOffscreenPageLimit(int)), it just needs to be able to create the page based on the page number (or index/position). In this case the index is the number of weeks that the week is from the minimum date. With this approach you just have to maintain the minimum date and the number of pages (distance to the maximum date), then for any page you can easily compute the week associated with that page. No dancing around the fact that ViewPager doesn't support looping (a.k.a infinite pagination), and trying to force it to behave like it can scroll infinitely.

new FragmentStatePagerAdapter(getFragmentManager()) {
    @Override
    public Fragment getItem(int index) {
        final Bundle arguments = new Bundle(getArguments());
        final Calendar temp_calendar = Calendar.getInstance();
        temp_calendar.setTimeInMillis(_minimum_date.getTimeInMillis());
        temp_calendar.setFirstDayOfWeek(_calendar.getStartOfWeek());
        temp_calendar.add(Calendar.WEEK_OF_YEAR, index);
        // Moves to the first day of this week
        temp_calendar.add(Calendar.DAY_OF_YEAR,
                -UiUtils.modulus(temp_calendar.get(Calendar.DAY_OF_WEEK) - temp_calendar.getFirstDayOfWeek(),
                7));
        arguments.putLong(KEY_DATE, temp_calendar.getTimeInMillis());
        return Fragment.instantiate(getActivity(), WeekDaysFragment.class.getName(), arguments);
    }

    @Override
    public int getCount() {
        return _total_number_of_weeks;
    }
};

Then WeekDaysFragment can easily display the week starting at the date passed in its arguments.

Alternatively, it seems that some version of the Calendar app on Android uses a ViewSwitcher (which means there's only 2 pages, the one you see and the hidden page). It then changes the transition animation based on which way the user swiped and renders the next/previous page accordingly. In this way you get infinite pagination because it just switching between two pages infinitely. This requires using a View for the page though, which is way I went with the first approach.

In general, if you want "infinite pagination", it's probably because your pages are based off of dates or times somehow. If this is the case consider using a finite subset of time that is relatively infinite instead. This is how CalendarView is implemented for example. Or you can use the ViewSwitcher approach. The advantage of these two approaches is that neither does anything particularly unusual with the ViewSwitcher or ViewPager, and doesn't require any tricks or reimplementation to coerce them to behave infinitely (ViewSwitcher is already designed to switch between views infinitely, but ViewPager is designed to work on a finite, but not necessarily constant, set of pages).

Apache 2.4.6 on Ubuntu Server: Client denied by server configuration (PHP FPM) [While loading PHP file]

I had the following configuration in my httpd.conf that denied executing the wpadmin/setup-config.php file from wordpress. Removing the |-config part solved the problem. I think this httpd.conf is from plesk but it could be some default suggested config from wordpress, i don't know. Anyway, I could safely add it back after the setup finished.

<LocationMatch "(?i:(?:wp-config\\.bak|\\.wp-config\\.php\\.swp|(?:readme|license|changelog|-config|-sample)\\.(?:php|md|txt|htm|html)))">
                        Require all denied
                </LocationMatch>

Unzip a file with php

Just use this:

  $master = $_GET["master"];
  system('unzip' $master.'.zip'); 

in your code $master is passed as a string, system will be looking for a file called $master.zip

  $master = $_GET["master"];
  system('unzip $master.zip'); `enter code here`

Composer killed while updating

You can try setting preferred-install to "dist" in Composer config.

How to check if a value exists in an object using JavaScript

Shortest ES6+ one liner:

let exists = Object.values(obj).includes("test1");

Beamer: How to show images as step-by-step images

I found a solution to my problem, by using the visble-command.

EDITED:

\visible<2->{
   \textbf{Some text}
   \begin{figure}[ht]
       \includegraphics[width=5cm]{./path/to/image}
    \end{figure}
 }

Class Diagrams in VS 2017

Woo-hoo! It works with some hack!

According to this comment you need to:

  1. Manually edit Microsoft.CSharp.DesignTime.targets located in C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\Microsoft\VisualStudio\Managed (for VS Community edition, modify path for other editions), append ClassDesigner value to ProjectCapability (right pane):File diff

  2. Restart VS.

  3. Manually create text file, say MyClasses.cd with following content: <?xml version="1.0" encoding="utf-8"?> <ClassDiagram MajorVersion="1" MinorVersion="1"> <Font Name="Segoe UI" Size="9" /> </ClassDiagram>

Bingo. Now you may open this file in VS. You will see error message "Object reference not set to an instance of object" once after VS starts, but diagram works.

Checked on VS 2017 Community Edition, v15.3.0 with .NETCore 2.0 app/project:

enter image description here

GitHub issue expected to fix in v15.5

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

This will open a second cmd.exe window. If you want it to go away, replace the /K with /C.

Obviously, replace new_file_loc with whatever your new file location will be.

@echo off
for /F %%i in ('dir /B /O:-D *.txt') do (
    call :open "%%i"
    exit /B 0
)
:open
    start "window title" "cmd /K copy %~1 new_file_loc"
exit /B 0

Importing json file in TypeScript

Often in Node.js applications a .json is needed. With TypeScript 2.9, --resolveJsonModule allows for importing, extracting types from and generating .json files.

Example #

_x000D_
_x000D_
// tsconfig.json_x000D_
_x000D_
{_x000D_
    "compilerOptions": {_x000D_
        "module": "commonjs",_x000D_
        "resolveJsonModule": true,_x000D_
        "esModuleInterop": true_x000D_
    }_x000D_
}_x000D_
_x000D_
// .ts_x000D_
_x000D_
import settings from "./settings.json";_x000D_
_x000D_
settings.debug === true;  // OK_x000D_
settings.dry === 2;  // Error: Operator '===' cannot be applied boolean and number_x000D_
_x000D_
_x000D_
// settings.json_x000D_
_x000D_
{_x000D_
    "repo": "TypeScript",_x000D_
    "dry": false,_x000D_
    "debug": false_x000D_
}
_x000D_
_x000D_
_x000D_ by: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-9.html

In Java, how do I call a base class's method from the overriding method in a derived class?

class test
{
    void message()
    {
        System.out.println("super class");
    }
}

class demo extends test
{
    int z;
    demo(int y)
    {
        super.message();
        z=y;
        System.out.println("re:"+z);
    }
}
class free{
    public static void main(String ar[]){
        demo d=new demo(6);
    }
}

Could not reliably determine the server's fully qualified domain name

Under Debian Squeeze;

  1. Edit Apache2 conf file : vim /etc/apache2/apache2.conf
  2. Insert the following line at the apache2.conf: ServerName localhost
  3. Restart Apache2: apache2ctl restart or /etc/init.d/apache2 restart

Should work fine (it did solve the problem in my case)

tks noodl for the link on the different layouts. :)

Uncaught SyntaxError: Invalid or unexpected token

The accepted answer work when you have a single line string(the email) but if you have a

multiline string, the error will remain.

Please look into this matter:

<!-- start: definition-->
@{
    dynamic item = new System.Dynamic.ExpandoObject();
    item.MultiLineString = @"a multi-line
                             string";
    item.SingleLineString = "a single-line string";
}
<!-- end: definition-->
<a href="#" onclick="Getinfo('@item.MultiLineString')">6/16/2016 2:02:29 AM</a>
<script>
    function Getinfo(text) {
        alert(text);
    }
</script>

Change the single-quote(') to backtick(`) in Getinfo as bellow and error will be fixed:

<a href="#" onclick="Getinfo(`@item.MultiLineString`)">6/16/2016 2:02:29 AM</a>

Start systemd service after specific service?

In the .service file under the [Unit] section:

[Unit]
Description=My Website
After=syslog.target network.target mongodb.service

The important part is the mongodb.service

The manpage describes it however due to formatting it's not as clear on first sight

systemd.unit - well formatted

systemd.unit - not so well formatted

Horizontal scroll css?

use max-width instead of width

max-width:530px;

demo:http://jsfiddle.net/FPBWr/161/

How to change the length of a column in a SQL Server table via T-SQL

So, let's say you have this table:

CREATE TABLE YourTable(Col1 VARCHAR(10))

And you want to change Col1 to VARCHAR(20). What you need to do is this:

ALTER TABLE YourTable
ALTER COLUMN Col1 VARCHAR(20)

That'll work without problems since the length of the column got bigger. If you wanted to change it to VARCHAR(5), then you'll first gonna need to make sure that there are not values with more chars on your column, otherwise that ALTER TABLE will fail.

Printing Mongo query output to a file while in the mongo shell

There are ways to do this without having to quit the CLI and pipe mongo output to a non-tty.

To save the output from a query with result x we can do the following to directly store the json output to /tmp/x.json:

> EDITOR="cat > /tmp/x.json"
> x = db.MyCollection.find(...).toArray()
> edit x
>

Note that the output isn't strictly Json but rather the dialect that Mongo uses.

What causes a Python segmentation fault?

Segmentation fault is a generic one, there are many possible reasons for this:

  • Low memory
  • Faulty Ram memory
  • Fetching a huge data set from the db using a query (if the size of fetched data is more than swap mem)
  • wrong query / buggy code
  • having long loop (multiple recursion)

How to set up fixed width for <td>?

Hopefully this one will help someone:

<table class="table">
  <thead>
    <tr>
      <th style="width: 30%">Col 1</th>
      <th style="width: 20%">Col 2</th>
      <th style="width: 10%">Col 3</th>
      <th style="width: 30%">Col 4</th>
      <th style="width: 10%">Col 5</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Val 1</td>
      <td>Val 2</td>
      <td>Val 3</td>
      <td>Val 4</td>
      <td>Val 5</td>
    </tr>
  </tbody>
</table>

https://github.com/twbs/bootstrap/issues/863

How to parse JSON with VBA without external libraries?

There are two issues here. The first is to access fields in the array returned by your JSON parse, the second is to rename collections/fields (like sentences) away from VBA reserved names.

Let's address the second concern first. You were on the right track. First, replace all instances of sentences with jsentences If text within your JSON also contains the word sentences, then figure out a way to make the replacement unique, such as using "sentences":[ as the search string. You can use the VBA Replace method to do this.

Once that's done, so VBA will stop renaming sentences to Sentences, it's just a matter of accessing the array like so:

'first, declare the variables you need:
Dim jsent as Variant

'Get arr all setup, then
For Each jsent in arr.jsentences
  MsgBox(jsent.orig)
Next

How to get text with Selenium WebDriver in Python

This is the correct answer. It worked!!

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait

driver = webdriver.Chrome("E:\\Python\\selenium\\webdriver\\chromedriver.exe")
driver.get("https://www.tatacliq.com/global-desi-navy-embroidered-kurta/p-mp000000000876745")
driver.set_page_load_timeout(45)
driver.maximize_window()
driver.implicitly_wait(2)
driver.get_screenshot_as_file("E:\\Python\\Tatacliq.png")
print ("Executed Successfully")
driver.find_element_by_xpath("//div[@class='pdp-promo-title pdp-title']").click()
SpecialPrice = driver.find_element_by_xpath("//div[@class='pdp-promo-title pdp-title']").text
print(SpecialPrice)