Programs & Examples On #Circular slider

Is key-value observation (KVO) available in Swift?

One important thing to mention is that after updating your Xcode to 7 beta you might be getting the following message: "Method does not override any method from its superclass". That's because of the arguments' optionality. Make sure that your observation handler looks exactly as follows:

override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [NSObject : AnyObject]?, context: UnsafeMutablePointer<Void>)

REST API - Use the "Accept: application/json" HTTP Header

Basically I use Fiddler or Postman for testing API's.

In fiddler, in request header you need to specify instead of xml, html you need to change it to json. Eg: Accept: application/json. That should do the job.

Press Enter to move to next control

You can put a KeyPress handler on your TextBoxes, and see which key was used.

To handle the text selection, put a handler on the GotFocus event.

You may also want to consider how to (or if you need to) handle multi-line TextBoxes.

What is the best way to auto-generate INSERT statements for a SQL Server table?

Not sure, if I understand your question correctly.

If you have data in MS-Access, which you want to move it to SQL Server - you could use DTS.
And, I guess you could use SQL profiler to see all the INSERT statements going by, I suppose.

How to convert HTML file to word?

A good option is to use an API like Docverter. Docverter will allow you to convert HTML to PDF or DOCX using an API.

Split List into Sublists with LINQ

So performatic as the Sam Saffron's approach.

public static IEnumerable<IEnumerable<T>> Batch<T>(this IEnumerable<T> source, int size)
{
    if (source == null) throw new ArgumentNullException(nameof(source));
    if (size <= 0) throw new ArgumentOutOfRangeException(nameof(size), "Size must be greater than zero.");

    return BatchImpl(source, size).TakeWhile(x => x.Any());
}

static IEnumerable<IEnumerable<T>> BatchImpl<T>(this IEnumerable<T> source, int size)
{
    var values = new List<T>();
    var group = 1;
    var disposed = false;
    var e = source.GetEnumerator();

    try
    {
        while (!disposed)
        {
            yield return GetBatch(e, values, group, size, () => { e.Dispose(); disposed = true; });
            group++;
        }
    }
    finally
    {
        if (!disposed)
            e.Dispose();
    }
}

static IEnumerable<T> GetBatch<T>(IEnumerator<T> e, List<T> values, int group, int size, Action dispose)
{
    var min = (group - 1) * size + 1;
    var max = group * size;
    var hasValue = false;

    while (values.Count < min && e.MoveNext())
    {
        values.Add(e.Current);
    }

    for (var i = min; i <= max; i++)
    {
        if (i <= values.Count)
        {
            hasValue = true;
        }
        else if (hasValue = e.MoveNext())
        {
            values.Add(e.Current);
        }
        else
        {
            dispose();
        }

        if (hasValue)
            yield return values[i - 1];
        else
            yield break;
    }
}

}

How to add an extra language input to Android?

I just found Scandinavian Keyboard as a fine solution to this problem. It do also have English and German keyboard, but neither Dutch nor Spanish - but I guess they could be added. And I guess there is other alternatives out there.

Creating a file only if it doesn't exist in Node.js

This method is no longer recommended. fs.exists is deprecated. See comments.

Here are some options:

1) Have 2 "fs" calls. The first one is the "fs.exists" call, and the second is "fs.write / read, etc"

//checks if the file exists. 
//If it does, it just calls back.
//If it doesn't, then the file is created.
function checkForFile(fileName,callback)
{
    fs.exists(fileName, function (exists) {
        if(exists)
        {
            callback();
        }else
        {
            fs.writeFile(fileName, {flag: 'wx'}, function (err, data) 
            { 
                callback();
            })
        }
    });
}

function writeToFile()
{
    checkForFile("file.dat",function()
    {
       //It is now safe to write/read to file.dat
       fs.readFile("file.dat", function (err,data) 
       {
          //do stuff
       });
    });
}

2) Or Create an empty file first:

--- Sync:

//If you want to force the file to be empty then you want to use the 'w' flag:

var fd = fs.openSync(filepath, 'w');

//That will truncate the file if it exists and create it if it doesn't.

//Wrap it in an fs.closeSync call if you don't need the file descriptor it returns.

fs.closeSync(fs.openSync(filepath, 'w'));

--- ASync:

var fs = require("fs");
fs.open(path, "wx", function (err, fd) {
    // handle error
    fs.close(fd, function (err) {
        // handle error
    });
});

3) Or use "touch": https://github.com/isaacs/node-touch

Add element to a JSON file?

alternatively you can do

iter(data).next()['f'] = var

How to gracefully handle the SIGKILL signal in Java

There are ways to handle your own signals in certain JVMs -- see this article about the HotSpot JVM for example.

By using the Sun internal sun.misc.Signal.handle(Signal, SignalHandler) method call you are also able to register a signal handler, but probably not for signals like INT or TERM as they are used by the JVM.

To be able to handle any signal you would have to jump out of the JVM and into Operating System territory.

What I generally do to (for instance) detect abnormal termination is to launch my JVM inside a Perl script, but have the script wait for the JVM using the waitpid system call.

I am then informed whenever the JVM exits, and why it exited, and can take the necessary action.

How do I see the current encoding of a file in Sublime Text?

For my part, and without any plug-in, simply saving the file either from the File menu or with keyboards shortcuts

CTRL + S (Windows, Linux) or CMD + S (Mac OS)

briefly displays the current encoding - between parentheses - in the status bar, at the bottom of the editor's window. This suggestion works in Sublime Text 2 and 3.

Note that the displayed encoding to the right in the status bar of Sublime Text 3, may display the wrong encoding of the file if you have attempted to save the file with an encoding that can't represent all the characters in your file. In this case you would have seen an informational dialog and Sublime telling you it's falling back to UTF-8. This may not be the case, so be careful.

How can I show/hide a specific alert with twitter bootstrap?

I use this alert

_x000D_
_x000D_
function myFunction() {_x000D_
   $('#passwordsNoMatchRegister').fadeIn(1000);_x000D_
   setTimeout(function() { _x000D_
       $('#passwordsNoMatchRegister').fadeOut(1000); _x000D_
   }, 5000);_x000D_
}
_x000D_
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
  <script src="//ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
  <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
_x000D_
_x000D_
<button onclick="myFunction()">Try it</button> _x000D_
_x000D_
_x000D_
<div class="alert alert-danger" id="passwordsNoMatchRegister" style="display:none;">_x000D_
    <strong>Error!</strong> Looks like the passwords you entered don't match!_x000D_
  </div>_x000D_
  _x000D_
 _x000D_
  
_x000D_
_x000D_
_x000D_

Display help message with python argparse when script is called without any arguments

This isn't good (also, because intercepts all errors), but:

def _error(parser):
    def wrapper(interceptor):
        parser.print_help()

        sys.exit(-1)

    return wrapper

def _args_get(args=sys.argv[1:]):
    parser = argparser.ArgumentParser()

    parser.error = _error(parser)

    parser.add_argument(...)
    ...

Here is definition of the error function of the ArgumentParser class:

https://github.com/python/cpython/blob/276eb67c29d05a93fbc22eea5470282e73700d20/Lib/argparse.py#L2374

. As you see, following signature, it takes two arguments. However, functions outside the class nothing knows about first argument: self, because, roughly speaking, this is parameter for the class. (I know, that you know...) Thereby, just pass own self and message in _error(...) can't (

def _error(self, message):
    self.print_help()

    sys.exit(-1)

def _args_get(args=sys.argv[1:]):
    parser = argparser.ArgumentParser()

    parser.error = _error
    ...
...

will output:

...
"AttributeError: 'str' object has no attribute 'print_help'"

). You can pass parser (self) in _error function, by calling it:

def _error(self, message):
    self.print_help()

    sys.exit(-1)

def _args_get(args=sys.argv[1:]):
    parser = argparser.ArgumentParser()

    parser.error = _error(parser)
    ...
...

, but you don't want exit the program, right now. Then return it:

def _error(parser):
    def wrapper():
        parser.print_help()

        sys.exit(-1)

    return wrapper
...

. Nonetheless, parser doesn't know, that it has been modified, thus when an error occurs, it will send cause of it (by the way, its localized translation). Well, then intercept it:

def _error(parser):
    def wrapper(interceptor):
        parser.print_help()

        sys.exit(-1)

    return wrapper
...

. Now, when error occurs and parser will send cause of it, you'll intercept it, look at this, and... throw out.

Prevent text selection after double click

To prevent text selection ONLY after a double click:

You could use MouseEvent#detail property. For mousedown or mouseup events, it is 1 plus the current click count.

document.addEventListener('mousedown', function (event) {
  if (event.detail > 1) {
    event.preventDefault();
    // of course, you still do not know what you prevent here...
    // You could also check event.ctrlKey/event.shiftKey/event.altKey
    // to not prevent something useful.
  }
}, false);

See https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail

Best way to call a JSON WebService from a .NET Console

I use HttpWebRequest to GET from the web service, which returns me a JSON string. It looks something like this for a GET:

// Returns JSON string
string GET(string url) 
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    try {
        WebResponse response = request.GetResponse();
        using (Stream responseStream = response.GetResponseStream()) {
            StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8);
            return reader.ReadToEnd();
        }
    }
    catch (WebException ex) {
        WebResponse errorResponse = ex.Response;
        using (Stream responseStream = errorResponse.GetResponseStream())
        {
            StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.GetEncoding("utf-8"));
            String errorText = reader.ReadToEnd();
            // log errorText
        }
        throw;
    }
}

I then use JSON.Net to dynamically parse the string. Alternatively, you can generate the C# class statically from sample JSON output using this codeplex tool: http://jsonclassgenerator.codeplex.com/

POST looks like this:

// POST a JSON string
void POST(string url, string jsonContent) 
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    request.Method = "POST";

    System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
    Byte[] byteArray = encoding.GetBytes(jsonContent);

    request.ContentLength = byteArray.Length;
    request.ContentType = @"application/json";

    using (Stream dataStream = request.GetRequestStream()) {
        dataStream.Write(byteArray, 0, byteArray.Length);
    }
    long length = 0;
    try {
        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
            length = response.ContentLength;
        }
    }
    catch (WebException ex) {
        // Log exception and throw as for GET example above
    }
}

I use code like this in automated tests of our web service.

Correct use of transactions in SQL Server

Easy approach:

CREATE TABLE T
(
    C [nvarchar](100) NOT NULL UNIQUE,
);

SET XACT_ABORT ON -- Turns on rollback if T-SQL statement raises a run-time error.
SELECT * FROM T; -- Check before.
BEGIN TRAN
    INSERT INTO T VALUES ('A');
    INSERT INTO T VALUES ('B');
    INSERT INTO T VALUES ('B');
    INSERT INTO T VALUES ('C');
COMMIT TRAN
SELECT * FROM T; -- Check after.
DELETE T;

SQL not a single-group group function

Maybe you find this simpler

select * from (
    select ssn, sum(time) from downloads
    group by ssn
    order by sum(time) desc
) where rownum <= 10 --top 10 downloaders

Regards
K

Looping through all the properties of object php

Before you run the $object through a foreach loop you have to convert it to an array:

$array = (array) $object;  

 foreach($array as $key=>$val){
      echo "$key: $val";
      echo "<br>";
 }

How can I open a URL in Android's web browser from my application?

Simple, website view via intent,

Intent viewIntent = new Intent("android.intent.action.VIEW", Uri.parse("http://www.yoursite.in"));
startActivity(viewIntent);  

use this simple code toview your website in android app.

Add internet permission in manifest file,

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

Reload nginx configuration

Maybe you're not doing it as root?

Try sudo nginx -s reload, if it still doesn't work, you might want to try sudo pkill -HUP nginx.

PHP memcached Fatal error: Class 'Memcache' not found

Dispite what the accepted answer says in the comments, the correct way to install 'Memcache' is:

sudo apt-get install php5-memcache

NOTE Memcache & Memcached are two distinct although related pieces of software, that are often confused.

EDIT As this is now an old post I thought it worth mentioning that you should replace php5 with your php version number.

Split string with JavaScript

Assuming you're using jQuery..

var input = '19 51 2.108997\n20 47 2.1089';
var lines = input.split('\n');
var output = '';
$.each(lines, function(key, line) {
    var parts = line.split(' ');
    output += '<span>' + parts[0] + ' ' + parts[1] + '</span><span>' + parts[2] + '</span>\n';
});
$(output).appendTo('body');

Get HTML source of WebElement in Selenium WebDriver using Python

The other answers provide a lot of details about retrieving the markup of a WebElement. However, an important aspect is, modern websites are increasingly implementing JavaScript, ReactJS, jQuery, Ajax, Vue.js, Ember.js, GWT, etc. to render the dynamic elements within the DOM tree. Hence there is a necessity to wait for the element and its children to completely render before retrieving the markup.


Python

Hence, ideally you need to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following Locator Strategies:

  • Using get_attribute("outerHTML"):

    element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "#my-id")))
    print(element.get_attribute("outerHTML"))
    
  • Using execute_script():

    element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "#my-id")))
    print(driver.execute_script("return arguments[0].outerHTML;", element))
    
  • Note: You have to add the following imports:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    

How to access the request body when POSTing using Node.js and Express?

What you claim to have "tried doing" is exactly what you wrote in the code that works "as expected" when you invoke it with curl.

The error you're getting doesn't appear to be related to any of the code you've shown us.

If you want to get the raw request, set handlers on request for the data and end events (and, of course, remove any invocations of express.bodyParser()). Note that the data events will occur in chunks, and that unless you set an encoding for the data event those chunks will be buffers, not strings.

iOS 7 status bar overlapping UI

From Apple iOS7 transition Guide,

Specifically,

self.automaticallyAdjustsScrollViewInsets = YES;
self.edgesForExtendedLayout = UIRectEdgeNone;

works for me when I don't want to overlap and I have a UITableViewController.

How to uncheck a radio button?

Try

$(this).attr("checked" , false );

Unable to Install Any Package in Visual Studio 2015

Closing and re-opening VS2015 resolves the issue.

It seems that in some cases, simply reloading the affected project will work.

Pretty-Print JSON Data to a File using Python

You should use the optional argument indent.

header, output = client.request(twitterRequest, method="GET", body=None,
                            headers=None, force_auth_header=True)

# now write output to a file
twitterDataFile = open("twitterData.json", "w")
# magic happens here to make it pretty-printed
twitterDataFile.write(simplejson.dumps(simplejson.loads(output), indent=4, sort_keys=True))
twitterDataFile.close()

Print list without brackets in a single row

You need to loop through the list and use end=" "to keep it on one line

names = ["Sam", "Peter", "James", "Julian", "Ann"]
    index=0
    for name in names:
        print(names[index], end=", ")
        index += 1

How do I download NLTK data?

you can't have a saved python file called nltk.py because the interpreter is reading from that and not from the actual file.

Change the name of your file that the python shell is reading from and try what you were doing originally:

import nltk and then nltk.download()

In Python script, how do I set PYTHONPATH?

You can get and set environment variables via os.environ:

import os
user_home = os.environ["HOME"]

os.environ["PYTHONPATH"] = "..."

But since your interpreter is already running, this will have no effect. You're better off using

import sys
sys.path.append("...")

which is the array that your PYTHONPATH will be transformed into on interpreter startup.

JS jQuery - check if value is in array

The Array.prototype property represents the prototype for the Array constructor and allows you to add new properties and methods to all Array objects. we can create a prototype for this purpose

Array.prototype.has_element = function(element) {
    return $.inArray( element, this) !== -1;
};

And then use it like this

var numbers= [1, 2, 3, 4];
numbers.has_element(3) => true
numbers.has_element(10) => false

See the Demo below

_x000D_
_x000D_
Array.prototype.has_element = function(element) {_x000D_
  return $.inArray(element, this) !== -1;_x000D_
};_x000D_
_x000D_
_x000D_
_x000D_
var numbers = [1, 2, 3, 4];_x000D_
console.log(numbers.has_element(3));_x000D_
console.log(numbers.has_element(10));
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

How to import a new font into a project - Angular 5

the answer is already exist above, but I would like to add some thing.. you can specify the following in your @font-face

@font-face {
  font-family: 'Name You Font';
  src: url('assets/font/xxyourfontxxx.eot');
  src: local('Cera Pro Medium'), local('CeraPro-Medium'),
  url('assets/font/xxyourfontxxx.eot?#iefix') format('embedded-opentype'),
  url('assets/font/xxyourfontxxx.woff') format('woff'),
  url('assets/font/xxyourfontxxx.ttf') format('truetype');
  font-weight: 500;
  font-style: normal;
}

So you can just indicate your fontfamily name that you already choosed

NOTE: the font-weight and font-style depend on your .woff .ttf ... files

Javascript to display the current date and time

<!-- //Hide From Old Browsers



var d=new Date();
var y=d.getYear();
if (y < 1000)
 y+=1900;
var day=d.getDay();
var m=d.getMonth();
var daym=d.getDate();
if (daym<10)
 daym="0"+daym;
 var mon=new Array("January", "February", "March", "April", "May", "June", "July",  "August", "September", "October", "November", "December");
document.write("<font size='2' color='#660000'>"+mon[m]+" "+daym+", "+y+"</font>");

// End Hide -->


  Result :  November 08, 2014

Is right click a Javascript event?

Ya, though w3c says the right click can be detected by the click event, onClick is not triggered through right click in usual browsers.

In fact, right click only trigger onMouseDown onMouseUp and onContextMenu.

Thus, you can regard "onContextMenu" as the right click event. It's an HTML5.0 standard.

javax.faces.application.ViewExpiredException: View could not be restored

First what you have to do, before changing web.xml is to make sure your ManagedBean implements Serializable:

@ManagedBean
@ViewScoped
public class Login implements Serializable {
}

Especially if you use MyFaces

Select first row in each GROUP BY group?

In PostgreSQL this is typically simpler and faster (more performance optimization below):

SELECT DISTINCT ON (customer)
       id, customer, total
FROM   purchases
ORDER  BY customer, total DESC, id;

Or shorter (if not as clear) with ordinal numbers of output columns:

SELECT DISTINCT ON (2)
       id, customer, total
FROM   purchases
ORDER  BY 2, 3 DESC, 1;

If total can be NULL (won't hurt either way, but you'll want to match existing indexes):

...
ORDER  BY customer, total DESC NULLS LAST, id;

Major points

DISTINCT ON is a PostgreSQL extension of the standard (where only DISTINCT on the whole SELECT list is defined).

List any number of expressions in the DISTINCT ON clause, the combined row value defines duplicates. The manual:

Obviously, two rows are considered distinct if they differ in at least one column value. Null values are considered equal in this comparison.

Bold emphasis mine.

DISTINCT ON can be combined with ORDER BY. Leading expressions in ORDER BY must be in the set of expressions in DISTINCT ON, but you can rearrange order among those freely. Example.
You can add additional expressions to ORDER BY to pick a particular row from each group of peers. Or, as the manual puts it:

The DISTINCT ON expression(s) must match the leftmost ORDER BY expression(s). The ORDER BY clause will normally contain additional expression(s) that determine the desired precedence of rows within each DISTINCT ON group.

I added id as last item to break ties:
"Pick the row with the smallest id from each group sharing the highest total."

To order results in a way that disagrees with the sort order determining the first per group, you can nest above query in an outer query with another ORDER BY. Example.

If total can be NULL, you most probably want the row with the greatest non-null value. Add NULLS LAST like demonstrated. See:

The SELECT list is not constrained by expressions in DISTINCT ON or ORDER BY in any way. (Not needed in the simple case above):

  • You don't have to include any of the expressions in DISTINCT ON or ORDER BY.

  • You can include any other expression in the SELECT list. This is instrumental for replacing much more complex queries with subqueries and aggregate / window functions.

I tested with Postgres versions 8.3 – 13. But the feature has been there at least since version 7.1, so basically always.

Index

The perfect index for the above query would be a multi-column index spanning all three columns in matching sequence and with matching sort order:

CREATE INDEX purchases_3c_idx ON purchases (customer, total DESC, id);

May be too specialized. But use it if read performance for the particular query is crucial. If you have DESC NULLS LAST in the query, use the same in the index so that sort order matches and the index is applicable.

Effectiveness / Performance optimization

Weigh cost and benefit before creating tailored indexes for each query. The potential of above index largely depends on data distribution.

The index is used because it delivers pre-sorted data. In Postgres 9.2 or later the query can also benefit from an index only scan if the index is smaller than the underlying table. The index has to be scanned in its entirety, though.

For few rows per customer (high cardinality in column customer), this is very efficient. Even more so if you need sorted output anyway. The benefit shrinks with a growing number of rows per customer.
Ideally, you have enough work_mem to process the involved sort step in RAM and not spill to disk. But generally setting work_mem too high can have adverse effects. Consider SET LOCAL for exceptionally big queries. Find how much you need with EXPLAIN ANALYZE. Mention of "Disk:" in the sort step indicates the need for more:

For many rows per customer (low cardinality in column customer), a loose index scan (a.k.a. "skip scan") would be (much) more efficient, but that's not implemented up to Postgres 13. (An implementation for index-only scans is in development for Postgres 14. See here and here.)
For now, there are faster query techniques to substitute for this. In particular if you have a separate table holding unique customers, which is the typical use case. But also if you don't:

Benchmark

I had a simple benchmark here which is outdated by now. I replaced it with a detailed benchmark in this separate answer.

How to center a button within a div?

_x000D_
_x000D_
div {
    text-align : center;
}
button {
    width: 50%;
    margin: 1rem auto;
}
_x000D_
<div style="width:100%; height:100%; border: 1px solid">
  <button type="button">hello</button>
</div>
_x000D_
_x000D_
_x000D_

This is what I mostly do.
I think bootstrap also uses this in "mx-auto".

How to check if a date is greater than another in Java?

Parse the string into date, then compare using compareTo, before or after

Date d = new Date();
d.compareTo(anotherDate)

i.e

Date date1 = new SimpleDateFormat("MM/dd/yyyy").parse(date1string)
Date date2 = new SimpleDateFormat("MM/dd/yyyy").parse(date2string)

date1.compareTo(date2);

Copying the comment provided below by @MuhammadSaqib to complete this answer.

Returns the value 0 if the argument Date is equal to this Date; a value less than 0 if this Date is before the Date argument, and a value greater than 0 if this Date is after the Date argument. and NullPointerException - if anotherDate is null.

javadoc for compareTo http://docs.oracle.com/javase/6/docs/api/java/util/Date.html#compareTo(java.util.Date)

How to format a java.sql Timestamp for displaying?

For this particular question, the standard suggestion of java.text.SimpleDateFormat works, but has the unfortunate side effect that SimpleDateFormat is not thread-safe and can be the source of particularly nasty problems since it'll corrupt your output in multi-threaded scenarios, and you won't get any exceptions!

I would strongly recommend looking at Joda for anything like this. Why ? It's a much richer and more intuitive time/date library for Java than the current library (and the basis of the up-and-coming new standard Java date/time library, so you'll be learning a soon-to-be-standard API).

Interview Question: Merge two sorted singly linked lists without creating new nodes

public static Node merge(Node h1, Node h2) {

    Node h3 = new Node(0);
    Node current = h3;

    boolean isH1Left = false;
    boolean isH2Left = false;

    while (h1 != null || h2 != null) {
        if (h1.data <= h2.data) {
            current.next = h1;
            h1 = h1.next;
        } else {
            current.next = h2;
            h2 = h2.next;
        }
        current = current.next;

        if (h2 == null && h1 != null) {
            isH1Left = true;
            break;
        }

        if (h1 == null && h2 != null) {
            isH2Left = true;
            break;
        }
    }

    if (isH1Left) {
        while (h1 != null) {
            current.next = h1;
            current = current.next;
            h1 = h1.next;
        }
    } 

    if (isH2Left) {
        while (h2 != null) {
            current.next = h2;
            current = current.next;
            h2 = h2.next;
        }
    }

    h3 = h3.next;

    return h3;
}

Can I simultaneously declare and assign a variable in VBA?

You can sort-of do that with objects, as in the following.

Dim w As New Widget

But not with strings or variants.

Difference between Mutable objects and Immutable objects

Immutable Object's state cannot be altered.

for example String.

String str= "abc";//a object of string is created
str  = str + "def";// a new object of string is created and assigned to str

How to compare arrays in C#?

Array.Equals is comparing the references, not their contents:

Currently, when you compare two arrays with the = operator, we are really using the System.Object's = operator, which only compares the instances. (i.e. this uses reference equality, so it will only be true if both arrays points to the exact same instance)

Source

If you want to compare the contents of the arrays you need to loop though the arrays and compare the elements.

The same blog post has an example of how to do this.

TCP vs UDP on video stream

For video streaming bandwidth is likely the constraint on the system. Using multicast you can greatly reduce the amount of upstream bandwidth used. With UDP you can easily multicast your packets to all connected terminals. You could also use a reliable multicast protocol, one is called Pragmatic General Multicast (PGM), I don't know anything about it and I guess it isn't widespread in its use.

How to add text inside the doughnut chart using Chart.js?

You can use css with relative/absolute positioning if you want it responsive. Plus it can handle easily the multi-line.

https://jsfiddle.net/mgyp0jkk/

<div class="relative">
  <canvas id="myChart"></canvas>      
  <div class="absolute-center text-center">
    <p>Some text</p>
    <p>Some text</p>
  </div>
</div>

Multiple Inheritance in C#

i know i know even though its not allowed and so on, sometime u actualy need it so for the those:

class a {}
class b : a {}
class c : b {}

like in my case i wanted to do this class b : Form (yep the windows.forms) class c : b {}

cause half of the function were identical and with interface u must rewrite them all

Trigger validation of all fields in Angular Form submit

Note: I know this is a hack, but it was useful for Angular 1.2 and earlier that didn't provide a simple mechanism.

The validation kicks in on the change event, so some things like changing the values programmatically won't trigger it. But triggering the change event will trigger the validation. For example, with jQuery:

$('#formField1, #formField2').trigger('change');

Substitute multiple whitespace with single whitespace in Python

For completeness, you can also use:

mystring = mystring.strip()  # the while loop will leave a trailing space, 
                  # so the trailing whitespace must be dealt with
                  # before or after the while loop
while '  ' in mystring:
    mystring = mystring.replace('  ', ' ')

which will work quickly on strings with relatively few spaces (faster than re in these situations).

In any scenario, Alex Martelli's split/join solution performs at least as quickly (usually significantly more so).

In your example, using the default values of timeit.Timer.repeat(), I get the following times:

str.replace: [1.4317800167340238, 1.4174888149192384, 1.4163512401715934]
re.sub:      [3.741931446594549,  3.8389395858970374, 3.973777672860706]
split/join:  [0.6530919432498195, 0.6252146571700905, 0.6346594329726258]


EDIT:

Just came across this post which provides a rather long comparison of the speeds of these methods.

AngularJS Multiple ng-app within a page

_x000D_
_x000D_
// root-app_x000D_
const rootApp = angular.module('root-app', ['app1', 'app2E']);_x000D_
_x000D_
// app1_x000D_
const app11aa = angular.module('app1', []);_x000D_
app11aa.controller('main', function($scope) {_x000D_
  $scope.msg = 'App 1';_x000D_
});_x000D_
_x000D_
// app2_x000D_
const app2 = angular.module('app2E', []);_x000D_
app2.controller('mainB', function($scope) {_x000D_
  $scope.msg = 'App 2';_x000D_
});_x000D_
_x000D_
// bootstrap_x000D_
angular.bootstrap(document.querySelector('#app1a'), ['app1']);_x000D_
angular.bootstrap(document.querySelector('#app2b'), ['app2E']);
_x000D_
<!-- [email protected] -->_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.0/angular.min.js"></script>_x000D_
_x000D_
<!-- root-app -->_x000D_
<div ng-app="root-app">_x000D_
_x000D_
  <!-- app1 -->_x000D_
  <div id="app1a">_x000D_
    <div ng-controller="main">_x000D_
      {{msg}}_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
  <!-- app2 -->_x000D_
  <div id="app2b">_x000D_
    <div ng-controller="mainB">_x000D_
      {{msg}}_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

What is the best way to repeatedly execute a function every x seconds?

The easier way I believe to be:

import time

def executeSomething():
    #code here
    time.sleep(60)

while True:
    executeSomething()

This way your code is executed, then it waits 60 seconds then it executes again, waits, execute, etc... No need to complicate things :D

How to send email to multiple recipients using python smtplib?

I figured this out a few months back and blogged about it. The summary is:

If you want to use smtplib to send email to multiple recipients, use email.Message.add_header('To', eachRecipientAsString) to add them, and then when you invoke the sendmail method, use email.Message.get_all('To') send the message to all of them. Ditto for Cc and Bcc recipients.

What is the difference between res.end() and res.send()?

I would like to make a little bit more emphasis on some key differences between res.end() & res.send() with respect to response headers and why they are important.

1. res.send() will check the structure of your output and set header information accordingly.


    app.get('/',(req,res)=>{
       res.send('<b>hello</b>');
    });

enter image description here


     app.get('/',(req,res)=>{
         res.send({msg:'hello'});
     });

enter image description here

Where with res.end() you can only respond with text and it will not set "Content-Type"

      app.get('/',(req,res)=>{
           res.end('<b>hello</b>');
      }); 

enter image description here

2. res.send() will set "ETag" attribute in the response header

      app.get('/',(req,res)=>{
            res.send('<b>hello</b>');
      });

enter image description here

¿Why is this tag important?
The ETag HTTP response header is an identifier for a specific version of a resource. It allows caches to be more efficient, and saves bandwidth, as a web server does not need to send a full response if the content has not changed.

res.end() will NOT set this header attribute

How to get the Full file path from URI

  public String getPath(Uri uri) {
    Cursor cursor = getContentResolver().query(uri, null, null, null, null);
    cursor.moveToFirst();
    String document_id = cursor.getString(0);
    document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
    cursor.close();

    cursor = getContentResolver().query(
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
    cursor.moveToFirst();
    String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
    cursor.close();

    return path;
}

Using this method we can get string filepath from Uri.

Simplest Way to Test ODBC on WIndows

Make a file SOMEFILENAME.udl then double click on it and set it up as an ODBC connection object, username, pwd, target server

Append text to file from command line without using io redirection

If you don't mind using sed then,

$ cat test 
this is line 1
$ sed -i '$ a\this is line 2 without redirection' test 
$ cat test 
this is line 1
this is line 2 without redirection

As the documentation may be a bit long to go through, some explanations :

  • -i means an inplace transformation, so all changes will occur in the file you specify
  • $ is used to specify the last line
  • a means append a line after
  • \ is simply used as a delimiter

How to get a cookie from an AJAX response?

You're looking for a response header of Set-Cookie:

xhr.getResponseHeader('Set-Cookie');

It won't work with HTTPOnly cookies though.

Update

According to the XMLHttpRequest Level 1 and XMLHttpRequest Level 2, this particular response headers falls under the "forbidden" response headers that you can obtain using getResponseHeader(), so the only reason why this could work is basically a "naughty" browser.

How to detect a textbox's content has changed

Use closures to remember what was the text in the checkbox before the key stroke and check whether this has changed.

Yep. You don't have to use closures necessarily, but you will need to remember the old value and compare it to the new.

However! This still won't catch every change, because there a ways of editing textbox content that do not involve any keypress. For example selecting a range of text then right-click-cut. Or dragging it. Or dropping text from another app into the textbox. Or changing a word via the browser's spell-check. Or...

So if you must detect every change, you have to poll for it. You could window.setInterval to check the field against its previous value every (say) second. You could also wire onkeyup to the same function so that changes that are caused by keypresses are reflected quicker.

Cumbersome? Yes. But it's that or just do it the normal HTML onchange way and don't try to instant-update.

JavaScript: Get image dimensions

Similar question asked and answered using JQuery here:

Get width height of remote image from url

function getMeta(url){
  $("<img/>").attr("src", url).load(function(){
     s = {w:this.width, h:this.height};
     alert(s.w+' '+s.h);      
  }); 
}

getMeta("http://page.com/img.jpg");

How to add jQuery code into HTML Page

I would recommend to call the script like this

...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="/js/my.js"></script>
</body>

The js and css files must be treat differently

Put jquery as the first before other JS scripts at the bottom of <BODY> tag

  • The problem caused is that they block parallel downloads. The HTTP/1.1 specification suggests that browsers download no more than two components in parallel per hostname.
  • So select 2 (two) most important scripts on your page like analytic and pixel script on the <head> tags and let the rest including the jquery to be called on the bottom <body> tag.

Put CSS style on top of <HEAD> tag after the other more priority tags

  • Moving style sheets to the document HEAD makes pages appear to be loading faster. This is because putting style sheets in the HEAD allows the page to render progressively.
  • So for css sheets, it is better to put them all on the <head> tag but let the style that shall be immediately rendered to be put in <style> tags inside <HEAD> and the rest in <body>.

You may also find other suggestion when you test your page like on Google PageSpeed Insight

Use of "this" keyword in formal parameters for static methods in C#

In addition to Preet Sangha's explanation:
Intellisense displays the extension methods with a blue arrow (e.g. in front of "Aggregate<>"):

enter image description here

You need a

using the.namespace.of.the.static.class.with.the.extension.methods;

for the extension methods to appear and to be available, if they are in a different namespace than the code using them.

load iframe in bootstrap modal

I also wanted to load any iframe inside modal window. What I did was, Created an iframe inside Modal and passing the source of target iframe to the iframe inside the modal.

_x000D_
_x000D_
function closeModal() {_x000D_
  $('#modalwindow').hide();_x000D_
  var modalWindow = document.getElementById('iframeModalWindow');_x000D_
  modalWindow.src = "";_x000D_
}
_x000D_
.modal {_x000D_
  z-index: 3;_x000D_
  display: none;_x000D_
  padding-top: 5%;_x000D_
  padding-left: 5%;_x000D_
  position: fixed;_x000D_
  left: 0;_x000D_
  top: 0;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  overflow: auto;_x000D_
  background-color: rgb(51, 34, 34);_x000D_
  background-color: rgba(0, 0, 0, 0.4)_x000D_
}
_x000D_
<!-- Modal Window -->_x000D_
<div id="modalwindow" class="modal">_x000D_
  <div class="modal-header">_x000D_
    <button type="button" style="margin-left:80%" class="close" onclick=closeModal()>&times;</button>_x000D_
  </div>_x000D_
  <iframe id="iframeModalWindow" height="80%" width="80%" src="" name="iframe_modal"></iframe>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Location of the mongodb database on mac

The default data directory for MongoDB is /data/db.

This can be overridden by a dbpath option specified on the command line or in a configuration file.

If you install MongoDB via a package manager such as Homebrew or MacPorts these installs typically create a default data directory other than /data/db and set the dbpath in a configuration file.

If a dbpath was provided to mongod on startup you can check the value in the mongo shell:

db.serverCmdLineOpts()

You would see a value like:

"parsed" : {
    "dbpath" : "/usr/local/data"
},

Web.Config Debug/Release

It is possible using ConfigTransform build target available as a Nuget package - https://www.nuget.org/packages/CodeAssassin.ConfigTransform/

All "web.*.config" transform files will be transformed and output as a series of "web.*.config.transformed" files in the build output directory regardless of the chosen build configuration.

The same applies to "app.*.config" transform files in non-web projects.

and then adding the following target to your *.csproj.

<Target Name="TransformActiveConfiguration" Condition="Exists('$(ProjectDir)/Web.$(Configuration).config')" BeforeTargets="Compile" >
    <TransformXml Source="$(ProjectDir)/Web.Config" Transform="$(ProjectDir)/Web.$(Configuration).config" Destination="$(TargetDir)/Web.config" />
</Target>

Posting an answer as this is the first Stackoverflow post that appears in Google on the subject.

MongoDB: exception in initAndListen: 20 Attempted to create a lock file on a read-only directory: /data/db, terminating

If your system is using SELinux, make sure that you use the right context for the directory you created:

ls -dZ /data/db/
ls -dZ /var/lib/mongo/

and clone the context with:

chcon -R --reference=/var/lib/mongo /data/db

How to install iPhone application in iPhone Simulator

I see you have a problem. Try building your app as Release and then check out your source codes build folder. It may be called Release-iphonesimulator. Inside here will be the app. Then go to (home folder)/Library/Application Support/iPhone Simulator (if you can't find it, try pressing Command - J and choosing arrange by name). Go to an OS that has apps in it in the iPhone sim, like 4.1. In that folder there should be an Applications folder. Open that, and there should be folders with random lettering. Pick any one, and replace it with the app you have. Make sure to delete anything in the little folders!

If it doesn't work, then I'm dumbfounded.

How do I convert between ISO-8859-1 and UTF-8 in Java?

Here is a function to convert UNICODE (ISO_8859_1) to UTF-8

public static String String_ISO_8859_1To_UTF_8(String strISO_8859_1) {
final StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < strISO_8859_1.length(); i++) {
  final char ch = strISO_8859_1.charAt(i);
  if (ch <= 127) 
  {
      stringBuilder.append(ch);
  }
  else 
  {
      stringBuilder.append(String.format("%02x", (int)ch));
  }
}
String s = stringBuilder.toString();
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
    data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                         + Character.digit(s.charAt(i+1), 16));
}
String strUTF_8 =new String(data, StandardCharsets.UTF_8);
return strUTF_8;
}

TEST

String strA_ISO_8859_1_i = new String("??????".getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);

System.out.println("ISO_8859_1 strA est = "+ strA_ISO_8859_1_i + "\n String_ISO_8859_1To_UTF_8 = " + String_ISO_8859_1To_UTF_8(strA_ISO_8859_1_i));

RESULT

ISO_8859_1 strA est = اÙغÙا٠String_ISO_8859_1To_UTF_8 = ??????

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

I used jsPDF and dom-to-image library to export HTML to PDF.

I post here as reference to whom concern.

$('#downloadPDF').click(function () {
    domtoimage.toPng(document.getElementById('content2'))
      .then(function (blob) {
          var pdf = new jsPDF('l', 'pt', [$('#content2').width(), $('#content2').height()]);
          pdf.addImage(blob, 'PNG', 0, 0, $('#content2').width(), $('#content2').height());
          pdf.save("test.pdf");
      });
});

Demo: https://jsfiddle.net/viethien/md03wb21/27/

What does if [ $? -eq 0 ] mean for shell scripts?

It is an extremely overused way to check for the success/failure of a command. Typically, the code snippet you give would be refactored as:

if grep -e ERROR ${LOG_DIR_PATH}/${LOG_NAME} > /dev/null; then
   ...
fi

(Although you can use 'grep -q' in some instances instead of redirecting to /dev/null, doing so is not portable. Many implementations of grep do not support the -q option, so your script may fail if you use it.)

Output of git branch in tree like fashion

You can use a tool called gitk.

Android - java.lang.SecurityException: Permission Denial: starting Intent

I was facing this issue on a react-native project and it came after adding a splash screen activity and making it the launcher activity.

This is the change i made in my android manifest XML file on the MainActivity configuration.

_x000D_
_x000D_
<activity_x000D_
        android:name=".MainActivity"_x000D_
        android:label="@string/app_name"_x000D_
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize"_x000D_
        android:windowSoftInputMode="adjustResize"/>_x000D_
      <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
_x000D_
_x000D_
_x000D_

I added the android:exported=true and the activity configuration looked like this.

_x000D_
_x000D_
 <activity_x000D_
        android:name=".MainActivity"_x000D_
        android:exported="true"_x000D_
        android:label="@string/app_name"_x000D_
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize"_x000D_
        android:windowSoftInputMode="adjustResize"/>_x000D_
      <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />_x000D_
   
_x000D_
_x000D_
_x000D_

How to downgrade from Internet Explorer 11 to Internet Explorer 10?

  1. Save and close all Internet Explorer windows and then, run Windows Task Manager to end the running processes in background.
  2. Go to Control Panel.
  3. Click Programs and choose the View installed updates instead.
  4. Locate the following Windows Internet Explorer 11 or you can type "Internet Explorer" for a quick search.
  5. Choose the Yes option from the following "Uninstall an update".
  6. Please wait while Windows Internet Explorer 10 is being restored and reconfigured automatically.
  7. Follow the Microsoft Windows wizard to restart your system.

Note: You can do it for as many earlier versions you want, i.e. IE9, IE8 and so on.

javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake during web service communicaiton

I encountered this problem with Java 1.6. Running under Java 1.7 fixed my particular rendition of the problem. I think the underlying cause was that the server I was connecting to must have required stronger encryption than was available under 1.6.

jQuery UI 1.10: dialog and zIndex option

Add this before calling dialog

$( obiect ).css('zIndex',9999);

And remove

 zIndex: 700,

from dialog

How do I list all cron jobs for all users?

Depends on your linux version but I use:

tail -n 1000 /var/spool/cron/*

as root. Very simple and very short.

Gives me output like:

==> /var/spool/cron/root <==
15 2 * * * /bla

==> /var/spool/cron/my_user <==
*/10 1 * * * /path/to/script

Maximum number of rows in an MS Access database engine table?

Some comments:

  1. Jet/ACE files are organized in data pages, which means there is a certain amount of slack space when your record boundaries are not aligned with your data pages.

  2. Row-level locking will greatly reduce the number of possible records, since it forces one record per data page.

  3. In Jet 4, the data page size was increased to 4KBs (from 2KBs in Jet 3.x). As Jet 4 was the first Jet version to support Unicode, this meant that you could store 1GB of double-byte data (i.e., 1,000,000,000 double-byte characters), and with Unicode compression turned on, 2GBs of data. So, the number of records is going to be affected by whether or not you have Unicode compression on.

  4. Since we don't know how much room in a Jet/ACE file is taken up by headers and other metadata, nor precisely how much room index storage takes, the theoretical calculation is always going to be under what is practical.

  5. To get the most efficient possible storage, you'd want to use code to create your database rather than the Access UI, because Access creates certain properties that pure Jet does not need. This is not to say there are a lot of these, as properties set to the Access defaults are usually not set at all (the property is created only when you change it from the default value -- this can be seen by cycling through a field's properties collection, i.e., many of the properties listed for a field in the Access table designer are not there in the properties collection because they haven't been set), but you might want to limit yourself to Jet-specific data types (hyperlink fields are Access-only, for instance).

I just wasted an hour mucking around with this using Rnd() to populate 4 fields defined as type byte, with composite PK on the four fields, and it took forever to append enough records to get up to any significant portion of 2GBs. At over 2 million records, the file was under 80MBs. I finally quit after reaching just 700K 7 MILLION records and the file compacted to 184MBs. The amount of time it would take to get up near 2GBs is just more than I'm willing to invest!

Easiest way to develop simple GUI in Python

I would recommend wxpython. It's very easy to use and the documentation is pretty good.

Parse query string in JavaScript

Following on from my comment to the answer @bobby posted, here is the code I would use:

    function parseQuery(str)
        {
        if(typeof str != "string" || str.length == 0) return {};
        var s = str.split("&");
        var s_length = s.length;
        var bit, query = {}, first, second;
        for(var i = 0; i < s_length; i++)
            {
            bit = s[i].split("=");
            first = decodeURIComponent(bit[0]);
            if(first.length == 0) continue;
            second = decodeURIComponent(bit[1]);
            if(typeof query[first] == "undefined") query[first] = second;
            else if(query[first] instanceof Array) query[first].push(second);
            else query[first] = [query[first], second]; 
            }
        return query;
        }

This code takes in the querystring provided (as 'str') and returns an object. The string is split on all occurances of &, resulting in an array. the array is then travsersed and each item in it is split by "=". This results in sub arrays wherein the 0th element is the parameter and the 1st element is the value (or undefined if no = sign). These are mapped to object properties, so for example the string "hello=1&another=2&something" is turned into:

{
hello: "1",
another: "2",
something: undefined
}

In addition, this code notices repeating reoccurances such as "hello=1&hello=2" and converts the result into an array, eg:

{
hello: ["1", "2"]
}

You'll also notice it deals with cases in whih the = sign is not used. It also ignores if there is an equal sign straight after an & symbol.

A bit overkill for the original question, but a reusable solution if you ever need to work with querystrings in javascript :)

Find methods calls in Eclipse project

You can also search for specific methods. For e.g. If you want to search for isEmpty() method of the string class you have to got to - Search -> Java -> type java.lang.String.isEmpty() and in the 'Search For' option use Method.

You can then select the scope that you require.

How to Logout of an Application Where I Used OAuth2 To Login With Google?

If any one want it in Java, Here is my Answer, For this you have to call Another Thread.

How to resize a custom view programmatically?

try a this one:

...
View view = inflater.inflate(R.layout.active_slide, this);
view.setMinimumWidth(200);

Submit form on pressing Enter with AngularJS

I wanted something a little more extensible/semantic than the given answers so I wrote a directive that takes a javascript object in a similar way to the built-in ngClass:

HTML

<input key-bind="{ enter: 'go()', esc: 'clear()' }" type="text"></input>

The values of the object are evaluated in the context of the directive's scope - ensure they are encased in single quotes otherwise all of the functions will be executed when the directive is loaded(!)

So for example: esc : 'clear()' instead of esc : clear()

Javascript

myModule
    .constant('keyCodes', {
        esc: 27,
        space: 32,
        enter: 13,
        tab: 9,
        backspace: 8,
        shift: 16,
        ctrl: 17,
        alt: 18,
        capslock: 20,
        numlock: 144
    })
    .directive('keyBind', ['keyCodes', function (keyCodes) {
        function map(obj) {
            var mapped = {};
            for (var key in obj) {
                var action = obj[key];
                if (keyCodes.hasOwnProperty(key)) {
                    mapped[keyCodes[key]] = action;
                }
            }
            return mapped;
        }
        
        return function (scope, element, attrs) {
            var bindings = map(scope.$eval(attrs.keyBind));
            element.bind("keydown keypress", function (event) {
                if (bindings.hasOwnProperty(event.which)) {
                    scope.$apply(function() {
                         scope.$eval(bindings[event.which]);
                    });
                }
            });
        };
    }]);

Getting msbuild.exe without installing Visual Studio

The latest (as of Jan 2019) stand-alone MSBuild installers can be found here: https://www.visualstudio.com/downloads/

Scroll down to "Tools for Visual Studio 2019" and choose "Build Tools for Visual Studio 2019" (despite the name, it's for users who don't want the full IDE)

See this question for additional information.

numbers not allowed (0-9) - Regex Expression in javascript

Something as simple as [a-z]+, or perhaps [\S]+, or even [a-zA-Z]+?

Choose newline character in Notepad++

For a new document: Settings -> Preferences -> New Document/Default Directory -> New Document -> Format -> Windows/Mac/Unix

And for an already-open document: Edit -> EOL Conversion

Jackson serialization: ignore empty values (or null)

Or you can use GSON [https://code.google.com/p/google-gson/], where these null fields will be automatically removed.

SampleDTO.java

public class SampleDTO {

    String username;
    String email;
    String password;
    String birthday;
    String coinsPackage;
    String coins;
    String transactionId;
    boolean isLoggedIn;

    // getters/setters
}

Test.java

import com.google.gson.Gson;

public class Test {

    public static void main(String[] args) {
        SampleDTO objSampleDTO = new SampleDTO();
        Gson objGson = new Gson();
        System.out.println(objGson.toJson(objSampleDTO));
    }
}

OUTPUT:

{"isLoggedIn":false}

I used gson-2.2.4

syntax for creating a dictionary into another dictionary in python

You can declare a dictionary inside a dictionary by nesting the {} containers:

d = {'dict1': {'foo': 1, 'bar': 2}, 'dict2': {'baz': 3, 'quux': 4}}

And then you can access the elements using the [] syntax:

print d['dict1']           # {'foo': 1, 'bar': 2}
print d['dict1']['foo']    # 1
print d['dict2']['quux']   # 4

Given the above, if you want to add another dictionary to the dictionary, it can be done like so:

d['dict3'] = {'spam': 5, 'ham': 6}

or if you prefer to add items to the internal dictionary one by one:

d['dict4'] = {}
d['dict4']['king'] = 7
d['dict4']['queen'] = 8

Equivalent of typedef in C#

Here is the code for it, enjoy!, I picked that up from the dotNetReference type the "using" statement inside the namespace line 106 http://referencesource.microsoft.com/#mscorlib/microsoft/win32/win32native.cs

using System;
using System.Collections.Generic;
namespace UsingStatement
{
    using Typedeffed = System.Int32;
    using TypeDeffed2 = List<string>;
    class Program
    {
        static void Main(string[] args)
        {
        Typedeffed numericVal = 5;
        Console.WriteLine(numericVal++);

        TypeDeffed2 things = new TypeDeffed2 { "whatever"};
        }
    }
}

Negate if condition in bash script

You can choose:

if [[ $? -ne 0 ]]; then       # -ne: not equal

if ! [[ $? -eq 0 ]]; then     # -eq: equal

if [[ ! $? -eq 0 ]]; then

! inverts the return of the following expression, respectively.

Creating a chart in Excel that ignores #N/A or blank cells

Best way is use Empty

Dim i as Integer
For i = 1 to 1000
    If CPT_DB.Cells(i, 1) > 100 Then
       CPT_DB.Cells(i, 2) = CPT_DB.Cells(i, 1)
    Else
       CPT_DB.Cells(i, 2) = Empty //**********************
    End If
Next i

Can the Android layout folder contain subfolders?

I think the most elegant solution to this problem (given that subfolders are not allowed) is to prepend the file names with the name of the folder you would have placed it inside of. For example, if you have a bunch of layouts for an Activity, Fragment, or just general view called "places" then you should just prepend it with places_my_layout_name. At least this solves the problem of organizing them in a way that they are easier to find within the IDE. It's not the most awesome solution, but it's better than nothing.

Update Jenkins from a war file

I use this groovy script to download new war file

import java.util.concurrent.atomic.AtomicInteger

class ThreadHelper{
    static done = false;
    static starttime = System.currentTimeMillis()
    static synchronized printx (message) {    printf ("%5s seconds: %20s",(System.currentTimeMillis()-starttime)/1000.0 , message); println("") }
    def download(address)
    {
    def filename = new File(System.getenv()['CI_HOME'] + '/' + address.tokenize("/")[-1])
    println(filename.getCanonicalPath())
    def file = new FileOutputStream(filename)
    def out = new BufferedOutputStream(file)
    out << new URL(address).openStream()
    out.close()
    done=true;
    }

}

println("executing from ... "+ new File(".").getCanonicalPath())

def counter = new AtomicInteger();
    th = Thread.start {
    while(!ThreadHelper.done) {
    sleep 1000
    counter.incrementAndGet()
    print '.'
    }
}

th2 = Thread.start { new ThreadHelper().download("http://mirrors.jenkins-ci.org/war/latest/jenkins.war") }
th.join()
th2.join()

ThreadHelper.printx('done')

And another script shutsdown tomcat - copies the war and restarts it

We host it on windows 2008 and tomcat, I use sc query, sc config, sc stop, sc start to manage windows services

    set warname=jenkins

if '%name%' == 'trak' set warname=trak

pushd .
if '%name%'=='' goto badname
if '%warname%'=='' goto badname

if '%ci_home%'=='' goto badcihome

REM =====================================================
REM stop windows service
sc stop %name%

REM sleep for 5 seconds see http:\\stackoverflow.com\questions\1672338\how-to-sleep-for-5-seconds-in-windowss-command-prompt-or-dos
ping 1.1.1.1 -n 1 -w 3000 > nul

rem replace forward slash with backward slash
set tomcat_dir=%ci_home:/=\%\instances\tomcat7-%name%

REM Create sub directory called bak-yymmdd-hhmmss
REM where yymmdd-hhmmss is a date-time stamp like 120601-142907

set hh=%time:~0,2%

REM Since there is no leading zero for times before 10 am, have to put in
REM a zero when this is run before 10 am.

if "%time:~0,1%"==" " set hh=0%hh:~1,1%

set yymmdd_hhmmss=%date:~12,2%%date:~4,2%%date:~7,2%-%hh%%time:~3,2%%time:~6,2%

set backupdir=bak-%yymmdd_hhmmss%

REM =====================================================
md %tomcat_dir%\logs\%backupdir%

cd %tomcat_dir%\logs

dir bak*
echo "nothing-to-log" >> force.log

REM move command will fail if there is nothing to move hence the force log statement above

call move *.* %backupdir%

REM =====================================================
rmdir %tomcat_dir%\webapps\%name% /q/s

echo f|xcopy %ci_home%\%warname%.war %tomcat_dir%\webapps\%name%.war /y

REM TODO===== something about jenkins plugins

REM =====================================================
cd "%tomcat_dir%\bin"
call catalina version

echo =====================================================
echo ====== removing %name%
call service remove %name%

echo =====================================================
echo ====== installing %name%
call service install %name%

echo on

REM setting service to start automatically, note that space before the word auto IS REQUIRED
sc config %name% start= auto

REM =====================================================
sc start %name%

popd

exit 0

goto done

:badname
echo 'name required - this will be used as windows service name as well'
pause
exit 1

:badcihome
echo 'CI home env var required - ci_home'
pause
exit 1

:done

How to use TLS 1.2 in Java 6

After a few hours of playing with the Oracle JDK 1.6, I was able to make it work without any code change. The magic is done by Bouncy Castle to handle SSL and allow JDK 1.6 to run with TLSv1.2 by default. In theory, it could also be applied to older Java versions with eventual adjustments.

  1. Download the latest Java 1.6 version from the Java Archive Oracle website
  2. Uncompress it on your preferred path and set your JAVA_HOME environment variable
  3. Update the JDK with the latest Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files 6
  4. Download the Bounce Castle files bcprov-jdk15to18-165.jar and bctls-jdk15to18-165.jar and copy them into your ${JAVA_HOME}/jre/lib/ext folder
  5. Modify the file ${JAVA_HOME}/jre/lib/security/java.security commenting out the providers section and adding some extra lines
    # Original security providers (just comment it)
    # security.provider.1=sun.security.provider.Sun
    # security.provider.2=sun.security.rsa.SunRsaSign
    # security.provider.3=com.sun.net.ssl.internal.ssl.Provider
    # security.provider.4=com.sun.crypto.provider.SunJCE
    # security.provider.5=sun.security.jgss.SunProvider
    # security.provider.6=com.sun.security.sasl.Provider
    # security.provider.7=org.jcp.xml.dsig.internal.dom.XMLDSigRI
    # security.provider.8=sun.security.smartcardio.SunPCSC

    # Add the Bouncy Castle security providers with higher priority
    security.provider.1=org.bouncycastle.jce.provider.BouncyCastleProvider
    security.provider.2=org.bouncycastle.jsse.provider.BouncyCastleJsseProvider
    
    # Original security providers with different priorities
    security.provider.3=sun.security.provider.Sun
    security.provider.4=sun.security.rsa.SunRsaSign
    security.provider.5=com.sun.net.ssl.internal.ssl.Provider
    security.provider.6=com.sun.crypto.provider.SunJCE 
    security.provider.7=sun.security.jgss.SunProvider
    security.provider.8=com.sun.security.sasl.Provider
    security.provider.9=org.jcp.xml.dsig.internal.dom.XMLDSigRI
    security.provider.10=sun.security.smartcardio.SunPCSC

    # Here we are changing the default SSLSocketFactory implementation
    ssl.SocketFactory.provider=org.bouncycastle.jsse.provider.SSLSocketFactoryImpl

Just to make sure it's working let's make a simple Java program to download files from one URL using https.

import java.io.*;
import java.net.*;


public class DownloadWithHttps {

    public static void main(String[] args) {
        try {
            URL url = new URL(args[0]);
            System.out.println("File to Download: " + url);
            String filename = url.getFile();
            File f = new File(filename);
            System.out.println("Output File: " + f.getName());
            BufferedInputStream in = new BufferedInputStream(url.openStream());
            FileOutputStream fileOutputStream = new FileOutputStream(f.getName());
            int bytesRead;
            byte dataBuffer[] = new byte[1024];

            while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) {
                fileOutputStream.write(dataBuffer, 0, bytesRead);
            }
            fileOutputStream.close();

        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }
}

Now, just compile the DownloadWithHttps.java program and execute it with your Java 1.6


${JAVA_HOME}/bin/javac DownloadWithHttps.java
${JAVA_HOME}/bin/java DownloadWithHttps https://repo1.maven.org/maven2/org/apache/commons/commons-lang3/3.10/commons-lang3-3.10.jar

Important note for Windows users: This solution was tested in a Linux OS, if you are using Windows, please replace the ${JAVA_HOME} by %JAVA_HOME%.

How to temporarily disable a click handler in jQuery?

This is a more idiomatic alternative to the artificial state variable solutions:

$("#button_id").one('click', DoSomething);

function DoSomething() {
  // do something.

  $("#button_id").one('click', DoSomething);
}

One will only execute once (until attached again). More info here: http://docs.jquery.com/Events/one

HtmlEncode from Class Library

If you are using C#3 a good tip is to create an extension method to make this even simpler. Just create a static method (preferably in a static class) like so:

public static class Extensions
{
    public static string HtmlEncode(this string s)
    {
        return HttpUtility.HtmlEncode(s);
    }
}

You can then do neat stuff like this:

string encoded = "<div>I need encoding</div>".HtmlEncode();

How to call a method with a separate thread in Java?

In Java 8 you can do this with one line of code.

If your method doesn't take any parameters, you can use a method reference:

new Thread(MyClass::doWork).start();

Otherwise, you can call the method in a lambda expression:

new Thread(() -> doWork(someParam)).start();

How do I detect a click outside an element?

Instead using flow interruption, blur/focus event or any other tricky technics, simply match event flow with element's kinship:

$(document).on("click.menu-outside", function(event){
    // Test if target and it's parent aren't #menuscontainer
    // That means the click event occur on other branch of document tree
    if(!$(event.target).parents().andSelf().is("#menuscontainer")){
        // Click outisde #menuscontainer
        // Hide the menus (but test if menus aren't already hidden)
    }
});

To remove click outside event listener, simply:

$(document).off("click.menu-outside");

Uninstall old versions of Ruby gems

# remove all old versions of the gem
gem cleanup rjb

# choose which ones you want to remove
gem uninstall rjb

# remove version 1.1.9 only
gem uninstall rjb --version 1.1.9

# remove all versions less than 1.3.4
gem uninstall rjb --version '<1.3.4'

How do you send an HTTP Get Web Request in Python?

You can use urllib2

import urllib2
content = urllib2.urlopen(some_url).read()
print content

Also you can use httplib

import httplib
conn = httplib.HTTPConnection("www.python.org")
conn.request("HEAD","/index.html")
res = conn.getresponse()
print res.status, res.reason
# Result:
200 OK

or the requests library

import requests
r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
r.status_code
# Result:
200

Maximum on http header values?

No, HTTP does not define any limit. However most web servers do limit size of headers they accept. For example in Apache default limit is 8KB, in IIS it's 16K. Server will return 413 Entity Too Large error if headers size exceeds that limit.

Related question: How big can a user agent string get?

jQuery: Load Modal Dialog Contents via Ajax

var dialogName = '#dialog_XYZ';
$.ajax({
        url: "/ajax_pages/my_page.ext",
        data: {....},
        success: function(data) {
          $(dialogName ).remove();

          $('BODY').append(data);

          $(dialogName )
            .dialog(options.dialogOptions);
        }
});

The Ajax-Request load the Dialog, add them to the Body of the current page and open the Dialog.

If you only whant to load the content you can do:

var dialogName = '#dialog_XYZ';
$.ajax({
            url: "/ajax_pages/my_page.ext",
            data: {....},
            success: function(data) {
              $(dialogName).append(data);

              $(dialogName )
                .dialog(options.dialogOptions);
            }
});

Difference between $.ajax() and $.get() and $.load()

The methods provide different layers of abstraction.

  • $.ajax() gives you full control over the Ajax request. You should use it if the other methods don't fullfil your needs.

  • $.get() executes an Ajax GET request. The returned data (which can be any data) will be passed to your callback handler.

  • $(selector).load() will execute an Ajax GET request and will set the content of the selected returned data (which should be either text or HTML).

It depends on the situation which method you should use. If you want to do simple stuff, there is no need to bother with $.ajax().

E.g. you won't use $.load(), if the returned data will be JSON which needs to be processed further. Here you would either use $.ajax() or $.get().

How to remove duplicates from Python list and keep order?

If your input is already sorted, then there may be a simpler way to do it:

from operator import itemgetter
from itertools import groupby
unique_list = list(map(itemgetter(0), groupby(yourList)))

What are the default access modifiers in C#?

I would like to add some documentation link. Check out more detail here.

enter image description here

How to change default text file encoding in Eclipse?

If you need to edit files of same type with more encodings in different folders and projects (e.g. one project is in UTF-8 and other in Windows-12xx), go to Window > Preferences > General > Content Types > Text > and select each type with multiple encodings.

For each type delete content of the Default encoding and click Update.

This way Eclipse will not "autodetect" encoding and will use encoding set for project or folder.

Programmatically stop execution of python script?

You could raise SystemExit(0) instead of going to all the trouble to import sys; sys.exit(0).

Identifying and solving javax.el.PropertyNotFoundException: Target Unreachable

1. Target Unreachable, identifier 'bean' resolved to null

This boils down to that the managed bean instance itself could not be found by exactly that identifier (managed bean name) in EL like so #{bean}.

Identifying the cause can be broken down into three steps:

a. Who's managing the bean?
b. What's the (default) managed bean name?
c. Where's the backing bean class?

1a. Who's managing the bean?

First step would be checking which bean management framework is responsible for managing the bean instance. Is it CDI via @Named? Or is it JSF via @ManagedBean? Or is it Spring via @Component? Can you make sure that you're not mixing multiple bean management framework specific annotations on the very same backing bean class? E.g. @Named @ManagedBean, @Named @Component, or @ManagedBean @Component. This is wrong. The bean must be managed by at most one bean management framework and that framework must be properly configured. If you already have no idea which to choose, head to Backing beans (@ManagedBean) or CDI Beans (@Named)? and Spring JSF integration: how to inject a Spring component/service in JSF managed bean?

In case it's CDI who's managing the bean via @Named, then you need to make sure of the following:

  • CDI 1.0 (Java EE 6) requires an /WEB-INF/beans.xml file in order to enable CDI in WAR. It can be empty or it can have just the following content:

      <?xml version="1.0" encoding="UTF-8"?>
      <beans xmlns="http://java.sun.com/xml/ns/javaee" 
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                                 http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
      </beans>
    
  • CDI 1.1 (Java EE 7) without any beans.xml, or an empty beans.xml file, or with the above CDI 1.0 compatible beans.xml will behave the same as CDI 1.0. When there's a CDI 1.1 compatible beans.xml with an explicit version="1.1", then it will by default only register @Named beans with an explicit CDI scope annotation such as @RequestScoped, @ViewScoped, @SessionScoped, @ApplicationScoped, etc. In case you intend to register all beans as CDI managed beans, even those without an explicit CDI scope, use the below CDI 1.1 compatible /WEB-INF/beans.xml with bean-discovery-mode="all" set (the default is bean-discovery-mode="annotated").

      <?xml version="1.0" encoding="UTF-8"?>
      <beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
                                 http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
             version="1.1" bean-discovery-mode="all">
      </beans>
    
  • When using CDI 1.1+ with bean-discovery-mode="annotated" (default), make sure that you didn't accidentally import a JSF scope such as javax.faces.bean.RequestScoped instead of a CDI scope javax.enterprise.context.RequestScoped. Watch out with IDE autocomplete.

  • When using Mojarra 2.3.0-2.3.2 and CDI 1.1+ with bean-discovery-mode="annotated" (default), then you need to upgrade Mojarra to 2.3.3 or newer due to a bug. In case you can't upgrade, then you need either to set bean-discovery-mode="all" in beans.xml, or to put the JSF 2.3 specific @FacesConfig annotation on an arbitrary class in the WAR (generally some sort of an application scoped startup class).

  • When using JSF 2.3 on a Servlet 4.0 container with a web.xml declared conform Servlet 4.0, then you need to explicitly put the JSF 2.3 specific @FacesConfig annotation on an arbitrary class in the WAR (generally some sort of an application scoped startup class). This is not necessary in Servlet 3.x.

  • Non-Java EE containers like Tomcat and Jetty doesn't ship with CDI bundled. You need to install it manually. It's a bit more work than just adding the library JAR(s). For Tomcat, make sure that you follow the instructions in this answer: How to install and use CDI on Tomcat?

  • Your runtime classpath is clean and free of duplicates in CDI API related JARs. Make sure that you're not mixing multiple CDI implementations (Weld, OpenWebBeans, etc). Make sure that you don't provide another CDI or even Java EE API JAR file along webapp when the target container already bundles CDI API out the box.

  • If you're packaging CDI managed beans for JSF views in a JAR, then make sure that the JAR has at least a valid /META-INF/beans.xml (which can be kept empty).


In case it's JSF who's managing the bean via the since 2.3 deprecated @ManagedBean, and you can't migrate to CDI, then you need to make sure of the following:

  • The faces-config.xml root declaration is compatible with JSF 2.0. So the XSD file and the version must at least specify JSF 2.0 or higher and thus not 1.x.

      <faces-config
          xmlns="http://java.sun.com/xml/ns/javaee"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
          version="2.0">
    

    For JSF 2.1, just replace 2_0 and 2.0 by 2_1 and 2.1 respectively.

    If you're on JSF 2.2 or higher, then make sure you're using xmlns.jcp.org namespaces instead of java.sun.com over all place.

      <faces-config
          xmlns="http://xmlns.jcp.org/xml/ns/javaee"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd"
          version="2.2">
    

    For JSF 2.3, just replace 2_2 and 2.2 by 2_3 and 2.3 respectively.

  • You didn't accidentally import javax.annotation.ManagedBean instead of javax.faces.bean.ManagedBean. Watch out with IDE autocomplete, Eclipse is known to autosuggest the wrong one as first item in the list.

  • You didn't override the @ManagedBean by a JSF 1.x style <managed-bean> entry in faces-config.xml on the very same backing bean class along with a different managed bean name. This one will have precedence over @ManagedBean. Registering a managed bean in faces-config.xml is not necessary since JSF 2.0, just remove it.

  • Your runtime classpath is clean and free of duplicates in JSF API related JARs. Make sure that you're not mixing multiple JSF implementations (Mojarra and MyFaces). Make sure that you don't provide another JSF or even Java EE API JAR file along webapp when the target container already bundles JSF API out the box. See also "Installing JSF" section of our JSF wiki page for JSF installation instructions. In case you intend to upgrade container-bundled JSF from the WAR on instead of in container itself, make sure that you've instructed the target container to use WAR-bundled JSF API/impl.

  • If you're packaging JSF managed beans in a JAR, then make sure that the JAR has at least a JSF 2.0 compatible /META-INF/faces-config.xml. See also How to reference JSF managed beans which are provided in a JAR file?

  • If you're actually using the jurassic JSF 1.x, and you can't upgrade, then you need to register the bean via <managed-bean> in faces-config.xml instead of @ManagedBean. Don't forget to fix your project build path as such that you don't have JSF 2.x libraries anymore (so that the @ManagedBean annotation wouldn't confusingly successfully compile).


In case it's Spring who's managing the bean via @Component, then you need to make sure of the following:

  • Spring is being installed and integrated as per its documentation. Importantingly, you need to at least have this in web.xml:

      <listener>
          <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
      </listener>
    

    And this in faces-config.xml:

      <application>
          <el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
      </application>
    
  • (above is all I know with regard to Spring — I don't do Spring — feel free to edit/comment with other probable Spring related causes; e.g. some XML configuration related trouble)


In case it's a repeater component who's managing the (nested) bean via its var attribute (e.g. <h:dataTable var="item">, <ui:repeat var="item">, <p:tabView var="item">, etc) and you actually got a "Target Unreachable, identifier 'item' resolved to null", then you need to make sure of the following:

  • The #{item} is not referenced in binding attribtue of any child component. This is incorrect as binding attribute runs during view build time, not during view render time. Moreover, there's physically only one component in the component tree which is simply reused during every iteration round. In other words, you should actually be using binding="#{bean.component}" instead of binding="#{item.component}". But much better is to get rid of component bining to bean altogether and investigate/ask the proper approach for the problem you thought to solve this way. See also How does the 'binding' attribute work in JSF? When and how should it be used?


1b. What's the (default) managed bean name?

Second step would be checking the registered managed bean name. JSF and Spring use conventions conform JavaBeans specification while CDI has exceptions depending on CDI impl/version.

  • A FooBean backing bean class like below,

      @Named
      public class FooBean {}
    

    will in all bean management frameworks have a default managed bean name of #{fooBean}, as per JavaBeans specification.

  • A FOOBean backing bean class like below,

      @Named
      public class FOOBean {}
    

    whose unqualified classname starts with at least two capitals will in JSF and Spring have a default managed bean name of exactly the unqualified class name #{FOOBean}, also conform JavaBeans specificiation. In CDI, this is also the case in Weld versions released before June 2015, but not in Weld versions released after June 2015 (2.2.14/2.3.0.B1/3.0.0.A9) nor in OpenWebBeans due to an oversight in CDI spec. In those Weld versions and in all OWB versions it is only with the first character lowercased #{fOOBean}.

  • If you have explicitly specified a managed bean name foo like below,

      @Named("foo")
      public class FooBean {}
    

    or equivalently with @ManagedBean(name="foo") or @Component("foo"), then it will only be available by #{foo} and thus not by #{fooBean}.


1c. Where's the backing bean class?

Third step would be doublechecking if the backing bean class is at the right place in the built and deployed WAR file. Make sure that you've properly performed a full clean, rebuild, redeploy and restart of the project and server in case you was actually busy writing code and impatiently pressing F5 in the browser. If still in vain, let the build system produce a WAR file, which you then extract and inspect with a ZIP tool. The compiled .class file of the backing bean class must reside in its package structure in /WEB-INF/classes. Or, when it's packaged as part of a JAR module, the JAR containing the compiled .class file must reside in /WEB-INF/lib and thus not e.g. EAR's /lib or elsewhere.

If you're using Eclipse, make sure that the backing bean class is in src and thus not WebContent, and make sure that Project > Build Automatically is enabled. If you're using Maven, make sure that the backing bean class is in src/main/java and thus not in src/main/resources or src/main/webapp.

If you're packaging the web application as part of an EAR with EJB+WAR(s), then you need to make sure that the backing bean classes are in WAR module and thus not in EAR module nor EJB module. The business tier (EJB) must be free of any web tier (WAR) related artifacts, so that the business tier is reusable across multiple different web tiers (JSF, JAX-RS, JSP/Servlet, etc).


2. Target Unreachable, 'entity' returned null

This boils down to that the nested property entity as in #{bean.entity.property} returned null. This usually only exposes when JSF needs to set the value for property via an input component like below, while the #{bean.entity} actually returned null.

<h:inputText value="#{bean.entity.property}" />

You need to make sure that you have prepared the model entity beforehand in a @PostConstruct, or <f:viewAction> method, or perhaps an add() action method in case you're working with CRUD lists and/or dialogs on same view.

@Named
@ViewScoped
public class Bean {

    private Entity entity; // +getter (setter is not necessary).

    @Inject
    private EntityService entityService;

    @PostConstruct
    public void init() {
        // In case you're updating an existing entity.
        entity = entityService.getById(entityId);

        // Or in case you want to create a new entity.
        entity = new Entity();
    }

    // ...
}

As to the importance of @PostConstruct; doing this in a regular constructor would fail in case you're using a bean management framework which uses proxies, such as CDI. Always use @PostConstruct to hook on managed bean instance initialization (and use @PreDestroy to hook on managed bean instance destruction). Additionally, in a constructor you wouldn't have access to any injected dependencies yet, see also NullPointerException while trying to access @Inject bean in constructor.

In case the entityId is supplied via <f:viewParam>, you'd need to use <f:viewAction> instead of @PostConstruct. See also When to use f:viewAction / preRenderView versus PostConstruct?

You also need to make sure that you preserve the non-null model during postbacks in case you're creating it only in an add() action method. Easiest would be to put the bean in the view scope. See also How to choose the right bean scope?


3. Target Unreachable, 'null' returned null

This has actually the same cause as #2, only the (older) EL implementation being used is somewhat buggy in preserving the property name to display in the exception message, which ultimately incorrectly exposed as 'null'. This only makes debugging and fixing a bit harder when you've quite some nested properties like so #{bean.entity.subentity.subsubentity.property}.

The solution is still the same: make sure that the nested entity in question is not null, in all levels.


4. Target Unreachable, ''0'' returned null

This has also the same cause as #2, only the (older) EL implementation being used is buggy in formulating the exception message. This exposes only when you use the brace notation [] in EL as in #{bean.collection[index]} where the #{bean.collection} itself is non-null, but the item at the specified index doesn't exist. Such a message must then be interpreted as:

Target Unreachable, 'collection[0]' returned null

The solution is also the same as #2: make sure that the collection item is available.


5. Target Unreachable, 'BracketSuffix' returned null

This has actually the same cause as #4, only the (older) EL implementation being used is somewhat buggy in preserving the iteration index to display in the exception message, which ultimately incorrectly exposed as 'BracketSuffix' which is really the character ]. This only makes debugging and fixing a bit harder when you've multiple items in the collection.


Other possible causes of javax.el.PropertyNotFoundException:

Mask output of `The following objects are masked from....:` after calling attach() function

If you look at the down arrow in environment tab. The attached file can appear multiple times. You may need to highlight and run detach(filename) several times until all cases are gone then attach(newfilename) should have no output message.

attached files under environment tab

What is the proper declaration of main in C++?

The exact wording of the latest published standard (C++14) is:

An implementation shall allow both

  • a function of () returning int and

  • a function of (int, pointer to pointer to char) returning int

as the type of main.

This makes it clear that alternative spellings are permitted so long as the type of main is the type int() or int(int, char**). So the following are also permitted:

  • int main(void)
  • auto main() -> int
  • int main ( )
  • signed int main()
  • typedef char **a; typedef int b, e; e main(b d, a c)

How to compare two maps by their values

If anyone is looking to do it in Java 8 streams below is the example.

import java.util.HashMap;
import java.util.Map;

public class CompareTwoMaps {

    public static void main(String[] args) {

        Map<String, String> a = new HashMap<>();
        a.put("foo", "bar" + "bar");
        a.put("zoo", "bar" + "bar");

        Map<String, String> b = new HashMap<>();
        b.put(new String("foo"), "bar" + "bar");
        b.put(new String("zoo"), "bar" + "bar");

        System.out.println("result = " + areEqual(a, b));
    }

    private static boolean areEqual(Map<String, String> first, Map<String, String> second) {
        return first.entrySet().stream()
                .allMatch(e -> e.getValue().equals(second.get(e.getKey())));
    }
}

How do I calculate the MD5 checksum of a file in Python?

In Python 3.8+ you can do

import hashlib

with open("your_filename.png", "rb") as f:
    file_hash = hashlib.md5()
    while chunk := f.read(8192):
        file_hash.update(chunk)

print(file_hash.digest())
print(file_hash.hexdigest())  # to get a printable str instead of bytes

On Python 3.7 and below:

with open("your_filename.png", "rb") as f:
    file_hash = hashlib.md5()
    chunk = f.read(8192)
    while chunk:
        file_hash.update(chunk)
        chunk = f.read(8192)

print(file_hash.hexdigest())

This reads the file 8192 (or 2¹³) bytes at a time instead of all at once with f.read() to use less memory.


Consider using hashlib.blake2b instead of md5 (just replace md5 with blake2b in the above snippets). It's cryptographically secure and faster than MD5.

Cross-browser bookmark/add to favorites JavaScript

function bookmark(title, url) {
  if (window.sidebar) { 
    // Firefox
    window.sidebar.addPanel(title, url, '');
  } 
  else if (window.opera && window.print) 
  { 
    // Opera
    var elem = document.createElement('a');
    elem.setAttribute('href', url);
    elem.setAttribute('title', title);
    elem.setAttribute('rel', 'sidebar');
    elem.click(); //this.title=document.title;
  } 
  else if (document.all) 
  { 
    // ie
    window.external.AddFavorite(url, title);
  }
}

I used this & works great in IE, FF, Netscape. Chrome, Opera and safari do not support it!

HTML input fields does not get focus when clicked

I'm using JQuery UI and Bootstrap so I faced this issue and I think it is a conflict between the two as in normal case the textarea or the input filed is editable by nature but I made this solution after testing all the above answers but none solve the cross browser support for all major browsers, but I solved it and I like to share my solution you can use it on input text and textarea

(Tested on Desktop: IE (All Versions), Chrome, Safari, Windows Edge, Firefox, Visual Studio Cordova Ripple Viewer on Windows & Visual Studio Cordova Windows 10 Store App)

(Tested on Mobile: Chrome, Firefox, Android Internet Browser & Visual Studio Cordova App on Android & Visual Studio Cordova Windows 8 + 8.1 + 10 Phone App)

This is the HTML Code:

<textarea contenteditable id="textarea"></textarea>

This is The CSS Code:

textarea {
    -webkit-user-select: text !important;
    -khtml-user-select: text !important;
    -moz-user-select: text !important;
    -ms-user-select: text !important;
    user-select: text !important;
    /*to make sure that background color and text color is not the same (from the answers above)*/
    background-color:#fff !important;
    color:#733E27 !important;
 }        

This Is The JQuery Code On Document Ready

$("textarea").click(function() {
        setTimeout(function(){
            $("textarea").focus();
            //add this if you are using JQuery UI (From The Solutions Above)
            $("textarea").enableSelection();
            var val = $("textarea").val();
            if (val.charAt(val.length-1) !== " " && val.length !== 1) {
                alert(val.length);
                val += " ";
            }
            $("textarea").val(val);
        }, 0);
    });

    if (navigator.userAgent.indexOf('Safari') !== -1 || navigator.userAgent.indexOf('Chrome') !== -1) {
        //alert('Its Safari or chrome');
        $("textarea").onfocus(function(e) {
            setTimeout(function(){
                var end;
                if ($("textarea").val === "") {
                    end = 0;
                } else {
                    end = $("textarea").val.length;
                }
                if ($("textarea").setSelectionRange) {
                    var range = document.getElementById('textarea').createTextRange();
                    if (range) {
                        setTimeout(range, 0, [end, end]);
                    } else { // IE style
                        var aRange = document.getElementById('textarea').createTextRange();
                        aRange.collapse(true);
                        aRange.moveEnd('character', end);
                        aRange.moveStart('character', end);
                        aRange.select();
                    }
                }
                e.preventDefault();
                return false;
            }, 0);
        });
    }

You can test it on my web application at www.gahwehsada.com

How do I configure git to ignore some files locally?

From the relevant Git documentation:

Patterns which are specific to a particular repository but which do not need to be shared with other related repositories (e.g., auxiliary files that live inside the repository but are specific to one user's workflow) should go into the $GIT_DIR/info/exclude file.

The .git/info/exclude file has the same format as any .gitignore file. Another option is to set core.excludesFile to the name of a file containing global patterns.

Note, if you already have unstaged changes you must run the following after editing your ignore-patterns:

git update-index --assume-unchanged <file-list>

Note on $GIT_DIR: This is a notation used all over the git manual simply to indicate the path to the git repository. If the environment variable is set, then it will override the location of whichever repo you're in, which probably isn't what you want.


Edit: Another way is to use:

git update-index --skip-worktree <file-list>

Reverse it by:

git update-index --no-skip-worktree <file-list>

C++ Object Instantiation

The only reason I'd worry about is that Dog is now allocated on the stack, rather than the heap. So if Dog is megabytes in size, you may have a problem,

If you do need to go the new/delete route, be wary of exceptions. And because of this you should use auto_ptr or one of the boost smart pointer types to manage the object lifetime.

Display Bootstrap Modal using javascript onClick

A JavaScript function must first be made that holds what you want to be done:

function print() { console.log("Hello World!") }

and then that function must be called in the onClick method from inside an element:

<a onClick="print()"> ... </a>

You can learn more about modal interactions directly from the Bootstrap 3 documentation found here: http://getbootstrap.com/javascript/#modals

Your modal bind is also incorrect. It should be something like this, where "myModal" = ID of element:

$('#myModal').modal(options)

In other words, if you truly want to keep what you already have, put a "#" in front GSCCModal and see if that works.

It is also not very wise to have an onClick bound to a div element; something like a button would be more suitable.

Hope this helps!

JavaScript inside an <img title="<a href='#' onClick='alert('Hello World!')>The Link</a>" /> possible?

No, this is, as you say "rubbish code". If it works as should, it is because browsers try to "read the writer's mind" - in other words, they have algorithms to try to make sense of "rubbish code", guess at the probable intent and internally change it into something that actually makes sense.

In other words, your code only works by accident, and probably not in all browsers.

Is this what you're trying to do?

<a href="#" onClick="alert('Hello World!')"><img title="The Link" /></a>

How do I print colored output to the terminal in Python?

Color_Console library is comparatively easier to use. Install this library and the following code would help you.

from Color_Console import *
ctext("This will be printed" , "white" , "blue")
The first argument is the string to be printed, The second argument is the color of 
the text and the last one is the background color.

The latest version of Color_Console allows you to pass a list or dictionary of colors which would change after a specified delay time.

Also, they have good documentation on all of their functions.

Visit https://pypi.org/project/Color-Console/ to know more.

How do I check if PHP is connected to a database already?

// Earlier in your code
mysql_connect();
set_a_flag_that_db_is_connected();

// Later....
if (flag_is_set())
 mysql_connect(....);

MySQL error: key specification without a key length

You can specify the key length in the alter table request, something like:

alter table authors ADD UNIQUE(name_first(20), name_second(20));

TypeScript getting error TS2304: cannot find name ' require'

Add the following in tsconfig.json:

"typeRoots": [ "../node_modules/@types" ]

The application may be doing too much work on its main thread

As I did first preferably use SVG images instead of all other types, If not possible compress all of your PNG and JPG resources using some image processing tools such as Adobe Photoshop or Fotosizer. one of the easiest ways is online image compressing tools like this which helped me to decrease all my image files to almost 50% of their initial size.

Displaying unicode symbols in HTML

I know an answer has already been accepted, but wanted to point a few things out.

Setting the content-type and charset is obviously a good practice, doing it on the server is much better, because it ensures consistency across your application.

However, I would use UTF-8 only when the language of my application uses a lot of characters that are available only in the UTF-8 charset. If you want to show a unicode character or symbol in one of cases, you can do so without changing the charset of your page.

HTML renderers have always been able to display symbols which are not part of the encoding character set of the page, as long as you mention the symbol in its numeric character reference (NCR). Sounds weird but its true.

So, even if your html has a header that states it has an encoding of ansi or any of the iso charsets, you can display a check mark by using its html character reference, in decimal - &#10003; or in hex - &#x2713;

So its a little difficult to understand why you are facing this issue on your pages. Can you check if the NCR value is correct, this is a good reference http://www.fileformat.info/info/unicode/char/2713/index.htm

Edit In Place Content Editing

I've modified your plunker to get it working via angular-xeditable:

http://plnkr.co/edit/xUDrOS?p=preview

It is common solution for inline editing - you creale hyperlinks with editable-text directive that toggles into <input type="text"> tag:

<a href="#" editable-text="bday.name" ng-click="myform.$show()" e-placeholder="Name">
    {{bday.name || 'empty'}}
</a>

For date I used editable-date directive that toggles into html5 <input type="date">.

Creating a JavaScript cookie on a domain and reading it across sub domains

You want:

document.cookie = cookieName +"=" + cookieValue + ";domain=.example.com;path=/;expires=" + myDate;

As per the RFC 2109, to have a cookie available to all subdomains, you must put a . in front of your domain.

Setting the path=/ will have the cookie be available within the entire specified domain(aka .example.com).

Symfony2 : How to get form validation errors after binding the request to the form

For Symfony 2.1:

This is my final solution putting in together many others solutions:

protected function getAllFormErrorMessages($form)
{
    $retval = array();
    foreach ($form->getErrors() as $key => $error) {
        if($error->getMessagePluralization() !== null) {
            $retval['message'] = $this->get('translator')->transChoice(
                $error->getMessage(), 
                $error->getMessagePluralization(), 
                $error->getMessageParameters(), 
                'validators'
            );
        } else {
            $retval['message'] = $this->get('translator')->trans($error->getMessage(), array(), 'validators');
        }
    }
    foreach ($form->all() as $name => $child) {
        $errors = $this->getAllFormErrorMessages($child);
        if (!empty($errors)) {
           $retval[$name] = $errors; 
        }
    }
    return $retval;
}

Get GMT Time in Java

tl;dr

Instant.now()

java.time

The Answer by Damilola is correct in suggesting you use the java.time framework built into Java 8 and later. But that Answer uses the ZonedDateTime class which is overkill if you just want UTC rather than any particular time zone.

The troublesome old date-time classes are now legacy, supplanted by the java.time classes.

Instant

The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Simple code:

Instant instant = Instant.now() ;

instant.toString(): 2016-11-29T23:18:14.604Z

You can think of Instant as the building block to which you can add a time zone (ZoneID) to get a ZonedDateTime.

ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to java.time.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

  • Java SE 8 and SE 9 and later
    • Built-in.
    • Part of the standard Java API with a bundled implementation.
    • Java 9 adds some minor features and fixes.
  • Java SE 6 and SE 7
    • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

How to reload .bash_profile from the command line?

If you don't mind losing the history of your current shell terminal you could also do

bash -l

That would fork your shell and open up another child process of bash. The -l parameter tells bash to run as a login shell, this is required because .bash_profile will not run as a non-login shell, for more info about this read here

If you want to completely replace the current shell you can also do:

exec bash -l

The above will not fork your current shell but replace it completely, so when you type exit it will completely terminate, rather than dropping you to the previous shell.

DOUBLE vs DECIMAL in MySQL

From your comments,

the tax amount rounded to the 4th decimal and the total price rounded to the 2nd decimal.

Using the example in the comments, I might foresee a case where you have 400 sales of $1.47. Sales-before-tax would be $588.00, and sales-after-tax would sum to $636.51 (accounting for $48.51 in taxes). However, the sales tax of $0.121275 * 400 would be $48.52.

This was one way, albeit contrived, to force a penny's difference.

I would note that there are payroll tax forms from the IRS where they do not care if an error is below a certain amount (if memory serves, $0.50).

Your big question is: does anybody care if certain reports are off by a penny? If the your specs say: yes, be accurate to the penny, then you should go through the effort to convert to DECIMAL.

I have worked at a bank where a one-penny error was reported as a software defect. I tried (in vain) to cite the software specifications, which did not require this degree of precision for this application. (It was performing many chained multiplications.) I also pointed to the user acceptance test. (The software was verified and accepted.)

Alas, sometimes you just have to make the conversion. But I would encourage you to A) make sure that it's important to someone and then B) write tests to show that your reports are accurate to the degree specified.

How do you enable auto-complete functionality in Visual Studio C++ express edition?

It's enabled by default. Probably you just tried on an expression that failed to autocomplete.

In case you deactivated it somehow... you can enable it in the Visual Studio settings. Just browse to the Editor settings, then to the subgroup C/C++ and activate it again... should read something like "List members automatically" or "Auto list members" (sorry, I have the german Visual Studio).

Upon typing something like std::cout. a dropwdownlist with possible completitions should pop up.

Why am I getting Unknown error in line 1 of pom.xml?

Add 3.1.1 in to properties like below than fix issue

<properties>
        <java.version>1.8</java.version>
        <maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
</properties>

Just Update Project => right click => Maven=> Update Project

Get all files modified in last 30 days in a directory

A couple of issues

  • You're not limiting it to files, so when it finds a matching directory it will list every file within it.
  • You can't use > in -exec without something like bash -c '... > ...'. Though the > will overwrite the file, so you want to redirect the entire find anyway rather than each -exec.
  • +30 is older than 30 days, -30 would be modified in last 30 days.
  • -exec really isn't needed, you could list everything with various -printf options.

Something like below should work

find . -type f -mtime -30 -exec ls -l {} \; > last30days.txt

Example with -printf

find . -type f -mtime -30 -printf "%M %u %g %TR %TD %p\n" > last30days.txt

This will list files in format "permissions owner group time date filename". -printf is generally preferable to -exec in cases where you don't have to do anything complicated. This is because it will run faster as a result of not having to execute subshells for each -exec. Depending on the version of find, you may also be able to use -ls, which has a similar format to above.

Generate Controller and Model

Models:

php artisan krlove:generate:model Videos --table-name=videos

Convert A String (like testing123) To Binary In Java

The usual way is to use String#getBytes() to get the underlying bytes and then present those bytes in some other form (hex, binary whatever).

Note that getBytes() uses the default charset, so if you want the string converted to some specific character encoding, you should use getBytes(String encoding) instead, but many times (esp when dealing with ASCII) getBytes() is enough (and has the advantage of not throwing a checked exception).

For specific conversion to binary, here is an example:

  String s = "foo";
  byte[] bytes = s.getBytes();
  StringBuilder binary = new StringBuilder();
  for (byte b : bytes)
  {
     int val = b;
     for (int i = 0; i < 8; i++)
     {
        binary.append((val & 128) == 0 ? 0 : 1);
        val <<= 1;
     }
     binary.append(' ');
  }
  System.out.println("'" + s + "' to binary: " + binary);

Running this example will yield:

'foo' to binary: 01100110 01101111 01101111 

python: [Errno 10054] An existing connection was forcibly closed by the remote host

I know this is a very old question but it may be that you need to set the request headers. This solved it for me.

For example 'user-agent', 'accept' etc. here is an example with user-agent:

url = 'your-url-here'
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36'}
r = requests.get(url, headers=headers)

What does 'URI has an authority component' mean?

I had the same problem (NetBeans 6.9.1) and the fix is so simple :)

I realized NetBeans didn't create a META-INF folder and thus no context.xml was found, so I create the META-INF folder under the main project folder and create file context.xml with the following content.

<?xml version="1.0" encoding="UTF-8"?>
    <Context antiJARLocking="true" path="/home"/>

And it runs :)

Set transparent background of an imageview on Android

use RelativeLayout which has 2 imageViews in . and set transparency code on the top imageView.

transparency code :

<solid android:color="@color/white"/>
<gradient android:startColor="#40000000"   android:endColor="#FFFFFFFF" android:angle="270"/>

How to Pass data from child to parent component Angular

Hello you can make use of input and output. Input let you to pass variable form parent to child. Output the same but from child to parent.

The easiest way is to pass "startdate" and "endDate" as input

<calendar [startDateInCalendar]="startDateInSearch" [endDateInCalendar]="endDateInSearch" ></calendar>

In this way you have your startdate and enddate directly in search page. Let me know if it works, or think another way. Thanks

Default SQL Server Port

The default port for SQL Server Database Engine is 1433.

And as a best practice it should always be changed after the installation. 1433 is widely known which makes it vulnerable to attacks.

Powershell script to see currently logged in users (domain and machine) + status (active, idle, away)

If you want to find interactively logged on users, I found a great tip here :https://p0w3rsh3ll.wordpress.com/2012/02/03/get-logged-on-users/ (Win32_ComputerSystem did not help me)

$explorerprocesses = @(Get-WmiObject -Query "Select * FROM Win32_Process WHERE Name='explorer.exe'" -ErrorAction SilentlyContinue)
If ($explorerprocesses.Count -eq 0)
{
    "No explorer process found / Nobody interactively logged on"
}
Else
{
    ForEach ($i in $explorerprocesses)
    {
        $Username = $i.GetOwner().User
        $Domain = $i.GetOwner().Domain
        Write-Host "$Domain\$Username logged on since: $($i.ConvertToDateTime($i.CreationDate))"
    }
}

HTML embedded PDF iframe

Try this out.

_x000D_
_x000D_
<iframe src="https://docs.google.com/viewerng/viewer?url=http://infolab.stanford.edu/pub/papers/google.pdf&embedded=true" frameborder="0" height="100%" width="100%">_x000D_
</iframe>
_x000D_
_x000D_
_x000D_

Can't perform a React state update on an unmounted component

Based on @ford04 answer, here is the same encapsulated in a method :

import React, { FC, useState, useEffect, DependencyList } from 'react';

export function useEffectAsync( effectAsyncFun : ( isMounted: () => boolean ) => unknown, deps?: DependencyList ) {
    useEffect( () => {
        let isMounted = true;
        const _unused = effectAsyncFun( () => isMounted );
        return () => { isMounted = false; };
    }, deps );
} 

Usage:

const MyComponent : FC<{}> = (props) => {
    const [ asyncProp , setAsyncProp ] = useState( '' ) ;
    useEffectAsync( async ( isMounted ) =>
    {
        const someAsyncProp = await ... ;
        if ( isMounted() )
             setAsyncProp( someAsyncProp ) ;
    });
    return <div> ... ;
} ;

The "backspace" escape character '\b': unexpected behavior?

If you want a destructive backspace, you'll need something like

"\b \b"

i.e. a backspace, a space, and another backspace.

git push: permission denied (public key)

I was facing same problem, here is what I did that worked for me.

Use ssh instead of http. Remove origin if its http.

git remote rm origin

Add ssh url

git remote add origin [email protected]:<username>/<repo>.git

Generate ssh key inside .ssh/ folder. It will ask for path and passphrase where you can just press enter and proceed.

cd ~/.ssh
ssh-keygen

Copy the key. You can view your key using. If you hadn't specified a different path then this is the default one.

cat ~/.ssh/id_rsa.pub

Add this key to your github account. Next do

ssh -T [email protected]

You will get a welcome message in your console.

cd into to your project folder. git push -u origin master now works!

Cannot connect to the Docker daemon at unix:/var/run/docker.sock. Is the docker daemon running?

This exception comes when the service of docker is not running or the logged in user dont have the permission to access docker and generally it comes in RedHat

Using below command should resolve the issue

sudo service docker start

enter image description here

How to unmerge a Git merge?

You can reset your branch to the state it was in just before the merge if you find the commit it was on then.

One way is to use git reflog, it will list all the HEADs you've had. I find that git reflog --relative-date is very useful as it shows how long ago each change happened.

Once you find that commit just do a git reset --hard <commit id> and your branch will be as it was before.

If you have SourceTree, you can look up the <commit id> there if git reflog is too overwhelming.

difference between css height : 100% vs height : auto

A height of 100% for is, presumably, the height of your browser's inner window, because that is the height of its parent, the page. An auto height will be the minimum height of necessary to contain .

Python 2,3 Convert Integer to "bytes" Cleanly

You can use the struct's pack:

In [11]: struct.pack(">I", 1)
Out[11]: '\x00\x00\x00\x01'

The ">" is the byte-order (big-endian) and the "I" is the format character. So you can be specific if you want to do something else:

In [12]: struct.pack("<H", 1)
Out[12]: '\x01\x00'

In [13]: struct.pack("B", 1)
Out[13]: '\x01'

This works the same on both python 2 and python 3.

Note: the inverse operation (bytes to int) can be done with unpack.

How to show grep result with complete path or file name

Assuming you have two log-files in:

  • C:/temp/my.log
  • C:/temp/alsoMy.log

cd to C: and use:

grep -r somethingtosearch temp/*.log

It will give you a list like:

temp/my.log:somethingtosearch
temp/alsoMy.log:somethingtosearch1
temp/alsoMy.log:somethingtosearch2

Get exit code of a background process

The pid of a backgrounded child process is stored in $!. You can store all child processes' pids into an array, e.g. PIDS[].

wait [-n] [jobspec or pid …]

Wait until the child process specified by each process ID pid or job specification jobspec exits and return the exit status of the last command waited for. If a job spec is given, all processes in the job are waited for. If no arguments are given, all currently active child processes are waited for, and the return status is zero. If the -n option is supplied, wait waits for any job to terminate and returns its exit status. If neither jobspec nor pid specifies an active child process of the shell, the return status is 127.

Use wait command you can wait for all child processes finish, meanwhile you can get exit status of each child processes via $? and store status into STATUS[]. Then you can do something depending by status.

I have tried the following 2 solutions and they run well. solution01 is more concise, while solution02 is a little complicated.

solution01

#!/bin/bash

# start 3 child processes concurrently, and store each pid into array PIDS[].
process=(a.sh b.sh c.sh)
for app in ${process[@]}; do
  ./${app} &
  PIDS+=($!)
done

# wait for all processes to finish, and store each process's exit code into array STATUS[].
for pid in ${PIDS[@]}; do
  echo "pid=${pid}"
  wait ${pid}
  STATUS+=($?)
done

# after all processed finish, check their exit codes in STATUS[].
i=0
for st in ${STATUS[@]}; do
  if [[ ${st} -ne 0 ]]; then
    echo "$i failed"
  else
    echo "$i finish"
  fi
  ((i+=1))
done

solution02

#!/bin/bash

# start 3 child processes concurrently, and store each pid into array PIDS[].
i=0
process=(a.sh b.sh c.sh)
for app in ${process[@]}; do
  ./${app} &
  pid=$!
  PIDS[$i]=${pid}
  ((i+=1))
done

# wait for all processes to finish, and store each process's exit code into array STATUS[].
i=0
for pid in ${PIDS[@]}; do
  echo "pid=${pid}"
  wait ${pid}
  STATUS[$i]=$?
  ((i+=1))
done

# after all processed finish, check their exit codes in STATUS[].
i=0
for st in ${STATUS[@]}; do
  if [[ ${st} -ne 0 ]]; then
    echo "$i failed"
  else
    echo "$i finish"
  fi
  ((i+=1))
done

Toggle Class in React

refs is not a DOM element. In order to find a DOM element, you need to use findDOMNode menthod first.

Do, this

var node = ReactDOM.findDOMNode(this.refs.btn);
node.classList.toggle('btn-menu-open');

alternatively, you can use like this (almost actual code)

this.state.styleCondition = false;


<a ref="btn" href="#" className={styleCondition ? "btn-menu show-on-small" : ""}><i></i></a>

you can then change styleCondition based on your state change conditions.

Switch between two frames in tkinter

Note: According to JDN96, the answer below may cause a memory leak by repeatedly destroying and recreating frames. However, I have not tested to verify this myself.

One way to switch frames in tkinter is to destroy the old frame then replace it with your new frame.

I have modified Bryan Oakley's answer to destroy the old frame before replacing it. As an added bonus, this eliminates the need for a container object and allows you to use any generic Frame class.

# Multi-frame tkinter application v2.3
import tkinter as tk

class SampleApp(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self._frame = None
        self.switch_frame(StartPage)

    def switch_frame(self, frame_class):
        """Destroys current frame and replaces it with a new one."""
        new_frame = frame_class(self)
        if self._frame is not None:
            self._frame.destroy()
        self._frame = new_frame
        self._frame.pack()

class StartPage(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        tk.Label(self, text="This is the start page").pack(side="top", fill="x", pady=10)
        tk.Button(self, text="Open page one",
                  command=lambda: master.switch_frame(PageOne)).pack()
        tk.Button(self, text="Open page two",
                  command=lambda: master.switch_frame(PageTwo)).pack()

class PageOne(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        tk.Label(self, text="This is page one").pack(side="top", fill="x", pady=10)
        tk.Button(self, text="Return to start page",
                  command=lambda: master.switch_frame(StartPage)).pack()

class PageTwo(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        tk.Label(self, text="This is page two").pack(side="top", fill="x", pady=10)
        tk.Button(self, text="Return to start page",
                  command=lambda: master.switch_frame(StartPage)).pack()

if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()

Start page Page one Page two

Explanation

switch_frame() works by accepting any Class object that implements Frame. The function then creates a new frame to replace the old one.

  • Deletes old _frame if it exists, then replaces it with the new frame.
  • Other frames added with .pack(), such as menubars, will be unaffected.
  • Can be used with any class that implements tkinter.Frame.
  • Window automatically resizes to fit new content

Version History

v2.3

- Pack buttons and labels as they are initialized

v2.2

- Initialize `_frame` as `None`.
- Check if `_frame` is `None` before calling `.destroy()`.

v2.1.1

- Remove type-hinting for backwards compatibility with Python 3.4.

v2.1

- Add type-hinting for `frame_class`.

v2.0

- Remove extraneous `container` frame.
    - Application now works with any generic `tkinter.frame` instance.
- Remove `controller` argument from frame classes.
    - Frame switching is now done with `master.switch_frame()`.

v1.6

- Check if frame attribute exists before destroying it.
- Use `switch_frame()` to set first frame.

v1.5

  - Revert 'Initialize new `_frame` after old `_frame` is destroyed'.
      - Initializing the frame before calling `.destroy()` results
        in a smoother visual transition.

v1.4

- Pack frames in `switch_frame()`.
- Initialize new `_frame` after old `_frame` is destroyed.
    - Remove `new_frame` variable.

v1.3

- Rename `parent` to `master` for consistency with base `Frame` class.

v1.2

- Remove `main()` function.

v1.1

- Rename `frame` to `_frame`.
    - Naming implies variable should be private.
- Create new frame before destroying old frame.

v1.0

- Initial version.

Concatenate in jQuery Selector

There is nothing wrong with syntax of

$('#part' + number).html(text);

jQuery accepts a String (usually a CSS Selector) or a DOM Node as parameter to create a jQuery Object.

In your case you should pass a String to $() that is

$(<a string>)

Make sure you have access to the variables number and text.

To test do:

function(){
    alert(number + ":" + text);//or use console.log(number + ":" + text)
    $('#part' + number).html(text);
}); 

If you see you dont have access, pass them as parameters to the function, you have to include the uual parameters for $.get and pass the custom parameters after them.

git: fatal: I don't handle protocol '??http'

Please do not copy from the clipboard . Just copy the url from your browser's location / Address bar .enter image description here

Declaring an HTMLElement Typescript

In JavaScript you declare variables or functions by using the keywords var, let or function. In TypeScript classes you declare class members or methods without these keywords followed by a colon and the type or interface of that class member.

It’s just syntax sugar, there is no difference between:

var el: HTMLElement = document.getElementById('content');

and:

var el = document.getElementById('content');

On the other hand, because you specify the type you get all the information of your HTMLElement object.

What's the syntax for mod in java

In Java it is the % operator: 15.17.3. Remainder Operator %

Note that there is also floorMod in the java.lang.Math class which will give a different result from % for arguments with different signs:

public static int floorMod?(int x, int y)

Excel Validation Drop Down list using VBA

based on examples above and examples found on other sites, I created a generic procedure and some examples.

'Simple helper procedure to create a dropdown in a cell based on a list of values in a range
'ValueSheetName : the name of the sheet containing the value range
'ValueRangeString : the range on the sheet with name ValueSheetName containing the values for the dropdown
'CreateOnSheetName : the name of the sheet where the dropdown needs to be created
'CreateInRangeString : the range where the dropdown needs to be created
'FieldName As String : a name of the dropdown, will be used in the inputMessage and ErrorMessage
'See example below ExampleCreateDropDown
Public Sub CreateDropDown(ValueSheetName As String, ValueRangeString As String, CreateOnSheetName As String, CreateInRangeString As String, FieldName As String)
    Dim ValueSheet As Worksheet
    Set ValueSheet = Worksheets(ValueSheetName) 'The sheet containing the values
    Dim ValueRange As Range: Set ValueRange = ValueSheet.Range(ValueRangeString) 'The range containing the values
    Dim CreateOnSheet As Worksheet
    Set CreateOnSheet = Worksheets(CreateOnSheetName) 'The sheet containing the values
    Dim CreateInRange As Range: Set CreateInRange = CreateOnSheet.Range(CreateInRangeString)
    Dim InputTitle As String:  InputTitle = "Please Select a Value"
    Dim InputMessage As String:  InputMessage = "for " & FieldName
    Dim ErrorTitle As String:  ErrorTitle = "Please Select a Value"
    Dim ErrorMessage As String:  ErrorMessage = "for " & FieldName
    Dim ShowInput As Boolean:  ShowInput = True 'Show input message on hover
    Dim ShowError As Boolean:  ShowError = True 'Show error message on error
    Dim ValidationType As XlDVType:  ValidationType = xlValidateList
    Dim ValidationAlertStyle As XlDVAlertStyle:  ValidationAlertStyle = xlValidAlertStop 'Stop on invalid value
    Dim ValidationOperator As XlFormatConditionOperator:  ValidationOperator = xlEqual 'Value must be equal to one of the Values from the ValidationFormula1
    Dim ValidationFormula1 As Variant:  ValidationFormula1 = "=" & ValueSheetName & "!" & ValueRange.Address 'Formula referencing the values from the ValueRange
    Dim ValidationFormula2 As Variant:  ValidationFormula2 = ""

    Call CreateDropDownWithValidationInCell(CreateInRange, InputTitle, InputMessage, ErrorTitle, ErrorMessage, ShowInput, ShowError, ValidationType, ValidationAlertStyle, ValidationOperator, ValidationFormula1, ValidationFormula2)
End Sub


'An example using the ExampleCreateDropDown
Private Sub ExampleCreateDropDown()
    Call CreateDropDown(ValueSheetName:="Test", ValueRangeString:="C1:C5", CreateOnSheetName:="Test", CreateInRangeString:="B1", FieldName:="test2")
End Sub


'The full option function if you need more configurable options
'To create a dropdown in a cell based on a list of values in a range
'Validation: https://msdn.microsoft.com/en-us/library/office/ff840078.aspx
'ValidationTypes: XlDVType  https://msdn.microsoft.com/en-us/library/office/ff840715.aspx
'ValidationAlertStyle:  XlDVAlertStyle  https://msdn.microsoft.com/en-us/library/office/ff841223.aspx
'XlFormatConditionOperator  https://msdn.microsoft.com/en-us/library/office/ff840923.aspx
'See example below ExampleCreateDropDownWithValidationInCell
Public Sub CreateDropDownWithValidationInCell(CreateInRange As Range, _
                                        Optional InputTitle As String = "", _
                                        Optional InputMessage As String = "", _
                                        Optional ErrorTitle As String = "", _
                                        Optional ErrorMessage As String = "", _
                                        Optional ShowInput As Boolean = True, _
                                        Optional ShowError As Boolean = True, _
                                        Optional ValidationType As XlDVType = xlValidateList, _
                                        Optional ValidationAlertStyle As XlDVAlertStyle = xlValidAlertStop, _
                                        Optional ValidationOperator As XlFormatConditionOperator = xlEqual, _
                                        Optional ValidationFormula1 As Variant = "", _
                                        Optional ValidationFormula2 As Variant = "")

    With CreateInRange.Validation
        .Delete
        .Add Type:=ValidationType, AlertStyle:=ValidationAlertStyle, Operator:=ValidationOperator, Formula1:=ValidationFormula1, Formula2:=ValidationFormula2
        .IgnoreBlank = True
        .InCellDropdown = True
        .InputTitle = InputTitle
        .ErrorTitle = ErrorTitle
        .InputMessage = InputMessage
        .ErrorMessage = ErrorMessage
        .ShowInput = ShowInput
        .ShowError = ShowError
    End With
End Sub


'An example using the CreateDropDownWithValidationInCell
Private Sub ExampleCreateDropDownWithValidationInCell()
    Dim ValueSheetName As String: ValueSheetName = "Hidden" 'The sheet containing the values
    Dim ValueRangeString As String: ValueRangeString = "C7:C9" 'The range containing the values
    Dim CreateOnSheetName As String: CreateOnSheetName = "Test"  'The sheet containing the dropdown
    Dim CreateInRangeString As String: CreateInRangeString = "A1" 'The range containing the dropdown

    Dim ValueSheet As Worksheet
    Set ValueSheet = Worksheets(ValueSheetName)
    Dim ValueRange As Range: Set ValueRange = ValueSheet.Range(ValueRangeString)
    Dim CreateOnSheet As Worksheet
    Set CreateOnSheet = Worksheets(CreateOnSheetName)
    Dim CreateInRange As Range: Set CreateInRange = CreateOnSheet.Range(CreateInRangeString)
    Dim FieldName As String: FieldName = "Testing Dropdown"
    Dim InputTitle As String:  InputTitle = "Please Select a value"
    Dim InputMessage As String:  InputMessage = "for " & FieldName
    Dim ErrorTitle As String:  ErrorTitle = "Please Select a value"
    Dim ErrorMessage As String:  ErrorMessage = "for " & FieldName
    Dim ShowInput As Boolean:  ShowInput = True
    Dim ShowError As Boolean:  ShowError = True
    Dim ValidationType As XlDVType:  ValidationType = xlValidateList
    Dim ValidationAlertStyle As XlDVAlertStyle:  ValidationAlertStyle = xlValidAlertStop
    Dim ValidationOperator As XlFormatConditionOperator:  ValidationOperator = xlEqual
    Dim ValidationFormula1 As Variant:  ValidationFormula1 = "=" & ValueSheetName & "!" & ValueRange.Address
    Dim ValidationFormula2 As Variant:  ValidationFormula2 = ""

    Call CreateDropDownWithValidationInCell(CreateInRange, InputTitle, InputMessage, ErrorTitle, ErrorMessage, ShowInput, ShowError, ValidationType, ValidationAlertStyle, ValidationOperator, ValidationFormula1, ValidationFormula2)

End Sub

Open multiple Eclipse workspaces on the Mac

Based on a previous answer that helped me, but different directory:

cd /Applications/Eclipse.app/Contents/MacOS
./eclipse &

Thanks

How to create a batch file to run cmd as administrator

As user2549366 suggested before, "You can use a shortcut that links to the batch file." but in the Properties->Compatibility tab of the shortcut, run as administrator may be disabled.

So instead You just right click on your "file.bat - shortcut" then go to ->Properties->Shortcut tab -> Advanced and there you can click Run as administrator. After that, You can execute the shortcut.

setup android on eclipse but don't know SDK directory

I found it in this location:

C:\Users\amitsinha02\AppData\Local\Android\sdk\platform-tools

How to loop through an array of objects in swift

You can try using the simple NSArray in syntax for iterating over the array in swift which makes for shorter code. The following is working for me:

class ModelAttachment {
    var id: String?
    var url: String?
    var thumb: String?
}

var modelAttachementObj = ModelAttachment()
modelAttachementObj.id = "1"
modelAttachementObj.url = "http://www.google.com"
modelAttachementObj.thumb = "thumb"

var imgs: Array<ModelAttachment> = [modelAttachementObj]

for img in imgs  {
    let url = img.url
    NSLog(url!)
}

See docs here

Why doesn't indexOf work on an array IE8?

Versions of IE before IE9 don't have an .indexOf() function for Array, to define the exact spec version, run this before trying to use it:

if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length >>> 0;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}

This is the version from MDN, used in Firefox/SpiderMonkey. In other cases such as IE, it'll add .indexOf() in the case it's missing... basically IE8 or below at this point.

How to apply border radius in IE8 and below IE8 browsers?

The border-radius property is supported in IE9+, Firefox 4+, Chrome, Safari 5+, and Opera, because it is CSS3 property. so, you could use css3pie

first check this demo in IE 8 and download it from here write your css rule like this

 #myAwesomeElement {
    border: 1px solid #999;
    -webkit-border-radius: 10px;
    -moz-border-radius: 10px;
    border-radius: 10px;
    behavior: url(path/to/pie_files/PIE.htc);
}   

note: added behavior: url(path/to/pie_files/PIE.htc); in the above rule. within url() you need to specify your PIE.htc file location

Good examples of python-memcache (memcached) being used in Python?

I would advise you to use pylibmc instead.

It can act as a drop-in replacement of python-memcache, but a lot faster(as it's written in C). And you can find handy documentation for it here.

And to the question, as pylibmc just acts as a drop-in replacement, you can still refer to documentations of pylibmc for your python-memcache programming.

using CASE in the WHERE clause

SELECT *
FROM logs
WHERE pw='correct'
  AND CASE
          WHEN id<800 THEN success=1
          ELSE 1=1
      END
  AND YEAR(TIMESTAMP)=2011

Eclipse+Maven src/main/java not visible in src folder in Package Explorer

I used this tutorial to create my maven web project http://crunchify.com/how-to-create-dynamic-web-project-using-maven-in-eclipse/ and eclipse did not create src/main/java folder for me. When i tired to create the source folder src/main/java eclipse did not let me. So i created the folder outside eclipse in the project directly and then src/main/java appeared in eclipse.

how to run a winform from console application?

If you want to escape from Form Freeze and use editing (like text for a button) use this code

Form form = new Form();
Form.Button.Text = "randomText";
System.Windows.Forms.Application.EnableVisualStyles();
System.Windows.Forms.Application.Run(form);

removing html element styles via javascript

Completly removing style, not only set to NULL

document.getElementById("id").removeAttribute("style")

What is javax.inject.Named annotation supposed to be used for?

Use @Named to differentiate between different objects of the same type bound in the same scope.

@Named("maxWaitTime")
public long maxWaitTimeMs;

@Named("minWaitTime")
public long minWaitTimeMs;

Without the @Named qualifier, the injector would not know which long to bind to which variable.

  • If you want to create annotations that act like @Named, use the @Qualifier annotation when creating them.

  • If you look at @Named, it is itself annotated with @Qualifier.

Why and how to fix? IIS Express "The specified port is in use"

I had the same problem, but no proccess appeared neither in netstat nor in resmon.

What solved the problem for me was closing all the open browser windows.

How do I debug Windows services in Visual Studio?

I just added this code to my service class so I could indirectly call OnStart, similar for OnStop.

    public void MyOnStart(string[] args)
    {
        OnStart(args);
    }

Password Strength Meter

Password Strength Algorithm:

Password Length:
    5 Points: Less than 4 characters
    10 Points: 5 to 7 characters
    25 Points: 8 or more

Letters:
    0 Points: No letters
    10 Points: Letters are all lower case
    20 Points: Letters are upper case and lower case

Numbers:
    0 Points: No numbers
    10 Points: 1 number
    20 Points: 3 or more numbers

Characters:
    0 Points: No characters
    10 Points: 1 character
    25 Points: More than 1 character

Bonus:
    2 Points: Letters and numbers
    3 Points: Letters, numbers, and characters
    5 Points: Mixed case letters, numbers, and characters

Password Text Range:

    >= 90: Very Secure
    >= 80: Secure
    >= 70: Very Strong
    >= 60: Strong
    >= 50: Average
    >= 25: Weak
    >= 0: Very Weak

Settings Toggle to true or false, if you want to change what is checked in the password

var m_strUpperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var m_strLowerCase = "abcdefghijklmnopqrstuvwxyz";
var m_strNumber = "0123456789";
var m_strCharacters = "!@#$%^&*?_~"

Check password


function checkPassword(strPassword)
{
    // Reset combination count
    var nScore = 0;

    // Password length
    // -- Less than 4 characters
    if (strPassword.length < 5)
    {
        nScore += 5;
    }
    // -- 5 to 7 characters
    else if (strPassword.length > 4 && strPassword.length < 8)
    {
        nScore += 10;
    }
    // -- 8 or more
    else if (strPassword.length > 7)
    {
        nScore += 25;
    }

    // Letters
    var nUpperCount = countContain(strPassword, m_strUpperCase);
    var nLowerCount = countContain(strPassword, m_strLowerCase);
    var nLowerUpperCount = nUpperCount + nLowerCount;
    // -- Letters are all lower case
    if (nUpperCount == 0 && nLowerCount != 0) 
    { 
        nScore += 10; 
    }
    // -- Letters are upper case and lower case
    else if (nUpperCount != 0 && nLowerCount != 0) 
    { 
        nScore += 20; 
    }

    // Numbers
    var nNumberCount = countContain(strPassword, m_strNumber);
    // -- 1 number
    if (nNumberCount == 1)
    {
        nScore += 10;
    }
    // -- 3 or more numbers
    if (nNumberCount >= 3)
    {
        nScore += 20;
    }

    // Characters
    var nCharacterCount = countContain(strPassword, m_strCharacters);
    // -- 1 character
    if (nCharacterCount == 1)
    {
        nScore += 10;
    }   
    // -- More than 1 character
    if (nCharacterCount > 1)
    {
        nScore += 25;
    }

    // Bonus
    // -- Letters and numbers
    if (nNumberCount != 0 && nLowerUpperCount != 0)
    {
        nScore += 2;
    }
    // -- Letters, numbers, and characters
    if (nNumberCount != 0 && nLowerUpperCount != 0 && nCharacterCount != 0)
    {
        nScore += 3;
    }
    // -- Mixed case letters, numbers, and characters
    if (nNumberCount != 0 && nUpperCount != 0 && nLowerCount != 0 && nCharacterCount != 0)
    {
        nScore += 5;
    }


    return nScore;
}

// Runs password through check and then updates GUI 


function runPassword(strPassword, strFieldID) 
{
    // Check password
    var nScore = checkPassword(strPassword);


     // Get controls
        var ctlBar = document.getElementById(strFieldID + "_bar"); 
        var ctlText = document.getElementById(strFieldID + "_text");
        if (!ctlBar || !ctlText)
            return;

        // Set new width
        ctlBar.style.width = (nScore*1.25>100)?100:nScore*1.25 + "%";

    // Color and text
    // -- Very Secure
    /*if (nScore >= 90)
    {
        var strText = "Very Secure";
        var strColor = "#0ca908";
    }
    // -- Secure
    else if (nScore >= 80)
    {
        var strText = "Secure";
        vstrColor = "#7ff67c";
    }
    // -- Very Strong
    else 
    */
    if (nScore >= 80)
    {
        var strText = "Very Strong";
        var strColor = "#008000";
    }
    // -- Strong
    else if (nScore >= 60)
    {
        var strText = "Strong";
        var strColor = "#006000";
    }
    // -- Average
    else if (nScore >= 40)
    {
        var strText = "Average";
        var strColor = "#e3cb00";
    }
    // -- Weak
    else if (nScore >= 20)
    {
        var strText = "Weak";
        var strColor = "#Fe3d1a";
    }
    // -- Very Weak
    else
    {
        var strText = "Very Weak";
        var strColor = "#e71a1a";
    }

    if(strPassword.length == 0)
    {
    ctlBar.style.backgroundColor = "";
    ctlText.innerHTML =  "";
    }
else
    {
    ctlBar.style.backgroundColor = strColor;
    ctlText.innerHTML =  strText;
}
}

// Checks a string for a list of characters
function countContain(strPassword, strCheck)
{ 
    // Declare variables
    var nCount = 0;

    for (i = 0; i < strPassword.length; i++) 
    {
        if (strCheck.indexOf(strPassword.charAt(i)) > -1) 
        { 
                nCount++;
        } 
    } 

    return nCount; 
} 

You can customize by yourself according to your requirement.

How to get selected value of a dropdown menu in ReactJS

Using React Functional Components:

const [option,setOption] = useState()

function handleChange(event){
    setOption(event.target.value)
}

<select name='option' onChange={handleChange}>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
</select>

How to display HTML <FORM> as inline element?

Move your form tag just outside the paragraph and set margins / padding to zero:

<form style="margin: 0; padding: 0;">
  <p>
    Read this sentence 
    <input style="display: inline;" type="submit" value="or push this button" />
  </p>
</form>

iOS Detection of Screenshot?

As of iOS 7 the other answers are no longer true. Apple has made it so touchesCancelled:withEvent: is no longer called when the user takes a screenshot.

This would effectively break Snapchat entirely, so a couple betas in a new solution was added. Now, the solution is as simple as using NSNotificationCenter to add an observer to UIApplicationUserDidTakeScreenshotNotification.

Here's an example:

Objective C

NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];
[[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationUserDidTakeScreenshotNotification
                                                  object:nil
                                                   queue:mainQueue
                                              usingBlock:^(NSNotification *note) {
                                                 // executes after screenshot
                                              }];

Swift

NotificationCenter.default.addObserver(
    forName: UIApplication.userDidTakeScreenshotNotification,
    object: nil,
    queue: .main) { notification in
        //executes after screenshot
}

Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?

myDict = {}
for k in itertools.chain(A.keys(), B.keys()):
    myDict[k] = A.get(k, 0)+B.get(k, 0)

How to check which version of Keras is installed?

You can write:

python
import keras
keras.__version__

IF/ELSE Stored Procedure

Just a tip for this, you don't need the BEGIN and END if it only contains a single statement.

ie:

IF(@Trans_type = 'subscr_signup')    
 set @tmpType = 'premium' 
ELSE iF(@Trans_type = 'subscr_cancel')  
     set    @tmpType = 'basic'

Convert Enumeration to a Set/List

There is a simple example of convert enumeration to list. for this i used Collections.list(enum) method.

public class EnumerationToList {

    public static void main(String[] args) {
        Vector<String> vt = new Vector<String>();
        vt.add("java");
        vt.add("php");
        vt.add("array");
        vt.add("string");
        vt.add("c");

        Enumeration<String> enm = vt.elements();
        List<String> ll = Collections.list(enm);
        System.out.println("List elements: " + ll);
    }

}

Reference : How to convert enumeration to list

Find size of an array in Perl

Example:

my @a = (undef, undef);
my $size = @a;

warn "Size: " . $#a;   # Size: 1. It's not the size
warn "Size: " . $size; # Size: 2

log4net vs. Nlog

You might also consider Microsoft Enterprise Library Logging Block. It comes with nice designer.

Extract only right most n letters from a string

Without resorting to the bit converter and bit shifting (need to be sure of encoding) this is fastest method I use as an extension method 'Right'.

string myString = "123456789123456789";

if (myString > 6)
{

        char[] cString = myString.ToCharArray();
        Array.Reverse(myString);
        Array.Resize(ref myString, 6);
        Array.Reverse(myString);
        string val = new string(myString);
}

Video format or MIME type is not supported

In my case, this error:

Video format or MIME type is not supported.

Was due to the CSP in my .htaccess that did not allow the content to be loaded. You can check this by opening the browser's console and refreshing the page.

Once I added the domain that was hosting the video in the media-src part of that CSP, the console was clean and the video was loaded properly. Example:

Content-Security-Policy: default-src 'none'; media-src https://myvideohost.domain; script-src 'self'; style-src 'unsafe-inline' 'self'

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

As message shows that we need to add provider System.Data.SqlClient that's why we need to install nuget package of EntityFramework that has two dll but if we are developing only console application then we just need to add reference of EntityFramework.SqlServer.dll

How to find the lowest common ancestor of two nodes in any binary tree?

The answers given so far uses recursion or stores, for instance, a path in memory.

Both of these approaches might fail if you have a very deep tree.

Here is my take on this question. When we check the depth (distance from the root) of both nodes, if they are equal, then we can safely move upward from both nodes towards the common ancestor. If one of the depth is bigger then we should move upward from the deeper node while staying in the other one.

Here is the code:

findLowestCommonAncestor(v,w):
  depth_vv = depth(v);
  depth_ww = depth(w);

  vv = v; 
  ww = w;

  while( depth_vv != depth_ww ) {
    if ( depth_vv > depth_ww ) {
      vv = parent(vv);
      depth_vv--;
    else {
      ww = parent(ww);
      depth_ww--;
    }
  }

  while( vv != ww ) {
    vv = parent(vv);
    ww = parent(ww);
  }

  return vv;    

The time complexity of this algorithm is: O(n). The space complexity of this algorithm is: O(1).

Regarding the computation of the depth, we can first remember the definition: If v is root, depth(v) = 0; Otherwise, depth(v) = depth(parent(v)) + 1. We can compute depth as follows:

depth(v):
  int d = 0;
  vv = v;
  while ( vv is not root ) {
    vv = parent(vv);
    d++;
  }
  return d;

Get checkbox value in jQuery

<script type="text/javascript">
$(document).ready(function(){
    $('.laravel').click(function(){
        var val = $(this).is(":checked");
        $('#category').submit();
    });
});

<form action="{{route('directory')}}" method="post" id="category">
                        <input type="hidden" name="_token" value="{{ csrf_token() }}">
                        <input name="category" value="{{$name->id}}"  class="laravel" type="checkbox">{{$name->name}}
                      </form>

Firing events on CSS class changes in jQuery

You can bind the DOMSubtreeModified event. I add an example here:

HTML

<div id="mutable" style="width:50px;height:50px;">sjdfhksfh<div>
<div>
  <button id="changeClass">Change Class</button>
</div>

JavaScript

$(document).ready(function() {
  $('#changeClass').click(function() {
    $('#mutable').addClass("red");
  });

  $('#mutable').bind('DOMSubtreeModified', function(e) {
      alert('class changed');
  });
});

http://jsfiddle.net/hnCxK/13/

New xampp security concept: Access Forbidden Error 403 - Windows 7 - phpMyAdmin

Ubuntu (Linux)

:- $ sudo gedit /opt/lampp/etc/extra/httpd-xampp.conf

 Comment "Deny from all" in the following section,

Change file

# New XAMPP security concept
# <LocationMatch "^/(?i:(?:xampp|security|licenses|phpmyadmin|webalizer|server-status|server-info))">
    Order deny,allow

   #Deny from all
   #Require local
    Allow from ::1 127.0.0.0/8 \
            fc00::/7 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16 \
            fe80::/10 169.254.0.0/16

    ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var

How to count the number of occurrences of an element in a List

In Java 8:

Map<String, Long> counts =
    list.stream().collect(Collectors.groupingBy(e -> e, Collectors.counting()));

Better techniques for trimming leading zeros in SQL Server?

For converting number as varchar to int, you could also use simple

(column + 0)

Export table to file with column headers (column names) using the bcp utility and SQL Server 2008

This method automatically outputs column names with your row data using BCP.

The script writes one file for the column headers (read from INFORMATION_SCHEMA.COLUMNS table) then appends another file with the table data.

The final output is combined into TableData.csv which has the headers and row data. Just replace the environment variables at the top to specify the Server, Database and Table name.

set BCP_EXPORT_SERVER=put_my_server_name_here
set BCP_EXPORT_DB=put_my_db_name_here
set BCP_EXPORT_TABLE=put_my_table_name_here

BCP "DECLARE @colnames VARCHAR(max);SELECT @colnames = COALESCE(@colnames + ',', '') + column_name from %BCP_EXPORT_DB%.INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='%BCP_EXPORT_TABLE%'; select @colnames;" queryout HeadersOnly.csv -c -T -S%BCP_EXPORT_SERVER%

BCP %BCP_EXPORT_DB%.dbo.%BCP_EXPORT_TABLE% out TableDataWithoutHeaders.csv -c -t, -T -S%BCP_EXPORT_SERVER%

set BCP_EXPORT_SERVER=
set BCP_EXPORT_DB=
set BCP_EXPORT_TABLE=

copy /b HeadersOnly.csv+TableDataWithoutHeaders.csv TableData.csv

del HeadersOnly.csv
del TableDataWithoutHeaders.csv

Note that if you need to supply credentials, replace the -T option with -U my_username -P my_password

This method has the advantage of always having the column names in sync with the table by using INFORMATION_SCHEMA.COLUMNS. The downside is that it creates temporary files. Microsoft should really fix the bcp utility to support this.

This solution uses the SQL row concatenation trick from here combined with bcp ideas from here

How to get values of selected items in CheckBoxList with foreach in ASP.NET C#?

Note that I prefer the code to be short.

List<ListItem> selected = CBLGold.Items.Cast<ListItem>()
    .Where(li => li.Selected)
    .ToList();

or with a simple foreach:

List<ListItem> selected = new List<ListItem>();
foreach (ListItem item in CBLGold.Items)
    if (item.Selected) selected.Add(item);

If you just want the ListItem.Value:

List<string> selectedValues = CBLGold.Items.Cast<ListItem>()
   .Where(li => li.Selected)
   .Select(li => li.Value)
   .ToList();

Django - after login, redirect user to his custom page --> mysite.com/username

If you're using Django's built-in LoginView, it takes next as context, which is "The URL to redirect to after successful login. This may contain a query string, too." (see docs)

Also from the docs:

"If login is successful, the view redirects to the URL specified in next. If next isn’t provided, it redirects to settings.LOGIN_REDIRECT_URL (which defaults to /accounts/profile/)."

Example code:

urls.py

from django.urls import path
from django.contrib.auth import views as auth_views

from account.forms import LoginForm # optional form to pass to view


urlpatterns = [
    ...

    # --------------- login url/view -------------------
    path('account/login/', auth_views.LoginView.as_view(
        template_name='login.html',  
        authentication_form=LoginForm, 
        extra_context={ 

            # option 1: provide full path
            'next': '/account/my_custom_url/', 

            # option 2: just provide the name of the url
            # 'next': 'custom_url_name',  
        },
    ), name='login'),

    ...
]

login.html

...

<form method="post" action="{% url 'login' %}">

  ...

  {# option 1 #}
  <input type="hidden" name="next" value="{{ next }}">

  {# option 2 #}
  {# <input type="hidden" name="next" value="{% url next %}"> #}

</form>

Byte and char conversion in Java

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

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

From the language specification:

5.1.4. Widening and Narrowing Primitive Conversion

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


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


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

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

Include in SELECT a column that isn't actually in the database

You may want to use:

SELECT Name, 'Unpaid' AS Status FROM table;

The SELECT clause syntax, as defined in MSDN: SELECT Clause (Transact-SQL), is as follows:

SELECT [ ALL | DISTINCT ]
[ TOP ( expression ) [ PERCENT ] [ WITH TIES ] ] 
<select_list> 

Where the expression can be a constant, function, any combination of column names, constants, and functions connected by an operator or operators, or a subquery.

How to remove item from array by value?

If you have unique values in your array and ordering doesn't matter, you can use Set, and it has delete:

var mySet = new Set(['foo']);
mySet.delete('foo'); // Returns true.  Successfully removed.
mySet.has('foo');    // Returns false. The "foo" element is no longer present.