Programs & Examples On #Valgrind

valgrind is a dynamic analysis tool for Linux, OS X, Android, and Solaris systems. It can be used for profiling as well as for finding memory leaks, race conditions, and threading errors.

Still Reachable Leak detected by Valgrind

You don't appear to understand what still reachable means.

Anything still reachable is not a leak. You don't need to do anything about it.

How to use the addr2line command in Linux?

Try adding the -f option to show the function names :

addr2line -f -e a.out 0x4005BDC

Proper way to initialize C++ structs

Since it's a POD struct, you could always memset it to 0 - this might be the easiest way to get the fields initialized (assuming that is appropriate).

How to redirect Valgrind's output to a file?

By default, Valgrind writes its output to stderr. So you need to do something like:

valgrind a.out > log.txt 2>&1

Alternatively, you can tell Valgrind to write somewhere else; see http://valgrind.org/docs/manual/manual-core.html#manual-core.comment (but I've never tried this).

Is there a good Valgrind substitute for Windows?

For Visual C++, try Visual Leak Detector. When I used it, it detected a memory leak from a new call and returned the actual line in source code of the leak. The latest release can be found at http://vld.codeplex.com/.

pinpointing "conditional jump or move depends on uninitialized value(s)" valgrind message

What this means is that you are trying to print out/output a value which is at least partially uninitialized. Can you narrow it down so that you know exactly what value that is? After that, trace through your code to see where it is being initialized. Chances are, you will see that it is not being fully initialized.

If you need more help, posting the relevant sections of source code might allow someone to offer more guidance.

EDIT

I see you've found the problem. Note that valgrind watches for Conditional jump or move based on unitialized variables. What that means is that it will only give out a warning if the execution of the program is altered due to the uninitialized value (ie. the program takes a different branch in an if statement, for example). Since the actual arithmetic did not involve a conditional jump or move, valgrind did not warn you of that. Instead, it propagated the "uninitialized" status to the result of the statement that used it.

It may seem counterintuitive that it does not warn you immediately, but as mark4o pointed out, it does this because uninitialized values get used in C all the time (examples: padding in structures, the realloc() call, etc.) so those warnings would not be very useful due to the false positive frequency.

How do I use valgrind to find memory leaks?

Try this:

valgrind --leak-check=full -v ./your_program

As long as valgrind is installed it will go through your program and tell you what's wrong. It can give you pointers and approximate places where your leaks may be found. If you're segfault'ing, try running it through gdb.

C free(): invalid pointer

From where did you get the idea that you need to free(token) and free(tk)? You don't. strsep() doesn't allocate memory, it only returns pointers inside the original string. Of course, those are not pointers allocated by malloc() (or similar), so free()ing them is undefined behavior. You only need to free(s) when you are done with the entire string.

Also note that you don't need dynamic memory allocation at all in your example. You can avoid strdup() and free() altogether by simply writing char *s = p;.

Vue.js—Difference between v-model and v-bind

There are cases where you don't want to use v-model. If you have two inputs, and each depend on each other, you might have circular referential issues. Common use cases is if you're building an accounting calculator.

In these cases, it's not a good idea to use either watchers or computed properties.

Instead, take your v-model and split it as above answer indicates

<input
   :value="something"
   @input="something = $event.target.value"
>

In practice, if you are decoupling your logic this way, you'll probably be calling a method.

This is what it would look like in a real world scenario:

_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>_x000D_
_x000D_
<div id="app">_x000D_
  <input :value="extendedCost" @input="_onInputExtendedCost" />_x000D_
  <p> {{ extendedCost }}_x000D_
</div>_x000D_
_x000D_
<script>_x000D_
  var app = new Vue({_x000D_
    el: "#app",_x000D_
    data: function(){_x000D_
      return {_x000D_
        extendedCost: 0,_x000D_
      }_x000D_
    },_x000D_
    methods: {_x000D_
      _onInputExtendedCost: function($event) {_x000D_
        this.extendedCost = parseInt($event.target.value);_x000D_
        // Go update other inputs here_x000D_
    }_x000D_
  }_x000D_
  });_x000D_
</script>
_x000D_
_x000D_
_x000D_

PHP absolute path to root

The best way Using dirname(). Because SERVER['DOCUMENT_ROOT'] not working all servers, and also return server running path.

$root = dirname( __FILE__ );

$root = __DIR__;

$filePath = realpath(dirname(__FILE__));

$rootPath = realpath($_SERVER['DOCUMENT_ROOT']);

$htmlPath = str_replace($root, '', $filePath);

Dynamically add script tag with src that may include document.write

the only way to do this is to replace document.write with your own function which will append elements to the bottom of your page. It is pretty straight forward with jQuery:

document.write = function(htmlToWrite) {
  $(htmlToWrite).appendTo('body');
}

If you have html coming to document.write in chunks like the question example you'll need to buffer the htmlToWrite segments. Maybe something like this:

document.write = (function() {
  var buffer = "";
  var timer;
  return function(htmlPieceToWrite) {
    buffer += htmlPieceToWrite;
    clearTimeout(timer);
    timer = setTimeout(function() {
      $(buffer).appendTo('body');
      buffer = "";
    }, 0)
  }
})()

What do raw.githubusercontent.com URLs represent?

There are two ways of looking at github content, the "raw" way and the "Web page" way.

raw.githubusercontent.com returns the raw content of files stored in github, so they can be downloaded simply to your computer. For example, if the page represents a ruby install script, then you will get a ruby install script that your ruby installation will understand.

If you instead download the file using the github.com link, you will actually be downloading a web page with buttons and comments and which displays your wanted script in the middle -- it's what you want to give to your web browser to get a nice page to look at, but for the computer, it is not a script that can be executed or code that can be compiled, but a web page to be displayed. That web page has a button called Raw that sends you to the corresponding content on raw.githubusercontent.com.

To see the content of raw.githubusercontent.com/${repo}/${branch}/${path} in the usual github interface:

  1. you replace raw.githubusercontent.com with plain github.com
  2. AND you insert "blob" between the repo name and the branch name.

In this case, the branch name is "master" (which is a very common branch name), so you replace /master/ with /blob/master/, and so

https://raw.githubusercontent.com/Homebrew/install/master/install

becomes

https://github.com/Homebrew/install/blob/master/install

This is the reverse of finding a file on Github and clicking the Raw link.

Why am I getting this redefinition of class error?

the implementation in the cpp file should be in the form

gameObject::gameObject()
    {
    x = 0;
    y = 0;
    }
gameObject::gameObject(int inx, int iny)
    {
        x = inx;
        y = iny;
    }

gameObject::~gameObject()
    {
    //
    }
int gameObject::add()
    {
        return x+y;
    }

not within a class gameObject { } definition block

Rebase array keys after unsetting elements

Just an additive.

I know this is old, but I wanted to add a solution I don't see that I came up with myself. Found this question while on hunt of a different solution and just figured, "Well, while I'm here."

First of all, Neal's answer is good and great to use after you run your loop, however, I'd prefer do all work at once. Of course, in my specific case I had to do more work than this simple example here, but the method still applies. I saw where a couple others suggested foreach loops, however, this still leaves you with after work due to the nature of the beast. Normally I suggest simpler things like foreach, however, in this case, it's best to remember good old fashioned for loop logic. Simply use i! To maintain appropriate index, just subtract from i after each removal of an Array item.

Here's my simple, working example:

$array = array(1,2,3,4,5);

for ($i = 0; $i < count($array); $i++) {
    if($array[$i] == 1 || $array[$i] == 2) {
        array_splice($array, $i, 1);
        $i--;
    }
}

Will output:

array(3) {
    [0]=> int(3)
    [1]=> int(4)
    [2]=> int(5)
}

This can have many simple implementations. For example, my exact case required holding of latest item in array based on multidimensional values. I'll show you what I mean:

$files = array(
    array(
        'name' => 'example.zip',
        'size' => '100000000',
        'type' => 'application/x-zip-compressed',
        'url' => '28188b90db990f5c5f75eb960a643b96/example.zip',
        'deleteUrl' => 'server/php/?file=example.zip',
        'deleteType' => 'DELETE'
    ),
    array(
        'name' => 'example.zip',
        'size' => '10726556',
        'type' => 'application/x-zip-compressed',
        'url' => '28188b90db990f5c5f75eb960a643b96/example.zip',
        'deleteUrl' => 'server/php/?file=example.zip',
        'deleteType' => 'DELETE'
    ),
    array(
        'name' => 'example.zip',
        'size' => '110726556',
        'type' => 'application/x-zip-compressed',
        'deleteUrl' => 'server/php/?file=example.zip',
        'deleteType' => 'DELETE'
    ),
    array(
        'name' => 'example2.zip',
        'size' => '12356556',
        'type' => 'application/x-zip-compressed',
        'url' => '28188b90db990f5c5f75eb960a643b96/example2.zip',
        'deleteUrl' => 'server/php/?file=example2.zip',
        'deleteType' => 'DELETE'
    )
);

for ($i = 0; $i < count($files); $i++) {
    if ($i > 0) {
        if (is_array($files[$i-1])) {
            if (!key_exists('name', array_diff($files[$i], $files[$i-1]))) {
                if (!key_exists('url', $files[$i]) && key_exists('url', $files[$i-1])) $files[$i]['url'] = $files[$i-1]['url'];
                $i--;
                array_splice($files, $i, 1);
            }
        }
    }
}

Will output:

array(1) {
    [0]=> array(6) {
            ["name"]=> string(11) "example.zip"
            ["size"]=> string(9) "110726556"
            ["type"]=> string(28) "application/x-zip-compressed"
            ["deleteUrl"]=> string(28) "server/php/?file=example.zip"
            ["deleteType"]=> string(6) "DELETE"
            ["url"]=> string(44) "28188b90db990f5c5f75eb960a643b96/example.zip"
        }
    [1]=> array(6) {
            ["name"]=> string(11) "example2.zip"
            ["size"]=> string(9) "12356556"
            ["type"]=> string(28) "application/x-zip-compressed"
            ["deleteUrl"]=> string(28) "server/php/?file=example2.zip"
            ["deleteType"]=> string(6) "DELETE"
            ["url"]=> string(45) "28188b90db990f5c5f75eb960a643b96/example2.zip"
        }
}

As you see, I manipulate $i before the splice as I'm seeking to remove the previous, rather than the present item.

node.js shell command execution

Synchronous one-liner:

require('child_process').execSync("echo 'hi'", function puts(error, stdout, stderr) { console.log(stdout) });

jQuery .ready in a dynamically inserted iframe

I'm loading the PDF with jQuery ajax into browser cache. Then I create embedded element with data already in browser cache. I guess it will work with iframe too.


var url = "http://example.com/my.pdf";
// show spinner
$.mobile.showPageLoadingMsg('b', note, false);
$.ajax({
    url: url,
    cache: true,
    mimeType: 'application/pdf',
    success: function () {
        // display cached data
        $(scroller).append('<embed type="application/pdf" src="' + url + '" />');
        // hide spinner
        $.mobile.hidePageLoadingMsg();
    }
});

You have to set your http headers correctly as well.


HttpContext.Response.Expires = 1;
HttpContext.Response.Cache.SetNoServerCaching();
HttpContext.Response.Cache.SetAllowResponseInBrowserHistory(false);
HttpContext.Response.CacheControl = "Private";

UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128)

Below solution worked for me, Just added

u "String"

(representing the string as unicode) before my string.

result_html = result.to_html(col_space=1, index=False, justify={'right'})

text = u"""
<html>
<body>
<p>
Hello all, <br>
<br>
Here's weekly summary report.  Let me know if you have any questions. <br>
<br>
Data Summary <br>
<br>
<br>
{0}
</p>
<p>Thanks,</p>
<p>Data Team</p>
</body></html>
""".format(result_html)

Python - PIP install trouble shooting - PermissionError: [WinError 5] Access is denied

Note that if you are installing this through Anaconda, you will need to open Anaconda as an administrator and then launch the command prompt from there.

Otherwise, you can also run "Anaconda prompt" directly as an administrator to uninstall and install packages.

How do I create a dynamic key to be added to a JavaScript object variable

Associative Arrays in JavaScript don't really work the same as they do in other languages. for each statements are complicated (because they enumerate inherited prototype properties). You could declare properties on an object/associative array as Pointy mentioned, but really for this sort of thing you should use an array with the push method:

jsArr = []; 

for (var i = 1; i <= 10; i++) { 
    jsArr.push('example ' + 1); 
} 

Just don't forget that indexed arrays are zero-based so the first element will be jsArr[0], not jsArr[1].

TypeError: tuple indices must be integers, not str

Like the error says, row is a tuple, so you can't do row["pool_number"]. You need to use the index: row[0].

Group list by values

values = set(map(lambda x:x[1], mylist))
newlist = [[y[0] for y in mylist if y[1]==x] for x in values]

How to determine whether a given Linux is 32 bit or 64 bit?

getconf uses the fewest system calls:

$ strace getconf LONG_BIT | wc -l
253

$ strace arch | wc -l
280

$ strace uname -m | wc -l
281

$ strace grep -q lm /proc/cpuinfo | wc -l
301

Setting multiple attributes for an element at once with JavaScript

You might be able to use Object.assign(...) to apply your properties to the created element. See comments for additional details.

Keep in mind that height and width attributes are defined in pixels, not percents. You'll have to use CSS to make it fluid.

_x000D_
_x000D_
var elem = document.createElement('img')_x000D_
Object.assign(elem, {_x000D_
  className: 'my-image-class',_x000D_
  src: 'https://dummyimage.com/320x240/ccc/fff.jpg',_x000D_
  height: 120, // pixels_x000D_
  width: 160, // pixels_x000D_
  onclick: function () {_x000D_
    alert('Clicked!')_x000D_
  }_x000D_
})_x000D_
document.body.appendChild(elem)_x000D_
_x000D_
// One-liner:_x000D_
// document.body.appendChild(Object.assign(document.createElement(...), {...}))
_x000D_
.my-image-class {_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
  border: solid 5px transparent;_x000D_
  box-sizing: border-box_x000D_
}_x000D_
_x000D_
.my-image-class:hover {_x000D_
  cursor: pointer;_x000D_
  border-color: red_x000D_
}_x000D_
_x000D_
body { margin:0 }
_x000D_
_x000D_
_x000D_

Sleep function in C++

On Unix, include #include <unistd.h>.

The call you're interested in is usleep(). Which takes microseconds, so you should multiply your millisecond value by 1000 and pass the result to usleep().

Python Socket Multiple Clients

Here is the example from the SocketServer documentation which would make an excellent starting point

import SocketServer

class MyTCPHandler(SocketServer.BaseRequestHandler):
    """
    The RequestHandler class for our server.

    It is instantiated once per connection to the server, and must
    override the handle() method to implement communication to the
    client.
    """

    def handle(self):
        # self.request is the TCP socket connected to the client
        self.data = self.request.recv(1024).strip()
        print "{} wrote:".format(self.client_address[0])
        print self.data
        # just send back the same data, but upper-cased
        self.request.sendall(self.data.upper())

if __name__ == "__main__":
    HOST, PORT = "localhost", 9999

    # Create the server, binding to localhost on port 9999
    server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)

    # Activate the server; this will keep running until you
    # interrupt the program with Ctrl-C
    server.serve_forever()

Try it from a terminal like this

$ telnet localhost 9999
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Hello
HELLOConnection closed by foreign host.
$ telnet localhost 9999
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Sausage
SAUSAGEConnection closed by foreign host.

You'll probably need to use A Forking or Threading Mixin too

How do I get the current date in Cocoa

CFGregorianDate currentDate = CFAbsoluteTimeGetGregorianDate(CFAbsoluteTimeGetCurrent(), CFTimeZoneCopySystem());
countdownLabel.text = [NSString stringWithFormat:@"%02d:%02d:%2.0f", currentDate.hour, currentDate.minute, currentDate.second];

Mark was right this code is MUCH more efficient to manage dates hours min and secs. But he forgot the @ at the beginning of format string declaration.

Get counts of all tables in a schema

You have to use execute immediate (dynamic sql).

DECLARE 
v_owner varchar2(40); 
v_table_name varchar2(40); 
cursor get_tables is 
select distinct table_name,user 
from user_tables 
where lower(user) = 'schema_name'; 
begin 
open get_tables; 
loop
    fetch get_tables into v_table_name,v_owner; 
    EXIT WHEN get_tables%NOTFOUND;
    execute immediate 'INSERT INTO STATS_TABLE(TABLE_NAME,SCHEMA_NAME,RECORD_COUNT,CREATED) 
    SELECT ''' || v_table_name || ''' , ''' || v_owner ||''',COUNT(*),TO_DATE(SYSDATE,''DD-MON-YY'')     FROM ' || v_table_name; 
end loop;
CLOSE get_tables; 
END; 

Arrays in unix shell?

Bourne shell doesn't support arrays. However, there are two ways to handle the issue.

Use positional shell parameters $1, $2, etc.:

$ set one two three
$ echo $*
one two three
$ echo $#
3
$ echo $2
two

Use variable evaluations:

$ n=1 ; eval a$n="one" 
$ n=2 ; eval a$n="two" 
$ n=3 ; eval a$n="three"
$ n=2
$ eval echo \$a$n
two

IF a cell contains a string

=IFS(COUNTIF(A1,"*cats*"),"cats",COUNTIF(A1,"*22*"),"22",TRUE,"none")

Python constructor and default value

I would try:

self.wordList = list(wordList)

to force it to make a copy instead of referencing the same object.

What is the purpose of global.asax in asp.net

The root directory of a web application has a special significance and certain content can be present on in that folder. It can have a special file called as “Global.asax”. ASP.Net framework uses the content in the global.asax and creates a class at runtime which is inherited from HttpApplication. During the lifetime of an application, ASP.NET maintains a pool of Global.asax derived HttpApplication instances. When an application receives an http request, the ASP.Net page framework assigns one of these instances to process that request. That instance is responsible for managing the entire lifetime of the request it is assigned to and the instance can only be reused after the request has been completed when it is returned to the pool. The instance members in Global.asax cannot be used for sharing data across requests but static member can be. Global.asax can contain the event handlers of HttpApplication object and some other important methods which would execute at various points in a web application

How to convert SQL Query result to PANDAS Data Structure?

Here's the code I use. Hope this helps.

import pandas as pd
from sqlalchemy import create_engine

def getData():
  # Parameters
  ServerName = "my_server"
  Database = "my_db"
  UserPwd = "user:pwd"
  Driver = "driver=SQL Server Native Client 11.0"

  # Create the connection
  engine = create_engine('mssql+pyodbc://' + UserPwd + '@' + ServerName + '/' + Database + "?" + Driver)

  sql = "select * from mytable"
  df = pd.read_sql(sql, engine)
  return df

df2 = getData()
print(df2)

How to find the array index with a value?

In a multidimensional array.


Reference array:

var array = [
    { ID: '100', },
    { ID: '200', },
    { ID: '300', },
    { ID: '400', },
    { ID: '500', }
];

Using filter and indexOf:

var in_array = array.filter(function(item) { 
    return item.ID == '200' // look for the item where ID is equal to value
});
var index = array.indexOf(in_array[0]);

Looping through each item in the array using indexOf:

for (var i = 0; i < array.length; i++) {
    var item= array[i];
    if (item.ID == '200') { 
        var index = array.indexOf(item);
    }
}

Mac OS X - EnvironmentError: mysql_config not found

Also this happens when I was installing mysqlclient,

$ pip install mysqlclient

As user3429036 said,

$ brew install mysql

How to use Git for Unity3D source control?

The following is an excerpt from my personal blog .

Using Git with 3D Games

Update Oct 2015: GitHub has since released a plugin for Git called Git LFS that directly deals with the below problem. You can now easily and efficiently version large binary files!

Git can work fine with 3D games out of the box. However the main caveat here is that versioning large (>5 MB) media files can be a problem over the long term as your commit history bloats. We have solved this potential issue in our projects by only versioning the binary asset when it is considered final. Our 3D artists use Dropbox to work on WIP assets, both for the reason above and because it's much faster and simpler (not many artists will actively want to use Git!).

Git Workflow

Your Git workflow is very much something you need to decide for yourself given your own experiences as a team and how you work together. However. I would strongly recommend the appropriately named Git Flow methodology as described by the original author here.

I won't go into too much depth here on how the methodology works as the author describes it perfectly and in quite few words too so it's easy to get through. I have been using with my team for awhile now, and it's the best workflow we've tried so far.

Git GUI Client Application

This is really a personal preference here as there are quite a few options in terms of Git GUI or whether to use a GUI at all. But I would like to suggest the free SourceTree application as it plugs in perfectly with the Git Flow extension. Read the SourceTree tutorial here on implementing the Git Flow methodology in their application.

Unity3D Ignore Folders

For an up to date version checkout Github maintained Unity.gitignore file without OS specifics.

# =============== #
# Unity generated #
# =============== #
Temp/
Library/

# ===================================== #
# Visual Studio / MonoDevelop generated #
# ===================================== #
ExportedObj/
obj/
*.svd
*.userprefs
/*.csproj
*.pidb
*.suo
/*.sln
*.user
*.unityproj
*.booproj

# ============ #
# OS generated #
# ============ #
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db

Unity3D Settings

For versions of Unity 3D v4.3 and up:

  1. (Skip this step in v4.5 and up) Enable External option in Unity ? Preferences ? Packages ? Repository.
  2. Open the Edit menu and pick Project Settings ? Editor:
    1. Switch Version Control Mode to Visible Meta Files.
    2. Switch Asset Serialization Mode to Force Text.
  3. Save the scene and project from File menu.

Want you migrate your existing repo to LFS?

Check out my blog post for steps on how to do it here.

Additional Configuration

One of the few major annoyances one has with using Git with Unity3D projects is that Git doesn't care about directories and will happily leave empty directories around after removing files from them. Unity3D will make *.meta files for these directories and can cause a bit of a battle between team members when Git commits keep adding and removing these meta files.

Add this Git post-merge hook to the /.git/hooks/ folder for repositories with Unity3D projects in them. After any Git pull/merge, it will look at what files have been removed, check if the directory it existed in is empty, and if so delete it.

Multiple FROMs - what it means

As of May 2017, multiple FROMs can be used in a single Dockerfile.
See "Builder pattern vs. Multi-stage builds in Docker" (by Alex Ellis) and PR 31257 by Tõnis Tiigi.

The general syntax involves adding FROM additional times within your Dockerfile - whichever is the last FROM statement is the final base image. To copy artifacts and outputs from intermediate images use COPY --from=<base_image_number>.

FROM golang:1.7.3 as builder
WORKDIR /go/src/github.com/alexellis/href-counter/
RUN go get -d -v golang.org/x/net/html  
COPY app.go    .
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o app .

FROM alpine:latest  
RUN apk --no-cache add ca-certificates
WORKDIR /root/
COPY --from=builder /go/src/github.com/alexellis/href-counter/app    .
CMD ["./app"]  

The result would be two images, one for building, one with just the resulting app (much, much smaller)

REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE

multi               latest              bcbbf69a9b59        6 minutes ago       10.3MB  
golang              1.7.3               ef15416724f6        4 months ago        672MB  

what is a base image?

A set of files, plus EXPOSE'd ports, ENTRYPOINT and CMD.
You can add files and build a new image based on that base image, with a new Dockerfile starting with a FROM directive: the image mentioned after FROM is "the base image" for your new image.

does it mean that if I declare neo4j/neo4j in a FROM directive, that when my image is run the neo database will automatically run and be available within the container on port 7474?

Only if you don't overwrite CMD and ENTRYPOINT.
But the image in itself is enough: you would use a FROM neo4j/neo4j if you had to add files related to neo4j for your particular usage of neo4j.

How to install Guest addition in Mac OS as guest and Windows machine as host

Guest additions are not available for Mac OS X. You can get features like clipboard sync and shared folders by using VNC and SMB. Here's my answer on a similar question.

How to get text from EditText?

Put this in your MainActivity:

{
    public EditText bizname, storeno, rcpt, item, price, tax, total;
    public Button click, click2;
    int contentView;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.main_activity );
        bizname = (EditText) findViewById( R.id.editBizName );
        item = (EditText) findViewById( R.id.editItem );
        price = (EditText) findViewById( R.id.editPrice );
        tax = (EditText) findViewById( R.id.editTax );
        total = (EditText) findViewById( R.id.editTotal );
        click = (Button) findViewById( R.id.button );
    }
}

Put this under a button or something

public void clickBusiness(View view) {
    checkPermsOfStorage( this );

    bizname = (EditText) findViewById( R.id.editBizName );
    item = (EditText) findViewById( R.id.editItem );
    price = (EditText) findViewById( R.id.editPrice );
    tax = (EditText) findViewById( R.id.editTax );
    total = (EditText) findViewById( R.id.editTotal );
    String x = ("\nItem/Price: " + item.getText() + price.getText() + "\nTax/Total" + tax.getText() + total.getText());
    Toast.makeText( this, x, Toast.LENGTH_SHORT ).show();
    try {
        this.WriteBusiness(bizname,storeno,rcpt,item,price,tax,total);
        String vv = tax.getText().toString();
        System.console().printf( "%s", vv );
        //new XMLDivisionWriter(getString(R.string.SDDoc) + "/tax_div_business.xml");
    } catch (ReflectiveOperationException e) {
        e.printStackTrace();
    }
}

There! The debate is settled!

How to remove not null constraint in sql server using query

 ALTER TABLE YourTable ALTER COLUMN YourColumn columnType NULL

displayname attribute vs display attribute

I think the current answers are neglecting to highlight the actual important and significant differences and what that means for the intended usage. While they might both work in certain situations because the implementer built in support for both, they have different usage scenarios. Both can annotate properties and methods but here are some important differences:

DisplayAttribute

  • defined in the System.ComponentModel.DataAnnotations namespace in the System.ComponentModel.DataAnnotations.dll assembly
  • can be used on parameters and fields
  • lets you set additional properties like Description or ShortName
  • can be localized with resources

DisplayNameAttribute

  • DisplayName is in the System.ComponentModel namespace in System.dll
  • can be used on classes and events
  • cannot be localized with resources

The assembly and namespace speaks to the intended usage and localization support is the big kicker. DisplayNameAttribute has been around since .NET 2 and seems to have been intended more for naming of developer components and properties in the legacy property grid, not so much for things visible to end users that may need localization and such.

DisplayAttribute was introduced later in .NET 4 and seems to be designed specifically for labeling members of data classes that will be end-user visible, so it is more suitable for DTOs, entities, and other things of that sort. I find it rather unfortunate that they limited it so it can't be used on classes though.

EDIT: Looks like latest .NET Core source allows DisplayAttribute to be used on classes now as well.

How do I download/extract font from chrome developers tools?

Right-click, then "Open link in new tab"

edit : you can also double-click, it has the same effect

Is there a better way to do optional function parameters in JavaScript?

function foo(requiredArg){
  if(arguments.length>1) var optionalArg = arguments[1];
}

Using Server.MapPath in external C# Classes in ASP.NET

I use this too:

System.Web.HTTPContext.Current.Server.MapPath

How to hide .php extension in .htaccess

I've used this:

RewriteEngine On

# Unless directory, remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/$ http://example.com/folder/$1 [R=301,L]

# Redirect external .php requests to extensionless URL
RewriteCond %{THE_REQUEST} ^(.+)\.php([#?][^\ ]*)?\ HTTP/
RewriteRule ^(.+)\.php$ http://example.com/folder/$1 [R=301,L]

# Resolve .php file for extensionless PHP URLs
RewriteRule ^([^/.]+)$ $1.php [L]

See also: this question

Append an object to a list in R in amortized constant time, O(1)?

In the Lisp we did it this way:

> l <- c(1)
> l <- c(2, l)
> l <- c(3, l)
> l <- rev(l)
> l
[1] 1 2 3

though it was 'cons', not just 'c'. If you need to start with an empy list, use l <- NULL.

Execute PowerShell Script from C# with Commandline Arguments

Mine is a bit more smaller and simpler:

/// <summary>
/// Runs a PowerShell script taking it's path and parameters.
/// </summary>
/// <param name="scriptFullPath">The full file path for the .ps1 file.</param>
/// <param name="parameters">The parameters for the script, can be null.</param>
/// <returns>The output from the PowerShell execution.</returns>
public static ICollection<PSObject> RunScript(string scriptFullPath, ICollection<CommandParameter> parameters = null)
{
    var runspace = RunspaceFactory.CreateRunspace();
    runspace.Open();
    var pipeline = runspace.CreatePipeline();
    var cmd = new Command(scriptFullPath);
    if (parameters != null)
    {
        foreach (var p in parameters)
        {
            cmd.Parameters.Add(p);
        }
    }
    pipeline.Commands.Add(cmd);
    var results = pipeline.Invoke();
    pipeline.Dispose();
    runspace.Dispose();
    return results;
}

Attach a body onload event with JS

This takes advantage of DOMContentLoaded - which fires before onload - but allows you to stick in all your unobtrusiveness...

window.onload - Dean Edwards - The blog post talks more about it - and here is the complete code copied from the comments of that same blog.

// Dean Edwards/Matthias Miller/John Resig

function init() {
  // quit if this function has already been called
  if (arguments.callee.done) return;

  // flag this function so we don't do the same thing twice
  arguments.callee.done = true;

  // kill the timer
  if (_timer) clearInterval(_timer);

  // do stuff
};

/* for Mozilla/Opera9 */
if (document.addEventListener) {
  document.addEventListener("DOMContentLoaded", init, false);
}

/* for Internet Explorer */
/*@cc_on @*/
/*@if (@_win32)
  document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
  var script = document.getElementById("__ie_onload");
  script.onreadystatechange = function() {
    if (this.readyState == "complete") {
      init(); // call the onload handler
    }
  };
/*@end @*/

/* for Safari */
if (/WebKit/i.test(navigator.userAgent)) { // sniff
  var _timer = setInterval(function() {
    if (/loaded|complete/.test(document.readyState)) {
      init(); // call the onload handler
    }
  }, 10);
}

/* for other browsers */
window.onload = init;

Convert Map to JSON using Jackson

If you're using jackson, better to convert directly to ObjectNode.

//not including SerializationFeatures for brevity
static final ObjectMapper mapper = new ObjectMapper();

//pass it your payload
public static ObjectNode convObjToONode(Object o) {
    StringWriter stringify = new StringWriter();
    ObjectNode objToONode = null;

    try {
        mapper.writeValue(stringify, o);
        objToONode = (ObjectNode) mapper.readTree(stringify.toString());
    } catch (IOException e) {
        e.printStackTrace();
    }

    System.out.println(objToONode);
    return objToONode;
}

How to set up datasource with Spring for HikariCP?

I have recently migrated from C3P0 to HikariCP in a Spring and Hibernate based project and it was not as easy as I had imagined and here I am sharing my findings.

For Spring Boot see my answer here

I have the following setup

  • Spring 4.3.8+
  • Hiberante 4.3.8+
  • Gradle 2.x
  • PostgreSQL 9.5

Some of the below configs are similar to some of the answers above but, there are differences.

Gradle stuff

In order to pull in the right jars, I needed to pull in the following jars

//latest driver because *brettw* see https://github.com/pgjdbc/pgjdbc/pull/849
compile 'org.postgresql:postgresql:42.2.0'
compile('com.zaxxer:HikariCP:2.7.6') {
    //they are pulled in separately elsewhere
    exclude group: 'org.hibernate', module: 'hibernate-core'
}

// Recommended to use HikariCPConnectionProvider by Hibernate in 4.3.6+    
compile('org.hibernate:hibernate-hikaricp:4.3.8.Final') {
        //they are pulled in separately elsewhere, to avoid version conflicts
        exclude group: 'org.hibernate', module: 'hibernate-core'
        exclude group: 'com.zaxxer', module: 'HikariCP'
}

// Needed for HikariCP logging if you use log4j
compile('org.slf4j:slf4j-simple:1.7.25')  
compile('org.slf4j:slf4j-log4j12:1.7.25') {
    //log4j pulled in separately, exclude to avoid version conflict
    exclude group: 'log4j', module: 'log4j'
}

Spring/Hibernate based configs

In order to get Spring & Hibernate to make use of Hikari Connection pool, you need to define the HikariDataSource and feed it into sessionFactory bean as shown below.

<!-- HikariCP Database bean -->
<bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close">
    <constructor-arg ref="hikariConfig" />
</bean>

<!-- HikariConfig config that is fed to above dataSource -->
<bean id="hikariConfig" class="com.zaxxer.hikari.HikariConfig">
        <property name="poolName" value="SpringHikariPool" />
        <property name="dataSourceClassName" value="org.postgresql.ds.PGSimpleDataSource" />
        <property name="maximumPoolSize" value="20" />
        <property name="idleTimeout" value="30000" />

        <property name="dataSourceProperties">
            <props>
                <prop key="serverName">localhost</prop>
                <prop key="portNumber">5432</prop>
                <prop key="databaseName">dbname</prop>
                <prop key="user">dbuser</prop>
                <prop key="password">dbpassword</prop>
            </props>
        </property>
</bean>

<bean class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" id="sessionFactory">
        <!-- Your Hikari dataSource below -->
        <property name="dataSource" ref="dataSource"/>
        <!-- your other configs go here -->
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.connection.provider_class">org.hibernate.hikaricp.internal.HikariCPConnectionProvider</prop>
                <!-- Remaining props goes here -->
            </props>
        </property>
 </bean>

Once the above are setup then, you need to add an entry to your log4j or logback and set the level to DEBUG to see Hikari Connection Pool start up.

Log4j1.2

<!-- Keep additivity=false to avoid duplicate lines -->
<logger additivity="false" name="com.zaxxer.hikari">
    <level value="debug"/>
    <!-- Your appenders goes here -->
</logger>

Logback

Via application.properties in Spring Boot

debug=true
logging.level.com.zaxxer.hikari.HikariConfig=DEBUG 

Using logback.xml

<logger name="com.zaxxer.hikari" level="DEBUG" additivity="false">
    <appender-ref ref="STDOUT" />
</logger>

With the above you should be all good to go! Obviously you need to customize the HikariCP pool configs in order to get the performance that it promises.

How to save the contents of a div as a image?

Do something like this:

A <div> with ID of #imageDIV, another one with ID #download and a hidden <div> with ID #previewImage.

Include the latest version of jquery, and jspdf.debug.js from the jspdf CDN

Then add this script:

var element = $("#imageDIV"); // global variable
var getCanvas; // global variable
$('document').ready(function(){
  html2canvas(element, {
    onrendered: function (canvas) {
      $("#previewImage").append(canvas);
      getCanvas = canvas;
    }
  });
});
$("#download").on('click', function () {
  var imgageData = getCanvas.toDataURL("image/png");
  // Now browser starts downloading it instead of just showing it
  var newData = imageData.replace(/^data:image\/png/, "data:application/octet-stream");
  $("#download").attr("download", "image.png").attr("href", newData);
});

The div will be saved as a PNG on clicking the #download

How to convert a currency string to a double with jQuery or Javascript?

For anyone looking for a solution in 2021 you can use Currency.js.

After much research this was the most reliable method I found for production, I didn't have any issues so far. In addition it's very active on Github.

currency(123);      // 123.00
currency(1.23);     // 1.23
currency("1.23")    // 1.23
currency("$12.30")  // 12.30

var value = currency("123.45");
currency(value);    // 123.45

How to get DataGridView cell value in messagebox?

      try
        {

            for (int rows = 0; rows < dataGridView1.Rows.Count; rows++)
            {

                for (int col = 0; col < dataGridView1.Rows[rows].Cells.Count; col++)
                {
                    s1 = dataGridView1.Rows[0].Cells[0].Value.ToString();
                    label20.Text = s1;
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("try again"+ex);
        }

What is the maximum possible length of a query string?

Different web stacks do support different lengths of http-requests. I know from experience that the early stacks of Safari only supported 4000 characters and thus had difficulty handling ASP.net pages because of the USER-STATE. This is even for POST, so you would have to check the browser and see what the stack limit is. I think that you may reach a limit even on newer browsers. I cannot remember but one of them (IE6, I think) had a limit of 16-bit limit, 32,768 or something.

Hibernate Union alternatives

I too have been through this pain - if the query is dynamically generated (e.g. Hibernate Criteria) then I couldn't find a practical way to do it.

The good news for me was that I was only investigating union to solve a performance problem when using an 'or' in an Oracle database.

The solution Patrick posted (combining the results programmatically using a set) while ugly (especially since I wanted to do results paging as well) was adequate for me.

SQL select join: is it possible to prefix all columns as 'prefix.*'?

If concerned about schema changes this might work for you: 1. Run a 'DESCRIBE table' query on all tables involved. 2. Use the returned field names to dynamically construct a string of column names prefixed with your chosen alias.

Call to a member function fetch_assoc() on boolean in <path>

OK, i just fixed this error.

This happens when there is an error in query or table doesn't exist.

Try debugging the query buy running it directly on phpmyadmin to confirm the validity of the mysql Query

How to get Chrome to allow mixed content?

In Windows open the Run window (Win + R):

C:\Program Files (x86)\Google\Chrome\Application\chrome.exe  --allow-running-insecure-content

In OS-X Terminal.app run the following command +space:

open /Applications/Google\ Chrome.app --args --allow-running-insecure-content

Note: You seem to be able to add the argument --allow-running-insecure-content to bypass this for development. But its not a recommended solution.

String to object in JS

You need use JSON.parse() for convert String into a Object:

var obj = JSON.parse('{ "firstName":"name1", "lastName": "last1" }');

Is it not possible to define multiple constructors in Python?

The easiest way is through keyword arguments:

class City():
  def __init__(self, city=None):
    pass

someCity = City(city="Berlin")

This is pretty basic stuff. Maybe look at the Python documentation?

Refresh Page and Keep Scroll Position

this will do the magic

    <script>
        document.addEventListener("DOMContentLoaded", function(event) { 
            var scrollpos = localStorage.getItem('scrollpos');
            if (scrollpos) window.scrollTo(0, scrollpos);
        });

        window.onbeforeunload = function(e) {
            localStorage.setItem('scrollpos', window.scrollY);
        };
    </script>

merge one local branch into another local branch

  1. git checkout [branchYouWantToReceiveBranch] - checkout branch you want to receive branch
  2. git merge [branchYouWantToMergeIntoBranch]

How to update gradle in android studio?

On Mac, open terminal and run the following commands as per instructions:

$ curl -s https://get.sdkman.io | bash

then

$ sdk install gradle 3.0

Once the installation is complete, the terminal would ask whether to set it as a default version so type y and make it the default version.

Now open Android Studio -> Terminal and run the following command

Gradle --version

Creating a directory in /sdcard fails

I had same issue after I updated my Android phone to 6.0 (API level 23). The following solution works on me. Hopefully it helps you as well.

Please check your android version. If it is >= 6.0 (API level 23), you need to not only include

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

in your AndroidManifest.xml, but also request permission before calling mkdir(). Code snopshot.

public static final int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 1;
public int mkFolder(String folderName){ // make a folder under Environment.DIRECTORY_DCIM
    String state = Environment.getExternalStorageState();
    if (!Environment.MEDIA_MOUNTED.equals(state)){
        Log.d("myAppName", "Error: external storage is unavailable");
        return 0;
    }
    if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        Log.d("myAppName", "Error: external storage is read only.");
        return 0;
    }
    Log.d("myAppName", "External storage is not read only or unavailable");

    if (ContextCompat.checkSelfPermission(this, // request permission when it is not granted. 
            Manifest.permission.WRITE_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED) {
        Log.d("myAppName", "permission:WRITE_EXTERNAL_STORAGE: NOT granted!");
        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)) {

            // Show an expanation to the user *asynchronously* -- don't block
            // this thread waiting for the user's response! After the user
            // sees the explanation, try again to request the permission.

        } else {

            // No explanation needed, we can request the permission.

            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);

            // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
            // app-defined int constant. The callback method gets the
            // result of the request.
        }
    }
    File folder = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),folderName);
    int result = 0;
    if (folder.exists()) {
        Log.d("myAppName","folder exist:"+folder.toString());
        result = 2; // folder exist
    }else{
        try {
            if (folder.mkdir()) {
                Log.d("myAppName", "folder created:" + folder.toString());
                result = 1; // folder created
            } else {
                Log.d("myAppName", "creat folder fails:" + folder.toString());
                result = 0; // creat folder fails
            }
        }catch (Exception ecp){
            ecp.printStackTrace();
        }
    }
    return result;
}

@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted, yay! Do the
                // contacts-related task you need to do.

            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
}

More information please read "Requesting Permissions at Run Time"

postgreSQL - psql \i : how to execute script in a given path

Try this, I work myself to do so

\i 'somedir\\script2.sql'

Are these methods thread safe?

The only problem with threads is accessing the same object from different threads without synchronization.

If each function only uses parameters for reading and local variables, they don't need any synchronization to be thread-safe.

OpenCV - Saving images to a particular folder of choice

You can do it with OpenCV's function imwrite:

import cv2
cv2.imwrite('Path/Image.jpg', image_name)

In Angular, What is 'pathmatch: full' and what effect does it have?

RouterModule.forRoot([
      { path: 'welcome', component: WelcomeComponent },
      { path: '', redirectTo: 'welcome', pathMatch: 'full' },
      { path: '**', component: 'pageNotFoundComponent' }
    ])

Case 1 pathMatch:'full': In this case, when app is launched on localhost:4200 (or some server) the default page will be welcome screen, since the url will be https://localhost:4200/

If https://localhost:4200/gibberish this will redirect to pageNotFound screen because of path:'**' wildcard

Case 2 pathMatch:'prefix':

If the routes have { path: '', redirectTo: 'welcome', pathMatch: 'prefix' }, now this will never reach the wildcard route since every url would match path:'' defined.

Getting command-line password input in Python

Updating on the answer of @Ahmed ALaa

# import msvcrt
import getch

def getPass():
    passwor = ''
    while True:
        x = getch.getch()
        # x = msvcrt.getch().decode("utf-8")
        if x == '\r' or x == '\n':
            break
        print('*', end='', flush=True)
        passwor +=x
    return passwor

print("\nout=", getPass())

msvcrt us only for windows, but getch from PyPI should work for both (I only tested with linux). You can also comment/uncomment the two lines to make it work for windows.

What is the difference between Step Into and Step Over in a debugger

When debugging lines of code, here are the usual scenarios:

  • (Step Into) A method is about to be invoked, and you want to debug into the code of that method, so the next step is to go into that method and continue debugging step-by-step.
  • (Step Over) A method is about to be invoked, but you're not interested in debugging this particular invocation, so you want the debugger to execute that method completely as one entire step.
  • (Step Return) You're done debugging this method step-by-step, and you just want the debugger to run the entire method until it returns as one entire step.
  • (Resume) You want the debugger to resume "normal" execution instead of step-by-step
  • (Line Breakpoint) You don't care how it got there, but if execution reaches a particular line of code, you want the debugger to temporarily pause execution there so you can decide what to do.

Eclipse has other advanced debugging features, but these are the basic fundamentals.

See also

How to get the current TimeStamp?

I think you are looking for this function:

http://doc.qt.io/qt-5/qdatetime.html#toTime_t

uint QDateTime::toTime_t () const

Returns the datetime as the number of seconds that have passed since 1970-01-01T00:00:00, > Coordinated Universal Time (Qt::UTC).

On systems that do not support time zones, this function will behave as if local time were Qt::UTC.

See also setTime_t().

How to terminate script execution when debugging in Google Chrome?

If you are encountering this while using the debugger statement,

debugger;

... then I think the page will continue running forever until the js runtime yields, or the next break. Assuming you're in break-on-error mode (the pause-icon toggle), you can ensure a break happens by instead doing something like:

debugger;throw 1;

or maybe call a non-existent function:

debugger;z();

(Of course this doesn't help if you are trying to step through functions, though perhaps you could dynamically add in a throw 1 or z() or somesuch in the Sources panel, ctrl-S to save, and then ctrl-R to refresh... this may however skip one breakpoint, but may work if you're in a loop.)

If you are doing a loop and expect to trigger the debugger statement again, you could just type throw 1 instead.

throw 1;

Then when you hit ctrl-R, the next throw will be hit, and the page will refresh.

(tested with Chrome v38, circa Apr 2017)

Bootstrap 4 img-circle class not working

Now the class is this

_x000D_
_x000D_
 <img src="img/img5.jpg" width="200px" class="rounded-circle float-right">
_x000D_
_x000D_
_x000D_

How to put a horizontal divisor line between edit text's in a activity

Try this link.... horizontal rule

That should do the trick.

The code below is xml.

<View
    android:layout_width="fill_parent"
    android:layout_height="2dip"
    android:background="#FF00FF00" />

Adding click event listener to elements with the same class

(ES5) I use forEach to iterate on the collection returned by querySelectorAll and it works well :

document.querySelectorAll('your_selector').forEach(item => { /* do the job with item element */ });

How to avoid reverse engineering of an APK file?

Developers can take following steps to prevent an APK from theft somehow,

  • the most basic way is to use tools like ProGuard to obfuscate their code, but up until now, it has been quite difficult to completely prevent someone from decompiling an app.

  • Also I have heard about a tool HoseDex2Jar. It stops Dex2Jar by inserting harmless code in an Android APK that confuses and disables Dex2Jar and protects the code from decompilation. It could somehow prevent hackers from decompiling an APK into readable java code.

  • Use some server side application to communicate with the application only when it is needed. It could help prevent the important data.

At all, you can not completely protect your code from the potential hackers. Somehow, you could make it difficult and a bit frustrating task for them to decompile your code. One of the most efficient way is to write in native code(C/C++) and store it as compiled libraries.

mysql stored-procedure: out parameter

You must have use correct signature for input parameter *IN is missing in the below code.

CREATE PROCEDURE my_sqrt(IN input_number INT, OUT out_number FLOAT)

Can I set the cookies to be used by a WKWebView?

This works for me: After setcookies , add fetchdatarecords

   let cookiesSet = NetworkProvider.getCookies(forKey : 
    PaywallProvider.COOKIES_KEY, completionHandler: nil)
                let dispatchGroup = DispatchGroup()
                for (cookie) in cookiesSet {
                    if #available(iOS 11.0, *) {
                        dispatchGroup.enter()
                        self.webView.configuration.websiteDataStore.httpCookieStore.setCookie(cookie){
                            dispatchGroup.leave()
                            print ("cookie added: \(cookie.description)")
                            }
                        } else {
                                            // TODO Handle ios 10 Fallback on earlier versions
                        }
                    }
                    dispatchGroup.notify(queue: .main, execute: {


    self.webView.configuration.websiteDataStore.fetchDataRecords(ofTypes: 
    WKWebsiteDataStore.allWebsiteDataTypes()) { records in
                            records.forEach { record in

                                print("[WebCacheCleaner] Record \(record)")
                            }
                            self.webView.load(URLRequest(url: 
    self.dataController.premiumArticleURL , 
    cachePolicy:NSURLRequest.CachePolicy.reloadIgnoringLocalAndRemoteCacheData,
                                                         timeoutInterval: 10.0))
                        }

                    })
                }

How to get the full URL of a Drupal page?

You can also do it this way:

$current_url = 'http://' .$_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

It's a bit faster.

Pull all images from a specified directory and then display them

Strict Standards: Only variables should be passed by reference in /home/aadarshi/public_html/----------/upload/view.php on line 32

and the code is:

<?php

echo scanDirectoryImages("uploads");

/**
* Recursively search through directory for images and display them
* 
* @param  array  $exts
* @param  string $directory
* @return string
*/
function scanDirectoryImages($directory, array $exts = array('jpeg', 'jpg', 'gif', 'png'))
{
if (substr($directory, -1) == '/') {
    $directory = substr($directory, 0, -1);
}
$html = '';
if (
    is_readable($directory)
    && (file_exists($directory) || is_dir($directory))
) {
    $directoryList = opendir($directory);
    while($file = readdir($directoryList)) {
        if ($file != '.' && $file != '..') {
            $path = $directory . '/' . $file;
            if (is_readable($path)) {
                if (is_dir($path)) {
                    return scanDirectoryImages($path, $exts);
                }
                if (
                    is_file($path)
                    && in_array(end(explode('.', end(explode('/', $path)))),   $exts)
                ) {
                    $html .= '<a href="' . $path . '"><img src="' . $path
                        . '" style="max-height:100px;max-width:100px" />  </a>';
                }
            }
        }
    }
    closedir($directoryList);
}
return $html;
}

How can I trigger an onchange event manually?

MDN suggests that there's a much cleaner way of doing this in modern browsers:

// Assuming we're listening for e.g. a 'change' event on `element`

// Create a new 'change' event
var event = new Event('change');

// Dispatch it.
element.dispatchEvent(event);

How to put a link on a button with bootstrap?

You can call a function on click event of button.

<input type="button" class="btn btn-info" value="Input Button" onclick=" relocate_home()">

<script>
function relocate_home()
{
     location.href = "www.yoursite.com";
} 
</script>

OR Use this Code

<a href="#link" class="btn btn-info" role="button">Link Button</a>

Android SQLite Example

Sqlite helper class helps us to manage database creation and version management. SQLiteOpenHelper takes care of all database management activities. To use it,
1.Override onCreate(), onUpgrade() methods of SQLiteOpenHelper. Optionally override onOpen() method.
2.Use this subclass to create either a readable or writable database and use the SQLiteDatabase's four API methods insert(), execSQL(), update(), delete() to create, read, update and delete rows of your table.

Example to create a MyEmployees table and to select and insert records:

public class MyDatabaseHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "DBName";

    private static final int DATABASE_VERSION = 2;

    // Database creation sql statement
    private static final String DATABASE_CREATE = "create table MyEmployees
                                 ( _id integer primary key,name text not null);";

    public MyDatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // Method is called during creation of the database
    @Override
    public void onCreate(SQLiteDatabase database) {
        database.execSQL(DATABASE_CREATE);
    }

    // Method is called during an upgrade of the database,
    @Override
    public void onUpgrade(SQLiteDatabase database,int oldVersion,int newVersion){
        Log.w(MyDatabaseHelper.class.getName(),
                         "Upgrading database from version " + oldVersion + " to "
                         + newVersion + ", which will destroy all old data");
        database.execSQL("DROP TABLE IF EXISTS MyEmployees");
        onCreate(database);
    }
}

Now you can use this class as below,

public class MyDB{  

    private MyDatabaseHelper dbHelper;  

    private SQLiteDatabase database;  

    public final static String EMP_TABLE="MyEmployees"; // name of table 

    public final static String EMP_ID="_id"; // id value for employee
    public final static String EMP_NAME="name";  // name of employee

    /** 
     * 
     * @param context 
     */  
    public MyDB(Context context){  
        dbHelper = new MyDatabaseHelper(context);  
        database = dbHelper.getWritableDatabase();  
    }


    public long createRecords(String id, String name){  
        ContentValues values = new ContentValues();  
        values.put(EMP_ID, id);  
        values.put(EMP_NAME, name);  
        return database.insert(EMP_TABLE, null, values);  
    }    

    public Cursor selectRecords() {
        String[] cols = new String[] {EMP_ID, EMP_NAME};  
        Cursor mCursor = database.query(true, EMP_TABLE,cols,null  
            , null, null, null, null, null);  
        if (mCursor != null) {  
            mCursor.moveToFirst();  
        }  
        return mCursor; // iterate to get each value.
    }
}

Now you can use MyDB class in you activity to have all the database operations. The create records will help you to insert the values similarly you can have your own functions for update and delete.

Can I have multiple background images using CSS?

You could have a div for the top with one background and another for the main page, and seperate the page content between them or put the content in a floating div on another z-level. The way you are doing it may work but I doubt it will work across every browser you encounter.

Closure in Java 7

According to Tom Hawtin

A closure is a block of code that can be referenced (and passed around) with access to the variables of the enclosing scope.

Now I'm trying to emulate the JavaScript closure example on Wikipedia, with a "straigth" translation to Java, in the hope to be useful:

//ECMAScript
var f, g;
function foo() {
  var x = 0;
  f = function() { return ++x; };
  g = function() { return --x; };
  x = 1;
  print('inside foo, call to f(): ' + f()); // "2"  
}
foo();
print('call to g(): ' + g()); // "1"
print('call to f(): ' + f()); // "2"

Now the java part: Function1 is "Functor" interface with arity 1 (one argument). Closure is the class implementing the Function1, a concrete Functor that acts as function (int -> int). In the main() method I just instantiate foo as a Closure object, replicating the calls from the JavaScript example. The IntBox class is just a simple container, it behave like an array of 1 int:

int a[1] = {0}

interface Function1   {
    public final IntBag value = new IntBag();
    public int apply();
}

class Closure implements Function1 {
   private IntBag x = value;
   Function1 f;
   Function1 g;

   @Override
   public int apply()  {
    // print('inside foo, call to f(): ' + f()); // "2"
    // inside apply, call to f.apply()
       System.out.println("inside foo, call to f.apply(): " + f.apply());
       return 0;
   }

   public Closure() {
       f = new Function1() {
           @Override
           public int apply()  {
               x.add(1);
                return x.get();
           }
       };
       g = new Function1() {
           @Override
           public int apply()  {
               x.add(-1);
               return x.get();
           }
       };
    // x = 1;
       x.set(1);
   }
}
public class ClosureTest {
    public static void main(String[] args) {
        // foo()
        Closure foo = new Closure();
        foo.apply();
        // print('call to g(): ' + g()); // "1"
        System.out.println("call to foo.g.apply(): " + foo.g.apply());
        // print('call to f(): ' + f()); // "2"
        System.out.println("call to foo.f.apply(): " + foo.f.apply());

    }
}

It prints:

inside foo, call to f.apply(): 2
call to foo.g.apply(): 1
call to foo.f.apply(): 2 

using stored procedure in entity framework

// Add some tenants to context so we have something for the procedure to return! AddTenentsToContext(Context);

    // ACT
    // Get the results by calling the stored procedure from the context extention method 
    var results = Context.ExecuteStoredProcedure(procedure);

    // ASSERT
    Assert.AreEqual(expectedCount, results.Count);
}

How do I dynamically change the content in an iframe using jquery?

If you just want to change where the iframe points to and not the actual content inside the iframe, you would just need to change the src attribute.

 $("#myiframe").attr("src", "newwebpage.html");

How do I search within an array of hashes by hash values in ruby?

if your array looks like

array = [
 {:name => "Hitesh" , :age => 27 , :place => "xyz"} ,
 {:name => "John" , :age => 26 , :place => "xtz"} ,
 {:name => "Anil" , :age => 26 , :place => "xsz"} 
]

And you Want To know if some value is already present in your array. Use Find Method

array.find {|x| x[:name] == "Hitesh"}

This will return object if Hitesh is present in name otherwise return nil

Modifying the "Path to executable" of a windows service

You could also do it with PowerShell:

Get-WmiObject win32_service -filter "Name='My Service'" `
    | Invoke-WmiMethod -Name Change `
    -ArgumentList @($null,$null,$null,$null,$null, `
    "C:\Program Files (x86)\My Service\NewName.EXE")

Or:

Set-ItemProperty -Path "HKLM:\System\CurrentControlSet\Services\My Service" `
    -Name ImagePath -Value "C:\Program Files (x86)\My Service\NewName.EXE"

How to use glyphicons in bootstrap 3.0

The icons (glyphicons) are now contained in a separate css file...

The markup has changed to:

<i class="glyphicon glyphicon-search"></i>

or

<span class="glyphicon glyphicon-search"></span>

Here is a helpful list of changes for Bootstrap 3: http://bootply.com/bootstrap-3-migration-guide

'typeid' versus 'typeof' in C++

You can use Boost demangle to accomplish a nice looking name:

#include <boost/units/detail/utility.hpp>

and something like

To_main_msg_evt ev("Failed to initialize cards in " + boost::units::detail::demangle(typeid(*_IO_card.get()).name()) + ".\n", true, this);

Scrolling a div with jQuery

An excellent plug-in is jscrollpane

sys.argv[1] meaning in script

sys.argv is a attribute of the sys module. It says the arguments passed into the file in the command line. sys.argv[0] catches the directory where the file is located. sys.argv[1] returns the first argument passed in the command line. Think like we have a example.py file.

example.py

import sys # Importing the main sys module to catch the arguments
print(sys.argv[1]) # Printing the first argument

Now here in the command prompt when we do this:

python example.py

It will throw a index error at line 2. Cause there is no argument passed yet. You can see the length of the arguments passed by user using if len(sys.argv) >= 1: # Code. If we run the example.py with passing a argument

python example.py args

It prints:

args

Because it was the first arguement! Let's say we have made it a executable file using PyInstaller. We would do this:

example argumentpassed

It prints:

argumentpassed

It's really helpful when you are making a command in the terminal. First check the length of the arguments. If no arguments passed, do the help text.

Error: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp()

The answer may already be given somewhere but here is my take to this error which may be thrown for multiple reasons:

  1. Default app is initialized after the other one. Correct way is to initialize the default app first and then the rest.
  2. firebase.apps.app() is being called before default app initialization. This code is basically returning the default app instance. Since it is not present, hence the error.
  3. Lastly, you are initializing other firebase services like auth, database, firestore, etc before app is initialized.

Hot to get all form elements values using jQuery?

jQuery has very helpful function called serialize.

Demo: http://jsfiddle.net/55xnJ/2/

//Just type:
$("#preview_form").serialize();

//to get result:
single=Single&multiple=Multiple&multiple=Multiple3&check=check2&radio=radio1

Singular matrix issue with Numpy

By definition, by multiplying a 1D vector by its transpose, you've created a singular matrix.

Each row is a linear combination of the first row.

Notice that the second row is just 8x the first row.

Likewise, the third row is 50x the first row.

There's only one independent row in your matrix.

What is the difference between signed and unsigned variables?

Signed variables can be 0, positive or negative.

Unsigned variables can be 0 or positive.

Unsigned variables are used sometimes because more bits can be used to represent the actual value. Giving you a larger range. Also you can ensure that a negative value won't be passed to your function for example.

Show image using file_get_contents

Do i need to modify the headers and just echo it or something?

exactly.

Send a header("content-type: image/your_image_type"); and the data afterwards.

IOError: [Errno 32] Broken pipe: Python

I feel obliged to point out that the method using

signal(SIGPIPE, SIG_DFL) 

is indeed dangerous (as already suggested by David Bennet in the comments) and in my case led to platform-dependent funny business when combined with multiprocessing.Manager (because the standard library relies on BrokenPipeError being raised in several places). To make a long and painful story short, this is how I fixed it:

First, you need to catch the IOError (Python 2) or BrokenPipeError (Python 3). Depending on your program you can try to exit early at that point or just ignore the exception:

from errno import EPIPE

try:
    broken_pipe_exception = BrokenPipeError
except NameError:  # Python 2
    broken_pipe_exception = IOError

try:
    YOUR CODE GOES HERE
except broken_pipe_exception as exc:
    if broken_pipe_exception == IOError:
        if exc.errno != EPIPE:
            raise

However, this isn't enough. Python 3 may still print a message like this:

Exception ignored in: <_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>
BrokenPipeError: [Errno 32] Broken pipe

Unfortunately getting rid of that message is not straightforward, but I finally found http://bugs.python.org/issue11380 where Robert Collins suggests this workaround that I turned into a decorator you can wrap your main function with (yes, that's some crazy indentation):

from functools import wraps
from sys import exit, stderr, stdout
from traceback import print_exc


def suppress_broken_pipe_msg(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        try:
            return f(*args, **kwargs)
        except SystemExit:
            raise
        except:
            print_exc()
            exit(1)
        finally:
            try:
                stdout.flush()
            finally:
                try:
                    stdout.close()
                finally:
                    try:
                        stderr.flush()
                    finally:
                        stderr.close()
    return wrapper


@suppress_broken_pipe_msg
def main():
    YOUR CODE GOES HERE

How to discard local commits in Git?

I had to do a :

git checkout -b master

as git said that it doesn't exists, because it's been wipe with the

git -D master

Port 80 is being used by SYSTEM (PID 4), what is that?

It sounds like IIS is listening to port 80 for HTTP requests.

Try stopping IIS by going into Control Panel/Administrative Tools/Internet Information Services, right-clicking on Default Web Site, and click on the Stop option in the popup menu, and see if the listener on port 80 has cleared.

CSS show div background image on top of other contained elements

How about making the <div id="mainWrapperDivWithBGImage"> as three divs, where the two outside divs hold the rounded corners images, and the middle div simply has a background-color to match the rounded corner images. Then you could simply place the other elements inside the middle div, or:

#outside_left{width:10px; float:left;}
#outside_right{width:10px; float:right;}
#middle{background-color:#color of rnd_crnrs_foo.gif; float:left;}

Then

HTML:

<div id="mainWrapperDivWithBGImage">
  <div id="outside_left><img src="rnd_crnrs_left.gif" /></div>
  <div id="middle">
    <div id="another_div"><img src="foo.gif" /></div>
  <div id="outside_right><img src="rnd_crnrs_right.gif" /></div>
</div>

You may have to do position:relative; and such.

document.getElementById().value and document.getElementById().checked not working for IE

Jin Yong - IE has an issue with polluting the global scope with object references to any DOM elements with a "name" or "id" attribute set on the "initial" page load.

Thus you may have issues due to your variable name.

Try this and see if it works.

var someOtherName="abc";
//  ^^^^^^^^^^^^^
document.getElementById('msg').value = someOtherName;
document.getElementById('sp_100').checked = true;

There is a chance (in your original code) that IE attempts to set the value of the input to a reference to that actual element (ignores the error) but leaves you with no new value.

Keep in mind that in IE6/IE7 case doesn't matter for naming objects. IE believes that "foo" "Foo" and "FOO" are all the same object.

Detect URLs in text with JavaScript

Generic Object Oriented Solution

For people like me that use frameworks like angular that don't allow manipulating DOM directly, I created a function that takes a string and returns an array of url/plainText objects that can be used to create any UI representation that you want.

URL regex

For URL matching I used (slightly adapted) h0mayun regex: /(?:(?:https?:\/\/)|(?:www\.))[^\s]+/g

My function also drops punctuation characters from the end of a URL like . and , that I believe more often will be actual punctuation than a legit URL ending (but it could be! This is not rigorous science as other answers explain well) For that I apply the following regex onto matched URLs /^(.+?)([.,?!'"]*)$/.

Typescript code

    export function urlMatcherInText(inputString: string): UrlMatcherResult[] {
        if (! inputString) return [];

        const results: UrlMatcherResult[] = [];

        function addText(text: string) {
            if (! text) return;

            const result = new UrlMatcherResult();
            result.type = 'text';
            result.value = text;
            results.push(result);
        }

        function addUrl(url: string) {
            if (! url) return;

            const result = new UrlMatcherResult();
            result.type = 'url';
            result.value = url;
            results.push(result);
        }

        const findUrlRegex = /(?:(?:https?:\/\/)|(?:www\.))[^\s]+/g;
        const cleanUrlRegex = /^(.+?)([.,?!'"]*)$/;

        let match: RegExpExecArray;
        let indexOfStartOfString = 0;

        do {
            match = findUrlRegex.exec(inputString);

            if (match) {
                const text = inputString.substr(indexOfStartOfString, match.index - indexOfStartOfString);
                addText(text);

                var dirtyUrl = match[0];
                var urlDirtyMatch = cleanUrlRegex.exec(dirtyUrl);
                addUrl(urlDirtyMatch[1]);
                addText(urlDirtyMatch[2]);

                indexOfStartOfString = match.index + dirtyUrl.length;
            }
        }
        while (match);

        const remainingText = inputString.substr(indexOfStartOfString, inputString.length - indexOfStartOfString);
        addText(remainingText);

        return results;
    }

    export class UrlMatcherResult {
        public type: 'url' | 'text'
        public value: string
    }

What does the 'Z' mean in Unix timestamp '120314170138Z'?

The Z stands for 'Zulu' - your times are in UTC. From Wikipedia:

The UTC time zone is sometimes denoted by the letter Z—a reference to the equivalent nautical time zone (GMT), which has been denoted by a Z since about 1950. The letter also refers to the "zone description" of zero hours, which has been used since 1920 (see time zone history). Since the NATO phonetic alphabet and amateur radio word for Z is "Zulu", UTC is sometimes known as Zulu time. This is especially true in aviation, where Zulu is the universal standard.

Read entire file in Scala?

For faster overall reading / uploading a (large) file, consider increasing the size of bufferSize (Source.DefaultBufSize set to 2048), for instance as follows,

val file = new java.io.File("myFilename")
io.Source.fromFile(file, bufferSize = Source.DefaultBufSize * 2)

Note Source.scala. For further discussion see Scala fast text file read and upload to memory.

Disable Copy or Paste action for text box?

Here is the updated fiddle.

$(document).ready(function(){
    $('#confirmEmail').bind("cut copy paste",function(e) {
        e.preventDefault();
    });
});

This will prevent cut copy paste on Confirm Email text box.

Hope it helps.

javascript return true or return false when and how to use it?

I think a lot of times when you see this code, it's from people who are in the habit of event handlers for forms, buttons, inputs, and things of that sort.

Basically, when you have something like:

<form onsubmit="return callSomeFunction();"></form>

or

<a href="#" onclick="return callSomeFunction();"></a>`

and callSomeFunction() returns true, then the form or a will submit, otherwise it won't.

Other more obvious general purposes for returning true or false as a result of a function are because they are expected to return a boolean.

In Spring MVC, how can I set the mime type header when using @ResponseBody

I don't think you can, apart from response.setContentType(..)

Difference between parameter and argument

They are often used interchangeably in text, but in most standards the distinction is that an argument is an expression passed to a function, where a parameter is a reference declared in a function declaration.

Python interpreter error, x takes no arguments (1 given)

Python implicitly passes the object to method calls, but you need to explicitly declare the parameter for it. This is customarily named self:

def updateVelocity(self):

connect to host localhost port 22: Connection refused

you need to check the configuration in sshd_config ListenAddress 0.0.0.0 update this and restart the sshd service that will resolve the issue.

TypeError: expected string or buffer

readlines() will return a list of all the lines in the file, so lines is a list. You probably want something like this:

for line in f.readlines(): # Iterates through every line and looks for a match
#or
#for line in f:
    match = re.findall('[A-Z]+', line)
    print match

Or, if the file isn't too large you can grab it as as single string:

lines = f.read() # Warning: reads the FULL FILE into memory. This can be bad.
match = re.findall('[A-Z]+', lines)
print match

Prevent browser caching of AJAX call result

add header

headers: {
                'Cache-Control':'no-cache'
            }

Can the "IN" operator use LIKE-wildcards (%) in Oracle?

Not 100% what you were looking for, but kind of an inside-out way of doing it:

SQL> CREATE TABLE mytable (id NUMBER, status VARCHAR2(50));

Table created.

SQL> INSERT INTO mytable VALUES (1,'Finished except pouring water on witch');

1 row created.

SQL> INSERT INTO mytable VALUES (2,'Finished except clicking ruby-slipper heels');

1 row created.

SQL> INSERT INTO mytable VALUES (3,'You shall (not?) pass');

1 row created.

SQL> INSERT INTO mytable VALUES (4,'Done');

1 row created.

SQL> INSERT INTO mytable VALUES (5,'Done with it.');

1 row created.

SQL> INSERT INTO mytable VALUES (6,'In Progress');

1 row created.

SQL> INSERT INTO mytable VALUES (7,'In progress, OK?');

1 row created.

SQL> INSERT INTO mytable VALUES (8,'In Progress Check Back In Three Days'' Time');

1 row created.

SQL> SELECT *
  2  FROM   mytable m
  3  WHERE  +1 NOT IN (INSTR(m.status,'Done')
  4            ,       INSTR(m.status,'Finished except')
  5            ,       INSTR(m.status,'In Progress'));

        ID STATUS
---------- --------------------------------------------------
         3 You shall (not?) pass
         7 In progress, OK?

SQL>

How to check if an element is in an array

Swift

If you are not using object then you can user this code for contains.

let elements = [ 10, 20, 30, 40, 50]

if elements.contains(50) {

   print("true")

}

If you are using NSObject Class in swift. This variables is according to my requirement. you can modify for your requirement.

var cliectScreenList = [ATModelLeadInfo]()
var cliectScreenSelectedObject: ATModelLeadInfo!

This is for a same data type.

{ $0.user_id == cliectScreenSelectedObject.user_id }

If you want to AnyObject type.

{ "\($0.user_id)" == "\(cliectScreenSelectedObject.user_id)" }

Full condition

if cliectScreenSelected.contains( { $0.user_id == cliectScreenSelectedObject.user_id } ) == false {

    cliectScreenSelected.append(cliectScreenSelectedObject)

    print("Object Added")

} else {

    print("Object already exists")

 }

How do you delete an ActiveRecord object?

If you are using Rails 5 and above, the following solution will work.

#delete based on id
user_id = 50
User.find(id: user_id).delete_all

#delete based on condition
threshold_age = 20
User.where(age: threshold_age).delete_all

https://www.rubydoc.info/docs/rails/ActiveRecord%2FNullRelation:delete_all

moving committed (but not pushed) changes to a new branch after pull

Here is a much simpler way:

  1. Create a new branch

  2. On your new branch do a git merge master- this will merge your committed (not pushed) changes to your new branch

  3. Delete you local master branch git branch -D master Use -D instead of -d because you want to force delete the branch.

  4. Just do a git fetch on your master branch and do a git pull on your master branch to ensure you have your teams latest code.

Remove Blank option from Select Option with AngularJS

It is kind of a workaround but works like a charm. Just add <option value="" style="display: none"></option> as a filler. Like in:

<select size="4" ng-model="feed.config" ng-options="template.value as template.name for template in feed.configs">
       <option value="" style="display: none"></option>
</select>

How to Customize the time format for Python logging?

To add to the other answers, here are the variable list from Python Documentation.

Directive   Meaning Notes

%a  Locale’s abbreviated weekday name.   
%A  Locale’s full weekday name.  
%b  Locale’s abbreviated month name.     
%B  Locale’s full month name.    
%c  Locale’s appropriate date and time representation.   
%d  Day of the month as a decimal number [01,31].    
%H  Hour (24-hour clock) as a decimal number [00,23].    
%I  Hour (12-hour clock) as a decimal number [01,12].    
%j  Day of the year as a decimal number [001,366].   
%m  Month as a decimal number [01,12].   
%M  Minute as a decimal number [00,59].  
%p  Locale’s equivalent of either AM or PM. (1)
%S  Second as a decimal number [00,61]. (2)
%U  Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0.    (3)
%w  Weekday as a decimal number [0(Sunday),6].   
%W  Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0.    (3)
%x  Locale’s appropriate date representation.    
%X  Locale’s appropriate time representation.    
%y  Year without century as a decimal number [00,99].    
%Y  Year with century as a decimal number.   
%z  Time zone offset indicating a positive or negative time difference from UTC/GMT of the form +HHMM or -HHMM, where H represents decimal hour digits and M represents decimal minute digits [-23:59, +23:59].  
%Z  Time zone name (no characters if no time zone exists).   
%%  A literal '%' character.     

what is the unsigned datatype?

According to C17 6.7.2 §2:

Each list of type specifiers shall be one of the following multisets (delimited by commas, when there is more than one multiset per item); the type specifiers may occur in any order, possibly intermixed with the other declaration specifiers

— void
— char
— signed char
— unsigned char
— short, signed short, short int, or signed short int
— unsigned short, or unsigned short int
— int, signed, or signed int
— unsigned, or unsigned int
— long, signed long, long int, or signed long int
— unsigned long, or unsigned long int
— long long, signed long long, long long int, or signed long long int
— unsigned long long, or unsigned long long int
— float
— double
— long double
— _Bool
— float _Complex
— double _Complex
— long double _Complex
— atomic type specifier
— struct or union specifier
— enum specifier
— typedef name

So in case of unsigned int we can either write unsigned or unsigned int, or if we are feeling crazy, int unsigned. The latter since the standard is stupid enough to allow "...may occur in any order, possibly intermixed". This is a known flaw of the language.

Proper C code uses unsigned int.

Need help rounding to 2 decimal places

It is caused by a lack of precision with doubles / decimals (i.e. - the function will not always give the result you expect).

See the following link: MSDN on Math.Round

Here is the relevant quote:

Because of the loss of precision that can result from representing decimal values as floating-point numbers or performing arithmetic operations on floating-point values, in some cases the Round(Double, Int32, MidpointRounding) method may not appear to round midpoint values as specified by the mode parameter.This is illustrated in the following example, where 2.135 is rounded to 2.13 instead of 2.14.This occurs because internally the method multiplies value by 10digits, and the multiplication operation in this case suffers from a loss of precision.

How do I run a VBScript in 32-bit mode on a 64-bit machine?

If you have control over running the cscript executable then run the X:\windows\syswow64\cscript.exe version which is the 32bit implementation.

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

Amazon EC2 cannot offer Mac OS X EC2 instances due to Apple's tight licensing to only allow it to legally run on Apple hardware and the current EC2 infrastructure relies upon virtualized hardware.

Apple Mac image on Amazon EC2?

Can you run OS X on an Amazon EC2 instance?

There are other companies that do provide Mac OS X hosting, presumably on Apple hardware. One example is Go Daddy:

Go Daddy Product Catalog (see Mac® Powered Cloud Servers under Web Hosting)

To find more, search for "Mac OS X hosting" and you'll find more options.

Embed ruby within URL : Middleman Blog

<%= link_to "http://www.facebook.com/sharer.php?u=" + article_url(article, :text => article.title), :class => "btn btn-primary" do %>   <i class="fa fa-facebook">     Facebook Share    </i> <%end%> 

I am assuming that current_article_url is http://0.0.0.0:4567/link_to_title

What is the difference between sscanf or atoi to convert a string to an integer?

To @R.. I think it's not enough to check errno for error detection in strtol call.

long strtol (const char *String, char **EndPointer, int Base)

You'll also need to check EndPointer for errors.

How do I detect if Python is running as a 64-bit application?

While it may work on some platforms, be aware that platform.architecture is not always a reliable way to determine whether python is running in 32-bit or 64-bit. In particular, on some OS X multi-architecture builds, the same executable file may be capable of running in either mode, as the example below demonstrates. The quickest safe multi-platform approach is to test sys.maxsize on Python 2.6, 2.7, Python 3.x.

$ arch -i386 /usr/local/bin/python2.7
Python 2.7.9 (v2.7.9:648dcafa7e5f, Dec 10 2014, 10:10:46)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import platform, sys
>>> platform.architecture(), sys.maxsize
(('64bit', ''), 2147483647)
>>> ^D
$ arch -x86_64 /usr/local/bin/python2.7
Python 2.7.9 (v2.7.9:648dcafa7e5f, Dec 10 2014, 10:10:46)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import platform, sys
>>> platform.architecture(), sys.maxsize
(('64bit', ''), 9223372036854775807)

See changes to a specific file using git

You can execute

git status -s

This will show modified files name and then by copying the interested file path you can see changes using git diff

git diff <filepath + filename>

How to call a REST web service API from JavaScript?

    $("button").on("click",function(){
      //console.log("hii");
      $.ajax({
        headers:{  
           "key":"your key",
     "Accept":"application/json",//depends on your api
      "Content-type":"application/x-www-form-urlencoded"//depends on your api
        },   url:"url you need",
        success:function(response){
          var r=JSON.parse(response);
          $("#main").html(r.base);
        }
      });
});

How can I know if a process is running?

Synchronous solution :

void DisplayProcessStatus(Process process)
{
    process.Refresh();  // Important


    if(process.HasExited)
    {
        Console.WriteLine("Exited.");
    }
    else
    {
        Console.WriteLine("Running.");
    } 
}

Asynchronous solution:

void RegisterProcessExit(Process process)
{
    // NOTE there will be a race condition with the caller here
    //   how to fix it is left as an exercise
    process.Exited += process_Exited;
}

static void process_Exited(object sender, EventArgs e)
{
   Console.WriteLine("Process has exited.");
}

IIS7 Cache-Control

there is a easy way: 1. using website's web.config 2. in "staticContent" section remove specific fileExtension and add mimeMap 3. add "clientCache"

<configuration>
  <system.webServer>
    <urlCompression doStaticCompression="true" doDynamicCompression="true" />
    <staticContent>
      <remove fileExtension=".ipa" />
      <remove fileExtension=".apk" />
      <mimeMap fileExtension=".ipa" mimeType="application/iphone" />
      <mimeMap fileExtension=".apk" mimeType="application/vnd.android.package-archive" />
      <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="777.00:00:00" />
    </staticContent>
  </system.webServer>
</configuration>

How to put an image next to each other

Check this out. Just use float and get rid of relative.

http://jsfiddle.net/JhpRk/

#icons{float:left;}

Order by descending date - month, day and year

You have the field in a string, so you'll need to convert it to datetime

order by CONVERT(datetime, EventDate ) desc

How do I run Google Chrome as root?

Just replace following line

exec -a "$0" "$HERE/chrome" "$@"

with

exec -a "$0" "$HERE/chrome" "$@" --user-data-dir 

all things will be right.

ReDim Preserve to a Multi-Dimensional Array in Visual Basic 6

If you not want include other function like 'ReDimPreserve' could use temporal matrix for resizing. On based to your code:

 Dim n As Integer, m As Integer, i as Long, j as Long
 Dim arrTemporal() as Variant

    n = 1
    m = 0
    Dim arrCity() As String
    ReDim arrCity(n, m)

    n = n + 1
    m = m + 1

    'VBA automatically adapts the size of the receiving matrix.
    arrTemporal = arrCity
    ReDim arrCity(n, m)

    'Loop for assign values to arrCity
    For i = 1 To UBound(arrTemporal , 1)
        For j = 1 To UBound(arrTemporal , 2)
            arrCity(i, j) = arrTemporal (i, j)
        Next
    Next

If you not declare of type VBA assume that is Variant.

Dim n as Integer, m As Integer

Find all files with name containing string

Use grep as follows:

grep -R "touch" .

-R means recurse. If you would rather not go into the subdirectories, then skip it.

-i means "ignore case". You might find this worth a try as well.

How can I use a JavaScript variable as a PHP variable?

I had the same problem a few weeks ago like yours; but I invented a brilliant solution for exchanging variables between PHP and JavaScript. It worked for me well:

  1. Create a hidden form on a HTML page

  2. Create a Textbox or Textarea in that hidden form

  3. After all of your code written in the script, store the final value of your variable in that textbox

  4. Use $_REQUEST['textbox name'] line in your PHP to gain access to value of your JavaScript variable.

I hope this trick works for you.

Docker "ERROR: could not find an available, non-overlapping IPv4 address pool among the defaults to assign to the network"

I fixed this issue by steps :

  1. turn off your network (wireless or wired...).

  2. reboot your system.

  3. before turning on your network on PC, execute command docker-compose up, it's going to create new network.

  4. then you can turn network on and go on ...

How to securely save username/password (local)?

I have used this before and I think in order to make sure credential persist and in a best secure way is

  1. you can write them to the app config file using the ConfigurationManager class
  2. securing the password using the SecureString class
  3. then encrypting it using tools in the Cryptography namespace.

This link will be of great help I hope : Click here

jquery remove "selected" attribute of option?

It's something in the way jQuery translates to IE8, not necessarily the browser itself.

I was able to work around by going old school and breaking out of jQuery for one line:

document.getElementById('myselect').selectedIndex = -1;

How to fix committing to the wrong Git branch?

If you haven't yet pushed your changes, you can also do a soft reset:

git reset --soft HEAD^

This will revert the commit, but put the committed changes back into your index. Assuming the branches are relatively up-to-date with regard to each other, git will let you do a checkout into the other branch, whereupon you can simply commit:

git checkout branch
git commit

The disadvantage is that you need to re-enter your commit message.

How do you add an image?

Shouldn't that be:

<xsl:value-of select="/root/Image/img/@src"/>

? It looks like you are trying to copy the entire Image/img node to the attribute @src

'Must Override a Superclass Method' Errors after importing a project into Eclipse

In my case this problem happened when I imported a Maven project into Eclipse. To solve this, I added the following in pom.xml:

<properties>
   ...
   <maven.compiler.source>1.8</maven.compiler.source>
   <maven.compiler.target>1.8</maven.compiler.target>
</properties>

Then in the context menu of the project, go to "Maven -> Update Project ...", and press OK.

That's it. Hope this helps.

Get timezone from users browser using moment(timezone).js

Using Moment library, see their website -> https://momentjs.com/timezone/docs/#/using-timezones/converting-to-zone/

i notice they also user their own library in their website, so you can have a try using the browser console before installing it

moment().tz(String);

The moment#tz mutator will change the time zone and update the offset.

moment("2013-11-18").tz("America/Toronto").format('Z'); // -05:00
moment("2013-11-18").tz("Europe/Berlin").format('Z');   // +01:00

This information is used consistently in other operations, like calculating the start of the day.

var m = moment.tz("2013-11-18 11:55", "America/Toronto");
m.format();                     // 2013-11-18T11:55:00-05:00
m.startOf("day").format();      // 2013-11-18T00:00:00-05:00
m.tz("Europe/Berlin").format(); // 2013-11-18T06:00:00+01:00
m.startOf("day").format();      // 2013-11-18T00:00:00+01:00

Without an argument, moment#tz returns:

    the time zone name assigned to the moment instance or
    undefined if a time zone has not been set.

var m = moment.tz("2013-11-18 11:55", "America/Toronto");
m.tz();  // America/Toronto
var m = moment.tz("2013-11-18 11:55");
m.tz() === undefined;  // true

How To Upload Files on GitHub

If you want to upload a folder or a file to Github

1- Create a repository on the Github

2- make: git remote add origin "Your Link" as it is described on the Github

3- Then use git push -u origin master.

4- You have to enter your username and Password.

5- After the authentication, the transfer will start

Auto reloading python Flask app upon code changes

The current recommended way is with the flask command line utility.

https://flask.palletsprojects.com/en/1.1.x/quickstart/#debug-mode

Example:

$ export FLASK_APP=main.py
$ export FLASK_ENV=development
$ flask run

or in one command:

$ FLASK_APP=main.py FLASK_ENV=development flask run

If you want different port than the default (5000) add --port option.

Example:

$ FLASK_APP=main.py FLASK_ENV=development flask run --port 8080

More options are available with:

$ flask run --help

FLASK_APP can also be set to module:app or module:create_app instead of module.py. See https://flask.palletsprojects.com/en/1.1.x/cli/#application-discovery for a full explanation.

How to create localhost database using mysql?

See here for starting the service and here for how to make it permanent. In short to test it, open a "DOS" terminal with administrator privileges and write:

shell> "C:\Program Files\MySQL\[YOUR MYSQL VERSION PATH]\bin\mysqld"

How Does Modulus Divison Work

Write out a table starting with 0.

{0,1,2,3,4}

Continue the table in rows.

{0,1,2,3,4}
{5,6,7,8,9}
{10,11,12,13,14}

Everything in column one is a multiple of 5. Everything in column 2 is a multiple of 5 with 1 as a remainder. Now the abstract part: You can write that (1) as 1/5 or as a decimal expansion. The modulus operator returns only the column, or in another way of thinking, it returns the remainder on long division. You are dealing in modulo(5). Different modulus, different table. Think of a Hash Table.

Python not working in the command line of git bash

2 workarounds, rather than a solution: In my Git Bash, following command hangs and I don't get the prompt back:

% python

So I just use:

% winpty python

As some people have noted above, you can also use:

% python -i

2020-07-14: Git 2.27.0 has added optional experimental support for pseudo consoles, which allow running Python from the command line: enter image description here

See attached session.enter image description here

Enable/disable buttons with Angular

    <div class="col-md-12">
      <p style="color: #28a745; font-weight: bold; font-size:25px; text-align: right " >Total Productos a pagar= {{ getTotal() }} {{ getResult() | currency }}
      <button class="btn btn-success" type="submit" [disabled]="!getResult()" (click)="onSubmit()">
        Ver Pedido
      </button>
     </p>
    </div>

Capturing console output from a .NET application (C#)

ConsoleAppLauncher is an open source library made specifically to answer that question. It captures all the output generated in the console and provides simple interface to start and close console application.

The ConsoleOutput event is fired every time when a new line is written by the console to standard/error output. The lines are queued and guaranteed to follow the output order.

Also available as NuGet package.

Sample call to get full console output:

// Run simplest shell command and return its output.
public static string GetWindowsVersion()
{
    return ConsoleApp.Run("cmd", "/c ver").Output.Trim();
}

Sample with live feedback:

// Run ping.exe asynchronously and return roundtrip times back to the caller in a callback
public static void PingUrl(string url, Action<string> replyHandler)
{
    var regex = new Regex("(time=|Average = )(?<time>.*?ms)", RegexOptions.Compiled);
    var app = new ConsoleApp("ping", url);
    app.ConsoleOutput += (o, args) =>
    {
        var match = regex.Match(args.Line);
        if (match.Success)
        {
            var roundtripTime = match.Groups["time"].Value;
            replyHandler(roundtripTime);
        }
    };
    app.Run();
}

MAMP mysql server won't start. No mysql processes are running

Since none of the answers here solved my particular issue, I should probably add my own solution to to the list.

I had to hard reset my computer while MAMP was still running. This sometimes leads to a problem where, after restarting the machine MAMP can start the Apache Server, but can not start the MySQL server for some reason.

My solution for this issue was to:

  • Close MAMP
  • Go to Applications/MAMP/tmp/mysql
  • delete the file mysql.sock.lock
  • Restart MAMP

Update query using Subquery in Sql Server

Here is a nice explanation of update operation with some examples. Although it is Postgres site, but the SQL queries are valid for the other DBs, too. The following examples are intuitive to understand.

-- Update contact names in an accounts table to match the currently assigned salesmen:

UPDATE accounts SET (contact_first_name, contact_last_name) =
    (SELECT first_name, last_name FROM salesmen
     WHERE salesmen.id = accounts.sales_id);

-- A similar result could be accomplished with a join:

UPDATE accounts SET contact_first_name = first_name,
                    contact_last_name = last_name
  FROM salesmen WHERE salesmen.id = accounts.sales_id;

However, the second query may give unexpected results if salesmen.id is not a unique key, whereas the first query is guaranteed to raise an error if there are multiple id matches. Also, if there is no match for a particular accounts.sales_id entry, the first query will set the corresponding name fields to NULL, whereas the second query will not update that row at all.

Hence for the given example, the most reliable query is like the following.

UPDATE tempDataView SET (marks) =
    (SELECT marks FROM tempData
     WHERE tempDataView.Name = tempData.Name);

DB query builder toArray() laravel 4

Please note, the option presented below is apparently no longer supported as of Laravel 5.4 (thanks @Alex).

In Laravel 5.3 and below, there is a method to set the fetch mode for select queries.

In this case, it might be more efficient to do:

DB::connection()->setFetchMode(PDO::FETCH_ASSOC);
$result = DB::table('user')->where('name',=,'Jhon')->get();

That way, you won't waste time creating objects and then converting them back into arrays.

When & why to use delegates?

I've just go my head around these, and so I'll share an example as you already have descriptions but at the moment one advantage I see is to get around the Circular Reference style warnings where you can't have 2 projects referencing each other.

Let's assume an application downloads an XML, and then saves the XML to a database.

I have 2 projects here which build my solution: FTP and a SaveDatabase.

So, our application starts by looking for any downloads and downloading the file(s) then it calls the SaveDatabase project.

Now, our application needs to notify the FTP site when a file is saved to the database by uploading a file with Meta data (ignore why, it's a request from the owner of the FTP site). The issue is at what point and how? We need a new method called NotifyFtpComplete() but in which of our projects should it be saved too - FTP or SaveDatabase? Logically, the code should live in our FTP project. But, this would mean our NotifyFtpComplete will have to be triggered or, it will have to wait until the save is complete, and then query the database to ensure it is in there. What we need to do is tell our SaveDatabase project to call the NotifyFtpComplete() method direct but we can't; we'd get a ciruclar reference and the NotifyFtpComplete() is a private method. What a shame, this would have worked. Well, it can.

During our application's code, we would have passed parameters between methods, but what if one of those parameters was the NotifyFtpComplete method. Yup, we pass the method, with all of the code inside as well. This would mean we could execute the method at any point, from any project. Well, this is what the delegate is. This means, we can pass the NotifyFtpComplete() method as a parameter to our SaveDatabase() class. At the point it saves, it simply executes the delegate.

See if this crude example helps (pseudo code). We will also assume that the application starts with the Begin() method of the FTP class.

class FTP
{
    public void Begin()
    {
        string filePath = DownloadFileFromFtpAndReturnPathName();

        SaveDatabase sd = new SaveDatabase();
        sd.Begin(filePath, NotifyFtpComplete());
    }

    private void NotifyFtpComplete()
    {
        //Code to send file to FTP site
    }
}


class SaveDatabase
{
    private void Begin(string filePath, delegateType NotifyJobComplete())
    {
        SaveToTheDatabase(filePath);

        /* InvokeTheDelegate - 
         * here we can execute the NotifyJobComplete
         * method at our preferred moment in the application,
         * despite the method being private and belonging
         * to a different class.
         */
        NotifyJobComplete.Invoke();
    }
}

So, with that explained, we can do it for real now with this Console Application using C#

using System;

namespace ConsoleApplication1
{
    /* I've made this class private to demonstrate that 
    * the SaveToDatabase cannot have any knowledge of this Program class.
    */
    class Program
    {
        static void Main(string[] args)
        {
            //Note, this NotifyDelegate type is defined in the SaveToDatabase project
            NotifyDelegate nofityDelegate = new NotifyDelegate(NotifyIfComplete);

            SaveToDatabase sd = new SaveToDatabase();            
            sd.Start(nofityDelegate);
            Console.ReadKey();
        }

        /* this is the method which will be delegated -
         * the only thing it has in common with the NofityDelegate
         * is that it takes 0 parameters and that it returns void.
         * However, it is these 2 which are essential.
         * It is really important to notice that it writes
         * a variable which, due to no constructor,
         * has not yet been called (so _notice is not initialized yet).
         */ 
    private static void NotifyIfComplete()
    {
        Console.WriteLine(_notice);
    }

    private static string _notice = "Notified";
    }


    public class SaveToDatabase
    {
        public void Start(NotifyDelegate nd)
        {
            /* I shouldn't write to the console from here, 
             * just for demonstration purposes
             */
            Console.WriteLine("SaveToDatabase Complete");
            Console.WriteLine(" ");
            nd.Invoke();
        }
    }
    public delegate void NotifyDelegate();
}

I suggest you step through the code and see when _notice is called and when the method (delegate) is called as this, I hope, will make things very clear.

However, lastly, we can make it more useful by changing the delegate type to include a parameter.

using System.Text;

namespace ConsoleApplication1
{
    /* I've made this class private to demonstrate that the SaveToDatabase
     * cannot have any knowledge of this Program class.
     */
    class Program
    {
        static void Main(string[] args)
        {
            SaveToDatabase sd = new SaveToDatabase();
            /* Please note, that although NotifyIfComplete()
         * takes a string parameter, we do not declare it,
         * all we want to do is tell C# where the method is
         * so it can be referenced later,
         * we will pass the parameter later.
         */
            var notifyDelegateWithMessage = new NotifyDelegateWithMessage(NotifyIfComplete);

            sd.Start(notifyDelegateWithMessage );

            Console.ReadKey();
        }

        private static void NotifyIfComplete(string message)
        {
            Console.WriteLine(message);
        }
    }


    public class SaveToDatabase
    {
        public void Start(NotifyDelegateWithMessage nd)
        {
                        /* To simulate a saving fail or success, I'm just going
         * to check the current time (well, the seconds) and
         * store the value as variable.
         */
            string message = string.Empty;
            if (DateTime.Now.Second > 30)
                message = "Saved";
            else
                message = "Failed";

            //It is at this point we pass the parameter to our method.
            nd.Invoke(message);
        }
    }

    public delegate void NotifyDelegateWithMessage(string message);
}

403 Forbidden vs 401 Unauthorized HTTP responses

In English:

401

You are potentially allowed access but for some reason on this request you were denied. Such as a bad password? Try again, with the correct request you will get a success response instead.

403

You are not, ever, allowed. Your name is not on the list, you won't ever get in, go away, don't send a re-try request, it will be refused, always. Go away.

How to pass credentials to httpwebrequest for accessing SharePoint Library

If you need to run request as the current user from desktop application use CredentialCache.DefaultCredentials (see on MSDN).

Your code looks fine if you need to run a request from server side code or under a different user.

Please note that you should be careful when storing passwords - consider using the SecureString version of the constructor.

DOS: find a string, if found then run another script

As the answer is marked correct then it's a Windows Dos prompt script and this will work too:

find "string" status.txt >nul && call "my batch file.bat"

What is a callback in java

A callback is commonly used in asynchronous programming, so you could create a method which handles the response from a web service. When you call the web service, you could pass the method to it so that when the web service responds, it call's the method you told it ... it "calls back".

In Java this can commonly be done through implementing an interface and passing an object (or an anonymous inner class) that implements it. You find this often with transactions and threading - such as the Futures API.

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/Future.html

Local storage in Angular 2

To store in LocalStorage :

window.localStorage.setItem(key, data);

To remove an item from LocalStorage :

window.localStorage.removeItem(key);

To get an item from LocalStorage :

window.localStorage.getItem(key);

You can only store a string in LocalStorage; if you have an object, first you have to convert it to string like the following:

window.localStorage.setItem(key, JSON.stringify(obj));

And when you want to get an object from LocalStorage :

const result=JSON.parse(window.localStorage.getItem(key));

All Tips above are the same for SessionStorage.

You can use the following service to work on SessionStorage and LocalStorage. All methods in the service :

getSession(key: string): any
setSession(key: string, value: any): void
removeSession(key: string): void
removeAllSessions(): void
getLocal(key: string): any
setLocal(key: string, value: any): void
removeLocal(key: string): void 
removeAllLocals(): void

Inject this service in your components, services and ...; Do not forget to register the service in your core module.

import { Injectable } from '@angular/core';

@Injectable()
export class BrowserStorageService {

  getSession(key: string): any {
    const data = window.sessionStorage.getItem(key);
    if (data) {
      return JSON.parse(data);
    } else {
      return null;
    }
  }

  setSession(key: string, value: any): void {
    const data = value === undefined ? '' : JSON.stringify(value);
    window.sessionStorage.setItem(key, data);
  }

  removeSession(key: string): void {
    window.sessionStorage.removeItem(key);
  }

  removeAllSessions(): void {
    for (const key in window.sessionStorage) {
      if (window.sessionStorage.hasOwnProperty(key)) {
        this.removeSession(key);
      }
    }
  }

  getLocal(key: string): any {
    const data = window.localStorage.getItem(key);
    if (data) {
      return JSON.parse(data);
    } else {
      return null;
    }
  }

  setLocal(key: string, value: any): void {
    const data = value === undefined ? '' : JSON.stringify(value);
    window.localStorage.setItem(key, data);
  }

  removeLocal(key: string): void {
    window.localStorage.removeItem(key);
  }

  removeAllLocals(): void {
    for (const key in window.localStorage) {
      if (window.localStorage.hasOwnProperty(key)) {
        this.removeLocal(key);
      }
    }
  }
}

C++ equivalent of java's instanceof

Instanceof implementation without dynamic_cast

I think this question is still relevant today. Using the C++11 standard you are now able to implement a instanceof function without using dynamic_cast like this:

if (dynamic_cast<B*>(aPtr) != nullptr) {
  // aPtr is instance of B
} else {
  // aPtr is NOT instance of B
}

But you're still reliant on RTTI support. So here is my solution for this problem depending on some Macros and Metaprogramming Magic. The only drawback imho is that this approach does not work for multiple inheritance.

InstanceOfMacros.h

#include <set>
#include <tuple>
#include <typeindex>

#define _EMPTY_BASE_TYPE_DECL() using BaseTypes = std::tuple<>;
#define _BASE_TYPE_DECL(Class, BaseClass) \
  using BaseTypes = decltype(std::tuple_cat(std::tuple<BaseClass>(), Class::BaseTypes()));
#define _INSTANCE_OF_DECL_BODY(Class)                                 \
  static const std::set<std::type_index> baseTypeContainer;           \
  virtual bool instanceOfHelper(const std::type_index &_tidx) {       \
    if (std::type_index(typeid(ThisType)) == _tidx) return true;      \
    if (std::tuple_size<BaseTypes>::value == 0) return false;         \
    return baseTypeContainer.find(_tidx) != baseTypeContainer.end();  \
  }                                                                   \
  template <typename... T>                                            \
  static std::set<std::type_index> getTypeIndexes(std::tuple<T...>) { \
    return std::set<std::type_index>{std::type_index(typeid(T))...};  \
  }

#define INSTANCE_OF_SUB_DECL(Class, BaseClass) \
 protected:                                    \
  using ThisType = Class;                      \
  _BASE_TYPE_DECL(Class, BaseClass)            \
  _INSTANCE_OF_DECL_BODY(Class)

#define INSTANCE_OF_BASE_DECL(Class)                                                    \
 protected:                                                                             \
  using ThisType = Class;                                                               \
  _EMPTY_BASE_TYPE_DECL()                                                               \
  _INSTANCE_OF_DECL_BODY(Class)                                                         \
 public:                                                                                \
  template <typename Of>                                                                \
  typename std::enable_if<std::is_base_of<Class, Of>::value, bool>::type instanceOf() { \
    return instanceOfHelper(std::type_index(typeid(Of)));                               \
  }

#define INSTANCE_OF_IMPL(Class) \
  const std::set<std::type_index> Class::baseTypeContainer = Class::getTypeIndexes(Class::BaseTypes());

Demo

You can then use this stuff (with caution) as follows:

DemoClassHierarchy.hpp*

#include "InstanceOfMacros.h"

struct A {
  virtual ~A() {}
  INSTANCE_OF_BASE_DECL(A)
};
INSTANCE_OF_IMPL(A)

struct B : public A {
  virtual ~B() {}
  INSTANCE_OF_SUB_DECL(B, A)
};
INSTANCE_OF_IMPL(B)

struct C : public A {
  virtual ~C() {}
  INSTANCE_OF_SUB_DECL(C, A)
};
INSTANCE_OF_IMPL(C)

struct D : public C {
  virtual ~D() {}
  INSTANCE_OF_SUB_DECL(D, C)
};
INSTANCE_OF_IMPL(D)

The following code presents a small demo to verify rudimentary the correct behavior.

InstanceOfDemo.cpp

#include <iostream>
#include <memory>
#include "DemoClassHierarchy.hpp"

int main() {
  A *a2aPtr = new A;
  A *a2bPtr = new B;
  std::shared_ptr<A> a2cPtr(new C);
  C *c2dPtr = new D;
  std::unique_ptr<A> a2dPtr(new D);

  std::cout << "a2aPtr->instanceOf<A>(): expected=1, value=" << a2aPtr->instanceOf<A>() << std::endl;
  std::cout << "a2aPtr->instanceOf<B>(): expected=0, value=" << a2aPtr->instanceOf<B>() << std::endl;
  std::cout << "a2aPtr->instanceOf<C>(): expected=0, value=" << a2aPtr->instanceOf<C>() << std::endl;
  std::cout << "a2aPtr->instanceOf<D>(): expected=0, value=" << a2aPtr->instanceOf<D>() << std::endl;
  std::cout << std::endl;
  std::cout << "a2bPtr->instanceOf<A>(): expected=1, value=" << a2bPtr->instanceOf<A>() << std::endl;
  std::cout << "a2bPtr->instanceOf<B>(): expected=1, value=" << a2bPtr->instanceOf<B>() << std::endl;
  std::cout << "a2bPtr->instanceOf<C>(): expected=0, value=" << a2bPtr->instanceOf<C>() << std::endl;
  std::cout << "a2bPtr->instanceOf<D>(): expected=0, value=" << a2bPtr->instanceOf<D>() << std::endl;
  std::cout << std::endl;
  std::cout << "a2cPtr->instanceOf<A>(): expected=1, value=" << a2cPtr->instanceOf<A>() << std::endl;
  std::cout << "a2cPtr->instanceOf<B>(): expected=0, value=" << a2cPtr->instanceOf<B>() << std::endl;
  std::cout << "a2cPtr->instanceOf<C>(): expected=1, value=" << a2cPtr->instanceOf<C>() << std::endl;
  std::cout << "a2cPtr->instanceOf<D>(): expected=0, value=" << a2cPtr->instanceOf<D>() << std::endl;
  std::cout << std::endl;
  std::cout << "c2dPtr->instanceOf<A>(): expected=1, value=" << c2dPtr->instanceOf<A>() << std::endl;
  std::cout << "c2dPtr->instanceOf<B>(): expected=0, value=" << c2dPtr->instanceOf<B>() << std::endl;
  std::cout << "c2dPtr->instanceOf<C>(): expected=1, value=" << c2dPtr->instanceOf<C>() << std::endl;
  std::cout << "c2dPtr->instanceOf<D>(): expected=1, value=" << c2dPtr->instanceOf<D>() << std::endl;
  std::cout << std::endl;
  std::cout << "a2dPtr->instanceOf<A>(): expected=1, value=" << a2dPtr->instanceOf<A>() << std::endl;
  std::cout << "a2dPtr->instanceOf<B>(): expected=0, value=" << a2dPtr->instanceOf<B>() << std::endl;
  std::cout << "a2dPtr->instanceOf<C>(): expected=1, value=" << a2dPtr->instanceOf<C>() << std::endl;
  std::cout << "a2dPtr->instanceOf<D>(): expected=1, value=" << a2dPtr->instanceOf<D>() << std::endl;

  delete a2aPtr;
  delete a2bPtr;
  delete c2dPtr;

  return 0;
}

Output:

a2aPtr->instanceOf<A>(): expected=1, value=1
a2aPtr->instanceOf<B>(): expected=0, value=0
a2aPtr->instanceOf<C>(): expected=0, value=0
a2aPtr->instanceOf<D>(): expected=0, value=0

a2bPtr->instanceOf<A>(): expected=1, value=1
a2bPtr->instanceOf<B>(): expected=1, value=1
a2bPtr->instanceOf<C>(): expected=0, value=0
a2bPtr->instanceOf<D>(): expected=0, value=0

a2cPtr->instanceOf<A>(): expected=1, value=1
a2cPtr->instanceOf<B>(): expected=0, value=0
a2cPtr->instanceOf<C>(): expected=1, value=1
a2cPtr->instanceOf<D>(): expected=0, value=0

c2dPtr->instanceOf<A>(): expected=1, value=1
c2dPtr->instanceOf<B>(): expected=0, value=0
c2dPtr->instanceOf<C>(): expected=1, value=1
c2dPtr->instanceOf<D>(): expected=1, value=1

a2dPtr->instanceOf<A>(): expected=1, value=1
a2dPtr->instanceOf<B>(): expected=0, value=0
a2dPtr->instanceOf<C>(): expected=1, value=1
a2dPtr->instanceOf<D>(): expected=1, value=1

Performance

The most interesting question which now arises is, if this evil stuff is more efficient than the usage of dynamic_cast. Therefore I've written a very basic performance measurement app.

InstanceOfPerformance.cpp

#include <chrono>
#include <iostream>
#include <string>
#include "DemoClassHierarchy.hpp"

template <typename Base, typename Derived, typename Duration>
Duration instanceOfMeasurement(unsigned _loopCycles) {
  auto start = std::chrono::high_resolution_clock::now();
  volatile bool isInstanceOf = false;
  for (unsigned i = 0; i < _loopCycles; ++i) {
    Base *ptr = new Derived;
    isInstanceOf = ptr->template instanceOf<Derived>();
    delete ptr;
  }
  auto end = std::chrono::high_resolution_clock::now();
  return std::chrono::duration_cast<Duration>(end - start);
}

template <typename Base, typename Derived, typename Duration>
Duration dynamicCastMeasurement(unsigned _loopCycles) {
  auto start = std::chrono::high_resolution_clock::now();
  volatile bool isInstanceOf = false;
  for (unsigned i = 0; i < _loopCycles; ++i) {
    Base *ptr = new Derived;
    isInstanceOf = dynamic_cast<Derived *>(ptr) != nullptr;
    delete ptr;
  }
  auto end = std::chrono::high_resolution_clock::now();
  return std::chrono::duration_cast<Duration>(end - start);
}

int main() {
  unsigned testCycles = 10000000;
  std::string unit = " us";
  using DType = std::chrono::microseconds;

  std::cout << "InstanceOf performance(A->D)  : " << instanceOfMeasurement<A, D, DType>(testCycles).count() << unit
            << std::endl;
  std::cout << "InstanceOf performance(A->C)  : " << instanceOfMeasurement<A, C, DType>(testCycles).count() << unit
            << std::endl;
  std::cout << "InstanceOf performance(A->B)  : " << instanceOfMeasurement<A, B, DType>(testCycles).count() << unit
            << std::endl;
  std::cout << "InstanceOf performance(A->A)  : " << instanceOfMeasurement<A, A, DType>(testCycles).count() << unit
            << "\n"
            << std::endl;
  std::cout << "DynamicCast performance(A->D) : " << dynamicCastMeasurement<A, D, DType>(testCycles).count() << unit
            << std::endl;
  std::cout << "DynamicCast performance(A->C) : " << dynamicCastMeasurement<A, C, DType>(testCycles).count() << unit
            << std::endl;
  std::cout << "DynamicCast performance(A->B) : " << dynamicCastMeasurement<A, B, DType>(testCycles).count() << unit
            << std::endl;
  std::cout << "DynamicCast performance(A->A) : " << dynamicCastMeasurement<A, A, DType>(testCycles).count() << unit
            << "\n"
            << std::endl;
  return 0;
}

The results vary and are essentially based on the degree of compiler optimization. Compiling the performance measurement program using g++ -std=c++11 -O0 -o instanceof-performance InstanceOfPerformance.cpp the output on my local machine was:

InstanceOf performance(A->D)  : 699638 us
InstanceOf performance(A->C)  : 642157 us
InstanceOf performance(A->B)  : 671399 us
InstanceOf performance(A->A)  : 626193 us

DynamicCast performance(A->D) : 754937 us
DynamicCast performance(A->C) : 706766 us
DynamicCast performance(A->B) : 751353 us
DynamicCast performance(A->A) : 676853 us

Mhm, this result was very sobering, because the timings demonstrates that the new approach is not much faster compared to the dynamic_cast approach. It is even less efficient for the special test case which tests if a pointer of A is an instance ofA. BUT the tide turns by tuning our binary using compiler otpimization. The respective compiler command is g++ -std=c++11 -O3 -o instanceof-performance InstanceOfPerformance.cpp. The result on my local machine was amazing:

InstanceOf performance(A->D)  : 3035 us
InstanceOf performance(A->C)  : 5030 us
InstanceOf performance(A->B)  : 5250 us
InstanceOf performance(A->A)  : 3021 us

DynamicCast performance(A->D) : 666903 us
DynamicCast performance(A->C) : 698567 us
DynamicCast performance(A->B) : 727368 us
DynamicCast performance(A->A) : 3098 us

If you are not reliant on multiple inheritance, are no opponent of good old C macros, RTTI and template metaprogramming and are not too lazy to add some small instructions to the classes of your class hierarchy, then this approach can boost your application a little bit with respect to its performance, if you often end up with checking the instance of a pointer. But use it with caution. There is no warranty for the correctness of this approach.

Note: All demos were compiled using clang (Apple LLVM version 9.0.0 (clang-900.0.39.2)) under macOS Sierra on a MacBook Pro Mid 2012.

Edit: I've also tested the performance on a Linux machine using gcc (Ubuntu 5.4.0-6ubuntu1~16.04.9) 5.4.0 20160609. On this platform the perfomance benefit was not so significant as on macOs with clang.

Output (without compiler optimization):

InstanceOf performance(A->D)  : 390768 us
InstanceOf performance(A->C)  : 333994 us
InstanceOf performance(A->B)  : 334596 us
InstanceOf performance(A->A)  : 300959 us

DynamicCast performance(A->D) : 331942 us
DynamicCast performance(A->C) : 303715 us
DynamicCast performance(A->B) : 400262 us
DynamicCast performance(A->A) : 324942 us

Output (with compiler optimization):

InstanceOf performance(A->D)  : 209501 us
InstanceOf performance(A->C)  : 208727 us
InstanceOf performance(A->B)  : 207815 us
InstanceOf performance(A->A)  : 197953 us

DynamicCast performance(A->D) : 259417 us
DynamicCast performance(A->C) : 256203 us
DynamicCast performance(A->B) : 261202 us
DynamicCast performance(A->A) : 193535 us

Maven: Failed to retrieve plugin descriptor error

I was having exactly the same problem.I went to my IE setting->LAN Settings.Then copied the Address as host and port as the port and it worked. Following is the snapshot of the proxies tag in the Settings.xml that I changed.

<proxy>
  <id>optional</id>
  <active>true</active>
  <protocol>http</protocol>
  <!--username>proxyuser</username>
  <password>proxypass</password-->
  <host>webtitan</host>
  <port>8881</port>
  <!--nonProxyHosts>local.net|some.host.com</nonProxyHosts-->
</proxy>

Difference between exit() and sys.exit() in Python

exit is a helper for the interactive shell - sys.exit is intended for use in programs.

The site module (which is imported automatically during startup, except if the -S command-line option is given) adds several constants to the built-in namespace (e.g. exit). They are useful for the interactive interpreter shell and should not be used in programs.


Technically, they do mostly the same: raising SystemExit. sys.exit does so in sysmodule.c:

static PyObject *
sys_exit(PyObject *self, PyObject *args)
{
    PyObject *exit_code = 0;
    if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code))
        return NULL;
    /* Raise SystemExit so callers may catch it or clean up. */
    PyErr_SetObject(PyExc_SystemExit, exit_code);
   return NULL;
}

While exit is defined in site.py and _sitebuiltins.py, respectively.

class Quitter(object):
    def __init__(self, name):
        self.name = name
    def __repr__(self):
        return 'Use %s() or %s to exit' % (self.name, eof)
    def __call__(self, code=None):
        # Shells like IDLE catch the SystemExit, but listen when their
        # stdin wrapper is closed.
        try:
            sys.stdin.close()
        except:
            pass
        raise SystemExit(code)
__builtin__.quit = Quitter('quit')
__builtin__.exit = Quitter('exit')

Note that there is a third exit option, namely os._exit, which exits without calling cleanup handlers, flushing stdio buffers, etc. (and which should normally only be used in the child process after a fork()).

Converting HTML element to string in JavaScript / JQuery

Try a slight different approach:

//set string and append it as object
var myHtmlString = '<iframe id="myFrame" width="854" height="480" src="http://www.youtube.com/embed/gYKqrjq5IjU?feature=oembed" frameborder="0" allowfullscreen></iframe>';
$('body').append(myHtmlString);

//as you noticed you can't just get it back
var myHtmlStringBack = $('#myFrame').html(); 
alert(myHtmlStringBack); // will be empty (a bug in jquery?) but...

//since an id was added to your iframe so you can retrieve its attributes back...
var width = $('#myFrame').attr('width');
var height = $('#myFrame').attr('height');
var src = $('#myFrame').attr('src');
var myReconstructedString = '<iframe id="myFrame" width="'+ width +'" height="'+ height +'" src="'+ src+'" frameborder="0" allowfullscreen></iframe>';
alert(myReconstructedString);

How to approach a "Got minus one from a read call" error when connecting to an Amazon RDS Oracle instance

We faced the same issue and fixed it. Below is the reason and solution.

Problem

When the connection pool mechanism is used, the application server (in our case, it is JBOSS) creates connections according to the min-connection parameter. If you have 10 applications running, and each has a min-connection of 10, then a total of 100 sessions will be created in the database. Also, in every database, there is a max-session parameter, if your total number of connections crosses that border, then you will get Got minus one from a read call.

FYI: Use the query below to see your total number of sessions:

SELECT username, count(username) FROM v$session 
WHERE username IS NOT NULL group by username

Solution: With the help of our DBA, we increased that max-session parameter, so that all our application min-connection can accommodate.

How to make python Requests work via socks proxy

As soon as python requests will be merged with SOCKS5 pull request it will do as simple as using proxies dictionary:

#proxy
        # SOCKS5 proxy for HTTP/HTTPS
        proxies = {
            'http' : "socks5://myproxy:9191",
            'https' : "socks5://myproxy:9191"
        }

        #headers
        headers = {

        }

        url='http://icanhazip.com/'
        res = requests.get(url, headers=headers, proxies=proxies)

See SOCKS Proxy Support

Another options, in case that you cannot wait request to be ready, when you cannot use requesocks - like on GoogleAppEngine due to the lack of pwd built-in module, is to use PySocks that was mentioned above:

  1. Grab the socks.py file from the repo and put a copy in your root folder;
  2. Add import socks and import socket

At this point configure and bind the socket before using with urllib2 - in the following example:

import urllib2
import socket
import socks

socks.set_default_proxy(socks.SOCKS5, "myprivateproxy.net",port=9050)
socket.socket = socks.socksocket
res=urllib2.urlopen(url).read()

How to set password for Redis?

you can also use following command on client

cmd :: config set requirepass p@ss$12E45

above command will set p@ss$12E45 as a redis server password.

How do I call a non-static method from a static method in C#?

You can't call a non-static method without first creating an instance of its parent class.

So from the static method, you would have to instantiate a new object...

Vehicle myCar = new Vehicle();

... and then call the non-static method.

myCar.Drive();

HTML table with 100% width, with vertical scroll inside tbody

In following solution, table occupies 100% of the parent container, no absolute sizes required. It's pure CSS, flex layout is used.

Here is how it looks: enter image description here

Possible disadvantages:

  • vertical scrollbar is always visible, regardless of whether it's required;
  • table layout is fixed - columns do not resize according to the content width (you still can set whatever column width you want explicitly);
  • there is one absolute size - the width of the scrollbar, which is about 0.9em for the browsers I was able to check.

HTML (shortened):

<div class="table-container">
    <table>
        <thead>
            <tr>
                <th>head1</th>
                <th>head2</th>
                <th>head3</th>
                <th>head4</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>content1</td>
                <td>content2</td>
                <td>content3</td>
                <td>content4</td>
            </tr>
            <tr>
                <td>content1</td>
                <td>content2</td>
                <td>content3</td>
                <td>content4</td>
            </tr>
            ...
        </tbody>
    </table>
</div>

CSS, with some decorations omitted for clarity:

.table-container {
    height: 10em;
}
table {
    display: flex;
    flex-flow: column;
    height: 100%;
    width: 100%;
}
table thead {
    /* head takes the height it requires, 
    and it's not scaled when table is resized */
    flex: 0 0 auto;
    width: calc(100% - 0.9em);
}
table tbody {
    /* body takes all the remaining available space */
    flex: 1 1 auto;
    display: block;
    overflow-y: scroll;
}
table tbody tr {
    width: 100%;
}
table thead, table tbody tr {
    display: table;
    table-layout: fixed;
}

full code on jsfiddle

Same code in LESS so you can mix it in:

.table-scrollable() {
  @scrollbar-width: 0.9em;
  display: flex;
  flex-flow: column;

  thead,
  tbody tr {
    display: table;
    table-layout: fixed;
  }

  thead {
    flex: 0 0 auto;
    width: ~"calc(100% - @{scrollbar-width})";
  }

  tbody {
    display: block;
    flex: 1 1 auto;
    overflow-y: scroll;

    tr {
      width: 100%;
    }
  }
}

Convert Base64 string to an image file?

$datetime = date("Y-m-d h:i:s");
$timestamp = strtotime($datetime);
$image = $_POST['image'];
$imgdata = base64_decode($image);
$f = finfo_open();
$mime_type = finfo_buffer($f, $imgdata, FILEINFO_MIME_TYPE);
$temp=explode('/',$mime_type);
$path = "uploads/$timestamp.$temp[1]";
file_put_contents($path,base64_decode($image));
echo "Successfully Uploaded->>> $timestamp.$temp[1]";

This will be enough for image processing. Special thanks to Mr. Dev Karan Sharma

What is a NullPointerException, and how do I fix it?

Question: What causes a NullPointerException (NPE)?

As you should know, Java types are divided into primitive types (boolean, int, etc.) and reference types. Reference types in Java allow you to use the special value null which is the Java way of saying "no object".

A NullPointerException is thrown at runtime whenever your program attempts to use a null as if it was a real reference. For example, if you write this:

public class Test {
    public static void main(String[] args) {
        String foo = null;
        int length = foo.length();   // HERE
    }
}

the statement labeled "HERE" is going to attempt to run the length() method on a null reference, and this will throw a NullPointerException.

There are many ways that you could use a null value that will result in a NullPointerException. In fact, the only things that you can do with a null without causing an NPE are:

  • assign it to a reference variable or read it from a reference variable,
  • assign it to an array element or read it from an array element (provided that array reference itself is non-null!),
  • pass it as a parameter or return it as a result, or
  • test it using the == or != operators, or instanceof.

Question: How do I read the NPE stacktrace?

Suppose that I compile and run the program above:

$ javac Test.java 
$ java Test
Exception in thread "main" java.lang.NullPointerException
    at Test.main(Test.java:4)
$

First observation: the compilation succeeds! The problem in the program is NOT a compilation error. It is a runtime error. (Some IDEs may warn your program will always throw an exception ... but the standard javac compiler doesn't.)

Second observation: when I run the program, it outputs two lines of "gobbledy-gook". WRONG!! That's not gobbledy-gook. It is a stacktrace ... and it provides vital information that will help you track down the error in your code if you take the time to read it carefully.

So let's look at what it says:

Exception in thread "main" java.lang.NullPointerException

The first line of the stack trace tells you a number of things:

  • It tells you the name of the Java thread in which the exception was thrown. For a simple program with one thread (like this one), it will be "main". Let's move on ...
  • It tells you the full name of the exception that was thrown; i.e. java.lang.NullPointerException.
  • If the exception has an associated error message, that will be output after the exception name. NullPointerException is unusual in this respect, because it rarely has an error message.

The second line is the most important one in diagnosing an NPE.

at Test.main(Test.java:4)

This tells us a number of things:

  • "at Test.main" says that we were in the main method of the Test class.
  • "Test.java:4" gives the source filename of the class, AND it tells us that the statement where this occurred is in line 4 of the file.

If you count the lines in the file above, line 4 is the one that I labeled with the "HERE" comment.

Note that in a more complicated example, there will be lots of lines in the NPE stack trace. But you can be sure that the second line (the first "at" line) will tell you where the NPE was thrown1.

In short, the stack trace will tell us unambiguously which statement of the program has thrown the NPE.

See also: What is a stack trace, and how can I use it to debug my application errors?

1 - Not quite true. There are things called nested exceptions...

Question: How do I track down the cause of the NPE exception in my code?

This is the hard part. The short answer is to apply logical inference to the evidence provided by the stack trace, the source code, and the relevant API documentation.

Let's illustrate with the simple example (above) first. We start by looking at the line that the stack trace has told us is where the NPE happened:

int length = foo.length(); // HERE

How can that throw an NPE?

In fact, there is only one way: it can only happen if foo has the value null. We then try to run the length() method on null and... BANG!

But (I hear you say) what if the NPE was thrown inside the length() method call?

Well, if that happened, the stack trace would look different. The first "at" line would say that the exception was thrown in some line in the java.lang.String class and line 4 of Test.java would be the second "at" line.

So where did that null come from? In this case, it is obvious, and it is obvious what we need to do to fix it. (Assign a non-null value to foo.)

OK, so let's try a slightly more tricky example. This will require some logical deduction.

public class Test {

    private static String[] foo = new String[2];

    private static int test(String[] bar, int pos) {
        return bar[pos].length();
    }

    public static void main(String[] args) {
        int length = test(foo, 1);
    }
}

$ javac Test.java 
$ java Test
Exception in thread "main" java.lang.NullPointerException
    at Test.test(Test.java:6)
    at Test.main(Test.java:10)
$ 

So now we have two "at" lines. The first one is for this line:

return args[pos].length();

and the second one is for this line:

int length = test(foo, 1);
    

Looking at the first line, how could that throw an NPE? There are two ways:

  • If the value of bar is null then bar[pos] will throw an NPE.
  • If the value of bar[pos] is null then calling length() on it will throw an NPE.

Next, we need to figure out which of those scenarios explains what is actually happening. We will start by exploring the first one:

Where does bar come from? It is a parameter to the test method call, and if we look at how test was called, we can see that it comes from the foo static variable. In addition, we can see clearly that we initialized foo to a non-null value. That is sufficient to tentatively dismiss this explanation. (In theory, something else could change foo to null ... but that is not happening here.)

So what about our second scenario? Well, we can see that pos is 1, so that means that foo[1] must be null. Is this possible?

Indeed it is! And that is the problem. When we initialize like this:

private static String[] foo = new String[2];

we allocate a String[] with two elements that are initialized to null. After that, we have not changed the contents of foo ... so foo[1] will still be null.

What about on Android?

On Android, tracking down the immediate cause of an NPE is a bit simpler. The exception message will typically tell you the (compile time) type of the null reference you are using and the method you were attempting to call when the NPE was thrown. This simplifies the process of pinpointing the immediate cause.

But on the flipside, Android has some common platform-specific causes for NPEs. A very common is when getViewById unexpectedly returns a null. My advice would be to search for Q&As about the cause of the unexpected null return value.

What is the reason for having '//' in Python?

To complement Alex's response, I would add that starting from Python 2.2.0a2, from __future__ import division is a convenient alternative to using lots of float(…)/…. All divisions perform float divisions, except those with //. This works with all versions from 2.2.0a2 on.

Save modifications in place with awk

@sudo_O has the right answer.

This can't work:

someprocess < file > file

The shell performs the redirections before handing control over to someprocess (redirections). The > redirection will truncate the file to zero size (redirecting output). Therefore, by the time someprocess gets launched and wants to read from the file, there is no data for it to read.

What does it mean when Statement.executeUpdate() returns -1?

So 4 years later, Microsoft has open sourced their JDBC driver on Github. I got a notification about this question today, and went and had a look, and I believe I have found the culprit here, mssql-jdbc/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerStatement.java:1713.

Basically, the driver tries to understand what SQL Server sends back if it is not a definite result set. According to the comments, it goes like this:

  1. Check for errors first. (ln 1669)

  2. Not an error. Is it a result set? (ln 1680)

  3. Not an error or a result set. Maybe a result from a T-SQL statement? That is, one of the following:

    • a positive count of the number of rows affected (from INSERT, UPDATE, or DELETE),
    • a zero indicating no rows affected, or the statement was DDL, or
    • a -1 indicating the statement succeeded, but there is no update count information available (translates to Statement.SUCCESS_NO_INFO in batch update count arrays). (ln 1706)
  4. None of the above. Last chance here... Going into the parser above, we know moreResults was initially true. If we come out with moreResults false, the we hit a DONE token (either DONE (FINAL) or DONE (RPC in batch)) that indicates that the batch succeeded overall, but that there is no information on individual statements' update counts. This is similar to the last case above, except that there is no update count. That is: we have a successful result (return true), but we have no other information about it (updateCount = -1). (ln 1693)

  5. Only way to get here (moreResults is still true, but no apparent results of any kind) is if the TDSParser didn't actually parse anything. That is, we are at EOF in the response. In that case, there truly are no more results. We're done. (ln 1717)

(Emphasis mine)

So you guys were right in the end. SQL simply can't tell how many rows are affected, and defaults to -1. :)

pip3: command not found

Writing the whole path/directory eg. (for windows) C:\Programs\Python\Python36-32\Scripts\pip3.exe install mypackage. This worked well for me when I had trouble with pip.

Numpy isnan() fails on an array of floats (from pandas dataframe apply)

A great substitute for np.isnan() and pd.isnull() is

for i in range(0,a.shape[0]):
    if(a[i]!=a[i]):
       //do something here
       //a[i] is nan

since only nan is not equal to itself.

Why can't Python import Image from PIL?

For me, I had typed image with a lower case "i" instead of Image. So I did:

from PIL import Image NOT from PIL import image

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 );

Visual Studio 64 bit?

no, but it runs fine on win64, and can create win64 .EXEs

Javascript callback when IFRAME is finished loading?

Using onload attrbute will solve your problem.

Here is an example.

_x000D_
_x000D_
function a() {_x000D_
alert("Your iframe has been loaded");_x000D_
}
_x000D_
<iframe src="https://stackoverflow.com" onload="a()"></iframe>
_x000D_
_x000D_
_x000D_

Is this what you want?

Click here for more information.

Deleting row from datatable in C#

There several different ways to do it. But You can use the following approach:

List<DataRow> RowsToDelete = new List<DataRow>();

for (int i = 0; i < drr.Length; i++) 
{     
   if(condition to delete the row) 
   {  
       RowsToDelete.Add(drr[i]);     
   } 
}

foreach(var dr in RowsToDelete) 
{     
   drr.Rows.Remove(dr); 
} 

Delete duplicate records from a SQL table without a primary key

ALTER IGNORE TABLE test
           ADD UNIQUE INDEX 'test' ('b'); 

@ here 'b' is column name to uniqueness, @ here 'test' is index name.

Getting reference to the top-most view/window in iOS application

If your application only works in portrait orientation, this is enough:

[[[UIApplication sharedApplication] keyWindow] addSubview:yourView]

And your view will not be shown over keyboard and status bar.

If you want to get a topmost view that over keyboard or status bar, or you want the topmost view can rotate correctly with devices, please try this framework:

https://github.com/HarrisonXi/TopmostView

It supports iOS7/8/9.

How do I implement onchange of <input type="text"> with jQuery?

As @pimvdb said in his comment,

Note that change will only fire when the input element has lost focus. There is also the input event which fires whenever the textbox updates without it needing to lose focus. Unlike key events it also works for pasting/dragging text.

(See documentation.)

This is so useful, it is worth putting it in an answer. Currently (v1.8*?) there is no .input() convenience fn in jquery, so the way to do it is

$('input.myTextInput').on('input',function(e){
 alert('Changed!')
});

window.location.href not working

if anyone faced problem even after using return false; . then use the below.

setTimeout(function(){document.location.href = "index.php"},500);

Javascript change color of text and background to input value

document.getElementById("fname").style.borderTopColor = 'red';
document.getElementById("fname").style.borderBottomColor = 'red';

Why am I getting the error "connection refused" in Python? (Sockets)

This error means that for whatever reason the client cannot connect to the port on the computer running server script. This can be caused by few things, like lack of routing to the destination, but since you can ping the server, it should not be the case. The other reason might be that you have a firewall somewhere between your client and the server - it could be on server itself or on the client. Given your network addressing, I assume both server and client are on the same LAN, so there shouldn't be any router/firewall involved that could block the traffic. In this case, I'd try the following:

  • check if you really have that port listening on the server (this should tell you if your code does what you think it should): based on your OS, but on linux you could do something like netstat -ntulp
  • check from the server, if you're accepting the connections to the server: again based on your OS, but telnet LISTENING_IP LISTENING_PORT should do the job
  • check if you can access the port of the server from the client, but not using the code: just us the telnet (or appropriate command for your OS) from the client

and then let us know the findings.

How to get element-wise matrix multiplication (Hadamard product) in numpy?

import numpy as np
x = np.array([[1,2,3], [4,5,6]])
y = np.array([[-1, 2, 0], [-2, 5, 1]])

x*y
Out: 
array([[-1,  4,  0],
       [-8, 25,  6]])

%timeit x*y
1000000 loops, best of 3: 421 ns per loop

np.multiply(x,y)
Out: 
array([[-1,  4,  0],
       [-8, 25,  6]])

%timeit np.multiply(x, y)
1000000 loops, best of 3: 457 ns per loop

Both np.multiply and * would yield element wise multiplication known as the Hadamard Product

%timeit is ipython magic

How to get all subsets of a set? (powerset)

def powerset(lst):
    return reduce(lambda result, x: result + [subset + [x] for subset in result],
                  lst, [[]])

How to get just one file from another branch

git checkout branch_name file_name

Example:

git checkout master App.java

This will not work if your branch name has a period in it.

git checkout "fix.june" alive.html
error: pathspec 'fix.june' did not match any file(s) known to git.

How to handle an IF STATEMENT in a Mustache template?

I have a simple and generic hack to perform key/value if statement instead of boolean-only in mustache (and in an extremely readable fashion!) :

function buildOptions (object) {
    var validTypes = ['string', 'number', 'boolean'];
    var value;
    var key;
    for (key in object) {
        value = object[key];
        if (object.hasOwnProperty(key) && validTypes.indexOf(typeof value) !== -1) {
            object[key + '=' + value] = true;
        }
    }
    return object;
}

With this hack, an object like this:

var contact = {
  "id": 1364,
  "author_name": "Mr Nobody",
  "notified_type": "friendship",
  "action": "create"
};

Will look like this before transformation:

var contact = {
  "id": 1364,
  "id=1364": true,
  "author_name": "Mr Nobody",
  "author_name=Mr Nobody": true,
  "notified_type": "friendship",
  "notified_type=friendship": true,
  "action": "create",
  "action=create": true
};

And your mustache template will look like this:

{{#notified_type=friendship}}
    friendship…
{{/notified_type=friendship}}

{{#notified_type=invite}}
    invite…
{{/notified_type=invite}}

How to display data from database into textbox, and update it

Populate the text box values in the Page Init event as opposed to using the Postback.

protected void Page_Init(object sender, EventArgs e)
{
    DropDownTitle();
}

Receiving "Attempted import error:" in react app

import { combineReducers } from '../../store/reducers';

should be

import combineReducers from '../../store/reducers';

since it's a default export, and not a named export.

There's a good breakdown of the differences between the two here.

Exception thrown in catch and finally clause

The easiest way to think of this is imagine that there is a variable global to the entire application that is holding the current exception.

Exception currentException = null;

As each exception is thrown, "currentException" is set to that exception. When the application ends, if currentException is != null, then the runtime reports the error.

Also, the finally blocks always run before the method exits. You could then requite the code snippet to:

public class C1 {

    public static void main(String [] argv) throws Exception {
        try {
            System.out.print(1);
            q();

        }
        catch ( Exception i ) {
            // <-- currentException = Exception, as thrown by q()'s finally block
            throw( new MyExc2() ); // <-- currentException = MyExc2
        }
        finally {
             // <-- currentException = MyExc2, thrown from main()'s catch block
            System.out.print(2);
            throw( new MyExc1() ); // <-- currentException = MyExc1
        }

    }  // <-- At application exit, currentException = MyExc1, from main()'s finally block. Java now dumps that to the console.

    static void q() throws Exception {
        try {
            throw( new MyExc1() ); // <-- currentException = MyExc1
        }
        catch( Exception y ) {
           // <-- currentException = null, because the exception is caught and not rethrown
        }
        finally {
            System.out.print(3);
            throw( new Exception() ); // <-- currentException = Exception
        }
    }
}

The order in which the application executes is:

main()
{
  try
    q()
    {
      try
      catch
      finally
    }
  catch
  finally
}

How do I post button value to PHP?

Give them all a name that is the same

For example

<input type="button" value="a" name="btn" onclick="a" />
<input type="button" value="b" name="btn" onclick="b" />

Then in your php use:

$val = $_POST['btn']

Edit, as BalusC said; If you're not going to use onclick for doing any javascript (for example, sending the form) then get rid of it and use type="submit"

Could not find or load main class with a Jar File

If you use package names, it won't work with folders containing dots (Error: Could not find or load main class). Even though it compiles and creates the jar file successfully.

Instead it requires a complete folder hierarchy.

Fails:

com.example.mypackage/
    Main.java

Works:

com/
    example/
        mypackage/
            Main.java

To compile in Linux:

javac `find com/ -name '*.java'` \ && jar cfe app.jar com.example.mypackage.Main `find com/ -name '*.class'`

Displaying a webcam feed using OpenCV and Python

change import cv to import cv2.cv as cv See also the post here.

Truncate with condition

You can simply export the table with a query clause using datapump and import it back with table_exists_action=replace clause. Its will drop and recreate your table and take very less time. Please read about it before implementing.

Matching special characters and letters in regex

Try this RegEx: Matching special charecters which we use in paragraphs and alphabets

   Javascript : /^[a-zA-Z]+(([\'\,\.\-_ \/)(:][a-zA-Z_ ])?[a-zA-Z_ .]*)*$/.test(str)

                .test(str) returns boolean value if matched true and not matched false

            c# :  ^[a-zA-Z]+(([\'\,\.\-_ \/)(:][a-zA-Z_ ])?[a-zA-Z_ .]*)*$

error::make_unique is not a member of ‘std’

If you have latest compiler, you can change the following in your build settings:

 C++ Language Dialect    C++14[-std=c++14]

This works for me.

What is the shortcut in IntelliJ IDEA to find method / functions?

If I need navigate to method in currently opened class, I use this combination: ALT+7 (CMD+7 on Mac) to open structure view, and press two times (first time open, second time focus on view), type name of methods, select on of needed.

How to use onClick with divs in React.js

I just needed a simple testing button for react.js. Here is what I did and it worked.

function Testing(){
 var f=function testing(){
         console.log("Testing Mode activated");
         UserData.authenticated=true;
         UserData.userId='123';
       };
 console.log("Testing Mode");

 return (<div><button onClick={f}>testing</button></div>);
}

How to convert integer to char in C?

You can try atoi() library function. Also sscanf() and sprintf() would help.

Here is a small example to show converting integer to character string:

main()
{
  int i = 247593;
  char str[10];

  sprintf(str, "%d", i);
  // Now str contains the integer as characters
} 

Here for another Example

#include <stdio.h>

int main(void)
{
   char text[] = "StringX";
   int digit;
   for (digit = 0; digit < 10; ++digit)
   {
      text[6] = digit + '0';
      puts(text);
   }
   return 0;
}

/* my output
String0
String1
String2
String3
String4
String5
String6
String7
String8
String9
*/

Rails 4 image-path, image-url and asset-url no longer work in SCSS files

I had a similar problem, trying to add a background image with inline css. No need to specify the images folder due to the way asset sync works.

This worked for me:

background-image: url('/assets/image.jpg');

Python Pandas - Missing required dependencies ['numpy'] 1

I have same problem. I have got two version of numpy 1.16.6 and 1.15.4, fresh installed pandas did not work correctly. I fixed it by uninstalling all versions of numpy and pandas and install the last versions.

$ pip uninstall  numpy pandas -y
Uninstalling numpy-1.16.6:
  Successfully uninstalled numpy-1.16.6
Uninstalling pandas-0.24.2:
  Successfully uninstalled pandas-0.24.2
$ pip uninstall  numpy pandas -y
Uninstalling numpy-1.15.4:
  Successfully uninstalled numpy-1.15.4
Cannot uninstall requirement pandas, not installed
$ pip uninstall  numpy pandas -y
Cannot uninstall requirement numpy, not installed
$ pip install  numpy pandas

C++ style cast from unsigned char * to const char *

Hope it help. :)

const unsigned attribName = getname();
const unsigned attribVal = getvalue();
const char *attrName=NULL, *attrVal=NULL;
attrName = (const char*) attribName;
attrVal = (const char*) attribVal;

How to use sudo inside a docker container?

If SUDO or apt-get is not accessible inside the Container, You can use, below option in running container.

docker exec -u root -it f83b5c5bf413 ash

"f83b5c5bf413" is my container ID & here is working example from my terminal:

enter image description here