Programs & Examples On #Http status codes

HTTP status codes are a set of standardized codes returned in an HTTP web response. Questions about why a service is (unexpectedly) returning a status code should not use this tag.

HTTP response code for POST when resource already exists

More likely it is 400 Bad Request

6.5.1. 400 Bad Request


The 400 (Bad Request) status code indicates that the server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).

As the request contains duplicate value(value that already exists), it can be perceived as a client error. Need to change the request before the next try.
By considering these facts we can conclude as HTTP STATUS 400 Bad Request.

What's the most appropriate HTTP status code for an "item not found" error page

/**
* {@code 422 Unprocessable Entity}.
* @see <a href="https://tools.ietf.org/html/rfc4918#section-11.2">WebDAV</a>
*/
UNPROCESSABLE_ENTITY(422, "Unprocessable Entity")

Python Request Post with param data

Set data to this:

data ={"eventType":"AAS_PORTAL_START","data":{"uid":"hfe3hf45huf33545","aid":"1","vid":"1"}}

REST HTTP status codes for failed validation or invalid duplicate

Ember-Data's ActiveRecord adapter expects 422 UNPROCESSABLE ENTITY to be returned from server. So, if you're client is written in Ember.js you should use 422. Only then DS.Errors will be populated with returned errors. You can of course change 422 to any other code in your adapter.

400 vs 422 response to POST of data

Case study: GitHub API

https://developer.github.com/v3/#client-errors

Maybe copying from well known APIs is a wise idea:

There are three possible types of client errors on API calls that receive request bodies:

Sending invalid JSON will result in a 400 Bad Request response.

HTTP/1.1 400 Bad Request
Content-Length: 35

{"message":"Problems parsing JSON"}

Sending the wrong type of JSON values will result in a 400 Bad Request response.

HTTP/1.1 400 Bad Request
Content-Length: 40

{"message":"Body should be a JSON object"}

Sending invalid fields will result in a 422 Unprocessable Entity response.

HTTP/1.1 422 Unprocessable Entity
Content-Length: 149

{
  "message": "Validation Failed",
  "errors": [
    {
      "resource": "Issue",
      "field": "title",
      "code": "missing_field"
    }
  ]
}

In Python, how do I use urllib to see if a website is 404 or 200?

import urllib2

try:
    fileHandle = urllib2.urlopen('http://www.python.org/fish.html')
    data = fileHandle.read()
    fileHandle.close()
except urllib2.URLError, e:
    print 'you got an error with the code', e

Script to get the HTTP status code of a list of urls?

This relies on widely available wget, present almost everywhere, even on Alpine Linux.

wget --server-response --spider --quiet "${url}" 2>&1 | awk 'NR==1{print $2}'

The explanations are as follow :

--quiet

Turn off Wget's output.

Source - wget man pages

--spider

[ ... ] it will not download the pages, just check that they are there. [ ... ]

Source - wget man pages

--server-response

Print the headers sent by HTTP servers and responses sent by FTP servers.

Source - wget man pages

What they don't say about --server-response is that those headers output are printed to standard error (sterr), thus the need to redirect to stdin.

The output sent to standard input, we can pipe it to awk to extract the HTTP status code. That code is :

  • the second ($2) non-blank group of characters: {$2}
  • on the very first line of the header: NR==1

And because we want to print it... {print $2}.

wget --server-response --spider --quiet "${url}" 2>&1 | awk 'NR==1{print $2}'

Spring: return @ResponseBody "ResponseEntity<List<JSONObject>>"

I am late for this but i want put some more solution relevant to this.

 @GetMapping
public ResponseEntity<List<JSONObject>> getRole() {
    return ResponseEntity.ok(service.getRole());
}

What HTTP status response code should I use if the request is missing a required parameter?

I Usually go for 422 (Unprocessable entity) if something in the required parameters didn't match what the API endpoint required (like a too short password) but for a missing parameter i would go for 406 (Unacceptable).

How do I get the HTTP status code with jQuery?

$.ajax({
    url: "http://my-ip/test/test.php",
    data: {},
    error: function(xhr, statusText, errorThrown){alert(xhr.status);}
});

Set Response Status Code

I had the same issue with CakePHP 2.0.1

I tried using

header( 'HTTP/1.1 400 BAD REQUEST' );

and

$this->header( 'HTTP/1.1 400 BAD REQUEST' );

However, neither of these solved my issue.

I did eventually resolve it by using

$this->header( 'HTTP/1.1 400: BAD REQUEST' );

After that, no errors or warning from php / CakePHP.

*edit: In the last $this->header function call, I put a colon (:) between the 400 and the description text of the error.

How to specify HTTP error code?

In express 4.0 they got it right :)

res.sendStatus(statusCode)
// Sets the response HTTP status code to statusCode and send its string representation as the response body.

res.sendStatus(200); // equivalent to res.status(200).send('OK')
res.sendStatus(403); // equivalent to res.status(403).send('Forbidden')
res.sendStatus(404); // equivalent to res.status(404).send('Not Found')
res.sendStatus(500); // equivalent to res.status(500).send('Internal Server Error')

//If an unsupported status code is specified, the HTTP status is still set to statusCode and the string version of the code is sent as the response body.

res.sendStatus(2000); // equivalent to res.status(2000).send('2000')

HTTP 400 (bad request) for logical error, not malformed request syntax

In my case:

I am getting 400 bad request because I set content-type wrongly. I changed content type then able to get response successfully.

Before (Issue):

ClientResponse response = Client.create().resource(requestUrl).queryParam("noOfDates", String.valueOf(limit))
                .header(SecurityConstants.AUTHORIZATION, formatedToken).
header("Content-Type", "\"application/json\"").get(ClientResponse.class);

After (Fixed):

ClientResponse response = Client.create().resource(requestUrl).queryParam("noOfDates", String.valueOf(limit))
                .header(SecurityConstants.AUTHORIZATION, formatedToken).
header("Content-Type", "\"application/x-www-form-urlencoded\"").get(ClientResponse.class);

JAX-RS — How to return JSON and HTTP status code together?

The answer by hisdrewness will work, but it modifies the whole approach to letting a provider such as Jackson+JAXB automatically convert your returned object to some output format such as JSON. Inspired by an Apache CXF post (which uses a CXF-specific class) I've found one way to set the response code that should work in any JAX-RS implementation: inject an HttpServletResponse context and manually set the response code. For example, here is how to set the response code to CREATED when appropriate.

@Path("/foos/{fooId}")
@PUT
@Consumes("application/json")
@Produces("application/json")
public Foo setFoo(@PathParam("fooID") final String fooID, final Foo foo, @Context final HttpServletResponse response)
{
  //TODO store foo in persistent storage
  if(itemDidNotExistBefore) //return 201 only if new object; TODO app-specific logic
  {
    response.setStatus(Response.Status.CREATED.getStatusCode());
  }
  return foo;  //TODO get latest foo from storage if needed
}

Improvement: After finding another related answer, I learned that one can inject the HttpServletResponse as a member variable, even for singleton service class (at least in RESTEasy)!! This is a much better approach than polluting the API with implementation details. It would look like this:

@Context  //injected response proxy supporting multiple threads
private HttpServletResponse response;

@Path("/foos/{fooId}")
@PUT
@Consumes("application/json")
@Produces("application/json")
public Foo setFoo(@PathParam("fooID") final String fooID, final Foo foo)
{
  //TODO store foo in persistent storage
  if(itemDidNotExistBefore) //return 201 only if new object; TODO app-specific logic
  {
    response.setStatus(Response.Status.CREATED.getStatusCode());
  }
  return foo;  //TODO get latest foo from storage if needed
}

Returning http status code from Web Api controller

For ASP.NET Web Api 2, this post from MS suggests to change the method's return type to IHttpActionResult. You can then return a built in IHttpActionResult implementation like Ok, BadRequest, etc (see here) or return your own implementation.

For your code, it could be done like:

public IHttpActionResult GetUser(int userId, DateTime lastModifiedAtClient)
{
    var user = new DataEntities().Users.First(p => p.Id == userId);
    if (user.LastModified <= lastModifiedAtClient)
    {
        return StatusCode(HttpStatusCode.NotModified);
    }
    return Ok(user);
}

How to get HTTP response code for a URL in Java?

You could try the following:

class ResponseCodeCheck 
{

    public static void main (String args[]) throws Exception
    {

        URL url = new URL("http://google.com");
        HttpURLConnection connection = (HttpURLConnection)url.openConnection();
        connection.setRequestMethod("GET");
        connection.connect();

        int code = connection.getResponseCode();
        System.out.println("Response code of the object is "+code);
        if (code==200)
        {
            System.out.println("OK");
        }
    }
}

Should a 502 HTTP status code be used if a proxy receives no response at all?

Yes. Empty or incomplete headers or response body typically caused by broken connections or server side crash can cause 502 errors if accessed via a gateway or proxy.

For more information about the network errors

https://en.wikipedia.org/wiki/List_of_HTTP_status_codes

HTTP Get with 204 No Content: Is that normal

The POST/GET with 204 seems fine in the first sight and will also work.

Documentation says, 2xx -- This class of status codes indicates the action requested by the client was received, understood, accepted, and processed successfully. whereas 4xx -- The 4xx class of status code is intended for situations in which the client seems to have erred.

Since, the request was successfully received, understood and processed on server. The result was that the resource was not found. So, in this case this was not an error on the client side or the client has not erred.

Hence this should be a series 2xx code and not 4xx. Sending 204 (No Content) in this case will be better than a 404 or 410 response.

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

200 (cache) means Firefox is simply using the locally cached version. This is the fastest because no request to the Web server is made.

304 means Firefox is sending a "If-Modified-Since" conditional request to the Web server. If the file has not been updated since the date sent by the browser, the Web server returns a 304 response which essentially tells Firefox to use its cached version. It is not as fast as 200 (cache) because the request is still sent to the Web server, but the server doesn't have to send the contents of the file.

To your last question, I don't know why the two JavaScript files in the same directory are returning different results.

Throw HttpResponseException or return Request.CreateErrorResponse?

Case #1

  1. Not necessarily, there are other places in the pipeline to modify the response (action filters, message handlers).
  2. See above -- but if the action returns a domain model, then you can't modify the response inside the action.

Cases #2-4

  1. The main reasons to throw HttpResponseException are:
    • if you are returning a domain model but need to handle error cases,
    • to simplify your controller logic by treating errors as exceptions
  2. These should be equivalent; HttpResponseException encapsulates an HttpResponseMessage, which is what gets returned back as the HTTP response.

    e.g., case #2 could be rewritten as

    public HttpResponseMessage Get(string id)
    {
        HttpResponseMessage response;
        var customer = _customerService.GetById(id);
        if (customer == null)
        {
            response = new HttpResponseMessage(HttpStatusCode.NotFound);
        }
        else
        {
            response = Request.CreateResponse(HttpStatusCode.OK, customer);
            response.Content.Headers.Expires = new DateTimeOffset(DateTime.Now.AddSeconds(300));
        }
        return response;
    }
    

    ... but if your controller logic is more complicated, throwing an exception might simplify the code flow.

  3. HttpError gives you a consistent format for the response body and can be serialized to JSON/XML/etc, but it's not required. e.g., you may not want to include an entity-body in the response, or you might want some other format.

HTTP status code for update and delete?

Short answer: for both PUT and DELETE, you should send either 200 (OK) or 204 (No Content).

Long answer: here's a complete decision diagram (click to magnify).

HTTP 1.1 decision diagram

Source: https://github.com/for-GET/http-decision-diagram

403 Forbidden vs 401 Unauthorized HTTP responses

Given the latest RFC's on the matter (7231 and 7235) the use-case seems quite clear (italics added):

  • 401 is for unauthenticated ("lacks valid authentication"); i.e. 'I don't know who you are, or I don't trust you are who you say you are.'

401 Unauthorized

The 401 (Unauthorized) status code indicates that the request has not been applied because it lacks valid authentication credentials for the target resource. The server generating a 401 response MUST send a WWW-Authenticate header field (Section 4.1) containing at least one challenge applicable to the target resource.

If the request included authentication credentials, then the 401 response indicates that authorization has been refused for those credentials. The user agent MAY repeat the request with a new or replaced Authorization header field (Section 4.2). If the 401 response contains the same challenge as the prior response, and the user agent has already attempted authentication at least once, then the user agent SHOULD present the enclosed representation to the user, since it usually contains relevant diagnostic information.

  • 403 is for unauthorized ("refuses to authorize"); i.e. 'I know who you are, but you don't have permission to access this resource.'

403 Forbidden

The 403 (Forbidden) status code indicates that the server understood the request but refuses to authorize it. A server that wishes to make public why the request has been forbidden can describe that reason in the response payload (if any).

If authentication credentials were provided in the request, the server considers them insufficient to grant access. The client SHOULD NOT automatically repeat the request with the same credentials. The client MAY repeat the request with new or different credentials. However, a request might be forbidden for reasons unrelated to the credentials.

An origin server that wishes to "hide" the current existence of a forbidden target resource MAY instead respond with a status code of 404 (Not Found).

How do I resolve a HTTP 414 "Request URI too long" error?

I have a simple workaround.

Suppose your URI has a string stringdata that is too long. You can simply break it into a number of parts depending on the limits of your server. Then submit the first one, in my case to write a file. Then submit the next ones to append to previously added data.

Laravel - Return json along with http status code

laravel 7.* You don't have to speicify JSON RESPONSE cause it's automatically converted it to JSON

return response(['Message'=>'Wrong Credintals'], 400);

System.Net.WebException HTTP status code

this works only if WebResponse is a HttpWebResponse.

try
{
    ...
}
catch (System.Net.WebException exc)
{
    var webResponse = exc.Response as System.Net.HttpWebResponse;
    if (webResponse != null && 
        webResponse.StatusCode == System.Net.HttpStatusCode.Unauthorized)
    {
        MessageBox.Show("401");
    }
    else
        throw;
}

Create request with POST, which response codes 200 or 201 and content

Another answer I would have for this would be to take a pragmatic approach and keep your REST API contract simple. In my case I had refactored my REST API to make things more testable without resorting to JavaScript or XHR, just simple HTML forms and links.

So to be more specific on your question above, I'd just use return code 200 and have the returned message contain a JSON message that your application can understand. Depending on your needs it may require the ID of the object that is newly created so the web application can get the data in another call.

One note, in my refactored API contract, POST responses should not contain any cacheable data as POSTs are not really cachable, so limit it to IDs that can be requested and cached using a GET request.

What's an appropriate HTTP status code to return by a REST API service for a validation failure?

If "validation failure" means that there is some client error in the request, then use HTTP 400 (Bad Request). For instance if the URI is supposed to have an ISO-8601 date and you find that it's in the wrong format or refers to February 31st, then you would return an HTTP 400. Ditto if you expect well-formed XML in an entity body and it fails to parse.

(1/2016): Over the last five years WebDAV's more specific HTTP 422 (Unprocessable Entity) has become a very reasonable alternative to HTTP 400. See for instance its use in JSON API. But do note that HTTP 422 has not made it into HTTP 1.1, RFC-7231.

Richardson and Ruby's RESTful Web Services contains a very helpful appendix on when to use the various HTTP response codes. They say:

400 (“Bad Request”)
Importance: High.
This is the generic client-side error status, used when no other 4xx error code is appropriate. It’s commonly used when the client submits a representation along with a PUT or POST request, and the representation is in the right format, but it doesn’t make any sense. (p. 381)

and:

401 (“Unauthorized”)
Importance: High.
The client tried to operate on a protected resource without providing the proper authentication credentials. It may have provided the wrong credentials, or none at all. The credentials may be a username and password, an API key, or an authentication token—whatever the service in question is expecting. It’s common for a client to make a request for a URI and accept a 401 just so it knows what kind of credentials to send and in what format. [...]

Why is AJAX returning HTTP status code 0?

Status code 0 means the requested url is not reachable. By changing http://something/something to https://something/something worked for me. IE throwns an error saying "permission denied" when the status code is 0, other browsers dont.

HTTP status code 0 - Error Domain=NSURLErrorDomain?

There is no HTTP status code 0. What you see is a 0 returned by the API/library that you are using. You will have to check the documentation for that.

How to update a value, given a key in a hashmap?

The simplified Java 8 way:

map.put(key, map.getOrDefault(key, 0) + 1);

This uses the method of HashMap that retrieves the value for a key, but if the key can't be retrieved it returns the specified default value (in this case a '0').

This is supported within core Java: HashMap<K,V> getOrDefault(Object key, V defaultValue)

Fatal error: Call to undefined function socket_create()

I got this error when my .env file was not set up properly. Make sure you have a .env file with valid database login credentials.

How to install numpy on windows using pip install?

Frustratingly the Numpy package published to PyPI won't install on most Windows computers https://github.com/numpy/numpy/issues/5479

Instead:

  1. Download the Numpy wheel for your Python version from http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy
  2. Install it from the command line pip install numpy-1.10.2+mkl-cp35-none-win_amd64.whl

How to compile C++ under Ubuntu Linux?

Use g++. And make sure you have the relevant libraries installed.

What's the difference between 'r+' and 'a+' when open file in python?

If you have used them in C, then they are almost same as were in C.

From the manpage of fopen() function : -

  • r+ : - Open for reading and writing. The stream is positioned at the beginning of the file.

  • a+ : - Open for reading and writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subse- quent writes to the file will always end up at the then current end of file, irrespective of any intervening fseek(3) or similar.

HREF="" automatically adds to current page URL (in PHP). Can't figure it out

You do realize this is the default behavior, right? if you add /something the results would be different.

you can do a number of things to prevent default behavior.

href="#":

Will do nothing but anchor - not the best solution since it may jump to page top.

<a href="#">

href="javascript:void(0);"

Will do nothing at all and is perfectly legit.

<a href="javascript:void(0);"></a>

href="your-actual-intended-link" (Best)

obviously the best.

<a href="<your-actual-intended-link>"></a>

If you don't want an a tag to go somewhere, why use an a tag at all?

How to find file accessed/created just few minutes ago

To find files accessed 1, 2, or 3 minutes ago use -3

find . -cmin -3

What is the 'new' keyword in JavaScript?

The new keyword creates instances of objects using functions as a constructor. For instance:

var Foo = function() {};
Foo.prototype.bar = 'bar';

var foo = new Foo();
foo instanceof Foo; // true

Instances inherit from the prototype of the constructor function. So given the example above...

foo.bar; // 'bar'

PHP refresh window? equivalent to F5 page reload?

All you need to do to manually refresh a page is to provide a link pointing to the same page

Like this: Refresh the selection

WordPress Get the Page ID outside the loop

This is the correct code.

echo $post->ID;

How to pass datetime from c# to sql correctly?

I had many issues involving C# and SqlServer. I ended up doing the following:

  1. On SQL Server I use the DateTime column type
  2. On c# I use the .ToString("yyyy-MM-dd HH:mm:ss") method

Also make sure that all your machines run on the same timezone.

Regarding the different result sets you get, your first example is "July First" while the second is "4th of July" ...

Also, the second example can be also interpreted as "April 7th", it depends on your server localization configuration (my solution doesn't suffer from this issue).

EDIT: hh was replaced with HH, as it doesn't seem to capture the correct hour on systems with AM/PM as opposed to systems with 24h clock. See the comments below.

Split a vector into chunks

I need a function that takes the argument of a data.table (in quotes) and another argument that is the upper limit on the number of rows in the subsets of that original data.table. This function produces whatever number of data.tables that upper limit allows for:

library(data.table)    
split_dt <- function(x,y) 
    {
    for(i in seq(from=1,to=nrow(get(x)),by=y)) 
        {df_ <<- get(x)[i:(i + y)];
            assign(paste0("df_",i),df_,inherits=TRUE)}
    rm(df_,inherits=TRUE)
    }

This function gives me a series of data.tables named df_[number] with the starting row from the original data.table in the name. The last data.table can be short and filled with NAs so you have to subset that back to whatever data is left. This type of function is useful because certain GIS software have limits on how many address pins you can import, for example. So slicing up data.tables into smaller chunks may not be recommended, but it may not be avoidable.

Select count(*) from result query

select count(*) from(select count(SID) from Test where Date = '2012-12-10' group by SID)select count(*) from(select count(SID) from Test where Date = '2012-12-10' group by SID)

should works

Why do I get a warning icon when I add a reference to an MEF plugin project?

For me, I ran into this issue when referencing a .NET Standard 2.0 class library in a .NET Framework 4.7.1 console application. Yes, the frameworks are different, but they are compatible (.NET Standard is supposed to jive with both .NET Core and .NET Framework.) I tried cleaning, rebuilding, removing and readding the project reference, etc... with no success. Finally, quitting Visual Studio and reopening resolved the issue.

How to get StackPanel's children to fill maximum space downward?

An alternative method is to use a Grid with one column and n rows. Set all the rows heights to Auto, and the bottom-most row height to 1*.

I prefer this method because I've found Grids have better layout performance than DockPanels, StackPanels, and WrapPanels. But unless you're using them in an ItemTemplate (where the layout is being performed for a large number of items), you'll probably never notice.

How to make a select with array contains value clause in psql

Note that this may also work:

SELECT * FROM table WHERE s=ANY(array)

How to import existing Git repository into another?

I can suggest another solution (alternative to git-submodules) for your problem - gil (git links) tool

It allows to describe and manage complex git repositories dependencies.

Also it provides a solution to the git recursive submodules dependency problem.

Consider you have the following project dependencies: sample git repository dependency graph

Then you can define .gitlinks file with repositories relation description:

# Projects
CppBenchmark CppBenchmark https://github.com/chronoxor/CppBenchmark.git master
CppCommon CppCommon https://github.com/chronoxor/CppCommon.git master
CppLogging CppLogging https://github.com/chronoxor/CppLogging.git master

# Modules
Catch2 modules/Catch2 https://github.com/catchorg/Catch2.git master
cpp-optparse modules/cpp-optparse https://github.com/weisslj/cpp-optparse.git master
fmt modules/fmt https://github.com/fmtlib/fmt.git master
HdrHistogram modules/HdrHistogram https://github.com/HdrHistogram/HdrHistogram_c.git master
zlib modules/zlib https://github.com/madler/zlib.git master

# Scripts
build scripts/build https://github.com/chronoxor/CppBuildScripts.git master
cmake scripts/cmake https://github.com/chronoxor/CppCMakeScripts.git master

Each line describe git link in the following format:

  1. Unique name of the repository
  2. Relative path of the repository (started from the path of .gitlinks file)
  3. Git repository which will be used in git clone command Repository branch to checkout
  4. Empty line or line started with # are not parsed (treated as comment).

Finally you have to update your root sample repository:

# Clone and link all git links dependencies from .gitlinks file
gil clone
gil link

# The same result with a single command
gil update

As the result you'll clone all required projects and link them to each other in a proper way.

If you want to commit all changes in some repository with all changes in child linked repositories you can do it with a single command:

gil commit -a -m "Some big update"

Pull, push commands works in a similar way:

gil pull
gil push

Gil (git links) tool supports the following commands:

usage: gil command arguments
Supported commands:
    help - show this help
    context - command will show the current git link context of the current directory
    clone - clone all repositories that are missed in the current context
    link - link all repositories that are missed in the current context
    update - clone and link in a single operation
    pull - pull all repositories in the current directory
    push - push all repositories in the current directory
    commit - commit all repositories in the current directory

More about git recursive submodules dependency problem.

Could not load file or assembly ... An attempt was made to load a program with an incorrect format (System.BadImageFormatException)

I just had this error message running IIS Express in Visual Studio 2015. In my case I needed to be running the 64 bit version of IIS Express:

Tools ? Options ? Projects and Solutions ? Web Projects
Check the box that says "Use the 64 bit version of IIS Express for web sites and projects".

Screenshot:

Screenshot of VS options for Web Project.

How to manage startActivityForResult on Android?

How to check the result from the main activity?

You need to override Activity.onActivityResult() then check its parameters:

  • requestCode identifies which app returned these results. This is defined by you when you call startActivityForResult().
  • resultCode informs you whether this app succeeded, failed, or something different
  • data holds any information returned by this app. This may be null.

Allow anything through CORS Policy

Have a look at the rack-cors middleware. It will handle CORS headers in a configurable manner.

angular2 submit form by pressing enter without submit button

If you want to include both - accept on enter and accept on click then do -

 <div class="form-group">
    <input class="form-control"   type="text" 
    name="search" placeholder="Enter Search Text"
              [(ngModel)]="filterdata"  
           (keyup.enter)="searchByText(filterdata)">
  <button type="submit"  
          (click)="searchByText(filterdata)" >

  </div>

How to loop through a checkboxlist and to find what's checked and not checked?

for (int i = 0; i < clbIncludes.Items.Count; i++)
  if (clbIncludes.GetItemChecked(i))
    // Do selected stuff
  else
    // Do unselected stuff

If the the check is in indeterminate state, this will still return true. You may want to replace

if (clbIncludes.GetItemChecked(i))

with

if (clbIncludes.GetItemCheckState(i) == CheckState.Checked)

if you want to only include actually checked items.

ValueError: unconverted data remains: 02:05

  timeobj = datetime.datetime.strptime(my_time, '%Y-%m-%d %I:%M:%S')
  File "/usr/lib/python2.7/_strptime.py", line 335, in _strptime
    data_string[found.end():])
ValueError: unconverted data remains:

In my case, the problem was an extra space in the input date string. So I used strip() and it started to work.

How to pass arguments to a Button command in Tkinter?

The best thing to do is use lambda as follows:

button = Tk.Button(master=frame, text='press', command=lambda: action(someNumber))

How do I check if a directory exists? "is_dir", "file_exists" or both?

Well instead of checking both, you could do if(stream_resolve_include_path($folder)!==false). It is slower but kills two birds in one shot.

Another option is to simply ignore the E_WARNING, not by using @mkdir(...); (because that would simply waive all possible warnings, not just the directory already exists one), but by registering a specific error handler before doing it:

namespace com\stackoverflow;

set_error_handler(function($errno, $errm) { 
    if (strpos($errm,"exists") === false) throw new \Exception($errm); //or better: create your own FolderCreationException class
});
mkdir($folder);
/* possibly more mkdir instructions, which is when this becomes useful */
restore_error_handler();

Non-Static method cannot be referenced from a static context with methods and variables

You should place Scanner input = new Scanner (System.in); into the main method rather than creating the input object outside.

How to round 0.745 to 0.75 using BigDecimal.ROUND_HALF_UP?

For your interest, to do the same with double

double doubleVal = 1.745;
double doubleVal2 = 0.745;
doubleVal = Math.round(doubleVal * 100 + 0.005) / 100.0;
doubleVal2 = Math.round(doubleVal2 * 100 + 0.005) / 100.0;
System.out.println("bdTest: " + doubleVal); //1.75
System.out.println("bdTest1: " + doubleVal2);//0.75

or just

double doubleVal = 1.745;
double doubleVal2 = 0.745;
System.out.printf("bdTest: %.2f%n",  doubleVal);
System.out.printf("bdTest1: %.2f%n",  doubleVal2);

both print

bdTest: 1.75
bdTest1: 0.75

I prefer to keep code as simple as possible. ;)

As @mshutov notes, you need to add a little more to ensure that a half value always rounds up. This is because numbers like 265.335 are a little less than they appear.

Match whitespace but not newlines

The below regex would match white spaces but not of a new line character.

(?:(?!\n)\s)

DEMO

If you want to add carriage return also then add \r with the | operator inside the negative lookahead.

(?:(?![\n\r])\s)

DEMO

Add + after the non-capturing group to match one or more white spaces.

(?:(?![\n\r])\s)+

DEMO

I don't know why you people failed to mention the POSIX character class [[:blank:]] which matches any horizontal whitespaces (spaces and tabs). This POSIX chracter class would work on BRE(Basic REgular Expressions), ERE(Extended Regular Expression), PCRE(Perl Compatible Regular Expression).

DEMO

Warning: implode() [function.implode]: Invalid arguments passed

You are getting the error because $ret is not an array.

To get rid of the error, at the start of your function, define it with this line: $ret = array();

It appears that the get_tags() call is returning nothing, so the foreach is not run, which means that $ret isn't defined.

Markdown and including multiple files

Just recently I wrote something like this in Node called markdown-include that allows you to include markdown files with C style syntax, like so:

#include "my-file.md"

I believe this aligns nicely with the question you're asking. I know this an old one, but I wanted to update it at least.

You can include this in any markdown file you wish. That file can also have more includes and markdown-include will make an internal link and do all of the work for you.

You can download it via npm

npm install -g markdown-include

TLS 1.2 not working in cURL

You must use an integer value for the CURLOPT_SSLVERSION value, not a string as listed above

Try this:

curl_setopt ($setuploginurl, CURLOPT_SSLVERSION, 6); //Integer NOT string TLS v1.2

http://php.net/manual/en/function.curl-setopt.php

value should be an integer for the following values of the option parameter: CURLOPT_SSLVERSION

One of

CURL_SSLVERSION_DEFAULT (0)
CURL_SSLVERSION_TLSv1 (1)
CURL_SSLVERSION_SSLv2 (2)
CURL_SSLVERSION_SSLv3 (3)
CURL_SSLVERSION_TLSv1_0 (4)
CURL_SSLVERSION_TLSv1_1 (5)
CURL_SSLVERSION_TLSv1_2 (6).

How to get whole and decimal part of a number?

I was having a hard time finding a way to actually separate the dollar amount and the amount after the decimal. I think I figured it out mostly and thought to share if any of yall were having trouble

So basically...

if price is 1234.44... whole would be 1234 and decimal would be 44 or

if price is 1234.01... whole would be 1234 and decimal would be 01 or

if price is 1234.10... whole would be 1234 and decimal would be 10

and so forth

$price = 1234.44;

$whole = intval($price); // 1234
$decimal1 = $price - $whole; // 0.44000000000005 uh oh! that's why it needs... (see next line)
$decimal2 = round($decimal1, 2); // 0.44 this will round off the excess numbers
$decimal = substr($decimal2, 2); // 44 this removed the first 2 characters

if ($decimal == 1) { $decimal = 10; } // Michel's warning is correct...
if ($decimal == 2) { $decimal = 20; } // if the price is 1234.10... the decimal will be 1...
if ($decimal == 3) { $decimal = 30; } // so make sure to add these rules too
if ($decimal == 4) { $decimal = 40; }
if ($decimal == 5) { $decimal = 50; }
if ($decimal == 6) { $decimal = 60; }
if ($decimal == 7) { $decimal = 70; }
if ($decimal == 8) { $decimal = 80; }
if ($decimal == 9) { $decimal = 90; }

echo 'The dollar amount is ' . $whole . ' and the decimal amount is ' . $decimal;

LOAD DATA INFILE Error Code : 13

  1. GRANT ALL PRIVILEGES ON db_name.* TO 'db_user'@'localhost';
  2. GRANT FILE on .* to 'db_user'@'localhost' IDENTIFIED BY 'password';
  3. FLUSH PRIVILEGES;
  4. SET GLOBAL local_infile = 1;
  5. Variable in the config of the MYSQL "secure-file-priv" must be empty line!!!

"SELECT ... IN (SELECT ...)" query in CodeIgniter

Also, to note - the Active Record Class also has a $this->db->where_in() method.

How to destroy an object?

A handy post explaining several mis-understandings about this:

Don't Call The Destructor explicitly

This covers several misconceptions about how the destructor works. Calling it explicitly will not actually destroy your variable, according to the PHP5 doc:

PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as C++. The destructor method will be called as soon as there are no other references to a particular object, or in any order during the shutdown sequence.

The post above does state that setting the variable to null can work in some cases, as long as nothing else is pointing to the allocated memory.

change PATH permanently on Ubuntu

Add

export PATH=$PATH:/home/me/play

to your ~/.profile and execute

source ~/.profile 

in order to immediately reflect changes to your current terminal instance.

DNS problem, nslookup works, ping doesn't

I know it's not your specific problem, but I faced the same symptoms when I configured a static IP address in the network adapter settings and forgot to enter a "Default Gateway".

Leaving the field blank, the network icon shows an Internet connection, and I could ping internal servers but not external ones, so I assumed it was a DNS problem. NSLookup still worked, but of course, ping failed to find the server (again, seemed like a DNS issue.) Anyway, one more thing to check. =P

Insert current date/time using now() in a field using MySQL/PHP

You forgot to close the mysql_query command:

mysql_query("INSERT INTO users (first, last, whenadded) VALUES ('$first', '$last', now())");

Note that last parentheses.

MAC addresses in JavaScript

Nope. The reason ActiveX can do it is because ActiveX is a little application that runs on the client's machine.

I would imagine access to such information via JavaScript would be a security vulnerability.

IF - ELSE IF - ELSE Structure in Excel

Say P7 is a Cell then you can use the following Syntex to check the value of the cell and assign appropriate value to another cell based on this following nested if:

=IF(P7=0,200,IF(P7=1,100,IF(P7=2,25,IF(P7=3,10,IF((P7=4),5,0)))))

Auto Increment after delete in MySQL

MYSQL Query Auto Increment Solution. It works perfect when you have inserted many records during testing phase of software. Now you want to launch your application live to your client and You want to start auto increment from 1.

To avoid any unwanted problems, for safer side First export .sql file.
Then follow the below steps:

  • Step 1) First Create the copy of an existing table MySQL Command to create Copy:

    CREATE TABLE new_Table_Name  SELECT * FROM existing_Table_Name;
    

    The exact copy of a table is created with all rows except Constraints.
    It doesn’t copy constraints like Auto Increment and Primary Key into new_Table_name

  • Step 2) Delete All rows If Data is not inserted in testing phase and it is not useful. If Data is important then directly go to Step 3.

    DELETE from new_Table_Name;
    
  • Step 3) To Add Constraints, Goto Structure of a table

    • 3A) Add primary key constraint from More option (If You Require).
    • 3B) Add Auto Increment constraint from Change option. For this set Defined value as None.
    • 3C) Delete existing_Table_Name and
    • 3D) rename new_Table_Name to existing_Table_Name.

Now It will work perfectly. The new first record will take first value in Auto Increment column.

Google Maps setCenter()

I searched and searched and finally found that ie needs to know the map size. Set the map size to match the div size.

map = new GMap2(document.getElementById("map_canvas2"), { size: new GSize(850, 600) });

<div id="map_canvas2" style="width: 850px; height: 600px">
</div>

What is the difference between functional and non-functional requirements?

functional requirements are the main things that the user expects from the software for example if the application is a banking application that application should be able to create a new account, update the account, delete an account, etc. functional requirements are detailed and are specified in the system design

Non-functional requirement are not straight forward the requirement of the system rather it is related to usability( in some way ) for example for a banking application a major non-functional requirement will be available the application should be available 24/7 with no downtime if possible.

Ascending and Descending Number Order in java

You could take the ascending array and output in reverse order, so replace the second for statement with:

for(int i = arr.length - 1; i >= 0; i--) {
    ...
}

If you have Apache's commons-lang on the classpath, it has a method ArrayUtils.reverse(int[]) that you can use.

By the way, you probably don't want to sort it in every cycle of the for loop.

Get the time of a datetime using T-SQL?

Assuming the title of your question is correct and you want the time:

SELECT CONVERT(char,GETDATE(),14) 

Edited to include millisecond.

Sort array by firstname (alphabetically) in Javascript

You can use something similar, to get rid of case sensitive

users.sort(function(a, b){

  //compare two values
  if(a.firstname.toLowerCase() < b.firstname.toLowerCase()) return -1;
  if(a.firstname.toLowerCase() > b.firstname.toLowerCase()) return 1;
  return 0;

})

What's wrong with nullable columns in composite primary keys?

Primary keys are for uniquely identifying rows. This is done by comparing all parts of a key to the input.

Per definition, NULL cannot be part of a successful comparison. Even a comparison to itself (NULL = NULL) will fail. This means a key containing NULL would not work.

Additonally, NULL is allowed in a foreign key, to mark an optional relationship.(*) Allowing it in the PK as well would break this.


(*)A word of caution: Having nullable foreign keys is not clean relational database design.

If there are two entities A and B where A can optionally be related to B, the clean solution is to create a resolution table (let's say AB). That table would link A with B: If there is a relationship then it would contain a record, if there isn't then it would not.

how to console.log result of this ajax call?

$.ajax({
    type: 'POST',
    url: 'loginCheck',
    data: $(formLogin).serialize(),    
    success: function(result){
        console.log('my message' + result);
    }
});

'Source code does not match the bytecode' when debugging on a device

My app is compiled on API LEVEL 29, but debugging on real device on API LEVEL 28.I got the warning source code does not match the bytecode in AndroidStudio.I fixed it thought these steps:

  1. Go to Preferences>Instant Run: uncheck the instant run

  2. Go to Build>Clean Build

  3. Re-RUN the app

Now, the debug runs normal.

String parsing in Java with delimiter tab "\t" using split

String[] columnDetail = new String[11];
columnDetail = column.split("\t", -1); // unlimited
OR
columnDetail = column.split("\t", 11); // if you are sure about limit.
 * The {@code limit} parameter controls the number of times the
 * pattern is applied and therefore affects the length of the resulting
 * array.  If the limit <i>n</i> is greater than zero then the pattern
 * will be applied at most <i>n</i>&nbsp;-&nbsp;1 times, the array's
 * length will be no greater than <i>n</i>, and the array's last entry
 * will contain all input beyond the last matched delimiter.  If <i>n</i>
 * is non-positive then the pattern will be applied as many times as
 * possible and the array can have any length.  If <i>n</i> is zero then
 * the pattern will be applied as many times as possible, the array can
 * have any length, and trailing empty strings will be discarded.

Calendar date to yyyy-MM-dd format in java

Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 7);
Date date = c.getTime();
SimpleDateFormat ft = new SimpleDateFormat("MM-dd-YYYY");
JOptionPane.showMessageDialog(null, ft.format(date));

This will display your date + 7 days in month, day and year format in a JOption window pane.

See line breaks and carriage returns in editor

To disagree with the official answer:

:set list will not show ^M characters (CRs). Supplying the -b option to vi/vim will work. Or, once vim is loaded, type :e ++ff=unix.

Export to xls using angularjs

You can try Alasql JavaScript library which can work together with XLSX.js library for easy export of Angular.js data. This is an example of controller with exportData() function:

function myCtrl($scope) {
  $scope.exportData = function () {
    alasql('SELECT * INTO XLSX("john.xlsx",{headers:true}) FROM ?',[$scope.items]);
  };

  $scope.items = [{
    name: "John Smith",
    email: "[email protected]",
    dob: "1985-10-10"
  }, {
    name: "Jane Smith",
    email: "[email protected]",
    dob: "1988-12-22"
  }];
}

See full HTML and JavaScript code for this example in jsFiddle.

UPDATED Another example with coloring cells.

Also you need to include two libraries:

source of historical stock data

Let me add a source I just discovered, found here.

It has lots of historical stock data in csv format and was gathered by Andy Pavlo, who according to his homepage is an "Assistant Professor in the Computer Science Department at Carnegie Mellon University".

Changing the JFrame title

I strongly recommend you learn how to use layout managers to get the layout you want to see. null layouts are fragile, and cause no end of trouble.

Try this source & check the comments.

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class VolumeCalculator extends JFrame implements ActionListener {
    private JTabbedPane jtabbedPane;
    private JPanel options;
    JTextField poolLengthText, poolWidthText, poolDepthText, poolVolumeText, hotTub,
            hotTubLengthText, hotTubWidthText, hotTubDepthText, hotTubVolumeText, temp, results,
            myTitle;
    JTextArea labelTubStatus;

    public VolumeCalculator(){
        setSize(400, 250);
        setVisible(true);
        setSize(400, 250);
        setVisible(true);
        setTitle("Volume Calculator");
        setSize(300, 200);
        JPanel topPanel = new JPanel();
        topPanel.setLayout(new BorderLayout());
        getContentPane().add(topPanel);

        createOptions();

        jtabbedPane = new JTabbedPane();

        jtabbedPane.addTab("Options", options);

        topPanel.add(jtabbedPane, BorderLayout.CENTER);
    }
    /* CREATE OPTIONS */

    public void createOptions(){
        options = new JPanel();
        //options.setLayout(null);
        JLabel labelOptions = new JLabel("Change Company Name:");
        labelOptions.setBounds(120, 10, 150, 20);
        options.add(labelOptions);
        JTextField newTitle = new JTextField("Some Title");
        //newTitle.setBounds(80, 40, 225, 20);    
        options.add(newTitle);
        myTitle = new JTextField(20);
        // myTitle WAS NEVER ADDED to the GUI!
        options.add(myTitle);
        //myTitle.setBounds(80, 40, 225, 20);
        //myTitle.add(labelOptions);
        JButton newName = new JButton("Set New Name");
        //newName.setBounds(60, 80, 150, 20);
        newName.addActionListener(this);
        options.add(newName);
        JButton Exit = new JButton("Exit");
        //Exit.setBounds(250, 80, 80, 20);
        Exit.addActionListener(this);
        options.add(Exit);
    }

    public void actionPerformed(ActionEvent event){
        JButton button = (JButton) event.getSource();
        String buttonLabel = button.getText();
        if ("Exit".equalsIgnoreCase(buttonLabel)){
            Exit_pressed();
            return;
        }
        if ("Set New Name".equalsIgnoreCase(buttonLabel)){
            New_Name();
            return;
        }
    }

    private void Exit_pressed(){
        System.exit(0);
    }

    private void New_Name(){
        System.out.println("'" + myTitle.getText() + "'");
        this.setTitle(myTitle.getText());
    }

    private void Options(){
    }

    public static void main(String[] args){
        JFrame frame = new VolumeCalculator();
        frame.pack();
        frame.setSize(380, 350);
        frame.setVisible(true);
    }
}

HQL "is null" And "!= null" on an Oracle column

That is a binary operator in hibernate you should use

is not null

Have a look at 14.10. Expressions

Windows command to convert Unix line endings?

My contribution for this, converting several files in a folder: for %%z in (*.txt) do (for /f "delims=" %%i in (%%z) do @echo %%i)>%%z.tmp

Removing all line breaks and adding them after certain text

You can also go to Notepad++ and do the following steps:

Edit->LineOperations-> Remove Empty Lines or Remove Empty Lines(Containing blank characters)

Checking if a number is an Integer in Java

One example more :)

double a = 1.00

if(floor(a) == a) {
   // a is an integer
} else {
   //a is not an integer.
}

In this example, ceil can be used and have the exact same effect.

How do I verify that a string only contains letters, numbers, underscores and dashes?

[Edit] There's another solution not mentioned yet, and it seems to outperform the others given so far in most cases.

Use string.translate to replace all valid characters in the string, and see if we have any invalid ones left over. This is pretty fast as it uses the underlying C function to do the work, with very little python bytecode involved.

Obviously performance isn't everything - going for the most readable solutions is probably the best approach when not in a performance critical codepath, but just to see how the solutions stack up, here's a performance comparison of all the methods proposed so far. check_trans is the one using the string.translate method.

Test code:

import string, re, timeit

pat = re.compile('[\w-]*$')
pat_inv = re.compile ('[^\w-]')
allowed_chars=string.ascii_letters + string.digits + '_-'
allowed_set = set(allowed_chars)
trans_table = string.maketrans('','')

def check_set_diff(s):
    return not set(s) - allowed_set

def check_set_all(s):
    return all(x in allowed_set for x in s)

def check_set_subset(s):
    return set(s).issubset(allowed_set)

def check_re_match(s):
    return pat.match(s)

def check_re_inverse(s): # Search for non-matching character.
    return not pat_inv.search(s)

def check_trans(s):
    return not s.translate(trans_table,allowed_chars)

test_long_almost_valid='a_very_long_string_that_is_mostly_valid_except_for_last_char'*99 + '!'
test_long_valid='a_very_long_string_that_is_completely_valid_' * 99
test_short_valid='short_valid_string'
test_short_invalid='/$%$%&'
test_long_invalid='/$%$%&' * 99
test_empty=''

def main():
    funcs = sorted(f for f in globals() if f.startswith('check_'))
    tests = sorted(f for f in globals() if f.startswith('test_'))
    for test in tests:
        print "Test %-15s (length = %d):" % (test, len(globals()[test]))
        for func in funcs:
            print "  %-20s : %.3f" % (func, 
                   timeit.Timer('%s(%s)' % (func, test), 'from __main__ import pat,allowed_set,%s' % ','.join(funcs+tests)).timeit(10000))
        print

if __name__=='__main__': main()

The results on my system are:

Test test_empty      (length = 0):
  check_re_inverse     : 0.042
  check_re_match       : 0.030
  check_set_all        : 0.027
  check_set_diff       : 0.029
  check_set_subset     : 0.029
  check_trans          : 0.014

Test test_long_almost_valid (length = 5941):
  check_re_inverse     : 2.690
  check_re_match       : 3.037
  check_set_all        : 18.860
  check_set_diff       : 2.905
  check_set_subset     : 2.903
  check_trans          : 0.182

Test test_long_invalid (length = 594):
  check_re_inverse     : 0.017
  check_re_match       : 0.015
  check_set_all        : 0.044
  check_set_diff       : 0.311
  check_set_subset     : 0.308
  check_trans          : 0.034

Test test_long_valid (length = 4356):
  check_re_inverse     : 1.890
  check_re_match       : 1.010
  check_set_all        : 14.411
  check_set_diff       : 2.101
  check_set_subset     : 2.333
  check_trans          : 0.140

Test test_short_invalid (length = 6):
  check_re_inverse     : 0.017
  check_re_match       : 0.019
  check_set_all        : 0.044
  check_set_diff       : 0.032
  check_set_subset     : 0.037
  check_trans          : 0.015

Test test_short_valid (length = 18):
  check_re_inverse     : 0.125
  check_re_match       : 0.066
  check_set_all        : 0.104
  check_set_diff       : 0.051
  check_set_subset     : 0.046
  check_trans          : 0.017

The translate approach seems best in most cases, dramatically so with long valid strings, but is beaten out by regexes in test_long_invalid (Presumably because the regex can bail out immediately, but translate always has to scan the whole string). The set approaches are usually worst, beating regexes only for the empty string case.

Using all(x in allowed_set for x in s) performs well if it bails out early, but can be bad if it has to iterate through every character. isSubSet and set difference are comparable, and are consistently proportional to the length of the string regardless of the data.

There's a similar difference between the regex methods matching all valid characters and searching for invalid characters. Matching performs a little better when checking for a long, but fully valid string, but worse for invalid characters near the end of the string.

WPF Datagrid Get Selected Cell Value

When I faced this problem, I approached it like this: I created a DataRowView, grabbed the column index, and then used that in the row's ItemArray

DataRowView dataRow = (DataRowView)dataGrid1.SelectedItem;
int index = dataGrid1.CurrentCell.Column.DisplayIndex;
string cellValue = dataRow.Row.ItemArray[index].ToString();

Best way to split string into lines

  • If it looks ugly, just remove the unnecessary ToCharArray call.

  • If you want to split by either \n or \r, you've got two options:

    • Use an array literal – but this will give you empty lines for Windows-style line endings \r\n:

      var result = text.Split(new [] { '\r', '\n' });
      
    • Use a regular expression, as indicated by Bart:

      var result = Regex.Split(text, "\r\n|\r|\n");
      
  • If you want to preserve empty lines, why do you explicitly tell C# to throw them away? (StringSplitOptions parameter) – use StringSplitOptions.None instead.

A keyboard shortcut to comment/uncomment the select text in Android Studio

Windows 10 and Android Studio: Ctrl + / (on small num pad), don't use Ctrl + Shift-7!

Disabling Chrome cache for website development

Hey if your site is using PHP then place following little PHP snippet at the beginning of your html page :

   //dev versioning - stop caching
   $rand = rand(1, 99999999);

Now everywhere you load resources like CSS- or JS- files in a script or link element you append your generated random value to the request URL after appending '?' to the URI via PHP:

    echo $rand;

Thats it! There will be no browser that caches you site anymore - regardless which kind.

Of course remove your code before publishing or simply set $rand to an empty string to allow caching again.

Oracle row count of table by count(*) vs NUM_ROWS from DBA_TABLES

According to the documentation NUM_ROWS is the "Number of rows in the table", so I can see how this might be confusing. There, however, is a major difference between these two methods.

This query selects the number of rows in MY_TABLE from a system view. This is data that Oracle has previously collected and stored.

select num_rows from all_tables where table_name = 'MY_TABLE'

This query counts the current number of rows in MY_TABLE

select count(*) from my_table

By definition they are difference pieces of data. There are two additional pieces of information you need about NUM_ROWS.

  1. In the documentation there's an asterisk by the column name, which leads to this note:

    Columns marked with an asterisk (*) are populated only if you collect statistics on the table with the ANALYZE statement or the DBMS_STATS package.

    This means that unless you have gathered statistics on the table then this column will not have any data.

  2. Statistics gathered in 11g+ with the default estimate_percent, or with a 100% estimate, will return an accurate number for that point in time. But statistics gathered before 11g, or with a custom estimate_percent less than 100%, uses dynamic sampling and may be incorrect. If you gather 99.999% a single row may be missed, which in turn means that the answer you get is incorrect.

If your table is never updated then it is certainly possible to use ALL_TABLES.NUM_ROWS to find out the number of rows in a table. However, and it's a big however, if any process inserts or deletes rows from your table it will be at best a good approximation and depending on whether your database gathers statistics automatically could be horribly wrong.

Generally speaking, it is always better to actually count the number of rows in the table rather then relying on the system tables.

How to tell if UIViewController's view is visible

Here's @progrmr's solution as a UIViewController category:

// UIViewController+Additions.h

@interface UIViewController (Additions)

- (BOOL)isVisible;

@end


// UIViewController+Additions.m

#import "UIViewController+Additions.h"

@implementation UIViewController (Additions)

- (BOOL)isVisible {
    return [self isViewLoaded] && self.view.window;
}

@end

What database does Google use?

And it's maybe also handy to know that BigTable is not a relational database (like MySQL) but a huge (distributed) hash table which has very different characteristics. You can play around with (a limited version) of BigTable yourself on the Google AppEngine platform.

Next to Hadoop mentioned above there are many other implementations that try to solve the same problems as BigTable (scalability, availability). I saw a nice blog post yesterday listing most of them here.

javascript compare strings without being case sensitive

Another method using a regular expression (this is more correct than Zachary's answer):

var string1 = 'someText',
    string2 = 'SometexT',
    regex = new RegExp('^' + string1 + '$', 'i');

if (regex.test(string2)) {
    return true;
}

RegExp.test() will return true or false.

Also, adding the '^' (signifying the start of the string) to the beginning and '$' (signifying the end of the string) to the end make sure that your regular expression will match only if 'sometext' is the only text in stringToTest. If you're looking for text that contains the regular expression, it's ok to leave those off.

It might just be easier to use the string.toLowerCase() method.

So... regular expressions are powerful, but you should only use them if you understand how they work. Unexpected things can happen when you use something you don't understand.

There are tons of regular expression 'tutorials', but most appear to be trying to push a certain product. Here's what looks like a decent tutorial... granted, it's written for using php, but otherwise, it appears to be a nice beginner's tutorial: http://weblogtoolscollection.com/regex/regex.php

This appears to be a good tool to test regular expressions: http://gskinner.com/RegExr/

Byte Array and Int conversion in Java

/*sorry this is the correct */

     public byte[] IntArrayToByteArray(int[] iarray , int sizeofintarray)
     {
       final ByteBuffer bb ;
       bb = ByteBuffer.allocate( sizeofintarray * 4);
       for(int k = 0; k < sizeofintarray ; k++)
       bb.putInt(k * 4, iar[k]);
       return bb.array();
     }

Find the PID of a process that uses a port on Windows

PowerShell (Core-compatible) one-liner to ease copypaste scenarios:

netstat -aon | Select-String 8080 | ForEach-Object { $_ -replace '\s+', ',' } | ConvertFrom-Csv -Header @('Empty', 'Protocol', 'AddressLocal', 'AddressForeign', 'State', 'PID') | ForEach-Object { $portProcess = Get-Process | Where-Object Id -eq $_.PID; $_ | Add-Member -NotePropertyName 'ProcessName' -NotePropertyValue $portProcess.ProcessName; Write-Output $_ } | Sort-Object ProcessName, State, Protocol, AddressLocal, AddressForeign | Select-Object  ProcessName, State, Protocol, AddressLocal, AddressForeign | Format-Table

Output:

ProcessName State     Protocol AddressLocal AddressForeign
----------- -----     -------- ------------ --------------
System      LISTENING TCP      [::]:8080    [::]:0
System      LISTENING TCP      0.0.0.0:8080 0.0.0.0:0

Same code, developer-friendly:

$Port = 8080

# Get PID's listening to $Port, as PSObject
$PidsAtPortString = netstat -aon `
  | Select-String $Port
$PidsAtPort = $PidsAtPortString `
  | ForEach-Object { `
      $_ -replace '\s+', ',' `
  } `
  | ConvertFrom-Csv -Header @('Empty', 'Protocol', 'AddressLocal', 'AddressForeign', 'State', 'PID')

# Enrich port's list with ProcessName data
$ProcessesAtPort = $PidsAtPort `
  | ForEach-Object { `
    $portProcess = Get-Process `
      | Where-Object Id -eq $_.PID; `
    $_ | Add-Member -NotePropertyName 'ProcessName' -NotePropertyValue $portProcess.ProcessName; `
    Write-Output $_;
  }

# Show output
$ProcessesAtPort `
  | Sort-Object    ProcessName, State, Protocol, AddressLocal, AddressForeign `
  | Select-Object  ProcessName, State, Protocol, AddressLocal, AddressForeign `
  | Format-Table

Graphical user interface Tutorial in C

You can also have a look at FLTK (C++ and not plain C though)

FLTK (pronounced "fulltick") is a cross-platform C++ GUI toolkit for UNIX®/Linux® (X11), Microsoft® Windows®, and MacOS® X. FLTK provides modern GUI functionality without the bloat and supports 3D graphics via OpenGL® and its built-in GLUT emulation.

FLTK is designed to be small and modular enough to be statically linked, but works fine as a shared library. FLTK also includes an excellent UI builder called FLUID that can be used to create applications in minutes.

Here are some quickstart screencasts

[Happy New Year!]

How to apply CSS to iframe?

If you control the page in the iframe, as hangy said, the easiest approach is to create a shared CSS file with common styles, then just link to it from your html pages.

Otherwise it is unlikely you will be able to dynamically change the style of a page from an external page in your iframe. This is because browsers have tightened the security on cross frame dom scripting due to possible misuse for spoofing and other hacks.

This tutorial may provide you with more information on scripting iframes in general. About cross frame scripting explains the security restrictions from the IE perspective.

What does it mean if a Python object is "subscriptable" or not?

It basically means that the object implements the __getitem__() method. In other words, it describes objects that are "containers", meaning they contain other objects. This includes strings, lists, tuples, and dictionaries.

Best way to disable button in Twitter's Bootstrap

You just need the $('button').prop('disabled', true); part, the button will automatically take the disabled class.

Can a website detect when you are using Selenium with chromedriver?

Additionally to the great answer of Erti-Chris Eelmaa - there's annoying window.navigator.webdriver and it is read-only. Event if you change the value of it to false it will still have true. That's why the browser driven by automated software can still be detected.

MDN

The variable is managed by the flag --enable-automation in chrome. The chromedriver launches Chrome with that flag and Chrome sets the window.navigator.webdriver to true. You can find it here. You need to add to "exclude switches" the flag. For instance (Go):

package main

import (
    "github.com/tebeka/selenium"
    "github.com/tebeka/selenium/chrome"
)

func main() {

caps := selenium.Capabilities{
    "browserName": "chrome",
}

chromeCaps := chrome.Capabilities{
    Path:            "/path/to/chrome-binary",
    ExcludeSwitches: []string{"enable-automation"},
}
caps.AddChrome(chromeCaps)

wd, err := selenium.NewRemote(caps, fmt.Sprintf("http://localhost:%d/wd/hub", 4444))
}

Git: Create a branch from unstaged/uncommitted changes on master

In the latest GitHub client for Windows, if you have uncommitted changes, and choose to create a new branch.
It prompts you how to handle this exact scenario:

enter image description here

The same applies if you simply switch the branch too.

writing a batch file that opens a chrome URL

It's very simple. Just try:

start chrome https://www.google.co.in/

it will open the Google page in the Chrome browser.

If you wish to open the page in Firefox, try:

start firefox https://www.google.co.in/

Have Fun!

Android RecyclerView addition & removal of items

Possibly a duplicate answer but quite useful for me. You can implement the method given below in RecyclerView.Adapter<RecyclerView.ViewHolder> and can use this method as per your requirements, I hope it will work for you

public void removeItem(@NonNull Object object) {
        mDataSetList.remove(object);
        notifyDataSetChanged();
    }

How to run Selenium WebDriver test cases in Chrome

Download the latest version of the Chrome driver and use this code:

System.setProperty("webdriver.chrome.driver", "path of chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
Thread.sleep(10000);
driver.get("http://stackoverflow.com");
    

How to get last inserted id?

string insertSql = 
    "INSERT INTO aspnet_GameProfiles(UserId,GameId) VALUES(@UserId, @GameId)SELECT SCOPE_IDENTITY()";

int primaryKey;

using (SqlConnection myConnection = new SqlConnection(myConnectionString))
{
   myConnection.Open();

   SqlCommand myCommand = new SqlCommand(insertSql, myConnection);

   myCommand.Parameters.AddWithValue("@UserId", newUserId);
   myCommand.Parameters.AddWithValue("@GameId", newGameId);

   primaryKey = Convert.ToInt32(myCommand.ExecuteScalar());

   myConnection.Close();
}

This will work.

groovy: safely find a key in a map and return its value

def mymap = [name:"Gromit", id:1234]
def x = mymap.find{ it.key == "likes" }?.value
if(x)
    println "x value: ${x}"

println x.getClass().name

?. checks for null and does not create an exception in Groovy. If the key does not exist, the result will be a org.codehaus.groovy.runtime.NullObject.

Optional Parameters in Web Api Attribute Routing

For an incoming request like /v1/location/1234, as you can imagine it would be difficult for Web API to automatically figure out if the value of the segment corresponding to '1234' is related to appid and not to deviceid.

I think you should change your route template to be like [Route("v1/location/{deviceOrAppid?}", Name = "AddNewLocation")] and then parse the deiveOrAppid to figure out the type of id.

Also you need to make the segments in the route template itself optional otherwise the segments are considered as required. Note the ? character in this case. For example: [Route("v1/location/{deviceOrAppid?}", Name = "AddNewLocation")]

How to determine the version of android SDK installed in computer?

You can check following path for Windows 10

C:\Users{user-name}\AppData\Local\Android\sdk\platforms

Also, you can check from android studio

File > Project Structure > SDK Location > Android SDK Location

Programmatically scroll to a specific position in an Android ListView

For a direct scroll:

getListView().setSelection(21);

For a smooth scroll:

getListView().smoothScrollToPosition(21);

Reading a json file in Android

Put that file in assets.

For project created in Android Studio project you need to create assets folder under the main folder.

Read that file as:

public String loadJSONFromAsset(Context context) {
        String json = null;
        try {
            InputStream is = context.getAssets().open("file_name.json");

            int size = is.available();

            byte[] buffer = new byte[size];

            is.read(buffer);

            is.close();

            json = new String(buffer, "UTF-8");


        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        return json;

    }

and then you can simply read this string return by this function as

JSONObject obj = new JSONObject(json_return_by_the_function);

For further details regarding JSON see http://www.vogella.com/articles/AndroidJSON/article.html

Hope you will get what you want.

Set the intervals of x-axis using r

You can use axis:

> axis(side=1, at=c(0:23))

That is, something like this:

plot(0:23, d, type='b', axes=FALSE)
axis(side=1, at=c(0:23))
axis(side=2, at=seq(0, 600, by=100))
box()

C++ getters/setters coding style

As an aside, in C++, it is somewhat odd to have a const reference member. You have to assign it in the constructor list. Who owns the actually memory of that object and what is it's lifetime?

As for style, I agree with the others that you don't want to expose your privates. :-) I like this pattern for setters/getters

class Foo
{
public:
  const string& FirstName() const;
  Foo& FirstName(const string& newFirstName);

  const string& LastName() const;
  Foo& LastName(const string& newLastName);

  const string& Title() const;
  Foo& Title(const string& newTitle);
};

This way you can do something like:

Foo f;
f.FirstName("Jim").LastName("Bob").Title("Programmer");

What is the difference between new/delete and malloc/free?

In C++ new/delete call the Constructor/Destructor accordingly.

malloc/free simply allocate memory from the heap. new/delete allocate memory as well.

How do I stop a program when an exception is raised in Python?

You can stop catching the exception, or - if you need to catch it (to do some custom handling), you can re-raise:

try:
  doSomeEvilThing()
except Exception, e:
  handleException(e)
  raise

Note that typing raise without passing an exception object causes the original traceback to be preserved. Typically it is much better than raise e.

Of course - you can also explicitly call

import sys 
sys.exit(exitCodeYouFindAppropriate)

This causes SystemExit exception to be raised, and (unless you catch it somewhere) terminates your application with specified exit code.

How to update/refresh specific item in RecyclerView

That's also my last problem. Here my solution I use data Model and adapter for my RecyclerView

 /*Firstly, register your new data to your model*/
 DataModel detail = new DataModel(id, name, sat, image);

 /*after that, use set to replace old value with the new one*/
 int index = 4;
 mData.set(index, detail);

 /*finally, refresh your adapter*/
 if(adapter!=null)
    adapter.notifyItemChanged(index);

How to regex in a MySQL query

I think you can use REGEXP instead of LIKE

SELECT trecord FROM `tbl` WHERE (trecord REGEXP '^ALA[0-9]')

Convert SVG to PNG in Python

Here is what I did using cairosvg:

from cairosvg import svg2png

svg_code = """
    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
        <circle cx="12" cy="12" r="10"/>
        <line x1="12" y1="8" x2="12" y2="12"/>
        <line x1="12" y1="16" x2="12" y2="16"/>
    </svg>
"""

svg2png(bytestring=svg_code,write_to='output.png')

And it works like a charm!

See more: cairosvg document

How to undo last commit

Warning: Don't do this if you've already pushed

You want to do:

git reset HEAD~

If you don't want the changes and blow everything away:

git reset --hard HEAD~

Click events on Pie Charts in Chart.js

If using a Donught Chart, and you want to prevent user to trigger your event on click inside the empty space around your chart circles, you can use the following alternative :

var myDoughnutChart = new Chart(ctx).Doughnut(data);

document.getElementById("myChart").onclick = function(evt){
    var activePoints = myDoughnutChart.getSegmentsAtEvent(evt);

    /* this is where we check if event has keys which means is not empty space */       
    if(Object.keys(activePoints).length > 0)
    {
        var label = activePoints[0]["label"];
        var value = activePoints[0]["value"];
        var url = "http://example.com/?label=" + label + "&value=" + value
        /* process your url ... */
    }
};

What does auto do in margin:0 auto?

margin-top:0;
margin-bottom:0;
margin-left:auto;
margin-right:auto;

0 is for top-bottom and auto for left-right. The browser sets the margin.

Is there a performance difference between i++ and ++i in C?

Short answer:

There is never any difference between i++ and ++i in terms of speed. A good compiler should not generate different code in the two cases.

Long answer:

What every other answer fails to mention is that the difference between ++i versus i++ only makes sense within the expression it is found.

In the case of for(i=0; i<n; i++), the i++ is alone in its own expression: there is a sequence point before the i++ and there is one after it. Thus the only machine code generated is "increase i by 1" and it is well-defined how this is sequenced in relation to the rest of the program. So if you would change it to prefix ++, it wouldn't matter in the slightest, you would still just get the machine code "increase i by 1".

The differences between ++i and i++ only matters in expressions such as array[i++] = x; versus array[++i] = x;. Some may argue and say that the postfix will be slower in such operations because the register where i resides have to be reloaded later. But then note that the compiler is free to order your instructions in any way it pleases, as long as it doesn't "break the behavior of the abstract machine" as the C standard calls it.

So while you may assume that array[i++] = x; gets translated to machine code as:

  • Store value of i in register A.
  • Store address of array in register B.
  • Add A and B, store results in A.
  • At this new address represented by A, store the value of x.
  • Store value of i in register A // inefficient because extra instruction here, we already did this once.
  • Increment register A.
  • Store register A in i.

the compiler might as well produce the code more efficiently, such as:

  • Store value of i in register A.
  • Store address of array in register B.
  • Add A and B, store results in B.
  • Increment register A.
  • Store register A in i.
  • ... // rest of the code.

Just because you as a C programmer is trained to think that the postfix ++ happens at the end, the machine code doesn't have to be ordered in that way.

So there is no difference between prefix and postfix ++ in C. Now what you as a C programmer should be vary of, is people who inconsistently use prefix in some cases and postfix in other cases, without any rationale why. This suggests that they are uncertain about how C works or that they have incorrect knowledge of the language. This is always a bad sign, it does in turn suggest that they are making other questionable decisions in their program, based on superstition or "religious dogmas".

"Prefix ++ is always faster" is indeed one such false dogma that is common among would-be C programmers.

How to change ProgressBar's progress indicator color in Android

A simpler solution:

progess_drawable_blue

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@android:id/background">
    <shape>
        <solid
                android:color="@color/disabled" />
    </shape>
</item>

<item
    android:id="@android:id/progress">
    <clip>
        <shape>
            <solid
                android:color="@color/blue" />
        </shape>
    </clip>
</item>

</layer-list>

How to scroll the page when a modal dialog is longer than the screen?

Here.. Works perfectly for me

.modal-body { 
    max-height:500px; 
    overflow-y:auto;
}

Error:Failed to open zip file. Gradle's dependency cache may be corrupt

****Following solution is working for me**** Manually deleted all files from C:\Users\Admin.gradle\wrapper\dists\

where Admin is my user name

How and when to use ‘async’ and ‘await’

public static void Main(string[] args)
{
    string result = DownloadContentAsync().Result;
    Console.ReadKey();
}

// You use the async keyword to mark a method for asynchronous operations.
// The "async" modifier simply starts synchronously the current thread. 
// What it does is enable the method to be split into multiple pieces.
// The boundaries of these pieces are marked with the await keyword.
public static async Task<string> DownloadContentAsync()// By convention, the method name ends with "Async
{
    using (HttpClient client = new HttpClient())
    {
        // When you use the await keyword, the compiler generates the code that checks if the asynchronous operation is finished.
        // If it is already finished, the method continues to run synchronously.
        // If not completed, the state machine will connect a continuation method that must be executed WHEN the Task is completed.


        // Http request example. 
        // (In this example I can set the milliseconds after "sleep=")
        String result = await client.GetStringAsync("http://httpstat.us/200?sleep=1000");

        Console.WriteLine(result);

        // After completing the result response, the state machine will continue to synchronously execute the other processes.


        return result;
    }
}

How to send email to multiple recipients using python smtplib?

I came up with this importable module function. It uses the gmail email server in this example. Its split into header and message so you can clearly see whats going on:

import smtplib

def send_alert(subject=""):

    to = ['[email protected]', 'email2@another_email.com', '[email protected]']
    gmail_user = '[email protected]'
    gmail_pwd = 'my_pass'
    smtpserver = smtplib.SMTP("smtp.gmail.com", 587)
    smtpserver.ehlo()
    smtpserver.starttls()
    smtpserver.ehlo
    smtpserver.login(gmail_user, gmail_pwd)
    header = 'To:' + ", ".join(to) + '\n' + 'From: ' + gmail_user + '\n' + 'Subject: ' + subject + '\n'
    msg = header + '\n' + subject + '\n\n'
    smtpserver.sendmail(gmail_user, to, msg)
    smtpserver.close()

Reading and displaying data from a .txt file

BufferedReader in = new BufferedReader(new FileReader("<Filename>"));

Then, you can use in.readLine(); to read a single line at a time. To read until the end, write a while loop as such:

String line;
while((line = in.readLine()) != null)
{
    System.out.println(line);
}
in.close();

What is token-based authentication?

It's just hash which is associated with user in database or some other way. That token can be used to authenticate and then authorize a user access related contents of the application. To retrieve this token on client side login is required. After first time login you need to save retrieved token not any other data like session, session id because here everything is token to access other resources of application.

Token is used to assure the authenticity of the user.

UPDATES: In current time, We have more advanced token based technology called JWT (Json Web Token). This technology helps to use same token in multiple systems and we call it single sign-on.

Basically JSON Based Token contains information about user details and token expiry details. So that information can be used to further authenticate or reject the request if token is invalid or expired based on details.

Python script to convert from UTF-8 to ASCII

import codecs

 ...

fichier = codecs.open(filePath, "r", encoding="utf-8")

 ...

fichierTemp = codecs.open("tempASCII", "w", encoding="ascii", errors="ignore")
fichierTemp.write(contentOfFile)

 ...

How to select a dropdown value in Selenium WebDriver using Java

WebDriver driver = new FirefoxDriver();
WebElement identifier = driver.findElement(By.id("periodId"));
Select select = new Select(identifier);
select.selectByVisibleText("Last 52 Weeks"); 

JSONResult to String

You can also use Json.NET.

return JsonConvert.SerializeObject(jsonResult.Data);

How to add a 'or' condition in #ifdef

I am really OCD about maintaining strict column limits, and not a fan of "\" line continuation because you can't put a comment after it, so here is my method.

//|¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯|//
#ifdef  CONDITION_01             //|       |//
#define             TEMP_MACRO   //|       |//
#endif                           //|       |//
#ifdef  CONDITION_02             //|       |//
#define             TEMP_MACRO   //|       |//
#endif                           //|       |//
#ifdef  CONDITION_03             //|       |//
#define             TEMP_MACRO   //|       |//
#endif                           //|       |//
#ifdef              TEMP_MACRO   //|       |//
//|-  --  --  --  --  --  --  --  --  --  -|//

printf("[IF_CONDITION:(1|2|3)]\n");

//|-  --  --  --  --  --  --  --  --  --  -|//
#endif                           //|       |//
#undef              TEMP_MACRO   //|       |//
//|________________________________________|//

Error: Unexpected value 'undefined' imported by the module

For me, I just did a CTRL+C and YES .
And I restart by

ionic serve 

This works for me.

Background color on input type=button :hover state sticks in IE

Try using the type attribute selector to find buttons (maybe this'll fix it too):

input[type=button]
{
  background-color: #E3E1B8; 
}

input[type=button]:hover
{
  background-color: #46000D
}

link_to method and click event in Rails

To follow up on Ron's answer if using JQuery and putting it in application.js or the head section you need to wrap it in a ready() section...

$(document).ready(function() {
  $('#my-link').click(function(event){
    alert('Hooray!');
    event.preventDefault(); // Prevent link from following its href
  });
});

How to make Git "forget" about a file that was tracked but is now in .gitignore?

Do the following steps serially,you will be fine.

1.remove the mistakenly added files from the directory/storage. You can use "rm -r"(for linux) command or delete them by browsing the directories. Or move them to another location on your PC.[You maybe need to close the IDE if running for moving/removing]

2.add the files / directories to gitignore file now and save it.

3.now remove them from git cache by using these commands (if there are more than one directory, remove them one by one by repeatedly issuing this command)

git rm -r --cached path-to-those-files

4.now do a commit and push, use these commands. This will remove those files from git remote and make git stop tracking those files.

git add .
git commit -m "removed unnecessary files from git"
git push origin

Using jQuery to programmatically click an <a> link

I had similar issue. try this $('#myAnchor').get(0).click();this works for me

Using JQuery to open a popup window and print

Got it! I found an idea here

http://www.mail-archive.com/[email protected]/msg18410.html

In this example, they loaded a blank popup window into an object, cloned the contents of the element to be displayed, and appended it to the body of the object. Since I already knew what the contents of view-details (or any page I load in the lightbox), I just had to clone that content instead and load it into an object. Then, I just needed to print that object. The final outcome looks like this:

$('.printBtn').bind('click',function() {
    var thePopup = window.open( '', "Customer Listing", "menubar=0,location=0,height=700,width=700" );
    $('#popup-content').clone().appendTo( thePopup.document.body );
    thePopup.print();
});

I had one small drawback in that the style sheet I was using in view-details.php was using a relative link. I had to change it to an absolute link. The reason being that the window didn't have a URL associated with it, so it had no relative position to draw on.

Works in Firefox. I need to test it in some other major browsers too.

I don't know how well this solution works when you're dealing with images, videos, or other process intensive solutions. Although, it works pretty well in my case, since I'm just loading tables and text values.

Thanks for the input! You gave me some ideas of how to get around this.

Why use @Scripts.Render("~/bundles/jquery")

You can also use:

@Scripts.RenderFormat("<script type=\"text/javascript\" src=\"{0}\"></script>", "~/bundles/mybundle")

To specify the format of your output in a scenario where you need to use Charset, Type, etc.

How to open my files in data_folder with pandas using relative path?

For non-Windows users:

import pandas as pd
import os

os.chdir("../data_folder")
df = pd.read_csv("data.csv")

For Windows users:

import pandas as pd

df = pd.read_csv(r"C:\data_folder\data.csv")

The prefix r in location above saves time when giving the location to the pandas Dataframe.

How to round up the result of integer division?

In need of an extension method:

    public static int DivideUp(this int dividend, int divisor)
    {
        return (dividend + (divisor - 1)) / divisor;
    }

No checks here (overflow, DivideByZero, etc), feel free to add if you like. By the way, for those worried about method invocation overhead, simple functions like this might be inlined by the compiler anyways, so I don't think that's where to be concerned. Cheers.

P.S. you might find it useful to be aware of this as well (it gets the remainder):

    int remainder; 
    int result = Math.DivRem(dividend, divisor, out remainder);

How can I get the domain name of my site within a Django template?

I know this question is old, but I stumbled upon it looking for a pythonic way to get current domain.

def myview(request):
    domain = request.build_absolute_uri('/')[:-1]
    # that will build the complete domain: http://foobar.com

Execute specified function every X seconds

Use System.Windows.Forms.Timer.

private Timer timer1; 
public void InitTimer()
{
    timer1 = new Timer();
    timer1.Tick += new EventHandler(timer1_Tick);
    timer1.Interval = 2000; // in miliseconds
    timer1.Start();
}

private void timer1_Tick(object sender, EventArgs e)
{
    isonline();
}

You can call InitTimer() in Form1_Load().

Change text (html) with .animate

refer to official jquery example: and play with it.

.animate({
    width: "70%",
    opacity: 0.4,
    marginLeft: "0.6in",
    fontSize: "3em",
    borderWidth: "10px"
  }, 1500 );

How to clear react-native cache?

For React Native Init approach (without expo) use:

npm start -- --reset-cache

Android: why is there no maxHeight for a View?

Wrap your ScrollView around your a plainLinearLayout with layout_height="max_height", this will do a perfect job. In fact, I have this code in production from last 5 years with zero issues.

<LinearLayout
        android:id="@+id/subsParent"
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:gravity="bottom|center_horizontal"
        android:orientation="vertical">

        <ScrollView
            android:id="@+id/subsScroll"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:layout_marginEnd="15dp"
            android:layout_marginStart="15dp">

            <TextView
                android:id="@+id/subsTv"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/longText"
                android:visibility="visible" />

        </ScrollView>
    </LinearLayout>

How do I get the title of the current active window using c#?

If it happens that you need the Current Active Form from your MDI application: (MDI- Multi Document Interface).

Form activForm;
activForm = Form.ActiveForm.ActiveMdiChild;

Find duplicate records in a table using SQL Server

Try this instead

SELECT MAX(shoppername), COUNT(*) AS cnt
FROM dbo.sales
GROUP BY CHECKSUM(*)
HAVING COUNT(*) > 1

Read about the CHECKSUM function first, as there can be duplicates.

Initialize a byte array to a certain value, other than the default null?

Guys before me gave you your answer. I just want to point out your misuse of foreach loop. See, since you have to increment index standard "for loop" would be not only more compact, but also more efficient ("foreach" does many things under the hood):

for (int index = 0; index < UserCode.Length; ++index)
{
    UserCode[index] = 0x20;
}

How to transform array to comma separated words string?

You're looking for implode()

$string = implode(",", $array);

Force IE8 Into IE7 Compatiblity Mode

This can be done in IIS: http://weblogs.asp.net/joelvarty/archive/2009/03/23/force-ie7-compatibility-mode-in-ie8-with-iis-settings.aspx

Read the comments as well: Wednesday, April 01, 2009 8:57 AM by John Moore

A quick follow-up. This worked great for my site as long as I use the IE=EmulateIE7 value. Trying to use the IE=7 resulted in my site essentially hanging when run on IE8.

Pause in Python

An external WConio module can help here: http://newcenturycomputers.net/projects/wconio.html

import WConio
WConio.getch()

How to efficiently concatenate strings in go

This is the fastest solution that does not require you to know or calculate the overall buffer size first:

var data []byte
for i := 0; i < 1000; i++ {
    data = append(data, getShortStringFromSomewhere()...)
}
return string(data)

By my benchmark, it's 20% slower than the copy solution (8.1ns per append rather than 6.72ns) but still 55% faster than using bytes.Buffer.

Save array in mysql database

You can store the array using serialize/unserialize. With that solution they cannot easily be used from other programming languages, so you may consider using json_encode/json_decode instead (which gives you a widely supported format). Avoid using implode/explode for this since you'll probably end up with bugs or security flaws.

Note that this makes your table non-normalized, which may be a bad idea since you cannot easily query the data. Therefore consider this carefully before going forward. May you need to query the data for statistics or otherwise? Are there other reasons to normalize the data?

Also, don't save the raw $_POST array. Someone can easily make their own web form and post data to your site, thereby sending a really large form which takes up lots of space. Save those fields you want and make sure to validate the data before saving it (so you won't get invalid values).

Is bool a native C type?

No, there is no bool in ISO C90.

Here's a list of keywords in standard C (not C99):

  • auto
  • break
  • case
  • char
  • const
  • continue
  • default
  • do
  • double
  • else
  • enum
  • extern
  • float
  • for
  • goto
  • if
  • int
  • long
  • register
  • return
  • short
  • signed
  • static
  • struct
  • switch
  • typedef
  • union
  • unsigned
  • void
  • volatile
  • while

Here's an article discussing some other differences with C as used in the kernel and the standard: http://www.ibm.com/developerworks/linux/library/l-gcc-hacks/index.html

"Parameter" vs "Argument"

A parameter is the variable which is part of the method’s signature (method declaration). An argument is an expression used when calling the method.

Consider the following code:

void Foo(int i, float f)
{
    // Do things
}

void Bar()
{
    int anInt = 1;
    Foo(anInt, 2.0);
}

Here i and f are the parameters, and anInt and 2.0 are the arguments.

How to append a jQuery variable value inside the .html tag

HTML :

<div id="myDiv">
    <form id="myForm">
    </form> 
</div>

jQuery :

var chbx='<input type="checkbox" id="Mumbai" name="Mumbai" value="Mumbai" />Mumbai<br /> <input type="checkbox" id=" Delhi" name=" Delhi" value=" Delhi" /> Delhi<br/><input type="checkbox" id=" Bangalore" name=" Bangalore" value=" Bangalore"/>Bangalore<br />';

$("#myDiv form#myForm").html(chbx);

//to insert dynamically created form 
$("#myDiv").html("<form id='dynamicForm'>" +chbx + "'</form>");

Demo

Compiling C++ on remote Linux machine - "clock skew detected" warning

The solution is to run an NTP client , just run the command as below

#ntpdate 172.16.12.100

172.16.12.100 is the ntp server

Change text color with Javascript?

Try below code:

$(document).ready(function(){
$('#about').css({'background-color':'black'});    
});

http://jsfiddle.net/jPCFC/

Good PHP ORM Library?

Try RedBean, its requires:

  • No configuration
  • No database (it creates everything on the fly)
  • No models
  • etc.

It even does all the locking and transactions for you and monitors performance in the background. (Heck! it even does garbage collection....) Best of all... you don't have to write a single... line of code... Jesus this, ORM layer, saved me ass!

Empty or Null value display in SSRS text boxes

=IIF(ISNOTHING(CStr(Fields!MyFields.Value)) or CStr(Fields!MyFields.Value) = "","-",CStr(Fields!MyFields.Value))

Use this expression you may get the answer.

Here CStr is an default function for handling String datatypes.

Delete certain lines in a txt file via a batch file

You can accomplish the same solution as @paxdiablo's using just findstr by itself. There's no need to pipe multiple commands together:

findstr /V "ERROR REFERENCE" infile.txt > outfile.txt

Details of how this works:

  • /v finds lines that don't match the search string (same switch @paxdiablo uses)
  • if the search string is in quotes, it performs an OR search, using each word (separator is a space)
  • findstr can take an input file, you don't need to feed it the text using the "type" command
  • "> outfile.txt" will send the results to the file outfile.txt instead printing them to your console. (Note that it will overwrite the file if it exists. Use ">> outfile.txt" instead if you want to append.)
  • You might also consider adding the /i switch to do a case-insensitive match.

De-obfuscate Javascript code to make it readable again

From the first link on google;

function call_func(_0x41dcx2) {
 var _0x41dcx3 = eval('(' + _0x41dcx2 + ')');
 var _0x41dcx4 = document['createElement']('div');
 var _0x41dcx5 = _0x41dcx3['id'];
 var _0x41dcx6 = _0x41dcx3['Student_name'];
 var _0x41dcx7 = _0x41dcx3['student_dob'];
 var _0x41dcx8 = '<b>ID:</b>';
 _0x41dcx8 += '<a href="/learningyii/index.php?r=student/view&amp; id=' + _0x41dcx5 + '">' + _0x41dcx5 + '</a>';
 _0x41dcx8 += '<br/>';
 _0x41dcx8 += '<b>Student Name:</b>';
 _0x41dcx8 += _0x41dcx6;
 _0x41dcx8 += '<br/>';
 _0x41dcx8 += '<b>Student DOB:</b>';
 _0x41dcx8 += _0x41dcx7;
 _0x41dcx8 += '<br/>';
 _0x41dcx4['innerHTML'] = _0x41dcx8;
 _0x41dcx4['setAttribute']('class', 'view');
 $('#StudentGridViewId')['find']('.items')['prepend'](_0x41dcx4);
};

It won't get you all the way back to source, and that's not really possible, but it'll get you out of a hole.

How to call a function after delay in Kotlin?

I recommended using SingleThread because you do not have to kill it after using. Also, "stop()" method is deprecated in Kotlin language.

private fun mDoThisJob(){

    Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate({
        //TODO: You can write your periodical job here..!

    }, 1, 1, TimeUnit.SECONDS)
}

Moreover, you can use it for periodical job. It is very useful. If you would like to do job for each second, you can set because parameters of it:

Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit);

TimeUnit values are: NANOSECONDS, MICROSECONDS, MILLISECONDS, SECONDS, MINUTES, HOURS, DAYS.

@canerkaseler

C++ convert hex string to signed integer

I had the same problem today, here's how I solved it so I could keep lexical_cast<>

typedef unsigned int    uint32;
typedef signed int      int32;

class uint32_from_hex   // For use with boost::lexical_cast
{
    uint32 value;
public:
    operator uint32() const { return value; }
    friend std::istream& operator>>( std::istream& in, uint32_from_hex& outValue )
    {
        in >> std::hex >> outValue.value;
    }
};

class int32_from_hex   // For use with boost::lexical_cast
{
    uint32 value;
public:
    operator int32() const { return static_cast<int32>( value ); }
    friend std::istream& operator>>( std::istream& in, int32_from_hex& outValue )
    {
        in >> std::hex >> outvalue.value;
    }
};

uint32 material0 = lexical_cast<uint32_from_hex>( "0x4ad" );
uint32 material1 = lexical_cast<uint32_from_hex>( "4ad" );
uint32 material2 = lexical_cast<uint32>( "1197" );

int32 materialX = lexical_cast<int32_from_hex>( "0xfffefffe" );
int32 materialY = lexical_cast<int32_from_hex>( "fffefffe" );
// etc...

(Found this page when I was looking for a less sucky way :-)

Cheers, A.

How do I properly force a Git push?

And if push --force doesn't work you can do push --delete. Look at 2nd line on this instance:

git reset --hard HEAD~3  # reset current branch to 3 commits ago
git push origin master --delete  # do a very very bad bad thing
git push origin master  # regular push

But beware...

Never ever go back on a public git history!

In other words:

  • Don't ever force push on a public repository.
  • Don't do this or anything that can break someone's pull.
  • Don't ever reset or rewrite history in a repo someone might have already pulled.

Of course there are exceptionally rare exceptions even to this rule, but in most cases it's not needed to do it and it will generate problems to everyone else.

Do a revert instead.

And always be careful with what you push to a public repo. Reverting:

git revert -n HEAD~3..HEAD  # prepare a new commit reverting last 3 commits
git commit -m "sorry - revert last 3 commits because I was not careful"
git push origin master  # regular push

In effect, both origin HEADs (from the revert and from the evil reset) will contain the same files.


edit to add updated info and more arguments around push --force

Consider pushing force with lease instead of push, but still prefer revert

Another problem push --force may bring is when someone push anything before you do, but after you've already fetched. If you push force your rebased version now you will replace work from others.

git push --force-with-lease introduced in the git 1.8.5 (thanks to @VonC comment on the question) tries to address this specific issue. Basically, it will bring an error and not push if the remote was modified since your latest fetch.

This is good if you're really sure a push --force is needed, but still want to prevent more problems. I'd go as far to say it should be the default push --force behaviour. But it's still far from being an excuse to force a push. People who fetched before your rebase will still have lots of troubles, which could be easily avoided if you had reverted instead.

And since we're talking about git --push instances...

Why would anyone want to force push?

@linquize brought a good push force example on the comments: sensitive data. You've wrongly leaked data that shouldn't be pushed. If you're fast enough, you can "fix"* it by forcing a push on top.

* The data will still be on the remote unless you also do a garbage collect, or clean it somehow. There is also the obvious potential for it to be spread by others who'd fetched it already, but you get the idea.

How to count number of unique values of a field in a tab-delimited text file?

awk -F '\t' '{ a[$1]++ } END { for (n in a) print n, a[n] } ' test.csv

What is SELF JOIN and when would you use it?

You'd use a self-join on a table that "refers" to itself - e.g. a table of employees where managerid is a foreign-key to employeeid on that same table.

Example:

SELECT E.name, ME.name AS manager
FROM dbo.Employees E
LEFT JOIN dbo.Employees ME
ON ME.employeeid = E.managerid

Java simple code: java.net.SocketException: Unexpected end of file from server

I would suggest using wire shark to trace packets. If you are using Ubuntu, sudo-apt get wireshark. Like Joni stated the only way to figure out whats going wrong is to follow the GET requests and their associated responses.

http://www.wireshark.org/download.html

Biggest advantage to using ASP.Net MVC vs web forms

In webforms you could also render almost whole html by hand, except few tags like viewstate, eventvalidation and similar, which can be removed with PageAdapters. Nobody force you to use GridView or some other server side control that has bad html rendering output.

I would say that biggest advantage of MVC is SPEED!

Next is forced separation of concern. But it doesn't forbid you to put whole BL and DAL logic inside Controller/Action! It's just separation of view, which can be done also in webforms (MVP pattern for example). A lot of things that people mentions for mvc can be done in webforms, but with some additional effort.
Main difference is that request comes to controller, not view, and those two layers are separated, not connected via partial class like in webforms (aspx + code behind)

XSS filtering function in PHP

There are a number of ways hackers put to use for XSS attacks, PHP's built-in functions do not respond to all sorts of XSS attacks. Hence, functions such as strip_tags, filter_var, mysql_real_escape_string, htmlentities, htmlspecialchars, etc do not protect us 100%. You need a better mechanism, here is what is solution:

function xss_clean($data)
{
// Fix &entity\n;
$data = str_replace(array('&amp;','&lt;','&gt;'), array('&amp;amp;','&amp;lt;','&amp;gt;'), $data);
$data = preg_replace('/(&#*\w+)[\x00-\x20]+;/u', '$1;', $data);
$data = preg_replace('/(&#x*[0-9A-F]+);*/iu', '$1;', $data);
$data = html_entity_decode($data, ENT_COMPAT, 'UTF-8');

// Remove any attribute starting with "on" or xmlns
$data = preg_replace('#(<[^>]+?[\x00-\x20"\'])(?:on|xmlns)[^>]*+>#iu', '$1>', $data);

// Remove javascript: and vbscript: protocols
$data = preg_replace('#([a-z]*)[\x00-\x20]*=[\x00-\x20]*([`\'"]*)[\x00-\x20]*j[\x00-\x20]*a[\x00-\x20]*v[\x00-\x20]*a[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iu', '$1=$2nojavascript...', $data);
$data = preg_replace('#([a-z]*)[\x00-\x20]*=([\'"]*)[\x00-\x20]*v[\x00-\x20]*b[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iu', '$1=$2novbscript...', $data);
$data = preg_replace('#([a-z]*)[\x00-\x20]*=([\'"]*)[\x00-\x20]*-moz-binding[\x00-\x20]*:#u', '$1=$2nomozbinding...', $data);

// Only works in IE: <span style="width: expression(alert('Ping!'));"></span>
$data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?expression[\x00-\x20]*\([^>]*+>#i', '$1>', $data);
$data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?behaviour[\x00-\x20]*\([^>]*+>#i', '$1>', $data);
$data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:*[^>]*+>#iu', '$1>', $data);

// Remove namespaced elements (we do not need them)
$data = preg_replace('#</*\w+:\w[^>]*+>#i', '', $data);

do
{
    // Remove really unwanted tags
    $old_data = $data;
    $data = preg_replace('#</*(?:applet|b(?:ase|gsound|link)|embed|frame(?:set)?|i(?:frame|layer)|l(?:ayer|ink)|meta|object|s(?:cript|tyle)|title|xml)[^>]*+>#i', '', $data);
}
while ($old_data !== $data);

// we are done...
return $data;
}

SQL query for getting data for last 3 months

SELECT * 
FROM TABLE_NAME
WHERE Date_Column >= DATEADD(MONTH, -3, GETDATE()) 

Mureinik's suggested method will return the same results, but doing it this way your query can benefit from any indexes on Date_Column.

or you can check against last 90 days.

SELECT * 
FROM TABLE_NAME
WHERE Date_Column >= DATEADD(DAY, -90, GETDATE()) 

How to insert data using wpdb

global $wpdb;
$insert = $wpdb->query("INSERT INTO `front-post`(`id`, `content`) VALUES ('$id', '$content')");

No line-break after a hyphen

Late to the party, but I think this is actually the most elegant. Use the WORD JOINER Unicode character &#8288; on either side of your hyphen, or em dash, or any character.

So, like so:

&#8288;—&#8288;

This will join the symbol on both ends to its neighbors (without adding a space) and prevent line breaking.

Insert line break inside placeholder attribute of a textarea?

A slightly improved version of the Jason Gennaro's answer (see code comments):

var placeholder = 'This is a line \nthis should be a new line';
$('textarea').attr('value', placeholder);
$('textarea').focus(function(){
    if($(this).val() == placeholder){
        // reset the value only if it equals the initial one    
        $(this).attr('value', '');
    }
});
$('textarea').blur(function(){
    if($(this).val() == ''){
        $(this).attr('value', placeholder);
    }    
});
// remove the focus, if it is on by default
$('textarea').blur();

Java constructor/method with optional parameters?

You can simulate it with using varargs, however then you should check it for too many arguments.

public void foo(int param1, int ... param2)
{
   int param2_
   if(param2.length == 0)
      param2_ = 2
   else if(para2.length == 1)
      param2_ = param2[0]
   else
      throw new TooManyArgumentsException(); // user provided too many arguments,

   // rest of the code
}

However this approach is not a good way of doing this, therefore it is better to use overloading.

ORA-00942: table or view does not exist (works when a separate sql, but does not work inside a oracle function)

There's a strong chance that the privileges to select from table1 have been granted to a role, and the role has been granted to you. Privileges granted to a role are not available to PL/SQL written by a user, even if the user has been granted the role.

You see this a lot for users that have been granted the dba role on objects owned by sys. A user with dba role will be able to, say, SELECT * from V$SESSION, but will not be able to write a function that includes SELECT * FROM V$SESSION.

The fix is to grant explicit permissions on the object in question to the user directly, for example, in the case above, the SYS user has to GRANT SELECT ON V_$SESSION TO MyUser;

How do I perform a JAVA callback between classes?

Define an interface, and implement it in the class that will receive the callback.

Have attention to the multi-threading in your case.

Code example from http://cleancodedevelopment-qualityseal.blogspot.com.br/2012/10/understanding-callbacks-with-java.html

interface CallBack {                   //declare an interface with the callback methods, so you can use on more than one class and just refer to the interface
    void methodToCallBack();
}

class CallBackImpl implements CallBack {          //class that implements the method to callback defined in the interface
    public void methodToCallBack() {
        System.out.println("I've been called back");
    }
}

class Caller {

    public void register(CallBack callback) {
        callback.methodToCallBack();
    }

    public static void main(String[] args) {
        Caller caller = new Caller();
        CallBack callBack = new CallBackImpl();       //because of the interface, the type is Callback even thought the new instance is the CallBackImpl class. This alows to pass different types of classes that have the implementation of CallBack interface
        caller.register(callBack);
    }
} 

In your case, apart from multi-threading you could do like this:

interface ServerInterface {
    void newSeverConnection(Socket socket);
}

public class Server implements ServerInterface {

    public Server(int _address) {
        System.out.println("Starting Server...");
        serverConnectionHandler = new ServerConnections(_address, this);
        workers.execute(serverConnectionHandler);
        System.out.println("Do something else...");
    }

    void newServerConnection(Socket socket) {
        System.out.println("A function of my child class was called.");
    }

}

public class ServerConnections implements Runnable {

    private ServerInterface serverInterface;

    public ServerConnections(int _serverPort, ServerInterface _serverInterface) {
      serverPort = _serverPort;
      serverInterface = _serverInterface;
    }

    @Override
    public void run() {
        System.out.println("Starting Server Thread...");

        if (serverInterface == null) {
            System.out.println("Server Thread error: callback null");
        }

        try {
            mainSocket = new ServerSocket(serverPort);

            while (true) {
                serverInterface.newServerConnection(mainSocket.accept());
            }
        } catch (IOException ex) {
            Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

Multi-threading

Remember this does not handle multi-threading, this is another topic and can have various solutions depending on the project.

The observer-pattern

The observer-pattern does nearly this, the major difference is the use of an ArrayList for adding more than one listener. Where this is not needed, you get better performance with one reference.

Plotting with ggplot2: "Error: Discrete value supplied to continuous scale" on categorical y-axis

In my case, you need to convert the column(you think this column is numeric, but actually not) to numeric

geom_segment(data=tmpp, 
   aes(x=start_pos, 
   y=lib.complexity, 
   xend=end_pos, 
   yend=lib.complexity)
)
# to 
geom_segment(data=tmpp, 
   aes(x=as.numeric(start_pos), 
   y=as.numeric(lib.complexity), 
   xend=as.numeric(end_pos), 
   yend=as.numeric(lib.complexity))
)

Average of multiple columns

You don't mention if the columns are nullable. If they are and you want the same semantics that the AVG aggregate provides you can do (2008)

SELECT *,
       (SELECT AVG(c)
        FROM   (VALUES(R1),
                      (R2),
                      (R3),
                      (R4),
                      (R5)) T (c)) AS [Average]
FROM   Request  

The 2005 version is a bit more tedious

SELECT *,
       (SELECT AVG(c)
        FROM   (SELECT R1
                UNION ALL
                SELECT R2
                UNION ALL
                SELECT R3
                UNION ALL
                SELECT R4
                UNION ALL
                SELECT R5) T (c)) AS [Average]
FROM   Request

Passing javascript variable to html textbox

This was a problem for me, too. One reason for doing this (in my case) was that I needed to convert a client-side event (a javascript variable being modified) to a server-side variable (for that variable to be used in php). Hence populating a form with a javascript variable (eg a sessionStorage key/value) and converting it to a $_POST variable.

<form name='formName'>
<input name='inputName'>
</form>

<script>
document.formName.inputName.value=var
</script>

Optional query string parameters in ASP.NET Web API

This issue has been fixed in the regular release of MVC4. Now you can do:

public string GetFindBooks(string author="", string title="", string isbn="", string  somethingelse="", DateTime? date= null) 
{
    // ...
}

and everything will work out of the box.

What should main() return in C and C++?

The return value for main indicates how the program exited. Normal exit is represented by a 0 return value from main. Abnormal exit is signaled by a non-zero return, but there is no standard for how non-zero codes are interpreted. As noted by others, void main() is prohibited by the C++ standard and should not be used. The valid C++ main signatures are:

int main()

and

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

which is equivalent to

int main(int argc, char** argv)

It is also worth noting that in C++, int main() can be left without a return-statement, at which point it defaults to returning 0. This is also true with a C99 program. Whether return 0; should be omitted or not is open to debate. The range of valid C program main signatures is much greater.

Efficiency is not an issue with the main function. It can only be entered and left once (marking the program's start and termination) according to the C++ standard. For C, re-entering main() is allowed, but should be avoided.

How to configure XAMPP to send mail from localhost?

As in my personal experience I found that very similar thing to Vikas Dwivedi answer will work just fine.

Step 1 (php.ini file)

In php.ini file located in xampp\php\php.ini. Change settings to the following:

 extension=php_openssl.dll
 [mail function]
 sendmail_path =":\xampp7\sendmail\sendmail.exe -t"
 mail.add_x_header=On

Turn off other variables under mail funciton by putting ; before them. e.g ;smtp_port=25

Step 2 (sendmail.ini file)

In sendmail.ini located in xampp\sendmail\semdmail.ini change to the following:

 smtp_server=smtp.gmail.com
 smtp_port=465
 smtp_ssl=auto
 [email protected]
 auth_password=YourPassword

Step 3 (code)

Create a php file and use the following:

 <?php
    mail($to, "subject", "body", "From: ".$from);
 ?>

Notice

  • You need to restart apache in order for php.ini to reload.
  • you need to activate Google Less secure app access in https://myaccount.google.com/u/1/security
  • It might help to run Xampp with Admin permission.

Centering floating divs within another div

Solution:

<!DOCTYPE HTML>
<html>
    <head>
        <title>Knowledge is Power</title>
        <script src="js/jquery.js"></script>
        <script type="text/javascript">
        </script>
        <style type="text/css">
            #outer {
                text-align:center;
                width:100%;
                height:200px;
                background:red;
            }
            #inner {
                display:inline-block;
                height:200px;
                background:yellow;
            }
        </style>
    </head>
    <body>
        <div id="outer">
            <div id="inner">Hello, I am Touhid Rahman. The man in Light</div>
        </div>
    </body>
</html>

Split value from one field to two

In MySQL this is working this option:

SELECT Substring(nameandsurname, 1, Locate(' ', nameandsurname) - 1) AS 
       firstname, 
       Substring(nameandsurname, Locate(' ', nameandsurname) + 1)    AS lastname 
FROM   emp  

PHP Get name of current directory

To get only the name of the directory where script executed:

//Path to script: /data/html/cars/index.php
echo basename(dirname(__FILE__)); //"cars"

ALTER TABLE on dependent column

If your constraint is on a user type, then don't forget to see if there is a Default Constraint, usually something like DF__TableName__ColumnName__6BAEFA67, if so then you will need to drop the Default Constraint, like this:

ALTER TABLE TableName DROP CONSTRAINT [DF__TableName__ColumnName__6BAEFA67]

For more info see the comments by the brilliant Aaron Bertrand on this answer.

How to prevent text in a table cell from wrapping

Have a look at the white-space property, used like this:

th {
    white-space: nowrap;
}

This will force the contents of <th> to display on one line.

From linked page, here are the various options for white-space:

normal
This value directs user agents to collapse sequences of white space, and break lines as necessary to fill line boxes.

pre
This value prevents user agents from collapsing sequences of white space. Lines are only broken at preserved newline characters.

nowrap
This value collapses white space as for 'normal', but suppresses line breaks within text.

pre-wrap
This value prevents user agents from collapsing sequences of white space. Lines are broken at preserved newline characters, and as necessary to fill line boxes.

pre-line
This value directs user agents to collapse sequences of white space. Lines are broken at preserved newline characters, and as necessary to fill line boxes.

How to install plugins to Sublime Text 2 editor?

  1. Install the Package Manager as directed on https://packagecontrol.io/installation

  2. Open the Package Manager using Ctrl+Shift+P

  3. Type Package Control to show related commands (Install Package, Remove Package etc.) with packages

Enjoy it!

enter image description here

Android: how to draw a border to a LinearLayout

Extend LinearLayout/RelativeLayout and use it straight on the XML

package com.pkg_name ;
...imports...
public class LinearLayoutOutlined extends LinearLayout {
    Paint paint;    

    public LinearLayoutOutlined(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
        setWillNotDraw(false) ;
        paint = new Paint();
    }
    public LinearLayoutOutlined(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
        setWillNotDraw(false) ;
        paint = new Paint();
    }
    @Override
    protected void onDraw(Canvas canvas) {
        /*
        Paint fillPaint = paint;
        fillPaint.setARGB(255, 0, 255, 0);
        fillPaint.setStyle(Paint.Style.FILL);
        canvas.drawPaint(fillPaint) ;
        */

        Paint strokePaint = paint;
        strokePaint.setARGB(255, 255, 0, 0);
        strokePaint.setStyle(Paint.Style.STROKE);
        strokePaint.setStrokeWidth(2);  
        Rect r = canvas.getClipBounds() ;
        Rect outline = new Rect( 1,1,r.right-1, r.bottom-1) ;
        canvas.drawRect(outline, strokePaint) ;
    }

}

<?xml version="1.0" encoding="utf-8"?>

<com.pkg_name.LinearLayoutOutlined
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
    android:layout_width=...
    android:layout_height=...
   >
   ... your widgets here ...

</com.pkg_name.LinearLayoutOutlined>

How to get out of while loop in java with Scanner method "hasNext" as condition?

You can simply use one of the system dependent end-of-file indicators ( d for Unix/Linux/Ubuntu, z for windows) to make the while statement false. This should get you out of the loop nicely. :)

How to match "any character" in regular expression?

I work this Not always dot is means any char. Exception when single line mode. \p{all} should be

String value = "|°¬<>!\"#$%&/()=?'\\¡¿/*-+_@[]^^{}";
String expression = "[a-zA-Z0-9\\p{all}]{0,50}";
if(value.matches(expression)){
    System.out.println("true");
} else {
    System.out.println("false");
}

php create object without class

you can always use new stdClass(). Example code:

   $object = new stdClass();
   $object->property = 'Here we go';

   var_dump($object);
   /*
   outputs:

   object(stdClass)#2 (1) {
      ["property"]=>
      string(10) "Here we go"
    }
   */

Also as of PHP 5.4 you can get same output with:

$object = (object) ['property' => 'Here we go'];

SQLException: No suitable driver found for jdbc:derby://localhost:1527

if the database is created and you have started the connection to the, then al you need is to add the driver jar. from the project window, right click on the libraries folder, goto c:programsfiles\sun\javadb\lib\derbyclient.jar. load the file and you should be able to run.

all the best

Android java.exe finished with non-zero exit value 1

There's many reason that leads to

com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.8.0_60\bin\java.exe'' finished with non-zero exit value 1

If you are not hitting the dex limit but you are getting error similar to this Error:com.android.dx.cf.iface.ParseException: name already added: string{"a"}

Try disable proguard, if it manage to compile without issue then you will need to figure out which library caused it and add it to proguard-rules.pro file

In my case this issue occur when I updated compile 'com.google.android.gms:play-services-ads:8.3.0' to compile 'com.google.android.gms:play-services-ads:8.4.0'

One of the workaround is I added this to proguard-rules.pro file

## Google AdMob specific rules ##
## https://developers.google.com/admob/android/quick-start ##

-keep public class com.google.ads.** {
   public *;
}

Android Studio

Using ADB to capture the screen

Using some of the knowledge from this and a couple of other posts, I found the method that worked the best for me was to:

adb shell 'stty raw; screencap -p'

I have posted a very simple Python script on GitHub that essentially mirrors the screen of a device connected over ADB:

https://github.com/baitisj/android_screen_mirror

Returning Month Name in SQL Server Query

Change:

CONVERT(varchar(3), DATEPART(MONTH, S0.OrderDateTime) AS OrderMonth

To:

CONVERT(varchar(3), DATENAME(MONTH, S0.OrderDateTime)) AS OrderMonth

How do I find out which keystore was used to sign an app?

You can do this with the apksigner tool that is part of the Android SDK:

apksigner verify --print-certs my_app.apk

You can find apksigner inside the build-tools directory. For example: ~/Library/Android/sdk/build-tools/29.0.1/apksigner

How to use concerns in Rails 4

This post helped me understand concerns.

# app/models/trader.rb
class Trader
  include Shared::Schedule
end

# app/models/concerns/shared/schedule.rb
module Shared::Schedule
  extend ActiveSupport::Concern
  ...
end

TypeError: 'float' object not iterable

for i in count: means for i in 7:, which won't work. The bit after the in should be of an iterable type, not a number. Try this:

for i in range(count):

One or more types required to compile a dynamic expression cannot be found. Are you missing references to Microsoft.CSharp.dll and System.Core.dll?

I had the same problem and solved it by removing "Microsoft.CSharp" reference from the project and then added it again.

How can I see an the output of my C programs using Dev-C++?

Use #include conio.h

Then add getch(); before return 0;

Node.js create folder or use existing

You'd better not to count the filesystem hits while you code in Javascript, in my opinion. However, (1) stat & mkdir and (2) mkdir and check(or discard) the error code, both ways are right ways to do what you want.

What is the Git equivalent for revision number?

If you're interested, I managed version numbers automatically from git infos here under the format

<major>.<minor>.<patch>-b<build>

where build is the total number of commits. You'll see the interesting code in the Makefile. Here is the relevant part to access the different part of the version number:

LAST_TAG_COMMIT = $(shell git rev-list --tags --max-count=1)
LAST_TAG = $(shell git describe --tags $(LAST_TAG_COMMIT) )
TAG_PREFIX = "latex-tutorial-v"

VERSION  = $(shell head VERSION)
# OR try to guess directly from the last git tag
#VERSION    = $(shell  git describe --tags $(LAST_TAG_COMMIT) | sed "s/^$(TAG_PREFIX)//")
MAJOR      = $(shell echo $(VERSION) | sed "s/^\([0-9]*\).*/\1/")
MINOR      = $(shell echo $(VERSION) | sed "s/[0-9]*\.\([0-9]*\).*/\1/")
PATCH      = $(shell echo $(VERSION) | sed "s/[0-9]*\.[0-9]*\.\([0-9]*\).*/\1/")
# total number of commits       
BUILD      = $(shell git log --oneline | wc -l | sed -e "s/[ \t]*//g")

#REVISION   = $(shell git rev-list $(LAST_TAG).. --count)
#ROOTDIR    = $(shell git rev-parse --show-toplevel)
NEXT_MAJOR_VERSION = $(shell expr $(MAJOR) + 1).0.0-b$(BUILD)
NEXT_MINOR_VERSION = $(MAJOR).$(shell expr $(MINOR) + 1).0-b$(BUILD)
NEXT_PATCH_VERSION = $(MAJOR).$(MINOR).$(shell expr $(PATCH) + 1)-b$(BUILD)

How do I release memory used by a pandas dataframe?

This solves the problem of releasing the memory for me!!!

import gc
import pandas as pd

del [[df_1,df_2]]
gc.collect()
df_1=pd.DataFrame()
df_2=pd.DataFrame()

the data-frame will be explicitly set to null

in the above statements

Firstly, the self reference of the dataframe is deleted meaning the dataframe is no longer available to python there after all the references of the dataframe is collected by garbage collector (gc.collect()) and then explicitly set all the references to empty dataframe.

more on the working of garbage collector is well explained in https://stackify.com/python-garbage-collection/

Error:attempt to apply non-function

I got the error because of a clumsy typo:

This errors:

knitr::opts_chunk$seet(echo = FALSE)

Error: attempt to apply non-function

After correcting the typo, it works:

knitr::opts_chunk$set(echo = FALSE)

Setting max-height for table cell contents

Possibly not cross browser but I managed get this: http://jsfiddle.net/QexkH/

basically it requires a fixed height header and footer. and it absolute positions the table.

    table {
        width: 50%;
        height: 50%;
        border-spacing: 0;
        position:absolute;
    }
    td {
        border: 1px solid black;
    }
    #content {
        position:absolute;
        width:100%;
        left:0px;
        top:20px;
        bottom:20px;
        overflow: hidden;
    }

Handling null values in Freemarker

Use ?? operator at the end of your <#if> statement.

This example demonstrates how to handle null values for two lists in a Freemaker template.

List of cars:
<#if cars??>
    <#list cars as car>${car.owner};</#list>
</#if>
List of motocycles:
<#if motocycles??>
    <#list motocycles as motocycle>${motocycle.owner};</#list>
</#if>

When and Why to use abstract classes/methods?

At a very high level:

Abstraction of any kind comes down to separating concerns. "Client" code of an abstraction doesn't care how the contract exposed by the abstraction is fulfilled. You usually don't care if a string class uses a null-terminated or buffer-length-tracked internal storage implementation, for example. Encapsulation hides the details, but by making classes/methods/etc. abstract, you allow the implementation to change or for new implementations to be added without affecting the client code.

How large should my recv buffer be when calling recv in the socket library

The answers to these questions vary depending on whether you are using a stream socket (SOCK_STREAM) or a datagram socket (SOCK_DGRAM) - within TCP/IP, the former corresponds to TCP and the latter to UDP.

How do you know how big to make the buffer passed to recv()?

  • SOCK_STREAM: It doesn't really matter too much. If your protocol is a transactional / interactive one just pick a size that can hold the largest individual message / command you would reasonably expect (3000 is likely fine). If your protocol is transferring bulk data, then larger buffers can be more efficient - a good rule of thumb is around the same as the kernel receive buffer size of the socket (often something around 256kB).

  • SOCK_DGRAM: Use a buffer large enough to hold the biggest packet that your application-level protocol ever sends. If you're using UDP, then in general your application-level protocol shouldn't be sending packets larger than about 1400 bytes, because they'll certainly need to be fragmented and reassembled.

What happens if recv gets a packet larger than the buffer?

  • SOCK_STREAM: The question doesn't really make sense as put, because stream sockets don't have a concept of packets - they're just a continuous stream of bytes. If there's more bytes available to read than your buffer has room for, then they'll be queued by the OS and available for your next call to recv.

  • SOCK_DGRAM: The excess bytes are discarded.

How can I know if I have received the entire message?

  • SOCK_STREAM: You need to build some way of determining the end-of-message into your application-level protocol. Commonly this is either a length prefix (starting each message with the length of the message) or an end-of-message delimiter (which might just be a newline in a text-based protocol, for example). A third, lesser-used, option is to mandate a fixed size for each message. Combinations of these options are also possible - for example, a fixed-size header that includes a length value.

  • SOCK_DGRAM: An single recv call always returns a single datagram.

Is there a way I can make a buffer not have a fixed amount of space, so that I can keep adding to it without fear of running out of space?

No. However, you can try to resize the buffer using realloc() (if it was originally allocated with malloc() or calloc(), that is).

Using variables inside a bash heredoc

Don't use quotes with <<EOF:

var=$1
sudo tee "/path/to/outfile" > /dev/null <<EOF
Some text that contains my $var
EOF

Variable expansion is the default behavior inside of here-docs. You disable that behavior by quoting the label (with single or double quotes).

How do I change column default value in PostgreSQL?

If you want to remove the default value constraint, you can do:

ALTER TABLE <table> ALTER COLUMN <column> DROP DEFAULT;

When to use Hadoop, HBase, Hive and Pig?

Consider that you work with RDBMS and have to select what to use - full table scans, or index access - but only one of them.
If you select full table scan - use hive. If index access - HBase.

How can I change the Bootstrap default font family using font from Google?

If you use Sass, there are Bootstrap variables are defined with !default, among which you'll find font families. You can just set the variables in your own .scss file before including the Bootstrap Sass file and !default will not overwrite yours. Here's a good explanation of how !default works: https://thoughtbot.com/blog/sass-default.

Here's an untested example using Bootstrap 4, npm, Gulp, gulp-sass and gulp-cssmin to give you an idea how you could hook this up together.

package.json

{
  "devDependencies": {
    "bootstrap": "4.0.0-alpha.6",
    "gulp": "3.9.1",
    "gulp-sass": "3.1.0",
    "gulp-cssmin": "0.2.0"
  }
}

mysite.scss

@import "./myvariables";

// Bootstrap
@import "bootstrap/scss/variables";
// ... need to include other bootstrap files here.  Check node_modules\bootstrap\scss\bootstrap.scss for a list

_myvariables.scss

// For a list of Bootstrap variables you can override, look at node_modules\bootstrap\scss\_variables.scss

// These are the defaults, but you can override any values
$font-family-sans-serif: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif !default;
$font-family-serif:      Georgia, "Times New Roman", Times, serif !default;
$font-family-monospace:  Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace !default;
$font-family-base:       $font-family-sans-serif !default;

gulpfile.js

var gulp = require("gulp"),
    sass = require("gulp-sass"),
    cssmin = require("gulp-cssmin");

gulp.task("transpile:sass", function() {
    return gulp.src("./mysite.scss")
        .pipe(sass({ includePaths: "./node_modules" }).on("error", sass.logError))
        .pipe(cssmin())
        .pipe(gulp.dest("./css/"));
});

index.html

<html>
    <head>
        <link rel="stylesheet" type="text/css" href="mysite.css" />
    </head>
    <body>
        ...
    </body>
</html>

How to detect READ_COMMITTED_SNAPSHOT is enabled?

Neither on SQL2005 nor 2012 does DBCC USEROPTIONS show is_read_committed_snapshot_on:

Set Option  Value
textsize    2147483647
language    us_english
dateformat  mdy
datefirst   7
lock_timeout    -1
quoted_identifier   SET
arithabort  SET
ansi_null_dflt_on   SET
ansi_warnings   SET
ansi_padding    SET
ansi_nulls  SET
concat_null_yields_null SET
isolation level read committed

clear data inside text file in c++

If you set the trunc flag.

#include<fstream>

using namespace std;

fstream ofs;

int main(){
ofs.open("test.txt", ios::out | ios::trunc);
ofs<<"Your content here";
ofs.close(); //Using microsoft incremental linker version 14
}

I tested this thouroughly for my own needs in a common programming situation I had. Definitely be sure to preform the ".close();" operation. If you don't do this there is no telling whether or not you you trunc or just app to the begging of the file. Depending on the file type you might just append over the file which depending on your needs may not fullfill its purpose. Be sure to call ".close();" explicity on the fstream you are trying to replace.

Cannot call getSupportFragmentManager() from activity

I used FragmentActivity

TabAdapter = new TabPagerAdapter(((FragmentActivity) getActivity()).getSupportFragmentManager());

Caching a jquery ajax response in javascript/browser

Old question, but my solution is a bit different.

I was writing a single page web app that was constantly making ajax calls triggered by the user, and to make it even more difficult it required libraries that used methods other than jquery (like dojo, native xhr, etc). I wrote a plugin for one of my own libraries to cache ajax requests as efficiently as possible in a way that would work in all major browsers, regardless of which libraries were being used to make the ajax call.

The solution uses jSQL (written by me - a client-side persistent SQL implementation written in javascript which uses indexeddb and other dom storage methods), and is bundled with another library called XHRCreep (written by me) which is a complete re-write of the native XHR object.

To implement all you need to do is include the plugin in your page, which is here.

There are two options:

jSQL.xhrCache.max_time = 60;

Set the maximum age in minutes. any cached responses that are older than this are re-requested. Default is 1 hour.

jSQL.xhrCache.logging = true;

When set to true, mock XHR calls will be shown in the console for debugging.

You can clear the cache on any given page via

jSQL.tables = {}; jSQL.persist();

In Java, what does NaN mean?

NaN means "Not a Number" and is the result of undefined operations on floating point numbers like for example dividing zero by zero. (Note that while dividing a non-zero number by zero is also usually undefined in mathematics, it does not result in NaN but in positive or negative infinity).

Efficient iteration with index in Scala

How about this?

val a = Array("One", "Two", "Three")
a.foldLeft(0) ((i, x) => {println(i + ": " + x); i + 1;} )

Output:

0: One
1: Two
2: Three