Programs & Examples On #Zlib

zlib is a library used for data compression. Also a crucial component of many software platforms including Linux, Mac OS X, and the iOS

How are zlib, gzip and zip related? What do they have in common and how are they different?

Short form:

.zip is an archive format using, usually, the Deflate compression method. The .gz gzip format is for single files, also using the Deflate compression method. Often gzip is used in combination with tar to make a compressed archive format, .tar.gz. The zlib library provides Deflate compression and decompression code for use by zip, gzip, png (which uses the zlib wrapper on deflate data), and many other applications.

Long form:

The ZIP format was developed by Phil Katz as an open format with an open specification, where his implementation, PKZIP, was shareware. It is an archive format that stores files and their directory structure, where each file is individually compressed. The file type is .zip. The files, as well as the directory structure, can optionally be encrypted.

The ZIP format supports several compression methods:

    0 - The file is stored (no compression)
    1 - The file is Shrunk
    2 - The file is Reduced with compression factor 1
    3 - The file is Reduced with compression factor 2
    4 - The file is Reduced with compression factor 3
    5 - The file is Reduced with compression factor 4
    6 - The file is Imploded
    7 - Reserved for Tokenizing compression algorithm
    8 - The file is Deflated
    9 - Enhanced Deflating using Deflate64(tm)
   10 - PKWARE Data Compression Library Imploding (old IBM TERSE)
   11 - Reserved by PKWARE
   12 - File is compressed using BZIP2 algorithm
   13 - Reserved by PKWARE
   14 - LZMA
   15 - Reserved by PKWARE
   16 - IBM z/OS CMPSC Compression
   17 - Reserved by PKWARE
   18 - File is compressed using IBM TERSE (new)
   19 - IBM LZ77 z Architecture 
   20 - deprecated (use method 93 for zstd)
   93 - Zstandard (zstd) Compression 
   94 - MP3 Compression 
   95 - XZ Compression 
   96 - JPEG variant
   97 - WavPack compressed data
   98 - PPMd version I, Rev 1
   99 - AE-x encryption marker (see APPENDIX E)

Methods 1 to 7 are historical and are not in use. Methods 9 through 98 are relatively recent additions and are in varying, small amounts of use. The only method in truly widespread use in the ZIP format is method 8, Deflate, and to some smaller extent method 0, which is no compression at all. Virtually every .zip file that you will come across in the wild will use exclusively methods 8 and 0, likely just method 8. (Method 8 also has a means to effectively store the data with no compression and relatively little expansion, and Method 0 cannot be streamed whereas Method 8 can be.)

The ISO/IEC 21320-1:2015 standard for file containers is a restricted zip format, such as used in Java archive files (.jar), Office Open XML files (Microsoft Office .docx, .xlsx, .pptx), Office Document Format files (.odt, .ods, .odp), and EPUB files (.epub). That standard limits the compression methods to 0 and 8, as well as other constraints such as no encryption or signatures.

Around 1990, the Info-ZIP group wrote portable, free, open-source implementations of zip and unzip utilities, supporting compression with the Deflate format, and decompression of that and the earlier formats. This greatly expanded the use of the .zip format.

In the early '90s, the gzip format was developed as a replacement for the Unix compress utility, derived from the Deflate code in the Info-ZIP utilities. Unix compress was designed to compress a single file or stream, appending a .Z to the file name. compress uses the LZW compression algorithm, which at the time was under patent and its free use was in dispute by the patent holders. Though some specific implementations of Deflate were patented by Phil Katz, the format was not, and so it was possible to write a Deflate implementation that did not infringe on any patents. That implementation has not been so challenged in the last 20+ years. The Unix gzip utility was intended as a drop-in replacement for compress, and in fact is able to decompress compress-compressed data (assuming that you were able to parse that sentence). gzip appends a .gz to the file name. gzip uses the Deflate compressed data format, which compresses quite a bit better than Unix compress, has very fast decompression, and adds a CRC-32 as an integrity check for the data. The header format also permits the storage of more information than the compress format allowed, such as the original file name and the file modification time.

Though compress only compresses a single file, it was common to use the tar utility to create an archive of files, their attributes, and their directory structure into a single .tar file, and to then compress it with compress to make a .tar.Z file. In fact, the tar utility had and still has an option to do the compression at the same time, instead of having to pipe the output of tar to compress. This all carried forward to the gzip format, and tar has an option to compress directly to the .tar.gz format. The tar.gz format compresses better than the .zip approach, since the compression of a .tar can take advantage of redundancy across files, especially many small files. .tar.gz is the most common archive format in use on Unix due to its very high portability, but there are more effective compression methods in use as well, so you will often see .tar.bz2 and .tar.xz archives.

Unlike .tar, .zip has a central directory at the end, which provides a list of the contents. That and the separate compression provides random access to the individual entries in a .zip file. A .tar file would have to be decompressed and scanned from start to end in order to build a directory, which is how a .tar file is listed.

Shortly after the introduction of gzip, around the mid-1990s, the same patent dispute called into question the free use of the .gif image format, very widely used on bulletin boards and the World Wide Web (a new thing at the time). So a small group created the PNG losslessly compressed image format, with file type .png, to replace .gif. That format also uses the Deflate format for compression, which is applied after filters on the image data expose more of the redundancy. In order to promote widespread usage of the PNG format, two free code libraries were created. libpng and zlib. libpng handled all of the features of the PNG format, and zlib provided the compression and decompression code for use by libpng, as well as for other applications. zlib was adapted from the gzip code.

All of the mentioned patents have since expired.

The zlib library supports Deflate compression and decompression, and three kinds of wrapping around the deflate streams. Those are: no wrapping at all ("raw" deflate), zlib wrapping, which is used in the PNG format data blocks, and gzip wrapping, to provide gzip routines for the programmer. The main difference between zlib and gzip wrapping is that the zlib wrapping is more compact, six bytes vs. a minimum of 18 bytes for gzip, and the integrity check, Adler-32, runs faster than the CRC-32 that gzip uses. Raw deflate is used by programs that read and write the .zip format, which is another format that wraps around deflate compressed data.

zlib is now in wide use for data transmission and storage. For example, most HTTP transactions by servers and browsers compress and decompress the data using zlib, specifically HTTP header Content-Encoding: deflate means deflate compression method wrapped inside the zlib data format.

Different implementations of deflate can result in different compressed output for the same input data, as evidenced by the existence of selectable compression levels that allow trading off compression effectiveness for CPU time. zlib and PKZIP are not the only implementations of deflate compression and decompression. Both the 7-Zip archiving utility and Google's zopfli library have the ability to use much more CPU time than zlib in order to squeeze out the last few bits possible when using the deflate format, reducing compressed sizes by a few percent as compared to zlib's highest compression level. The pigz utility, a parallel implementation of gzip, includes the option to use zlib (compression levels 1-9) or zopfli (compression level 11), and somewhat mitigates the time impact of using zopfli by splitting the compression of large files over multiple processors and cores.

Simple way to unzip a .zip file using zlib

Minizip does have an example programs to demonstrate its usage - the files are called minizip.c and miniunz.c.

Update: I had a few minutes so I whipped up this quick, bare bones example for you. It's very smelly C, and I wouldn't use it without major improvements. Hopefully it's enough to get you going for now.

// uzip.c - Simple example of using the minizip API.
// Do not use this code as is! It is educational only, and probably
// riddled with errors and leaks!
#include <stdio.h>
#include <string.h>

#include "unzip.h"

#define dir_delimter '/'
#define MAX_FILENAME 512
#define READ_SIZE 8192

int main( int argc, char **argv )
{
    if ( argc < 2 )
    {
        printf( "usage:\n%s {file to unzip}\n", argv[ 0 ] );
        return -1;
    }

    // Open the zip file
    unzFile *zipfile = unzOpen( argv[ 1 ] );
    if ( zipfile == NULL )
    {
        printf( "%s: not found\n" );
        return -1;
    }

    // Get info about the zip file
    unz_global_info global_info;
    if ( unzGetGlobalInfo( zipfile, &global_info ) != UNZ_OK )
    {
        printf( "could not read file global info\n" );
        unzClose( zipfile );
        return -1;
    }

    // Buffer to hold data read from the zip file.
    char read_buffer[ READ_SIZE ];

    // Loop to extract all files
    uLong i;
    for ( i = 0; i < global_info.number_entry; ++i )
    {
        // Get info about current file.
        unz_file_info file_info;
        char filename[ MAX_FILENAME ];
        if ( unzGetCurrentFileInfo(
            zipfile,
            &file_info,
            filename,
            MAX_FILENAME,
            NULL, 0, NULL, 0 ) != UNZ_OK )
        {
            printf( "could not read file info\n" );
            unzClose( zipfile );
            return -1;
        }

        // Check if this entry is a directory or file.
        const size_t filename_length = strlen( filename );
        if ( filename[ filename_length-1 ] == dir_delimter )
        {
            // Entry is a directory, so create it.
            printf( "dir:%s\n", filename );
            mkdir( filename );
        }
        else
        {
            // Entry is a file, so extract it.
            printf( "file:%s\n", filename );
            if ( unzOpenCurrentFile( zipfile ) != UNZ_OK )
            {
                printf( "could not open file\n" );
                unzClose( zipfile );
                return -1;
            }

            // Open a file to write out the data.
            FILE *out = fopen( filename, "wb" );
            if ( out == NULL )
            {
                printf( "could not open destination file\n" );
                unzCloseCurrentFile( zipfile );
                unzClose( zipfile );
                return -1;
            }

            int error = UNZ_OK;
            do    
            {
                error = unzReadCurrentFile( zipfile, read_buffer, READ_SIZE );
                if ( error < 0 )
                {
                    printf( "error %d\n", error );
                    unzCloseCurrentFile( zipfile );
                    unzClose( zipfile );
                    return -1;
                }

                // Write data to file.
                if ( error > 0 )
                {
                    fwrite( read_buffer, error, 1, out ); // You should check return of fwrite...
                }
            } while ( error > 0 );

            fclose( out );
        }

        unzCloseCurrentFile( zipfile );

        // Go the the next entry listed in the zip file.
        if ( ( i+1 ) < global_info.number_entry )
        {
            if ( unzGoToNextFile( zipfile ) != UNZ_OK )
            {
                printf( "cound not read next file\n" );
                unzClose( zipfile );
                return -1;
            }
        }
    }

    unzClose( zipfile );

    return 0;
}

I built and tested it with MinGW/MSYS on Windows like this:

contrib/minizip/$ gcc -I../.. -o unzip uzip.c unzip.c ioapi.c ../../libz.a
contrib/minizip/$ ./unzip.exe /j/zlib-125.zip

Compilation error - missing zlib.h

Maybe you can download zlib.h from https://dev.w3.org/Amaya/libpng/zlib/zlib.h, and put it in the directory to solve the problem.

no module named zlib

Sounds like you need to install the devel package for zlib, probably want to do something like sudo apt-get install zlib1g-dev (I don't use ubuntu so you'll want to double-check the package). Instead of using python-brew you might want to consider just compiling by hand, it's not very hard. Just download the source, and configure, make, make install. You'll want to at least set --prefix to somewhere, so it'll get installed where you want.

./configure --prefix=/opt/python2.7 + other options
make
make install

You can check what configuration options are available with ./configure --help and see what your system python was compiled with by doing:

python -c "import sysconfig; print sysconfig.get_config_var('CONFIG_ARGS')"

The key is to make sure you have the development packages installed for your system, so that Python will be able to build the zlib, sqlite3, etc modules. The python docs cover the build process in more detail: http://docs.python.org/using/unix.html#building-python.

Postgresql tables exists, but getting "relation does not exist" when querying

The error can be caused by access restrictions. Solution:

GRANT ALL PRIVILEGES ON DATABASE my_database TO my_user;

Could not open input file: composer.phar

Another solution could be.. find the location of composer.phar file in your computer. If composer is installed successfully then it can be found in the installed directory.

Copy that location & instead of composer.phar in the command line, put the entire path there.

It also worked for me!

How to do this using jQuery - document.getElementById("selectlist").value

In some cases of which I can't remember why but $('#selectlist').val() won't always return the correct item value, so I use $('#selectlist option:selected').val() instead.

Verify if file exists or not in C#

These answers all assume the file you are checking is on the server side. Unfortunately, there is no cast iron way to ensure that a file exists on the client side (e.g. if you are uploading the resume). Sure, you can do it in Javascript but you are still not going to be 100% sure on the server side.

The best way to handle this, in my opinion, is to assume that the user will actually select an appropriate file for upload, and then do whatever work you need to do to ensure the uploaded file is what you expect (hint - assume the user is trying to poison your system in every possible way with his/her input)

How to include another XHTML in XHTML using JSF 2.0 Facelets?

<ui:include>

Most basic way is <ui:include>. The included content must be placed inside <ui:composition>.

Kickoff example of the master page /page.xhtml:

<!DOCTYPE html>
<html lang="en"
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://xmlns.jcp.org/jsf/core"
    xmlns:h="http://xmlns.jcp.org/jsf/html"
    xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
    <h:head>
        <title>Include demo</title>
    </h:head>
    <h:body>
        <h1>Master page</h1>
        <p>Master page blah blah lorem ipsum</p>
        <ui:include src="/WEB-INF/include.xhtml" />
    </h:body>
</html>

The include page /WEB-INF/include.xhtml (yes, this is the file in its entirety, any tags outside <ui:composition> are unnecessary as they are ignored by Facelets anyway):

<ui:composition 
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://xmlns.jcp.org/jsf/core"
    xmlns:h="http://xmlns.jcp.org/jsf/html"
    xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
    <h2>Include page</h2>
    <p>Include page blah blah lorem ipsum</p>
</ui:composition>
  

This needs to be opened by /page.xhtml. Do note that you don't need to repeat <html>, <h:head> and <h:body> inside the include file as that would otherwise result in invalid HTML.

You can use a dynamic EL expression in <ui:include src>. See also How to ajax-refresh dynamic include content by navigation menu? (JSF SPA).


<ui:define>/<ui:insert>

A more advanced way of including is templating. This includes basically the other way round. The master template page should use <ui:insert> to declare places to insert defined template content. The template client page which is using the master template page should use <ui:define> to define the template content which is to be inserted.

Master template page /WEB-INF/template.xhtml (as a design hint: the header, menu and footer can in turn even be <ui:include> files):

<!DOCTYPE html>
<html lang="en"
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://xmlns.jcp.org/jsf/core"
    xmlns:h="http://xmlns.jcp.org/jsf/html"
    xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
    <h:head>
        <title><ui:insert name="title">Default title</ui:insert></title>
    </h:head>
    <h:body>
        <div id="header">Header</div>
        <div id="menu">Menu</div>
        <div id="content"><ui:insert name="content">Default content</ui:insert></div>
        <div id="footer">Footer</div>
    </h:body>
</html>

Template client page /page.xhtml (note the template attribute; also here, this is the file in its entirety):

<ui:composition template="/WEB-INF/template.xhtml"
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://xmlns.jcp.org/jsf/core"
    xmlns:h="http://xmlns.jcp.org/jsf/html"
    xmlns:ui="http://xmlns.jcp.org/jsf/facelets">

    <ui:define name="title">
        New page title here
    </ui:define>

    <ui:define name="content">
        <h1>New content here</h1>
        <p>Blah blah</p>
    </ui:define>
</ui:composition>

This needs to be opened by /page.xhtml. If there is no <ui:define>, then the default content inside <ui:insert> will be displayed instead, if any.


<ui:param>

You can pass parameters to <ui:include> or <ui:composition template> by <ui:param>.

<ui:include ...>
    <ui:param name="foo" value="#{bean.foo}" />
</ui:include>
<ui:composition template="...">
    <ui:param name="foo" value="#{bean.foo}" />
    ...
</ui:composition >

Inside the include/template file, it'll be available as #{foo}. In case you need to pass "many" parameters to <ui:include>, then you'd better consider registering the include file as a tagfile, so that you can ultimately use it like so <my:tagname foo="#{bean.foo}">. See also When to use <ui:include>, tag files, composite components and/or custom components?

You can even pass whole beans, methods and parameters via <ui:param>. See also JSF 2: how to pass an action including an argument to be invoked to a Facelets sub view (using ui:include and ui:param)?


Design hints

The files which aren't supposed to be publicly accessible by just entering/guessing its URL, need to be placed in /WEB-INF folder, like as the include file and the template file in above example. See also Which XHTML files do I need to put in /WEB-INF and which not?

There doesn't need to be any markup (HTML code) outside <ui:composition> and <ui:define>. You can put any, but they will be ignored by Facelets. Putting markup in there is only useful for web designers. See also Is there a way to run a JSF page without building the whole project?

The HTML5 doctype is the recommended doctype these days, "in spite of" that it's a XHTML file. You should see XHTML as a language which allows you to produce HTML output using a XML based tool. See also Is it possible to use JSF+Facelets with HTML 4/5? and JavaServer Faces 2.2 and HTML5 support, why is XHTML still being used.

CSS/JS/image files can be included as dynamically relocatable/localized/versioned resources. See also How to reference CSS / JS / image resource in Facelets template?

You can put Facelets files in a reusable JAR file. See also Structure for multiple JSF projects with shared code.

For real world examples of advanced Facelets templating, check the src/main/webapp folder of Java EE Kickoff App source code and OmniFaces showcase site source code.

show all tables in DB2 using the LIST command

I'm using db2 7.1 and SQuirrel. This is the only query that worked for me.

select * from SYSIBM.tables where table_schema = 'my_schema' and table_type = 'BASE TABLE';

Python class returning value

the worked proposition for me is __call__ on class who create list of little numbers:

import itertools
    
class SmallNumbers:
    def __init__(self, how_much):
        self.how_much = int(how_much)
        self.work_list = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
        self.generated_list = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
        start = 10
        end = 100
        for cmb in range(2, len(str(self.how_much)) + 1):
            self.ListOfCombinations(is_upper_then=start, is_under_then=end, combinations=cmb)
            start *= 10
            end *= 10

    def __call__(self, number, *args, **kwargs):
        return self.generated_list[number]

    def ListOfCombinations(self, is_upper_then, is_under_then, combinations):
        multi_work_list = eval(str('self.work_list,') * combinations)
        nbr = 0
        for subset in itertools.product(*multi_work_list):
            if is_upper_then <= nbr < is_under_then:
                self.generated_list.append(''.join(subset))
                if self.how_much == nbr:
                    break
            nbr += 1

and to run it:

if __name__ == '__main__':
        sm = SmallNumbers(56)
        print(sm.generated_list)
        print(sm.generated_list[34], sm.generated_list[27], sm.generated_list[10])
        print('The Best', sm(15), sm(55), sm(49), sm(0))

result

['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56']
34 27 10
The Best 15 55 49 0

How do I localize the jQuery UI Datepicker?

I solved it by adding the property data-date-language="it":

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $('#TxtDaDataDoc_Val').datepicker();_x000D_
});
_x000D_
<meta charset="utf-8">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">_x000D_
<link rel="stylesheet" href="/resources/demos/style.css">_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>_x000D_
_x000D_
<div class="form-group col-xs-2 col-sm-2 col-md-2">_x000D_
    <div class="input-group input-append date form-group" _x000D_
        id="TxtDaDataDoc" data-date-language="it">_x000D_
        <input type="text" class="form-control" name="date" _x000D_
               id="TxtDaDataDoc_Val" runat="server" />_x000D_
        <span class="input-group-addon add-on">_x000D_
            <span class="glyphicon glyphicon-calendar"></span>_x000D_
        </span>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I make my match non greedy in vim?

G'day,

Vim's regexp processing is not too brilliant. I've found that the regexp syntax for sed is about the right match for vim's capabilities.

I usually set the search highlighting on (:set hlsearch) and then play with the regexp after entering a slash to enter search mode.

Edit: Mark, that trick to minimise greedy matching is also covered in Dale Dougherty's excellent book "Sed & Awk" (sanitised Amazon link).

Chapter Three "Understanding Regular Expression Syntax" is an excellent intro to the more primitive regexp capabilities involved with sed and awk. Only a short read and highly recommended.

HTH

cheers,

Return array in a function

Here's a full example of this kind of problem to solve

#include <bits/stdc++.h>
using namespace std;
int* solve(int brr[],int n)
{
sort(brr,brr+n);
return brr;
}

int main()
{
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
{
    cin>>arr[i];
}
int *a=solve(arr,n);
for(int i=0;i<n;i++)
{
    cout<<a[i]<<endl;
}

return 0;
}

define() vs. const

I believe that as of PHP 5.3, you can use const outside of classes, as shown here in the second example:

http://www.php.net/manual/en/language.constants.syntax.php

<?php
// Works as of PHP 5.3.0
const CONSTANT = 'Hello World';

echo CONSTANT;
?>

Ignore mapping one property with Automapper

When mapping a view model back to a domain model, it can be much cleaner to simply validate the source member list rather than the destination member list

Mapper.CreateMap<OrderModel, Orders>(MemberList.Source); 

Now my mapping validation doesn't fail, requiring another Ignore(), every time I add a property to my domain class.

iOS Remote Debugging

Note: I have no affiliation with Ghostlab creators Vanamco whatsoever.

It was important to me to be able to debug Chrome-specific problems, so I set out to find something that could help me with that. I ended up happily throwing my money at Ghostlab 3. I can test Chrome and Safari mobile browsers as if I was viewing them on my desktop. It just gives me a LAN address to use for any device I’d like to debug. Each application using that address will appear in the list in Ghostlab.

enter image description here

enter image description here

Highly recommended.

Javascript: best Singleton pattern

function SingletonClass() 
{
    // demo variable
    var names = [];

    // instance of the singleton
    this.singletonInstance = null;

    // Get the instance of the SingletonClass
    // If there is no instance in this.singletonInstance, instanciate one
    var getInstance = function() {
        if (!this.singletonInstance) {
            // create a instance
            this.singletonInstance = createInstance();
        }

        // return the instance of the singletonClass
        return this.singletonInstance;
    }

    // function for the creation of the SingletonClass class
    var createInstance = function() {

        // public methodes
        return {
            add : function(name) {
                names.push(name);
            },
            names : function() {
                return names;
            }
        }
    }

    // wen constructed the getInstance is automaticly called and return the SingletonClass instance 
    return getInstance();
}

var obj1 = new SingletonClass();
obj1.add("Jim");
console.log(obj1.names());
// prints: ["Jim"]

var obj2 = new SingletonClass();
obj2.add("Ralph");
console.log(obj1.names());
// Ralph is added to the singleton instance and there for also acceseble by obj1
// prints: ["Jim", "Ralph"]
console.log(obj2.names());
// prints: ["Jim", "Ralph"]

obj1.add("Bart");
console.log(obj2.names());
// prints: ["Jim", "Ralph", "Bart"]

How to use lodash to find and return an object from Array?

With the find method, your callback is going to be passed the value of each element, like:

{
    description: 'object1', id: 1
}

Thus, you want code like:

_.find(savedViews, function(o) {
        return o.description === view;
})

Check if passed argument is file or directory in Bash

function check_file_path(){
    [ -f "$1" ] && return
    [ -d "$1" ] && return
    return 1
}
check_file_path $path_or_file

how to get bounding box for div element in jquery

As this is specifically tagged for jQuery -

$("#myElement")[0].getBoundingClientRect();

or

$("#myElement").get(0).getBoundingClientRect();

(These are functionally identical, in some older browsers .get() was slightly faster)

Note that if you try to get the values via jQuery calls then it will not take into account any css transform values, which can give unexpected results...

Note 2: In jQuery 3.0 it has changed to using the proper getBoundingClientRect() calls for its own dimension calls (see the jQuery Core 3.0 Upgrade Guide) - which means that the other jQuery answers will finally always be correct - but only when using the new jQuery version - hence why it's called a breaking change...

How to read/write arbitrary bits in C/C++

You need to shift and mask the value, so for example...

If you want to read the first two bits, you just need to mask them off like so:

int value = input & 0x3;

If you want to offset it you need to shift right N bits and then mask off the bits you want:

int value = (intput >> 1) & 0x3;

To read three bits like you asked in your question.

int value = (input >> 1) & 0x7;

Is String.Contains() faster than String.IndexOf()?

Contains calls IndexOf:

public bool Contains(string value)
{
    return (this.IndexOf(value, StringComparison.Ordinal) >= 0);
}

Which calls CompareInfo.IndexOf, which ultimately uses a CLR implementation.

If you want to see how strings are compared in the CLR this will show you (look for CaseInsensitiveCompHelper).

IndexOf(string) has no options and Contains()uses an Ordinal compare (a byte-by-byte comparison rather than trying to perform a smart compare, for example, e with é).

So IndexOf will be marginally faster (in theory) as IndexOf goes straight to a string search using FindNLSString from kernel32.dll (the power of reflector!).

Updated for .NET 4.0 - IndexOf no longer uses Ordinal Comparison and so Contains can be faster. See comment below.

Undefined symbols for architecture i386: _OBJC_CLASS_$_SKPSMTPMessage", referenced from: error

Also could be that you're missing to link against a Binary Library, check Build Phases in your Targes add required libraries and then Product > Clean Product > Build

That must work too!

How to access shared folder without giving username and password

I found one way to access the shared folder without giving the username and password.

We need to change the share folder protect settings in the machine where the folder has been shared.

Go to Control Panel > Network and sharing center > Change advanced sharing settings > Enable Turn Off password protect sharing option.

By doing the above settings we can access the shared folder without any username/password.

Pyspark: Exception: Java gateway process exited before sending the driver its port number

Had the same issue when was trying to run the pyspark job triggered from the Airflow with remote spark.driver.host. The cause of the issue in my case was:

Exception: Java gateway process exited before sending the driver its port number

...

Exception in thread "main" java.lang.Exception: When running with master 'yarn' either HADOOP_CONF_DIR or YARN_CONF_DIR must be set in the environment.

Fixed by adding exports:

export HADOOP_CONF_DIR=/etc/hadoop/conf

And the same environment variable added in the pyspark script:

import os
os.environ["HADOOP_CONF_DIR"] = '/etc/hadoop/conf'

How to combine date from one field with time from another field - MS SQL Server

select s.SalesID from SalesTbl s 
        where cast(cast(s.SaleDate  as date) as datetime) + cast(cast(s.SaleCreatedDate as time) as datetime)  

between @FromDate and @ToDate

Python Prime number checker

The two main problems with your code are:

  1. After designating a number not prime, you continue to check the rest of the divisors even though you already know it is not prime, which can lead to it printing "prime" after printing "not prime". Hint: use the `break' statement.
  2. You designate a number prime before you have checked all the divisors you need to check, because you are printing "prime" inside the loop. So you get "prime" multiple times, once for each divisor that doesn't go evenly into the number being tested. Hint: use an else clause with the loop to print "prime" only if the loop exits without breaking.

A couple pretty significant inefficiencies:

  1. You should keep track of the numbers you have already found that are prime and only divide by those. Why divide by 4 when you have already divided by 2? If a number is divisible by 4 it is also divisible by 2, so you would have already caught it and there is no need to divide by 4.
  2. You need only to test up to the square root of the number being tested because any factor larger than that would need to be multiplied with a number smaller than that, and that would already have been tested by the time you get to the larger one.

How to print a double with two decimals in Android?

textView2.setText(String.format("%.2f", result));

and

DecimalFormat form = new DecimalFormat("0.00");
         textView2.setText(form.format(result) );

...cause "NumberFormatException" error in locale for Europe because it sets result as comma instead of point decimal - error occurs when textView is added to number in editText. Both solutions are working excellent in locale US and UK.

How do I make a text go onto the next line if it overflows?

As long as you specify a width on the element, it should wrap itself without needing anything else.

Invoke-Command error "Parameter set cannot be resolved using the specified named parameters"

I was solving same problem recently. I was designing a write cmdlet for my Subtitle module. I had six different user stories:

  • Subtitle only
  • Subtitle and path (original file name is used)
  • Subtitle and new file name (original path is used)
  • Subtitle and name suffix is used (original path and modified name is used).
  • Subtile, new path and new file name is is used.
  • Subtitle, new path and suffix is used.

I end up in the big frustration because I though that 4 parameters will be enough. Like most of the times, the frustration was pointless because it was my fault. I didn't know enough about parameter sets.

After some research in documentation, I realized where is the problem. With knowledge how the parameter sets should be used, I developed a general and simple approach how to solve this problem. A pencil and a sheet of paper is required but a spreadsheet editor is better:

  1. Write down all intended ways how the cmdlet should be used => user stories.
  2. Keep adding parameters with meaningful names and mark the use of the parameters until you have a unique collection set => no repetitive combination of parameters.
  3. Implement parameter sets into your code.
  4. Prepare tests for all possible user stories.
  5. Run tests (big surprise, right?). IDEs doesn't checks parameter sets collision, tests could save lots of trouble later one.

Example:

Unique parameter binding resolution approach.

The practical example could be seen over here.

BTW: The parameter uniqueness within parameter sets is the reason why the ParameterSetName property doesn't support [String[]]. It doesn't really make any sense.

how to read a long multiline string line by line in python

by splitting with newlines.

for line in wallop_of_a_string_with_many_lines.split('\n'):
  #do_something..

if you iterate over a string, you are iterating char by char in that string, not by line.

>>>string = 'abc'
>>>for line in string:
    print line

a
b
c

I need an unordered list without any bullets

ul{list-style-type:none;}

Just set the style of unordered list is none.

Downloading all maven dependencies to a directory NOT in repository?

I found the next command

mvn dependency:copy-dependencies -Dclassifier=sources

here maven.apache.org

How to Correctly Check if a Process is running and Stop it

If you don't need to display exact result "running" / "not runnuning", you could simply:

ps notepad -ErrorAction SilentlyContinue | kill -PassThru

If the process was not running, you'll get no results. If it was running, you'll receive get-process output, and the process will be stopped.

Postgresql: Scripting psql execution with password

If you intend on having multiple hosts/database connections, the ~/.pgpass file is the way to go.

Steps:

  1. Create the file using vim ~/.pgpass or similar. Input your information in the following format: hostname:port:database:username:password Do not add string quotes around your field values. You can also use * as a wildcard for your port/database fields.
  2. You must chmod 0600 ~/.pgpass in order for it to not be silently ignored by psql.
  3. Create an alias in your bash profile that runs your psql command for you. For example:alias postygresy='psql --host hostname database_name -U username' The values should match those that you inputted to the ~/.pgpass file.
  4. Source your bash profile with . ~/.bashrc or similar.
  5. Type your alias from the command line.

Note that if you have an export PGPASSWORD='' variable set, it will take precedence over the file.

How to upgrade glibc from version 2.13 to 2.15 on Debian?

Your script contains errors as well, for example if you have dos2unix installed your install works but if you don't like I did then it will fail with dependency issues.

I found this by accident as I was making a script file of this to give to my friend who is new to Linux and because I made the scripts on windows I directed him to install it, at the time I did not have dos2unix installed thus I got errors.

here is a copy of the script I made for your solution but have dos2unix installed.

#!/bin/sh
echo "deb http://ftp.debian.org/debian sid main" >> /etc/apt/sources.list
apt-get update
apt-get -t sid install libc6 libc6-dev libc6-dbg
echo "Please remember to hash out sid main from your sources list. /etc/apt/sources.list"

this script has been tested on 3 machines with no errors.

How to add months to a date in JavaScript?

Split your date into year, month, and day components then use Date:

var d = new Date(year, month, day);
d.setMonth(d.getMonth() + 8);

Date will take care of fixing the year.

Parsing HTTP Response in Python

You can also use python's requests library instead.

import requests

url = 'http://www.quandl.com/api/v1/datasets/FRED/GDP.json'    
response = requests.get(url)    
dict = response.json()

Now you can manipulate the "dict" like a python dictionary.

git clone: Authentication failed for <URL>

I'm facing exactly same error when I'm trying to clone a repository on a brand new machine. I'm using Git bash as my Git client. When I ran Git's command to clone a repository it was not prompting me for user id and password which will be used for authentication. It was a fresh machine where not a single credential was cached by Windows credential manager.

As a last resort, I manually added my credentials in credentials manager.

Go to > Control Panel\User Accounts\Credential Manager > Windows Credentials

Click Add a Windows credential link and then Supply the details as shown in the form below and you're done:

enter image description here

I had put the details as below:

Internet or network address: <gitRepoServerNameOrIPAddress>
User Name: MyCompanysDomainName\MyUserName
Password: MyPassword

Next time you run any Git command targeting a repository set up on above address this manually created credential will be used.

It is also important if you have a git command line you close it and reopen it for changes to be applied.

Difference Between Select and SelectMany

One more example how SelectMany + Select can be used in order to accumulate sub array objects data.

Suppose we have users with they phones:

class Phone { 
    public string BasePart = "555-xxx-xxx"; 
}

class User { 
    public string Name = "Xxxxx";
    public List<Phone> Phones; 
}

Now we need to select all phones' BaseParts of all users:

var usersArray = new List<User>(); // array of arrays
List<string> allBaseParts = usersArray.SelectMany(ua => ua.Phones).Select(p => p.BasePart).ToList();

Android: remove notification from notification bar

You can try this quick code

public static void cancelNotification(Context ctx, int notifyId) {
    String ns = Context.NOTIFICATION_SERVICE;
    NotificationManager nMgr = (NotificationManager) ctx.getSystemService(ns);
    nMgr.cancel(notifyId);
}

Count the number occurrences of a character in a string

Python-3.x:

"aabc".count("a")

str.count(sub[, start[, end]])

Return the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.

How do I force Postgres to use a particular index?

Assuming you're asking about the common "index hinting" feature found in many databases, PostgreSQL doesn't provide such a feature. This was a conscious decision made by the PostgreSQL team. A good overview of why and what you can do instead can be found here. The reasons are basically that it's a performance hack that tends to cause more problems later down the line as your data changes, whereas PostgreSQL's optimizer can re-evaluate the plan based on the statistics. In other words, what might be a good query plan today probably won't be a good query plan for all time, and index hints force a particular query plan for all time.

As a very blunt hammer, useful for testing, you can use the enable_seqscan and enable_indexscan parameters. See:

These are not suitable for ongoing production use. If you have issues with query plan choice, you should see the documentation for tracking down query performance issues. Don't just set enable_ params and walk away.

Unless you have a very good reason for using the index, Postgres may be making the correct choice. Why?

  • For small tables, it's faster to do sequential scans.
  • Postgres doesn't use indexes when datatypes don't match properly, you may need to include appropriate casts.
  • Your planner settings might be causing problems.

See also this old newsgroup post.

Adding Http Headers to HttpClient

When it can be the same header for all requests or you dispose the client after each request you can use the DefaultRequestHeaders.Add option:

client.DefaultRequestHeaders.Add("apikey","xxxxxxxxx");      

Python equivalent for HashMap

You need a dict:

my_dict = {'cheese': 'cake'}

Example code (from the docs):

>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True

You can read more about dictionaries here.

Appending to an object

[Javascript] After a bit of jiggery pokery, this worked for me:

 let dateEvents = (
            {
                'Count': 2,
                'Items': [
                    {
                        'LastPostedDateTime': {
                            "S": "10/16/2019 11:04:59"
                        }
                    },
                    {
                        'LastPostedDateTime': {
                            "S": "10/30/2019 21:41:39"
                        }
                    }
                ],
            }
        );
        console.log('dateEvents', dateEvents);

The problem I needed to solve was that I might have any number of events and they would all have the same name: LastPostedDateTime all that is different is the date and time.

INFO: No Spring WebApplicationInitializer types detected on classpath

I found the error: I have a library that it was built using jdk 1.6. The Spring main controller and components are in this library. And how I use jdk 1.7, It does not find the classes built in 1.6.

The solution was built all using "compiler compliance level: 1.7" and "Generated .class files compatibility: 1.6", "Source compatibility: 1.6".

I setup this option in Eclipse: Preferences\Java\Compiler.

Thanks everybody.

python plot normal distribution

I don't think there is a function that does all that in a single call. However you can find the Gaussian probability density function in scipy.stats.

So the simplest way I could come up with is:

import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm

# Plot between -10 and 10 with .001 steps.
x_axis = np.arange(-10, 10, 0.001)
# Mean = 0, SD = 2.
plt.plot(x_axis, norm.pdf(x_axis,0,2))
plt.show()

Sources:

android View not attached to window manager

After a fight with this issue, I finally end up with this workaround:

/**
 * Dismiss {@link ProgressDialog} with check for nullability and SDK version
 *
 * @param dialog instance of {@link ProgressDialog} to dismiss
 */
public void dismissProgressDialog(ProgressDialog dialog) {
    if (dialog != null && dialog.isShowing()) {

            //get the Context object that was used to great the dialog
            Context context = ((ContextWrapper) dialog.getContext()).getBaseContext();

            // if the Context used here was an activity AND it hasn't been finished or destroyed
            // then dismiss it
            if (context instanceof Activity) {

                // Api >=17
                if (!((Activity) context).isFinishing() {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                        if (!((Activity) context).isDestroyed()) {
                            dismissWithExceptionHandling(dialog);
                        }
                    } else { 
                        // Api < 17. Unfortunately cannot check for isDestroyed()
                        dismissWithExceptionHandling(dialog);
                    }
                }
            } else
                // if the Context used wasn't an Activity, then dismiss it too
                dismissWithExceptionHandling(dialog);
        }
        dialog = null;
    }
}

/**
 * Dismiss {@link ProgressDialog} with try catch
 *
 * @param dialog instance of {@link ProgressDialog} to dismiss
 */
public void dismissWithExceptionHandling(ProgressDialog dialog) {
    try {
        dialog.dismiss();
    } catch (final IllegalArgumentException e) {
        // Do nothing.
    } catch (final Exception e) {
        // Do nothing.
    } finally {
        dialog = null;
    }
}

Sometimes, good exception handling works well if there wasn't a better solution for this issue.

Adjust list style image position?

Not really. Your padding is (probably) being applied to the list item, so will only affect the actual content within the list item.

Using a combination of background and padding styles can create something that looks similar e.g.

li {
  background: url(images/bullet.gif) no-repeat left top; /* <-- change `left` & `top` too for extra control */
  padding: 3px 0px 3px 10px;
  /* reset styles (optional): */
  list-style: none;
  margin: 0;
}

You might be looking to add styling to the parent list container (ul) to position your bulleted list items, this A List Apart article has a good starting reference.

javascript regular expression to not match a word

This can be done in 2 ways:

if (str.match(/abc|def/)) {
                       ...
                    }


if (/abc|def/.test(str)) {
                        ....
                    } 

How to remove all callbacks from a Handler?

As josh527 said, handler.removeCallbacksAndMessages(null); can work.
But why?
If you have a look at the source code, you can understand it more clearly. There are 3 type of method to remove callbacks/messages from handler(the MessageQueue):

  1. remove by callback (and token)
  2. remove by message.what (and token)
  3. remove by token

Handler.java (leave some overload method)

/**
 * Remove any pending posts of Runnable <var>r</var> with Object
 * <var>token</var> that are in the message queue.  If <var>token</var> is null,
 * all callbacks will be removed.
 */
public final void removeCallbacks(Runnable r, Object token)
{
    mQueue.removeMessages(this, r, token);
}

/**
 * Remove any pending posts of messages with code 'what' and whose obj is
 * 'object' that are in the message queue.  If <var>object</var> is null,
 * all messages will be removed.
 */
public final void removeMessages(int what, Object object) {
    mQueue.removeMessages(this, what, object);
}

/**
 * Remove any pending posts of callbacks and sent messages whose
 * <var>obj</var> is <var>token</var>.  If <var>token</var> is null,
 * all callbacks and messages will be removed.
 */
public final void removeCallbacksAndMessages(Object token) {
    mQueue.removeCallbacksAndMessages(this, token);
}

MessageQueue.java do the real work:

void removeMessages(Handler h, int what, Object object) {
    if (h == null) {
        return;
    }

    synchronized (this) {
        Message p = mMessages;

        // Remove all messages at front.
        while (p != null && p.target == h && p.what == what
               && (object == null || p.obj == object)) {
            Message n = p.next;
            mMessages = n;
            p.recycleUnchecked();
            p = n;
        }

        // Remove all messages after front.
        while (p != null) {
            Message n = p.next;
            if (n != null) {
                if (n.target == h && n.what == what
                    && (object == null || n.obj == object)) {
                    Message nn = n.next;
                    n.recycleUnchecked();
                    p.next = nn;
                    continue;
                }
            }
            p = n;
        }
    }
}

void removeMessages(Handler h, Runnable r, Object object) {
    if (h == null || r == null) {
        return;
    }

    synchronized (this) {
        Message p = mMessages;

        // Remove all messages at front.
        while (p != null && p.target == h && p.callback == r
               && (object == null || p.obj == object)) {
            Message n = p.next;
            mMessages = n;
            p.recycleUnchecked();
            p = n;
        }

        // Remove all messages after front.
        while (p != null) {
            Message n = p.next;
            if (n != null) {
                if (n.target == h && n.callback == r
                    && (object == null || n.obj == object)) {
                    Message nn = n.next;
                    n.recycleUnchecked();
                    p.next = nn;
                    continue;
                }
            }
            p = n;
        }
    }
}

void removeCallbacksAndMessages(Handler h, Object object) {
    if (h == null) {
        return;
    }

    synchronized (this) {
        Message p = mMessages;

        // Remove all messages at front.
        while (p != null && p.target == h
                && (object == null || p.obj == object)) {
            Message n = p.next;
            mMessages = n;
            p.recycleUnchecked();
            p = n;
        }

        // Remove all messages after front.
        while (p != null) {
            Message n = p.next;
            if (n != null) {
                if (n.target == h && (object == null || n.obj == object)) {
                    Message nn = n.next;
                    n.recycleUnchecked();
                    p.next = nn;
                    continue;
                }
            }
            p = n;
        }
    }
}

Determine the number of lines within a text file

You can launch the "wc.exe" executable (comes with UnixUtils and does not need installation) run as an external process. It supports different line count methods (like unix vs mac vs windows).

How do I get the current time only in JavaScript

Do you mean:

var d = new Date();
var curr_hour = d.getHours();
var curr_min = d.getMinutes();

Ruby on Rails: how to render a string as HTML?

If you're on rails which utilizes Erubis — the coolest way to do it is

<%== @str >

Note the double equal sign. See related question on SO for more info.

Quickly reading very large tables as dataframes

I am reading data very quickly using the new arrow package. It appears to be in a fairly early stage.

Specifically, I am using the parquet columnar format. This converts back to a data.frame in R, but you can get even deeper speedups if you do not. This format is convenient as it can be used from Python as well.

My main use case for this is on a fairly restrained RShiny server. For these reasons, I prefer to keep data attached to the Apps (i.e., out of SQL), and therefore require small file size as well as speed.

This linked article provides benchmarking and a good overview. I have quoted some interesting points below.

https://ursalabs.org/blog/2019-10-columnar-perf/

File Size

That is, the Parquet file is half as big as even the gzipped CSV. One of the reasons that the Parquet file is so small is because of dictionary-encoding (also called “dictionary compression”). Dictionary compression can yield substantially better compression than using a general purpose bytes compressor like LZ4 or ZSTD (which are used in the FST format). Parquet was designed to produce very small files that are fast to read.

Read Speed

When controlling by output type (e.g. comparing all R data.frame outputs with each other) we see the the performance of Parquet, Feather, and FST falls within a relatively small margin of each other. The same is true of the pandas.DataFrame outputs. data.table::fread is impressively competitive with the 1.5 GB file size but lags the others on the 2.5 GB CSV.


Independent Test

I performed some independent benchmarking on a simulated dataset of 1,000,000 rows. Basically I shuffled a bunch of things around to attempt to challenge the compression. Also I added a short text field of random words and two simulated factors.

Data

library(dplyr)
library(tibble)
library(OpenRepGrid)

n <- 1000000

set.seed(1234)
some_levels1 <- sapply(1:10, function(x) paste(LETTERS[sample(1:26, size = sample(3:8, 1), replace = TRUE)], collapse = ""))
some_levels2 <- sapply(1:65, function(x) paste(LETTERS[sample(1:26, size = sample(5:16, 1), replace = TRUE)], collapse = ""))


test_data <- mtcars %>%
  rownames_to_column() %>%
  sample_n(n, replace = TRUE) %>%
  mutate_all(~ sample(., length(.))) %>%
  mutate(factor1 = sample(some_levels1, n, replace = TRUE),
         factor2 = sample(some_levels2, n, replace = TRUE),
         text = randomSentences(n, sample(3:8, n, replace = TRUE))
         )

Read and Write

Writing the data is easy.

library(arrow)

write_parquet(test_data , "test_data.parquet")

# you can also mess with the compression
write_parquet(test_data, "test_data2.parquet", compress = "gzip", compression_level = 9)

Reading the data is also easy.

read_parquet("test_data.parquet")

# this option will result in lightning fast reads, but in a different format.
read_parquet("test_data2.parquet", as_data_frame = FALSE)

I tested reading this data against a few of the competing options, and did get slightly different results than with the article above, which is expected.

benchmarking

This file is nowhere near as large as the benchmark article, so maybe that is the difference.

Tests

  • rds: test_data.rds (20.3 MB)
  • parquet2_native: (14.9 MB with higher compression and as_data_frame = FALSE)
  • parquet2: test_data2.parquet (14.9 MB with higher compression)
  • parquet: test_data.parquet (40.7 MB)
  • fst2: test_data2.fst (27.9 MB with higher compression)
  • fst: test_data.fst (76.8 MB)
  • fread2: test_data.csv.gz (23.6MB)
  • fread: test_data.csv (98.7MB)
  • feather_arrow: test_data.feather (157.2 MB read with arrow)
  • feather: test_data.feather (157.2 MB read with feather)

Observations

For this particular file, fread is actually very fast. I like the small file size from the highly compressed parquet2 test. I may invest the time to work with the native data format rather than a data.frame if I really need the speed up.

Here fst is also a great choice. I would either use the highly compressed fst format or the highly compressed parquet depending on if I needed the speed or file size trade off.

YouTube URL in Video Tag

The most straight forward answer to this question is: You can't.

Youtube doesn't output their video's in the right format, thus they can't be embedded in a
<video/> element.

There are a few solutions posted using javascript, but don't trust on those, they all need a fallback, and won't work cross-browser.

How do I write a custom init for a UIView subclass in Swift?

Here is how I do it on iOS 9 in Swift -

import UIKit

class CustomView : UIView {

    init() {
        super.init(frame: UIScreen.mainScreen().bounds);

        //for debug validation
        self.backgroundColor = UIColor.blueColor();
        print("My Custom Init");

        return;
    }

    required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented"); }
}

Here is a full project with example:

How to import an existing project from GitHub into Android Studio

Unzip the github project to a folder. Open Android Studio. Go to File -> New -> Import Project. Then choose the specific project you want to import and then click Next->Finish. It will build the Gradle automatically and'll be ready for you to use.

P.S: In some versions of Android Studio a certain error occurs-
error:package android.support.v4.app does not exist.
To fix it go to Gradle Scripts->build.gradle(Module:app) and the add the dependecies:

dependencies {      
    compile fileTree(dir: 'libs', include: ['*.jar'])  
    compile 'com.android.support:appcompat-v7:21.0.3'  
}

Enjoy working in Android Studio

How to Get the HTTP Post data in C#?

Use this:

    public void ShowAllPostBackData()
    {
        if (IsPostBack)
        {
            string[] keys = Request.Form.AllKeys;
            Literal ctlAllPostbackData = new Literal();
            ctlAllPostbackData.Text = "<div class='well well-lg' style='border:1px solid black;z-index:99999;position:absolute;'><h3>All postback data:</h3><br />";
            for (int i = 0; i < keys.Length; i++)
            {
                ctlAllPostbackData.Text += "<b>" + keys[i] + "</b>: " + Request[keys[i]] + "<br />";
            }
            ctlAllPostbackData.Text += "</div>";
            this.Controls.Add(ctlAllPostbackData);
        }
    }

Error # 1045 - Cannot Log in to MySQL server -> phpmyadmin

a number of answers; check out this one also; make sure that no instance of mysql is running, always brought by not ending your sessions well. get the super user rights with

sudo su

and type your password when prompted to (remember nothing appears when you type your password, so, don't worry just type it and press enter). Next go to your terminal and stop all mysql instances:

/etc/init.d/mysql stop

after that, go and restart the mysql services (or restart xampp as a whole). This solved my problem. All the best.

Change CSS properties on click

In your code you aren't using jquery, so, if you want to use it, yo need something like...

$('#foo').css({'background-color' : 'red', 'color' : 'white', 'font-size' : '44px'});

http://api.jquery.com/css/

Other way, if you are not using jquery, you need to do ...

document.getElementById('foo').style = 'background-color: red; color: white; font-size: 44px';

Node.js, can't open files. Error: ENOENT, stat './path/to/file'

Here the code to use your app.js

input specifies file name

res.download(__dirname+'/'+input);

IntelliJ and Tomcat.. Howto..?

You can also debug tomcat using the community edition (Unlike what is said above).

Start tomcat in debug mode, for example like this: .\catalina.bat jpda run

In intellij: Run > Edit Configurations > +

Select "Remote" Name the connection: "somename" Set "Port:" 8000 (default 5005)

Select Run > Debug "somename"

Cannot resolve the collation conflict between "SQL_Latin1_General_CP1_CI_AS" and "Latin1_General_CI_AS" in the equal to operation

Thanks to marc_s's answer I solved my original problem - inspired to take it a step further and post one approach to transforming a whole table at a time - tsql script to generate the alter column statements:

DECLARE @tableName VARCHAR(MAX)
SET @tableName = 'affiliate'
--EXEC sp_columns @tableName
SELECT  'Alter table ' + @tableName + ' alter column ' + col.name
        + CASE ( col.user_type_id )
            WHEN 231
            THEN ' nvarchar(' + CAST(col.max_length / 2 AS VARCHAR) + ') '
          END + 'collate Latin1_General_CI_AS ' + CASE ( col.is_nullable )
                                                    WHEN 0 THEN ' not null'
                                                    WHEN 1 THEN ' null'
                                                  END
FROM    sys.columns col
WHERE   object_id = OBJECT_ID(@tableName)

gets: ALTER TABLE Affiliate ALTER COLUMN myTable NVARCHAR(4000) COLLATE Latin1_General_CI_AS NOT NULL

I'll admit to being puzzled by the need to col.max_length / 2 -

Using COALESCE to handle NULL values in PostgreSQL

If you're using 0 and an empty string '' and null to designate undefined you've got a data problem. Just update the columns and fix your schema.

UPDATE pt.incentive_channel
SET   pt.incentive_marketing = NULL
WHERE pt.incentive_marketing = '';

UPDATE pt.incentive_channel
SET   pt.incentive_advertising = NULL
WHERE pt.incentive_marketing = '';

UPDATE pt.incentive_channel
SET   pt.incentive_channel = NULL
WHERE pt.incentive_marketing = '';

This will make joining and selecting substantially easier moving forward.

Difference between SelectedItem, SelectedValue and SelectedValuePath

inspired by this question I have written a blog along with the code snippet here. Below are some of the excerpts from the blog

SelectedItem – Selected Item helps to bind the actual value from the DataSource which will be displayed. This is of type object and we can bind any type derived from object type with this property. Since we will be using the MVVM binding for our combo boxes in that case this is the property which we can use to notify VM that item has been selected.

SelectedValue and SelectedValuePath – These are the two most confusing and misinterpreted properties for combobox. But these properties come to rescue when we want to bind our combobox with the value from already created object. Please check my last scenario in the following list to get a brief idea about the properties.

JavaScript Uncaught ReferenceError: jQuery is not defined; Uncaught ReferenceError: $ is not defined

You did not include jquery library. In jsfiddle its already there. Just include this line in your head section.

 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">

How to update (append to) an href in jquery?

jQuery 1.4 has a new feature for doing this, and it rules. I've forgotten what it's called, but you use it like this:

$("a.directions-link").attr("href", function(i, href) {
  return href + '?q=testing';
});

That loops over all the elements too, so no need for $.each

How can I find WPF controls by name or type?

My extensions to the code.

  • Added overloads to find one child by type, by type and criteria (predicate), find all children of type which meet the criteria
  • the FindChildren method is an iterator in addition to being an extension method for DependencyObject
  • FindChildren walks logical sub-trees also. See Josh Smith's post linked in the blog post.

Source: https://code.google.com/p/gishu-util/source/browse/#git%2FWPF%2FUtilities

Explanatory blog post : http://madcoderspeak.blogspot.com/2010/04/wpf-find-child-control-of-specific-type.html

How to dismiss AlertDialog in android

Try this:

   AlertDialog.Builder builder = new AlertDialog.Builder(this);
   AlertDialog OptionDialog = builder.create();
  background.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            SetBackground();
       OptionDialog .dismiss();
        }
    });

How to stop creating .DS_Store on Mac?

Open Terminal. Execute this command:

defaults write com.apple.desktopservices DSDontWriteNetworkStores true

Either restart the computer or log out and back in to the user account.

for more informations:

http://support.apple.com/kb/ht1629

How to use subList()

To get the last element, simply use the size of the list as the second parameter. So for example, if you have 35 files, and you want the last five, you would do:

dataList.subList(30, 35);

A guaranteed safe way to do this is:

dataList.subList(Math.max(0, first), Math.min(dataList.size(), last) );

How do I autoindent in Netbeans?

Select the lines you want to reformat (indenting), then hit Alt+Shift+F. Only the selected lines will be reformatted.

What does #defining WIN32_LEAN_AND_MEAN exclude exactly?

According the to Windows Dev Center WIN32_LEAN_AND_MEAN excludes APIs such as Cryptography, DDE, RPC, Shell, and Windows Sockets.

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

LabelEncoding worked for me (basically you've to encode your data feature-wise) (mydata is a 2d array of string datatype):

myData=np.genfromtxt(filecsv, delimiter=",", dtype ="|a20" ,skip_header=1);

from sklearn import preprocessing
le = preprocessing.LabelEncoder()
for i in range(*NUMBER OF FEATURES*):
    myData[:,i] = le.fit_transform(myData[:,i])

Scraping html tables into R data frames using the XML package

The rvest along with xml2 is another popular package for parsing html web pages.

library(rvest)
theurl <- "http://en.wikipedia.org/wiki/Brazil_national_football_team"
file<-read_html(theurl)
tables<-html_nodes(file, "table")
table1 <- html_table(tables[4], fill = TRUE)

The syntax is easier to use than the xml package and for most web pages the package provides all of the options ones needs.

Create a directory if it doesn't exist

Use the WINAPI CreateDirectory() function to create a folder.

You can use this function without checking if the directory already exists as it will fail but GetLastError() will return ERROR_ALREADY_EXISTS:

if (CreateDirectory(OutputFolder.c_str(), NULL) ||
    ERROR_ALREADY_EXISTS == GetLastError())
{
    // CopyFile(...)
}
else
{
     // Failed to create directory.
}

The code for constructing the target file is incorrect:

string(OutputFolder+CopiedFile).c_str()

this would produce "D:\testEmploi Nam.docx": there is a missing path separator between the directory and the filename. Example fix:

string(OutputFolder+"\\"+CopiedFile).c_str()

how can I login anonymously with ftp (/usr/bin/ftp)?

Anonymous FTP usage is covered by RFC 1635: How to Use Anonymous FTP:

What is Anonymous FTP?

Anonymous FTP is a means by which archive sites allow general access to their archives of information. These sites create a special account called "anonymous".

Traditionally, this special anonymous user account accepts any string as a password, although it is common to use either the password "guest" or one's electronic mail (e-mail) address. Some archive sites now explicitly ask for the user's e-mail address and will not allow login with the "guest" password. Providing an e-mail address is a courtesy that allows archive site operators to get some idea of who is using their services.

These are general recommendations, though. Each FTP server may have its own guidelines.

For sample use of the ftp command on anonymous FTP access, see appendix A:

atlas.arc.nasa.gov% ftp naic.nasa.gov
Connected to naic.nasa.gov.
220 naic.nasa.gov FTP server (Wed May 4 12:15:15 PDT 1994) ready.
Name (naic.nasa.gov:amarine): anonymous
331 Guest login ok, send your complete e-mail address as password.
Password:
230-----------------------------------------------------------------
230-Welcome to the NASA Network Applications and Info Center Archive
230-
230-     Access to NAIC's online services is also available through:
230-
230-        Gopher         - naic.nasa.gov (port 70)
230-    World-Wide-Web - http://naic.nasa.gov/naic/naic-home.html
230-
230-        If you experience any problems please send email to
230-
230-                    [email protected]
230-
230-                 or call +1 (800) 858-9947
230-----------------------------------------------------------------
230-
230-Please read the file README
230-  it was last modified on Fri Dec 10 13:06:33 1993 - 165 days ago
230 Guest login ok, access restrictions apply.
ftp> cd files/rfc
250-Please read the file README.rfc
250-  it was last modified on Fri Jul 30 16:47:29 1993 - 298 days ago
250 CWD command successful.
ftp> get rfc959.txt
200 PORT command successful.
150 Opening ASCII mode data connection for rfc959.txt (147316 bytes).
226 Transfer complete.
local: rfc959.txt remote: rfc959.txt
151249 bytes received in 0.9 seconds (1.6e+02 Kbytes/s)
ftp> quit
221 Goodbye.
atlas.arc.nasa.gov%

See also the example session at the University of Edinburgh site.

Any way to declare an array in-line?

You can directly write the array in modern Java, without an initializer. Your example is now valid. It is generally best to name the parameter anyway.

String[] array = {"blah", "hey", "yo"};

or

int[] array = {1, 2, 3};

If you have to inline, you'll need to declare the type:

functionCall(new String[]{"blah", "hey", "yo"});

or use varargs (variable arguments)

void functionCall(String...stringArray) {
    // Becomes a String[] containing any number of items or empty
}

functionCall("blah", "hey", "yo");

Hopefully Java's developers will allow implicit initialization in the future

Update: Kotlin Answer

Kotlin has made working with arrays so much easier! For most types, just use arrayOf and it will implicitly determine type. Pass nothing to leave them empty.

arrayOf("1", "2", "3") // String
arrayOf(1, 2, 3)       // Int
arrayOf(1, 2, "foo")   // Any 
arrayOf<Int>(1, 2, 3)  // Set explict type
arrayOf<String>()      // Empty String array

Primitives have utility functions. Pass nothing to leave them empty.

intArrayOf(1, 2, 3)
charArrayOf()
booleanArrayOf()
longArrayOf()
shortArrayOf()
byteArrayOf()

If you already have a Collection and wish to convert it to an array inline, simply use:

collection.toTypedArray()

If you need to coerce an array type, use:

array.toIntArray()
array.toLongArray()
array.toCharArray()
...

Do C# Timers elapse on a separate thread?

It depends. The System.Timers.Timer has two modes of operation.

If SynchronizingObject is set to an ISynchronizeInvoke instance then the Elapsed event will execute on the thread hosting the synchronizing object. Usually these ISynchronizeInvoke instances are none other than plain old Control and Form instances that we are all familiar with. So in that case the Elapsed event is invoked on the UI thread and it behaves similar to the System.Windows.Forms.Timer. Otherwise, it really depends on the specific ISynchronizeInvoke instance that was used.

If SynchronizingObject is null then the Elapsed event is invoked on a ThreadPool thread and it behaves similar to the System.Threading.Timer. In fact, it actually uses a System.Threading.Timer behind the scenes and does the marshaling operation after it receives the timer callback if needed.

How to replace a string in a SQL Server Table Column

If target column type is other than varchar/nvarchar like text, we need to cast the column value as string and then convert it as:

update URL_TABLE
set Parameters = REPLACE ( cast(Parameters as varchar(max)), 'india', 'bharat')
where URL_ID='150721_013359670'

Async/Await Class Constructor

Based on your comments, you should probably do what every other HTMLElement with asset loading does: make the constructor start a sideloading action, generating a load or error event depending on the result.

Yes, that means using promises, but it also means "doing things the same way as every other HTML element", so you're in good company. For instance:

var img = new Image();
img.onload = function(evt) { ... }
img.addEventListener("load", evt => ... );
img.onerror = function(evt) { ... }
img.addEventListener("error", evt => ... );
img.src = "some url";

this kicks off an asynchronous load of the source asset that, when it succeeds, ends in onload and when it goes wrong, ends in onerror. So, make your own class do this too:

class EMailElement extends HTMLElement {
  constructor() {
    super();
    this.uid = this.getAttribute('data-uid');
  }

  setAttribute(name, value) {
    super.setAttribute(name, value);
    if (name === 'data-uid') {
      this.uid = value;
    }
  }

  set uid(input) {
    if (!input) return;
    const uid = parseInt(input);
    // don't fight the river, go with the flow
    let getEmail = new Promise( (resolve, reject) => {
      yourDataBase.getByUID(uid, (err, result) => {
        if (err) return reject(err);
        resolve(result);
      });
    });
    // kick off the promise, which will be async all on its own
    getEmail()
    .then(result => {
      this.renderLoaded(result.message);
    })
    .catch(error => {
      this.renderError(error);
    });
  }
};

customElements.define('e-mail', EmailElement);

And then you make the renderLoaded/renderError functions deal with the event calls and shadow dom:

  renderLoaded(message) {
    const shadowRoot = this.attachShadow({mode: 'open'});
    shadowRoot.innerHTML = `
      <div class="email">A random email message has appeared. ${message}</div>
    `;
    // is there an ancient event listener?
    if (this.onload) {
      this.onload(...);
    }
    // there might be modern event listeners. dispatch an event.
    this.dispatchEvent(new Event('load', ...));
  }

  renderFailed() {
    const shadowRoot = this.attachShadow({mode: 'open'});
    shadowRoot.innerHTML = `
      <div class="email">No email messages.</div>
    `;
    // is there an ancient event listener?
    if (this.onload) {
      this.onerror(...);
    }
    // there might be modern event listeners. dispatch an event.
    this.dispatchEvent(new Event('error', ...));
  }

Also note I changed your id to a class, because unless you write some weird code to only ever allow a single instance of your <e-mail> element on a page, you can't use a unique identifier and then assign it to a bunch of elements.

Woocommerce get products

<?php
$args     = array( 'post_type' => 'product', 'category' => 34, 'posts_per_page' => -1 );
$products = get_posts( $args ); 
?>

This should grab all the products you want, I may have the post type wrong though I can't quite remember what woo-commerce uses for the post type. It will return an array of products

Executing <script> elements inserted with .innerHTML

Thanks to Larry's script, which worked perfectly well in IE10, this is what I've used:

$('#' + id)[0].innerHTML = result;
$('#' + id + " script").each(function() { this.text = this.text || $(this).text();} );

Starting a shell in the Docker Alpine container

Usually, an Alpine Linux image doesn't contain bash, Instead you can use /bin/ash, /bin/sh, ash or only sh.

/bin/ash

docker run -it --rm alpine /bin/ash

/bin/sh

docker run -it --rm alpine /bin/sh

ash

docker run -it --rm alpine ash

sh

docker run -it --rm alpine sh

I hope this information helps you.

Laravel orderBy on a relationship

It is possible to extend the relation with query functions:

<?php
public function comments()
{
    return $this->hasMany('Comment')->orderBy('column');
}

[edit after comment]

<?php
class User
{
    public function comments()
    {
        return $this->hasMany('Comment');
    }
}

class Controller
{
    public function index()
    {
        $column = Input::get('orderBy', 'defaultColumn');
        $comments = User::find(1)->comments()->orderBy($column)->get();

        // use $comments in the template
    }
}

default User model + simple Controller example; when getting the list of comments, just apply the orderBy() based on Input::get(). (be sure to do some input-checking ;) )

Why can't I find SQL Server Management Studio after installation?

It appears that SQL Server 2008 R2 can be downloaded with or without the management tools. I honestly have NO IDEA why someone would not want the management tools. But either way, the options are here:

http://www.microsoft.com/sqlserver/en/us/editions/express.aspx

and the one for 64 bit WITH the management tools (management studio) is here:

http://www.microsoft.com/sqlserver/en/us/editions/express.aspx

From the first link I presented, the 3rd and 4th include the management studio for 32 and 64 bit respectively.

Getting cursor position in Python

sudo add-apt-repository ppa:deadsnakes
sudo apt-get update
sudo apt-get install python3.5 python3.5-tk
# or 2.7, 3.6 etc
# sudo apt-get install python2.7 python2.7-tk
# mouse_position.py
import Tkinter
p=Tkinter.Tk()
print(p.winfo_pointerxy()

Or with one-liner from the command line:

python -c "import Tkinter; p=Tkinter.Tk(); print(p.winfo_pointerxy())"
(1377, 379)

MySQL SELECT AS combine two columns into one

In case of NULL columns it is better to use IF clause like this which combine the two functions of : CONCAT and COALESCE and uses special chars between the columns in result like space or '_'

SELECT FirstName , LastName , 
IF(FirstName IS NULL AND LastName IS NULL, NULL,' _ ',CONCAT(COALESCE(FirstName ,''), COALESCE(LastName ,''))) 
AS Contact_Phone FROM   TABLE1

What is the T-SQL To grant read and write access to tables in a database in SQL Server?

In SQL Server 2012, 2014:

USE mydb
GO

ALTER ROLE db_datareader ADD MEMBER MYUSER
GO
ALTER ROLE db_datawriter ADD MEMBER MYUSER
GO

In SQL Server 2008:

use mydb
go

exec sp_addrolemember db_datareader, MYUSER 
go
exec sp_addrolemember db_datawriter, MYUSER 
go

To also assign the ability to execute all Stored Procedures for a Database:

GRANT EXECUTE TO MYUSER;

To assign the ability to execute specific stored procedures:

GRANT EXECUTE ON dbo.sp_mystoredprocedure TO MYUSER;

Which Python memory profiler is recommended?

My module memory_profiler is capable of printing a line-by-line report of memory usage and works on Unix and Windows (needs psutil on this last one). Output is not very detailed but the goal is to give you an overview of where the code is consuming more memory, not an exhaustive analysis on allocated objects.

After decorating your function with @profile and running your code with the -m memory_profiler flag it will print a line-by-line report like this:

Line #    Mem usage  Increment   Line Contents
==============================================
     3                           @profile
     4      5.97 MB    0.00 MB   def my_func():
     5     13.61 MB    7.64 MB       a = [1] * (10 ** 6)
     6    166.20 MB  152.59 MB       b = [2] * (2 * 10 ** 7)
     7     13.61 MB -152.59 MB       del b
     8     13.61 MB    0.00 MB       return a

Where does linux store my syslog?

You have to tell the system what information to log and where to put the info. Logging is configured in the /etc/rsyslog.conf file, then restart rsyslog to load the new config. The default logging rules are usually in a /etc/rsyslog.d/50-default.conf file.

How do I get the current date in JavaScript?

As toISOString() will only return current UTC time , not local time. We have to make a date by using '.toString()' function to get date in yyyy-MM-dd format like

_x000D_
_x000D_
document.write(new Date(new Date().toString().split('GMT')[0]+' UTC').toISOString().split('T')[0]);
_x000D_
_x000D_
_x000D_

To get date and time into in yyyy-MM-ddTHH:mm:ss format

_x000D_
_x000D_
document.write(new Date(new Date().toString().split('GMT')[0]+' UTC').toISOString().split('.')[0]);
_x000D_
_x000D_
_x000D_

To get date and time into in yyyy-MM-dd HH:mm:ss format

_x000D_
_x000D_
document.write(new Date(new Date().toString().split('GMT')[0]+' UTC').toISOString().split('.')[0].replace('T',' '));
_x000D_
_x000D_
_x000D_

GIT_DISCOVERY_ACROSS_FILESYSTEM not set

Check whether you are actually under a github repo.

So, listing of .git/ should give you results..otherwise you may be some level outside your repo.

Now, cd to your repo and you are good to go.

Calculate percentage Javascript

You can use this

function percentage(partialValue, totalValue) {
   return (100 * partialValue) / totalValue;
} 

Example to calculate the percentage of a course progress base in their activities.

const totalActivities = 10;
const doneActivities = 2;

percentage(doneActivities, totalActivities) // Will return 20 that is 20%

What is the correct way to declare a boolean variable in Java?

Not only there is no need to declare it as false first, I would add few other improvements:

  • use boolean instead of Boolean (which can also be null for no reason)

  • assign during declaration:

    boolean isMatch = email1.equals(email2);
    
  • ...and use final keyword if you can:

    final boolean isMatch = email1.equals(email2);
    

Last but not least:

if (isMatch == true)

can be expressed as:

if (isMatch)

which renders the isMatch flag not that useful, inlining it might not hurt readability. I suggest looking for some better courses/tutorials out there...

How to create a custom attribute in C#

You start by writing a class that derives from Attribute:

public class MyCustomAttribute: Attribute
{
    public string SomeProperty { get; set; }
}

Then you could decorate anything (class, method, property, ...) with this attribute:

[MyCustomAttribute(SomeProperty = "foo bar")]
public class Foo
{

}

and finally you would use reflection to fetch it:

var customAttributes = (MyCustomAttribute[])typeof(Foo).GetCustomAttributes(typeof(MyCustomAttribute), true);
if (customAttributes.Length > 0)
{
    var myAttribute = customAttributes[0];
    string value = myAttribute.SomeProperty;
    // TODO: Do something with the value
}

You could limit the target types to which this custom attribute could be applied using the AttributeUsage attribute:

/// <summary>
/// This attribute can only be applied to classes
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public class MyCustomAttribute : Attribute

Important things to know about attributes:

  • Attributes are metadata.
  • They are baked into the assembly at compile-time which has very serious implications of how you could set their properties. Only constant (known at compile time) values are accepted
  • The only way to make any sense and usage of custom attributes is to use Reflection. So if you don't use reflection at runtime to fetch them and decorate something with a custom attribute don't expect much to happen.
  • The time of creation of the attributes is non-deterministic. They are instantiated by the CLR and you have absolutely no control over it.

Check if property has attribute

If you are trying to do that in a Portable Class Library PCL (like me), then here is how you can do it :)

public class Foo
{
   public string A {get;set;}

   [Special]
   public string B {get;set;}   
}

var type = typeof(Foo);

var specialProperties = type.GetRuntimeProperties()
     .Where(pi => pi.PropertyType == typeof (string) 
      && pi.GetCustomAttributes<Special>(true).Any());

You can then check on the number of properties that have this special property if you need to.

Unable to open debugger port in IntelliJ

This error can happen Tomcat is already running. So make sure Tomcat isn't running in the background if you've asked Intellij to start it up ( default ).

Also, check the full output window for more errors. As a more useful error may have preceded this one ( as was the case with my configuration just now )

System.Net.WebException: The operation has timed out

It means what it says. The operation took too long to complete.

BTW, look at WebRequest.Timeout and you'll see that you've set your timeout for 1/5 second.

How do I get the fragment identifier (value after hash #) from a URL?

It's very easy. Try the below code

$(document).ready(function(){
  var hashValue = location.hash.replace(/^#/, '');  
  //do something with the value here  
});

Is there shorthand for returning a default value if None in Python?

You can use a conditional expression:

x if x is not None else some_value

Example:

In [22]: x = None

In [23]: print x if x is not None else "foo"
foo

In [24]: x = "bar"

In [25]: print x if x is not None else "foo"
bar

How do I give ASP.NET permission to write to a folder in Windows 7?

The full command would be something like below, notice the quotes

icacls "c:\inetpub\wwwroot\tmp" /grant "IIS AppPool\DefaultAppPool:F"

Getting the Facebook like/share count for a given URL

UPDATE: This solution is no longer valid. FQLs are deprecated since August 7th, 2016.


https://api.facebook.com/method/fql.query?query=select%20%20like_count%20from%20link_stat%20where%20url=%22http://www.techlila.com%22

Also http://api.facebook.com/restserver.php?method=links.getStats&urls=http://www.techlila.com will show you all the data like 'Share Count', 'Like Count' and 'Comment Count' and total of all these.

Change the URL (i.e. http://www.techlila.com) as per your need.

This is the correct URL, I'm getting right results.

EDIT (May 2017): as of v2.9 you can make a graph API call where ID is the URL and select the 'engagement' field, below is a link with the example from the graph explorer.

https://developers.facebook.com/tools/explorer/?method=GET&path=%3Fid%3Dhttp%3A%2F%2Fcomunidade.edp.pt%26fields%3Dengagement&version=v2.9

What's the strangest corner case you've seen in C# or .NET?

C# supports conversions between arrays and lists as long as the arrays are not multidimensional and there is an inheritance relation between the types and the types are reference types

object[] oArray = new string[] { "one", "two", "three" };
string[] sArray = (string[])oArray;

// Also works for IList (and IEnumerable, ICollection)
IList<string> sList = (IList<string>)oArray;
IList<object> oList = new string[] { "one", "two", "three" };

Note that this does not work:

object[] oArray2 = new int[] { 1, 2, 3 }; // Error: Cannot implicitly convert type 'int[]' to 'object[]'
int[] iArray = (int[])oArray2;            // Error: Cannot convert type 'object[]' to 'int[]'

Locking pattern for proper use of .NET MemoryCache

This is my 2nd iteration of the code. Because MemoryCache is thread safe you don't need to lock on the initial read, you can just read and if the cache returns null then do the lock check to see if you need to create the string. It greatly simplifies the code.

const string CacheKey = "CacheKey";
static readonly object cacheLock = new object();
private static string GetCachedData()
{

    //Returns null if the string does not exist, prevents a race condition where the cache invalidates between the contains check and the retreival.
    var cachedString = MemoryCache.Default.Get(CacheKey, null) as string;

    if (cachedString != null)
    {
        return cachedString;
    }

    lock (cacheLock)
    {
        //Check to see if anyone wrote to the cache while we where waiting our turn to write the new value.
        cachedString = MemoryCache.Default.Get(CacheKey, null) as string;

        if (cachedString != null)
        {
            return cachedString;
        }

        //The value still did not exist so we now write it in to the cache.
        var expensiveString = SomeHeavyAndExpensiveCalculation();
        CacheItemPolicy cip = new CacheItemPolicy()
                              {
                                  AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddMinutes(20))
                              };
        MemoryCache.Default.Set(CacheKey, expensiveString, cip);
        return expensiveString;
    }
}

EDIT: The below code is unnecessary but I wanted to leave it to show the original method. It may be useful to future visitors who are using a different collection that has thread safe reads but non-thread safe writes (almost all of classes under the System.Collections namespace is like that).

Here is how I would do it using ReaderWriterLockSlim to protect access. You need to do a kind of "Double Checked Locking" to see if anyone else created the cached item while we where waiting to to take the lock.

const string CacheKey = "CacheKey";
static readonly ReaderWriterLockSlim cacheLock = new ReaderWriterLockSlim();
static string GetCachedData()
{
    //First we do a read lock to see if it already exists, this allows multiple readers at the same time.
    cacheLock.EnterReadLock();
    try
    {
        //Returns null if the string does not exist, prevents a race condition where the cache invalidates between the contains check and the retreival.
        var cachedString = MemoryCache.Default.Get(CacheKey, null) as string;

        if (cachedString != null)
        {
            return cachedString;
        }
    }
    finally
    {
        cacheLock.ExitReadLock();
    }

    //Only one UpgradeableReadLock can exist at one time, but it can co-exist with many ReadLocks
    cacheLock.EnterUpgradeableReadLock();
    try
    {
        //We need to check again to see if the string was created while we where waiting to enter the EnterUpgradeableReadLock
        var cachedString = MemoryCache.Default.Get(CacheKey, null) as string;

        if (cachedString != null)
        {
            return cachedString;
        }

        //The entry still does not exist so we need to create it and enter the write lock
        var expensiveString = SomeHeavyAndExpensiveCalculation();
        cacheLock.EnterWriteLock(); //This will block till all the Readers flush.
        try
        {
            CacheItemPolicy cip = new CacheItemPolicy()
            {
                AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddMinutes(20))
            };
            MemoryCache.Default.Set(CacheKey, expensiveString, cip);
            return expensiveString;
        }
        finally 
        {
            cacheLock.ExitWriteLock();
        }
    }
    finally
    {
        cacheLock.ExitUpgradeableReadLock();
    }
}

What is the correct way to check for string equality in JavaScript?

always Until you fully understand the differences and implications of using the == and === operators, use the === operator since it will save you from obscure (non-obvious) bugs and WTFs. The "regular" == operator can have very unexpected results due to the type-coercion internally, so using === is always the recommended approach.

For insight into this, and other "good vs. bad" parts of Javascript read up on Mr. Douglas Crockford and his work. There's a great Google Tech Talk where he summarizes lots of good info: http://www.youtube.com/watch?v=hQVTIJBZook


Update:

The You Don't Know JS series by Kyle Simpson is excellent (and free to read online). The series goes into the commonly misunderstood areas of the language and explains the "bad parts" that Crockford suggests you avoid. By understanding them you can make proper use of them and avoid the pitfalls.

The "Up & Going" book includes a section on Equality, with this specific summary of when to use the loose (==) vs strict (===) operators:

To boil down a whole lot of details to a few simple takeaways, and help you know whether to use == or === in various situations, here are my simple rules:

  • If either value (aka side) in a comparison could be the true or false value, avoid == and use ===.
  • If either value in a comparison could be of these specific values (0, "", or [] -- empty array), avoid == and use ===.
  • In all other cases, you're safe to use ==. Not only is it safe, but in many cases it simplifies your code in a way that improves readability.

I still recommend Crockford's talk for developers who don't want to invest the time to really understand Javascript—it's good advice for a developer who only occasionally works in Javascript.

Error Handler - Exit Sub vs. End Sub

Your ProcExit label is your place where you release all the resources whether an error happened or not. For instance:

Public Sub SubA()
  On Error Goto ProcError

  Connection.Open
  Open File for Writing
  SomePreciousResource.GrabIt

ProcExit:  
  Connection.Close
  Connection = Nothing
  Close File
  SomePreciousResource.Release

  Exit Sub

ProcError:  
  MsgBox Err.Description  
  Resume ProcExit
End Sub

How to tar certain file types in all subdirectories?

find ./ -type f -name "*.php" -o -name "*.html" -printf '%P\n' |xargs tar -I 'pigz -9' -cf target.tgz

for multicore or just for one core:

find ./ -type f -name "*.php" -o -name "*.html" -printf '%P\n' |xargs tar -czf target.tgz

Changing :hover to touch/click for mobile devices

A CSS only solution for those who are having trouble with mobile touchscreen button styling.

This will fix your hover-stick / active button problems.

_x000D_
_x000D_
body, html {
  width: 600px;
}
p {
  font-size: 20px;
}

button {
  border: none;
  width: 200px;
  height: 60px;
  border-radius: 30px;
  background: #00aeff;
  font-size: 20px;
}

button:active {
  background: black;
  color: white;
}

.delayed {
  transition: all 0.2s;
  transition-delay: 300ms;
}

.delayed:active {
  transition: none;
}
_x000D_
<h1>Sticky styles for better touch screen buttons!</h1>

<button>Normal button</button>

<button class="delayed"><a href="https://www.google.com"/>Delayed style</a></button>

<p>The CSS :active psuedo style is displayed between the time when a user touches down (when finger contacts screen) on a element to the time when the touch up (when finger leaves the screen) occures.   With a typical touch-screen tap interaction, the time of which the :active psuedo style is displayed can be very small resulting in the :active state not showing or being missed by the user entirely.  This can cause issues with users not undertanding if their button presses have actually reigstered or not.</p>

<p>Having the the :active styling stick around for a few hundred more milliseconds after touch up would would improve user understanding when they have interacted with a button.</p>
_x000D_
_x000D_
_x000D_

How do you use the "WITH" clause in MySQL?

I liked @Brad's answer from this thread, but wanted a way to save the results for further processing (MySql 8):

-- May need to adjust the recursion depth first
SET @@cte_max_recursion_depth = 10000 ; -- permit deeper recursion

-- Some boundaries 
set @startDate = '2015-01-01'
    , @endDate = '2020-12-31' ; 

-- Save it to a table for later use
drop table if exists tmpDates ;
create temporary table tmpDates as      -- this has to go _before_ the "with", Duh-oh! 
    WITH RECURSIVE t as (
        select @startDate as dt
      UNION
        SELECT DATE_ADD(t.dt, INTERVAL 1 DAY) FROM t WHERE DATE_ADD(t.dt, INTERVAL 1 DAY) <= @endDate
    )
    select * FROM t     -- need this to get the "with"'s results as a "result set", into the "create"
;

-- Exists?
select * from tmpDates ;

Which produces:

dt        |
----------|
2015-01-01|
2015-01-02|
2015-01-03|
2015-01-04|
2015-01-05|
2015-01-06|

How to sum array of numbers in Ruby?

ruby 1.8.7 way is the following:

array.inject(0, &:+) 

npm install doesn't create node_modules directory

For node_modules you have to follow the below steps

1) In Command prompt -> Goto your project directory.

2) Command :npm init

3) It asks you to set up your package.json file

4) Command: npm install or npm update

How to disable compiler optimizations in gcc?

The gcc option -O enables different levels of optimization. Use -O0 to disable them and use -S to output assembly. -O3 is the highest level of optimization.

Starting with gcc 4.8 the optimization level -Og is available. It enables optimizations that do not interfere with debugging and is the recommended default for the standard edit-compile-debug cycle.

To change the dialect of the assembly to either intel or att use -masm=intel or -masm=att.

You can also enable certain optimizations manually with -fname.

Have a look at the gcc manual for much more.

Search and replace part of string in database

update VersionedFields
set Value = replace(replace(value,'<iframe','<a>iframe'), '> </iframe>','</a>')

and you do it in a single pass.

Check if element at position [x] exists in the list

int? here = (list.ElementAtOrDefault(2) != 0 ? list[2]:(int?) null);

What methods of ‘clearfix’ can I use?

My Favourite Method is to create a clearfix class in my css / scss document as below

.clearfix{
    clear:both
}

And then call it in my html document as shown below

<html>
  <div class="div-number-one">
    Some Content before the clearfix
  </div>

  <!-- Let's say we need to clearfix Here between these two divs --->
  <div class="clearfix"></div>

  <div class="div-number-two">
    Some more content after the clearfix
  </div>
</html>

Convert double to float in Java

Use dataType casting. For example:

// converting from double to float:
double someValue;
// cast someValue to float!
float newValue = (float)someValue;

Cheers!

Note:

Integers are whole numbers, e.g. 10, 400, or -5.

Floating point numbers (floats) have decimal points and decimal places, for example 12.5, and 56.7786543.

Doubles are a specific type of floating point number that have greater precision than standard floating point numbers (meaning that they are accurate to a greater number of decimal places).

Returning JSON from PHP to JavaScript?

Php has an inbuilt JSON Serialising function.

json_encode

json_encode

Please use that if you can and don't suffer Not Invented Here syndrome.

Unable to create a constant value of type Only primitive types or enumeration types are supported in this context

I had this issue and what I did and solved the problem was that I used AsEnumerable() just before my Join clause. here is my query:

List<AccountViewModel> selectedAccounts;

 using (ctx = SmallContext.GetInstance()) {
                var data = ctx.Transactions.
                    Include(x => x.Source).
                    Include(x => x.Relation).
                    AsEnumerable().
                    Join(selectedAccounts, x => x.Source.Id, y => y.Id, (x, y) => x).
                    GroupBy(x => new { Id = x.Relation.Id, Name = x.Relation.Name }).
                    ToList();
            }

I was wondering why this issue happens, and now I think It is because after you make a query via LINQ, the result will be in memory and not loaded into objects, I don't know what that state is but they are in in some transitional state I think. Then when you use AsEnumerable() or ToList(), etc, you are placing them into physical memory objects and the issue is resolving.

Using LINQ to remove elements from a List<T>

I was wondering, if there is any difference between RemoveAll and Except and the pros of using HashSet, so I have done quick performance check :)

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;

namespace ListRemoveTest
{
    class Program
    {
        private static Random random = new Random( (int)DateTime.Now.Ticks );

        static void Main( string[] args )
        {
            Console.WriteLine( "Be patient, generating data..." );

            List<string> list = new List<string>();
            List<string> toRemove = new List<string>();
            for( int x=0; x < 1000000; x++ )
            {
                string randString = RandomString( random.Next( 100 ) );
                list.Add( randString );
                if( random.Next( 1000 ) == 0 )
                    toRemove.Insert( 0, randString );
            }

            List<string> l1 = new List<string>( list );
            List<string> l2 = new List<string>( list );
            List<string> l3 = new List<string>( list );
            List<string> l4 = new List<string>( list );

            Console.WriteLine( "Be patient, testing..." );

            Stopwatch sw1 = Stopwatch.StartNew();
            l1.RemoveAll( toRemove.Contains );
            sw1.Stop();

            Stopwatch sw2 = Stopwatch.StartNew();
            l2.RemoveAll( new HashSet<string>( toRemove ).Contains );
            sw2.Stop();

            Stopwatch sw3 = Stopwatch.StartNew();
            l3 = l3.Except( toRemove ).ToList();
            sw3.Stop();

            Stopwatch sw4 = Stopwatch.StartNew();
            l4 = l4.Except( new HashSet<string>( toRemove ) ).ToList();
            sw3.Stop();


            Console.WriteLine( "L1.Len = {0}, Time taken: {1}ms", l1.Count, sw1.Elapsed.TotalMilliseconds );
            Console.WriteLine( "L2.Len = {0}, Time taken: {1}ms", l1.Count, sw2.Elapsed.TotalMilliseconds );
            Console.WriteLine( "L3.Len = {0}, Time taken: {1}ms", l1.Count, sw3.Elapsed.TotalMilliseconds );
            Console.WriteLine( "L4.Len = {0}, Time taken: {1}ms", l1.Count, sw3.Elapsed.TotalMilliseconds );

            Console.ReadKey();
        }


        private static string RandomString( int size )
        {
            StringBuilder builder = new StringBuilder();
            char ch;
            for( int i = 0; i < size; i++ )
            {
                ch = Convert.ToChar( Convert.ToInt32( Math.Floor( 26 * random.NextDouble() + 65 ) ) );
                builder.Append( ch );
            }

            return builder.ToString();
        }
    }
}

Results below:

Be patient, generating data...
Be patient, testing...
L1.Len = 985263, Time taken: 13411.8648ms
L2.Len = 985263, Time taken: 76.4042ms
L3.Len = 985263, Time taken: 340.6933ms
L4.Len = 985263, Time taken: 340.6933ms

As we can see, best option in that case is to use RemoveAll(HashSet)

java.net.URL read stream to byte[]

byte[] b = IOUtils.toByteArray((new URL( )).openStream()); //idiom

Note however, that stream is not closed in the above example.

if you want a (76-character) chunk (using commons codec)...

byte[] b = Base64.encodeBase64(IOUtils.toByteArray((new URL( )).openStream()), true);

What is causing this error - "Fatal error: Unable to find local grunt"

Install Grunt in node_modules rather than globally

Unable to find local Grunt likely means that you have installed Grunt globally.

The Grunt CLI insists that you install grunt in your local node_modules directory, so Grunt is local to your project.

This will fail:

npm install -g grunt

Do this instead:

npm install grunt --save-dev

Kill a postgresql session/connection

Case :
Fail to execute the query :

DROP TABLE dbo.t_tabelname

Solution :
a. Display query Status Activity as follow :

SELECT * FROM pg_stat_activity  ;

b. Find row where 'Query' column has contains :

'DROP TABLE dbo.t_tabelname'

c. In the same row, get value of 'PID' Column

example : 16409

d. Execute these scripts :

SELECT 
    pg_terminate_backend(25263) 
FROM 
    pg_stat_activity 
WHERE 
    -- don't kill my own connection!
    25263 <> pg_backend_pid()
    -- don't kill the connections to other databases
    AND datname = 'database_name'
    ;

console.log showing contents of array object

Json stands for JavaScript Object Notation really all json is are javascript objects so your array is in json form already. To write it out in a div you could do a bunch of things one of the easiest I think would be:

 objectDiv.innerHTML = filter;

where objectDiv is the div you want selected from the DOM using jquery. If you wanted to list parts of the array out you could access them since it is a javascript object like so:

 objectDiv.innerHTML = filter.dvals.valueToDisplay; //brand or count depending.

edit: anything you want to be a string but is not currently (which is rare javascript treats almost everything as a string) just use the toString() function built in. so line above if you needed it would be filter.dvals.valueToDisplay.toString();

second edit to clarify: this answer is in response to the OP's comments and not completely to his original question.

What is the maximum recursion depth in Python, and how to increase it?

It's to avoid a stack overflow. The Python interpreter limits the depths of recursion to help you avoid infinite recursions, resulting in stack overflows. Try increasing the recursion limit (sys.setrecursionlimit) or re-writing your code without recursion.

From the Python documentation:

sys.getrecursionlimit()

Return the current value of the recursion limit, the maximum depth of the Python interpreter stack. This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python. It can be set by setrecursionlimit().

JQuery - how to select dropdown item based on value

 $('#mySelect').val('ab').change();

 // or

 $('#mySelect').val('ab').trigger("change");

How to add text at the end of each line in Vim?

This will do it to every line in the file:

:%s/$/,/

If you want to do a subset of lines instead of the whole file, you can specify them in place of the %.

One way is to do a visual select and then type the :. It will fill in :'<,'> for you, then you type the rest of it (Notice you only need to add s/$/,/)

:'<,'>s/$/,/

How to convert "Mon Jun 18 00:00:00 IST 2012" to 18/06/2012?

java.time

The modern approach is with the java.time classes. These supplant the troublesome old legacy date-time classes such as Date, Calendar, and SimpleDateFormat.

Parse as a ZonedDateTime.

String input = "Mon Jun 18 00:00:00 IST 2012";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "E MMM dd HH:mm:ss z uuuu" )
                                       .withLocale( Locale.US );
ZonedDateTime zdt = ZonedDateTime.parse( input , f );

Extract a date-only object, a LocalDate, without any time-of-day and without any time zone.

LocalDate ld = zdt.toLocalDate();
DateTimeFormatter fLocalDate = DateTimeFormatter.ofPattern( "dd/MM/uuuu" );
String output = ld.format( fLocalDate) ;

Dump to console.

System.out.println( "input: " + input );
System.out.println( "zdt: " + zdt );
System.out.println( "ld: " + ld );
System.out.println( "output: " + output );

input: Mon Jun 18 00:00:00 IST 2012

zdt: 2012-06-18T00:00+03:00[Asia/Jerusalem]

ld: 2012-06-18

output: 18/06/2012

See this code run live in IdeOne.com.

Poor choice of format

Your format is a poor choice for data exchange: hard to read by human, hard to parse by computer, uses non-standard 3-4 letter zone codes, and assumes English.

Instead use the standard ISO 8601 formats whenever possible. The java.time classes use ISO 8601 formats by default when parsing/generating date-time values.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!). For example, your use of IST may be Irish Standard Time, Israel Standard Time (as interpreted by java.time, seen above), or India Standard Time.


About java.time

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

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

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

Where to obtain the java.time classes?

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

RegEx for validating an integer with a maximum length of 10 characters

Don't forget that integers can be negative:

^\s*-?[0-9]{1,10}\s*$

Here's the meaning of each part:

  • ^: Match must start at beginning of string
  • \s: Any whitespace character
    • *: Occurring zero or more times
  • -: The hyphen-minus character, used to denote a negative integer
    • ?: May or may not occur
  • [0-9]: Any character whose ASCII code (or Unicode code point) is between '0' and '9'
    • {1,10}: Occurring at least one, but not more than ten times
  • \s: Any whitespace character
    • *: Occurring zero or more times
  • $: Match must end at end of string

This ignores leading and trailing whitespace and would be more complex if you consider commas acceptable or if you need to count the minus sign as one of the ten allowed characters.

Is it safe to clean docker/overlay2/

Friends, to keep everything clean you can use de commands:

  • docker system prune -a && docker volume prune.

Java generics - get class?

I'm able to get the Class of the generic type this way:

class MyList<T> {
  Class<T> clazz = (Class<T>) DAOUtil.getTypeArguments(MyList.class, this.getClass()).get(0);
}

You need two functions from this file: http://code.google.com/p/hibernate-generic-dao/source/browse/trunk/dao/src/main/java/com/googlecode/genericdao/dao/DAOUtil.java

For more explanation: http://www.artima.com/weblogs/viewpost.jsp?thread=208860

PHP - Get bool to echo false when false

This is the easiest way to do this:

$text = var_export($bool_value,true);
echo $text;

or

var_export($bool_value)

If the second argument is not true, it will output the result directly.

How to kill all processes matching a name?

The safe way to do this is:

pkill -f amarok

How do I get the picture size with PIL?

Here's how you get the image size from the given URL in Python 3:

from PIL import Image
import urllib.request
from io import BytesIO

file = BytesIO(urllib.request.urlopen('http://getwallpapers.com/wallpaper/full/b/8/d/32803.jpg').read())
im = Image.open(file)
width, height = im.size

Using the "animated circle" in an ImageView while loading stuff

Simply put this block of xml in your activity layout file:

<RelativeLayout
    android:id="@+id/loadingPanel"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center" >

    <ProgressBar
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:indeterminate="true" />
</RelativeLayout>

And when you finish loading, call this one line:

findViewById(R.id.loadingPanel).setVisibility(View.GONE);

The result (and it spins too):

enter image description here

What's the right way to decode a string that has special HTML entities in it?

jQuery will encode and decode for you.

_x000D_
_x000D_
function htmlDecode(value) {_x000D_
  return $("<textarea/>").html(value).text();_x000D_
}_x000D_
_x000D_
function htmlEncode(value) {_x000D_
  return $('<textarea/>').text(value).html();_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<script>_x000D_
$(document).ready(function() {_x000D_
   $("#encoded")_x000D_
  .text(htmlEncode("<img src onerror='alert(0)'>"));_x000D_
   $("#decoded")_x000D_
  .text(htmlDecode("&lt;img src onerror='alert(0)'&gt;"));_x000D_
});_x000D_
</script>_x000D_
_x000D_
<span>htmlEncode() result:</span><br/>_x000D_
<div id="encoded"></div>_x000D_
<br/>_x000D_
<span>htmlDecode() result:</span><br/>_x000D_
<div id="decoded"></div>
_x000D_
_x000D_
_x000D_

Possible to view PHP code of a website?

By using exploits or on badly configured servers it could be possible to download your PHP source. You could however either obfuscate and/or encrypt your code (using Zend Guard, Ioncube or a similar app) if you want to make sure your source will not be readable (to be accurate, obfuscation by itself could be reversed given enough time/resources, but I haven't found an IonCube or Zend Guard decryptor yet...).

How to list all the files in a commit?

List all files in a commit tree:

git ls-tree --name-only --full-tree a21e610

Python 3 Online Interpreter / Shell

Ideone supports Python 2.6 and Python 3

Svn switch from trunk to branch

In my case, I wanted to check out a new branch that has cut recently but it's it big in size and I want to save time and internet bandwidth, as I'm in a slow metered network

so I copped the previous branch that I already checked in

I went to the working directory, and from svn info, I can see it's on the previous branch I did the following command (you can find this command from svn switch --help)

svn switch ^/branches/newBranchName

go check svn info again you can see it is becoming the newBranchName go ahead and svn up

and this how I got the new branch easily, quickly with minimum data transmitting over the internet

hope sharing my case helps and speeds up your work

R cannot be resolved - Android error

What Will said was right

R is an automatically generated class that holds the constants used to identify your >resources. If you don't have an R.java file (it would be gen/eu.mauriziopz.gps/R.java in >Eclipse with the 1.5 SDK) I would recommend closing and reopening your project or going to >Project > Build all (and selecting "Build Automatically" while there as recommended by >Josef). If that doesn't work than try making a new project, if the problem is recreated than >post here again and we'll go into more detail.

but I've found out that there was another problem that was causing the first one. The tools in the SDK directory didn't have the permissions to be executed, so it was like the didn't exist for Eclipse, thus it didn't build the R.java file.

So modifying the permission and selecting "Build Automatically" solved the problem.

Generate full SQL script from EF 5 Code First Migrations

For anyone using entity framework core ending up here. This is how you do it.

# Powershell / Package manager console
Script-Migration

# Cli 
dotnet ef migrations script

You can use the -From and -To parameter to generate an update script to update a database to a specific version.

Script-Migration -From 20190101011200_Initial-Migration -To 20190101021200_Migration-2

https://docs.microsoft.com/en-us/ef/core/managing-schemas/migrations/#generate-sql-scripts

There are several options to this command.

The from migration should be the last migration applied to the database before running the script. If no migrations have been applied, specify 0 (this is the default).

The to migration is the last migration that will be applied to the database after running the script. This defaults to the last migration in your project.

An idempotent script can optionally be generated. This script only applies migrations if they haven't already been applied to the database. This is useful if you don't exactly know what the last migration applied to the database was or if you are deploying to multiple databases that may each be at a different migration.

CASE in WHERE, SQL Server

Try this:

WHERE a.Country = (CASE WHEN @Country > 0 THEN @Country ELSE a.Country END)

How can I sanitize user input with PHP?

If you're using PostgreSQL, the input from PHP can be escaped with pg_escape_string()

 $username = pg_escape_string($_POST['username']);

From the documentation (http://php.net/manual/es/function.pg-escape-string.php):

pg_escape_string() escapes a string for querying the database. It returns an escaped string in the PostgreSQL format without quotes.

What is the purpose of shuffling and sorting phase in the reducer in Map Reduce Programming?

This is a good reading. Hope it helps. In terms of sorting you are concerning, I think it is for the merge operation in last step of Map. When map operation is done, and need to write the result to local disk, a multi-merge will be operated on the splits generated from buffer. And for a merge operation, sorting each partition in advanced is helpful.

nginx: how to create an alias url route?

server {
  server_name example.com;
  root /path/to/root;
  location / {
    # bla bla
  }
  location /demo {
    alias /path/to/root/production/folder/here;
  }
}

If you need to use try_files inside /demo you'll need to replace alias with a root and do a rewrite because of the bug explained here

How to change href attribute using JavaScript after opening the link in a new window?

Your onclick fires before the href so it will change before the page is opened, you need to make the function handle the window opening like so:

function changeLink() {
    var link = document.getElementById("mylink");

    window.open(
      link.href,
      '_blank'
    );

    link.innerHTML = "facebook";
    link.setAttribute('href', "http://facebook.com");

    return false;
}

get jquery `$(this)` id

this is the DOM element on which the event was hooked. this.id is its ID. No need to wrap it in a jQuery instance to get it, the id property reflects the attribute reliably on all browsers.

$("select").change(function() {    
    alert("Changed: " + this.id);
}

Live example

You're not doing this in your code sample, but if you were watching a container with several form elements, that would give you the ID of the container. If you want the ID of the element that triggered the event, you could get that from the event object's target property:

$("#container").change(function(event) {
    alert("Field " + event.target.id + " changed");
});

Live example

(jQuery ensures that the change event bubbles, even on IE where it doesn't natively.)

Javascript: console.log to html

You can override the default implementation of console.log()

(function () {
    var old = console.log;
    var logger = document.getElementById('log');
    console.log = function (message) {
        if (typeof message == 'object') {
            logger.innerHTML += (JSON && JSON.stringify ? JSON.stringify(message) : message) + '<br />';
        } else {
            logger.innerHTML += message + '<br />';
        }
    }
})();

Demo: Fiddle

Where is body in a nodejs http.get response?

A portion of Coffee here:

# My little helper
read_buffer = (buffer, callback) ->
  data = ''
  buffer.on 'readable', -> data += buffer.read().toString()
  buffer.on 'end', -> callback data

# So request looks like
http.get 'http://i.want.some/stuff', (res) ->
  read_buffer res, (response) ->
    # Do some things with your response
    # but don't do that exactly :D
    eval(CoffeeScript.compile response, bare: true)

And compiled

var read_buffer;

read_buffer = function(buffer, callback) {
  var data;
  data = '';
  buffer.on('readable', function() {
    return data += buffer.read().toString();
  });
  return buffer.on('end', function() {
    return callback(data);
  });
};

http.get('http://i.want.some/stuff', function(res) {
  return read_buffer(res, function(response) {
    return eval(CoffeeScript.compile(response, {
      bare: true
    }));
  });
});

Enable UTF-8 encoding for JavaScript

This is a quite old request to reply but I want to give a short answer for newcommers. I had the same problem while working on an eight-languaged site. The problem is IDE based. The solution is to use Komodo Edit as code-editor. I tried many editors until I found one which doesnt change charset-settings of my pages. Dreamweaver (or almost all of others) change all pages code-page/charset settings whenever you change it for page. When you have changes in more than one page and have changed charset of any file then clicked "Save all", all open pages (including unchanged but assumed changed by editor because of charset) are silently re-assigned the new charset and all mismatching pages are broken down. I lost months on re-translating messages again and again until I discovered that Komodo Edit keeps settings separately for each file.

List Highest Correlation Pairs from a Large Correlation Matrix in Pandas?

Use the code below to view the correlations in the descending order.

# See the correlations in descending order

corr = df.corr() # df is the pandas dataframe
c1 = corr.abs().unstack()
c1.sort_values(ascending = False)

Comparing two arrays of objects, and exclude the elements who match values into new array in JS

Just using the Array iteration methods built into JS is fine for this:

_x000D_
_x000D_
var result1 = [_x000D_
    {id:1, name:'Sandra', type:'user', username:'sandra'},_x000D_
    {id:2, name:'John', type:'admin', username:'johnny2'},_x000D_
    {id:3, name:'Peter', type:'user', username:'pete'},_x000D_
    {id:4, name:'Bobby', type:'user', username:'be_bob'}_x000D_
];_x000D_
_x000D_
var result2 = [_x000D_
    {id:2, name:'John', email:'[email protected]'},_x000D_
    {id:4, name:'Bobby', email:'[email protected]'}_x000D_
];_x000D_
_x000D_
var props = ['id', 'name'];_x000D_
_x000D_
var result = result1.filter(function(o1){_x000D_
    // filter out (!) items in result2_x000D_
    return !result2.some(function(o2){_x000D_
        return o1.id === o2.id;          // assumes unique id_x000D_
    });_x000D_
}).map(function(o){_x000D_
    // use reduce to make objects with only the required properties_x000D_
    // and map to apply this to the filtered array as a whole_x000D_
    return props.reduce(function(newo, name){_x000D_
        newo[name] = o[name];_x000D_
        return newo;_x000D_
    }, {});_x000D_
});_x000D_
_x000D_
document.body.innerHTML = '<pre>' + JSON.stringify(result, null, 4) +_x000D_
        '</pre>';
_x000D_
_x000D_
_x000D_

If you are doing this a lot, then by all means look at external libraries to help you out, but it's worth learning the basics first, and the basics will serve you well here.

How do you see recent SVN log entries?

I like to use -v for verbose mode.
It'll give you the commit id, comments and all affected files.

svn log -v --limit 4

Example of output:

I added some migrations and deleted a test xml file
------------------------------------------------------------------------
r58687 | mr_x | 2012-04-02 15:31:31 +0200 (Mon, 02 Apr 2012) | 1 line Changed
paths: 
A /trunk/java/App/src/database/support    
A /trunk/java/App/src/database/support/MIGRATE    
A /trunk/java/App/src/database/support/MIGRATE/remove_device.sql
D /trunk/java/App/src/code/test.xml

How to get names of classes inside a jar file?

You can try:

jar tvf jarfile.jar 

This will be helpful only if your jar is executable i.e. in manifest you have defined some class as main class

Access the css ":after" selector with jQuery

You can't manipulate :after, because it's not technically part of the DOM and therefore is inaccessible by any JavaScript. But you can add a new class with a new :after specified.

CSS:

.pageMenu .active.changed:after { 
/* this selector is more specific, so it takes precedence over the other :after */
    border-top-width: 22px;
    border-left-width: 22px;
    border-right-width: 22px;
}

JS:

$('.pageMenu .active').toggleClass('changed');

UPDATE: while it's impossible to directly modify the :after content, there are ways to read and/or override it using JavaScript. See "Manipulating CSS pseudo-elements using jQuery (e.g. :before and :after)" for a comprehensive list of techniques.

Define: What is a HashSet?

From application perspective, if one needs only to avoid duplicates then HashSet is what you are looking for since it's Lookup, Insert and Remove complexities are O(1) - constant. What this means it does not matter how many elements HashSet has it will take same amount of time to check if there's such element or not, plus since you are inserting elements at O(1) too it makes it perfect for this sort of thing.

How to install mysql-connector via pip

First install setuptools

sudo pip install setuptools

Then install mysql-connector

sudo pip install mysql-connector

If using Python3, then replace pip by pip3

Best way to check if MySQL results returned in PHP?

What is more logical then testing the TYPE of the result variable before processing? It is either of type 'boolean' or 'resource'. When you use a boolean for parameter with mysqli_num_rows, a warning will be generated because the function expects a resource.

$result = mysqli_query($dbs, $sql);

if(gettype($result)=='boolean'){ // test for boolean
    if($result){  // returned TRUE, e.g. in case of a DELETE sql  
        echo "SQL succeeded"; 
    } else { // returned FALSE
        echo "Error: " . mysqli_error($dbs);
    } 
} else { // must be a resource
    if(mysqli_num_rows($result)){

       // process the data    

    }
    mysqli_free_result($result);  
 }

Capturing browser logs with Selenium WebDriver using Java

As a non-java selenium user, here is the python equivalent to Margus's answer:

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities    

class ChromeConsoleLogging(object):

    def __init__(self, ):
        self.driver = None

    def setUp(self, ):
        desired = DesiredCapabilities.CHROME
        desired ['loggingPrefs'] = { 'browser':'ALL' }
        self.driver = webdriver.Chrome(desired_capabilities=desired)

    def analyzeLog(self, ):
        data = self.driver.get_log('browser')
        print(data)

    def testMethod(self, ):
        self.setUp()
        self.driver.get("http://mypage.com")
        self.analyzeLog()

Reference

Edit: Keeping Python answer in this thread because it is very similar to the Java answer and this post is returned on a Google search for the similar Python question

Correct way to work with vector of arrays

You cannot store arrays in a vector or any other container. The type of the elements to be stored in a container (called the container's value type) must be both copy constructible and assignable. Arrays are neither.

You can, however, use an array class template, like the one provided by Boost, TR1, and C++0x:

std::vector<std::array<double, 4> >

(You'll want to replace std::array with std::tr1::array to use the template included in C++ TR1, or boost::array to use the template from the Boost libraries. Alternatively, you can write your own; it's quite straightforward.)

Change header text of columns in a GridView

protected void grdDis_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            #region Dynamically Show gridView header From data base
            getAllheaderName();/*To get all Allowences master headerName*/

            TextBox txt_Days = (TextBox)grdDis.HeaderRow.FindControl("txtDays");
            txt_Days.Text = hidMonthsDays.Value;
            #endregion
        }
    }

Delete branches in Bitbucket

For deleting branch from Bitbucket,

  1. Go to Overview (Your repository > branches in the left sidebar)
  2. Click the number of branches (that should show you the list of branches)
  3. Click on the branch that you want to delete
  4. On top right corner, click the 3 dots (besides Merge button).
  5. There is the option of "Delete Branch" if you have rights.

How do you Change a Package's Log Level using Log4j?

I just encountered the issue and couldn't figure out what was going wrong even after reading all the above and everything out there. What I did was

  1. Set root logger level to WARN
  2. Set package log level to DEBUG

Each logging implementation has it's own way of setting it via properties or via code(lot of help available on this)

Irrespective of all the above I would not get the logs in my console or my log file. What I had overlooked was the below...


enter image description here


All I was doing with the above jugglery was controlling only the production of the logs(at root/package/class etc), left of the red line in above image. But I was not changing the way displaying/consumption of the logs of the same, right of the red line in above image. Handler(Consumption) is usually defaulted at INFO, therefore your precious debug statements wouldn't come through. Consumption/displaying is controlled by setting the log levels for the Handlers(ConsoleHandler/FileHandler etc..) So I went ahead and set the log levels of all my handlers to finest and everything worked.

This point was not made clear in a precise manner in any place.

I hope someone scratching their head, thinking why the properties are not working will find this bit helpful.

How do I calculate the date six months from the current date using the datetime Python module?

In this function, n can be positive or negative.

def addmonth(d, n):
    n += 1
    dd = datetime.date(d.year + n/12, d.month + n%12, 1)-datetime.timedelta(1)
    return datetime.date(dd.year, dd.month, min(d.day, dd.day))

What event handler to use for ComboBox Item Selected (Selected Item not necessarily changed)

You can try "SelectedIndexChanged", it will trigger the event even if the same item is selected.

How to exclude subdirectories in the destination while using /mir /xd switch in robocopy

The argument order seems to matter... to exclude subdirectories, I used

robocopy \\source\folder C:\destinationfolder /XD * /MIR

...and that works for me (Windows 10 copy from Windows Server 2016)

How to make HTML table cell editable?

this is actually so straight forward, this is my HTML, jQuery sample.. and it works like a charm, I build all the code using an online json data sample. cheers

<< HTML >>

<table id="myTable"></table>

<< jQuery >>

<script>
        var url = 'http://jsonplaceholder.typicode.com/posts';
        var currentEditedIndex = -1;
        $(document).ready(function () {
            $.getJSON(url,
            function (json) {
                var tr;
                tr = $('<tr/>');
                tr.append("<td>ID</td>");
                tr.append("<td>userId</td>");
                tr.append("<td>title</td>");
                tr.append("<td>body</td>");
                tr.append("<td>edit</td>");
                $('#myTable').append(tr);

                for (var i = 0; i < json.length; i++) {
                    tr = $('<tr/>');
                    tr.append("<td>" + json[i].id + "</td>");
                    tr.append("<td>" + json[i].userId + "</td>");
                    tr.append("<td>" + json[i].title + "</td>");
                    tr.append("<td>" + json[i].body + "</td>");
                    tr.append("<td><input type='button' value='edit' id='edit' onclick='myfunc(" + i + ")' /></td>");
                    $('#myTable').append(tr);
                }
            });


        });


        function myfunc(rowindex) {

            rowindex++;
            console.log(currentEditedIndex)
            if (currentEditedIndex != -1) {  //not first time to click
                cancelClick(rowindex)
            }
            else {
                cancelClick(currentEditedIndex)
            }

            currentEditedIndex = rowindex; //update the global variable to current edit location

            //get cells values
            var cell1 = ($("#myTable tr:eq(" + (rowindex) + ") td:eq(0)").text());
            var cell2 = ($("#myTable tr:eq(" + (rowindex) + ") td:eq(1)").text());
            var cell3 = ($("#myTable tr:eq(" + (rowindex) + ") td:eq(2)").text());
            var cell4 = ($("#myTable tr:eq(" + (rowindex) + ") td:eq(3)").text());

            //remove text from previous click


            //add a cancel button
            $("#myTable tr:eq(" + (rowindex) + ") td:eq(4)").append(" <input type='button' onclick='cancelClick("+rowindex+")' id='cancelBtn' value='Cancel'  />");
            $("#myTable tr:eq(" + (rowindex) + ") td:eq(4)").css("width", "200");

            //make it a text box
            $("#myTable tr:eq(" + (rowindex) + ") td:eq(0)").html(" <input type='text' id='mycustomid' value='" + cell1 + "' style='width:30px' />");
            $("#myTable tr:eq(" + (rowindex) + ") td:eq(1)").html(" <input type='text' id='mycustomuserId' value='" + cell2 + "' style='width:30px' />");
            $("#myTable tr:eq(" + (rowindex) + ") td:eq(2)").html(" <input type='text' id='mycustomtitle' value='" + cell3 + "' style='width:130px' />");
            $("#myTable tr:eq(" + (rowindex) + ") td:eq(3)").html(" <input type='text' id='mycustomedit' value='" + cell4 + "' style='width:400px' />");

        }

        //on cancel, remove the controls and remove the cancel btn
        function cancelClick(indx)
        {

            //console.log('edit is at row>> rowindex:' + currentEditedIndex);
            indx = currentEditedIndex;

            var cell1 = ($("#myTable #mycustomid").val());
            var cell2 = ($("#myTable #mycustomuserId").val());
            var cell3 = ($("#myTable #mycustomtitle").val());
            var cell4 = ($("#myTable #mycustomedit").val()); 

            $("#myTable tr:eq(" + (indx) + ") td:eq(0)").html(cell1);
            $("#myTable tr:eq(" + (indx) + ") td:eq(1)").html(cell2);
            $("#myTable tr:eq(" + (indx) + ") td:eq(2)").html(cell3);
            $("#myTable tr:eq(" + (indx) + ") td:eq(3)").html(cell4);
            $("#myTable tr:eq(" + (indx) + ") td:eq(4)").find('#cancelBtn').remove();
        }



    </script>

How to set DialogFragment's width and height?

One way to control your DialogFragment's width and height is to make sure its dialog respects your view's width and height if their value is WRAP_CONTENT.

Using ThemeOverlay.AppCompat.Dialog

One simple way to achieve this is to make use of the ThemeOverlay.AppCompat.Dialog style that's included in Android Support Library.

DialogFragment with Dialog:

@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    LayoutInflater inflater = LayoutInflater.from(getContext());
    View view = inflater.inflate(R.layout.dialog_view, null);

    Dialog dialog = new Dialog(getContext(), R.style.ThemeOverlay_AppCompat_Dialog);
    dialog.setContentView(view);
    return dialog;
}

DialogFragment with AlertDialog (caveat: minHeight="48dp"):

@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    LayoutInflater inflater = LayoutInflater.from(getContext());
    View view = inflater.inflate(R.layout.dialog_view, null);

    AlertDialog.Builder builder = new AlertDialog.Builder(getContext(), R.style.ThemeOverlay_AppCompat_Dialog);
    builder.setView(view);
    return builder.create();
}

You can also set ThemeOverlay.AppCompat.Dialog as the default theme when creating your dialogs, by adding it to your app's xml theme.
Be careful, as many dialogs do need the default minimum width to look good.

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- For Android Dialog. -->
    <item name="android:dialogTheme">@style/ThemeOverlay.AppCompat.Dialog</item>

    <!-- For Android AlertDialog. -->
    <item name="android:alertDialogTheme">@style/ThemeOverlay.AppCompat.Dialog</item>

    <!-- For AppCompat AlertDialog. -->
    <item name="alertDialogTheme">@style/ThemeOverlay.AppCompat.Dialog</item>

    <!-- Other attributes. -->
</style>

DialogFragment with Dialog, making use of android:dialogTheme:

@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    LayoutInflater inflater = LayoutInflater.from(getContext());
    View view = inflater.inflate(R.layout.dialog_view, null);

    Dialog dialog = new Dialog(getContext());
    dialog.setContentView(view);
    return dialog;
}

DialogFragment with AlertDialog, making use of android:alertDialogTheme or alertDialogTheme (caveat: minHeight="48dp"):

@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    LayoutInflater inflater = LayoutInflater.from(getContext());
    View view = inflater.inflate(R.layout.dialog_view, null);

    AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
    builder.setView(view);
    return builder.create();
}

Bonus

On Older Android APIs, Dialogs seem to have some width issues, because of their title (even if you don't set one).
If you don't want to use ThemeOverlay.AppCompat.Dialog style and your Dialog doesn't need a title (or has a custom one), you might want to disable it:

@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    LayoutInflater inflater = LayoutInflater.from(getContext());
    View view = inflater.inflate(R.layout.dialog_view, null);

    Dialog dialog = new Dialog(getContext());
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(view);
    return dialog;
}

Outdated answer, won't work in most cases

I was trying to make the dialog respect the width and height of my layout, without specifying a fixed size programmatically.

I figured that android:windowMinWidthMinor and android:windowMinWidthMajor were causing the problem. Even though they were not included in the theme of my Activity or Dialog, they were still being applied to the Activity theme, somehow.

I came up with three possible solutions.

Solution 1: create a custom dialog theme and use it when creating the dialog in the DialogFragment.

<style name="Theme.Material.Light.Dialog.NoMinWidth" parent="android:Theme.Material.Light.Dialog">
    <item name="android:windowMinWidthMinor">0dip</item>
    <item name="android:windowMinWidthMajor">0dip</item>
</style>
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    return new Dialog(getActivity(), R.style.Theme_Material_Light_Dialog_NoMinWidth);
}

Solution 2: create a custom theme to be used in a ContextThemeWrapper that will serve as Context for the dialog. Use this if you don't want to create a custom dialog theme (for instance, when you want to use the theme specified by android:dialogTheme).

<style name="Theme.Window.NoMinWidth" parent="">
    <item name="android:windowMinWidthMinor">0dip</item>
    <item name="android:windowMinWidthMajor">0dip</item>
</style>
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    return new Dialog(new ContextThemeWrapper(getActivity(), R.style.Theme_Window_NoMinWidth), getTheme());
}

Solution 3 (with an AlertDialog): enforce android:windowMinWidthMinor and android:windowMinWidthMajor into the ContextThemeWrapper created by the AlertDialog$Builder.

<style name="Theme.Window.NoMinWidth" parent="">
    <item name="android:windowMinWidthMinor">0dip</item>
    <item name="android:windowMinWidthMajor">0dip</item>
</style>
@Override
public final Dialog onCreateDialog(Bundle savedInstanceState) {
    View view = new View(); // Inflate your view here.
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setView(view);
    // Make sure the dialog width works as WRAP_CONTENT.
    builder.getContext().getTheme().applyStyle(R.style.Theme_Window_NoMinWidth, true);
    return builder.create();
}

How can I change the Y-axis figures into percentages in a barplot?

Use:

+ scale_y_continuous(labels = scales::percent)

Or, to specify formatting parameters for the percent:

+ scale_y_continuous(labels = scales::percent_format(accuracy = 1))

(the command labels = percent is obsolete since version 2.2.1 of ggplot2)

How to select all the columns of a table except one column?

This is not a generic solution, but some databases allow you to use regular expressions to specify the columns.

For instance, in the case of Hive, the following query selects all columns except ds and hr:

SELECT `(ds|hr)?+.+` FROM sales

https://cwiki.apache.org/confluence/display/Hive/LanguageManual+Select#LanguageManualSelect-REGEXColumnSpecification

Javascript validation: Block special characters

Try this one, this function allows alphanumeric and spaces:

function alpha(e) {
    var k;
    document.all ? k = e.keyCode : k = e.which;
    return ((k > 64 && k < 91) || (k > 96 && k < 123) || k == 8 || k == 32 || (k >= 48 && k <= 57));
}

in your html:

<input type="text" name="name"  onkeypress="return alpha(event)"/>

Should operator<< be implemented as a friend or as a member function?

operator<< implemented as a friend function:

#include <iostream>
#include <string>
using namespace std;

class Samp
{
public:
    int ID;
    string strName; 
    friend std::ostream& operator<<(std::ostream &os, const Samp& obj);
};
 std::ostream& operator<<(std::ostream &os, const Samp& obj)
    {
        os << obj.ID<< “ ” << obj.strName;
        return os;
    }

int main()
{
   Samp obj, obj1;
    obj.ID = 100;
    obj.strName = "Hello";
    obj1=obj;
    cout << obj <<endl<< obj1;

} 

OUTPUT:
100 Hello
100 Hello

This can be a friend function only because the object is on the right hand side of operator<< and argument cout is on the left hand side. So this can't be a member function to the class, it can only be a friend function.

Using UPDATE in stored procedure with optional parameters

UPDATE tbl_ClientNotes 
SET ordering=@ordering, title=@title, content=@content 
WHERE id=@id 
AND @ordering IS NOT NULL
AND @title IS NOT NULL
AND @content IS NOT NULL

Or if you meant you only want to update individual columns you would use the post above mine. I read it as do not update if any values are null

How to move a file?

For either the os.rename or shutil.move you will need to import the module. No * character is necessary to get all the files moved.

We have a folder at /opt/awesome called source with one file named awesome.txt.

in /opt/awesome
? ? ls
source
? ? ls source
awesome.txt

python 
>>> source = '/opt/awesome/source'
>>> destination = '/opt/awesome/destination'
>>> import os
>>> os.rename(source, destination)
>>> os.listdir('/opt/awesome')
['destination']

We used os.listdir to see that the folder name in fact changed. Here's the shutil moving the destination back to source.

>>> import shutil
>>> shutil.move(destination, source)
>>> os.listdir('/opt/awesome/source')
['awesome.txt']

This time I checked inside the source folder to be sure the awesome.txt file I created exists. It is there :)

Now we have moved a folder and its files from a source to a destination and back again.

File Upload to HTTP server in iphone programming

Try this.. very easy to understand & implementation...

You can download sample code directly here https://github.com/Tech-Dev-Mobile/Json-Sample

- (void)simpleJsonParsingPostMetod
{

#warning set webservice url and parse POST method in JSON
    //-- Temp Initialized variables
    NSString *first_name;
    NSString *image_name;
    NSData *imageData;

    //-- Convert string into URL
    NSString *urlString = [NSString stringWithFormat:@"demo.com/your_server_db_name/service/link"];
    NSMutableURLRequest *request =[[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:urlString]];
    [request setHTTPMethod:@"POST"];

    NSString *boundary = @"14737809831466499882746641449";
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"];

    //-- Append data into posr url using following method
    NSMutableData *body = [NSMutableData data];


    //-- For Sending text

        //-- "firstname" is keyword form service
        //-- "first_name" is the text which we have to send
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",@"firstname"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"%@",first_name] dataUsingEncoding:NSUTF8StringEncoding]];


    //-- For sending image into service if needed (send image as imagedata)

        //-- "image_name" is file name of the image (we can set custom name)
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

    [body appendData:[[NSString stringWithFormat:@"Content-Disposition:form-data; name=\"file\"; filename=\"%@\"\r\n",image_name] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[NSData dataWithData:imageData]];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];


    //-- Sending data into server through URL
    [request setHTTPBody:body];

    //-- Getting response form server
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

    //-- JSON Parsing with response data
    NSDictionary *result = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil];
    NSLog(@"Result = %@",result);
}

Close iOS Keyboard by touching anywhere using Swift

I found the best solution included the accepted answer from @Esqarrouth, with some adjustments:

extension UIViewController {
    func hideKeyboardWhenTappedAround() {
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboardView")
        tap.cancelsTouchesInView = false
        view.addGestureRecognizer(tap)
    }

    func dismissKeyboardView() {
        view.endEditing(true)
    }
}

The line tap.cancelsTouchesInView = false was critical: it ensures that the UITapGestureRecognizer does not prevent other elements on the view from receiving user interaction.

The method dismissKeyboard() was changed to the slightly less elegant dismissKeyboardView(). This is because in my project's fairly old codebase, there were numerous times where dismissKeyboard() was already used (I imagine this is not uncommon), causing compiler issues.

Then, as above, this behaviour can be enabled in individual View Controllers:

override func viewDidLoad() {
    super.viewDidLoad()
    self.hideKeyboardWhenTappedAround() 
}

How to autowire RestTemplate using annotations

Errors you'll see if a RestTemplate isn't defined

Consider defining a bean of type 'org.springframework.web.client.RestTemplate' in your configuration.

or

No qualifying bean of type [org.springframework.web.client.RestTemplate] found

How to define a RestTemplate via annotations

Depending on which technologies you're using and what versions will influence how you define a RestTemplate in your @Configuration class.

Spring >= 4 without Spring Boot

Simply define an @Bean:

@Bean
public RestTemplate restTemplate() {
    return new RestTemplate();
}

Spring Boot <= 1.3

No need to define one, Spring Boot automatically defines one for you.

Spring Boot >= 1.4

Spring Boot no longer automatically defines a RestTemplate but instead defines a RestTemplateBuilder allowing you more control over the RestTemplate that gets created. You can inject the RestTemplateBuilder as an argument in your @Bean method to create a RestTemplate:

@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
   // Do any additional configuration here
   return builder.build();
}

Using it in your class

@Autowired
private RestTemplate restTemplate;

or

@Inject
private RestTemplate restTemplate;

AngularJS access scope from outside js function

I'm newbie, so sorry if is a bad practice. Based on the chosen answer, I did this function:

function x_apply(selector, variable, value) {
    var scope = angular.element( $(selector) ).scope();
    scope.$apply(function(){
        scope[variable] = value;
    });
}

I'm using it this way:

x_apply('#fileuploader', 'thereisfiles', true);

By the way, sorry for my english

Limiting floats to two decimal points

The answers I saw didn't work with the float(52.15) case. After some tests, there is the solution that I'm using:

import decimal
        
def value_to_decimal(value, decimal_places):
    decimal.getcontext().rounding = decimal.ROUND_HALF_UP  # define rounding method
    return decimal.Decimal(str(float(value))).quantize(decimal.Decimal('1e-{}'.format(decimal_places)))

(The conversion of the 'value' to float and then string is very important, that way, 'value' can be of the type float, decimal, integer or string!)

Hope this helps anyone.

Casting interfaces for deserialization in JSON.NET

@SamualDavis provided a great solution in a related question, which I'll summarize here.

If you have to deserialize a JSON stream into a concrete class that has interface properties, you can include the concrete classes as parameters to a constructor for the class! The NewtonSoft deserializer is smart enough to figure out that it needs to use those concrete classes to deserialize the properties.

Here is an example:

public class Visit : IVisit
{
    /// <summary>
    /// This constructor is required for the JSON deserializer to be able
    /// to identify concrete classes to use when deserializing the interface properties.
    /// </summary>
    public Visit(MyLocation location, Guest guest)
    {
        Location = location;
        Guest = guest;
    }
    public long VisitId { get; set; }
    public ILocation Location { get;  set; }
    public DateTime VisitDate { get; set; }
    public IGuest Guest { get; set; }
}

store and retrieve a class object in shared preference

Yes .You can store and retrive the object using Sharedpreference

Using %s in C correctly - very basic level

Here goes:

char str[] = "This is the end";
char input[100];

printf("%s\n", str);
printf("%c\n", *str);

scanf("%99s", input);

Debug JavaScript in Eclipse

It's possible to debug JavaScript by setting breakpoints in Eclipse using the AJAX Tools Framework.

Using Linq to get the last N elements of a collection?

It is a little inefficient to take the last N of a collection using LINQ as all the above solutions require iterating across the collection. TakeLast(int n) in System.Interactive also has this problem.

If you have a list a more efficient thing to do is slice it using the following method

/// Select from start to end exclusive of end using the same semantics
/// as python slice.
/// <param name="list"> the list to slice</param>
/// <param name="start">The starting index</param>
/// <param name="end">The ending index. The result does not include this index</param>
public static List<T> Slice<T>
(this IReadOnlyList<T> list, int start, int? end = null)
{
    if (end == null)
    {
        end = list.Count();
    }
     if (start < 0)
    {
        start = list.Count + start;
    }
     if (start >= 0 && end.Value > 0 && end.Value > start)
    {
        return list.GetRange(start, end.Value - start);
    }
     if (end < 0)
    {
        return list.GetRange(start, (list.Count() + end.Value) - start);
    }
     if (end == start)
    {
        return new List<T>();
    }
     throw new IndexOutOfRangeException(
        "count = " + list.Count() + 
        " start = " + start +
        " end = " + end);
}

with

public static List<T> GetRange<T>( this IReadOnlyList<T> list, int index, int count )
{
    List<T> r = new List<T>(count);
    for ( int i = 0; i < count; i++ )
    {
        int j=i + index;
        if ( j >= list.Count )
        {
            break;
        }
        r.Add(list[j]);
    }
    return r;
}

and some test cases

[Fact]
public void GetRange()
{
    IReadOnlyList<int> l = new List<int>() { 0, 10, 20, 30, 40, 50, 60 };
     l
        .GetRange(2, 3)
        .ShouldAllBeEquivalentTo(new[] { 20, 30, 40 });
     l
        .GetRange(5, 10)
        .ShouldAllBeEquivalentTo(new[] { 50, 60 });

}
 [Fact]
void SliceMethodShouldWork()
{
    var list = new List<int>() { 1, 3, 5, 7, 9, 11 };
    list.Slice(1, 4).ShouldBeEquivalentTo(new[] { 3, 5, 7 });
    list.Slice(1, -2).ShouldBeEquivalentTo(new[] { 3, 5, 7 });
    list.Slice(1, null).ShouldBeEquivalentTo(new[] { 3, 5, 7, 9, 11 });
    list.Slice(-2)
        .Should()
        .BeEquivalentTo(new[] {9, 11});
     list.Slice(-2,-1 )
        .Should()
        .BeEquivalentTo(new[] {9});
}

Is it possible to convert char[] to char* in C?

You don't need to declare them as arrays if you want to use use them as pointers. You can simply reference pointers as if they were multi-dimensional arrays. Just create it as a pointer to a pointer and use malloc:

int i;
int M=30, N=25;
int ** buf;
buf = (int**) malloc(M * sizeof(int*));
for(i=0;i<M;i++)
    buf[i] = (int*) malloc(N * sizeof(int));

and then you can reference buf[3][5] or whatever.

How can I add a class attribute to an HTML element generated by MVC's HTML Helpers?

In order to create an anonymous type (or any type) with a property that has a reserved keyword as its name in C#, you can prepend the property name with an at sign, @:

Html.BeginForm("Foo", "Bar", FormMethod.Post, new { @class = "myclass"})

For VB.NET this syntax would be accomplished using the dot, ., which in that language is default syntax for all anonymous types:

Html.BeginForm("Foo", "Bar", FormMethod.Post, new with { .class = "myclass" })

How to get Node.JS Express to listen only on localhost?

Thanks for the info, think I see the problem. This is a bug in hive-go that only shows up when you add a host. The last lines of it are:

app.listen(3001);
console.log("... port %d in %s mode", app.address().port, app.settings.env);

When you add the host on the first line, it is crashing when it calls app.address().port.

The problem is the potentially asynchronous nature of .listen(). Really it should be doing that console.log call inside a callback passed to listen. When you add the host, it tries to do a DNS lookup, which is async. So when that line tries to fetch the address, there isn't one yet because the DNS request is running, so it crashes.

Try this:

app.listen(3001, 'localhost', function() {
  console.log("... port %d in %s mode", app.address().port, app.settings.env);
});

Bigger Glyphicons

The .btn-lg class has the following CSS in Bootstrap 3 (link):

.btn-lg {
  padding: 10px 16px;
  font-size: 18px;
  line-height: 1.33;
  border-radius: 6px;
}

If you apply the same font-size and line-height to your span (either .glyphicon-link or a newly created .glyphicons-lg if you're going to use this effect in more than one instance), you'll get a Glyphicon the same size as the large button.

Uncaught TypeError: Cannot read property 'ownerDocument' of undefined

In case you are appending to the DOM, make sure the content is compatible:

modal.find ('div.modal-body').append (content) // check content

Docker - a way to give access to a host USB or serial device?

I wanted to extend the answers already given to include support for dynamically connected devices that aren't captured with /dev/bus/usb and how to get this working when using a Windows host along with the boot2docker VM.

If you are working with Windows, you'll need to add any USB rules for devices that you want Docker to access within the VirtualBox manager. To do this you can stop the VM by running:

host:~$ docker-machine stop default

Open the VirtualBox Manager and add USB support with filters as required.

Start the boot2docker VM:

host:~$ docker-machine start default

Since the USB devices are connected to the boot2docker VM, the commands need to be run from that machine. Open up a terminal with the VM and run the docker run command:

host:~$ docker-machine ssh
docker@default:~$ docker run -it --privileged ubuntu bash

Note, when the command is run like this, then only previously connected USB devices will be captures. The volumes flag is only required if you want this to work with devices connected after the container is started. In that case, you can use:

docker@default:~$ docker run -it --privileged -v /dev:/dev ubuntu bash

Note, I had to use /dev instead of /dev/bus/usb in some cases to capture a device like /dev/sg2. I can only assume the same would be true for devices like /dev/ttyACM0 or /dev/ttyUSB0.

The docker run commands will work with a Linux host as well.

How do I mock a class without an interface?

If worse comes to worse, you can create an interface and adapter pair. You would change all uses of ConcreteClass to use the interface instead, and always pass the adapter instead of the concrete class in production code.

The adapter implements the interface, so the mock can also implement the interface.

It's more scaffolding than just making a method virtual or just adding an interface, but if you don't have access to the source for the concrete class it can get you out of a bind.

Why is JsonRequestBehavior needed?

By default Jsonresult "Deny get"

Suppose if we have method like below

  [HttpPost]
 public JsonResult amc(){}

By default it "Deny Get".

In the below method

public JsonResult amc(){}

When you need to allowget or use get ,we have to use JsonRequestBehavior.AllowGet.

public JsonResult amc()
{
 return Json(new Modle.JsonResponseData { Status = flag, Message = msg, Html = html }, JsonRequestBehavior.AllowGet);
}

Keystore change passwords

[How can I] Change the password, so I can share it with others and let them sign

Using keytool:

keytool -storepasswd -keystore /path/to/keystore
Enter keystore password:  changeit
New keystore password:  new-password
Re-enter new keystore password:  new-password

Android Completely transparent Status Bar?

You Can Use Below Code To Make Status Bar Transparent. See Images With red highlight which helps you to identify use of Below code

1]

Kotlin code snippet for your android app

Step:1 Write down code in On create Method

if (Build.VERSION.SDK_INT >= 19 && Build.VERSION.SDK_INT < 21) {
    setWindowFlag(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, true)
}
if (Build.VERSION.SDK_INT >= 19) {
    window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
}
if (Build.VERSION.SDK_INT >= 21) {
    setWindowFlag(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, false)
    window.statusBarColor = Color.TRANSPARENT
}

Step2: You Need SetWindowFlag method which describe in Below code.

private fun setWindowFlag(bits: Int, on: Boolean) {
    val win = window
    val winParams = win.attributes
    if (on) {
        winParams.flags = winParams.flags or bits
    } else {
        winParams.flags = winParams.flags and bits.inv()
    }
    win.attributes = winParams
}

Java code snippet for your android app:

Step1: Main Activity Code

if (Build.VERSION.SDK_INT >= 19 && Build.VERSION.SDK_INT < 21) {
    setWindowFlag(this, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, true);
}
if (Build.VERSION.SDK_INT >= 19) {
    getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
}

if (Build.VERSION.SDK_INT >= 21) {
    setWindowFlag(this, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, false);
    getWindow().setStatusBarColor(Color.TRANSPARENT);
}

Step2: SetWindowFlag Method

public static void setWindowFlag(Activity activity, final int bits, boolean on) {
    Window win = activity.getWindow();
    WindowManager.LayoutParams winParams = win.getAttributes();
    if (on) {
        winParams.flags |= bits;
    } else {
        winParams.flags &= ~bits;
    }
    win.setAttributes(winParams);
}

how can get index & count in vuejs

Why its printing 0,1,2...?

Because those are indexes of the items in array, and index always starts from 0 to array.length-1.

To print the item count instead of index, use index+1. Like this:

<li v-for="(catalog, index) in catalogs">this index : {{index + 1}}</li>

And to show the total count use array.length, Like this:

<p>Total Count: {{ catalogs.length }}</p>

As per DOC:

v-for also supports an optional second argument (not first) for the index of the current item.

How can I get the URL of the current tab from a Google Chrome extension?

This Solution is already TESTED.

set permissions for API in manifest.json

"permissions": [ ...
   "tabs",
    "activeTab",
    "<all_urls>"
]

On first load call function. https://developer.chrome.com/extensions/tabs#event-onActivated

chrome.tabs.onActivated.addListener((activeInfo) => {  
  sendCurrentUrl()
})

On change call function. https://developer.chrome.com/extensions/tabs#event-onSelectionChanged

chrome.tabs.onSelectionChanged.addListener(() => {
  sendCurrentUrl()
})

the function to get the URL

function sendCurrentUrl() {
  chrome.tabs.getSelected(null, function(tab) {
    var tablink = tab.url
    console.log(tablink)
  })

get dataframe row count based on conditions

For increased performance you should not evaluate the dataframe using your predicate. You can just use the outcome of your predicate directly as illustrated below:

In [1]: import pandas as pd
        import numpy as np
        df = pd.DataFrame(np.random.randn(20,4),columns=list('ABCD'))


In [2]: df.head()
Out[2]:
          A         B         C         D
0 -2.019868  1.227246 -0.489257  0.149053
1  0.223285 -0.087784 -0.053048 -0.108584
2 -0.140556 -0.299735 -1.765956  0.517803
3 -0.589489  0.400487  0.107856  0.194890
4  1.309088 -0.596996 -0.623519  0.020400

In [3]: %time sum((df['A']>0) & (df['B']>0))
CPU times: user 1.11 ms, sys: 53 µs, total: 1.16 ms
Wall time: 1.12 ms
Out[3]: 4

In [4]: %time len(df[(df['A']>0) & (df['B']>0)])
CPU times: user 1.38 ms, sys: 78 µs, total: 1.46 ms
Wall time: 1.42 ms
Out[4]: 4

Keep in mind that this technique only works for counting the number of rows that comply with your predicate.

PHP mkdir: Permission denied problem

Fix the permissions of the directory you try to create a directory in.