Programs & Examples On #Urlencode

To “URL encode” or “percent encode” text means to encode it for use in a URL. Some characters are not valid when used as-is in URLs, and so much be URL-encoded (percent-encoded) when appearing in URLs.

URL Encoding using C#

In addition to @Dan Herbert's answer , You we should encode just the values generally.

Split has params parameter Split('&','='); expression firstly split by & then '=' so odd elements are all values to be encoded shown below.

public static void EncodeQueryString(ref string queryString)
{
    var array=queryString.Split('&','=');
    for (int i = 0; i < array.Length; i++) {
        string part=array[i];
        if(i%2==1)
        {               
            part=System.Web.HttpUtility.UrlEncode(array[i]);
            queryString=queryString.Replace(array[i],part);
        }
    }
}

Encode URL in JavaScript?

You should not use encodeURIComponent() directly.

Take a look at RFC3986: Uniform Resource Identifier (URI): Generic Syntax

sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="

The purpose of reserved characters is to provide a set of delimiting characters that are distinguishable from other data within a URI.

These reserved characters from the URI definition in RFC3986 ARE NOT escaped by encodeURIComponent().

MDN Web Docs: encodeURIComponent()

To be more stringent in adhering to RFC 3986 (which reserves !, ', (, ), and *), even though these characters have no formalized URI delimiting uses, the following can be safely used:

Use the MDN Web Docs function...

function fixedEncodeURIComponent(str) {
  return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
    return '%' + c.charCodeAt(0).toString(16);
  });
}

URL encoding in Android

You don't encode the entire URL, only parts of it that come from "unreliable sources".

  • Java:

    String query = URLEncoder.encode("apples oranges", "utf-8");
    String url = "http://stackoverflow.com/search?q=" + query;
    
  • Kotlin:

    val query: String = URLEncoder.encode("apples oranges", "utf-8")
    val url = "http://stackoverflow.com/search?q=$query"
    

Alternatively, you can use Strings.urlEncode(String str) of DroidParts that doesn't throw checked exceptions.

Or use something like

String uri = Uri.parse("http://...")
                .buildUpon()
                .appendQueryParameter("key", "val")
                .build().toString();

How to set the "Content-Type ... charset" in the request header using a HTML link

This is not possible from HTML on. The closest what you can get is the accept-charset attribute of the <form>. Only MSIE browser adheres that, but even then it is doing it wrong (e.g. CP1252 is actually been used when it says that it has sent ISO-8859-1). Other browsers are fully ignoring it and they are using the charset as specified in the Content-Type header of the response. Setting the character encoding right is basically fully the responsiblity of the server side. The client side should just send it back in the same charset as the server has sent the response in.

To the point, you should really configure the character encoding stuff entirely from the server side on. To overcome the inability to edit URIEncoding attribute, someone here on SO wrote a (complex) filter: Detect the URI encoding automatically in Tomcat. You may find it useful as well (note: I haven't tested it).


Update: Noted should be that the meta tag as given in your question is ignored when the content is been transferred over HTTP. Instead, the HTTP response Content-Type header will be used to determine the content type and character encoding. You can determine the HTTP header with for example Firebug, in the Net panel.

alt text

How to encode the plus (+) symbol in a URL

It's safer to always percent-encode all characters except those defined as "unreserved" in RFC-3986.

unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"

So, percent-encode the plus character and other special characters.

The problem that you are having with pluses is because, according to RFC-1866 (HTML 2.0 specification), paragraph 8.2.1. subparagraph 1., "The form field names and values are escaped: space characters are replaced by `+', and then reserved characters are escaped"). This way of encoding form data is also given in later HTML specifications, look for relevant paragraphs about application/x-www-form-urlencoded.

How to URL encode in Python 3?

For Python 3 you could try using quote instead of quote_plus:

import urllib.parse

print(urllib.parse.quote("http://www.sample.com/"))

Result:

http%3A%2F%2Fwww.sample.com%2F

Or:

from requests.utils import requote_uri
requote_uri("http://www.sample.com/?id=123 abc")

Result:

'https://www.sample.com/?id=123%20abc'

Server.UrlEncode vs. HttpUtility.UrlEncode

The same, Server.UrlEncode() calls HttpUtility.UrlEncode()

Encode/Decode URLs in C++

Adding a follow-up to Bill's recommendation for using libcurl: great suggestion, and to be updated:
after 3 years, the curl_escape function is deprecated, so for future use it's better to use curl_easy_escape.

How to encode a URL in Swift

URLQueryAllowedCharacterSet should not be used for URL encoding of query parameters because this charset includes &, ?, / etc. which serve as delimiters in a URL query, e.g.

/?paramname=paramvalue&paramname=paramvalue

These characters are allowed in URL queries as a whole but not in parameter values.

RFC 3986 specifically talks about unreserved characters, which are different from allowed:

2.3. Unreserved Characters

Characters that are allowed in a URI but do not have a reserved
purpose are called unreserved. These include uppercase and lowercase letters, decimal digits, hyphen, period, underscore, and tilde.

  unreserved  = ALPHA / DIGIT / "-" / "." / "_" / "~"

Accordingly:

extension String {
    var URLEncoded:String {
        var URLEncoded:String {
    let unreservedChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"
    let unreservedCharsSet: CharacterSet = CharacterSet(charactersIn: unreservedChars)
    let encodedString = self.addingPercentEncoding(withAllowedCharacters: unreservedCharsSet)!
    return encodedString
}
    }
}

The code above doesn't make a call to alphanumericCharacterSet because of the enormous size of the charset it returns (103806 characters). And in view of how many Unicode characters alphanumericCharacterSet allows for, using it for the purpose of URL encoding would be simply erroneous.

Usage:

let URLEncodedString = myString.URLEncoded

How do I replace all the spaces with %20 in C#?

I needed to do this too, found this question from years ago but question title and text don't quite match up, and using Uri.EscapeDataString or UrlEncode (don't use that one please!) doesn't usually make sense unless we are talking about passing URLs as parameters to other URLs.

(For example, passing a callback URL when doing open ID authentication, Azure AD, etc.)

Hoping this is more pragmatic answer to the question: I want to make a string into a URL using C#, there must be something in the .NET framework that should help, right?

Yes - two functions are helpful for making URL strings in C#

  • String.Format for formatting the URL
  • Uri.EscapeDataString for escaping any parameters in the URL

This code

String.Format("https://site/app/?q={0}&redirectUrl={1}", 
  Uri.EscapeDataString("search for cats"), 
  Uri.EscapeDataString("https://mysite/myapp/?state=from idp"))

produces this result

https://site/app/?q=search%20for%20cats&redirectUrl=https%3A%2F%2Fmysite%2Fmyapp

Which can be safely copied and pasted into a browser's address bar, or the src attribute of a HTML A tag, or used with curl, or encoded into a QR code, etc.

HTTP URL Address Encoding in Java

I read the previous answers to write my own method because I could not have something properly working using the solution of the previous answers, it looks good for me but if you can find URL that does not work with this, please let me know.

public static URL convertToURLEscapingIllegalCharacters(String toEscape) throws MalformedURLException, URISyntaxException {
            URL url = new URL(toEscape);
            URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
            //if a % is included in the toEscape string, it will be re-encoded to %25 and we don't want re-encoding, just encoding
            return new URL(uri.toString().replace("%25", "%"));
}

How do I encode URI parameter values?

Mmhh I know you've already discarded URLEncoder, but despite of what the docs say, I decided to give it a try.

You said:

For example, given an input:

http://google.com/resource?key=value

I expect the output:

http%3a%2f%2fgoogle.com%2fresource%3fkey%3dvalue

So:

C:\oreyes\samples\java\URL>type URLEncodeSample.java
import java.net.*;

public class URLEncodeSample {
    public static void main( String [] args ) throws Throwable {
        System.out.println( URLEncoder.encode( args[0], "UTF-8" ));
    }
}

C:\oreyes\samples\java\URL>javac URLEncodeSample.java

C:\oreyes\samples\java\URL>java URLEncodeSample "http://google.com/resource?key=value"
http%3A%2F%2Fgoogle.com%2Fresource%3Fkey%3Dvalue

As expected.

What would be the problem with this?

Encoding URL query parameters in Java

if you have only space problem in url. I have used below code and it work fine

String url;
URL myUrl = new URL(url.replace(" ","%20"));

example : url is

www.xyz.com?para=hello sir

then output of muUrl is

www.xyz.com?para=hello%20sir

How to URL encode a string in Ruby

str = "\x12\x34\x56\x78\x9a\xbc\xde\xf1\x23\x45\x67\x89\xab\xcd\xef\x12\x34\x56\x78\x9a".force_encoding('ASCII-8BIT')
puts CGI.escape str


=> "%124Vx%9A%BC%DE%F1%23Eg%89%AB%CD%EF%124Vx%9A"

urlencode vs rawurlencode?

I believe urlencode is for query parameters, whereas the rawurlencode is for the path segments. This is mainly due to %20 for path segments vs + for query parameters. See this answer which talks about the spaces: When to encode space to plus (+) or %20?

However %20 now works in query parameters as well, which is why rawurlencode is always safer. However the plus sign tends to be used where user experience of editing and readability of query parameters matter.

Note that this means rawurldecode does not decode + into spaces (http://au2.php.net/manual/en/function.rawurldecode.php). This is why the $_GET is always automatically passed through urldecode, which means that + and %20 are both decoded into spaces.

If you want the encoding and decoding to be consistent between inputs and outputs and you have selected to always use + and not %20 for query parameters, then urlencode is fine for query parameters (key and value).

The conclusion is:

Path Segments - always use rawurlencode/rawurldecode

Query Parameters - for decoding always use urldecode (done automatically), for encoding, both rawurlencode or urlencode is fine, just choose one to be consistent, especially when comparing URLs.

How to create query parameters in Javascript?

functional

function encodeData(data) {
    return Object.keys(data).map(function(key) {
        return [key, data[key]].map(encodeURIComponent).join("=");
    }).join("&");
}   

What is the proper way to URL encode Unicode characters?

I would always encode in UTF-8. From the Wikipedia page on percent encoding:

The generic URI syntax mandates that new URI schemes that provide for the representation of character data in a URI must, in effect, represent characters from the unreserved set without translation, and should convert all other characters to bytes according to UTF-8, and then percent-encode those values. This requirement was introduced in January 2005 with the publication of RFC 3986. URI schemes introduced before this date are not affected.

It seems like because there were other accepted ways of doing URL encoding in the past, browsers attempt several methods of decoding a URI, but if you're the one doing the encoding you should use UTF-8.

How can I URL encode a string in Excel VBA?

Although, this one is very old. I have come up with a solution based in this answer:

Dim ScriptEngine As ScriptControl
Set ScriptEngine = New ScriptControl
ScriptEngine.Language = "JScript"

ScriptEngine.AddCode "function encode(str) {return encodeURIComponent(str);}"
Dim encoded As String
encoded = ScriptEngine.Run("encode", "€ömE.sdfds")

Add Microsoft Script Control as reference and you are done.

Just a side note, because of the JS part, this is fully UTF-8-compatible. VB will convert correctly from UTF-16 to UTF-8.

URLEncoder not able to translate space character

Encode Query params

org.apache.commons.httpclient.util.URIUtil
    URIUtil.encodeQuery(input);

OR if you want to escape chars within URI

public static String escapeURIPathParam(String input) {
  StringBuilder resultStr = new StringBuilder();
  for (char ch : input.toCharArray()) {
   if (isUnsafe(ch)) {
    resultStr.append('%');
    resultStr.append(toHex(ch / 16));
    resultStr.append(toHex(ch % 16));
   } else{
    resultStr.append(ch);
   }
  }
  return resultStr.toString();
 }

 private static char toHex(int ch) {
  return (char) (ch < 10 ? '0' + ch : 'A' + ch - 10);
 }

 private static boolean isUnsafe(char ch) {
  if (ch > 128 || ch < 0)
   return true;
  return " %$&+,/:;=?@<>#%".indexOf(ch) >= 0;
 }

How to percent-encode URL parameters in Python?

If you're using django, you can use urlquote:

>>> from django.utils.http import urlquote
>>> urlquote(u"Müller")
u'M%C3%BCller'

Note that changes to Python since this answer was published mean that this is now a legacy wrapper. From the Django 2.1 source code for django.utils.http:

A legacy compatibility wrapper to Python's urllib.parse.quote() function.
(was used for unicode handling on Python 2)

In a URL, should spaces be encoded using %20 or +?

It shouldn't matter, any more than if you encoded the letter A as %41.

However, if you're dealing with a system that doesn't recognize one form, it seems like you're just going to have to give it what it expects regardless of what the "spec" says.

URL encode sees “&” (ampersand) as “&amp;” HTML entity

Without seeing your code, it's hard to answer other than a stab in the dark. I would guess that the string you're passing to encodeURIComponent(), which is the correct method to use, is coming from the result of accessing the innerHTML property. The solution is to get the innerText/textContent property value instead:

var str, 
    el = document.getElementById("myUrl");

if ("textContent" in el)
    str = encodeURIComponent(el.textContent);
else
    str = encodeURIComponent(el.innerText);

If that isn't the case, you can use the replace() method to replace the HTML entity:

encodeURIComponent(str.replace(/&amp;/g, "&"));

Parsing GET request parameters in a URL that contains another URL

While creating url encode them with urlencode

$val=urlencode('http://google.com/?var=234&key=234')

<a href="http://localhost/test.php?id=<?php echo $val ?>">Click here</a>

and while fetching decode it wiht urldecode

JavaScript URL Decode function

_x000D_
_x000D_
var uri = "my test.asp?name=ståle&car=saab";_x000D_
console.log(encodeURI(uri));
_x000D_
_x000D_
_x000D_

Java URL encoding of query string parameters

You need to first create a URI like:

String urlStr = "http://www.example.com/CEREC® Materials & Accessories/IPS Empress® CAD.pdf"
URL url= new URL(urlStr);
URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());

Then convert that Uri to ASCII string:

urlStr=uri.toASCIIString();

Now your url string is completely encoded first we did simple url encoding and then we converted it to ASCII String to make sure no character outside US-ASCII are remaining in string. This is exactly how browsers do.

Should I URL-encode POST data?

curl will encode the data for you, just drop your raw field data into the fields array and tell it to "go".

How do you UrlEncode without using System.Web?

In .Net 4.5+ use WebUtility

Just for formatting I'm submitting this as an answer.

Couldn't find any good examples comparing them so:

string testString = "http://test# space 123/text?var=val&another=two";
Console.WriteLine("UrlEncode:         " + System.Web.HttpUtility.UrlEncode(testString));
Console.WriteLine("EscapeUriString:   " + Uri.EscapeUriString(testString));
Console.WriteLine("EscapeDataString:  " + Uri.EscapeDataString(testString));
Console.WriteLine("EscapeDataReplace: " + Uri.EscapeDataString(testString).Replace("%20", "+"));

Console.WriteLine("HtmlEncode:        " + System.Web.HttpUtility.HtmlEncode(testString));
Console.WriteLine("UrlPathEncode:     " + System.Web.HttpUtility.UrlPathEncode(testString));

//.Net 4.0+
Console.WriteLine("WebUtility.HtmlEncode: " + WebUtility.HtmlEncode(testString));
//.Net 4.5+
Console.WriteLine("WebUtility.UrlEncode:  " + WebUtility.UrlEncode(testString));

Outputs:

UrlEncode:             http%3a%2f%2ftest%23+space+123%2ftext%3fvar%3dval%26another%3dtwo
EscapeUriString:       http://test#%20space%20123/text?var=val&another=two
EscapeDataString:      http%3A%2F%2Ftest%23%20space%20123%2Ftext%3Fvar%3Dval%26another%3Dtwo
EscapeDataReplace:     http%3A%2F%2Ftest%23+space+123%2Ftext%3Fvar%3Dval%26another%3Dtwo

HtmlEncode:            http://test# space 123/text?var=val&amp;another=two
UrlPathEncode:         http://test#%20space%20123/text?var=val&another=two

//.Net 4.0+
WebUtility.HtmlEncode: http://test# space 123/text?var=val&amp;another=two
//.Net 4.5+
WebUtility.UrlEncode:  http%3A%2F%2Ftest%23+space+123%2Ftext%3Fvar%3Dval%26another%3Dtwo

In .Net 4.5+ use WebUtility.UrlEncode

This appears to replicate HttpUtility.UrlEncode (pre-v4.0) for the more common characters:
Uri.EscapeDataString(testString).Replace("%20", "+").Replace("'", "%27").Replace("~", "%7E")
Note: EscapeUriString will keep a valid uri string, which causes it to use as many plaintext characters as possible.

See this answer for a Table Comparing the various Encodings:
https://stackoverflow.com/a/11236038/555798

Line Breaks All of them listed here (other than HttpUtility.HtmlEncode) will convert "\n\r" into %0a%0d or %0A%0D

Please feel free to edit this and add new characters to my test string, or leave them in the comments and I'll edit it.

How to properly URL encode a string in PHP?

For the URI query use urlencode/urldecode; for anything else use rawurlencode/rawurldecode.

The difference between urlencode and rawurlencode is that

PHP: convert spaces in string into %20?

I believe that, if you need to use the %20 variant, you could perhaps use rawurlencode().

When to encode space to plus (+) or %20?

Its better to always encode spaces as %20, not as "+".

It was RFC-1866 (HTML 2.0 specification), which specified that space characters should be encoded as "+" in "application/x-www-form-urlencoded" content-type key-value pairs. (see paragraph 8.2.1. subparagraph 1.). This way of encoding form data is also given in later HTML specifications, look for relevant paragraphs about application/x-www-form-urlencoded.

Here is an example of such a string in URL where RFC-1866 allows encoding spaces as pluses: "http://example.com/over/there?name=foo+bar". So, only after "?", spaces can be replaced by pluses, according to RFC-1866. In other cases, spaces should be encoded to %20. But since it's hard to determine the context, it's the best practice to never encode spaces as "+".

I would recommend to percent-encode all character except "unreserved" defined in RFC-3986, p.2.3

unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"

Swift - encode URL

Had need of this myself, so I wrote a String extension that both allows for URLEncoding strings, as well as the more common end goal, converting a parameter dictionary into "GET" style URL Parameters:

extension String {
    func URLEncodedString() -> String? {
        var escapedString = self.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
        return escapedString
    }
    static func queryStringFromParameters(parameters: Dictionary<String,String>) -> String? {
        if (parameters.count == 0)
        {
            return nil
        }
        var queryString : String? = nil
        for (key, value) in parameters {
            if let encodedKey = key.URLEncodedString() {
                if let encodedValue = value.URLEncodedString() {
                    if queryString == nil
                    {
                        queryString = "?"
                    }
                    else
                    {
                        queryString! += "&"
                    }
                    queryString! += encodedKey + "=" + encodedValue
                }
            }
        }
        return queryString
    }
}

Enjoy!

Objective-C and Swift URL encoding

Here's what I use. Note you have to use the @autoreleasepool feature or the program might crash or lockup the IDE. I had to restart my IDE three times until I realized the fix. It appears that this code is ARC compliant.

This question has been asked many times, and many answers given, but sadly all of the ones selected (and a few others suggested) are wrong.

Here's the test string that I used: This is my 123+ test & test2. Got it?!

These are my Objective C++ class methods:

static NSString * urlDecode(NSString *stringToDecode) {
    NSString *result = [stringToDecode stringByReplacingOccurrencesOfString:@"+" withString:@" "];
    result = [result stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    return result;
}

static NSString * urlEncode(NSString *stringToEncode) {
    @autoreleasepool {
        NSString *result = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
                NULL,
                (CFStringRef)stringToEncode,
                NULL,
                (CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ",
                kCFStringEncodingUTF8
            ));
        result = [result stringByReplacingOccurrencesOfString:@"%20" withString:@"+"];
        return result;
    }
}

How to urlencode data for curl command?

If you wish to run GET request and use pure curl just add --get to @Jacob's solution.

Here is an example:

curl -v --get --data-urlencode "access_token=$(cat .fb_access_token)" https://graph.facebook.com/me/feed

How to urlencode a querystring in Python?

Context

  • Python (version 2.7.2 )

Problem

  • You want to generate a urlencoded query string.
  • You have a dictionary or object containing the name-value pairs.
  • You want to be able to control the output ordering of the name-value pairs.

Solution

  • urllib.urlencode
  • urllib.quote_plus

Pitfalls

Example

The following is a complete solution, including how to deal with some pitfalls.

### ********************
## init python (version 2.7.2 )
import urllib

### ********************
## first setup a dictionary of name-value pairs
dict_name_value_pairs = {
  "bravo"   : "True != False",
  "alpha"   : "http://www.example.com",
  "charlie" : "hello world",
  "delta"   : "1234567 !@#$%^&*",
  "echo"    : "[email protected]",
  }

### ********************
## setup an exact ordering for the name-value pairs
ary_ordered_names = []
ary_ordered_names.append('alpha')
ary_ordered_names.append('bravo')
ary_ordered_names.append('charlie')
ary_ordered_names.append('delta')
ary_ordered_names.append('echo')

### ********************
## show the output results
if('NO we DO NOT care about the ordering of name-value pairs'):
  queryString  = urllib.urlencode(dict_name_value_pairs)
  print queryString 
  """
  echo=user%40example.com&bravo=True+%21%3D+False&delta=1234567+%21%40%23%24%25%5E%26%2A&charlie=hello+world&alpha=http%3A%2F%2Fwww.example.com
  """

if('YES we DO care about the ordering of name-value pairs'):
  queryString  = "&".join( [ item+'='+urllib.quote_plus(dict_name_value_pairs[item]) for item in ary_ordered_names ] )
  print queryString
  """
  alpha=http%3A%2F%2Fwww.example.com&bravo=True+%21%3D+False&charlie=hello+world&delta=1234567+%21%40%23%24%25%5E%26%2A&echo=user%40example.com
  """ 

equivalent of rm and mv in windows .cmd

move and del ARE certainly the equivalents, but from a functionality standpoint they are woefully NOT equivalent. For example, you can't move both files AND folders (in a wildcard scenario) with the move command. And the same thing applies with del.

The preferred solution in my view is to use Win32 ports of the Linux tools, the best collection of which I have found being here.

mv and rm are in the CoreUtils package and they work wonderfully!

Javascript Cookie with no expiration date

Nope. That can't be done. The best 'way' of doing that is just making the expiration date be like 2100.

MySQL check if a table exists without throwing an exception

This is posted simply if anyone comes looking for this question. Even though its been answered a bit. Some of the replies make it more complex than it needed to be.

For mysql* I used :

if (mysqli_num_rows(
    mysqli_query(
                    $con,"SHOW TABLES LIKE '" . $table . "'")
                ) > 0
        or die ("No table set")
    ){

In PDO I used:

if ($con->query(
                   "SHOW TABLES LIKE '" . $table . "'"
               )->rowCount() > 0
        or die("No table set")
   ){

With this I just push the else condition into or. And for my needs I only simply need die. Though you can set or to other things. Some might prefer the if/ else if/else. Which is then to remove or and then supply if/else if/else.

Git fatal: protocol 'https' is not supported

Copy in plain notepad (git clone https://github.com/./Spoon-Knife.git) and paste it in cmd. now it will work.

How to write file in UTF-8 format?

I put all together and got easy way to convert ANSI text files to "UTF-8 No Mark":

function filesToUTF8($searchdir,$convdir,$filetypes) {
  $get_files = glob($searchdir.'*{'.$filetypes.'}', GLOB_BRACE);
  foreach($get_files as $file) {
    $expl_path = explode('/',$file);
    $filename = end($expl_path);
    $get_file_content = file_get_contents($file);
    $new_file_content = iconv(mb_detect_encoding($get_file_content, mb_detect_order(), true), "UTF-8", $get_file_content);
    $put_new_file = file_put_contents($convdir.$filename,$new_file_content);
  }
}

Usage: filesToUTF8('C:/Temp/','C:/Temp/conv_files/','php,txt');

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

So this happened! I accidently clicked on "assume unchanged"! I tried searching on Internet, but could not find any working solution! So, I tried few things here and there and finally I found the solution (easiest one) for this which will undo the assume unchanged!

Right click on "Your Project" then Team > Advanced > No assume Unchanged.

Image shows the way to do it

In JavaScript can I make a "click" event fire programmatically for a file input element?

I have been searching for solution to this whole day. And these are the conclusions that I have made:

  1. For the security reasons Opera and Firefox don't allow to trigger file input.
  2. The only convenient alternative is to create a "hidden" file input (using opacity, not "hidden" or "display: none"!) and afterwards create the button "below" it. In this way the button is seen but on user click it actually activates the file input.

Hope this helps! :)

<div style="display: block; width: 100px; height: 20px; overflow: hidden;">
<button style="width: 110px; height: 30px; position: relative; top: -5px; left: -5px;"><a href="javascript: void(0)">Upload File</a></button>
<input type="file" id="upload_input" name="upload" style="font-size: 50px; width: 120px; opacity: 0; filter:alpha(opacity=0);  position: relative; top: -40px;; left: -20px" />
</div>

Creating a byte array from a stream

i was able to make it work on a single line:

byte [] byteArr= ((MemoryStream)localStream).ToArray();

as clarified by johnnyRose, Above code will only work for MemoryStream

How would you make two <div>s overlap?

Using CSS, you set the logo div to position absolute, and set the z-order to be above the second div.

#logo
{
    position: absolute:
    z-index: 2000;
    left: 100px;
    width: 100px;
    height: 50px;
}

What is [Serializable] and when should I use it?

What is it?

When you create an object in a .Net framework application, you don't need to think about how the data is stored in memory. Because the .Net Framework takes care of that for you. However, if you want to store the contents of an object to a file, send an object to another process or transmit it across the network, you do have to think about how the object is represented because you will need to convert to a different format. This conversion is called SERIALIZATION.

Uses for Serialization

Serialization allows the developer to save the state of an object and recreate it as needed, providing storage of objects as well as data exchange. Through serialization, a developer can perform actions like sending the object to a remote application by means of a Web Service, passing an object from one domain to another, passing an object through a firewall as an XML string, or maintaining security or user-specific information across applications.

Apply SerializableAttribute to a type to indicate that instances of this type can be serialized. Apply the SerializableAttribute even if the class also implements the ISerializable interface to control the serialization process.

All the public and private fields in a type that are marked by the SerializableAttribute are serialized by default, unless the type implements the ISerializable interface to override the serialization process. The default serialization process excludes fields that are marked with NonSerializedAttribute. If a field of a serializable type contains a pointer, a handle, or some other data structure that is specific to a particular environment, and cannot be meaningfully reconstituted in a different environment, then you might want to apply NonSerializedAttribute to that field.

See MSDN for more details.

Edit 1

Any reason to not mark something as serializable

When transferring or saving data, you need to send or save only the required data. So there will be less transfer delays and storage issues. So you can opt out unnecessary chunk of data when serializing.

"Could not find bundler" error

Make sure you're entering "bundle" update, if you have the bundler gem installed.

bundle update

If you don't have bundler installed, do gem install bundler.

How to run crontab job every week on Sunday

@weekly work better for me! example,add the fellowing crontab -e ,it will work in every sunday 0:00 AM @weekly /root/fd/databasebackup/week.sh >> ~/test.txt

How to implement and do OCR in a C# project?

I'm using tesseract OCR engine with TessNet2 (a C# wrapper - http://www.pixel-technology.com/freeware/tessnet2/).

Some basic code:

using tessnet2;

...

Bitmap image = new Bitmap(@"u:\user files\bwalker\2849257.tif");
            tessnet2.Tesseract ocr = new tessnet2.Tesseract();
            ocr.SetVariable("tessedit_char_whitelist", "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz.,$-/#&=()\"':?"); // Accepted characters
            ocr.Init(@"C:\Users\bwalker\Documents\Visual Studio 2010\Projects\tessnetWinForms\tessnetWinForms\bin\Release\", "eng", false); // Directory of your tessdata folder
            List<tessnet2.Word> result = ocr.DoOCR(image, System.Drawing.Rectangle.Empty);
            string Results = "";
            foreach (tessnet2.Word word in result)
            {
                Results += word.Confidence + ", " + word.Text + ", " + word.Left + ", " + word.Top + ", " + word.Bottom + ", " + word.Right + "\n";
            }

how to add css class to html generic control div?

To add a class to a div that is generated via the HtmlGenericControl way you can use:

div1.Attributes.Add("class", "classname"); 

If you are using the Panel option, it would be:

panel1.CssClass = "classname";

Delete all rows in an HTML table

How about this:

When the page first loads, do this:

var myTable = document.getElementById("myTable");
myTable.oldHTML=myTable.innerHTML;

Then when you want to clear the table:

myTable.innerHTML=myTable.oldHTML;

The result will be your header row(s) if that's all you started with, the performance is dramatically faster than looping.

Difference between try-catch and throw in java

try block contains set of statements where an exception can occur.

catch block will be used to used to handle the exception that occur with in try block. A try block is always followed by a catch block and we can have multiple catch blocks.

finally block is executed after catch block. We basically use it to put some common code when there are multiple catch blocks. Even if there is an exception or not finally block gets executed.

throw keyword will allow you to throw an exception and it is used to transfer control from try block to catch block.

throws keyword is used for exception handling without try & catch block. It specifies the exceptions that a method can throw to the caller and does not handle itself.

// Java program to demonstrate working of throws, throw, try, catch and finally.

 public class MyExample { 
      
        static void myMethod() throws IllegalAccessException 
        { 
            System.out.println("Inside myMethod()."); 
            throw new IllegalAccessException("demo"); 
        } 
      
        // This is a caller function  
        public static void main(String args[]) 
        { 
            try { 
                myMethod(); 
            } 
            catch (IllegalAccessException e) { 
                System.out.println("exception caught in main method."); 
            }
            finally(){
                System.out.println("I am in final block.");
            } 
        } 
    } 

Output:

Inside myMethod().
exception caught in main method.
I am in final block.

How to find the difference in days between two dates?

And in python

$python -c "from datetime import date; print (date(2003,11,22)-date(2002,10,20)).days"
398

Include of non-modular header inside framework module

Try going Build Settings under "Target" and set "Allow Non-modular Includes in Framework Modules" to YES.

The real answer is that the location of the imports needs to be changed by the library owner. Those files ifaddrs.h, arpa/inet.h, sys/types.h are getting imported in a .h file in a framework, which Xcode doesn't like. The library maintainer should move them to a .m file. See for example this issue on GitHub, where AFNetworking fixed the same problem: https://github.com/AFNetworking/AFNetworking/issues/2205

iterating quickly through list of tuples

I wonder whether the below method is what you want.

You can use defaultdict.

>>> from collections import defaultdict
>>> s = [('red',1), ('blue',2), ('red',3), ('blue',4), ('red',1), ('blue',4)]
>>> d = defaultdict(list)
>>> for k, v in s:
       d[k].append(v)    
>>> sorted(d.items())
[('blue', [2, 4, 4]), ('red', [1, 3, 1])]

How to get the latest record in each group using GROUP BY?

Just complementing what Devart said, the below code is not ordering according to the question:

SELECT t1.* FROM messages t1
  JOIN (SELECT from_id, MAX(timestamp) timestamp FROM messages GROUP BY from_id) t2
    ON t1.from_id = t2.from_id AND t1.timestamp = t2.timestamp;

The "GROUP BY" clause must be in the main query since that we need first reorder the "SOURCE" to get the needed "grouping" so:

SELECT t1.* FROM messages t1
  JOIN (SELECT from_id, MAX(timestamp) timestamp FROM messages ORDER BY timestamp DESC) t2
    ON t1.from_id = t2.from_id AND t1.timestamp = t2.timestamp GROUP BY t2.timestamp;

Regards,

How to align two divs side by side using the float, clear, and overflow elements with a fixed position div/

I did this:

<!DOCTYPE HTML>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>AutoDealer</title>
        <style>
        .container{
            width: 860px;
            height: 1074px;
            margin-right: auto;
            margin-left: auto;
            border: 1px solid red;

        }
        .nav{

        }
        .wrapper{
            display: block;
            overflow: hidden;
            border: 1px solid green;
        }
       .otherWrapper{
            display: block;
            overflow: hidden;
            border: 1px solid green;
            float:left;
        }
    .left{
        width: 399px;
        float: left;
        background-color: pink;
    }
            .bottom{
        clear: both;
        width: 399px;
        background-color: yellow;



    }
    .right{
        height:350px;
        width: 449px;
        overflow: hidden;
        background-color: blue;
        overflow: hidden;
        float:right;
    }

    </style>
</head>
<body>
    <div class="container">
        <div class="nav"></div>
        <div class="wrapper">
        <div class="otherWrapper">
            <div class="left">
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ultricies aliquet tellus sit amet ultrices. Sed faucibus, nunc vitae accumsan laoreet, enim metus varius nulla, ac ultricies felis ante venenatis justo. In hac habitasse platea dictumst. In cursus enim nec urna molestie, id mattis elit mollis. In sed eros eget nibh congue vehicula. Nunc vestibulum enim risus, sit amet suscipit dui auctor et. Morbi orci magna, accumsan at turpis a, scelerisque congue eros. Morbi non mi vel nibh varius blandit sed et urna.</p>
            </div>
             <div class="bottom">
                <p>ucibus eros, sed viverra ex. Vestibulum aliquet accumsan massa, at feugiat ipsum interdum blandit. Morbi et orci hendrerit orci consequat ornare ac et sapien. Nulla vestibulum lectus bibendum, efficitur purus in, venenatis nunc. Nunc tincidunt velit sit amet orci pellentesq</p></div>
             </div>

             <div class="right">
                <p>Quisque vulputate mi id turpis luctus, quis laoreet nisi vestibulum. Morbi facilisis erat vitae augue ornare convallis. Fusce sit amet magna rutrum, hendrerit purus vitae, congue justo. Nam non mi eget purus ultricies lacinia. Fusce ante nisl, efficitur venenatis urna ut, pellentesque egestas nisl. In ut faucibus eros, sed viverra ex. Vestibulum aliquet accumsan massa, at feugiat ipsum interdum blandit. Morbi et orci hendrerit orci consequat ornare ac et sapien. Nulla vestibulum lectus bibendum, efficitur purus in, venenatis nunc. Nunc tincidunt velit sit amet orci pellentesque maximus. Quisque a tempus lectus.</p>
             </div>
        </div>
    </div>
</body>

So basically I just made another div to wrap the pink and yellow, and I make that div have a float:left on it. The blue div has a float:right on it.

Purge Kafka Topic

have you considered having your app simply use a new renamed topic? (i.e. a topic that is named like the original topic but with a "1" appended at the end).

That would also give your app a fresh clean topic.

HTTP error 403 in Python 3 Web Scraping

Based on previous answers this has worked for me with Python 3.7

from urllib.request import Request, urlopen

req = Request('Url_Link', headers={'User-Agent': 'XYZ/3.0'})
webpage = urlopen(req, timeout=10).read()

print(webpage)

Importing a GitHub project into Eclipse

When the local git projects are cloned in eclipse and are viewable in git perspective but not in package explorer (workspace), the following steps worked for me:

  • Select the repository in git perspective
  • Right click and select import projects

Sort a list of Class Instances Python

import operator
sorted_x = sorted(x, key=operator.attrgetter('score'))

if you want to sort x in-place, you can also:

x.sort(key=operator.attrgetter('score'))

How to disable back swipe gesture in UINavigationController on iOS 7

I found a solution:

Objective-C:

if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
}

Swift 3+:
self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false

Debugging the error "gcc: error: x86_64-linux-gnu-gcc: No such file or directory"

the error can be due to one of several missing package. Below command will install several packages like g++, gcc, etc.

sudo apt-get install build-essential

sum two columns in R

It could be that one or two of your columns may have a factor in them, or what is more likely is that your columns may be formatted as factors. Please would you give str(col1) and str(col2) a try? That should tell you what format those columns are in.

I am unsure if you're trying to add the rows of a column to produce a new column or simply all of the numbers in both columns to get a single number.

better way to drop nan rows in pandas

Just in case commands in previous answers doesn't work, Try this: dat.dropna(subset=['x'], inplace = True)

Iterate through object properties

As of JavaScript 1.8.5 you can use Object.keys(obj) to get an Array of properties defined on the object itself (the ones that return true for obj.hasOwnProperty(key)).

Object.keys(obj).forEach(function(key,index) {
    // key: the name of the object key
    // index: the ordinal position of the key within the object 
});

This is better (and more readable) than using a for-in loop.

Its supported on these browsers:

  • Firefox (Gecko): 4 (2.0)
  • Chrome: 5
  • Internet Explorer: 9

See the Mozilla Developer Network Object.keys()'s reference for futher information.

Circle drawing with SVG's arc path

A totally different approach:

Instead of fiddling with paths to specify an arc in svg, you can also take a circle element and specify a stroke-dasharray, in pseudo code:

with $score between 0..1, and pi = 3.141592653589793238

$length = $score * 2 * pi * $r
$max = 7 * $r  (i.e. well above 2*pi*r)

<circle r="$r" stroke-dasharray="$length $max" />

Its simplicity is the main advantage over the multiple-arc-path method (e.g. when scripting you only plug in one value and you're done for any arc length)

The arc starts at the rightmost point, and can be shifted around using a rotate transform.

Note: Firefox has an odd bug where rotations over 90 degrees or more are ignored. So to start the arc from the top, use:

<circle r="$r" transform="rotate(-89.9)" stroke-dasharray="$length $max" />

Change UITableView height dynamically

I found adding constraint programmatically much easier than in storyboard.

    var leadingMargin = NSLayoutConstraint(item: self.tableView, attribute: NSLayoutAttribute.LeadingMargin, relatedBy: NSLayoutRelation.Equal, toItem: self.mView, attribute: NSLayoutAttribute.LeadingMargin, multiplier: 1, constant: 0.0)

    var trailingMargin = NSLayoutConstraint(item: self.tableView, attribute: NSLayoutAttribute.TrailingMargin, relatedBy: NSLayoutRelation.Equal, toItem: mView, attribute: NSLayoutAttribute.TrailingMargin, multiplier: 1, constant: 0.0)

    var height = NSLayoutConstraint(item: self.tableView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: screenSize.height - 55)

    var bottom = NSLayoutConstraint(item: self.tableView, attribute: NSLayoutAttribute.BottomMargin, relatedBy: NSLayoutRelation.Equal, toItem: self.mView, attribute: NSLayoutAttribute.BottomMargin, multiplier: 1, constant: screenSize.height - 200)

    var top = NSLayoutConstraint(item: self.tableView, attribute: NSLayoutAttribute.TopMargin, relatedBy: NSLayoutRelation.Equal, toItem: self.mView, attribute: NSLayoutAttribute.TopMargin, multiplier: 1, constant: 250)

    self.view.addConstraint(leadingMargin)
    self.view.addConstraint(trailingMargin)
    self.view.addConstraint(height)
    self.view.addConstraint(bottom)
    self.view.addConstraint(top)

How to return result of a SELECT inside a function in PostgreSQL?

Use RETURN QUERY:

CREATE OR REPLACE FUNCTION word_frequency(_max_tokens int)
  RETURNS TABLE (txt   text   -- also visible as OUT parameter inside function
               , cnt   bigint
               , ratio bigint) AS
$func$
BEGIN
   RETURN QUERY
   SELECT t.txt
        , count(*) AS cnt                 -- column alias only visible inside
        , (count(*) * 100) / _max_tokens  -- I added brackets
   FROM  (
      SELECT t.txt
      FROM   token t
      WHERE  t.chartype = 'ALPHABETIC'
      LIMIT  _max_tokens
      ) t
   GROUP  BY t.txt
   ORDER  BY cnt DESC;                    -- potential ambiguity 
END
$func$  LANGUAGE plpgsql;

Call:

SELECT * FROM word_frequency(123);

Explanation:

  • It is much more practical to explicitly define the return type than simply declaring it as record. This way you don't have to provide a column definition list with every function call. RETURNS TABLE is one way to do that. There are others. Data types of OUT parameters have to match exactly what is returned by the query.

  • Choose names for OUT parameters carefully. They are visible in the function body almost anywhere. Table-qualify columns of the same name to avoid conflicts or unexpected results. I did that for all columns in my example.

    But note the potential naming conflict between the OUT parameter cnt and the column alias of the same name. In this particular case (RETURN QUERY SELECT ...) Postgres uses the column alias over the OUT parameter either way. This can be ambiguous in other contexts, though. There are various ways to avoid any confusion:

    1. Use the ordinal position of the item in the SELECT list: ORDER BY 2 DESC. Example:
    2. Repeat the expression ORDER BY count(*).
    3. (Not applicable here.) Set the configuration parameter plpgsql.variable_conflict or use the special command #variable_conflict error | use_variable | use_column in the function. See:
  • Don't use "text" or "count" as column names. Both are legal to use in Postgres, but "count" is a reserved word in standard SQL and a basic function name and "text" is a basic data type. Can lead to confusing errors. I use txt and cnt in my examples.

  • Added a missing ; and corrected a syntax error in the header. (_max_tokens int), not (int maxTokens) - type after name.

  • While working with integer division, it's better to multiply first and divide later, to minimize the rounding error. Even better: work with numeric (or a floating point type). See below.

Alternative

This is what I think your query should actually look like (calculating a relative share per token):

CREATE OR REPLACE FUNCTION word_frequency(_max_tokens int)
  RETURNS TABLE (txt            text
               , abs_cnt        bigint
               , relative_share numeric) AS
$func$
BEGIN
   RETURN QUERY
   SELECT t.txt, t.cnt
        , round((t.cnt * 100) / (sum(t.cnt) OVER ()), 2)  -- AS relative_share
   FROM  (
      SELECT t.txt, count(*) AS cnt
      FROM   token t
      WHERE  t.chartype = 'ALPHABETIC'
      GROUP  BY t.txt
      ORDER  BY cnt DESC
      LIMIT  _max_tokens
      ) t
   ORDER  BY t.cnt DESC;
END
$func$  LANGUAGE plpgsql;

The expression sum(t.cnt) OVER () is a window function. You could use a CTE instead of the subquery - pretty, but a subquery is typically cheaper in simple cases like this one.

A final explicit RETURN statement is not required (but allowed) when working with OUT parameters or RETURNS TABLE (which makes implicit use of OUT parameters).

round() with two parameters only works for numeric types. count() in the subquery produces a bigint result and a sum() over this bigint produces a numeric result, thus we deal with a numeric number automatically and everything just falls into place.

Spring Data JPA Update @Query not updating?

I was able to get this to work. I will describe my application and the integration test here.

The Example Application

The example application has two classes and one interface that are relevant to this problem:

  1. The application context configuration class
  2. The entity class
  3. The repository interface

These classes and the repository interface are described in the following.

The source code of the PersistenceContext class looks as follows:

import com.jolbox.bonecp.BoneCPDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.util.Properties;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "net.petrikainulainen.spring.datajpa.todo.repository")
@PropertySource("classpath:application.properties")
public class PersistenceContext {

    protected static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver";
    protected static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";
    protected static final String PROPERTY_NAME_DATABASE_URL = "db.url";
    protected static final String PROPERTY_NAME_DATABASE_USERNAME = "db.username";

    private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
    private static final String PROPERTY_NAME_HIBERNATE_FORMAT_SQL = "hibernate.format_sql";
    private static final String PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO = "hibernate.hbm2ddl.auto";
    private static final String PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY = "hibernate.ejb.naming_strategy";
    private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";

    private static final String PROPERTY_PACKAGES_TO_SCAN = "net.petrikainulainen.spring.datajpa.todo.model";

    @Autowired
    private Environment environment;

    @Bean
    public DataSource dataSource() {
        BoneCPDataSource dataSource = new BoneCPDataSource();

        dataSource.setDriverClass(environment.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
        dataSource.setJdbcUrl(environment.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));
        dataSource.setUsername(environment.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
        dataSource.setPassword(environment.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));

        return dataSource;
    }

    @Bean
    public JpaTransactionManager transactionManager() {
        JpaTransactionManager transactionManager = new JpaTransactionManager();

        transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());

        return transactionManager;
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();

        entityManagerFactoryBean.setDataSource(dataSource());
        entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
        entityManagerFactoryBean.setPackagesToScan(PROPERTY_PACKAGES_TO_SCAN);

        Properties jpaProperties = new Properties();
        jpaProperties.put(PROPERTY_NAME_HIBERNATE_DIALECT, environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
        jpaProperties.put(PROPERTY_NAME_HIBERNATE_FORMAT_SQL, environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_FORMAT_SQL));
        jpaProperties.put(PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO, environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO));
        jpaProperties.put(PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY, environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY));
        jpaProperties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));

        entityManagerFactoryBean.setJpaProperties(jpaProperties);

        return entityManagerFactoryBean;
    }
}

Let's assume that we have a simple entity called Todo which source code looks as follows:

@Entity
@Table(name="todos")
public class Todo {

    public static final int MAX_LENGTH_DESCRIPTION = 500;
    public static final int MAX_LENGTH_TITLE = 100;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(name = "description", nullable = true, length = MAX_LENGTH_DESCRIPTION)
    private String description;

    @Column(name = "title", nullable = false, length = MAX_LENGTH_TITLE)
    private String title;

    @Version
    private long version;
}

Our repository interface has a single method called updateTitle() which updates the title of a todo entry. The source code of the TodoRepository interface looks as follows:

import net.petrikainulainen.spring.datajpa.todo.model.Todo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;

public interface TodoRepository extends JpaRepository<Todo, Long> {

    @Modifying
    @Query("Update Todo t SET t.title=:title WHERE t.id=:id")
    public void updateTitle(@Param("id") Long id, @Param("title") String title);
}

The updateTitle() method is not annotated with the @Transactional annotation because I think that it is best to use a service layer as a transaction boundary.

The Integration Test

The Integration Test uses DbUnit, Spring Test and Spring-Test-DBUnit. It has three components which are relevant to this problem:

  1. The DbUnit dataset which is used to initialize the database into a known state before the test is executed.
  2. The DbUnit dataset which is used to verify that the title of the entity is updated.
  3. The integration test.

These components are described with more details in the following.

The name of the DbUnit dataset file which is used to initialize the database to known state is toDoData.xml and its content looks as follows:

<dataset>
    <todos id="1" description="Lorem ipsum" title="Foo" version="0"/>
    <todos id="2" description="Lorem ipsum" title="Bar" version="0"/>
</dataset>

The name of the DbUnit dataset which is used to verify that the title of the todo entry is updated is called toDoData-update.xml and its content looks as follows (for some reason the version of the todo entry was not updated but the title was. Any ideas why?):

<dataset>
    <todos id="1" description="Lorem ipsum" title="FooBar" version="0"/>
    <todos id="2" description="Lorem ipsum" title="Bar" version="0"/>
</dataset>

The source code of the actual integration test looks as follows (Remember to annotate the test method with the @Transactional annotation):

import com.github.springtestdbunit.DbUnitTestExecutionListener;
import com.github.springtestdbunit.TransactionDbUnitTestExecutionListener;
import com.github.springtestdbunit.annotation.DatabaseSetup;
import com.github.springtestdbunit.annotation.ExpectedDatabase;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import org.springframework.test.context.support.DirtiesContextTestExecutionListener;
import org.springframework.test.context.transaction.TransactionalTestExecutionListener;
import org.springframework.transaction.annotation.Transactional;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {PersistenceContext.class})
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class,
        DirtiesContextTestExecutionListener.class,
        TransactionalTestExecutionListener.class,
        DbUnitTestExecutionListener.class })
@DatabaseSetup("todoData.xml")
public class ITTodoRepositoryTest {

    @Autowired
    private TodoRepository repository;

    @Test
    @Transactional
    @ExpectedDatabase("toDoData-update.xml")
    public void updateTitle_ShouldUpdateTitle() {
        repository.updateTitle(1L, "FooBar");
    }
}

After I run the integration test, the test passes and the title of the todo entry is updated. The only problem which I am having is that the version field is not updated. Any ideas why?

I undestand that this description is a bit vague. If you want to get more information about writing integration tests for Spring Data JPA repositories, you can read my blog post about it.

How do I install g++ on MacOS X?

xcode is now available for free from the app store. Just "buy it" (for free) and it will download. To get the command line tools go into preferences/downloads and "install command line compiler tools".

Instead of gcc you are using clang, but it works the same.

How to get the browser viewport dimensions?

Cross-browser @media (width) and @media (height) values 

const vw = Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0)
const vh = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0)

window.innerWidth and window.innerHeight

  • gets CSS viewport @media (width) and @media (height) which include scrollbars
  • initial-scale and zoom variations may cause mobile values to wrongly scale down to what PPK calls the visual viewport and be smaller than the @media values
  • zoom may cause values to be 1px off due to native rounding
  • undefined in IE8-

document.documentElement.clientWidth and .clientHeight


Resources

How to display images from a folder using php - PHP

Here is a possible solution the solution #3 on my comments to blubill's answer:

yourscript.php
========================
<?php
    $dir = '/home/user/Pictures';
    $file_display = array('jpg', 'jpeg', 'png', 'gif');

    if (file_exists($dir) == false) 
    {
        echo 'Directory "', $dir, '" not found!';
    } 
    else 
    {
        $dir_contents = scandir($dir);

        foreach ($dir_contents as $file) 
        {
            $file_type = strtolower(end(explode('.', $file)));
            if ($file !== '.' && $file !== '..' && in_array($file_type, $file_display) == true)     
            {
                $name = basename($file);
                echo "<img src='img.php?name={$name}' />";
            }
        }
    }
?>


img.php
========================
<?php
    $name = $_GET['name'];
    $mimes = array
    (
        'jpg' => 'image/jpg',
        'jpeg' => 'image/jpg',
        'gif' => 'image/gif',
        'png' => 'image/png'
    );

    $ext = strtolower(end(explode('.', $name)));

    $file = '/home/users/Pictures/'.$name;
    header('content-type: '. $mimes[$ext]);
    header('content-disposition: inline; filename="'.$name.'";');
    readfile($file);
?>

How to check if an object is defined?

If a class type is not defined, you'll get a compiler error if you try to use the class, so in that sense you should have to check.

If you have an instance, and you want to ensure it's not null, simply check for null:

if (value != null)
{
    // it's not null. 
}

Convert stdClass object to array in PHP

You can convert an std object to array like this:

$objectToArray = (array)$object;

Add button to navigationbar programmatically

self.navigationItem.rightBarButtonItem=[[[UIBarButtonItem alloc]initWithTitle:@"Save" style:UIBarButtonItemStylePlain target:self action:@selector(saveAction:)]autorelease];

-(void)saveAction:(UIBarButtonItem *)sender{

//perform your action

}

RandomForestClassfier.fit(): ValueError: could not convert string to float

You have to do some encoding before using fit. As it was told fit() does not accept Strings but you solve this.

There are several classes that can be used :

  • LabelEncoder : turn your string into incremental value
  • OneHotEncoder : use One-of-K algorithm to transform your String into integer

Personally I have post almost the same question on StackOverflow some time ago. I wanted to have a scalable solution but didn't get any answer. I selected OneHotEncoder that binarize all the strings. It is quite effective but if you have a lot different strings the matrix will grow very quickly and memory will be required.

How to open a new window on form submit

I generally use a small jQuery snippet globally to open any external links in a new tab / window. I've added the selector for a form for my own site and it works fine so far:

// URL target
    $('a[href*="//"]:not([href*="'+ location.hostname +'"]),form[action*="//"]:not([href*="'+ location.hostname +'"]').attr('target','_blank');

Nginx 403 forbidden for all files

We had the same issue, using Plesk Onyx 17. Instead of messing up with rights etc., solution was to add nginx user into psacln group, in which all the other domain owners (users) were:

usermod -aG psacln nginx

Now nginx has rights to access .htaccess or any other file necessary to properly show the content.

On the other hand, also make sure that Apache is in psaserv group, to serve static content:

usermod -aG psaserv apache

And don't forget to restart both Apache and Nginx in Plesk after! (and reload pages with Ctrl-F5)

Output array to CSV in Ruby

If you have an array of arrays of data:

rows = [["a1", "a2", "a3"],["b1", "b2", "b3", "b4"], ["c1", "c2", "c3"]]

Then you can write this to a file with the following, which I think is much simpler:

require "csv"
File.write("ss.csv", rows.map(&:to_csv).join)

How to get current memory usage in android?

It depends on your definition of what memory query you wish to get.


Usually, you'd like to know the status of the heap memory, since if it uses too much memory, you get OOM and crash the app.

For this, you can check the next values:

final Runtime runtime = Runtime.getRuntime();
final long usedMemInMB=(runtime.totalMemory() - runtime.freeMemory()) / 1048576L;
final long maxHeapSizeInMB=runtime.maxMemory() / 1048576L;
final long availHeapSizeInMB = maxHeapSizeInMB - usedMemInMB;

The more the "usedMemInMB" variable gets close to "maxHeapSizeInMB", the closer availHeapSizeInMB gets to zero, the closer you get OOM. (Due to memory fragmentation, you may get OOM BEFORE this reaches zero.)

That's also what the DDMS tool of memory usage shows.


Alternatively, there is the real RAM usage, which is how much the entire system uses - see accepted answer to calculate that.


Update: since Android O makes your app also use the native RAM (at least for Bitmaps storage, which is usually the main reason for huge memory usage), and not just the heap, things have changed, and you get less OOM (because the heap doesn't contain bitmaps anymore,check here), but you should still keep an eye on memory use if you suspect you have memory leaks. On Android O, if you have memory leaks that should have caused OOM on older versions, it seems it will just crash without you being able to catch it. Here's how to check for memory usage:

val nativeHeapSize = Debug.getNativeHeapSize()
val nativeHeapFreeSize = Debug.getNativeHeapFreeSize()
val usedMemInBytes = nativeHeapSize - nativeHeapFreeSize
val usedMemInPercentage = usedMemInBytes * 100 / nativeHeapSize

But I believe it might be best to use the profiler of the IDE, which shows the data in real time, using a graph.

So the good news on Android O is that it's much harder to get crashes due to OOM of storing too many large bitmaps, but the bad news is that I don't think it's possible to catch such a case during runtime.


EDIT: seems Debug.getNativeHeapSize() changes over time, as it shows you the total max memory for your app. So those functions are used only for the profiler, to show how much your app is using.

If you want to get the real total and available native RAM , use this:

val memoryInfo = ActivityManager.MemoryInfo()
(getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager).getMemoryInfo(memoryInfo)
val nativeHeapSize = memoryInfo.totalMem
val nativeHeapFreeSize = memoryInfo.availMem
val usedMemInBytes = nativeHeapSize - nativeHeapFreeSize
val usedMemInPercentage = usedMemInBytes * 100 / nativeHeapSize
Log.d("AppLog", "total:${Formatter.formatFileSize(this, nativeHeapSize)} " +
        "free:${Formatter.formatFileSize(this, nativeHeapFreeSize)} " +
        "used:${Formatter.formatFileSize(this, usedMemInBytes)} ($usedMemInPercentage%)")

ReactJS map through Object

I use the below Object.entries to easily output the key and the value:

{Object.entries(someObject).map(([key, val], i) => (
    <p key={i}>
        {key}: {val}
    </p>
))}

Return string without trailing slash

function someFunction(site) {
  if (site.indexOf('/') > 0)
    return site.substring(0, site.indexOf('/'));
  return site;
}

Java String encoding (UTF-8)

This could be complicated way of doing

String newString = new String(oldString);

This shortens the String is the underlying char[] used is much longer.

However more specifically it will be checking that every character can be UTF-8 encoded.

There are some "characters" you can have in a String which cannot be encoded and these would be turned into ?

Any character between \uD800 and \uDFFF cannot be encoded and will be turned into '?'

String oldString = "\uD800";
String newString = new String(oldString.getBytes("UTF-8"), "UTF-8");
System.out.println(newString.equals(oldString));

prints

false

Pipe output and capture exit status in Bash

So I wanted to contribute an answer like lesmana's, but I think mine is perhaps a little simpler and slightly more advantageous pure-Bourne-shell solution:

# You want to pipe command1 through command2:
exec 4>&1
exitstatus=`{ { command1; printf $? 1>&3; } | command2 1>&4; } 3>&1`
# $exitstatus now has command1's exit status.

I think this is best explained from the inside out - command1 will execute and print its regular output on stdout (file descriptor 1), then once it's done, printf will execute and print icommand1's exit code on its stdout, but that stdout is redirected to file descriptor 3.

While command1 is running, its stdout is being piped to command2 (printf's output never makes it to command2 because we send it to file descriptor 3 instead of 1, which is what the pipe reads). Then we redirect command2's output to file descriptor 4, so that it also stays out of file descriptor 1 - because we want file descriptor 1 free for a little bit later, because we will bring the printf output on file descriptor 3 back down into file descriptor 1 - because that's what the command substitution (the backticks), will capture and that's what will get placed into the variable.

The final bit of magic is that first exec 4>&1 we did as a separate command - it opens file descriptor 4 as a copy of the external shell's stdout. Command substitution will capture whatever is written on standard out from the perspective of the commands inside it - but since command2's output is going to file descriptor 4 as far as the command substitution is concerned, the command substitution doesn't capture it - however once it gets "out" of the command substitution it is effectively still going to the script's overall file descriptor 1.

(The exec 4>&1 has to be a separate command because many common shells don't like it when you try to write to a file descriptor inside a command substitution, that is opened in the "external" command that is using the substitution. So this is the simplest portable way to do it.)

You can look at it in a less technical and more playful way, as if the outputs of the commands are leapfrogging each other: command1 pipes to command2, then the printf's output jumps over command 2 so that command2 doesn't catch it, and then command 2's output jumps over and out of the command substitution just as printf lands just in time to get captured by the substitution so that it ends up in the variable, and command2's output goes on its merry way being written to the standard output, just as in a normal pipe.

Also, as I understand it, $? will still contain the return code of the second command in the pipe, because variable assignments, command substitutions, and compound commands are all effectively transparent to the return code of the command inside them, so the return status of command2 should get propagated out - this, and not having to define an additional function, is why I think this might be a somewhat better solution than the one proposed by lesmana.

Per the caveats lesmana mentions, it's possible that command1 will at some point end up using file descriptors 3 or 4, so to be more robust, you would do:

exec 4>&1
exitstatus=`{ { command1 3>&-; printf $? 1>&3; } 4>&- | command2 1>&4; } 3>&1`
exec 4>&-

Note that I use compound commands in my example, but subshells (using ( ) instead of { } will also work, though may perhaps be less efficient.)

Commands inherit file descriptors from the process that launches them, so the entire second line will inherit file descriptor four, and the compound command followed by 3>&1 will inherit the file descriptor three. So the 4>&- makes sure that the inner compound command will not inherit file descriptor four, and the 3>&- will not inherit file descriptor three, so command1 gets a 'cleaner', more standard environment. You could also move the inner 4>&- next to the 3>&-, but I figure why not just limit its scope as much as possible.

I'm not sure how often things use file descriptor three and four directly - I think most of the time programs use syscalls that return not-used-at-the-moment file descriptors, but sometimes code writes to file descriptor 3 directly, I guess (I could imagine a program checking a file descriptor to see if it's open, and using it if it is, or behaving differently accordingly if it's not). So the latter is probably best to keep in mind and use for general-purpose cases.

Call Python function from MATLAB

As @dgorissen said, Jython is the easiest solution.

Just install Jython from the homepage.

Then:

javaaddpath('/path-to-your-jython-installation/jython.jar')

import org.python.util.PythonInterpreter;

python = PythonInterpreter; %# takes a long time to load!
python.exec('import some_module');
python.exec('result = some_module.run_something()');
result = python.get('result');

See the documentation for some examples.

Beware: I never actually worked with Jython and it seems that the standard library one may know from CPython is not fully implemented in Jython!

Small examples I tested worked just fine, but you may find that you have to prepend your Python code directory to sys.path.

Cannot use special principal dbo: Error 15405

This answer doesn't help for SQL databases where SharePoint is connected. db_securityadmin is required for the configuration databases. In order to add db_securityadmin, you will need to change the owner of the database to an administrative account. You can use that account just for dbo roles.

PHP combine two associative arrays into one array

There is also array_replace, where an original array is modified by other arrays preserving the key => value association without creating duplicate keys.

  • Same keys on other arrays will cause values to overwrite the original array
  • New keys on other arrays will be created on the original array

Why is my JavaScript function sometimes "not defined"?

My guess is, somehow the document is not fully loaded by the time the method is called. Have your code executing after the document is ready event.

mysql_fetch_array() expects parameter 1 to be resource problem

$id = intval($_GET['id']);
$sql = "SELECT * FROM student WHERE IDNO=$id";
$result = mysql_query($sql) or trigger_error(mysql_error().$sql);

always do it this way and it will tell you what is wrong

JSON datetime between Python and JavaScript

If you're certain that only Javascript will be consuming the JSON, I prefer to pass Javascript Date objects directly.

The ctime() method on datetime objects will return a string that the Javascript Date object can understand.

import datetime
date = datetime.datetime.today()
json = '{"mydate":new Date("%s")}' % date.ctime()

Javascript will happily use that as an object literal, and you've got your Date object built right in.

How to compare 2 dataTables

Well if you are using a DataTable at all then rather than comparing two 'DataTables' could you just compare the DataTable that is going to have changes with the original data when it was loaded AKA DataTable.GetChanges Method (DataRowState)

How to copy an object by value, not by reference

You may use clone() which works well if your object has immutable objects and/or primitives, but it may be a little problematic when you don't have these ( such as collections ) for which you may need to perform a deep clone.

User userCopy = (User) user.clone();//make a copy

for(...) {
    user.age = 1;
    user.id = -1;

    UserDao.update(user)
    user = userCopy; 
}

It seems like you just want to preserve the attributes: age and id which are of type int so, why don't you give it a try and see if it works.

For more complex scenarios you could create a "copy" method:

publc class User { 
    public static User copy( User other ) {
         User newUser = new User();
         newUser.age = other.age;
         newUser.id = other.id;
         //... etc. 
         return newUser;
    }
}

It should take you about 10 minutes.

And then you can use that instead:

     User userCopy = User.copy( user ); //make a copy
     // etc. 

To read more about clone read this chapter in Joshua Bloch "Effective Java: Override clone judiciously"

Multiple aggregations of the same column using pandas GroupBy.agg()

Would something like this work:

In [7]: df.groupby('dummy').returns.agg({'func1' : lambda x: x.sum(), 'func2' : lambda x: x.prod()})
Out[7]: 
              func2     func1
dummy                        
1     -4.263768e-16 -0.188565

When would you use the different git merge strategies?

As the answers above are not showing all strategy details. For example, some answer is missing the details about the import resolve option and the recursive which has many sub options as ours, theirs, patience, renormalize, etc.

Therefore, I would recommend to visit the official git documentation which explains all the possible features features:

https://git-scm.com/docs/merge-strategies

How do I set up DNS for an apex domain (no www) pointing to a Heroku app?

To point your apex/root/naked domain at a Heroku-hosted application, you'll need to use a DNS provider who supports CNAME-like records (often referred to as ALIAS or ANAME records). Currently Heroku recommends:

Whichever of those you choose, your record will look like the following:

Record: ALIAS or ANAME

Name: empty or @

Target: example.com.herokudns.com.

That's all you need.


However, it's not good for SEO to have both the www version and non-www version resolve. One should point to the other as the canonical URL. How you decide to do that depends on if you're using HTTPS or not. And if you're not, you probably should be as Heroku now handles SSL certificates for you automatically and for free for all applications running on paid dynos.

If you're not using HTTPS, you can just set up a 301 Redirect record with most DNS providers pointing name www to http://example.com.

If you are using HTTPS, you'll most likely need to handle the redirection at the application level. If you want to know why, check out these short and long explanations but basically since your DNS provider or other URL forwarding service doesn't have, and shouldn't have, your SSL certificate and private key, they can't respond to HTTPS requests for your domain.

To handle the redirects at the application level, you'll need to:

  • Add both your apex and www host names to the Heroku application (heroku domains:add example.com and heroku domains:add www.example.com)
  • Set up your SSL certificates
  • Point your apex domain record at Heroku using an ALIAS or ANAME record as described above
  • Add a CNAME record with name www pointing to www.example.com.herokudns.com.
  • And then in your application, 301 redirect any www requests to the non-www URL (here's an example of how to do it in Django)
  • Also in your application, you should probably redirect any HTTP requests to HTTPS (for example, in Django set SECURE_SSL_REDIRECT to True)

Check out this post from DNSimple for more.

How to find files that match a wildcard string in Java?

The wildcard library efficiently does both glob and regex filename matching:

http://code.google.com/p/wildcard/

The implementation is succinct -- JAR is only 12.9 kilobytes.

How do I use PHP namespaces with autoload?

I recently found tanerkuc's answer very helpful! Just wanted to add that using strrpos() + substr() is slightly faster than explode() + end():

spl_autoload_register( function( $class ) {
    $pos = strrpos( $class, '\\' );
    include ( $pos === false ? $class : substr( $class, $pos + 1 ) ).'.php';
});

Html helper for <input type="file" />

You can also use:

@using (Html.BeginForm("Upload", "File", FormMethod.Post, new { enctype = "multipart/form-data" }))
{ 
    <p>
        <input type="file" id="fileUpload" name="fileUpload" size="23" />
    </p>
    <p>
        <input type="submit" value="Upload file" /></p> 
}

docker run <IMAGE> <MULTIPLE COMMANDS>

You can do this a couple of ways:

  1. Use the -w option to change the working directory:

    -w, --workdir="" Working directory inside the container

    https://docs.docker.com/engine/reference/commandline/run/#set-working-directory--w

  2. Pass the entire argument to /bin/bash:

    docker run image /bin/bash -c "cd /path/to/somewhere; python a.py"
    

How can I regenerate ios folder in React Native project?

  1. Open Terminal/cmd
  2. Move to the folder/directory where the project "ProjectName" folder exist(Do not go into project directory)
  3. run command as: react-native init "ProjectName" and it will warn that project directory already exist but you continue.
  4. It will install all updated node modules as well as missing platform (android/ios) folders inside project without disturbing the code already written.
  5. cd "ProjectName" and then cd ios and then run pod install

PS: Take backup of your code in case it changes App.js

PowerShell script to return versions of .NET Framework on a machine?

Not pretty. Definitely not pretty:

ls $Env:windir\Microsoft.NET\Framework | ? { $_.PSIsContainer } | select -exp Name -l 1

This may or may not work. But as far as the latest version is concerned this should be pretty reliable, as there are essentially empty folders for old versions (1.0, 1.1) but not newer ones – those only appear once the appropriate framework is installed.

Still, I suspect there must be a better way.

jQuery Scroll to bottom of page/iframe

A simple function that jumps (instantly scrolls) to the bottom of the whole page. It uses the built-in .scrollTop(). I haven’t tried to adapt this to work with individual page elements.

function jumpToPageBottom() {
    $('html, body').scrollTop( $(document).height() - $(window).height() );
}

When to use reinterpret_cast?

The C++ standard guarantees the following:

static_casting a pointer to and from void* preserves the address. That is, in the following, a, b and c all point to the same address:

int* a = new int();
void* b = static_cast<void*>(a);
int* c = static_cast<int*>(b);

reinterpret_cast only guarantees that if you cast a pointer to a different type, and then reinterpret_cast it back to the original type, you get the original value. So in the following:

int* a = new int();
void* b = reinterpret_cast<void*>(a);
int* c = reinterpret_cast<int*>(b);

a and c contain the same value, but the value of b is unspecified. (in practice it will typically contain the same address as a and c, but that's not specified in the standard, and it may not be true on machines with more complex memory systems.)

For casting to and from void*, static_cast should be preferred.

Return array in a function

and what about:

int (*func())
{
    int *f = new int[10] {1,2,3};

    return f;
}

int fa[10] = { 0 };
auto func2() -> int (*) [10]
{
    return &fa;
}

Sending simple message body + file attachment using Linux Mailx

Try this it works for me:

(echo "Hello XYX" ; uuencode /export/home/TOTAL_SI_COUNT_10042016.csv TOTAL_SI_COUNT_10042016.csv ) | mailx -s 'Script test' [email protected]

Localhost not working in chrome and firefox

For all browsers,

  • Open internet Options (or Internet properties)
  • Go to connections tab
  • Click on LAN Settings
  • Tick Use proxy server for your LAN
  • Tick Bypass proxy server for your local address (Don't change the port number)
  • Click on Ok

Now you are good to go. :)

Programmatically close aspx page from code behind

You can just simply use this.. short and easy.

Response.Write("<script>window.close();</script>");

Hope this helps.

How to create roles in ASP.NET Core and assign them to users?

In addition to Temi Lajumoke's answer, it's worth noting that after creating the required roles and assigning them to specific users in ASP.NET Core 2.1 MVC Web Application, after launching the application, you may encounter a method error, such as registering or managing an account:

InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Identity.UI.Services.IEmailSender' while attempting to activate 'WebApplication.Areas.Identity.Pages.Account.Manage.IndexModel'.

A similar error can be quickly corrected in the ConfigureServices method by adding the AddDefaultUI() method:

services.AddIdentity<IdentityUser, IdentityRole>()
//services.AddDefaultIdentity<IdentityUser>()
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultUI()
    .AddDefaultTokenProviders();

Check

 https://blogs.msdn.microsoft.com/webdev/2018/03/02/aspnetcore-2-1-identity-ui/

and related topic on github:

 https://github.com/aspnet/Docs/issues/6784 for more information.

And for assigning role to specific user could be used IdentityUser class instead of ApplicationUser.

Rename a file using Java

Try This

File file=new File("Your File");
boolean renameResult = file.renameTo(new File("New Name"));
// todo: check renameResult

Note : We should always check the renameTo return value to make sure rename file is successful because it’s platform dependent(different Operating system, different file system) and it doesn’t throw IO exception if rename fails.

Where does VBA Debug.Print log to?

Where do you want to see the output?

Messages being output via Debug.Print will be displayed in the immediate window which you can open by pressing Ctrl+G.

You can also Activate the so called Immediate Window by clicking View -> Immediate Window on the VBE toolbar

enter image description here

CSS ''background-color" attribute not working on checkbox inside <div>

The Best solution to change background checkbox color

_x000D_
_x000D_
input[type=checkbox] {_x000D_
    margin-right: 5px;_x000D_
    cursor: pointer;_x000D_
    font-size: 14px;_x000D_
    width: 15px;_x000D_
    height: 12px;_x000D_
    position: relative;_x000D_
  }_x000D_
  _x000D_
  input[type=checkbox]:after {_x000D_
    position: absolute;_x000D_
    width: 10px;_x000D_
    height: 15px;_x000D_
    top: 0;_x000D_
    content: " ";_x000D_
    background-color: #ff0000;_x000D_
    color: #fff;_x000D_
    display: inline-block;_x000D_
    visibility: visible;_x000D_
    padding: 0px 3px;_x000D_
    border-radius: 3px;_x000D_
  }_x000D_
  _x000D_
  input[type=checkbox]:checked:after {_x000D_
   content: "?";_x000D_
   font-size: 12px;_x000D_
  }
_x000D_
  <input type="checkbox" name="vehicle" value="Bike"> I have a bike<br>_x000D_
  <input type="checkbox" name="vehicle" value="Car" checked> I have a car<br>_x000D_
_x000D_
  <input type="checkbox" name="vehicle" value="Car" checked> I have a bus<br>
_x000D_
_x000D_
_x000D_

Checking for #N/A in Excel cell from VBA code

First check for an error (N/A value) and then try the comparisation against cvErr(). You are comparing two different things, a value and an error. This may work, but not always. Simply casting the expression to an error may result in similar problems because it is not a real error only the value of an error which depends on the expression.

If IsError(ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value) Then
  If (ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value <> CVErr(xlErrNA)) Then
    'do something
  End If
End If

differences between using wmode="transparent", "opaque", or "window" for an embedded object on a webpage

One bizarre thing is that in Chrome + Firefox, the MOUSE_LEAVE event isn't dispatched for OPAQUE and TRANSPARENT.

With WINDOW it works fine. That one took some time to find out! grr...

(note: jediericb mentioned this bug - which is similar but doesn't mention MOUSE_LEAVE)

Disable building workspace process in Eclipse

if needed programmatic from a PDE or JDT code:

public static void setWorkspaceAutoBuild(boolean flag) throws CoreException 
{
IWorkspace workspace = ResourcesPlugin.getWorkspace();
final IWorkspaceDescription description = workspace.getDescription();
description.setAutoBuilding(flag);
workspace.setDescription(description);
}

Communication between multiple docker-compose projects

Another option is just running up the first module with the 'docker-compose' check the ip related with the module, and connect the second module with the previous net like external, and pointing the internal ip

example app1 - new-network created in the service lines, mark as external: true at the bottom app2 - indicate the "new-network" created by app1 when goes up, mark as external: true at the bottom, and set in the config to connect, the ip that app1 have in this net.

With this, you should be able to talk with each other

*this way is just for local-test focus, in order to don't do an over complex configuration ** I know is very 'patch way' but works for me and I think is so simple some other can take advantage of this

Define global variable with webpack

I solved this issue by setting the global variables as a static properties on the classes to which they are most relevant. In ES5 it looks like this:

var Foo = function(){...};
Foo.globalVar = {};

How do I check in python if an element of a list is empty?

Just check if that element is equal to None type or make use of NOT operator ,which is equivalent to the NULL type you observe in other languages.

if not A[i]:
    ## do whatever

Anyway if you know the size of your list then you don't need to do all this.

Android Fragment onClick button Method

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.writeqrcode_main, container, false);
    // Inflate the layout for this fragment

    txt_name = (TextView) view.findViewById(R.id.name);
    txt_usranme = (TextView) view.findViewById(R.id.surname);
    txt_number = (TextView) view.findViewById(R.id.number);
    txt_province = (TextView) view.findViewById(R.id.province);
    txt_write = (EditText) view.findViewById(R.id.editText_write);
    txt_show1 = (Button) view.findViewById(R.id.buttonShow1);

    txt_show1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.e("Onclick","Onclick");

            txt_show1.setVisibility(View.INVISIBLE);
            txt_name.setVisibility(View.VISIBLE);
            txt_usranme.setVisibility(View.VISIBLE);
            txt_number.setVisibility(View.VISIBLE);
            txt_province.setVisibility(View.VISIBLE);
        }
    });
    return view;
}

You OK !!!!

How to send a stacktrace to log4j?

This answer may be not related to the question asked but related to title of the question.

public class ThrowableTest {

    public static void main(String[] args) {

        Throwable createdBy = new Throwable("Created at main()");
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        PrintWriter pw = new PrintWriter(os);
        createdBy.printStackTrace(pw);
        try {
            pw.close();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        logger.debug(os.toString());
    }
}

OR

public static String getStackTrace (Throwable t)
{
    StringWriter stringWriter = new StringWriter();
    PrintWriter  printWriter  = new PrintWriter(stringWriter);
    t.printStackTrace(printWriter);
    printWriter.close();    //surprise no IO exception here
    try {
        stringWriter.close();
    }
    catch (IOException e) {
    }
    return stringWriter.toString();
}

OR

StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
for(StackTraceElement stackTrace: stackTraceElements){
    logger.debug(stackTrace.getClassName()+ "  "+ stackTrace.getMethodName()+" "+stackTrace.getLineNumber());
}

How to use jQuery to show/hide divs based on radio button selection?

Just hide them before showing them:

$(document).ready(function(){ 
    $("input[name$='group2']").click(function() {
        var test = $(this).val();
        $("div.desc").hide();
        $("#"+test).show();
    }); 
});

std::cin input with spaces?

You have to use cin.getline():

char input[100];
cin.getline(input,sizeof(input));

How to Generate Barcode using PHP and Display it as an Image on the same page

There is a library for this BarCode PHP. You just need to include a few files:

require_once('class/BCGFontFile.php');
require_once('class/BCGColor.php');
require_once('class/BCGDrawing.php');

You can generate many types of barcodes, namely 1D or 2D. Add the required library:

require_once('class/BCGcode39.barcode.php');

Generate the colours:

// The arguments are R, G, and B for color.
$colorFront = new BCGColor(0, 0, 0);
$colorBack = new BCGColor(255, 255, 255);

After you have added all the codes, you will get this way:

Example

Since several have asked for an example here is what I was able to do to get it done

require_once('class/BCGFontFile.php');
require_once('class/BCGColor.php');
require_once('class/BCGDrawing.php');

require_once('class/BCGcode128.barcode.php');

header('Content-Type: image/png');

$color_white = new BCGColor(255, 255, 255);

$code = new BCGcode128();
$code->parse('HELLO');

$drawing = new BCGDrawing('', $color_white);
$drawing->setBarcode($code);

$drawing->draw();
$drawing->finish(BCGDrawing::IMG_FORMAT_PNG);

If you want to actually create the image file so you can save it then change

$drawing = new BCGDrawing('', $color_white);

to

$drawing = new BCGDrawing('image.png', $color_white);

jquery clear input default value

$('.input').on('focus', function(){
    $(this).val('');
});

$('[type="submit"]').on('click', function(){
    $('.input').val('');
});

writing to existing workbook using xlwt

You need xlutils.copy. Try something like this:

from xlutils.copy import copy
w = copy('book1.xls')
w.get_sheet(0).write(0,0,"foo")
w.save('book2.xls')

Keep in mind you can't overwrite cells by default as noted in this question.

Easiest way to mask characters in HTML(5) text input

A little late, but a useful plugin that will actually use a mask to give a bit more restriction on user input.

<div class="col-sm-3 col-md-6 col-lg-4">
  <div class="form-group">
     <label for="addPhone">Phone Number *</label>
      <input id="addPhone" name="addPhone" type="text" class="form-control 
       required" data-mask="(999) 999-9999"placeholder>
    <span class="help-block">(999) 999-9999</span>
  </div>
</div>

 <!-- Input Mask -->
 <script src="js/plugins/jasny/jasny-bootstrap.min.js"></script>

enter image description here

More info on the plugin https://www.jasny.net/bootstrap/2.3.1/javascript.html#inputmask

How do you test that a Python function throws an exception?

The code in my previous answer can be simplified to:

def test_afunction_throws_exception(self):
    self.assertRaises(ExpectedException, afunction)

And if afunction takes arguments, just pass them into assertRaises like this:

def test_afunction_throws_exception(self):
    self.assertRaises(ExpectedException, afunction, arg1, arg2)

JDBC ODBC Driver Connection

Didn't work with ODBC-Bridge for me too. I got the way around to initialize ODBC connection using ODBC driver.

 import java.sql.*;  
 public class UserLogin
 {
     public static void main(String[] args)
     {
        try
        {    
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

            // C:\\databaseFileName.accdb" - location of your database 
           String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "C:\\emp.accdb";

            // specify url, username, pasword - make sure these are valid 
            Connection conn = DriverManager.getConnection(url, "username", "password");

            System.out.println("Connection Succesfull");
         } 
         catch (Exception e) 
         {
            System.err.println("Got an exception! ");
            System.err.println(e.getMessage());

          }
      }
  }

How to set text color in submit button?

_x000D_
_x000D_
.button_x000D_
{_x000D_
    font-size: 13px;_x000D_
    color:green;_x000D_
}
_x000D_
<input type="submit" value="Fetch" class="button"/>
_x000D_
_x000D_
_x000D_

Can I concatenate multiple MySQL rows into one field?

For somebody looking here how to use GROUP_CONCAT with subquery - posting this example

SELECT i.*,
(SELECT GROUP_CONCAT(userid) FROM favourites f WHERE f.itemid = i.id) AS idlist
FROM items i
WHERE i.id = $someid

So GROUP_CONCAT must be used inside the subquery, not wrapping it.

How does "304 Not Modified" work exactly?

When the browser puts something in its cache, it also stores the Last-Modified or ETag header from the server.

The browser then sends a request with the If-Modified-Since or If-None-Match header, telling the server to send a 304 if the content still has that date or ETag.

The server needs some way of calculating a date-modified or ETag for each version of each resource; this typically comes from the filesystem or a separate database column.

Recommended SQL database design for tags or tagging

Use a single formatted text column[1] for storing the tags and use a capable full text search engine to index this. Else you will run into scaling problems when trying to implement boolean queries.

If you need details about the tags you have, you can either keep track of it in a incrementally maintained table or run a batch job to extract the information.

[1] Some RDBMS even provide a native array type which might be even better suited for storage by not needing a parsing step, but might cause problems with the full text search.

How do I use boolean variables in Perl?

I came across a tutorial which have a well explaination about What values are true and false in Perl. It state that:

Following scalar values are considered false:

  • undef - the undefined value
  • 0 the number 0, even if you write it as 000 or 0.0
  • '' the empty string.
  • '0' the string that contains a single 0 digit.

All other scalar values, including the following are true:

  • 1 any non-0 number
  • ' ' the string with a space in it
  • '00' two or more 0 characters in a string
  • "0\n" a 0 followed by a newline
  • 'true'
  • 'false' yes, even the string 'false' evaluates to true.

There is another good tutorial which explain about Perl true and false.

Convert all data frame character columns to factors

Roland's answer is great for this specific problem, but I thought I would share a more generalized approach.

DF <- data.frame(x = letters[1:5], y = 1:5, z = LETTERS[1:5], 
                 stringsAsFactors=FALSE)
str(DF)
# 'data.frame':  5 obs. of  3 variables:
#  $ x: chr  "a" "b" "c" "d" ...
#  $ y: int  1 2 3 4 5
#  $ z: chr  "A" "B" "C" "D" ...

## The conversion
DF[sapply(DF, is.character)] <- lapply(DF[sapply(DF, is.character)], 
                                       as.factor)
str(DF)
# 'data.frame':  5 obs. of  3 variables:
#  $ x: Factor w/ 5 levels "a","b","c","d",..: 1 2 3 4 5
#  $ y: int  1 2 3 4 5
#  $ z: Factor w/ 5 levels "A","B","C","D",..: 1 2 3 4 5

For the conversion, the left hand side of the assign (DF[sapply(DF, is.character)]) subsets the columns that are character. In the right hand side, for that subset, you use lapply to perform whatever conversion you need to do. R is smart enough to replace the original columns with the results.

The handy thing about this is if you wanted to go the other way or do other conversions, it's as simple as changing what you're looking for on the left and specifying what you want to change it to on the right.

Set new id with jQuery

Did you try

$(this).val('test');

instead of

$(this).attr('value', 'test');

val() is generally easier, since the attribute you need to change may be different on different DOM elements.

Fixing Sublime Text 2 line endings?

to chnage line endings from LF to CRLF:

open Sublime and follow the steps:-

1 press Ctrl+shift+p then install package name line unify endings

then again press Ctrl+shift+p

2 in the blank input box type "Line unify ending "

3 Hit enter twice

Sublime may freeze for sometimes and as a result will change the line endings from LF to CRLF

phpmyadmin #1045 Cannot log in to the MySQL server. after installing mysql command line client

I would suggest 3 things:

  1. First try clearing browser's cache
  2. Try to assign username & password statically into config.inc.php
  3. Once you've done with installation, delete the config.inc.php file under "phpmyadmin" folder

The last one worked for me.

How to set the color of "placeholder" text?

For giving placeholder a color just use these lines of code:

::-webkit-input-placeholder { color: red; }
::-moz-placeholder {color: red; }
:-ms-input-placeholder { color: red; } 
:-o-input-placeholder { color: red; } 

How do I save and restore multiple variables in python?

The following approach seems simple and can be used with variables of different size:

import hickle as hkl
# write variables to filename [a,b,c can be of any size]
hkl.dump([a,b,c], filename)

# load variables from filename
a,b,c = hkl.load(filename)

Which keycode for escape key with jQuery

Your best bet is

$(document).keyup(function(e) { 
    if (e.which === 13) $('.save').click();   // enter 
    if (e.which === 27) $('.cancel').click(); // esc   

    /* OPTIONAL: Only if you want other elements to ignore event */
    e.preventDefault();
    e.stopPropagation();
});

Summary

  • which is more preferable than keyCode because it is normalized
  • keyup is more preferable than keydown because keydown may occur multiple times if user keeps it pressed.
  • Do not use keypress unless you want to capture actual characters.

Interestingly Bootstrap uses keydown and keyCode in its dropdown component (as of 3.0.2)! I think it's probably poor choice there.

Related snippet from JQuery doc

While browsers use differing properties to store this information, jQuery normalizes the .which property so you can reliably use it to retrieve the key code. This code corresponds to a key on the keyboard, including codes for special keys such as arrows. For catching actual text entry, .keypress() may be a better choice.

Other item of interest: JavaScript Keypress Library

Have log4net use application config file for configuration data

From the config shown in the question there is but one appender configured and it is named "EventLogAppender". But in the config for root, the author references an appender named "ConsoleAppender", hence the error message.

How can I validate a string to only allow alphanumeric characters in it?

Based on cletus's answer you may create new extension.

public static class StringExtensions
{        
    public static bool IsAlphaNumeric(this string str)
    {
        if (string.IsNullOrEmpty(str))
            return false;

        Regex r = new Regex("^[a-zA-Z0-9]*$");
        return r.IsMatch(str);
    }
}

Google Maps V3 marker with label

I doubt the standard library supports this.

But you can use the google maps utility library:

http://code.google.com/p/google-maps-utility-library-v3/wiki/Libraries#MarkerWithLabel

var myLatlng = new google.maps.LatLng(-25.363882,131.044922);

var myOptions = {
    zoom: 8,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };

map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);

var marker = new MarkerWithLabel({
   position: myLatlng,
   map: map,
   draggable: true,
   raiseOnDrag: true,
   labelContent: "A",
   labelAnchor: new google.maps.Point(3, 30),
   labelClass: "labels", // the CSS class for the label
   labelInBackground: false
 });

The basics about marker can be found here: https://developers.google.com/maps/documentation/javascript/overlays#Markers

Inserting NOW() into Database with CodeIgniter's Active Record

aspirinemaga, just replace:

$this->db->set('time', 'NOW()', FALSE);
$this->db->insert('mytable', $data);

for it:

$this->db->set('time', 'NOW() + INTERVAL 1 DAY', FALSE);
$this->db->insert('mytable', $data);

What does "<html xmlns="http://www.w3.org/1999/xhtml">" do?

It sounds like your site has CSS or JS that depends on running in quirks mode. Which is why you need garbage above your doctype to render "correctly". I suggest removing said garbage and then fixing your CSS+JS to actually work in standards mode; you'll save yourself a lot of pain in the long run.

tell pip to install the dependencies of packages listed in a requirement file

Any way to do this without manually re-installing the packages in a new virtualenv to get their dependencies ? This would be error-prone and I'd like to automate the process of cleaning the virtualenv from no-longer-needed old dependencies.

That's what pip-tools package is for (from https://github.com/jazzband/pip-tools):

Installation

$ pip install --upgrade pip  # pip-tools needs pip==6.1 or higher (!)
$ pip install pip-tools

Example usage for pip-compile

Suppose you have a Flask project, and want to pin it for production. Write the following line to a file:

# requirements.in
Flask

Now, run pip-compile requirements.in:

$ pip-compile requirements.in
#
# This file is autogenerated by pip-compile
# Make changes in requirements.in, then run this to update:
#
#    pip-compile requirements.in
#
flask==0.10.1
itsdangerous==0.24        # via flask
jinja2==2.7.3             # via flask
markupsafe==0.23          # via jinja2
werkzeug==0.10.4          # via flask

And it will produce your requirements.txt, with all the Flask dependencies (and all underlying dependencies) pinned. Put this file under version control as well and periodically re-run pip-compile to update the packages.

Example usage for pip-sync

Now that you have a requirements.txt, you can use pip-sync to update your virtual env to reflect exactly what's in there. Note: this will install/upgrade/uninstall everything necessary to match the requirements.txt contents.

$ pip-sync
Uninstalling flake8-2.4.1:
  Successfully uninstalled flake8-2.4.1
Collecting click==4.1
  Downloading click-4.1-py2.py3-none-any.whl (62kB)
    100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 65kB 1.8MB/s
  Found existing installation: click 4.0
    Uninstalling click-4.0:
      Successfully uninstalled click-4.0
Successfully installed click-4.1

What is monkey patching?

A MonkeyPatch is a piece of Python code which extends or modifies other code at runtime (typically at startup).

A simple example looks like this:

from SomeOtherProduct.SomeModule import SomeClass

def speak(self):
    return "ook ook eee eee eee!"

SomeClass.speak = speak

Source: MonkeyPatch page on Zope wiki.

How to properly reference local resources in HTML?

  • A leading slash tells the browser to start at the root directory.
  • If you don't have the leading slash, you're referencing from the current directory.
  • If you add two dots before the leading slash, it means you're referencing the parent of the current directory.

Take the following folder structure

demo folder structure

notice:

  • the ROOT checkmark is green,
  • the second checkmark is orange,
  • the third checkmark is purple,
  • the forth checkmark is yellow

Now in the index.html.en file you'll want to put the following markup

<p>
    <span>src="check_mark.png"</span>
    <img src="check_mark.png" />
    <span>I'm purple because I'm referenced from this current directory</span>
</p>

<p>
    <span>src="/check_mark.png"</span>
    <img src="/check_mark.png" />
    <span>I'm green because I'm referenced from the ROOT directory</span>
</p>

<p>
    <span>src="subfolder/check_mark.png"</span>
    <img src="subfolder/check_mark.png" />
    <span>I'm yellow because I'm referenced from the child of this current directory</span>
</p>

<p>
    <span>src="/subfolder/check_mark.png"</span>
    <img src="/subfolder/check_mark.png" />
    <span>I'm orange because I'm referenced from the child of the ROOT directory</span>
</p>

<p>
    <span>src="../subfolder/check_mark.png"</span>
    <img src="../subfolder/check_mark.png" />
    <span>I'm purple because I'm referenced from the parent of this current directory</span>
</p>

<p>
    <span>src="subfolder/subfolder/check_mark.png"</span>
    <img src="subfolder/subfolder/check_mark.png" />
    <span>I'm [broken] because there is no subfolder two children down from this current directory</span>
</p>

<p>
    <span>src="/subfolder/subfolder/check_mark.png"</span>
    <img src="/subfolder/subfolder/check_mark.png" />
    <span>I'm purple because I'm referenced two children down from the ROOT directory</span>
</p>

Now if you load up the index.html.en file located in the second subfolder
http://example.com/subfolder/subfolder/

This will be your output

enter image description here

Set width of a "Position: fixed" div relative to parent div

Here is a little hack that we ran across while fixing some redraw issues on a large app.

Use -webkit-transform: translateZ(0); on the parent. Of course this is specific to Chrome.

http://jsfiddle.net/senica/bCQEa/

-webkit-transform: translateZ(0);

How to dynamically build a JSON object with Python?

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

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

from string

import json
from types import SimpleNamespace

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

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

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

output:

3
1
2

from file:

JSON object: data.json

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

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

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

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

output:

3
1
2

from requests

import json
from types import SimpleNamespace
import requests

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

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

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

output:

Milovan Tomaševic
NLB
milovantomasevic.com

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

Implement paging (skip / take) functionality with this query

In order to do this in SQL Server, you must order the query by a column, so you can specify the rows you want.

Example:

select * from table order by [some_column] 
offset 10 rows
FETCH NEXT 10 rows only

And you can't use the "TOP" keyword when doing this.

You can learn more here: https://technet.microsoft.com/pt-br/library/gg699618%28v=sql.110%29.aspx

Null check in VB

Change your Ands to AndAlsos

A standard And will test both expressions. If comp.Container is Nothing, then the second expression will raise a NullReferenceException because you're accessing a property on a null object.

AndAlso will short-circuit the logical evaluation. If comp.Container is Nothing, then the 2nd expression will not be evaluated.

When should an Excel VBA variable be killed or set to Nothing?

I have at least one situation where the data is not automatically cleaned up, which would eventually lead to "Out of Memory" errors. In a UserForm I had:

Public mainPicture As StdPicture
...
mainPicture = LoadPicture(PAGE_FILE)

When UserForm was destroyed (after Unload Me) the memory allocated for the data loaded in the mainPicture was not being de-allocated. I had to add an explicit

mainPicture = Nothing

in the terminate event.

Create folder in Android

Add this permission in Manifest,
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

File folder = new File(Environment.getExternalStorageDirectory() + 
                             File.separator + "TollCulator");
boolean success = true;
if (!folder.exists()) {
    success = folder.mkdirs();
}
if (success) {
    // Do something on success
} else {
    // Do something else on failure 
}

when u run the application go too DDMS->File Explorer->mnt folder->sdcard folder->toll-creation folder

Difference between hamiltonian path and euler path

Euler Path - An Euler path is a path in which each edge is traversed exactly once.

Hamiltonian Path - An Hamiltonian path is path in which each vertex is traversed exactly once.

If you have ever confusion remember E - Euler E - Edge.

Change variable name in for loop using R

You could use assign, but using assign (or get) is often a symptom of a programming structure that is not very R like. Typically, lists or matrices allow cleaner solutions.

  • with a list:

    A <- lapply (1 : 10, function (x) d + rnorm (3))
    
  • with a matrix:

    A <- matrix (rep (d, each = 10) + rnorm (30), nrow = 10)
    

Call two functions from same onclick

Binding events from html is NOT recommended. This is recommended way:

document.getElementById('btn').addEventListener('click', function(){
    pay();
    cls();
});

Position Relative vs Absolute?

Marco Pellicciotta: The position of the element inside another element can be relative or absolute, about the element it's inside.

If you need to position the element in the browser window point of view it's best to use position:fixed

C++ Remove new line from multiline string

The code removes all newlines from the string str.

O(N) implementation best served without comments on SO and with comments in production.

unsigned shift=0;
for (unsigned i=0; i<length(str); ++i){
    if (str[i] == '\n') {
        ++shift;
    }else{
        str[i-shift] = str[i];
    }
}
str.resize(str.length() - shift);

I want to use CASE statement to update some records in sql server 2005

Add a WHERE clause

UPDATE dbo.TestStudents  
SET     LASTNAME =  CASE  
                        WHEN LASTNAME = 'AAA' THEN 'BBB' 
                        WHEN LASTNAME = 'CCC' THEN 'DDD' 
                        WHEN LASTNAME = 'EEE' THEN 'FFF' 
                        ELSE LASTNAME
                    END 
WHERE   LASTNAME IN ('AAA', 'CCC', 'EEE')

How do I use arrays in cURL POST requests

    $ch = curl_init();

    $data = array(
        'client_id' => 'xx',
        'client_secret' => 'xx',
        'redirect_uri' => $x,
        'grant_type' => 'xxx',
        'code' => $xx,
    );

    $data = http_build_query($data);

    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_URL, "https://example.com");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);

    $output = curl_exec($ch);

Using Ajax.BeginForm with ASP.NET MVC 3 Razor

Example:

Model:

public class MyViewModel
{
    [Required]
    public string Foo { get; set; }
}

Controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new MyViewModel());
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        return Content("Thanks", "text/html");
    }
}

View:

@model AppName.Models.MyViewModel

<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>

<div id="result"></div>

@using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "result" }))
{
    @Html.EditorFor(x => x.Foo)
    @Html.ValidationMessageFor(x => x.Foo)
    <input type="submit" value="OK" />
}

and here's a better (in my perspective) example:

View:

@model AppName.Models.MyViewModel

<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/index.js")" type="text/javascript"></script>

<div id="result"></div>

@using (Html.BeginForm())
{
    @Html.EditorFor(x => x.Foo)
    @Html.ValidationMessageFor(x => x.Foo)
    <input type="submit" value="OK" />
}

index.js:

$(function () {
    $('form').submit(function () {
        if ($(this).valid()) {
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    $('#result').html(result);
                }
            });
        }
        return false;
    });
});

which can be further enhanced with the jQuery form plugin.

'Malformed UTF-8 characters, possibly incorrectly encoded' in Laravel

I've experienced the same problem. The thing is that I forgot to start the apache and mysql in xampp... :S

Twig ternary operator, Shorthand if-then-else

{{ (ability.id in company_abilities) ? 'selected' : '' }}

The ternary operator is documented under 'other operators'

What's the difference between including files with JSP include directive, JSP include action and using JSP Tag Files?

All three template options - <%@include>, <jsp:include> and <%@tag> are valid, and all three cover different use cases.

With <@include>, the JSP parser in-lines the content of the included file into the JSP before compilation (similar to a C #include). You'd use this option with simple, static content: for example, if you wanted to include header, footer, or navigation elements into every page in your web-app. The included content becomes part of the compiled JSP and there's no extra cost at runtime.

<jsp:include> (and JSTL's <c:import>, which is similar and even more powerful) are best suited to dynamic content. Use these when you need to include content from another URL, local or remote; when the resource you're including is itself dynamic; or when the included content uses variables or bean definitions that conflict with the including page. <c:import> also allows you to store the included text in a variable, which you can further manipulate or reuse. Both these incur an additional runtime cost for the dispatch: this is minimal, but you need to be aware that the dynamic include is not "free".

Use tag files when you want to create reusable user interface components. If you have a List of Widgets, say, and you want to iterate over the Widgets and display properties of each (in a table, or in a form), you'd create a tag. Tags can take arguments, using <%@tag attribute> and these arguments can be either mandatory or optional - somewhat like method parameters.

Tag files are a simpler, JSP-based mechanism of writing tag libraries, which (pre JSP 2.0) you had to write using Java code. It's a lot cleaner to write JSP tag files when there's a lot of rendering to do in the tag: you don't need to mix Java and HTML code as you'd have to do if you wrote your tags in Java.

How to hide code from cells in ipython notebook visualized with nbviewer?

Here is a nice article (the same one @Ken posted) on how to polish up Jpuyter (the new IPython) notebooks for presentation. There are countless ways to extend Jupyter using JS, HTML, and CSS, including the ability to communicate with the notebook's python kernel from javascript. There are magic decorators for %%HTML and %%javascript so you can just do something like this in a cell by itself:

%%HTML
<script>
  function code_toggle() {
    if (code_shown){
      $('div.input').hide('500');
      $('#toggleButton').val('Show Code')
    } else {
      $('div.input').show('500');
      $('#toggleButton').val('Hide Code')
    }
    code_shown = !code_shown
  }

  $( document ).ready(function(){
    code_shown=false;
    $('div.input').hide()
  });
</script>
<form action="javascript:code_toggle()"><input type="submit" id="toggleButton" value="Show Code"></form>

I can also vouch Chris's methods work in jupyter 4.X.X.

getting the ng-object selected with ng-change

<select ng-model="item.size.code">
<option ng-repeat="size in sizes" ng-attr-value="size.code">{{size.name}}          </option>
</select>

How could others, on a local network, access my NodeJS app while it's running on my machine?

I had the same question and solved the problem. In my case, the Windows Firewall (not the router) was blocking the V8 machine I/O on the hosting machine.

  1. Go to windows button
  2. Search "Firewall"
  3. Choose "Allow programs to communicate through Firewall"
  4. Click Change Setup
  5. Tick all of "Evented I/O for V8 Javascript" OR "Node.js: Server-side Javascript"

My guess is that "Evented I/O for V8 Javascript" is the I/O process that node.js communicates to outside world and we need to free it before it can send packets outside of the local computer. After enabling this program to communicate over Windows firewall, I could use any port numbers to listen.

SQL query for getting data for last 3 months

Latest Versions of mysql don't support DATEADD instead use the syntax

DATE_ADD(date,INTERVAL expr type)

To get the last 3 months data use,

DATE_ADD(NOW(),INTERVAL -90 DAY) 
DATE_ADD(NOW(), INTERVAL -3 MONTH)

git: Switch branch and ignore any changes without committing

Follow,

$: git checkout -f

$: git checkout next_branch

How to drop unique in MySQL?

Use below query :

ALTER TABLE `table_name` DROP INDEX key_name;

If you don't know the key_name then first try below query, you can get key_name.

SHOW CREATE TABLE table_name

OR

SHOW INDEX FROM table_name;

If you want to remove/drop primary key from mysql table, Use below query for that

ALTER TABLE `products` DROP INDEX `PRIMARY`;

Code Taken from: http://chandreshrana.blogspot.in/2015/10/how-to-remove-unique-key-from-mysql.html

Mockito : doAnswer Vs thenReturn

doAnswer and thenReturn do the same thing if:

  1. You are using Mock, not Spy
  2. The method you're stubbing is returning a value, not a void method.

Let's mock this BookService

public interface BookService {
    String getAuthor();
    void queryBookTitle(BookServiceCallback callback);
}

You can stub getAuthor() using doAnswer and thenReturn.

BookService service = mock(BookService.class);
when(service.getAuthor()).thenReturn("Joshua");
// or..
doAnswer(new Answer() {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
        return "Joshua";
    }
}).when(service).getAuthor();

Note that when using doAnswer, you can't pass a method on when.

// Will throw UnfinishedStubbingException
doAnswer(invocation -> "Joshua").when(service.getAuthor());

So, when would you use doAnswer instead of thenReturn? I can think of two use cases:

  1. When you want to "stub" void method.

Using doAnswer you can do some additionals actions upon method invocation. For example, trigger a callback on queryBookTitle.

BookServiceCallback callback = new BookServiceCallback() {
    @Override
    public void onSuccess(String bookTitle) {
        assertEquals("Effective Java", bookTitle);
    }
};
doAnswer(new Answer() {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
        BookServiceCallback callback = (BookServiceCallback) invocation.getArguments()[0];
        callback.onSuccess("Effective Java");
        // return null because queryBookTitle is void
        return null;
    }
}).when(service).queryBookTitle(callback);
service.queryBookTitle(callback);
  1. When you are using Spy instead of Mock

When using when-thenReturn on Spy Mockito will call real method and then stub your answer. This can cause a problem if you don't want to call real method, like in this sample:

List list = new LinkedList();
List spy = spy(list);
// Will throw java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
when(spy.get(0)).thenReturn("java");
assertEquals("java", spy.get(0));

Using doAnswer we can stub it safely.

List list = new LinkedList();
List spy = spy(list);
doAnswer(invocation -> "java").when(spy).get(0);
assertEquals("java", spy.get(0));

Actually, if you don't want to do additional actions upon method invocation, you can just use doReturn.

List list = new LinkedList();
List spy = spy(list);
doReturn("java").when(spy).get(0);
assertEquals("java", spy.get(0));

Scanner is skipping nextLine() after using next() or nextFoo()?

Why not use a new Scanner for every reading? Like below. With this approach you will not confront your problem.

int i = new Scanner(System.in).nextInt();

Animate background image change with jQuery

Have a look at this jQuery plugin from OvalPixels.

It may do the trick.

Using multiple property files (via PropertyPlaceholderConfigurer) in multiple projects/modules

I know that this is an old question, but the ignore-unresolvable property was not working for me and I didn't know why.

The problem was that I needed an external resource (something like location="file:${CATALINA_HOME}/conf/db-override.properties") and the ignore-unresolvable="true" does not do the job in this case.

What one needs to do for ignoring a missing external resource is:

ignore-resource-not-found="true"

Just in case anyone else bumps into this.

React - changing an uncontrolled input

In my case, I was missing something really trivial.

<input value={state.myObject.inputValue} />

My state was the following when I was getting the warning:

state = {
   myObject: undefined
}

By alternating my state to reference the input of my value, my issue was solved:

state = {
   myObject: {
      inputValue: ''
   }
}

ImportError: DLL load failed: The specified module could not be found

I had the same issue with importing matplotlib.pylab with Python 3.5.1 on Win 64. Installing the Visual C++ Redistributable für Visual Studio 2015 from this links: https://www.microsoft.com/en-us/download/details.aspx?id=48145 fixed the missing DLLs.

I find it better and easier than downloading and pasting DLLs.

What is %2C in a URL?

In Firefox there is Ctrl+Shift+K for the Web console, then you type

;decodeURIComponent("%2c")
  • mind the semicolon in the beginning
  • if you Copy&Paste, you should first enable it (the console will warn you)

and you get the answer:

","

How do I change the UUID of a virtual disk?

The correct command is the following one.

VBoxManage internalcommands sethduuid "/home/user/VirtualBox VMs/drupal/drupal.vhd"

The path for the virtual disk contains a space, so it must be enclosed in double quotes to avoid it is parsed as two parameters.

How do you create a REST client for Java?

Try looking at http-rest-client

https://github.com/g00dnatur3/http-rest-client

Here is a simple example:

RestClient client = RestClient.builder().build();
String geocoderUrl = "http://maps.googleapis.com/maps/api/geocode/json"
Map<String, String> params = Maps.newHashMap();
params.put("address", "beverly hills 90210");
params.put("sensor", "false");
JsonNode node = client.get(geocoderUrl, params, JsonNode.class);

The library takes care of json serialization and binding for you.

Here is another example,

RestClient client = RestClient.builder().build();
String url = ...
Person person = ...
Header header = client.create(url, person);
if (header != null) System.out.println("Location header is:" + header.value());

And one last example,

RestClient client = RestClient.builder().build();
String url = ...
Person person = client.get(url, null, Person.class); //no queryParams

Cheers!

java.lang.OutOfMemoryError: GC overhead limit exceeded

Fix memory leaks in your application with help of profile tools like eclipse MAT or VisualVM

With JDK 1.7.x or later versions, use G1GC, which spends 10% on garbage collection unlike 2% in other GC algorithms.

Apart from setting heap memory with -Xms1g -Xmx2g , try `

-XX:+UseG1GC 
-XX:G1HeapRegionSize=n, 
-XX:MaxGCPauseMillis=m, 
-XX:ParallelGCThreads=n, 
-XX:ConcGCThreads=n`

Have a look at oracle article for fine-tuning these parameters.

Some question related to G1GC in SE:

Java 7 (JDK 7) garbage collection and documentation on G1

Java G1 garbage collection in production

Agressive garbage collector strategy

Best practices for Storyboard login screen, handling clearing of data upon logout

enter image description here

In App Delegate.m

 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60)
                                                     forBarMetrics:UIBarMetricsDefault];

NSString *identifier;
BOOL isSaved = [[NSUserDefaults standardUserDefaults] boolForKey:@"loginSaved"];
if (isSaved)
{
    //identifier=@"homeViewControllerId";
    UIWindow* mainWindow=[[[UIApplication sharedApplication] delegate] window];
    UITabBarController *tabBarVC =
    [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"TabBarVC"];
    mainWindow.rootViewController=tabBarVC;
}
else
{


    identifier=@"loginViewControllerId";
    UIStoryboard *    storyboardobj=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
    UIViewController *screen = [storyboardobj instantiateViewControllerWithIdentifier:identifier];

    UINavigationController *navigationController=[[UINavigationController alloc] initWithRootViewController:screen];

    self.window.rootViewController = navigationController;
    [self.window makeKeyAndVisible];

}

return YES;

}

view controller.m In view did load

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.

UIBarButtonItem* barButton = [[UIBarButtonItem alloc] initWithTitle:@"Logout" style:UIBarButtonItemStyleDone target:self action:@selector(logoutButtonClicked:)];
[self.navigationItem setLeftBarButtonItem:barButton];

}

In logout button action

-(void)logoutButtonClicked:(id)sender{

UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Alert" message:@"Do you want to logout?" preferredStyle:UIAlertControllerStyleAlert];

    [alertController addAction:[UIAlertAction actionWithTitle:@"Logout" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
           NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setBool:NO forKey:@"loginSaved"];
           [[NSUserDefaults standardUserDefaults] synchronize];
      AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
    UIStoryboard *    storyboardobj=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
    UIViewController *screen = [storyboardobj instantiateViewControllerWithIdentifier:@"loginViewControllerId"];
    [appDelegate.window setRootViewController:screen];
}]];


[alertController addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
    [self dismissViewControllerAnimated:YES completion:nil];
}]];

dispatch_async(dispatch_get_main_queue(), ^ {
    [self presentViewController:alertController animated:YES completion:nil];
});}

JavaScript console.log causes error: "Synchronous XMLHttpRequest on the main thread is deprecated..."

I get such warning in following case:

1) file1 which contains <script type="text/javascript" src="/javascript/jquery-1.10.2.js"></script>. Page has input fields. I enter some value in input field and click button. Jquery sends input to external php file.

2) external php file also contains jquery and in the external php file i also included <script type="text/javascript" src="/javascript/jquery-1.10.2.js"></script>. Because if this i got the warning.

Removed <script type="text/javascript" src="/javascript/jquery-1.10.2.js"></script> from external php file and works without the warning.

As i understand on loading the first file (file1), i load jquery-1.10.2.js and as the page does not reloads (it sends data to external php file using jquery $.post), then jquery-1.10.2.js continue to exist. So not necessary again to load it.

I have filtered my Excel data and now I want to number the rows. How do I do that?

Step 1: Highlight the entire column (not including the header) of the column you wish to populate

Step 2: (Using Kutools) On the Insert dropdown, click "Fill Custom List"

Step 3: Click Edit

Step 4: Create your list (For Ex: 1, 2)

Step 5: Choose your new custom list and then click "Fill Range"

DONE!!!

How do I prompt a user for confirmation in bash script?

This what I found elsewhere, is there a better possible version?

read -p "Are you sure you wish to continue?"
if [ "$REPLY" != "yes" ]; then
   exit
fi

Align items in a stack panel?

You can achieve this with a DockPanel:

<DockPanel Width="300">
    <TextBlock>Left</TextBlock>
    <Button HorizontalAlignment="Right">Right</Button>
</DockPanel>

The difference is that a StackPanel will arrange child elements into single line (either vertical or horizontally) whereas a DockPanel defines an area where you can arrange child elements either horizontally or vertically, relative to each other (the Dock property changes the position of an element relative to other elements within the same container. Alignment properties, such as HorizontalAlignment, change the position of an element relative to its parent element).

Update

As pointed out in the comments you can also use the FlowDirection property of a StackPanel. See @D_Bester's answer.

Bridged networking not working in Virtualbox under Windows 10

Uninstall then run the setup program again but this time as Administrator. Make sure the VB bridge driver is selected during installation.

moment.js get current time in milliseconds?

You can just get the individual time components and calculate the total. You seem to be expecting Moment to already have this feature neatly packaged up for you, but it doesn't. I doubt it's something that people have a need for very often.

Example:

_x000D_
_x000D_
var m = moment();_x000D_
_x000D_
var ms = m.milliseconds() + 1000 * (m.seconds() + 60 * (m.minutes() + 60 * m.hours()));_x000D_
_x000D_
console.log(ms);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
_x000D_
_x000D_
_x000D_

Java unsupported major minor version 52.0

I noticed that in netbeans Apache configuration in the servers tab. you can state the platform for your web application. I changed to 1.8 and it worked fine. (I am targeting java 8 platform in my application). Hope that might t help.

How to set shadows in React Native for android?

Set elevation: 3 and you should see the shadow in bottom of component without a 3rd party lib. At least in RN 0.57.4

Convert DOS line endings to Linux line endings in Vim

:set fileformat=unix to convert from DOS to Unix.

NOW() function in PHP

In PHP the logic equivalent of the MySQL's function now() is time().

But time() return a Unix timestamp that is different from a MySQL DATETIME.

So you must convert the Unix timestamp returned from time() in the MySQL format.

You do it with: date("Y-m-d H:i:s");

But where is time() in the date() function? It's the second parameter: infact you should provide to date() a timestamp as second parameter, but if it is omissed it is defaulted to time().

This is the most complete answer I can imagine.

Greetings.

Peak memory usage of a linux/unix process

Valgrind one-liner:

valgrind --tool=massif --pages-as-heap=yes --massif-out-file=massif.out ./test.sh; grep mem_heap_B massif.out | sed -e 's/mem_heap_B=\(.*\)/\1/' | sort -g | tail -n 1

Note use of --pages-as-heap to measure all memory in a process. More info here: http://valgrind.org/docs/manual/ms-manual.html

This will slow down your command significantly.

What is wrong with my SQL here? #1089 - Incorrect prefix key

Problem is the same for me in phpMyAdmin. I just created a table without any const. Later I modified the ID to a Primary key. Then I changed the ID to Auto-inc. That solved the issue.

ALTER TABLE `users` CHANGE `ID` `ID` INT(11) NOT NULL AUTO_INCREMENT;

Googlemaps API Key for Localhost

Where it says "Accept requests from these HTTP referrers (websites) (Optional)" you don't need to have any referrer listed. So click the X beside localhost on this page but continue to use your key.

It should then work after a few minutes.

Changes made can sometimes take a few minutes to take effect so wait a few minutes before testing again.

Create a List of primitive int?

When you use Java for Android development, it is recommended to use SparseIntArray to prevent autoboxing between int and Integer.

You can finde more information to SparseIntArray in the Android Developers documentation and a good explanation for autoboxing on Android enter link description here

How can I copy a conditional formatting from one document to another?

If you want to copy conditional formatting to another document you can use the "Copy to..." feature for the worksheet (click the tab with the name of the worksheet at the bottom) and copy the worksheet to the other document.

Then you can just copy what you want from that worksheet and right-click select "Paste special" -> "Paste conditional formatting only", as described earlier.

How to destroy a JavaScript object?

While the existing answers have given solutions to solve the issue and the second half of the question, they do not provide an answer to the self discovery aspect of the first half of the question that is in bold:

"How can I see which variable causes memory overhead...?"

It may not have been as robust 3 years ago, but the Chrome Developer Tools "Profiles" section is now quite powerful and feature rich. The Chrome team has an insightful article on using it and thus also how garbage collection (GC) works in javascript, which is at the core of this question.

Since delete is basically the root of the currently accepted answer by Yochai Akoka, it's important to remember what delete does. It's irrelevant if not combined with the concepts of how GC works in the next two answers: if there's an existing reference to an object it's not cleaned up. The answers are more correct, but probably not as appreciated because they require more thought than just writing 'delete'. Yes, one possible solution may be to use delete, but it won't matter if there's another reference to the memory leak.

Another answer appropriately mentions circular references and the Chrome team documentation can provide much more clarity as well as the tools to verify the cause.

Since delete was mentioned here, it also may be useful to provide the resource Understanding Delete. Although it does not get into any of the actual solution which is really related to javascript's garbage collector.

how to use #ifdef with an OR condition?

OR condition in #ifdef

#if defined LINUX || defined ANDROID
// your code here
#endif /* LINUX || ANDROID */

or-

#if defined(LINUX) || defined(ANDROID)
// your code here
#endif /* LINUX || ANDROID */

Both above are the same, which one you use simply depends on your taste.


P.S.: #ifdef is simply the short form of #if defined, however, does not support complex condition.


Further-

  • AND: #if defined LINUX && defined ANDROID
  • XOR: #if defined LINUX ^ defined ANDROID

Convert XmlDocument to String

Assuming xmlDoc is an XmlDocument object whats wrong with xmlDoc.OuterXml?

return xmlDoc.OuterXml;

The OuterXml property returns a string version of the xml.

Python: find position of element in array

I would assume your variable mean_temp already has the values loaded in to it and is nX1 dimension (i.e only one row). Now to achieve what you want, you can :

Change the datatype of your variable:

def coldest_location(data):

    mean_temp = numpy.mat(mean_temp) #data is now matrix type
    min_index = numpy.nonzero(mean_temp == mean_temp.min())  # this returns list of indexes
    print mean_temp[min_index[0],min_index[1]] # printing minimum value, i.e -24.6 in you data i believe

How to center a <p> element inside a <div> container?

?you should do these steps :

  1. the mother Element should be positioned(for EXP you can give it position:relative;)
  2. the child Element should have positioned "Absolute" and values should set like this: top:0;buttom:0;right:0;left:0; (to be middle vertically)
  3. for the child Element you should set "margin : auto" (to be middle vertically)
  4. the child and mother Element should have "height"and"width" value
  5. for mother Element => text-align:center (to be middle horizontally)

??simply here is the summery of those 5 steps:

.mother_Element {
    position : relative;
    height : 20%;
    width : 5%;
    text-align : center
    }
.child_Element {
    height : 1.2 em;
    width : 5%;
    margin : auto;
    position : absolute;
    top:0;
    bottom:0;
    left:0;
    right:0;
    }

angular 2 ngIf and CSS transition/animation

In my case I declared the animation on the wrong component by mistake.

app.component.html

  <app-order-details *ngIf="orderDetails" [@fadeInOut] [orderDetails]="orderDetails">
  </app-order-details>

The animation needs to be declared on the component where the element is used in (appComponent.ts). I was declaring the animation on OrderDetailsComponent.ts instead.

Hopefully it will help someone making the same mistake

How to change DatePicker dialog color for Android 5.0

For Changing Year list item text color (SPECIFIC FOR ANDROID 5.0)

Just set certain text color in your date picker dialog style. For some reason setting flag yearListItemTextAppearance doesn't reflect any change on year list.

<item name="android:textColor">@android:color/black</item>

back button callback in navigationController in iOS

Here's another way I implemented (didn't test it with an unwind segue but it probably wouldn't differentiate, as others have stated in regards to other solutions on this page) to have the parent view controller perform actions before the child VC it pushed gets popped off the view stack (I used this a couple levels down from the original UINavigationController). This could also be used to perform actions before the childVC gets pushed, too. This has the added advantage of working with the iOS system back button, instead of having to create a custom UIBarButtonItem or UIButton.

  1. Have your parent VC adopt the UINavigationControllerDelegate protocol and register for delegate messages:

    MyParentViewController : UIViewController <UINavigationControllerDelegate>
    
    -(void)viewDidLoad {
        self.navigationcontroller.delegate = self;
    }
    
  2. Implement this UINavigationControllerDelegate instance method in MyParentViewController:

    - (id<UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)navigationController animationControllerForOperation:(UINavigationControllerOperation)operation fromViewController:(UIViewController *)fromVC toViewController:(UIViewController *)toVC {
        // Test if operation is a pop; can also test for a push (i.e., do something before the ChildVC is pushed
        if (operation == UINavigationControllerOperationPop) {
            // Make sure it's the child class you're looking for
            if ([fromVC isKindOfClass:[ChildViewController class]]) {
                // Can handle logic here or send to another method; can also access all properties of child VC at this time
                return [self didPressBackButtonOnChildViewControllerVC:fromVC];
            }
        }
        // If you don't want to specify a nav controller transition
        return nil;
    }
    
  3. If you specify a specific callback function in the above UINavigationControllerDelegate instance method

    -(id <UIViewControllerAnimatedTransitioning>)didPressBackButtonOnAddSearchRegionsVC:(UIViewController *)fromVC {
        ChildViewController *childVC = ChildViewController.new;
        childVC = (ChildViewController *)fromVC;
    
        // childVC.propertiesIWantToAccess go here
    
        // If you don't want to specify a nav controller transition
        return nil;
    

    }

How to get to Model or Viewbag Variables in a Script Tag

When you're doing this

var model = @Html.Raw(Json.Encode(Model));

You're probably getting a JSON string, and not a JavaScript object.

You need to parse it in to an object:

var model = JSON.parse(model); //or $.parseJSON() since if jQuery is included
console.log(model.Sections);

Getting the button into the top right corner inside the div box

Just add position:absolute; top:0; right:0; to the CSS for your button.

 #button {
     line-height: 12px;
     width: 18px;
     font-size: 8pt;
     font-family: tahoma;
     margin-top: 1px;
     margin-right: 2px;
     position:absolute;
     top:0;
     right:0;
 }

jsFiddle example

What are differences between AssemblyVersion, AssemblyFileVersion and AssemblyInformationalVersion?

AssemblyVersion

Where other assemblies that reference your assembly will look. If this number changes, other assemblies have to update their references to your assembly! Only update this version, if it breaks backward compatibility. The AssemblyVersion is required.

I use the format: major.minor. This would result in:

[assembly: AssemblyVersion("1.0")]

If you're following SemVer strictly then this means you only update when the major changes, so 1.0, 2.0, 3.0, etc.

AssemblyFileVersion

Used for deployment. You can increase this number for every deployment. It is used by setup programs. Use it to mark assemblies that have the same AssemblyVersion, but are generated from different builds.

In Windows, it can be viewed in the file properties.

The AssemblyFileVersion is optional. If not given, the AssemblyVersion is used.

I use the format: major.minor.patch.build, where I follow SemVer for the first three parts and use the buildnumber of the buildserver for the last part (0 for local build). This would result in:

[assembly: AssemblyFileVersion("1.3.2.254")]

Be aware that System.Version names these parts as major.minor.build.revision!

AssemblyInformationalVersion

The Product version of the assembly. This is the version you would use when talking to customers or for display on your website. This version can be a string, like '1.0 Release Candidate'.

The AssemblyInformationalVersion is optional. If not given, the AssemblyFileVersion is used.

I use the format: major.minor[.patch] [revision as string]. This would result in:

[assembly: AssemblyInformationalVersion("1.0 RC1")]

Redirect form to different URL based on select option element

Just use a onchnage Event for select box.

<select id="selectbox" name="" onchange="javascript:location.href = this.value;">
    <option value="https://www.yahoo.com/" selected>Option1</option>
    <option value="https://www.google.co.in/">Option2</option>
    <option value="https://www.gmail.com/">Option3</option>

</select>

And if selected option to be loaded at the page load then add some javascript code

<script type="text/javascript">
    window.onload = function(){
        location.href=document.getElementById("selectbox").value;
    }       
</script>

for jQuery: Remove the onchange event from <select> tag

jQuery(function () {
    // remove the below comment in case you need chnage on document ready
    // location.href=jQuery("#selectbox").val(); 
    jQuery("#selectbox").change(function () {
        location.href = jQuery(this).val();
    })
})

Entity Framework Query for inner join

In case anyone's interested in the Method syntax, if you have a navigation property, it's way easy:

db.Services.Where(s=>s.ServiceAssignment.LocationId == 1);

If you don't, unless there's some Join() override I'm unaware of, I think it looks pretty gnarly (and I'm a Method syntax purist):

db.Services.Join(db.ServiceAssignments, 
     s => s.Id,
     sa => sa.ServiceId, 
     (s, sa) => new {service = s, asgnmt = sa})
.Where(ssa => ssa.asgnmt.LocationId == 1)
.Select(ssa => ssa.service);

What does java:comp/env/ do?

Quoting https://web.archive.org/web/20140227201242/http://v1.dione.zcu.cz/java/docs/jndi-1.2/tutorial/beyond/misc/policy.html

At the root context of the namespace is a binding with the name "comp", which is bound to a subtree reserved for component-related bindings. The name "comp" is short for component. There are no other bindings at the root context. However, the root context is reserved for the future expansion of the policy, specifically for naming resources that are tied not to the component itself but to other types of entities such as users or departments. For example, future policies might allow you to name users and organizations/departments by using names such as "java:user/alice" and "java:org/engineering".

In the "comp" context, there are two bindings: "env" and "UserTransaction". The name "env" is bound to a subtree that is reserved for the component's environment-related bindings, as defined by its deployment descriptor. "env" is short for environment. The J2EE recommends (but does not require) the following structure for the "env" namespace.

So the binding you did from spring or, for example, from a tomcat context descriptor go by default under java:comp/env/

For example, if your configuration is:

<bean id="someId" class="org.springframework.jndi.JndiObjectFactoryBean">
  <property name="jndiName" value="foo"/>
</bean>

Then you can access it directly using:

Context ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup("java:comp/env/foo");

or you could make an intermediate step so you don't have to specify "java:comp/env" for every resource you retrieve:

Context ctx = new InitialContext();
Context envCtx = (Context)ctx.lookup("java:comp/env");
DataSource ds = (DataSource)envCtx.lookup("foo");

Why is it bad style to `rescue Exception => e` in Ruby?

That's a specific case of the rule that you shouldn't catch any exception you don't know how to handle. If you don't know how to handle it, it's always better to let some other part of the system catch and handle it.

Rails: How can I set default values in ActiveRecord?

We put the default values in the database through migrations (by specifying the :default option on each column definition) and let Active Record use these values to set the default for each attribute.

IMHO, this approach is aligned with the principles of AR : convention over configuration, DRY, the table definition drives the model, not the other way around.

Note that the defaults are still in the application (Ruby) code, though not in the model but in the migration(s).

A warning - comparison between signed and unsigned integer expressions

or use this header library and write:

// |notEqaul|less|lessEqual|greater|greaterEqual
if(sweet::equal(valueA,valueB))

and don't care about signed/unsigned or different sizes

How to: Create trigger for auto update modified date with SQL Server 2008

My approach:

  • define a default constraint on the ModDate column with a value of GETDATE() - this handles the INSERT case

  • have a AFTER UPDATE trigger to update the ModDate column

Something like:

CREATE TRIGGER trg_UpdateTimeEntry
ON dbo.TimeEntry
AFTER UPDATE
AS
    UPDATE dbo.TimeEntry
    SET ModDate = GETDATE()
    WHERE ID IN (SELECT DISTINCT ID FROM Inserted)

Spring: how do I inject an HttpServletRequest into a request-scoped bean?

Spring exposes the current HttpServletRequest object (as well as the current HttpSession object) through a wrapper object of type ServletRequestAttributes. This wrapper object is bound to ThreadLocal and is obtained by calling the static method RequestContextHolder.currentRequestAttributes().

ServletRequestAttributes provides the method getRequest() to get the current request, getSession() to get the current session and other methods to get the attributes stored in both the scopes. The following code, though a bit ugly, should get you the current request object anywhere in the application:

HttpServletRequest curRequest = 
((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
.getRequest();

Note that the RequestContextHolder.currentRequestAttributes() method returns an interface and needs to be typecasted to ServletRequestAttributes that implements the interface.


Spring Javadoc: RequestContextHolder | ServletRequestAttributes

How to convert a string to character array in c (or) how to extract a single char form string?

In this simple way

char str [10] = "IAmCute";
printf ("%c",str[4]);

Opening a .ipynb.txt File

Try the following steps:

  1. Download the file open it in the Juypter Notebook.
  2. Go to File -> Rename and remove the .txt extension from the end; so now the file name has just .ipynb extension.
  3. Now reopen it from the Juypter Notebook.

Merging arrays with the same keys

You need to use array_merge_recursive instead of array_merge. Of course there can only be one key equal to 'c' in the array, but the associated value will be an array containing both 3 and 4.

what is the size of an enum type data in C++?

An enum is nearly an integer. To simplify a lot

enum yourenum { a, b, c };

is almost like

#define a 0
#define b 1
#define c 2

Of course, it is not really true. I'm trying to explain that enum are some kind of coding...

Capture Image from Camera and Display in Activity

Please, follow this example with this implementation by using Kotlin and Andoirdx support:

button1.setOnClickListener{
        file = getPhotoFile()
        val uri: Uri = FileProvider.getUriForFile(applicationContext, "com.example.foto_2.filrprovider", file!!)
        captureImage.putExtra(MediaStore.EXTRA_OUTPUT, uri)

        val camaraActivities: List<ResolveInfo> = applicationContext.getPackageManager().queryIntentActivities(captureImage, PackageManager.MATCH_DEFAULT_ONLY)

        for (activity in camaraActivities) {
            applicationContext.grantUriPermission(activity.activityInfo.packageName, uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
        }

        startActivityForResult(captureImage, REQUEST_PHOTO)
    }

And the activity result:

if (requestCode == REQUEST_PHOTO) {
        val uri = FileProvider.getUriForFile(applicationContext, "com.example.foto_2.filrprovider", file!!)
        applicationContext.revokeUriPermission(uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
        imageView1.viewTreeObserver.addOnGlobalLayoutListener {
            width = imageView1.width
            height = imageView1.height
            imageView1.setImageBitmap(getScaleBitmap(file!!.path , width , height))
        }
        if(width!=0&&height!=0){
            imageView1.setImageBitmap(getScaleBitmap(file!!.path , width , height))
        }else{
            val size = Point()
            this.windowManager.defaultDisplay.getSize(size)
            imageView1.setImageBitmap(getScaleBitmap(file!!.path , size.x , size.y))
        }

    }

You can get more detail in https://github.com/joelmmx/take_photo_kotlin.git

I hope it helps you!

Could not load type 'XXX.Global'

In my case, I was duplicating an online site locally and getting this error locally in Utildev Cassini for asp.net 2.0. It turned out that I copied only global.asax locally and didn't copy the App_code conterpart of it. Copying it fixed the problem.

Creating csv file with php

Its blank because you are writing to file. you should write to output using php://output instead and also send header information to indicate that it's csv.

Example

header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="sample.csv"');
$data = array(
        'aaa,bbb,ccc,dddd',
        '123,456,789',
        '"aaa","bbb"'
);

$fp = fopen('php://output', 'wb');
foreach ( $data as $line ) {
    $val = explode(",", $line);
    fputcsv($fp, $val);
}
fclose($fp);

Get filename from file pointer

You can get the path via fp.name. Example:

>>> f = open('foo/bar.txt')
>>> f.name
'foo/bar.txt'

You might need os.path.basename if you want only the file name:

>>> import os
>>> f = open('foo/bar.txt')
>>> os.path.basename(f.name)
'bar.txt'

File object docs (for Python 2) here.

Best way to convert an ArrayList to a string

This is quite an old conversation by now and apache commons are now using a StringBuilder internally: http://commons.apache.org/lang/api/src-html/org/apache/commons/lang/StringUtils.html#line.3045

This will as we know improve performance, but if performance is critical then the method used might be somewhat inefficient. Whereas the interface is flexible and will allow for consistent behaviour across different Collection types it is somewhat inefficient for Lists, which is the type of Collection in the original question.

I base this in that we are incurring some overhead which we would avoid by simply iterating through the elements in a traditional for loop. Instead there are some additional things happening behind the scenes checking for concurrent modifications, method calls etc. The enhanced for loop will on the other hand result in the same overhead since the iterator is used on the Iterable object (the List).

Difference between session affinity and sticky session?

They are Synonyms. No Difference At all

Sticky Session / Session Affinity:

Affinity/Stickiness/Contact between user session and, the server to which user request is sent is retained.

Encrypt and Decrypt in Java

KeyGenerator is used to generate keys

You may want to check KeySpec, SecretKey and SecretKeyFactory classes

http://docs.oracle.com/javase/1.5.0/docs/api/javax/crypto/spec/package-summary.html

Placeholder in UITextView

This mimics UITextField's placeholder perfectly, where the place holder text stays until you actually type something.

private let placeholder = "Type here"

@IBOutlet weak var textView: UITextView! {
    didSet {
        textView.textColor = UIColor.lightGray
        textView.text = placeholder
        textView.selectedRange = NSRange(location: 0, length: 0)
    }
}

extension ViewController: UITextViewDelegate {

    func textViewDidChangeSelection(_ textView: UITextView) {
        // Move cursor to beginning on first tap
        if textView.text == placeholder {
            textView.selectedRange = NSRange(location: 0, length: 0)
        }
    }

    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        if textView.text == placeholder && !text.isEmpty {
            textView.text = nil
            textView.textColor = UIColor.black
            textView.selectedRange = NSRange(location: 0, length: 0)
        }
        return true
    }

    func textViewDidChange(_ textView: UITextView) {
        if textView.text.isEmpty {
            textView.textColor = UIColor.lightGray
            textView.text = placeholder
        }
    }
}

Moment.js with Vuejs

I made it work with Vue 2.0 in single file component.

npm install moment in folder where you have vue installed

<template>
  <div v-for="meta in order.meta">
    {{ getHumanDate(meta.value.date) }}
  </div>
</template>
<script>
    import moment from 'moment';
    export default {
         methods: {
            getHumanDate : function (date) {
                return moment(date, 'YYYY-MM-DD').format('DD/MM/YYYY');
            }
        }
    }
</script>

How to configure nginx to enable kinda 'file browser' mode?

1. List content of all directories

Set autoindex option to on. It is off by default.

Your configuration file ( vi /etc/nginx/sites-available/default ) should be like this

location /{ 
   ... ( some other lines )
   autoindex on;
   ... ( some other lines )
}

2. List content of only some specific directory

Set autoindex option to on. It is off by default.

Your configuration file ( vi /etc/nginx/sites-available/default )
should be like this.
change path_of_your_directory to your directory path

location /path_of_your_directory{ 
   ... ( some other lines )
   autoindex on;
   ... ( some other lines )
}

Hope it helps..

Use index in pandas to plot data

Marius's answer worked perfectly for me:

df.reset_index() sets the index as the first column, with the column label "index." You can now use the index as an axis for plotting, as described in his answer:

monthly_mean.reset_index().plot(x='index', y='A')

However, this does not change the original dataframe. The original dataframe will be unchanged unless it is set using df = df.reset_index().

example:

df.reset_index()
print(df)
        COF    TSF    PSF
3.0   0.946  0.914  0.966
4.0   0.963  0.940  0.976
6.0   0.978  0.965  0.987
8.0   0.989  0.984  0.995
10.0  1.000  1.000  1.000
12.0  1.004  1.013  1.009
15.0  1.013  1.026  1.012
17.0  1.019  1.037  1.017
20.0  1.024  1.045  1.020
25.0  1.030  1.057  1.026
30.0  1.034  1.065  1.030
35.0  1.037  1.069  1.031
40.0  1.037  1.068  1.030
60.0  1.037  1.068  1.030
df = df.reset_index()
print(df)
    index    COF    TSF    PSF
0     3.0  0.946  0.914  0.966
1     4.0  0.963  0.940  0.976
2     6.0  0.978  0.965  0.987
3     8.0  0.989  0.984  0.995
4    10.0  1.000  1.000  1.000
5    12.0  1.004  1.013  1.009
6    15.0  1.013  1.026  1.012
7    17.0  1.019  1.037  1.017
8    20.0  1.024  1.045  1.020
9    25.0  1.030  1.057  1.026
10   30.0  1.034  1.065  1.030
11   35.0  1.037  1.069  1.031
12   40.0  1.037  1.068  1.030
13   60.0  1.037  1.068  1.030

See: DataFrame.reset_index and DataFrame.set_index

How can I easily switch between PHP versions on Mac OSX?

If you have both versions of PHP installed, you can switch between versions using the link and unlink brew commands.

For example, to switch between PHP 7.4 and PHP 7.3

brew unlink [email protected]
brew link [email protected]

PS: both versions of PHP have be installed for these commands to work.

What Process is using all of my disk IO

You're looking for iotop (assuming you've got kernel >2.6.20 and Python 2.5). Failing that, you're looking into hooking into the filesystem. I recommend the former.