Programs & Examples On #Httpwebrequest

HttpWebRequest is a class for .NET Framework applications that provides a HTTP-specific implementation of the WebRequest class.

How to properly make a http web GET request

Servers sometimes compress their responses to save on bandwidth, when this happens, you need to decompress the response before attempting to read it. Fortunately, the .NET framework can do this automatically, however, we have to turn the setting on.

Here's an example of how you could achieve that.

string html = string.Empty;
string url = @"";

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.AutomaticDecompression = DecompressionMethods.GZip;

using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
    html = reader.ReadToEnd();



public string Get(string uri)
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

    using(HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    using(Stream stream = response.GetResponseStream())
    using(StreamReader reader = new StreamReader(stream))
        return reader.ReadToEnd();

GET async

public async Task<string> GetAsync(string uri)
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

    using(HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
    using(Stream stream = response.GetResponseStream())
    using(StreamReader reader = new StreamReader(stream))
        return await reader.ReadToEndAsync();

Contains the parameter method in the event you wish to use other HTTP methods such as PUT, DELETE, ETC

public string Post(string uri, string data, string contentType, string method = "POST")
    byte[] dataBytes = Encoding.UTF8.GetBytes(data);

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
    request.ContentLength = dataBytes.Length;
    request.ContentType = contentType;
    request.Method = method;

    using(Stream requestBody = request.GetRequestStream())
        requestBody.Write(dataBytes, 0, dataBytes.Length);

    using(HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    using(Stream stream = response.GetResponseStream())
    using(StreamReader reader = new StreamReader(stream))
        return reader.ReadToEnd();


POST async
Contains the parameter method in the event you wish to use other HTTP methods such as PUT, DELETE, ETC

public async Task<string> PostAsync(string uri, string data, string contentType, string method = "POST")
    byte[] dataBytes = Encoding.UTF8.GetBytes(data);

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
    request.ContentLength = dataBytes.Length;
    request.ContentType = contentType;
    request.Method = method;

    using(Stream requestBody = request.GetRequestStream())
        await requestBody.WriteAsync(dataBytes, 0, dataBytes.Length);

    using(HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
    using(Stream stream = response.GetResponseStream())
    using(StreamReader reader = new StreamReader(stream))
        return await reader.ReadToEndAsync();

The request was aborted: Could not create SSL/TLS secure channel

"The request was aborted: Could not create SSL/TLS secure channel" exception can occur if the server is returning an HTTP 401 Unauthorized response to the HTTP request.

You can determine if this is happening by turning on trace-level System.Net logging for your client application, as described in this answer.

Once that logging configuration is in place, run the application and reproduce the error, then look in the logging output for a line like this:

System.Net Information: 0 : [9840] Connection#62912200 - Received status line: Version=1.1, StatusCode=401, StatusDescription=Unauthorized.

In my situation, I was failing to set a particular cookie that the server was expecting, leading to the server responding to the request with the 401 error, which in turn led to the "Could not create SSL/TLS secure channel" exception.

Login to website, via C#

Matthew Brindley, your code worked very good for some website I needed (with login), but I needed to change to HttpWebRequest and HttpWebResponse otherwise I get a 404 Bad Request from the remote server. Also I would like to share my workaround using your code, and is that I tried it to login to a website based on moodle, but it didn't work at your step "GETting the page behind the login form" because when successfully POSTing the login, the Header 'Set-Cookie' didn't return anything despite other websites does.

So I think this where we need to store cookies for next Requests, so I added this.

To the "POSTing to the login form" code block :

var cookies = new CookieContainer();
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(formUrl);
req.CookieContainer = cookies;

And To the "GETting the page behind the login form" :

HttpWebRequest getRequest = (HttpWebRequest)WebRequest.Create(getUrl);
getRequest.CookieContainer = new CookieContainer();
getRequest.Headers.Add("Cookie", cookieHeader);

Doing this, lets me Log me in and get the source code of the "page behind login" (website based moodle) I know this is a vague use of the CookieContainer and HTTPCookies because we may ask first is there a previously set of cookies saved before sending the request to the server. This works without problem anyway, but here's a good info to read about WebRequest and WebResponse with sample projects and tutorial:
Retrieving HTTP content in .NET
How to use HttpWebRequest and HttpWebResponse in .NET

No connection could be made because the target machine actively refused it

If you use WCF storm, can you even log-in to the WCF service endpoint? If not, and you are hosting it in a Windows service, you probably forgot to register that namespace. It's not very well advertised that this step is required, and it is actually annoying to do.

I use this tool to do this; it automates all those cumbersome steps.

Use C# HttpWebRequest to send json to web service

First of all you missed ScriptService attribute to add in webservice.


After then try following method to call webservice via JSON.

        var webAddr = "http://Domain/VBRService.asmx/callJson";
        var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
        httpWebRequest.ContentType = "application/json; charset=utf-8";
        httpWebRequest.Method = "POST";            

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            string json = "{\"x\":\"true\"}";


        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            var result = streamReader.ReadToEnd();
            return result;

Proxy Basic Authentication in C#: HTTP 407 error

I had a similar problem due to a password protected proxy server and couldn't find much in the way of information out there - hopefully this helps someone. I wanted to pick up the credentials as used by the customer's browser. However, the CredentialCache.DefaultCredentials and DefaultNetworkCredentials aren't working when the proxy has it's own username and password even though I had entered these details to ensure thatInternet explorer and Edge had access.

The solution for me in the end was to use a nuget package called "CredentialManagement.Standard" and the below code:

using WebClient webClient = new WebClient();    
var request = WebRequest.Create("");
var proxy = request.Proxy.GetProxy(new Uri(""));

var cmgr = new CredentialManagement.Credential() { Target = proxy.Host };
if (cmgr.Load())
    var credentials = new NetworkCredential(cmgr.Username, cmgr.Password);
    webClient.Proxy.Credentials = credentials;
    webClient.Credentials = credentials;

This grabs credentials from 'Credentials Manager' - which can be found via Windows - click Start then search for 'Credentials Manager'. Credentials for the proxy that were manually entered when prompted by the browser will be in the Windows Credentials section.

How to make an HTTP POST web request

Yet another way of doing it:

using (HttpClient httpClient = new HttpClient())
using (MultipartFormDataContent form = new MultipartFormDataContent())
    form.Add(new StringContent(param1), "param1");
    form.Add(new StringContent(param2), "param2");
    using (HttpResponseMessage response = await httpClient.PostAsync(url, form))
        string res = await response.Content.ReadAsStringAsync();
        return res;

This way you can easily post a stream.

HttpWebRequest-The remote server returned an error: (400) Bad Request

What type of authentication do you use? Send the credentials using the properties Ben said before and setup a cookie handler. You already allow redirection, check your webserver if any redirection occurs (NTLM auth does for sure). If there is a redirection you need to store the session which is mostly stored in a session cookie.

Send JSON via POST in C# and Receive the JSON returned?

You can also use the PostAsJsonAsync() method available in HttpClient()

   var requestObj= JsonConvert.SerializeObject(obj);_x000D_
   HttpResponseMessage response = await    client.PostAsJsonAsync($"endpoint",requestObj).ConfigureAwait(false);

Using CookieContainer with WebClient class

The HttpWebRequest modifies the CookieContainer assigned to it. There is no need to process returned cookies. Simply assign your cookie container to every web request.

public class CookieAwareWebClient : WebClient
    public CookieContainer CookieContainer { get; set; } = new CookieContainer();

    protected override WebRequest GetWebRequest(Uri uri)
        WebRequest request = base.GetWebRequest(uri);
        if (request is HttpWebRequest)
            (request as HttpWebRequest).CookieContainer = CookieContainer;
        return request;

Get host domain from URL?

You should construct your string as URI object and Authority property returns what you need.

How to post JSON to a server using C#?

Further to Sean's post, it isn't necessary to nest the using statements. By using the StreamWriter it will be flushed and closed at the end of the block so no need to explicitly call the Flush() and Close() methods:

var request = (HttpWebRequest)WebRequest.Create("http://url");
request.ContentType = "application/json";
request.Method = "POST";

using (var streamWriter = new StreamWriter(request.GetRequestStream()))
    string json = new JavaScriptSerializer().Serialize(new
                    user = "Foo",
                    password = "Baz"


var response = (HttpWebResponse)request.GetResponse();
using (var streamReader = new StreamReader(response.GetResponseStream()))
        var result = streamReader.ReadToEnd();

How to get error information when HttpWebRequest.GetResponse() fails

You can also use this library which wraps HttpWebRequest and Response into simple methods that return objects based on the results. It uses some of the techniques described in these answers and has plenty of code inspired by answers from this and similar threads. It automatically catches any exceptions, seeks to abstract as much boiler plate code needed to make these web requests as possible, and automatically deserializes the response object.

An example of what your code would look like using this wrapper is as simple as

    var response = httpClient.Get<SomeResponseObject>(request);
    if(response.StatusCode == HttpStatusCode.OK)
        //do something with the response
        console.Writeline(response.Body.Id); //where the body param matches the object you pass in as an anonymous type.  
    }else {
         //do something with the error
         console.Writelint(string.Format("{0}: {1}", response.StatusCode.ToString(), response.ErrorMessage);


Full disclosure This library is a free open source wrapper library, and I am the author of said library. I make no money off of this but have found it immensely useful over the years and am sure anyone who is still using the HttpWebRequest / HttpWebResponse classes will too.

It is not a silver bullet but supports get, post, delete with both async and non-async for get and post as well as JSON or XML requests and responses. It is being actively maintained as of 6/21/2020

Upload files with HTTPWebrequest (multipart/form-data)

Client use convert File to ToBase64String, after use Xml to promulgate to Server call, this server use File.WriteAllBytes(path,Convert.FromBase64String(dataFile_Client_sent)).

Good lucky!

Add custom header in HttpWebRequest

A simple method of creating the service, adding headers and reading the JSON response,

private static void WebRequest()
        const string WEBSERVICE_URL = "<<Web service URL>>";
            var webRequest = System.Net.WebRequest.Create(WEBSERVICE_URL);
            if (webRequest != null)
                webRequest.Method = "GET";
                webRequest.Timeout = 12000;
                webRequest.ContentType = "application/json";
                webRequest.Headers.Add("Authorization", "Basic dchZ2VudDM6cGFdGVzC5zc3dvmQ=");

                using (System.IO.Stream s = webRequest.GetResponse().GetResponseStream())
                    using (System.IO.StreamReader sr = new System.IO.StreamReader(s))
                        var jsonResponse = sr.ReadToEnd();
                        Console.WriteLine(String.Format("Response: {0}", jsonResponse));
        catch (Exception ex)

Make an HTTP request with android

As none of the answers described a way to perform requests with OkHttp, which is very popular http client nowadays for Android and Java in general, I am going to provide a simple example:

//get an instance of the client
OkHttpClient client = new OkHttpClient();

//add parameters
HttpUrl.Builder urlBuilder = HttpUrl.parse("").newBuilder();
urlBuilder.addQueryParameter("query", "stack-overflow");

String url =;

//build the request
Request request = new Request.Builder().url(url).build();

Response response = client.newCall(request).execute();

The clear advantage of this library is that it abstracts us from some low level details, providing more friendly and secure ways to interact with them. The syntax is also simplified and permits to write nice code.

.Net HttpWebRequest.GetResponse() raises exception when http status code 400 (bad request) is returned

Try this (it's VB-Code :-):


Catch exp As WebException
  Dim sResponse As String = New StreamReader(exp.Response.GetResponseStream()).ReadToEnd
End Try

C# HttpWebRequest The underlying connection was closed: An unexpected error occurred on a send

Code for WebTestPlugIn

public class Protocols : WebTestPlugin

    public override void PreRequest(object sender, PreRequestEventArgs e)
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;



Receiving JSON data back from HTTP request

Install this nuget package from Microsoft System.Net.Http.Json. It contains extension methods.

Then add using System.Net.Http.Json

Now, you'll be able to see these methods:

enter image description here

So you can now do this:

await httpClient.GetFromJsonAsync<IList<WeatherForecast>>("weatherforecast");


Sending HTTP Post request with SOAP action using org.apache.http

This is a full working example :

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

public void callWebService(String soapAction, String soapEnvBody)  throws IOException {
    // Create a StringEntity for the SOAP XML.
    String body ="<?xml version=\"1.0\" encoding=\"UTF-8\"?><SOAP-ENV:Envelope xmlns:SOAP-ENV=\"\" xmlns:ns1=\"\" xmlns:xsd=\"\" xmlns:xsi=\"\" xmlns:SOAP-ENC=\"\" SOAP-ENV:encodingStyle=\"\"><SOAP-ENV:Body>"+soapEnvBody+"</SOAP-ENV:Body></SOAP-ENV:Envelope>";
    StringEntity stringEntity = new StringEntity(body, "UTF-8");

    // Request parameters and other properties.
    HttpPost httpPost = new HttpPost("");
    httpPost.addHeader("Accept", "text/xml");
    httpPost.addHeader("SOAPAction", soapAction);

    // Execute and get the response.
    HttpClient httpClient = new DefaultHttpClient();
    HttpResponse response = httpClient.execute(httpPost);
    HttpEntity entity = response.getEntity();

    String strResponse = null;
    if (entity != null) {
        strResponse = EntityUtils.toString(entity);

Getting a Request.Headers value

if (Request.Headers["XYZComponent"].Count() > 0)

... will attempted to count the number of characters in the returned string, but if the header doesn't exist it will return NULL, hence why it's throwing an exception. Your second example effectively does the same thing, it will search through the collection of Headers and return NULL if it doesn't exist, which you then attempt to count the number of characters on:

Use this instead:

if(Request.Headers["XYZComponent"] != null)

Or if you want to treat blank or empty strings as not set then use:

if((Request.Headers["XYZComponent"] ?? "").Trim().Length > 0)

The Null Coalesce operator ?? will return a blank string if the header is null, stopping it throwing a NullReferenceException.

A variation of your second attempt will also work:

if (Request.Headers.AllKeys.Any(k => string.Equals(k, "XYZComponent")))

Edit: Sorry didn't realise you were explicitly checking for the value true:

bool isSet = Boolean.TryParse(Request.Headers["XYZComponent"], out isSet) && isSet;

Will return false if Header value is false, or if Header has not been set or if Header is any other value other than true or false. Will return true is the Header value is the string 'true'

reading HttpwebResponse json response, C#

I'd use RestSharp -

Create class to deserialize to:

public class MyObject {
    public string Id { get; set; }
    public string Text { get; set; }

And the code to get that object:

RestClient client = new RestClient("");
RestRequest request = new RestRequest("path/to/object");
request.AddParameter("id", "123");

// The above code will make a request URL of 
// ""
// You can pick and choose what you need

var response = client.Execute<MyObject>(request);

MyObject obj = response.Data;

Check out to get started.

How to send an HTTPS GET Request in C#

Add ?var1=data1&var2=data2 to the end of url to submit values to the page via GET:

using System.Net;
using System.IO;

string url = "";

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();

How to create JSON post to api using C#

Have you tried using the WebClient class?

you should be able to use

string result = "";
using (var client = new WebClient())
    client.Headers[HttpRequestHeader.ContentType] = "application/json"; 
    result = client.UploadString(url, "POST", json);

Documentation at

How to send HTTP request in java?

Google java http client has nice API for http requests. You can easily add JSON support etc. Although for simple request it might be overkill.


public class Network {

    static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();

    public void getRequest(String reqUrl) throws IOException {
        GenericUrl url = new GenericUrl(reqUrl);
        HttpRequest request = HTTP_TRANSPORT.createRequestFactory().buildGetRequest(url);
        HttpResponse response = request.execute();

        InputStream is = response.getContent();
        int ch;
        while ((ch = != -1) {
            System.out.print((char) ch);

Pure JavaScript Send POST Data Without a Form

There is an easy method to wrap your data and send it to server as if you were sending an HTML form using POST. you can do that using FormData object as following:

data = new FormData()

let request = new XMLHttpRequest();"POST", 'some_url/', true);

now you can handle the data on the server-side just like the way you deal with reugular HTML Forms.

Additional Info

It is advised that you must not set Content-Type header when sending FormData since the browser will take care of that.

Why am I getting "(304) Not Modified" error on some links when using HttpWebRequest?

I think you have not installed these features. see below in picture.

enter image description here

I also suffered from this problem some days ago. After installing this feature then I solved it. If you have not installed this feature then installed it.

Install Process:

  1. go to android studio
  2. Tools
  3. Android
  4. SDK Manager
  5. Appearance & Behavior
  6. Android SDK

The server committed a protocol violation. Section=ResponseStatusLine ERROR

In my case the IIS did not have the necessary permissions to access the relevant ASPX path.

I gave the IIS user permissions to the relevant directory and all was well.

How to pass credentials to httpwebrequest for accessing SharePoint Library

If you need to set the credentials on the fly, have a look at this source:

private ICredentials BuildCredentials(string siteurl, string username, string password, string authtype) {
    NetworkCredential cred;
    if (username.Contains(@"\")) {
        string domain = username.Substring(0, username.IndexOf(@"\"));
        username = username.Substring(username.IndexOf(@"\") + 1);
        cred = new System.Net.NetworkCredential(username, password, domain);
    } else {
        cred = new System.Net.NetworkCredential(username, password);
    CredentialCache cache = new CredentialCache();
    if (authtype.Contains(":")) {
        authtype = authtype.Substring(authtype.IndexOf(":") + 1); //remove the TMG: prefix
    cache.Add(new Uri(siteurl), authtype, cred);
    return cache;

Setting a WebRequest's body data

With HttpWebRequest.GetRequestStream

Code example from

string postData = "firstone=" + inputData;
ASCIIEncoding encoding = new ASCIIEncoding ();
byte[] byte1 = encoding.GetBytes (postData);

// Set the content type of the data being posted.
myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";

// Set the content length of the string being posted.
myHttpWebRequest.ContentLength = byte1.Length;

Stream newStream = myHttpWebRequest.GetRequestStream ();

newStream.Write (byte1, 0, byte1.Length);

From one of my own code:

var request = (HttpWebRequest)WebRequest.Create(uri);
request.Credentials = this.credentials;
request.Method = method;
request.ContentType = "application/atom+xml;type=entry";
using (Stream requestStream = request.GetRequestStream())
using (var xmlWriter = XmlWriter.Create(requestStream, new XmlWriterSettings() { Indent = true, NewLineHandling = NewLineHandling.Entitize, }))

    return (HttpWebResponse)request.GetResponse();  
catch (WebException wex)
    var httpResponse = wex.Response as HttpWebResponse;
    if (httpResponse != null)
        throw new ApplicationException(string.Format(
            "Remote server call {0} {1} resulted in a http error {2} {3}.",
            httpResponse.StatusDescription), wex);
        throw new ApplicationException(string.Format(
            "Remote server call {0} {1} resulted in an error.",
            uri), wex);
catch (Exception)

How can I get all element values from Request.Form without specifying exactly which one with .GetValues("ElementIdName")

You can get all keys in the Request.Form and then compare and get your desired values.

Your method body will look like this: -

List<int> listValues = new List<int>();
foreach (string key in Request.Form.AllKeys)
    if (key.StartsWith("List"))

Post form data using HttpWebRequest

Try this:

var request = (HttpWebRequest)WebRequest.Create("");

var postData = "thing1=hello";
    postData += "&thing2=world";
var data = Encoding.ASCII.GetBytes(postData);

request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;

using (var stream = request.GetRequestStream())
    stream.Write(data, 0, data.Length);

var response = (HttpWebResponse)request.GetResponse();

var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

C# HttpWebRequest of type "application/x-www-form-urlencoded" - how to send '&' character in content body?

As long as the server allows the ampresand character to be POSTed (not all do as it can be unsafe), all you should have to do is URL Encode the character. In the case of an ampresand, you should replace the character with %26.

.NET provides a nice way of encoding the entire string for you though:

string strNew = "&uploadfile=true&file=" + HttpUtility.UrlEncode(iCalStr);

What is the difference between HTTP status code 200 (cache) vs status code 304?

HTTP 304 is "not modified". Your web server is basically telling the browser "this file hasn't changed since the last time you requested it." Whereas an HTTP 200 is telling the browser "here is a successful response" - which should be returned when it's either the first time your browser is accessing the file or the first time a modified copy is being accessed.

For more info on status codes check out

Getting Http Status code number (200, 301, 404, etc.) from HttpWebRequest and HttpWebResponse


HttpStatusCode (the type of response.StatusCode) is an enumeration where the values of the members match the HTTP status codes, e.g.

public enum HttpStatusCode
    Moved = 301,
    OK = 200,
    Redirect = 302,

What does %5B and %5D in POST requests stand for?

They represent [ and ]. The encoding is called "URL encoding".

Adjusting HttpWebRequest Connection Timeout in C#

Something I found later which helped, is the .ReadWriteTimeout property. This, in addition to the .Timeout property seemed to finally cut down on the time threads would spend trying to download from a problematic server. The default time for .ReadWriteTimeout is 5 minutes, which for my application was far too long.

So, it seems to me:

.Timeout = time spent trying to establish a connection (not including lookup time) .ReadWriteTimeout = time spent trying to read or write data after connection established

More info: HttpWebRequest.ReadWriteTimeout Property


Per @KyleM's comment, the Timeout property is for the entire connection attempt, and reading up on it at MSDN shows:

Timeout is the number of milliseconds that a subsequent synchronous request made with the GetResponse method waits for a response, and the GetRequestStream method waits for a stream. The Timeout applies to the entire request and response, not individually to the GetRequestStream and GetResponse method calls. If the resource is not returned within the time-out period, the request throws a WebException with the Status property set to WebExceptionStatus.Timeout.

(Emphasis mine.)

What difference is there between WebClient and HTTPWebRequest classes in .NET?

Also WebClient doesn't have timeout property. And that's the problem, because dafault value is 100 seconds and that's too much to indicate if there's no Internet connection.

Workaround for that problem is here

Reasons for a 409/Conflict HTTP error when uploading a file to sharepoint using a .NET WebRequest?

We are also getting the same error while we are trying to access a same resource with in milliseconds. Like if i try to POST some data to and with in milliseconds an other request will also go for the same resource i.e. from the same user. So it'll give the 409 error.

json call with C#

If your function resides in an mvc controller u can use the below code with a dictionary object of what you want to convert to json

Json(someDictionaryObj, JsonRequestBehavior.AllowGet);

Also try and look at system.web.script.serialization.javascriptserializer if you are using .net 3.5

as for your web seems ok at first glance..

I would use something like this..

public void WebRequestinJson(string url, string postData)
    StreamWriter requestWriter;

    var webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
    if (webRequest != null)
        webRequest.Method = "POST";
        webRequest.ServicePoint.Expect100Continue = false;
        webRequest.Timeout = 20000;

        webRequest.ContentType = "application/json";
        //POST the data.
        using (requestWriter = new StreamWriter(webRequest.GetRequestStream()))

May be you can make the post and json string a parameter and use this as a generic webrequest method for all calls.

How to make an HTTP get request with parameters

My preferred way is this. It handles the escaping and parsing for you.

WebClient webClient = new WebClient();
webClient.QueryString.Add("param1", "value1");
webClient.QueryString.Add("param2", "value2");
string result = webClient.DownloadString("");

How to add parameters into a WebRequest?

I have a feeling that the username and password that you are sending should be part of the Authorization Header. So the code below shows you how to create the Base64 string of the username and password. I also included an example of sending the POST data. In my case it was a phone_number parameter.

string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(_username + ":" + _password));

HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(Request);
webRequest.Headers.Add("Authorization", string.Format("Basic {0}", credentials));
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = WebRequestMethods.Http.Post;
webRequest.AllowAutoRedirect = true;
webRequest.Proxy = null;

string data = "phone_number=19735559042"; 
byte[] dataStream = Encoding.UTF8.GetBytes(data);

request.ContentLength = dataStream.Length;
Stream newStream = webRequest.GetRequestStream();
newStream.Write(dataStream, 0, dataStream.Length);

HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader streamreader = new StreamReader(stream);
string s = streamreader.ReadToEnd();

How to ignore the certificate check when ssl

For .net core

using (var handler = new HttpClientHandler())
    // allow the bad certificate
    handler.ServerCertificateCustomValidationCallback = (request, cert, chain, errors) => true;
    using (var httpClient = new HttpClient(handler))
        await httpClient.PostAsync("the_url", null);

System.Net.WebException: The operation has timed out

proxy issue can cause this. IIS webconfig put this in

<defaultProxy useDefaultCredentials="true" enabled="true">
          <proxy usesystemdefault="True" />

Python convert decimal to hex

def main():
    result = int(input("Enter a whole, positive, number to be converted to hexadecimal: "))
    hexadecimal = ""
    while result != 0:
        remainder = changeDigit(result % 16)
        hexadecimal = str(remainder) + hexadecimal
        result = int(result / 16)

def changeDigit(digit):
    decimal =     [10 , 11 , 12 , 13 , 14 , 15 ]
    hexadecimal = ["A", "B", "C", "D", "E", "F"]
    for counter in range(7):
        if digit == decimal[counter - 1]:
            digit = hexadecimal[counter - 1]
    return digit


This is the densest I could make for converting decimal to hexadecimal. NOTE: This is in Python version 3.5.1

Set folder for classpath

If you are using Java 6 or higher you can use wildcards of this form:

java -classpath ".;c:\mylibs\*;c:\extlibs\*" MyApp

If you would like to add all subdirectories: lib\a\, lib\b\, lib\c\, there is no mechanism for this in except:

java -classpath ".;c:\lib\a\*;c:\lib\b\*;c:\lib\c\*" MyApp

There is nothing like lib\*\* or lib\** wildcard for the kind of job you want to be done.

Sort Go map values by keys

If, like me, you find you want essentially the same sorting code in more than one place, or just want to keep the code complexity down, you can abstract away the sorting itself to a separate function, to which you pass the function that does the actual work you want (which would be different at each call site, of course).

Given a map with key type K and value type V, represented as <K> and <V> below, the common sort function might look something like this Go-code template (which Go version 1 does not support as-is):

/* Go apparently doesn't support/allow 'interface{}' as the value (or
/* key) of a map such that any arbitrary type can be substituted at
/* run time, so several of these nearly-identical functions might be
/* needed for different key/value type combinations. */
func sortedMap<K><T>(m map[<K>]<V>, f func(k <K>, v <V>)) {
    var keys []<K>
    for k, _ := range m {
        keys = append(keys, k)
    sort.Strings(keys)  # or sort.Ints(keys), sort.Sort(...), etc., per <K>
    for _, k := range keys {
        v := m[k]
        f(k, v)

Then call it with the input map and a function (taking (k <K>, v <V>) as its input arguments) that is called over the map elements in sorted-key order.

So, a version of the code in the answer posted by Mingu might look like:

package main

import (

func sortedMapIntString(m map[int]string, f func(k int, v string)) {
    var keys []int
    for k, _ := range m {
        keys = append(keys, k)
    for _, k := range keys {
        f(k, m[k])

func main() {
    // Create a map for processing
    m := make(map[int]string)
    m[1] = "a"
    m[2] = "c"
    m[0] = "b"

        func(k int, v string) { fmt.Println("Key:", k, "Value:", v) })

The sortedMapIntString() function can be re-used for any map[int]string (assuming the same sort order is desired), keeping each use to just two lines of code.

Downsides include:

  • It's harder to read for people unaccustomed to using functions as first-class
  • It might be slower (I haven't done performance comparisons)

Other languages have various solutions:

  • If the use of <K> and <V> (to denote types for the key and value) looks a bit familiar, that code template is not terribly unlike C++ templates.
  • Clojure and other languages support sorted maps as fundamental data types.
  • While I don't know of any way Go makes range a first-class type such that it could be substituted with a custom ordered-range (in place of range in the original code), I think some other languages provide iterators that are powerful enough to accomplish the same thing.

PHP check if date between two dates

An other solution (with the assumption you know your date formats are always YYYY/MM/DD with lead zeros) is the max() and min() function. I figure this is okay given all the other answers assume the yyyy-mm-dd format too and it's the common naming convention for folders in file systems if ever you wanted to make sure they sorted in date order.

As others have said, given the order of the numbers you can compare the strings, no need for strtotime() function.


$biggest = max("2018/10/01","2018/10/02");

The advantage being you can stick more dates in there instead of just comparing two.

$biggest = max("2018/04/10","2019/12/02","2016/03/20");

To work out if a date is in between two dates you could compare the result of min() and max()

    // It's in the middle

It wouldn't work with any other date format, but for that one it does. No need to convert to seconds and no need for date functions.

Unrecognized attribute 'targetFramework'. Note that attribute names are case-sensitive

following 2 steps will force refresh Visual Studio and IIS Express cache and usually resolve my similar issues:

  1. Simply switch Project framework from 4+ to .Net framework 3.5 and run it
  2. If it ran successfully you can revert it back to your desired 4+ target framework and see that it will probably work again.

docker-compose up for only certain containers

I actually had a very similar challenge on my current project. That broght me to the idea of writing a small script which I called docker-compose-profile (or short: dcp). I published this today on GitLab as docker-compose-profile. So in short: I now can start several predefined docker-compose profiles using a command like dcp -p some-services "up -d". Feel free to try it out and give some feedback or suggestions for further improvements.

Row Offset in SQL Server

I use this technique for pagination. I do not fetch all the rows. For example, if my page needs to display the top 100 rows I fetch only the 100 with where clause. The output of the SQL should have a unique key.

The table has the following:

ID, KeyId, Rank

The same rank will be assigned for more than one KeyId.

SQL is select top 2 * from Table1 where Rank >= @Rank and ID > @Id

For the first time I pass 0 for both. The second time pass 1 & 14. 3rd time pass 2 and 6....

The value of the 10th record Rank & Id is passed to the next

11  21  1
14  22  1
7   11  1
6   19  2
12  31  2
13  18  2

This will have the least stress on the system

Do on-demand Mac OS X cloud services exist, comparable to Amazon's EC2 on-demand instances?

Here are some methods that may help others, though they aren't really services as much as they may be described as "methods that may, after some torture of effort or logic, lead to a claim of on-demand access to Mac OS X" (no doubt I should patent that phrase).

Fundamentally, I am inclined to believe that on-demand (per-hour) hosting does not exist, and @Erik has given information for the shortest feasible services, i.e. monthly hosting.

It seems that one may use EC2 itself, but install OS X on the instance through a lot of elbow grease.

  • This article on gives instructions for setting up OSX under Virtual Box and depends on hardware virtualization. It seems that the Cluster Compute instances (and Cluster GPU, but ignore these) are the only ones supporting hardware virtualization.
  • This article gives instructions for transferring a VirtualBox image to EC2.

Where this gets tricky is I'm not sure if this will work for a cluster compute instance. In fact, I think this is likely to be a royal pain. A similar approach may work for Rackspace or other cloud services.

I found only this site claiming on-demand Mac hosting, with a Mac Mini. It doesn't look particularly accurate: it offers free on-demand access to a Mini if one pays for a month of bandwidth. That's like free bandwidth if one rents a Mini for a month. That's not really how "on-demand" works.

Update 1: In the end, it seems that nobody offers a comparable service. An outfit called Media Temple claims they will offer the first virtual servers using Parallels, OS X Leopard, and some other stuff (in other words, I wonder if there is some caveat that makes them unique, but, without that caveat, someone else may have a usable offering).

After this search, I think that a counterpart to EC2 does not exist for the OS X operating system. It is extraordinarily unlikely that one would exist, offer a scalable solution, and yet be very difficult to find. One could set it up internally, but there's no reseller/vendor offering on-demand, hourly virtual servers. This may be disappointing, but not surprising - apparently iCloud is running on Amazon and Microsoft systems.

Difference between null and empty ("") Java String

here a is an Object but b(null) is not an Object it is a null reference

System.out.println(a instanceof Object); // true

System.out.println(b instanceof Object); // false

here is my similar answer

Non-alphanumeric list order from os.listdir()

Python for whatever reason does not come with a built-in way to have natural sorting (meaning 1, 2, 10 instead of 1, 10, 2), so you have to write it yourself:

import re
def sorted_alphanumeric(data):
    convert = lambda text: int(text) if text.isdigit() else text.lower()
    alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ] 
    return sorted(data, key=alphanum_key)

You can now use this function to sort a list:

dirlist = sorted_alphanumeric(os.listdir(...))

PROBLEMS: In case you use the above function to sort strings (for example folder names) and want them sorted like Windows Explorer does, it will not work properly in some edge cases.
This sorting function will return incorrect results on Windows, if you have folder names with certain 'special' characters in them. For example this function will sort 1, !1, !a, a, whereas Windows Explorer would sort !1, 1, !a, a.

So if you want to sort exactly like Windows Explorer does in Python you have to use the Windows built-in function StrCmpLogicalW via ctypes (this of course won't work on Unix):

from ctypes import wintypes, windll
from functools import cmp_to_key

def winsort(data):
    _StrCmpLogicalW = windll.Shlwapi.StrCmpLogicalW
    _StrCmpLogicalW.argtypes = [wintypes.LPWSTR, wintypes.LPWSTR]
    _StrCmpLogicalW.restype  = wintypes.INT

    cmp_fnc = lambda psz1, psz2: _StrCmpLogicalW(psz1, psz2)
    return sorted(data, key=cmp_to_key(cmp_fnc))

This function is slightly slower than sorted_alphanumeric().

Bonus: winsort can also sort full paths on Windows.

Alternatively, especially if you use Unix, you can use the natsort library (pip install natsort) to sort by full paths in a correct way (meaning subfolders at the correct position).

You can use it like this to sort full paths:

from natsort import natsorted, ns
dirlist = natsorted(dirlist, alg=ns.PATH | ns.IGNORECASE)

Starting with version 7.1.0 natsort supports os_sorted which internally uses either the beforementioned Windows API or Linux sorting and should be used instead of natsorted().

How to inject Javascript in WebBrowser control?

HtmlDocument doc = browser.Document;
HtmlElement head = doc.GetElementsByTagName("head")[0];
HtmlElement s = doc.CreateElement("script");
s.SetAttribute("text","function sayHello() { alert('hello'); }");

(tested in .NET 4 / Windows Forms App)

Edit: Fixed case issue in function set.

Hide horizontal scrollbar on an iframe?

This answer is only applicable for websites which use Bootstrap. The responsive embed feature of the Bootstrap takes care of the scrollbars.

<!-- 16:9 aspect ratio -->
<div class="embed-responsive embed-responsive-16by9">
  <iframe class="embed-responsive-item" src=""></iframe>


How to install a specific version of a ruby gem?

Use the -v flag:

$ gem install fog -v 1.8

Equivalent of Math.Min & Math.Max for Dates?

Now that we have LINQ, you can create an array with your two values (DateTimes, TimeSpans, whatever) and then use the .Max() extension method.

var values = new[] { Date1, Date2 }; 
var max = values.Max(); 

It reads nice, it's as efficient as Max can be, and it's reusable for more than 2 values of comparison.

The whole problem below worrying about .Kind is a big deal... but I avoid that by never working in local times, ever. If I have something important regarding times, I always work in UTC, even if it means more work to get there.

Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference

Here's a more concise answer for people that are looking for a quick reference as well as some examples using promises and async/await.

Start with the naive approach (that doesn't work) for a function that calls an asynchronous method (in this case setTimeout) and returns a message:

function getMessage() {
  var outerScopeVar;
  setTimeout(function() {
    outerScopeVar = 'Hello asynchronous world!';
  }, 0);
  return outerScopeVar;

undefined gets logged in this case because getMessage returns before the setTimeout callback is called and updates outerScopeVar.

The two main ways to solve it are using callbacks and promises:


The change here is that getMessage accepts a callback parameter that will be called to deliver the results back to the calling code once available.

function getMessage(callback) {
  setTimeout(function() {
    callback('Hello asynchronous world!');
  }, 0);
getMessage(function(message) {


Promises provide an alternative which is more flexible than callbacks because they can be naturally combined to coordinate multiple async operations. A Promises/A+ standard implementation is natively provided in node.js (0.12+) and many current browsers, but is also implemented in libraries like Bluebird and Q.

function getMessage() {
  return new Promise(function(resolve, reject) {
    setTimeout(function() {
      resolve('Hello asynchronous world!');
    }, 0);

getMessage().then(function(message) {

jQuery Deferreds

jQuery provides functionality that's similar to promises with its Deferreds.

function getMessage() {
  var deferred = $.Deferred();
  setTimeout(function() {
    deferred.resolve('Hello asynchronous world!');
  }, 0);
  return deferred.promise();

getMessage().done(function(message) {


If your JavaScript environment includes support for async and await (like Node.js 7.6+), then you can use promises synchronously within async functions:

function getMessage () {
    return new Promise(function(resolve, reject) {
        setTimeout(function() {
            resolve('Hello asynchronous world!');
        }, 0);

async function main() {
    let message = await getMessage();


What are the applications of binary trees?

The organization of Morse code is a binary tree.



Python 2.7: %d, %s, and float()

Try the following:

print "First is: %f" % (first)
print "Second is: %f" % (second)

I am unsure what answer is. But apart from that, this will be:

print "DONE: %f DIVIDED BY %f EQUALS %f, SWEET MATH BRO!" % (first, second, ans)

There's a lot of text on Format String Specifiers. You can google it and get a list of specifiers. One thing I forgot to note:

If you try this:

print "First is: %s" % (first)

It converts the float value in first to a string. So that would work as well.

How to get video duration, dimension and size in PHP?

If you use Wordpress you can just use the wordpress build in function with the video id provided wp_get_attachment_metadata($videoID):


helped me a lot. thats why i'm posting it, although its just for wordpress users.

makefile:4: *** missing separator. Stop

make has a very stupid relationship with tabs. All actions of every rule are identified by tabs. And, no, four spaces don't make a tab. Only a tab makes a tab.

To check, I use the command cat -e -t -v makefile_name.

It shows the presence of tabs with ^I and line endings with $. Both are vital to ensure that dependencies end properly and tabs mark the action for the rules so that they are easily identifiable to the make utility.


Kaizen ~/so_test $ cat -e -t -v  mk.t
all:ll$      ## here the $ is end of line ...                   
ll:ll.c   $
^Igcc  -c  -Wall -Werror -02 c.c ll.c  -o  ll  $@  $<$ 
## the ^I above means a tab was there before the action part, so this line is ok .
clean :$
   \rm -fr ll$
## see here there is no ^I which means , tab is not present .... 
## in this case you need to open the file again and edit/ensure a tab 
## starts the action part

The EntityManager is closed

// first need to reset current manager
// and then get new
$em = $this->getContainer()->get("doctrine");
// or in this way, depending of your environment:
$em = $this->getDoctrine();

Build error: You must add a reference to System.Runtime

The only way that worked for me - add the assembly to web.config

<compilation debug="true" targetFramework="4.5">
    <add assembly="System.Runtime, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />   

PHP parse/syntax errors; and how to solve them

unexpected ':', expecting ',' or ')'

If attempting to use PHP 8's new named parameter functionality in a version of PHP < 8 this error will occur:



  1. Upgrade your version of PHP tp PHP 8.8.0 or higher
  2. Do not use named parameters (pass the parameters in in the order they are expected)

Is it possible to make input fields read-only through CSS?

This is not possible with css, but I have used one css trick in one of my website, please check if this works for you.

The trick is: wrap the input box with a div and make it relative, place a transparent image inside the div and make it absolute over the input text box, so that no one can edit it.


.txtBox input{
.txtBox img{


<div class="txtBox">
<input name="" type="text" value="Text Box" />
<img src="" width="250" height="25" alt="" />

jsFiddle File

Difference between static memory allocation and dynamic memory allocation

Static memory allocation is allocated memory before execution pf program during compile time. Dynamic memory alocation is alocated memory during execution of program at run time.

How to show progress dialog in Android?

You better try with AsyncTask

Sample code -

private class YourAsyncTask extends AsyncTask<Void, Void, Void> {
    private ProgressDialog dialog;

    public YourAsyncTask(MyMainActivity activity) {
        dialog = new ProgressDialog(activity);

    protected void onPreExecute() {
        dialog.setMessage("Doing something, please wait.");;
    protected Void doInBackground(Void... args) {
        // do background work here
        return null;
    protected void onPostExecute(Void result) {
         // do UI work here
        if (dialog.isShowing()) {

Use the above code in your Login Button Activity. And, do the stuff in doInBackground and onPostExecute


ProgressDialog is integrated with AsyncTask as you said your task takes time for processing.


ProgressDialog class was deprecated as of API 26

Getting Class type from String

It should be:

Class.forName(String classname)

chrome undo the action of "prevent this page from creating additional dialogs"

Turning Hardware Acceleration OFF seems to be the setting that affects popups & dialogs.

Chrome was continually hiding Dialog Windows when I needed to respond Yes or No to things, also when I needed to Rename folders in my bookmarks panel. After weeks of doing this. I disabled all the Chrome helpers in Settings, Also In windows 10 I switched Window Snapping off. It has done something to put the popups and dialogs back in the Viewport.

When this bug is happening, I was able to shut a tab by first pressing Enter before clicking the tab close X button. The browser had an alert box, hidden which needed a response from the user.

Switching Hardware Accleration Off and back On, Killing the Chrome process and switching all the other Helpers Off and back has fixed it for me... It must be in chrome itself because Ive just gone into a Chrome window in the Mac and it has now stopped the problem, without any intervention. Im guessing flicking the chrome settings on/off/on has caused it to reposition the dialogs. I cant get the browser to repeat the fault now...

Python: 'ModuleNotFoundError' when trying to import module from imported package

For me when I created a file and saved it as python file, I was getting this error during importing. I had to create a filename with the type ".py" , like and then save it as a python file. post trying to import the file worked for me.

Easiest way to toggle 2 classes in jQuery

The easiest solution is to toggleClass() both classes individually.

Let's say you have an icon:

    <i id="target" class="fa fa-angle-down"></i>

To toggle between fa-angle-down and fa-angle-up do the following:


Since we had fa-angle-down at the beginning without fa-angle-up each time you toggle both, one leaves for the other to appear.

How can I start an Activity from a non-Activity class?

I don't know if this is good practice or not, but casting a Context object to an Activity object compiles fine.

Try this: ((Activity) mContext).startActivity(...)

Remove git mapping in Visual Studio 2015

The above answer did not work for me. The registry entries would just be automatically re-added when I opened the solution in Visual Studio. I found the resolution in one of the links in Matthews answer though so credit still goes to him for the correct answer.

Remove Git binding from Visual Studio 2013 solution?

Remove the hidden .git folder in your solutionfolder.

I also removed the .gitattributes and .gitignore files just to keep my folder clean.

Integer value comparison

To figure out if an Integer is greater than 0, you can:

  • check if compareTo(O) returns a positive number:

    if (count.compareTo(0) > 0)

    But that looks pretty silly, doesn't it? Better just...

  • use autoboxing1:

    if (count > 0)

    This is equivalent to:

    if (count.intValue() > 0)

    It is important to note that "==" is evaluated like this, with the Integer operand unboxed rather than the int operand boxed. Otherwise, count == 0 would return false when count was initialized as new Integer(0) (because "==" tests for reference equality).

1Technically, the first example uses autoboxing (before Java 1.5 you couldn't pass an int to compareTo) and the second example uses unboxing. The combined feature is often simply called "autoboxing" for short, which is often then extended into calling both types of conversions "autoboxing". I apologize for my lax usage of terminology.

How can I ask the Selenium-WebDriver to wait for few seconds in Java?

If using webdriverJs (node.js),

driver.findElement('btnCalculate')).click().then(function() {

The code above makes browser wait for 5 seconds after clicking the button.

what's data-reactid attribute in html?

That's the HTML data attribute. See this for more detail:

Basically it's just a container of your custom data while still making the HTML valid. It's data- plus some unique identifier.

How to add new line in Markdown presentation?

You could use &nbsp; in R markdown to create a new blank line.

For example, in your .Rmd file:

I want 3 new lines: 


End of file. 

How to hide the border for specified rows of a table?

You can simply add these lines of codes here to hide a row,

Either you can write border:0 or border-style:hidden; border: none or it will happen the same thing

<style type="text/css">_x000D_
              table, th, td {_x000D_
               border: 1px solid;_x000D_
              tr.hide_all > td, td.hide_all{_x000D_
                 border: 0;_x000D_
      <tr class= hide_all>_x000D_

running these lines of codes can solve the problem easily

SQL query to make all data in a column UPPER CASE?

If you want to only update on rows that are not currently uppercase (instead of all rows), you'd need to identify the difference using COLLATE like this:

SET    MyColumn = UPPER(MyColumn)
WHERE  MyColumn != UPPER(MyColumn) COLLATE Latin1_General_CS_AS 

A Bit About Collation

Cases sensitivity is based on your collation settings, and is typically case insensitive by default.

Collation can be set at the Server, Database, Column, or Query Level:

-- Server
-- Database
SELECT name, collation_name FROM sys.databases
-- Column 

Collation Names specify how a string should be encoded and read, for example:

  • Latin1_General_CI_AS ? Case Insensitive
  • Latin1_General_CS_AS ? Case Sensitive

Changing line colors with ggplot()

color and fill are separate aesthetics. Since you want to modify the color you need to use the corresponding scale:

d + scale_color_manual(values=c("#CC6666", "#9999CC"))

is what you want.

Setting Icon for wpf application (VS 08)

After getting a XamlParseException with message: 'Provide value on 'System.Windows.Baml2006.TypeConverterMarkupExtension' with the given solutions, setting the icon programmatically worked for me. This is how I did it:

  1. Put the icon in a folder <icon_path> in the project directory
  2. Mimic the folder path <icon_path> in the solution
  3. Add a new item (your icon) in the solution folder you created
  4. Add the following code in the WPF window's code behind:

Icon = new BitmapImage(new Uri("<icon_path>", UriKind.Relative));

Please inform me if you have any difficulties implementing this solution so I can help.

How to use Python's "easy_install" on Windows ... it's not so easy

One problem is that easy_install is set up to download and install .egg files or source distributions (contained within .tgz, .tar, .tar.gz, .tar.bz2, or .zip files). It doesn't know how to deal with the PyWin32 extensions because they are put within a separate installer executable. You will need to download the appropriate PyWin32 installer file (for Python 2.7) and run it yourself. When you run easy_install again (provided you have it installed right, like in Sergio's instructions), you should see that your winpexpect package has been installed correctly.

Since it's Windows and open source we are talking about, it can often be a messy combination of install methods to get things working properly. However, easy_install is still better than hand-editing configuration files, for sure.

Modulo operator in Python

same as a normal modulo 3.14 % 6.28 = 3.14, just like 3.14%4 =3.14 3.14%2 = 1.14 (the remainder...)

JQuery - Call the jquery button click event based on name property

You can use normal CSS selectors to select an element by name using jquery. Like this:

Button Code
<button type="button" name="mybutton">Click Me!</button>

Selector & Event Bind Code
$("button[name='mybutton']").click(function() {});

jQuery hasAttr checking to see if there is an attribute on an element

var attr = $(this).attr('name');

// For some browsers, `attr` is undefined; for others,
// `attr` is false.  Check for both.
if (typeof attr !== typeof undefined && attr !== false) {
    // ...

Strangest language feature

Perl’s many built-in variables:

  • $#not a comment!
  • $0, $$, and $? — just like the shell variables by the same name
  • $`, $&, and $' — weird matching variables
  • $" and $, — weird variables for list- and output-field-separators
  • $! — like errno as a number but strerror(errno) as a string
  • $_the stealth variable, always used and never seen
  • $#_ — index number of the last subroutine argument... maybe
  • @_ — the (non)names of the current function... maybe
  • $@ — the last-raised exception
  • %:: — the symbol table
  • $:, $^, $~, $-, and $= — something to do with output formats
  • $. and $% — input line number, output page number
  • $/ and $\ — input and output record separators
  • $| — output buffering controller
  • $[ — change your array base from 0-based to 1-based to 42-based: WHEEE!
  • $}nothing at all, oddly enough!
  • $<, $>, $(, $) — real and effective UIDs and GIDs
  • @ISA — names of current package’s direct superclasses
  • $^T — script start-up time in epoch seconds
  • $^O — current operating system name
  • $^V — what version of Perl this is

There’s a lot more where those came from. Read the complete list here.

Manage toolbar's navigation and back button from fragment in android

Probably the cleanest solution:

abstract class NavigationChildFragment : Fragment() {

    abstract fun onCreateChildView(inflater: LayoutInflater,
                                   container: ViewGroup?,
                                   savedInstanceState: Bundle?): View?

    override fun onCreateView(inflater: LayoutInflater,
                              container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        val activity = activity as? MainActivity
        return onCreateChildView(inflater, container, savedInstanceState)

    override fun onDestroyView() {
        val activity = activity as? MainActivity

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        val activity = activity as? MainActivity
        return when (item.itemId) {
   -> {
            else              -> super.onOptionsItemSelected(item)

Just use this class as parent for all Fragments that should support navigation.

wkhtmltopdf: cannot connect to X server

Pay attention: your file could be or wkhtmltopdf, check it on second step

You must copy it into directory : /usr/local/bin, make sur it's executable and add symlink of like :

1- the command :

sudo apt-get install wkhtmltopdf

2 - insert the binary in directory /usr/bin so the browser can't have permission to execute in this directory. You must copy the to directory /usr/local/bin cause the browser have permission in this directory like:

sudo cp /usr/bin/ /usr/local/bin/

3 - After make sur the binary have permission of execution like :

sudo chmod a+x /usr/local/bin/

4 - so now you can test, it's work like:

/usr/local/bin/ google.pdf

it make download the pdf in the current directory in your terminal

5 - Optional now you can add symlink in your directory /usr/local/bin like

ln -s /usr/local/bin/ /usr/local/bin/wkhtmltopdf

How do I check to see if a value is an integer in MySQL?

for me the only thing that works is:

RETURN SIN REGEXP '^(-|\\+){0,1}([0-9]+\\.[0-9]*|[0-9]*\\.[0-9]+|[0-9]+)$';

from kevinclark all other return useless stuff for me in case of 234jk456 or 12 inches

Laravel - check if Ajax request

public function index()
        return Redirect::to('login');

    if(Request::ajax()) // This is check ajax request
      return $JSON;

    $data = array();
    $data['records'] = $this->table->fetchAll();


How to downgrade php from 7.1.1 to 5.6 in xampp 7.1.1?

This solution is Only for local system / localhost on windows:

The simplest way to install xampp 5.6.X version as per your requirement in other windows drive then run xampp 5.6.X services from it's control panel for php 5.6 version.

NOTE: If you already have xampp (any other version) on your system then please close that xampp's services then start xampp 5.6.x services otherwise this solution will not work.

You can download your required (xampp 5.6 as per question) xampp version from below link:

I have used this solution many times, it worked like charm. I hope this will also help you. Thank you to ask this question.

How to close a window using jQuery

just window.close() is OK, why should write in jQuery?

position fixed is not working

if a parent container contains transform this could happen. try commenting them

-webkit-transform: translate3d(0,0,0);
transform: translate3d(0,0,0);

jquery background-color change on focus and blur

in code there should be coma"," not colon ":"

the code must be $(this).css({'background-color' , '#FFFFEE'});

i hope it helps.

regards Saleha

Error including image in Latex

I had the same problem, caused by a clash between the graphicx package and an inclusion of the epsfig package that survived the ages...

Please check that there is no inclusion of epsfig, it is deprecated.

Catch Ctrl-C in C

Set up a trap (you can trap several signals with one handler):

signal (SIGQUIT, my_handler);
signal (SIGINT, my_handler);

Handle the signal however you want, but be aware of limitations and gotchas:

void my_handler (int sig)
  /* Your code here. */

Html.DropDownList - Disabled/Readonly

try with @disabled and jquery, in that way you can get the value on the Controller.

Html.DropDownList("Types", Model.Types, new {@class = "your_class disabled", @disabled= "disabled" })

Add a class called "disabled" so you can enabled by searching that class(in case of multiples disabled fields), then you can use a "setTimeout" in case of not entering controller by validation attributes


  function clickSubmit() {
    $("select.disabled").attr("disabled", false);
    setTimeout(function () {
        $("select.disabled").attr("disabled", true);
    }, 500);

submit button like this.

 <button type="submit" value="Submit" onclick="clickSubmit();">Save</button>

in case of inputs, just use @readonly="readonly"

@Html.TextBoxFor("Types",Model.Types, new { @class = "form-control", @readonly= "readonly" })

How to shrink/purge ibdata1 file in MySQL

As already noted you can't shrink ibdata1 (to do so you need to dump and rebuild), but there's also often no real need to.

Using autoextend (probably the most common size setting) ibdata1 preallocates storage, growing each time it is nearly full. That makes writes faster as space is already allocated.

When you delete data it doesn't shrink but the space inside the file is marked as unused. Now when you insert new data it'll reuse empty space in the file before growing the file any further.

So it'll only continue to grow if you're actually needing that data. Unless you actually need the space for another application there's probably no reason to shrink it.

How do I space out the child elements of a StackPanel?

The UniformGrid might not be available in Silverlight, but someone has ported it from WPF.

What is the difference between a framework and a library?

Actually these terms can mean a lot of different things depending the context they are used.

For example, on Mac OS X frameworks are just libraries, packed into a bundle. Within the bundle you will find an actual dynamic library (libWhatever.dylib). The difference between a bare library and the framework on Mac is that a framework can contain multiple different versions of the library. It can contain extra resources (images, localized strings, XML data files, UI objects, etc.) and unless the framework is released to public, it usually contains the necessary .h files you need to use the library.

Thus you have everything within a single package you need to use the library in your application (a C/C++/Objective-C library without .h files is pretty useless, unless you write them yourself according to some library documentation), instead of a bunch of files to move around (a Mac bundle is just a directory on the Unix level, but the UI treats it like a single file, pretty much like you have JAR files in Java and when you click it, you usually don't see what's inside, unless you explicitly select to show the content).

Wikipedia calls framework a "buzzword". It defines a software framework as

A software framework is a re-usable design for a software system (or subsystem). A software framework may include support programs, code libraries, a scripting language, or other software to help develop and glue together the different components of a software project. Various parts of the framework may be exposed through an API..

So I'd say a library is just that, "a library". It is a collection of objects/functions/methods (depending on your language) and your application "links" against it and thus can use the objects/functions/methods. It is basically a file containing re-usable code that can usually be shared among multiple applications (you don't have to write the same code over and over again).

A framework can be everything you use in application development. It can be a library, a collection of many libraries, a collection of scripts, or any piece of software you need to create your application. Framework is just a very vague term.

Here's an article about some guy regarding the topic "Library vs. Framework". I personally think this article is highly arguable. It's not wrong what he's saying there, however, he's just picking out one of the multiple definitions of framework and compares that to the classic definition of library. E.g. he says you need a framework for sub-classing. Really? I can have an object defined in a library, I can link against it, and sub-class it in my code. I don't see how I need a "framework" for that. In some way he rather explains how the term framework is used nowadays. It's just a hyped word, as I said before. Some companies release just a normal library (in any sense of a classical library) and call it a "framework" because it sounds more fancy.

Python Function to test ping

Adding on to the other answers, you can check the OS and decide whether to use "-c" or "-n":

import os, platform
host = ""
os.system("ping " + ("-n 1 " if  platform.system().lower()=="windows" else "-c 1 ") + host)

This will work on Windows, OS X, and Linux

You can also use sys:

import os, sys
host = ""
os.system("ping " + ("-n 1 " if  sys.platform().lower()=="win32" else "-c 1 ") + host)

Flattening a shallow list in Python

In Python 2.6, using chain.from_iterable():

>>> from itertools import chain
>>> list(chain.from_iterable(mi.image_set.all() for mi in h.get_image_menu()))

It avoids creating of intermediate list.

TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

What the error is telling, is that you can't convert an entire list into an integer. You could get an index from the list and convert that into an integer:

x = ["0", "1", "2"] 
y = int(x[0]) #accessing the zeroth element

If you're trying to convert a whole list into an integer, you are going to have to convert the list into a string first:

x = ["0", "1", "2"]
y = ''.join(x) # converting list into string
z = int(y)

If your list elements are not strings, you'll have to convert them to strings before using str.join:

x = [0, 1, 2]
y = ''.join(map(str, x))
z = int(y)

Also, as stated above, make sure that you're not returning a nested list.

Multiple line comment in Python

#Single line


multi-line comment

jQuery autocomplete with callback ajax json

Perfectly good example in the Autocomplete docs with source code.


  $(function() {
    function log( message ) {
      $( "<div>" ).text( message ).prependTo( "#log" );
      $( "#log" ).scrollTop( 0 );

    $( "#city" ).autocomplete({
      source: function( request, response ) {
          url: "",
          dataType: "jsonp",
          data: {
            q: request.term
          success: function( data ) {
            response( data );
      minLength: 3,
      select: function( event, ui ) {
        log( ui.item ?
          "Selected: " + ui.item.label :
          "Nothing selected, input was " + this.value);
      open: function() {
        $( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
      close: function() {
        $( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );


<div class="ui-widget">
  <label for="city">Your city: </label>
  <input id="city">
  Powered by <a href=""></a>

<div class="ui-widget" style="margin-top:2em; font-family:Arial">
  <div id="log" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></div>

How to count the number of lines of a string in javascript

Hmm yeah... what you're doing is absolutely wrong. When you say str.split("\r\n|\r|\n") it will try to find the exact string "\r\n|\r|\n". That's where you're wrong. There's no such occurance in the whole string. What you really want is what David Hedlund suggested:

lines = str.split(/\r\n|\r|\n/);
return lines.length;

The reason is that the split method doesn't convert strings into regular expressions in JavaScript. If you want to use a regexp, use a regexp.

How to programmatically set SelectedValue of Dropdownlist when it is bound to XmlDataSource

DropDownList1.Items.FindByValue(stringValue).Selected = true; 

should work.

How do I get the first element from an IEnumerable<T> in .net?

If your IEnumerable doesn't expose it's <T> and Linq fails, you can write a method using reflection:

public static T GetEnumeratedItem<T>(Object items, int index) where T : class
  T item = null;
  if (items != null)
    System.Reflection.MethodInfo mi = items.GetType()
    if (mi != null)
      object o = mi.Invoke(items, null);
      if (o != null)
        System.Reflection.MethodInfo mn = o.GetType()
        if (mn != null)
          object next = mn.Invoke(o, null);
          while (next != null && next.ToString() == "True")
            if (index < 1)
              System.Reflection.PropertyInfo pi = o
              if (pi != null) item = pi
                .GetValue(o, null) as T;
  return item;

How to check the version before installing a package using apt-get?

apt-cache policy <package-name>

$ apt-cache policy redis-server
  Installed: (none)
  Candidate: 2:2.8.4-2
  Version table:
     2:2.8.4-2 0
        500 trusty/universe amd64 Packages

apt-get install -s <package-name>

$ apt-get install -s redis-server
NOTE: This is only a simulation!
      apt-get needs root privileges for real execution.
      Keep also in mind that locking is deactivated,
      so don't depend on the relevance to the real current situation!
Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following extra packages will be installed:
  libjemalloc1 redis-tools
The following NEW packages will be installed:
  libjemalloc1 redis-server redis-tools
0 upgraded, 3 newly installed, 0 to remove and 3 not upgraded.
Inst libjemalloc1 (3.5.1-2 Ubuntu:14.04/trusty [amd64])
Inst redis-tools (2:2.8.4-2 Ubuntu:14.04/trusty [amd64])
Inst redis-server (2:2.8.4-2 Ubuntu:14.04/trusty [amd64])
Conf libjemalloc1 (3.5.1-2 Ubuntu:14.04/trusty [amd64])
Conf redis-tools (2:2.8.4-2 Ubuntu:14.04/trusty [amd64])
Conf redis-server (2:2.8.4-2 Ubuntu:14.04/trusty [amd64])

apt-cache show <package-name>

$ apt-cache show redis-server
Package: redis-server
Priority: optional
Section: universe/misc
Installed-Size: 744
Maintainer: Ubuntu Developers <[email protected]>
Original-Maintainer: Chris Lamb <[email protected]>
Architecture: amd64
Source: redis
Version: 2:2.8.4-2
Depends: libc6 (>= 2.14), libjemalloc1 (>= 2.1.1), redis-tools (= 2:2.8.4-2), adduser
Filename: pool/universe/r/redis/redis-server_2.8.4-2_amd64.deb
Size: 267446
MD5sum: 066f3ce93331b876b691df69d11b7e36
SHA1: f7ffbf228cc10aa6ff23ecc16f8c744928d7782e
SHA256: 2d273574f134dc0d8d10d41b5eab54114dfcf8b716bad4e6d04ad8452fe1627d
Description-en: Persistent key-value database with network interface
 Redis is a key-value database in a similar vein to memcache but the dataset
 is non-volatile. Redis additionally provides native support for atomically
 manipulating and querying data structures such as lists and sets.
 The dataset is stored entirely in memory and periodically flushed to disk.
Description-md5: 9160ed1405585ab844f8750a9305d33f
Origin: Ubunt

dpkg -l <package-name>

$ dpkg -l nginx
| Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend
|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)
||/ Name                                     Version                   Architecture              Description
ii  nginx                                    1.6.2-1~trusty            amd64                     high performance web server

How do I get the base URL with PHP?

Edited at @user3832931 's answer to include server port..

to form URLs like 'https://localhost:8000/folder/'


How to Make Laravel Eloquent "IN" Query?

If you are using Query builder then you may use a blow

DB::table(Newsletter Subscription)
->whereIn('id', $send_users_list)

If you are working with Eloquent then you can use as below

$sendUsersList = Newsletter Subscription:: select ('*')
                ->whereIn('id', $send_users_list)

Where do I find old versions of Android NDK?

I successfully opened gstreamer SDK tutorials in Eclipse.

All I needed is to use an older version of ndk. specificly 9d.

(10c and 10d does not work, 10b - works just for tutorial-1 )

9d does work for all tutorials ! and you can:

  1. Download it from:

  2. Extract it.

  3. set it in eclipse->window->preferences->Android->NDK->NDK location.

  4. build - (ctrl+b).

"Uncaught TypeError: Illegal invocation" in Chrome

You can also use:

var obj = {
    alert: alert.bind(window)
obj.alert('I´m an alert!!');

Attaching click to anchor tag in angular

You just need to add !! before your click method handler call: (click)="!!onGoToPage2()". The !! will prevent the default action from happening by converting the return of your method to a boolean. If it's a void method, then this will become false.

How to commit changes to a new branch

If I understand right, you've made a commit to changed_branch and you want to copy that commit to other_branch? Easy:

git checkout other_branch
git cherry-pick changed_branch

Get Element value with minidom with Python

you can use something like this.It worked out for me

doc = parse('C:\\eve.xml')
my_node_list = doc.getElementsByTagName("name")
my_n_node = my_node_list[0]
my_child = my_n_node.firstChild
my_text = 
print my_text

How to convert a file into a dictionary?

d = {}
with open("file.txt") as f:
    for line in f:
       (key, val) = line.split()
       d[int(key)] = val

Razor-based view doesn't see referenced assemblies

in spacename models, yourClassModel, add public before name class

public class yourClassModel{

convert:not authorized `aaaa` @ error/constitute.c/ReadImage/453

The answer with highest votes (I have not enough reputation to add comment there) suggests to comment out the MVG line, but have in mind this:


ImageMagick supports ".svg/.mvg" files which means that attackers can craft code in a scripting language, e.g. MSL (Magick Scripting Language) and MVG (Magick Vector Graphics), upload it to a server disguised as an image file and force the software to run malicious commands on the server side as described above. For example adding the following commands in a file and uploading it to a webserver that uses a vulnerable ImageMagick version will result in running the command "ls -la" on the server.


push graphic-context viewbox 0 0 640 480 fill 'url("|ls "-la)' pop graphic-context


Any version below 7.0.1-2 or 6.9.4-0 is potentially vulnerable and affected parties should as soon as possible upgrade to the latest ImageMagick version.


What is the runtime performance cost of a Docker container?

Here's some more benchmarks for Docker based memcached server versus host native memcached server using Twemperf benchmark tool with 5000 connections and 20k connection rate

Connect time overhead for docker based memcached seems to agree with above whitepaper at roughly twice native speed.

Twemperf Docker Memcached

Connection rate: 9817.9 conn/s
Connection time [ms]: avg 341.1 min 73.7 max 396.2 stddev 52.11
Connect time [ms]: avg 55.0 min 1.1 max 103.1 stddev 28.14
Request rate: 83942.7 req/s (0.0 ms/req)
Request size [B]: avg 129.0 min 129.0 max 129.0 stddev 0.00
Response rate: 83942.7 rsp/s (0.0 ms/rsp)
Response size [B]: avg 8.0 min 8.0 max 8.0 stddev 0.00
Response time [ms]: avg 28.6 min 1.2 max 65.0 stddev 0.01
Response time [ms]: p25 24.0 p50 27.0 p75 29.0
Response time [ms]: p95 58.0 p99 62.0 p999 65.0

Twemperf Centmin Mod Memcached

Connection rate: 11419.3 conn/s
Connection time [ms]: avg 200.5 min 0.6 max 263.2 stddev 73.85
Connect time [ms]: avg 26.2 min 0.0 max 53.5 stddev 14.59
Request rate: 114192.6 req/s (0.0 ms/req)
Request size [B]: avg 129.0 min 129.0 max 129.0 stddev 0.00
Response rate: 114192.6 rsp/s (0.0 ms/rsp)
Response size [B]: avg 8.0 min 8.0 max 8.0 stddev 0.00
Response time [ms]: avg 17.4 min 0.0 max 28.8 stddev 0.01
Response time [ms]: p25 12.0 p50 20.0 p75 23.0
Response time [ms]: p95 28.0 p99 28.0 p999 29.0

Here's bencmarks using memtier benchmark tool

memtier_benchmark docker Memcached

4         Threads
50        Connections per thread
10000     Requests per thread
Type        Ops/sec     Hits/sec   Misses/sec      Latency       KB/sec
Sets       16821.99          ---          ---      1.12600      2271.79
Gets      168035.07    159636.00      8399.07      1.12000     23884.00
Totals    184857.06    159636.00      8399.07      1.12100     26155.79

memtier_benchmark Centmin Mod Memcached

4         Threads
50        Connections per thread
10000     Requests per thread
Type        Ops/sec     Hits/sec   Misses/sec      Latency       KB/sec
Sets       28468.13          ---          ---      0.62300      3844.59
Gets      284368.51    266547.14     17821.36      0.62200     39964.31
Totals    312836.64    266547.14     17821.36      0.62200     43808.90

How to Handle Button Click Events in jQuery?


Eclipse : Failed to connect to remote VM. Connection refused.

As suat said, most of the time the connection refused is due to the fact that the port you set up is in use or there is a difference between the port number in your remote application debugging configuration in Eclipse and the port number used in the address attribute in


Check those things. Thanks!

Android studio takes too much memory

To run Android envirorment on low configuration machine.

  1. Close the uncessesory web tabs in browser
  2. For Antivirus users, exclude the build folder which is auto generated
  3. Android studio have 1.2 Gb default heap can decrease to 512 MB

Help > Edit custom VM options


Layouts performace will be speed up

  1. For Gradle one of the core component in Android studio Mkae sure like right now 3.0beta is latest one

Below tips can affect the code quality so please use with cautions:

  1. Studio contain Power safe Mode when turned on it will close background operations that lint , code complelitions and so on.

  2. You can run manually lint check when needed ./gradlew lint

  3. Most of are using Android emulators on average it consume 2 GB RAM so if possible use actual Android device these will reduce your resource load on your computer. Alternatively you can reduce the RAM of the emulator and it will automatically reduce the virtual memory consumption on your computer. you can find this in virtual device configuration and advance setting.

  4. Gradle offline mode is a feature for bandwidth limited users to disable the downloading of build dependencies. It will reduce the background operation that will help to increase the performance of Android studio.

  5. Android studio offers an optimization to compile multiple modules in parallel. On low RAM machines this feature will likely have a negative impact on the performance. You can disable it in the compiler settings dialog.

Why my $.ajax showing "preflight is invalid redirect error"?

I received the same error when I tried to call https web service as http webservice.

e.g when I call url ''
which should be ''

This error is produced because of redirection status 302 when you try to call http instead of https.

return SQL table as JSON in python

If you are using an MSSQL Server 2008 and above, you can perform your SELECT query to return json by using the FOR JSON AUTO clause E.G

SELECT name, surname FROM users FOR JSON AUTO

Will return Json as

[{"name": "Jane","surname": "Doe" }, {"name": "Foo","surname": "Samantha" }, ..., {"name": "John", "surname": "boo" }]

How to install a previous exact version of a NPM package?

I have a general way to solve this type of problems, which could be helpful too, especially when cloning repositories to run them locally, but requires a little more analysis of the versions.

With the package npm-check-updates I verify the versions of the packages (according to the package.json file) that are not declared in their latest available versions, as shown in the figure (

enter image description here

With this information we can verify the update status of the different packages and make decisions as to which packages to upgrade / degrade and which ones do not.

Assuming that we decided to update all the packages as they are listed, we can use the ncu -u command which only modifies your package.json file. Run npm install to update your installed packages and package-lock.json.

Then, depending on the requirements of the repository, we can refine what is needed, installing the specific versions with npm view <package> versions and npm install <package>@<version>

log4j: Log output of a specific class to a specific appender

An example:

log4j.rootLogger=ERROR, logfile

log4j.appender.logfile.layout.ConversionPattern=%-6r %d{ISO8601} %-5p %40.40c %x - %m\n, myappender

log4j.appender.myappender.layout.ConversionPattern=%-6r %d{ISO8601} %-5p %40.40c %x - %m\n

PHP isset() with multiple parameters

You just need:

if (!empty($_POST['search_term']) && !empty($_POST['postcode']))

isset && !empty is redundant.

copying all contents of folder to another folder using batch file?

xcopy.exe is the solution here. It's built into Windows.

xcopy /s c:\Folder1 d:\Folder2

You can find more options at

How to add a spinner icon to button when it's in the Loading state?

Here is a full-fledged css solution inspired by Bulma. Just add

    .button {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      position: relative;
      min-width: 200px;
      max-width: 100%;
      min-height: 40px;
      text-align: center;
      cursor: pointer;

    @-webkit-keyframes spinAround {
      from {
        -webkit-transform: rotate(0deg);
        transform: rotate(0deg);
      to {
        -webkit-transform: rotate(359deg);
        transform: rotate(359deg);
    @keyframes spinAround {
      from {
        -webkit-transform: rotate(0deg);
        transform: rotate(0deg);
      to {
        -webkit-transform: rotate(359deg);
        transform: rotate(359deg);
    } {
      text-indent: -9999px;
      box-shadow: none;
      font-size: 1rem;
      height: 2.25em;
      line-height: 1.5;
      vertical-align: top;
      padding-bottom: calc(0.375em - 1px);
      padding-left: 0.75em;
      padding-right: 0.75em;
      padding-top: calc(0.375em - 1px);
      white-space: nowrap;
    }  {
      -webkit-animation: spinAround 500ms infinite linear;
      animation: spinAround 500ms infinite linear;
      border: 2px solid #dbdbdb;
      border-radius: 290486px;
      border-right-color: transparent;
      border-top-color: transparent;
      content: "";
      display: block;
      height: 1em;
      position: relative;
      width: 1em;

Get combobox value in Java swing

Method Object JComboBox.getSelectedItem() returns a value that is wrapped by Object type so you have to cast it accordingly.


YourType varName = (YourType)comboBox.getSelectedItem();`
String value = comboBox.getSelectedItem().toString();

Float sum with javascript

(parseFloat('2.3') + parseFloat('2.4')).toFixed(1);

its going to give you solution i suppose

Error retrieving parent for item: No resource found that matches the given name '@android:style/TextAppearance.Holo.Widget.ActionBar.Title'

<style name="Theme.IOSched" parent="android:style/Theme.Holo.Light">
    <item name="android:windowBackground">@drawable/window_background</item>
    <item name="android:actionBarStyle">@style/ActionBar</item>

you can not give your own color and backgroud in item windowBackground. give your color in your /color.xml file.

Python slice first and last element in list

def recall(x): 
    num1 = x[-4:]
    num2 = x[::-1]
    num3 = num2[-4:]
    num4 = [num3, num1]
    return num4

Now just make an variable outside the function and recall the function : like this:

avg = recall("idreesjaneqand") 

How to extract text from a string using sed?

sed doesn't recognize \d, use [[:digit:]] instead. You will also need to escape the + or use the -r switch (-E on OS X).

Note that [0-9] works as well for Arabic-Hindu numerals.

Angular 4.3 - HttpClient set params

Another option to do it is:

this.httpClient.get('path', {
    params: Object.entries(data).reduce(
    (params, [key, value]) => params.set(key, value), new HttpParams());

rawQuery(query, selectionArgs)

see below code it may help you.

String q = "SELECT * FROM customer";
Cursor mCursor = mDb.rawQuery(q, null);


String q = "SELECT * FROM customer WHERE _id = " + customerDbId  ;
Cursor mCursor = mDb.rawQuery(q, null);

How to enable CORS in flask

Improving the solution described here:

With after_request we can handle the CORS response headers avoiding to add extra code to our endpoints:

    ### CORS section
    def after_request_func(response):
        origin = request.headers.get('Origin')
        if request.method == 'OPTIONS':
            response = make_response()
            response.headers.add('Access-Control-Allow-Credentials', 'true')
            response.headers.add('Access-Control-Allow-Headers', 'Content-Type')
            response.headers.add('Access-Control-Allow-Headers', 'x-csrf-token')
                                'GET, POST, OPTIONS, PUT, PATCH, DELETE')
            if origin:
                response.headers.add('Access-Control-Allow-Origin', origin)
            response.headers.add('Access-Control-Allow-Credentials', 'true')
            if origin:
                response.headers.add('Access-Control-Allow-Origin', origin)

        return response
    ### end CORS section

Connect to sqlplus in a shell script and run SQL scripts

Some of the other answers here inspired me to write a script for automating the mixed sequential execution of SQL tasks using SQLPLUS along with shell commands for a project, a process that was previously manually done. Maybe this (highly sanitized) example will be useful to someone else:


runsql () {
  # param 1 is $1
sqlplus -S /nolog << EOF
CONNECT $1@$hoststring;
whenever sqlerror exit sql.sqlcode;
set echo off
set heading off

echo "TS::$(date): Starting SCHEM_A.PROC_YOU_NEED()..."
runsql "$acreds" "execute SCHEM_A.PROC_YOU_NEED();"

echo "TS::$(date): Starting superusefuljob..."

echo "TS::$(date): Starting SCHEM_B.SECRET_B_PROC()..."
runsql "$bcreds" "execute SCHEM_B.SECRET_B_PROC();"

echo "TS::$(date): DONE"

runsql allows you to pass a credential string as the first argument, and any SQL you need as the second argument. The variables containing the credentials are included for illustration, but for security I actually source them from another file. If you wanted to handle multiple database connections, you could easily modify the function to accept the hoststring as an additional parameter.

Background color for Tk in Python

config is another option:




CSS: 100% font size - 100% of what?

My understanding is that when the font is set as follows

body {
  font-size: 100%;

the browser will render the font as per the user settings for that browser.

The spec says that % is rendered

relative to parent element's font size

In this case, I take that to mean what the browser is set to.

How to send an email with Gmail as provider using Python?

Not directly related but still worth pointing out is that my package tries to make sending gmail messages really quick and painless. It also tries to maintain a list of errors and tries to point to the solution immediately.

It would literally only need this code to do exactly what you wrote:

import yagmail
yag = yagmail.SMTP('[email protected]')
yag.send('[email protected]', 'Why,Oh why!')

Or a one liner:

yagmail.SMTP('[email protected]').send('[email protected]', 'Why,Oh why!')

For the package/installation please look at git or pip, available for both Python 2 and 3.

How to generate Javadoc from command line

You can refer the javadoc 8 documentation

I think what you are looking at is something like this:

javadoc -d C:\javadoc\test com.test

hardcoded string "row three", should use @string resource

You can go to Design mode and select "Fix" at the bottom of the warning. Then a pop up will appear (seems like it's going to register the new string) and voila, the error is fixed.

Reason to Pass a Pointer by Reference in C++?

50% of C++ programmers like to set their pointers to null after a delete:

template<typename T>    
void moronic_delete(T*& p)
    delete p;
    p = nullptr;

Without the reference, you would only be changing a local copy of the pointer, not affecting the caller.

Variable might not have been initialized error

You declared them but did not provide them with an intial value - thus, they're unintialized. Try something like:

public static Rand searchCount (int[] x)  
  int a = 0 ;  
  int b = 0 ; 

and the warnings should go away.

How to get the dimensions of a tensor (in TensorFlow) at graph construction time?

Tensor.get_shape() from this post.

From documentation:

c = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
==> TensorShape([Dimension(2), Dimension(3)])

django change default runserver port

This is an old post but for those who are interested:

If you want to change the default port number so when you run the "runserver" command you start with your preferred port do this:

  1. Find your python installation. (you can have multiple pythons installed and you can have your virtual environment version as well so make sure you find the right one)
  2. Inside the python folder locate the site-packages folder. Inside that you will find your django installation
  3. Open the django folder-> core -> management -> commands
  4. Inside the commands folder open up the script with a text editor
  5. Find the DEFAULT_PORT field. it is equal to 8000 by default. Change it to whatever you like DEFAULT_PORT = "8080"
  6. Restart your server: python runserver and see that it uses your set port number

It works with python 2.7 but it should work with newer versions of python as well. Good luck

PL/SQL ORA-01422: exact fetch returns more than requested number of rows

A SELECT INTO statement will throw an error if it returns anything other than 1 row. If it returns 0 rows, you'll get a no_data_found exception. If it returns more than 1 row, you'll get a too_many_rows exception. Unless you know that there will always be exactly 1 employee with a salary greater than 3000, you do not want a SELECT INTO statement here.

Most likely, you want to use a cursor to iterate over (potentially) multiple rows of data (I'm also assuming that you intended to do a proper join between the two tables rather than doing a Cartesian product so I'm assuming that there is a departmentID column in both tables)

                FROM EMPLOYEE, 
               WHERE employee.departmentID = department.departmentID
                 AND EMPLOYEE.SALARY > 3000)
    DBMS_OUTPUT.PUT_LINE ('Employee Nnumber: ' || rec.EMPID);
    DBMS_OUTPUT.PUT_LINE ('---------------------------------------------------');
    DBMS_OUTPUT.PUT_LINE ('Employee Name: ' || rec.ENAME);
    DBMS_OUTPUT.PUT_LINE ('---------------------------------------------------');
    DBMS_OUTPUT.PUT_LINE ('Employee Designation: ' || rec.DESIGNATION);
    DBMS_OUTPUT.PUT_LINE ('----------------------------------------------------');
    DBMS_OUTPUT.PUT_LINE ('Employee Salary: ' || rec.SALARY);
    DBMS_OUTPUT.PUT_LINE ('----------------------------------------------------');
    DBMS_OUTPUT.PUT_LINE ('Employee Department: ' || rec.DEPT_NAME);

I'm assuming that you are just learning PL/SQL as well. In real code, you'd never use dbms_output like this and would not depend on anyone seeing data that you write to the dbms_output buffer.

Laravel is there a way to add values to a request array

You can also use below code

$request->request->set(key, value).

Fits better for me.

"code ." Not working in Command Line for Visual Studio Code on OSX/Mac

Steps to follow:-

  1. Open Visual Studio code application & type Command+Shift+P and type command 'install code'. Then enter it.
  2. You will see below message in Visual Studio Application :- shell command ' code' successfully installed in PATH.
  3. Now, Jump to iTerm CLI and type code .
  4. Then you will be able to redirect to Visual studio for any code change/view.

Hope this steps will be helpful for you.

How to concat two ArrayLists?

ArrayList<String> resultList = new ArrayList<String>();

R: Select values from data table in range

Construct some data

df <- data.frame( name=c("John", "Adam"), date=c(3, 5) )

Extract exact matches:

subset(df, date==3)

  name date
1 John    3

Extract matches in range:

subset(df, date>4 & date<6)

  name date
2 Adam    5

The following syntax produces identical results:

df[df$date>4 & df$date<6, ]

  name date
2 Adam    5

Iterate over model instance field names and values in template

I've come up with the following method, which works for me because in every case the model will have a ModelForm associated with it.

def GetModelData(form, fields):
    Extract data from the bound form model instance and return a
    dictionary that is easily usable in templates with the actual
    field verbose name as the label, e.g.

    model_data{"Address line 1": "32 Memory lane",
               "Address line 2": "Brainville",
               "Phone": "0212378492"}

    This way, the template has an ordered list that can be easily
    presented in tabular form.
    model_data = {}
    for field in fields:
        model_data[form[field].label] = eval("" % form[field].name)
    return model_data

def clients_view(request, client_id):
    client = Client.objects.get(id=client_id)
    form = AddClientForm(client)

    fields = ("address1", "address2", "address3", "address4",
              "phone", "fax", "mobile", "email")
    model_data = GetModelData(form, fields)

    template_vars = RequestContext(request,
            "client": client,
            "model_data": model_data
    return render_to_response("clients-view.html", template_vars)

Here is an extract from the template I am using for this particular view:

<table class="client-view">
    {% for field, value in model_data.items %}
            <td class="field-name">{{ field }}</td><td>{{ value }}</td>
    {% endfor %}

The nice thing about this method is that I can choose on a template-by-template basis the order in which I would like to display the field labels, using the tuple passed in to GetModelData and specifying the field names. This also allows me to exclude certain fields (e.g. a User foreign key) as only the field names passed in via the tuple are built into the final dictionary.

I'm not going to accept this as the answer because I'm sure someone can come up with something more "Djangonic" :-)

Update: I'm choosing this as the final answer because it is the simplest out of those given that does what I need. Thanks to everyone who contributed answers.

Android: how to make an activity return results to the activity which calls it?

If you want to finish and just add a resultCode (without data), you can call setResult(int resultCode) before finish().

For example:

if (everything_OK) {
    setResult(Activity.RESULT_OK); // OK! (use whatever code you want)
else {
   setResult(Activity.RESULT_CANCELED); // some error ...

Then in your calling activity, check the resultCode, to see if we're OK.

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == someCustomRequestCode) {
        if (resultCode == Activity.RESULT_OK) {
            // OK!
        else if (resultCode = Activity.RESULT_CANCELED) {
            // something went wrong :-(

Don't forget to call the activity with startActivityForResult(intent, someCustomRequestCode).

error MSB6006: "cmd.exe" exited with code 1

Actually Just delete the build ( clean it ) , then restart the compiler , build it again problem solved .

regex match any whitespace

Your regex should work 'as-is'. Assuming that it is doing what you want it to.

wordA(\s*)wordB(?! wordc)

This means match wordA followed by 0 or more spaces followed by wordB, but do not match if followed by wordc. Note the single space between ?! and wordc which means that wordA wordB wordc will not match, but wordA wordB wordc will.

Here are some example matches and the associated replacement output:

enter image description here

Note that all matches are replaced no matter how many spaces. There are a couple of other points: -

  • (?! wordc) is a negative lookahead, so you wont match lines wordA wordB wordc which is assume is intended (and is why the last line is not matched). Currently you are relying on the space after ?! to match the whitespace. You may want to be more precise and use (?!\swordc). If you want to match against more than one space before wordc you can use (?!\s*wordc) for 0 or more spaces or (?!\s*+wordc) for 1 or more spaces depending on what your intention is. Of course, if you do want to match lines with wordc after wordB then you shouldn't use a negative lookahead.

  • * will match 0 or more spaces so it will match wordAwordB. You may want to consider + if you want at least one space.

  • (\s*) - the brackets indicate a capturing group. Are you capturing the whitespace to a group for a reason? If not you could just remove the brackets, i.e. just use \s.

Update based on comment

Hello the problem is not the expression but the HTML out put   that are not considered as whitespace. it's a Joomla website.

Preserving your original regex you can use:


The only difference is that not the regex matches whitespace OR &nbsp;. I replaced wordc with \swordc since that is more explicit. Note as I have already pointed out that the negative lookahead ?! will not match when wordB is followed by a single whitespace and wordc. If you want to match multiple whitespaces then see my comments above. I also preserved the capture group around the whitespace, if you don't want this then remove the brackets as already described above.

Example matches:

enter image description here

Android: Unable to add window. Permission denied for this window type

    WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                    | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                    | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH
                    | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,

    params.gravity = Gravity.START | Gravity.TOP;
    params.x = left;
    params.y = top;
    windowManager.addView(view, params);

} else {
    WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                    | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                    | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH
                    | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,

    params.gravity = Gravity.START | Gravity.TOP;
    params.x = left;
    params.y = top;
    windowManager.addView(view, params);

Fastest method to replace all instances of a character in a string

// Find, Replace, Case
// i.e "Test to see if this works? (Yes|No)".replaceAll('(Yes|No)', 'Yes!');
// i.e.2 "Test to see if this works? (Yes|No)".replaceAll('(yes|no)', 'Yes!', true);
String.prototype.replaceAll = function(_f, _r, _c){ 

  var o = this.toString();
  var r = '';
  var s = o;
  var b = 0;
  var e = -1;
  if(_c){ _f = _f.toLowerCase(); s = o.toLowerCase(); }

  while((e=s.indexOf(_f)) > -1)
    r += o.substring(b, b+e) + _r;
    s = s.substring(e+_f.length, s.length);
    b += e+_f.length;

  // Add Leftover
  if(s.length>0){ r+=o.substring(o.length-s.length, o.length); }

  // Return New String
  return r;

jQuery UI Sortable Position

Use update instead of stop

update( event, ui )

Type: sortupdate

This event is triggered when the user stopped sorting and the DOM position has changed.


stop( event, ui )

Type: sortstop

This event is triggered when sorting has stopped. event Type: Event

Piece of code:

<script type="text/javascript">

var sortable    = new Object();
sortable.s1     = new Array(1, 2, 3, 4, 5);
sortable.s2     = new Array(1, 2, 3, 4, 5);
sortable.s3     = new Array(1, 2, 3, 4, 5);
sortable.s4     = new Array(1, 2, 3, 4, 5);
sortable.s5     = new Array(1, 2, 3, 4, 5);


function sortingExample()
    // Init vars

    var tDiv    = $('<div></div>');
    var tSel    = '';

    // ul
    for (var tName in sortable)

        // Creating ul list
        tDiv.append(createUl(sortable[tName], tName));
        // Add selector id
        tSel += '#' + tName + ',';


    $('body').append('<div id="divArrayInfo"></div>');

    // ul sortable params

       start: function(event, ui) 
            ui.item.startPos = ui.item.index();
        update: function(event, ui)
            var a   = ui.item.startPos;
            var b   = ui.item.index();
            var id =;

            // If element moved to another Ul then 'update' will be called twice
            // 1st from sender list
            // 2nd from receiver list
            // Skip call from sender. Just check is element removed or not

            if($('#' + id + ' li').length < sortable[id].length)

            if(ui.sender === null)
                sortArray(a, b,,;
                sortArray(a, b, $(ui.sender).attr('id'),;



// Add styles

    .attr('type', 'text/css')
    .html(' body {background:black; color:white; padding:50px;} .sortableClass { clear:both; display: block; overflow: hidden; list-style-type: none; } .sortableClass li { border: 1px solid grey; float:left; clear:none; padding:20px; }')



function printArrayInfo()

    var tStr = '';

    for ( tName in sortable)

        tStr += tName + ': ';

        for(var i=0; i < sortable[tName].length; i++)

            // console.log(sortable[tName][i]);
            tStr += sortable[tName][i] + ', ';


        tStr += '<br>';




function createUl(tArray, tId)

    var tUl = $('<ul>', {id:tId, class:'sortableClass'})

    for(var i=0; i < tArray.length; i++)

        // Create Li element
        var tLi = $('<li>' + tArray[i] + '</li>');


    return tUl;

function sortArray(a, b, idA, idB)
    var c;

    c = sortable[idA].splice(a, 1);
    sortable[idB].splice(b, 0, c);      


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

Select your proper configuration for launching Application.

In my case i found mistake as below image:

enter image description here

I had just changed like:

enter image description here

May it will help to someone, Thanks :)

How can I convert ArrayList<Object> to ArrayList<String>?

Using guava:

List<String> stringList=Lists.transform(list,new Function<Object,String>(){
    public String apply(Object arg0) {
            return arg0.toString();
            return "null";

How to initialize a vector of vectors on a struct?

You use new to perform dynamic allocation. It returns a pointer that points to the dynamically allocated object.

You have no reason to use new, since A is an automatic variable. You can simply initialise A using its constructor:

vector<vector<int> > A(dimension, vector<int>(dimension));

How to replace a whole line with sed?

This might work for you:

cat <<! | sed '/aaa=\(bbb\|ccc\|ddd\)/!s/\(aaa=\).*/\1xxx/'
> aaa=bbb
> aaa=ccc
> aaa=ddd
> aaa=[something else]

Convert SVG to image (JPEG, PNG, etc.) in the browser

Svg to png can be converted depending on conditions:

  1. If svg is in format SVG (string) paths:
  • create canvas
  • create new Path2D() and set svg as parameter
  • draw path on canvas
  • create image and use canvas.toDataURL() as src.


const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
let svgText = 'M10 10 h 80 v 80 h -80 Z';
let p = new Path2D('M10 10 h 80 v 80 h -80 Z');
let url = canvas.toDataURL();
const img = new Image();
img.src = url;

Note that Path2D not supported in ie and partially supported in edge. Polyfill solves that:

  1. Create svg blob and draw on canvas using .drawImage():
  • make canvas element
  • make a svgBlob object from the svg xml
  • make a url object from domUrl.createObjectURL(svgBlob);
  • create an Image object and assign url to image src
  • draw image into canvas
  • get png data string from canvas: canvas.toDataURL();

Nice description:

Note that in ie you will get exception on stage of canvas.toDataURL(); It is because IE has too high security restriction and treats canvas as readonly after drawing image there. All other browsers restrict only if image is cross origin.

  1. Use canvg JavaScript library. It is separate library but has useful functions.


var dataURL = canvas.toDataURL();

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

"this" extends the next class in the parameter list

So in the method signature below "this" extends "String". Line is passed to the function as a normal argument to the method. public static string[] SplitCsvLine(this String line)

In the above example "this" class is extending the built in "String" class.

How to scale down a range of numbers with a known min and max value

For convenience, here is Irritate's algorithm in a Java form. Add error checking, exception handling and tweak as necessary.

public class Algorithms { 
    public static double scale(final double valueIn, final double baseMin, final double baseMax, final double limitMin, final double limitMax) {
        return ((limitMax - limitMin) * (valueIn - baseMin) / (baseMax - baseMin)) + limitMin;


final double baseMin = 0.0;
final double baseMax = 360.0;
final double limitMin = 90.0;
final double limitMax = 270.0;
double valueIn = 0;
System.out.println(Algorithms.scale(valueIn, baseMin, baseMax, limitMin, limitMax));
valueIn = 360;
System.out.println(Algorithms.scale(valueIn, baseMin, baseMax, limitMin, limitMax));
valueIn = 180;
System.out.println(Algorithms.scale(valueIn, baseMin, baseMax, limitMin, limitMax));


How to exclude 0 from MIN formula Excel

All you have to do is to delete the "0" in the cells that contain just that and try again. That should work.

Export tables to an excel spreadsheet in same directory

Lawrence has given you a good answer. But if you want more control over what gets exported to where in Excel see Modules: Sample Excel Automation - cell by cell which is slow and Modules: Transferring Records to Excel with Automation You can do things such as export the recordset starting in row 2 and insert custom text in row 1. As well as any custom formatting required.

'pip install' fails for every package ("Could not find a version that satisfies the requirement")

Support for TLS 1.0 and 1.1 was dropped for PyPI. If your system does not use a more recent version, it could explain your error.

Could you try reinstalling pip system-wide, to update your system dependencies to a newer version of TLS?

This seems to be related to Unable to install Python libraries

See Dominique Barton's answer:

Apparently pip is trying to access PyPI via HTTPS (which is encrypted and fine), but with an old (insecure) SSL version. Your system seems to be out of date. It might help if you update your packages.

On Debian-based systems I'd try:

apt-get update && apt-get upgrade python-pip

On Red Hat Linux-based systems:

yum update python-pip # (or python2-pip, at least on Red Hat Linux 7)

On Mac:

sudo easy_install -U pip

You can also try to update openssl separately.

Dynamically add properties to a existing object

Take a look at the Clay library:

It provides something similar to the ExpandoObject but with a bunch of extra features. Here is blog post explaining how to use it:

(be sure to read the IPerson interface example)

MySQL string replace

In addition to gmaggio's answer if you need to dynamically REPLACE and UPDATE according to another column you can do for example:

UPDATE your_table t1
INNER JOIN other_table t2
ON t1.field_id = t2.field_id
SET t1.your_field = IF(LOCATE('articles/updates/', t1.your_field) > 0, 
REPLACE(t1.your_field, 'articles/updates/', t2.new_folder), t1.your_field) 

In my example the string articles/news/ is stored in other_table t2 and there is no need to use LIKE in the WHERE clause.

Detect home button press in android

Jack's answer is perfectly working for click event while longClick is considering is as menu button click.

By the way, if anyone is wondering how to do via kotlin,

class HomeButtonReceiver(private var context: Context,private var listener: OnHomeButtonClickListener) {
    private val mFilter: IntentFilter = IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)
    private var mReceiver: InnerReceiver = InnerReceiver()

    fun startWatch() {
        context.registerReceiver(mReceiver, mFilter)

    fun stopWatch() {

    inner class InnerReceiver: BroadcastReceiver() {
        private val systemDialogReasonKey = "reason"
        private val systemDialogReasonHomeKey = "homekey"
        override fun onReceive(context: Context?, intent: Intent?) {
            val action = intent?.action
            if (action == Intent.ACTION_CLOSE_SYSTEM_DIALOGS) {
                val reason = intent.getStringExtra(systemDialogReasonKey)
                if (reason != null && reason == systemDialogReasonHomeKey) {

How to write to a JSON file in the correct format

This question is for ruby 1.8 but it still comes on top when googling.

in ruby >= 1.9 you can use


other than what mentioned in other answers, in ruby 1.8 you can also use one liner form"public/temp.json","w"){ |f| f.write tempHash.to_json }

Remove ListView items in Android

I think if u add the following code, it will work


To remove an item, Just remove that item from the arraylist that we passed to the adapter and do listview.invalidateViews();
This will refresh the listview

how to implement login auth in node.js

Actually this is not really the answer of the question, but this is a better way to do it.

I suggest you to use connect/express as http server, since they save you a lot of time. You obviously don't want to reinvent the wheel. In your case session management is much easier with connect/express.

Beside that for authentication I suggest you to use everyauth. Which supports a lot of authentication strategies. Awesome for rapid development.

All this can be easily down with some copy pasting from their documentation!

Print Pdf in C#

A very straight forward approach is to use an installed Adobe Reader or any other PDF viewer capable of printing:

Process p = new Process( );
p.StartInfo = new ProcessStartInfo( )
    CreateNoWindow = true,
    Verb = "print",
    FileName = path //put the correct path here
p.Start( );

Another way is to use a third party component, e.g. PDFView4NET

GitHub "fatal: remote origin already exists"

First do a:

git remote rm origin


git remote add origin

and voila! Worked for me!

Android Saving created bitmap to directory on sd card

just change the extension to .bmp.

Do this:

ByteArrayOutputStream bytes = new ByteArrayOutputStream();
_bitmapScaled.compress(Bitmap.CompressFormat.PNG, 40, bytes);

//you can create a new file name "test.BMP" in sdcard folder.
File f = new File(Environment.getExternalStorageDirectory()
                        + File.separator + "test.bmp")

It'll sound that I'm just fooling around, but try it once and it'll get saved in BMP format. Cheers!

Inserting an image with PHP and FPDF

You can't treat a PDF like an HTML document. Images can't "float" within a document and have things flow around them, or flow with surrounding text. FPDF allows you to embed html in a text block, but only because it parses the tags and replaces <i> and <b> and so on with Postscript equivalent commands. It's not smart enough to dynamically place an image.

In other words, you have to specify coordinates (and if you don't, the current location's coordinates will be used anyways).

Difference between agile and iterative and incremental development

  • Iterative - you don't finish a feature in one go. You are in a code >> get feedback >> code >> ... cycle. You keep iterating till done.
  • Incremental - you build as much as you need right now. You don't over-engineer or add flexibility unless the need is proven. When the need arises, you build on top of whatever already exists. (Note: differs from iterative in that you're adding new things.. vs refining something).
  • Agile - you are agile if you value the same things as listed in the agile manifesto. It also means that there is no standard template or checklist or procedure to "do agile". It doesn't overspecify.. it just states that you can use whatever practices you need to "be agile". Scrum, XP, Kanban are some of the more prescriptive 'agile' methodologies because they share the same set of values. Continuous and early feedback, frequent releases/demos, evolve design, etc.. hence they can be iterative and incremental.

How can I display two div in one line via css inline property

use inline-block instead of inline. Read more information here about the difference between inline and inline-block.

.inline { 
display: inline-block; 
border: 1px solid red; 


Retrieve version from maven pom.xml in code

Sometimes the Maven command line is sufficient when scripting something related to the project version, e.g. for artifact retrieval via URL from a repository:

mvn help:evaluate -Dexpression=project.version -q -DforceStdout

Usage example:

VERSION=$( mvn help:evaluate -Dexpression=project.version -q -DforceStdout )
ARTIFACT_ID=$( mvn help:evaluate -Dexpression=project.artifactId -q -DforceStdout )
GROUP_ID_URL=$( mvn help:evaluate -Dexpression=project.groupId -q -DforceStdout | sed -e 's#\.#/#g' )
curl -f -S -O http://REPO-URL/mvn-repos/${GROUP_ID_URL}/${ARTIFACT_ID}/${VERSION}/${ARTIFACT_ID}-${VERSION}.jar

How do I request a file but not save it with Wget?

Use q flag for quiet mode, and tell wget to output to stdout with O- (uppercase o) and redirect to /dev/null to discard the output:

wget -qO- $url &> /dev/null

> redirects application output (to a file). if > is preceded by ampersand, shell redirects all outputs (error and normal) to the file right of >. If you don't specify ampersand, then only normal output is redirected.

./app &>  file # redirect error and standard output to file
./app >   file # redirect standard output to file
./app 2>  file # redirect error output to file

if file is /dev/null then all is discarded.

This works as well, and simpler:

wget -O/dev/null -q $url

file path Windows format to java format

Just check

in MacOS

File directory = new File("/Users/sivo03/eclipse-workspace/For4DC/AutomationReportBackup/"+dir);
File directoryApache = new File("/Users/sivo03/Automation/apache-tomcat-9.0.22/webapps/AutomationReport/"+dir); 

and same we use in windows

File directory = new File("C:\\Program Files (x86)\\Jenkins\\workspace\\BrokenLinkCheckerALL\\AutomationReportBackup\\"+dir);
File directoryApache = new File("C:\\Users\\Admin\\Downloads\\Automation\\apache-tomcat-9.0.26\\webapps\\AutomationReports\\"+dir);

use double backslash instead of single frontslash

so no need any converter tool just use find and replace

"C:\Documents and Settings\Manoj\Desktop" to "C:\\Documents and Settings\\Manoj\\Desktop"

Django datetime issues (

The answer to this one is actually wrong.

Auto filling in the value (auto_now/auto_now_add isn't the same as default). The default value will actually be what the user sees if its a brand new object. What I typically do is:

date = models.DateTimeField(, editable=False,)

Make sure, if your trying to represent this in an Admin page, that you list it as 'read_only' and reference the field name

read_only = 'date'

Again, I do this since my default value isn't typically editable, and Admin pages ignore non-editables unless specified otherwise. There is certainly a difference however between setting a default value and implementing the auto_add which is key here. Test it out!

How to build query string with Javascript

As Stein says, you can use the prototype javascript library from Include the JS and it is very simple then, $('formName').serialize() will return what you want!

typedef fixed length array

Building off the accepted answer, a multi-dimensional array type, that is a fixed-length array of fixed-length arrays, can't be declared with

typedef char[M] T[N];  // wrong!

instead, the intermediate 1D array type can be declared and used as in the accepted answer:

typedef char T_t[M];
typedef T_t T[N];

or, T can be declared in a single (arguably confusing) statement:

typedef char T[N][M];

which defines a type of N arrays of M chars (be careful about the order, here).

How to make button look like a link?

You can't style buttons as links reliably throughout browsers. I've tried it, but there's always some weird padding, margin or font issues in some browser. Either live with letting the button look like a button, or use onClick and preventDefault on a link.

How can I access my localhost from my Android device?

As this is an old question, there is a new way to do this that is really really simple. Download the ADB Chrome Extension and then follow these instructions:

When to use pthread_exit() and when to use pthread_join() in Linux?

Both methods ensure that your process doesn't end before all of your threads have ended.

The join method has your thread of the main function explicitly wait for all threads that are to be "joined".

The pthread_exit method terminates your main function and thread in a controlled way. main has the particularity that ending main otherwise would be terminating your whole process including all other threads.

For this to work, you have to be sure that none of your threads is using local variables that are declared inside them main function. The advantage of that method is that your main doesn't have to know all threads that have been started in your process, e.g because other threads have themselves created new threads that main doesn't know anything about.

Cordova : Requirements check failed for JDK 1.8 or greater

I was running into the same problem yesterday with my new laptop (all new installation), with the only execption that for me Cordova said:

Requirements check failed for JDK 8 ('1.8.*')! Detected version: null

That Detected version: null was the actual problem for me!

When looking into the check_reqs.js (as mentioned in a post above) you will notice that this is where the magic happens: It contains a function "check_java" that, at some point, uses "execa" to retrieve the installed version of Java:

return execa('javac', ['-version'], { all: true })
    .then(({ all: output }) => {
        // Java <= 8 writes version info to stderr, Java >= 9 to stdout
        const match = /javac\s+([\d.]+)/i.exec(output);
        return match && match[1];

The problem for me was that, for whatever reason, I had an outdated version of "execa" which does not contain the "all" property that was used for the output. Hence, the retrieved version of Java was always undefined. By adding "execa": "^4.0.2" to my dependencies in the package.json and running "npm i" again I was able to fix this problem.

Just wanted to share this insight.

How to Set a Custom Font in the ActionBar Title?

Following code will work for all the versions. I did checked this in a device with gingerbread as well as on JellyBean device

 private void actionBarIdForAll()
        int titleId = 0;

            titleId = getResources().getIdentifier("action_bar_title", "id", "android");
          // This is the id is from your app's generated R class when ActionBarActivity is used for SupportActionBar

            titleId =;

            // Do whatever you want ? It will work for all the versions.

            // 1. Customize your fonts
            // 2. Infact, customize your whole title TextView

            TextView titleView = (TextView)findViewById(titleId);

In Python script, how do I set PYTHONPATH?

PYTHONPATH ends up in sys.path, which you can modify at runtime.

import sys
sys.path += ["whatever"]

If Python is interpreted, what are .pyc files?

I've been given to understand that Python is an interpreted language...

This popular meme is incorrect, or, rather, constructed upon a misunderstanding of (natural) language levels: a similar mistake would be to say "the Bible is a hardcover book". Let me explain that simile...

"The Bible" is "a book" in the sense of being a class of (actual, physical objects identified as) books; the books identified as "copies of the Bible" are supposed to have something fundamental in common (the contents, although even those can be in different languages, with different acceptable translations, levels of footnotes and other annotations) -- however, those books are perfectly well allowed to differ in a myriad of aspects that are not considered fundamental -- kind of binding, color of binding, font(s) used in the printing, illustrations if any, wide writable margins or not, numbers and kinds of builtin bookmarks, and so on, and so forth.

It's quite possible that a typical printing of the Bible would indeed be in hardcover binding -- after all, it's a book that's typically meant to be read over and over, bookmarked at several places, thumbed through looking for given chapter-and-verse pointers, etc, etc, and a good hardcover binding can make a given copy last longer under such use. However, these are mundane (practical) issues that cannot be used to determine whether a given actual book object is a copy of the Bible or not: paperback printings are perfectly possible!

Similarly, Python is "a language" in the sense of defining a class of language implementations which must all be similar in some fundamental respects (syntax, most semantics except those parts of those where they're explicitly allowed to differ) but are fully allowed to differ in just about every "implementation" detail -- including how they deal with the source files they're given, whether they compile the sources to some lower level forms (and, if so, which form -- and whether they save such compiled forms, to disk or elsewhere), how they execute said forms, and so forth.

The classical implementation, CPython, is often called just "Python" for short -- but it's just one of several production-quality implementations, side by side with Microsoft's IronPython (which compiles to CLR codes, i.e., ".NET"), Jython (which compiles to JVM codes), PyPy (which is written in Python itself and can compile to a huge variety of "back-end" forms including "just-in-time" generated machine language). They're all Python (=="implementations of the Python language") just like many superficially different book objects can all be Bibles (=="copies of The Bible").

If you're interested in CPython specifically: it compiles the source files into a Python-specific lower-level form (known as "bytecode"), does so automatically when needed (when there is no bytecode file corresponding to a source file, or the bytecode file is older than the source or compiled by a different Python version), usually saves the bytecode files to disk (to avoid recompiling them in the future). OTOH IronPython will typically compile to CLR codes (saving them to disk or not, depending) and Jython to JVM codes (saving them to disk or not -- it will use the .class extension if it does save them).

These lower level forms are then executed by appropriate "virtual machines" also known as "interpreters" -- the CPython VM, the .Net runtime, the Java VM (aka JVM), as appropriate.

So, in this sense (what do typical implementations do), Python is an "interpreted language" if and only if C# and Java are: all of them have a typical implementation strategy of producing bytecode first, then executing it via a VM/interpreter.

More likely the focus is on how "heavy", slow, and high-ceremony the compilation process is. CPython is designed to compile as fast as possible, as lightweight as possible, with as little ceremony as feasible -- the compiler does very little error checking and optimization, so it can run fast and in small amounts of memory, which in turns lets it be run automatically and transparently whenever needed, without the user even needing to be aware that there is a compilation going on, most of the time. Java and C# typically accept more work during compilation (and therefore don't perform automatic compilation) in order to check errors more thoroughly and perform more optimizations. It's a continuum of gray scales, not a black or white situation, and it would be utterly arbitrary to put a threshold at some given level and say that only above that level you call it "compilation"!-)

Create a root password for PHPMyAdmin

I just faced the mysql user password problem - ERROR 1045: Access denied for user: 'root@localhost' (Using password: NO) - when I tried to do a do-release-upgrade on my operational system. So I corrected it in 2 steps.

Firstly, as I did not had access on phpmyadmin, so I followed the "Recover MySQL root password" step on the tutorial mensioned by ThoKra:

Secondly, with one of the users that I know the password, I made some password changes to the others users through phpmyadmin itself according to SonDang's information.

Setting a width and height on an A tag

You need to make your anchor display: block or display: inline-block; and then it will accept the width and height values.

HTTP Status 504

If your using ASP.Net 5 (now known as ASP.Net Core v1) ensure in your project.json "commands" section for each site you are hosting that the Kestrel proxy listening port differs between sites, otherwise one site will work but the other will return a 504 gateway timeout.

 "commands": {
    "web": "Microsoft.AspNet.Server.Kestrel --server.urls http://localhost:5090"

Am I trying to connect to a TLS-enabled daemon without TLS?

For me, running $(boot2docker shellinit 2> /dev/null) fixed the problem.

This runs the output of the boot2docker shellinit command (the three set -x ... lines) in your current terminal session, which lets the docker command know where to find the boot2docker virtual machine.

Adding $(boot2docker shellinit 2> /dev/null) to the bottom of your ~/.bash_profile file will make sure the docker command is configured, every time you open your terminal.

For people using Fish shell: boot2docker shellinit ^ /dev/null | source.

Note that 2> /dev/null (and the Fish equivalent ^ /dev/null) are optional. Like @pablo-fernandez suggested, this hides the Writing .. lines.

How to disable Home and other system buttons in Android?

First create a method :

public void hideNavigationBar() {
        final View decorView = this.getWindow().getDecorView();
        final int uiOptions =
                        | View.SYSTEM_UI_FLAG_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;

        Timer timer = new Timer();
        TimerTask task = new TimerTask() {
            public void run() {
                YourActivityName.this.runOnUiThread(new Runnable() {
                    public void run() {


        timer.scheduleAtFixedRate(task, 1, 2);


Then you call it on onCreate() method of your activity. Call it again on the onResume() method. Then you may add another method in your activity like this:

    public void onWindowFocusChanged(boolean hasFocus) {

That will be it. Do remember it will lock the screen till the next time user touches the screen, in Timer class you can change the delay and it will allow you change things for that instance.Then it will lock the screen again.

Java's L number (long) specification

By default any integral primitive data type (byte, short, int, long) will be treated as int type by java compiler. For byte and short, as long as value assigned to them is in their range, there is no problem and no suffix required. If value assigned to byte and short exceeds their range, explicit type casting is required.


byte b = 130; // CE: range is exceeding.

to overcome this perform type casting.

byte b = (byte)130; //valid, but chances of losing data is there.

In case of long data type, it can accept the integer value without any hassle. Suppose we assign like

Long l = 2147483647; //which is max value of int

in this case no suffix like L/l is required. By default value 2147483647 is considered by java compiler is int type. Internal type casting is done by compiler and int is auto promoted to Long type.

Long l = 2147483648; //CE: value is treated as int but out of range 

Here we need to put suffix as L to treat the literal 2147483648 as long type by java compiler.

so finally

Long l = 2147483648L;// works fine.

Python glob multiple filetypes

Use a list of extension and iterate through

from os.path import join
from glob import glob

files = []
extensions = ['*.gif', '*.png', '*.jpg']
for ext in extensions:
   files.extend(glob(join("path/to/dir", ext)))


phpMyAdmin allow remote users

My setup was a little different using XAMPP. in httpd-xampp.conf I had to make the following change.

Alias /phpmyadmin "C:/xampp/phpMyAdmin/"
<Directory "C:/xampp/phpMyAdmin">
    AllowOverride AuthConfig
    Require local
    ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var

change to

Alias /phpmyadmin "C:/xampp/phpMyAdmin/"
<Directory "C:/xampp/phpMyAdmin">
    AllowOverride AuthConfig
    #makes it so I can config the database from anywhere
    #change the line below
    Require all granted
    ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var

I need to state that I'm brand new at this so I'm just hacking around but this is how I got it working.

Where does Git store files?

If you are on an English Windows machine, Git's default storage path will be C:\Documents and Settings\< current_user>\, because on Windows the default Git local settings resides at C:\Documents and Settings\< current_user>\.git and so Git creates a separate folder for each repo/clone at C:\Documents and Settings\< current_user>\ and there are all the directories of cloned project.

For example, if you install Symfony 2 with

git clone git://

the Symfony directory and file will be at

C:\Documents and Settings\< current_user>\symfony\

How to uncommit my last commit in Git

Be careful with that.

But you can use the rebase command

git rebase -i HEAD~2

A vi will open and all you have to do is delete the line with the commit. Also can read instructions that were shown in proper edition @ vi. A couple of things can be performed on this mode.

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;


what is the use of fflush(stdin) in c programming

It's not in standard C, so the behavior is undefined.

Some implementation uses it to clear stdin buffer.

From C11 The fflush function, fflush works only with output/update stream, not input stream.

If stream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.

How to determine when a Git branch was created?

If you want to get the details for all the branches

for i in `git branch -r | tail -n +2 `;do git log --reverse $i|grep -A 2 -B 2 `echo $i | awk -F'origin/' '{print $2}'` |head -n 4; done

How does data binding work in AngularJS?

By dirty checking the $scope object

Angular maintains a simple array of watchers in the $scope objects. If you inspect any $scope you will find that it contains an array called $$watchers.

Each watcher is an object that contains among other things

  1. An expression which the watcher is monitoring. This might just be an attribute name, or something more complicated.
  2. A last known value of the expression. This can be checked against the current computed value of the expression. If the values differ the watcher will trigger the function and mark the $scope as dirty.
  3. A function which will be executed if the watcher is dirty.

How watchers are defined

There are many different ways of defining a watcher in AngularJS.

  • You can explicitly $watch an attribute on $scope.

      $scope.$watch('person.username', validateUnique);
  • You can place a {{}} interpolation in your template (a watcher will be created for you on the current $scope).

      <p>username: {{person.username}}</p>
  • You can ask a directive such as ng-model to define the watcher for you.

      <input ng-model="person.username" />

The $digest cycle checks all watchers against their last value

When we interact with AngularJS through the normal channels (ng-model, ng-repeat, etc) a digest cycle will be triggered by the directive.

A digest cycle is a depth-first traversal of $scope and all its children. For each $scope object, we iterate over its $$watchers array and evaluate all the expressions. If the new expression value is different from the last known value, the watcher's function is called. This function might recompile part of the DOM, recompute a value on $scope, trigger an AJAX request, anything you need it to do.

Every scope is traversed and every watch expression evaluated and checked against the last value.

If a watcher is triggered, the $scope is dirty

If a watcher is triggered, the app knows something has changed, and the $scope is marked as dirty.

Watcher functions can change other attributes on $scope or on a parent $scope. If one $watcher function has been triggered, we can't guarantee that our other $scopes are still clean, and so we execute the entire digest cycle again.

This is because AngularJS has two-way binding, so data can be passed back up the $scope tree. We may change a value on a higher $scope that has already been digested. Perhaps we change a value on the $rootScope.

If the $digest is dirty, we execute the entire $digest cycle again

We continually loop through the $digest cycle until either the digest cycle comes up clean (all $watch expressions have the same value as they had in the previous cycle), or we reach the digest limit. By default, this limit is set at 10.

If we reach the digest limit AngularJS will raise an error in the console:

10 $digest() iterations reached. Aborting!

The digest is hard on the machine but easy on the developer

As you can see, every time something changes in an AngularJS app, AngularJS will check every single watcher in the $scope hierarchy to see how to respond. For a developer this is a massive productivity boon, as you now need to write almost no wiring code, AngularJS will just notice if a value has changed, and make the rest of the app consistent with the change.

From the perspective of the machine though this is wildly inefficient and will slow our app down if we create too many watchers. Misko has quoted a figure of about 4000 watchers before your app will feel slow on older browsers.

This limit is easy to reach if you ng-repeat over a large JSON array for example. You can mitigate against this using features like one-time binding to compile a template without creating watchers.

How to avoid creating too many watchers

Each time your user interacts with your app, every single watcher in your app will be evaluated at least once. A big part of optimising an AngularJS app is reducing the number of watchers in your $scope tree. One easy way to do this is with one time binding.

If you have data which will rarely change, you can bind it only once using the :: syntax, like so:



<p ng-bind="::person.username"></p>

The binding will only be triggered when the containing template is rendered and the data loaded into $scope.

This is especially important when you have an ng-repeat with many items.

<div ng-repeat="person in people track by username">

Get value of multiselect box using jQuery or pure JS

According to the widget's page, it should be:

var myDropDownListValues = $("#myDropDownList").multiselect("getChecked").map(function()
    return this.value;    

It works for me :)

Passing data to a jQuery UI Dialog

In terms of what you are doing with jQuery, my understanding is that you can chain functions like you have and the inner ones have access to variables from the outer ones. So is your ShowDialog(x) function contains these other functions, you can re-use the x variable within them and it will be taken as a reference to the parameter from the outer function.

I agree with mausch, you should really look at using POST for these actions, which will add a <form> tag around each element, but make the chances of an automated script or tool triggering the Cancel event much less likely. The Change action can remain as is because it (presumably just opens an edit form).

Python Traceback (most recent call last)

You are using Python 2 for which the input() function tries to evaluate the expression entered. Because you enter a string, Python treats it as a name and tries to evaluate it. If there is no variable defined with that name you will get a NameError exception.

To fix the problem, in Python 2, you can use raw_input(). This returns the string entered by the user and does not attempt to evaluate it.

Note that if you were using Python 3, input() behaves the same as raw_input() does in Python 2.

Ignore .classpath and .project from Git

The git solution for such scenarios is setting SKIP-WORKTREE BIT. Run only the following command:

git update-index --skip-worktree .classpath .gitignore

It is used when you want git to ignore changes of files that are already managed by git and exist on the index. This is a common use case for config files.

Running git rm --cached doesn't work for the scenario mentioned in the question. If I simplify the question, it says:

How to have .classpath and .project on the repo while each one can change it locally and git ignores this change?

As I commented under the accepted answer, the drawback of git rm --cached is that it causes a change in the index, so you need to commit the change and then push it to the remote repository. As a result, .classpath and .project won't be available on the repo while the PO wants them to be there so anyone that clones the repo for the first time, they can use it.


Based on git documentaion:

Skip-worktree bit can be defined in one (long) sentence: When reading an entry, if it is marked as skip-worktree, then Git pretends its working directory version is up to date and read the index version instead. Although this bit looks similar to assume-unchanged bit, its goal is different from assume-unchanged bit’s. Skip-worktree also takes precedence over assume-unchanged bit when both are set.

More details is available here.

How to compare objects by multiple fields

//Following is the example in jdk 1.8
package com;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

class User {
    private String firstName;
    private String lastName;
    private Integer age;

    public Integer getAge() {
        return age;

    public User setAge(Integer age) {
        this.age = age;
        return this;

    public String getFirstName() {
        return firstName;

    public User setFirstName(String firstName) {
        this.firstName = firstName;
        return this;

    public String getLastName() {
        return lastName;

    public User setLastName(String lastName) {
        this.lastName = lastName;
        return this;


public class MultiFieldsComparision {

    public static void main(String[] args) {
        List<User> users = new ArrayList<User>();

        User u1 = new User().setFirstName("Pawan").setLastName("Singh").setAge(38);
        User u2 = new User().setFirstName("Pawan").setLastName("Payal").setAge(37);
        User u3 = new User().setFirstName("Anuj").setLastName("Kumar").setAge(60);
        User u4 = new User().setFirstName("Anuj").setLastName("Kumar").setAge(43);
        User u5 = new User().setFirstName("Pawan").setLastName("Chamoli").setAge(44);
        User u6 = new User().setFirstName("Pawan").setLastName("Singh").setAge(5);


        System.out.println("****** Before Sorting ******");

        users.forEach(user -> {
            System.out.println(user.getFirstName() + " , " + user.getLastName() + " , " + user.getAge());

        System.out.println("****** Aftre Sorting ******");


        users.forEach(user -> {
            System.out.println(user.getFirstName() + " , " + user.getLastName() + " , " + user.getAge());



how to change color of TextinputLayout's label and edittext underline android

Add this attribute in Edittext tag and enjoy:


mingw-w64 threads: posix vs win32

GCC comes with a compiler runtime library (libgcc) which it uses for (among other things) providing a low-level OS abstraction for multithreading related functionality in the languages it supports. The most relevant example is libstdc++'s C++11 <thread>, <mutex>, and <future>, which do not have a complete implementation when GCC is built with its internal Win32 threading model. MinGW-w64 provides a winpthreads (a pthreads implementation on top of the Win32 multithreading API) which GCC can then link in to enable all the fancy features.

I must stress this option does not forbid you to write any code you want (it has absolutely NO influence on what API you can call in your code). It only reflects what GCC's runtime libraries (libgcc/libstdc++/...) use for their functionality. The caveat quoted by @James has nothing to do with GCC's internal threading model, but rather with Microsoft's CRT implementation.

To summarize:

  • posix: enable C++11/C11 multithreading features. Makes libgcc depend on libwinpthreads, so that even if you don't directly call pthreads API, you'll be distributing the winpthreads DLL. There's nothing wrong with distributing one more DLL with your application.
  • win32: No C++11 multithreading features.

Neither have influence on any user code calling Win32 APIs or pthreads APIs. You can always use both.

JavaScript/jQuery to download file via POST with JSON data

I think the best approach is to use a combination, Your second approach seems to be an elegant solution where browsers are involved.

So depending on the how the call is made. (whether its a browser or a web service call) you can use a combination of the two, with sending a URL to the browser and sending raw data to any other web service client.

How to disable Google Chrome auto update?

For Windows users, you may follow the steps in Google Chrome Enterprise Help - Manage Chrome updates (Windows).

Just follow step 1: Install Google Update > Get the Google Update policy template & step 2: Configure auto-updates > Turn off Chrome Browser auto-updates.

If everything is configured correctly, you will see "Updates are disabled by your administrator." in Google Chrome settings About Chrome section after you reboot the pc. configured successful screenshot

sort dict by value python

From your comment to gnibbler answer, i'd say you want a list of pairs of key-value sorted by value:

sorted(data.items(), key=lambda x:x[1])

CMake error at CMakeLists.txt:30 (project): No CMAKE_C_COMPILER could be found

You can also make sure you are the sudo user and you have READ/WRITE access on the directory you are working. I had a similar problem on OS X, and I got it fixed just by entering in sudo mode.

HTML img align="middle" doesn't align an image

just remove float: left and replace align with margin: 0 auto and it will be centered.

ReactJS - How to use comments?

JSX Comments Syntax: You can use

  your comment 
  in multiple lines
  for documentation 


  your comment 
  in multiple lines

for multiple lines comment. And also,

  //your comment 

for single line comment.

Note: The syntax:

{ //your comment } 

doesn't work. You need to type braces in new lines.

Curly braces are used to distinguish between JSX and JavaScript in a React component. Inside curly braces, we use JavaScript comment syntax.

Reference: click here

What is a software framework?

I'm very late to answer it. But, I would like to share one example, which I only thought of today. If I told you to cut a piece of paper with dimensions 5m by 5m, then surely you would do that. But suppose I ask you to cut 1000 pieces of paper of the same dimensions. In this case, you won't do the measuring 1000 times; obviously, you would make a frame of 5m by 5m, and then with the help of it you would be able to cut 1000 pieces of paper in less time. So, what you did was make a framework which would do a specific type of task. Instead of performing the same type of task again and again for the same type of applications, you create a framework having all those facilities together in one nice packet, hence providing the abstraction for your application and more importantly many applications.

Saving awk output to variable

variable=$(ps -ef | awk '/[p]ort 10/ {print $12}')

The [p] is a neat trick to remove the search from showing from ps

@Jeremy If you post the output of ps -ef | grep "port 10", and what you need from the line, it would be more easy to help you getting correct syntax

How to convert XML to java.util.Map and vice versa

Here the converter for XStream including unmarshall

public class MapEntryConverter implements Converter{
public boolean canConvert(Class clazz) {
    return AbstractMap.class.isAssignableFrom(clazz);

public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context) {
    AbstractMap<String,String> map = (AbstractMap<String,String>) value;
    for (Entry<String,String> entry : map.entrySet()) {

public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
    Map<String, String> map = new HashMap<String, String>();

    while(reader.hasMoreChildren()) {
        map.put(reader.getNodeName(), reader.getValue());
    return map;

Deny all, allow only one IP through htaccess

I wasn't able to use the 403 method because I wanted the maintenance page and page images in a sub folder on my server, so used the following approach to redirect to a 'maintenance page' for everyone but a single IP*

RewriteEngine on
RewriteCond %{REMOTE_ADDR} !**.**.**.*
RewriteRule !^maintenance/ [R=302,L]

Source: Creating a holding page to hide your WordPress blog

SQL select join: is it possible to prefix all columns as 'prefix.*'?

The only database I know that does this is SQLite, depending on the settings you configure with PRAGMA full_column_names and PRAGMA short_column_names. See

Otherwise all I can recommend is to fetch columns in a result set by ordinal position rather than by column name, if it's too much trouble for you to type the names of the columns in your query.

This is a good example of why it's bad practice to use SELECT * -- because eventually you'll have a need to type out all the column names anyway.

I understand the need to support columns that may change name or position, but using wildcards makes that harder, not easier.

how to remove pagination in datatable

    "bInfo": false, //Dont display info e.g. "Showing 1 to 4 of 4 entries"
    "paging": false,//Dont want paging                
    "bPaginate": false,//Dont want paging      

Try this code

Identify duplicate values in a list in Python

The following code will fetch you desired results with duplicate items and their index values.

  for i in set(mylist):
    if mylist.count(i) > 1:
         print(i, mylist.index(i))

POST string to ASP.NET Web Api application - returns null

I use this code to post HttpRequests.

/// <summary>
        /// Post this message.
        /// </summary>
        /// <param name="url">URL of the document.</param>
        /// <param name="bytes">The bytes.</param>
        public T Post<T>(string url, byte[] bytes)
        T item;
        var request = WritePost(url, bytes);

        using (var response = request.GetResponse() as HttpWebResponse)
            item = DeserializeResponse<T>(response);

        return item;

    /// <summary>
    /// Writes the post.
    /// </summary>
    /// <param name="url">The URL.</param>
    /// <param name="bytes">The bytes.</param>
    /// <returns></returns>
    private static HttpWebRequest WritePost(string url, byte[] bytes)
        ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;

        HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
        Stream stream = null;
            request.PreAuthenticate = true;
            request.Connection = null;
            request.Expect = null;
            request.KeepAlive = false;
            request.ContentLength = bytes.Length;
            request.Timeout = -1;
            request.Method = "POST";
            stream = request.GetRequestStream();
            stream.Write(bytes, 0, bytes.Length);
        catch (Exception e)
            GetErrorResponse(url, e);
            if (stream != null)
        return request;

In regards to your code, try it without the content.Type (request.ContentType = "application/x-www-form-urlencoded";)


I believe the problem lies with how you are trying to retrieve the value. When you do a POST and send bytes via the Stream, they will not be passed into the action as a parameter. You'll need to retrieve the bytes via the stream on the server.

On the server, try getting the bytes from stream. The following code is what I use.

     /// <summary> Gets the body. </summary>
     /// <returns> The body. </returns>
     protected byte[] GetBytes()
       byte[] bytes;
        using (var binaryReader = new BinaryReader(Request.InputStream))
            bytes = binaryReader.ReadBytes(Request.ContentLength);

         return bytes;

How can I have a newline in a string in sh?

On my system (Ubuntu 17.10) your example just works as desired, both when typed from the command line (into sh) and when executed as a sh script:

[bash]§ sh
$ STR="Hello\nWorld"
$ echo $STR
$ exit
[bash]§ echo "STR=\"Hello\nWorld\"
> echo \$STR" >
[bash]§ cat 
echo $STR
[bash]§ sh 

I guess this answers your question: it just works. (I have not tried to figure out details such as at what moment exactly the substitution of the newline character for \n happens in sh).

However, i noticed that this same script would behave differently when executed with bash and would print out Hello\nWorld instead:

[bash]§ bash

I've managed to get the desired output with bash as follows:

[bash]§ STR="Hello
> World"
[bash]§ echo "$STR"

Note the double quotes around $STR. This behaves identically if saved and run as a bash script.

The following also gives the desired output:

[bash]§ echo "Hello
> World"

Getting the names of all files in a directory with PHP

Don't bother with open/readdir and use glob instead:

foreach(glob($log_directory.'/*.*') as $file) {

Request format is unrecognized for URL unexpectedly ending in

Despite 90% of all the information I found (while trying to find a solution to this error) telling me to add the HttpGet and HttpPost to the configuration, that did not work for me... and didn't make sense to me anyway.

My application is running on lots of servers (30+) and I've never had to add this configuration for any of them. Either the version of the application running under .NET 2.0 or .NET 4.0.

The solution for me was to re-register ASP.NET against IIS.

I used the following command line to achieve this...

C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -i

Android - how to replace part of a string by another string?

It is working, but it wont modify the caller object, but returning a new String.
So you just need to assign it to a new String variable, or to itself:

string = string.replace("to", "xyz");


String newString = string.replace("to", "xyz");

API Docs

public String replace (CharSequence target, CharSequence replacement) 

Since: API Level 1

Copies this string replacing occurrences of the specified target sequence with another sequence. The string is processed from the beginning to the end.


  • target the sequence to replace.
  • replacement the replacement sequence.

Returns the resulting string.
Throws NullPointerException if target or replacement is null.

How to set selectedIndex of select element using display text?

Try this:

function SelectAnimal() {
    var sel = document.getElementById('Animals');
    var val = document.getElementById('AnimalToFind').value;
    for(var i = 0, j = sel.options.length; i < j; ++i) {
        if(sel.options[i].innerHTML === val) {
           sel.selectedIndex = i;

Connect to docker container as user other than root

You can run a shell in a running docker container using a command like:

docker exec -it --user root <container id> /bin/bash

Rename Pandas DataFrame Index

df.index.rename('new name', inplace=True)

Is the only one that does the job for me (pandas 0.22.0).
Without the inplace=True, the name of the index is not set in my case.

Generating 8-character only UUIDs

It is not possible since a UUID is a 16-byte number per definition. But of course, you can generate 8-character long unique strings (see the other answers).

Also be careful with generating longer UUIDs and substring-ing them, since some parts of the ID may contain fixed bytes (e.g. this is the case with MAC, DCE and MD5 UUIDs).

Taking multiple inputs from user in python

How about making the input a list. Then you may use standard list operations.

a=list(input("Enter the numbers"))