Programs & Examples On #Capture output

Node.js spawn child process and get terminal output live

I had a little trouble getting logging output from the "npm install" command when I spawned npm in a child process. The realtime logging of dependencies did not show in the parent console.

The simplest way to do what the original poster wants seems to be this (spawn npm on windows and log everything to parent console):

var args = ['install'];

var options = {
    stdio: 'inherit' //feed all child process logging into parent process
};

var childProcess = spawn('npm.cmd', args, options);
childProcess.on('close', function(code) {
    process.stdout.write('"npm install" finished with code ' + code + '\n');
});

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

The only reason I can think of is you are adding it as string 'now()', not function call now().
Or whatever else typo.

SELECT NOW();

to see if it returns correct value?

std::enable_if to conditionally compile a member function

For those late-comers that are looking for a solution that "just works":

#include <utility>
#include <iostream>

template< typename T >
class Y {

    template< bool cond, typename U >
    using resolvedType  = typename std::enable_if< cond, U >::type; 

    public:
        template< typename U = T > 
        resolvedType< true, U > foo() {
            return 11;
        }
        template< typename U = T >
        resolvedType< false, U > foo() {
            return 12;
        }

};


int main() {
    Y< double > y;

    std::cout << y.foo() << std::endl;
}

Compile with:

g++ -std=gnu++14 test.cpp 

Running gives:

./a.out 
11

PostgreSQL Exception Handling

To catch the error message and its code:

do $$       
begin

    create table yyy(a int);
    create table yyy(a int); -- this will cause an error

exception when others then 

    raise notice 'The transaction is in an uncommittable state. '
                 'Transaction was rolled back';

    raise notice '% %', SQLERRM, SQLSTATE;

end; $$ 
language 'plpgsql';

Haven't found the line number yet

UPDATE April, 16, 2019

As suggested by Diego Scaravaggi, for Postgres 9.2 and up, use GET STACKED DIAGNOSTICS:

do language plpgsql $$
declare
    v_state   TEXT;
    v_msg     TEXT;
    v_detail  TEXT;
    v_hint    TEXT;
    v_context TEXT;
begin

    create table yyy(a int);
    create table yyy(a int); -- this will cause an error

exception when others then 

    get stacked diagnostics
        v_state   = returned_sqlstate,
        v_msg     = message_text,
        v_detail  = pg_exception_detail,
        v_hint    = pg_exception_hint,
        v_context = pg_exception_context;

    raise notice E'Got exception:
        state  : %
        message: %
        detail : %
        hint   : %
        context: %', v_state, v_msg, v_detail, v_hint, v_context;

    raise notice E'Got exception:
        SQLSTATE: % 
        SQLERRM: %', SQLSTATE, SQLERRM;     

    raise notice '%', message_text; -- invalid. message_text is contextual to GET STACKED DIAGNOSTICS only

end; $$;

Result:

NOTICE:  Got exception:
        state  : 42P07
        message: relation "yyy" already exists
        detail : 
        hint   : 
        context: SQL statement "create table yyy(a int)"
PL/pgSQL function inline_code_block line 11 at SQL statement
NOTICE:  Got exception:
        SQLSTATE: 42P07 
        SQLERRM: relation "yyy" already exists

ERROR:  column "message_text" does not exist
LINE 1: SELECT message_text
               ^
QUERY:  SELECT message_text
CONTEXT:  PL/pgSQL function inline_code_block line 33 at RAISE
SQL state: 42703

Aside from GET STACKED DIAGNOSTICS is SQL standard-compliant, its diagnostics variables (e.g., message_text) are contextual to GSD only. So if you have a field named message_text in your table, there's no chance that GSD can interfere with your field's value.

Still no line number though.

JavaScript module pattern with example

Here https://toddmotto.com/mastering-the-module-pattern you can find the pattern thoroughly explained. I would add that the second thing about modular JavaScript is how to structure your code in multiple files. Many folks may advice you here to go with AMD, yet I can say from experience that you will end up on some point with slow page response because of numerous HTTP requests. The way out is pre-compilation of your JavaScript modules (one per file) into a single file following CommonJS standard. Take a look at samples here http://dsheiko.github.io/cjsc/

Failed to execute 'postMessage' on 'DOMWindow': https://www.youtube.com !== http://localhost:9000

Make sure you are loading from a URL such as:

https://www.youtube.com/embed/HIbAz29L-FA?modestbranding=1&playsinline=0&showinfo=0&enablejsapi=1&origin=https%3A%2F%2Fintercoin.org&widgetid=1

Note the "origin" component, as well as "enablejsapi=1". The origin must match what your domain is, and then it will be whitelisted and work.

Xcode 6 iPhone Simulator Application Support location

I would suggest that you use SimPholders to find your Simulator files. It is a menu bar item that tracks your simulator apps and lets you go directly to their folders and content. It's awesome.

PostgreSQL: Resetting password of PostgreSQL on Ubuntu

Assuming you're the administrator of the machine, Ubuntu has granted you the right to sudo to run any command as any user.
Also assuming you did not restrict the rights in the pg_hba.conf file (in the /etc/postgresql/9.1/main directory), it should contain this line as the first rule:

# Database administrative login by Unix domain socket  
local   all             postgres                                peer

(About the file location: 9.1 is the major postgres version and main the name of your "cluster". It will differ if using a newer version of postgres or non-default names. Use the pg_lsclusters command to obtain this information for your version/system).

Anyway, if the pg_hba.conf file does not have that line, edit the file, add it, and reload the service with sudo service postgresql reload.

Then you should be able to log in with psql as the postgres superuser with this shell command:

sudo -u postgres psql

Once inside psql, issue the SQL command:

ALTER USER postgres PASSWORD 'newpassword';

In this command, postgres is the name of a superuser. If the user whose password is forgotten was ritesh, the command would be:

ALTER USER ritesh PASSWORD 'newpassword';

References: PostgreSQL 9.1.13 Documentation, Chapter 19. Client Authentication

Keep in mind that you need to type postgres with a single S at the end

If leaving the password in clear text in the history of commands or the server log is a problem, psql provides an interactive meta-command to avoid that, as an alternative to ALTER USER ... PASSWORD:

\password username

It asks for the password with a double blind input, then hashes it according to the password_encryption setting and issue the ALTER USER command to the server with the hashed version of the password, instead of the clear text version.

java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver

Have you copied classes12.jar in lib folder of your web application and set the classpath in eclipse.

Right-click project in Package explorer Build path -> Add external archives...

Select your ojdbc6.jar archive

Press OK

Or

Go through this link and read and do carefully.

The library should be now referenced in the "Referenced Librairies" under the Package explorer. Now try to run your program again.

How to convert datetime format to date format in crystal report using C#?

This formula works for me:

// Converts CR TimeDate format to AssignDate for WeightedAverageDate calculation.

Date( Year({DWN00500.BUDDT}), Month({DWN00500.BUDDT}), Day({DWN00500.BUDDT}) ) - CDate(1899, 12, 30)

How to get image size (height & width) using JavaScript?

Maybe this will help others. In my case, I have a File type (that is guaranteed to be an image) & I want the image dimensions without loading it on the DOM.

General strategy: Convert File to ArrayBuffer -> Convert ArrayBuffer to base64 string -> use this as the image source with an Image class -> use naturalHeight & naturalWidth to get dimensions.

const fr = new FileReader();
fr.readAsArrayBuffer(image); // image the the 'File' object
fr.onload = () => {
  const arrayBuffer: ArrayBuffer = fr.result as ArrayBuffer;

  // Convert to base64. String.fromCharCode can hit stack overflow error if you pass
  // the entire arrayBuffer in, iteration gets around this
  let binary = '';
  const bytes = new Uint8Array(arrayBuffer);
  bytes.forEach(b => binary += String.fromCharCode(b));
  const base64Data = window.btoa(binary);

  // Create image object. Note, a default width/height MUST be given to constructor (per 
  // the docs) or naturalWidth/Height will always return 0.
  const imageObj = new Image(100, 100);
  imageObj.src = `data:${image.type};base64,${base64Data}`;
  imageObj.onload = () => {
    console.log(imageObj.naturalWidth, imageObj.naturalHeight);
  }
}

This allows you to get the image dimensions & aspect ratio all from a File without rendering it. Can easily convert the onload functions to RxJS Observables using fromEvent for a better async experience:

// fr is the file reader, this is the same as fr.onload = () => { ... }
fromEvent(fr, 'load')

C# Interfaces. Implicit implementation versus Explicit implementation

An implicit interface implementation is where you have a method with the same signature of the interface.

An explicit interface implementation is where you explicitly declare which interface the method belongs to.

interface I1
{
    void implicitExample();
}

interface I2
{
    void explicitExample();
}


class C : I1, I2
{
    void implicitExample()
    {
        Console.WriteLine("I1.implicitExample()");
    }


    void I2.explicitExample()
    {
        Console.WriteLine("I2.explicitExample()");
    }
}

MSDN: implicit and explicit interface implementations

Get image data url in JavaScript?

shiv / shim / sham

If your image(s) are already loaded (or not), this "tool" may come in handy:

Object.defineProperty
(
    HTMLImageElement.prototype,'toDataURL',
    {enumerable:false,configurable:false,writable:false,value:function(m,q)
    {
        let c=document.createElement('canvas');
        c.width=this.naturalWidth; c.height=this.naturalHeight;
        c.getContext('2d').drawImage(this,0,0); return c.toDataURL(m,q);
    }}
);

.. but why?

This has the advantage of using the "already loaded" image data, so no extra request in needed. Aditionally it lets the end-user (programmer like you) decide the CORS and/or mime-type and quality -OR- you can leave out these arguments/parameters as described in the MDN specification here.

If you have this JS loaded (prior to when it's needed), then converting to dataURL is as simple as:

examples

HTML
<img src="/yo.jpg" onload="console.log(this.toDataURL('image/jpeg'))">
JS
console.log(document.getElementById("someImgID").toDataURL());

GPU fingerprinting

If you are concerned about the "preciseness" of the bits then you can alter this tool to suit your needs as provided by @Kaiido's answer.

EXTRACT() Hour in 24 Hour format

simple and easier solution:

select extract(hour from systimestamp) from dual;

EXTRACT(HOURFROMSYSTIMESTAMP)
-----------------------------
                           16 

How to fast-forward a branch to head?

To rebase the current local tracker branch moving local changes on top of the latest remote state:

$ git fetch && git rebase

More generally, to fast-forward and drop the local changes (hard reset)*:

$ git fetch && git checkout ${the_branch_name} && git reset --hard origin/${the_branch_name}

to fast-forward and keep the local changes (rebase):

$ git fetch && git checkout ${the_branch_name} && git rebase origin/${the_branch_name}

* - to undo the change caused by unintentional hard reset first do git reflog, that displays the state of the HEAD in reverse order, find the hash the HEAD was pointing to before the reset operation (usually obvious) and hard reset the branch to that hash.

Having links relative to root?

A root-relative URL starts with a / character, to look something like <a href="/directoryInRoot/fileName.html">link text</a>.

The link you posted: <a href="fruits/index.html">Back to Fruits List</a> is linking to an html file located in a directory named fruits, the directory being in the same directory as the html page in which this link appears.

To make it a root-relative URL, change it to:

<a href="/fruits/index.html">Back to Fruits List</a>

Edited in response to question, in comments, from OP:

So doing / will make it relative to www.example.com, is there a way to specify what the root is, e.g what if i want the root to be www.example.com/fruits in www.example.com/fruits/apples/apple.html?

Yes, prefacing the URL, in the href or src attributes, with a / will make the path relative to the root directory. For example, given the html page at www.example.com/fruits/apples.html, the a of href="/vegetables/carrots.html" will link to the page www.example.com/vegetables/carrots.html.

The base tag element allows you to specify the base-uri for that page (though the base tag would have to be added to every page in which it was necessary for to use a specific base, for this I'll simply cite the W3's example:

For example, given the following BASE declaration and A declaration:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">
<HTML>
 <HEAD>
   <TITLE>Our Products</TITLE>
   <BASE href="http://www.aviary.com/products/intro.html">
 </HEAD>

 <BODY>
   <P>Have you seen our <A href="../cages/birds.gif">Bird Cages</A>?
 </BODY>
</HTML>

the relative URI "../cages/birds.gif" would resolve to:

http://www.aviary.com/cages/birds.gif

Example quoted from: http://www.w3.org/TR/html401/struct/links.html#h-12.4.

Suggested reading:

Using 'make' on OS X

If you've installed Xcode 4.3 and its Command Line Tools, just open Terminal and type the following: On Xcode 4.3, type the following in Terminal:

export PATH=$PATH:/Applications/Xcode.app/Contents/Developer/usr/bin

How to use ng-repeat for dictionaries in AngularJs?

JavaScript developers tend to refer to the above data-structure as either an object or hash instead of a Dictionary.

Your syntax above is wrong as you are initializing the users object as null. I presume this is a typo, as the code should read:

// Initialize users as a new hash.
var users = {};
users["182982"] = "...";

To retrieve all the values from a hash, you need to iterate over it using a for loop:

function getValues (hash) {
    var values = [];
    for (var key in hash) {

        // Ensure that the `key` is actually a member of the hash and not
        // a member of the `prototype`.
        // see: http://javascript.crockford.com/code.html#for%20statement
        if (hash.hasOwnProperty(key)) {
            values.push(key);
        }
    }
    return values;
};

If you plan on doing a lot of work with data-structures in JavaScript then the underscore.js library is definitely worth a look. Underscore comes with a values method which will perform the above task for you:

var values = _.values(users);

I don't use Angular myself, but I'm pretty sure there will be a convenience method build in for iterating over a hash's values (ah, there we go, Artem Andreev provides the answer above :))

Print array elements on separate lines in Bash?

Try doing this :

$ printf '%s\n' "${my_array[@]}"

The difference between $@ and $*:

  • Unquoted, the results are unspecified. In Bash, both expand to separate args and then wordsplit and globbed.

  • Quoted, "$@" expands each element as a separate argument, while "$*" expands to the args merged into one argument: "$1c$2c..." (where c is the first char of IFS).

You almost always want "$@". Same goes for "${arr[@]}".

Always quote them!

java, get set methods

your panel class don't have a constructor that accepts a string

try change

RLS_strid_panel p = new RLS_strid_panel(namn1);

to

RLS_strid_panel p = new RLS_strid_panel();
p.setName1(name1);

Select statement to find duplicates on certain fields

This is a fun solution with SQL Server 2005 that I like. I'm going to assume that by "for every record except for the first one", you mean that there is another "id" column that we can use to identify which row is "first".

SELECT id
    , field1
    , field2
    , field3
FROM
(
    SELECT id
        , field1
        , field2
        , field3
        , RANK() OVER (PARTITION BY field1, field2, field3 ORDER BY id ASC) AS [rank]
    FROM table_name
) a
WHERE [rank] > 1

How to check if one DateTime is greater than the other in C#

I'd like to demonstrate that if you convert to .Date that you don't need to worry about hours/mins/seconds etc:

    [Test]
    public void ConvertToDateWillHaveTwoDatesEqual()
    {
        DateTime d1 = new DateTime(2008, 1, 1);
        DateTime d2 = new DateTime(2008, 1, 2);
        Assert.IsTrue(d1 < d2);

        DateTime d3 = new DateTime(2008, 1, 1,7,0,0);
        DateTime d4 = new DateTime(2008, 1, 1,10,0,0);
        Assert.IsTrue(d3 < d4);
        Assert.IsFalse(d3.Date < d4.Date);
    }

How do I determine if my python shell is executing in 32bit or 64bit?

One way is to look at sys.maxsize as documented here:

$ python-32 -c 'import sys;print("%x" % sys.maxsize, sys.maxsize > 2**32)'
('7fffffff', False)
$ python-64 -c 'import sys;print("%x" % sys.maxsize, sys.maxsize > 2**32)'
('7fffffffffffffff', True)

sys.maxsize was introduced in Python 2.6. If you need a test for older systems, this slightly more complicated test should work on all Python 2 and 3 releases:

$ python-32 -c 'import struct;print( 8 * struct.calcsize("P"))'
32
$ python-64 -c 'import struct;print( 8 * struct.calcsize("P"))'
64

BTW, you might be tempted to use platform.architecture() for this. Unfortunately, its results are not always reliable, particularly in the case of OS X universal binaries.

$ arch -x86_64 /usr/bin/python2.6 -c 'import sys,platform; print platform.architecture()[0], sys.maxsize > 2**32'
64bit True
$ arch -i386 /usr/bin/python2.6 -c 'import sys,platform; print platform.architecture()[0], sys.maxsize > 2**32'
64bit False

Why is it important to override GetHashCode when Equals method is overridden?

It's not necessarily important; it depends on the size of your collections and your performance requirements and whether your class will be used in a library where you may not know the performance requirements. I frequently know my collection sizes are not very large and my time is more valuable than a few microseconds of performance gained by creating a perfect hash code; so (to get rid of the annoying warning by the compiler) I simply use:

   public override int GetHashCode()
   {
      return base.GetHashCode();
   }

(Of course I could use a #pragma to turn off the warning as well but I prefer this way.)

When you are in the position that you do need the performance than all of the issues mentioned by others here apply, of course. Most important - otherwise you will get wrong results when retrieving items from a hash set or dictionary: the hash code must not vary with the life time of an object (more accurately, during the time whenever the hash code is needed, such as while being a key in a dictionary): for example, the following is wrong as Value is public and so can be changed externally to the class during the life time of the instance, so you must not use it as the basis for the hash code:


   class A
   {
      public int Value;

      public override int GetHashCode()
      {
         return Value.GetHashCode(); //WRONG! Value is not constant during the instance's life time
      }
   }    

On the other hand, if Value can't be changed it's ok to use:


   class A
   {
      public readonly int Value;

      public override int GetHashCode()
      {
         return Value.GetHashCode(); //OK  Value is read-only and can't be changed during the instance's life time
      }
   }

How to set max and min value for Y axis


> Best Solution


  "options":{
                    scales: {
                                yAxes: [{
                                    display: true,
                                    ticks: {
                                        suggestedMin: 0, //min
                                        suggestedMax: 100 //max 
                                    }
                                }]
                            }
                    }

Setting background-image using jQuery CSS property

Here is my code:

$('body').css('background-image', 'url("/apo/1.jpg")');

Enjoy, friend

MVC4 StyleBundle not resolving images

Although Chris Baxter's answer helps with original problem, it doesn't work in my case when application is hosted in virtual directory. After investigating the options, I finished with DIY solution.

ProperStyleBundle class includes code borrowed from original CssRewriteUrlTransform to properly transform relative paths within virtual directory. It also throws if file doesn't exist and prevents reordering of files in the bundle (code taken from BetterStyleBundle).

using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Optimization;
using System.Linq;

namespace MyNamespace
{
    public class ProperStyleBundle : StyleBundle
    {
        public override IBundleOrderer Orderer
        {
            get { return new NonOrderingBundleOrderer(); }
            set { throw new Exception( "Unable to override Non-Ordered bundler" ); }
        }

        public ProperStyleBundle( string virtualPath ) : base( virtualPath ) {}

        public ProperStyleBundle( string virtualPath, string cdnPath ) : base( virtualPath, cdnPath ) {}

        public override Bundle Include( params string[] virtualPaths )
        {
            foreach ( var virtualPath in virtualPaths ) {
                this.Include( virtualPath );
            }
            return this;
        }

        public override Bundle Include( string virtualPath, params IItemTransform[] transforms )
        {
            var realPath = System.Web.Hosting.HostingEnvironment.MapPath( virtualPath );
            if( !File.Exists( realPath ) )
            {
                throw new FileNotFoundException( "Virtual path not found: " + virtualPath );
            }
            var trans = new List<IItemTransform>( transforms ).Union( new[] { new ProperCssRewriteUrlTransform( virtualPath ) } ).ToArray();
            return base.Include( virtualPath, trans );
        }

        // This provides files in the same order as they have been added. 
        private class NonOrderingBundleOrderer : IBundleOrderer
        {
            public IEnumerable<BundleFile> OrderFiles( BundleContext context, IEnumerable<BundleFile> files )
            {
                return files;
            }
        }

        private class ProperCssRewriteUrlTransform : IItemTransform
        {
            private readonly string _basePath;

            public ProperCssRewriteUrlTransform( string basePath )
            {
                _basePath = basePath.EndsWith( "/" ) ? basePath : VirtualPathUtility.GetDirectory( basePath );
            }

            public string Process( string includedVirtualPath, string input )
            {
                if ( includedVirtualPath == null ) {
                    throw new ArgumentNullException( "includedVirtualPath" );
                }
                return ConvertUrlsToAbsolute( _basePath, input );
            }

            private static string RebaseUrlToAbsolute( string baseUrl, string url )
            {
                if ( string.IsNullOrWhiteSpace( url )
                     || string.IsNullOrWhiteSpace( baseUrl )
                     || url.StartsWith( "/", StringComparison.OrdinalIgnoreCase )
                     || url.StartsWith( "data:", StringComparison.OrdinalIgnoreCase )
                    ) {
                    return url;
                }
                if ( !baseUrl.EndsWith( "/", StringComparison.OrdinalIgnoreCase ) ) {
                    baseUrl = baseUrl + "/";
                }
                return VirtualPathUtility.ToAbsolute( baseUrl + url );
            }

            private static string ConvertUrlsToAbsolute( string baseUrl, string content )
            {
                if ( string.IsNullOrWhiteSpace( content ) ) {
                    return content;
                }
                return new Regex( "url\\(['\"]?(?<url>[^)]+?)['\"]?\\)" )
                    .Replace( content, ( match =>
                                         "url(" + RebaseUrlToAbsolute( baseUrl, match.Groups["url"].Value ) + ")" ) );
            }
        }
    }
}

Use it like StyleBundle:

bundles.Add( new ProperStyleBundle( "~/styles/ui" )
    .Include( "~/Content/Themes/cm_default/style.css" )
    .Include( "~/Content/themes/custom-theme/jquery-ui-1.8.23.custom.css" )
    .Include( "~/Content/DataTables-1.9.4/media/css/jquery.dataTables.css" )
    .Include( "~/Content/DataTables-1.9.4/extras/TableTools/media/css/TableTools.css" ) );

In nodeJs is there a way to loop through an array without using array size?

    var count=0;
    let myArray = '{"1":"a","2":"b","3":"c","4":"d"}'
    var data = JSON.parse(myArray);
    for (let key in data) {
      let value =  data[key]; // get the value by key
      console.log("key: , value:", key, value);
      count = count + 1;
    }
   console.log("size:",count);

Rename multiple files based on pattern in Unix

My version of renaming mass files:

for i in *; do
    echo "mv $i $i"
done |
sed -e "s#from_pattern#to_pattern#g” > result1.sh
sh result1.sh

How to write text on a image in windows using python opencv2

Was CV_FONT_HERSHEY_SIMPLEX in cv(1)? Here's all I have available for cv2 "FONT":

FONT_HERSHEY_COMPLEX
FONT_HERSHEY_COMPLEX_SMALL
FONT_HERSHEY_DUPLEX
FONT_HERSHEY_PLAIN
FONT_HERSHEY_SCRIPT_COMPLEX
FONT_HERSHEY_SCRIPT_SIMPLEX
FONT_HERSHEY_SIMPLEX
FONT_HERSHEY_TRIPLEX
FONT_ITALIC

Dropping the 'CV_' seems to work for me.

cv2.putText(image,"Hello World!!!", (x,y), cv2.FONT_HERSHEY_SIMPLEX, 2, 255)

What is the purpose of the "final" keyword in C++11 for functions?

A use-case for the 'final' keyword that I am fond of is as follows:

// This pure abstract interface creates a way
// for unit test suites to stub-out Foo objects
class FooInterface
{
public:
   virtual void DoSomething() = 0;
private:
   virtual void DoSomethingImpl() = 0;
};

// Implement Non-Virtual Interface Pattern in FooBase using final
// (Alternatively implement the Template Pattern in FooBase using final)
class FooBase : public FooInterface
{
public:
    virtual void DoSomething() final { DoFirst(); DoSomethingImpl(); DoLast(); }
private:
    virtual void DoSomethingImpl() { /* left for derived classes to customize */ }
    void DoFirst(); // no derived customization allowed here
    void DoLast(); // no derived customization allowed here either
};

// Feel secure knowing that unit test suites can stub you out at the FooInterface level
// if necessary
// Feel doubly secure knowing that your children cannot violate your Template Pattern
// When DoSomething is called from a FooBase * you know without a doubt that
// DoFirst will execute before DoSomethingImpl, and DoLast will execute after.
class FooDerived : public FooBase
{
private:
    virtual void DoSomethingImpl() {/* customize DoSomething at this location */}
};

Dynamically change color to lighter or darker by percentage CSS (Javascript)

If you only need to change background color, this is a great approach that is futureproof - Use linear-gradient method on background image!

Check out the example below:

_x000D_
_x000D_
document_x000D_
  .getElementById('colorpicker')_x000D_
  .addEventListener('change', function(event) {_x000D_
    document_x000D_
      .documentElement_x000D_
      .style.setProperty('--color', event.target.value);_x000D_
  });
_x000D_
span {_x000D_
  display: inline-block;_x000D_
  border-radius: 20px;_x000D_
  height: 40px;_x000D_
  width: 40px;_x000D_
  vertical-align: middle;_x000D_
}_x000D_
_x000D_
.red {_x000D_
  background-color: red;_x000D_
}_x000D_
_x000D_
.red-darker {_x000D_
  background: linear-gradient(_x000D_
    to top,_x000D_
    rgba(0, 0, 0, 0.25),_x000D_
    rgba(0, 0, 0, 0.25)_x000D_
  ) red;_x000D_
}_x000D_
_x000D_
:root {_x000D_
  --color: lime;_x000D_
}_x000D_
_x000D_
.dynamic-color {_x000D_
  background-color: var(--color);_x000D_
}_x000D_
_x000D_
.dynamic-color-darker {_x000D_
  background: linear-gradient(_x000D_
    to top,_x000D_
    rgba(0, 0, 0, 0.25),_x000D_
    rgba(0, 0, 0, 0.25)_x000D_
  ) var(--color);_x000D_
}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td><strong>Static Color</strong></td>_x000D_
    <td><span class="red"></span></td>_x000D_
    <td><span class="red-darker"></span></td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td><strong>Dynamic Color</strong></td>_x000D_
    <td><span class="dynamic-color"></span></td>_x000D_
    <td><span class="dynamic-color-darker"></span></td>_x000D_
  </tr>_x000D_
</table>_x000D_
<br/>_x000D_
Change the dynamic color: <input id="colorpicker" value="#00ff00" type="color"/>
_x000D_
_x000D_
_x000D_

Credits: https://css-tricks.com/css-custom-properties-theming/

Convert file: Uri to File in Android

None of this works for me. I found this to be the working solution. But my case is specific to images.

String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().getContentResolver().query(uri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();

SQL Error: ORA-01861: literal does not match format string 01861

Try replacing the string literal for date '1989-12-09' with TO_DATE('1989-12-09','YYYY-MM-DD')

Convert unix time stamp to date in java

You can use SimlpeDateFormat to format your date like this:

long unixSeconds = 1372339860;
// convert seconds to milliseconds
Date date = new java.util.Date(unixSeconds*1000L); 
// the format of your date
SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss z"); 
// give a timezone reference for formatting (see comment at the bottom)
sdf.setTimeZone(java.util.TimeZone.getTimeZone("GMT-4")); 
String formattedDate = sdf.format(date);
System.out.println(formattedDate);

The pattern that SimpleDateFormat takes if very flexible, you can check in the javadocs all the variations you can use to produce different formatting based on the patterns you write given a specific Date. http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

  • Because a Date provides a getTime() method that returns the milliseconds since EPOC, it is required that you give to SimpleDateFormat a timezone to format the date properly acording to your timezone, otherwise it will use the default timezone of the JVM (which if well configured will anyways be right)

using lodash .groupBy. how to add your own keys for grouped output?

Here is an updated version using lodash 4 and ES6

const result = _.chain(data)
    .groupBy("color")
    .toPairs()
    .map(pair => _.zipObject(['color', 'users'], pair))
    .value();

How do I get a HttpServletRequest in my spring beans?

Better way is to autowire with a constructor:

private final HttpServletRequest httpServletRequest;

public ClassConstructor(HttpServletRequest httpServletRequest){
      this.httpServletRequest = httpServletRequest;
}

Correct way of looping through C++ arrays

Add a stopping value to the array:

#include <iostream>
using namespace std;

int main ()
{
   string texts[] = {"Apple", "Banana", "Orange", ""};
   for( unsigned int a = 0; texts[a].length(); a = a + 1 )
   {
       cout << "value of a: " << texts[a] << endl;
   }

   return 0;
}

How to uninstall/upgrade Angular CLI?

I tried all the above things, and still ng as sticking around globally. So in powershell I ran Get-Command ng, and then it became clear what my problem was. I was using yarn heavily in the past, and all the old angular cli packages were also installed globally in the yarn cache location. I deleted my yarn cache for good measure, but probably could have just updated the global angular cli via yarn. In any case, I hope this helps remind some of you that if you use yarn, then global commands like ng can also live in another path than where npm puts them.

How do I select the parent form based on which submit button is clicked?

Eileen: No, it is not var nameVal = form.inputname.val();. It should be either...

in jQuery:

// you can use IDs (easier)

var nameVal =  $(form).find('#id').val();

// or use the [name=Fieldname] to search for the field

var nameVal =  $(form).find('[name=Fieldname]').val();

Or in JavaScript:

var nameVal = this.form.FieldName.value;

Or a combination:

var nameVal = $(this.form.FieldName).val();

With jQuery, you could even loop through all of the inputs in the form:

$(form).find('input, select, textarea').each(function(){

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

  var value = this.value;
  // OR
  var value = $(this).val();
  ....
  });

AES vs Blowfish for file encryption

It is a not-often-acknowledged fact that the block size of a block cipher is also an important security consideration (though nowhere near as important as the key size).

Blowfish (and most other block ciphers of the same era, like 3DES and IDEA) have a 64 bit block size, which is considered insufficient for the large file sizes which are common these days (the larger the file, and the smaller the block size, the higher the probability of a repeated block in the ciphertext - and such repeated blocks are extremely useful in cryptanalysis).

AES, on the other hand, has a 128 bit block size. This consideration alone is justification to use AES instead of Blowfish.

Set cookie and get cookie with JavaScript

I find the following code to be much simpler than anything else:

function setCookie(name,value,days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "")  + expires + "; path=/";
}
function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}
function eraseCookie(name) {   
    document.cookie = name +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}

Now, calling functions

setCookie('ppkcookie','testcookie',7);

var x = getCookie('ppkcookie');
if (x) {
    [do something with x]
}

Source - http://www.quirksmode.org/js/cookies.html

They updated the page today so everything in the page should be latest as of now.

Angular2 http.get() ,map(), subscribe() and observable pattern - basic understanding

Concepts

Observables in short tackles asynchronous processing and events. Comparing to promises this could be described as observables = promises + events.

What is great with observables is that they are lazy, they can be canceled and you can apply some operators in them (like map, ...). This allows to handle asynchronous things in a very flexible way.

A great sample describing the best the power of observables is the way to connect a filter input to a corresponding filtered list. When the user enters characters, the list is refreshed. Observables handle corresponding AJAX requests and cancel previous in-progress requests if another one is triggered by new value in the input. Here is the corresponding code:

this.textValue.valueChanges
    .debounceTime(500)
    .switchMap(data => this.httpService.getListValues(data))
    .subscribe(data => console.log('new list values', data));

(textValue is the control associated with the filter input).

Here is a wider description of such use case: How to watch for form changes in Angular 2?.

There are two great presentations at AngularConnect 2015 and EggHead:

Christoph Burgdorf also wrote some great blog posts on the subject:

In action

In fact regarding your code, you mixed two approaches ;-) Here are they:

  • Manage the observable by your own. In this case, you're responsible to call the subscribe method on the observable and assign the result into an attribute of the component. You can then use this attribute in the view for iterate over the collection:

    @Component({
      template: `
        <h1>My Friends</h1>
        <ul>
          <li *ngFor="#frnd of result">
            {{frnd.name}} is {{frnd.age}} years old.
          </li>
        </ul>
      `,
      directive:[CORE_DIRECTIVES]
    })
    export class FriendsList implement OnInit, OnDestroy {
      result:Array<Object>; 
    
      constructor(http: Http) {
      }
    
      ngOnInit() {
        this.friendsObservable = http.get('friends.json')
                      .map(response => response.json())
                      .subscribe(result => this.result = result);
       }
    
       ngOnDestroy() {
         this.friendsObservable.dispose();
       }
    }
    

    Returns from both get and map methods are the observable not the result (in the same way than with promises).

  • Let manage the observable by the Angular template. You can also leverage the async pipe to implicitly manage the observable. In this case, there is no need to explicitly call the subscribe method.

    @Component({
      template: `
        <h1>My Friends</h1>
        <ul>
          <li *ngFor="#frnd of (result | async)">
            {{frnd.name}} is {{frnd.age}} years old.
          </li>
        </ul>
      `,
      directive:[CORE_DIRECTIVES]
    })
    export class FriendsList implement OnInit {
      result:Array<Object>; 
    
      constructor(http: Http) {
      }
    
      ngOnInit() {
        this.result = http.get('friends.json')
                      .map(response => response.json());
       }
    }
    

You can notice that observables are lazy. So the corresponding HTTP request will be only called once a listener with attached on it using the subscribe method.

You can also notice that the map method is used to extract the JSON content from the response and use it then in the observable processing.

Hope this helps you, Thierry

Convert UIImage to NSData and convert back to UIImage in Swift?

UIImage(data:imageData,scale:1.0) presuming the image's scale is 1.

In swift 4.2, use below code for get Data().

image.pngData()

Python Write bytes to file

Write bytes and Create the file if not exists:

f = open('./put/your/path/here.png', 'wb')
f.write(data)
f.close()

wb means open the file in write binary mode.

What is difference between mutable and immutable String in java

Case 1:

String str = "Good";
str = str + " Morning";

In the above code you create 3 String Objects.

  1. "Good" it goes into the String Pool.
  2. " Morning" it goes into the String Pool as well.
  3. "Good Morning" created by concatenating "Good" and " Morning". This guy goes on the Heap.

Note: Strings are always immutable. There is no, such thing as a mutable String. str is just a reference which eventually points to "Good Morning". You are actually, not working on 1 object. you have 3 distinct String Objects.


Case 2:

StringBuffer str = new StringBuffer("Good"); 
str.append(" Morning");

StringBuffer contains an array of characters. It is not same as a String. The above code adds characters to the existing array. Effectively, StringBuffer is mutable, its String representation isn't.

mongodb, replicates and error: { "$err" : "not master and slaveOk=false", "code" : 13435 }

You have to set "secondary okay" mode to let the mongo shell know that you're allowing reads from a secondary. This is to protect you and your applications from performing eventually consistent reads by accident. You can do this in the shell with:

rs.secondaryOk()

After that you can query normally from secondaries.

A note about "eventual consistency": under normal circumstances, replica set secondaries have all the same data as primaries within a second or less. Under very high load, data that you've written to the primary may take a while to replicate to the secondaries. This is known as "replica lag", and reading from a lagging secondary is known as an "eventually consistent" read, because, while the newly written data will show up at some point (barring network failures, etc), it may not be immediately available.

Edit: You only need to set secondaryOk when querying from secondaries, and only once per session.

Regex for allowing alphanumeric,-,_ and space

For me I wanted a regex which supports a strings as preceding. Basically, the motive is to support some foreign countries postal format as it should be an alphanumeric with spaces allowed.

  1. ABC123
  2. ABC 123
  3. ABC123(space)
  4. ABC 123 (space)

So I ended up by writing custom regex as below.

/^([a-z]+[\s]*[0-9]+[\s]*)+$/i

enter image description here

Here, I gave * in [\s]* as it is not mandatory to have a space. A postal code may or may not contains space in my case.

Regex to match words of a certain length

^\w{0,10}$ # allows words of up to 10 characters.
^\w{5,}$   # allows words of more than 4 characters.
^\w{5,10}$ # allows words of between 5 and 10 characters.

DataTable: How to get item value with row name and column name? (VB)

'Create a class to hold the pair...

        Public Class ColumnValue
            Public ColumnName As String
            Public ColumnValue As New Object
        End Class

    'Build the pair...

        For Each row In [YourDataTable].Rows

              For Each item As DataColumn In row.Table.Columns
                Dim rowValue As New ColumnValue
                rowValue.ColumnName = item.Caption
                rowValue.ColumnValue = row.item(item.Ordinal)
                RowValues.Add(rowValue)
                rowValue = Nothing
              Next

        ' Now you can grab the value by the column name...

        Dim results = (From p In RowValues Where p.ColumnName = "MyColumn" Select  p.ColumnValue).FirstOrDefault    

        Next

Force "git push" to overwrite remote files

git push -f is a bit destructive because it resets any remote changes that had been made by anyone else on the team. A safer option is {git push --force-with-lease}.

What {--force-with-lease} does is refuse to update a branch unless it is the state that we expect; i.e. nobody has updated the branch upstream. In practice this works by checking that the upstream ref is what we expect, because refs are hashes, and implicitly encode the chain of parents into their value. You can tell {--force-with-lease} exactly what to check for, but by default will check the current remote ref. What this means in practice is that when Alice updates her branch and pushes it up to the remote repository, the ref pointing head of the branch will be updated. Now, unless Bob does a pull from the remote, his local reference to the remote will be out of date. When he goes to push using {--force-with-lease}, git will check the local ref against the new remote and refuse to force the push. {--force-with-lease} effectively only allows you to force-push if no-one else has pushed changes up to the remote in the interim. It's {--force} with the seatbelt on.

How can I loop over entries in JSON?

To decode json, you have to pass the json string. Currently you're trying to pass an object:

>>> response = urlopen(url)
>>> response
<addinfourl at 2146100812 whose fp = <socket._fileobject object at 0x7fe8cc2c>>

You can fetch the data with response.read().

drag drop files into standard html file input

Few years later, I've built this library to do drop files into any HTML element.

You can use it like

const Droppable = require('droppable');

const droppable = new Droppable({
    element: document.querySelector('#my-droppable-element')
})

droppable.onFilesDropped((files) => {
    console.log('Files were dropped:', files);
});

// Clean up when you're done!
droppable.destroy();

How to achieve ripple animation using support library?

I made a simple class that makes ripple buttons, i never needed it in the end so its not the best, But here it is:

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.Button;

public class RippleView extends Button
{
    private float duration = 250;

    private float speed = 1;
    private float radius = 0;
    private Paint paint = new Paint();
    private float endRadius = 0;
    private float rippleX = 0;
    private float rippleY = 0;
    private int width = 0;
    private int height = 0;
    private OnClickListener clickListener = null;
    private Handler handler;
    private int touchAction;
    private RippleView thisRippleView = this;

    public RippleView(Context context)
    {
        this(context, null, 0);
    }

    public RippleView(Context context, AttributeSet attrs)
    {
        this(context, attrs, 0);
    }

    public RippleView(Context context, AttributeSet attrs, int defStyleAttr)
    {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init()
    {
        if (isInEditMode())
            return;

        handler = new Handler();
        paint.setStyle(Paint.Style.FILL);
        paint.setColor(Color.WHITE);
        paint.setAntiAlias(true);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh)
    {
        super.onSizeChanged(w, h, oldw, oldh);
        width = w;
        height = h;
    }

    @Override
    protected void onDraw(@NonNull Canvas canvas)
    {
        super.onDraw(canvas);

        if(radius > 0 && radius < endRadius)
        {
            canvas.drawCircle(rippleX, rippleY, radius, paint);
            if(touchAction == MotionEvent.ACTION_UP)
                invalidate();
        }
    }

    @Override
    public boolean onTouchEvent(@NonNull MotionEvent event)
    {
        rippleX = event.getX();
        rippleY = event.getY();

        switch(event.getAction())
        {
            case MotionEvent.ACTION_UP:
            {
                getParent().requestDisallowInterceptTouchEvent(false);
                touchAction = MotionEvent.ACTION_UP;

                radius = 1;
                endRadius = Math.max(Math.max(Math.max(width - rippleX, rippleX), rippleY), height - rippleY);
                speed = endRadius / duration * 10;
                handler.postDelayed(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        if(radius < endRadius)
                        {
                            radius += speed;
                            paint.setAlpha(90 - (int) (radius / endRadius * 90));
                            handler.postDelayed(this, 1);
                        }
                        else
                        {
                            clickListener.onClick(thisRippleView);
                        }
                    }
                }, 10);
                invalidate();
                break;
            }
            case MotionEvent.ACTION_CANCEL:
            {
                getParent().requestDisallowInterceptTouchEvent(false);
                touchAction = MotionEvent.ACTION_CANCEL;
                radius = 0;
                invalidate();
                break;
            }
            case MotionEvent.ACTION_DOWN:
            {
                getParent().requestDisallowInterceptTouchEvent(true);
                touchAction = MotionEvent.ACTION_UP;
                endRadius = Math.max(Math.max(Math.max(width - rippleX, rippleX), rippleY), height - rippleY);
                paint.setAlpha(90);
                radius = endRadius/4;
                invalidate();
                return true;
            }
            case MotionEvent.ACTION_MOVE:
            {
                if(rippleX < 0 || rippleX > width || rippleY < 0 || rippleY > height)
                {
                    getParent().requestDisallowInterceptTouchEvent(false);
                    touchAction = MotionEvent.ACTION_CANCEL;
                    radius = 0;
                    invalidate();
                    break;
                }
                else
                {
                    touchAction = MotionEvent.ACTION_MOVE;
                    invalidate();
                    return true;
                }
            }
        }

        return false;
    }

    @Override
    public void setOnClickListener(OnClickListener l)
    {
        clickListener = l;
    }
}

EDIT

Since many people are looking for something like this i made a class that can make other views have the ripple effect:

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

public class RippleViewCreator extends FrameLayout
{
    private float duration = 150;
    private int frameRate = 15;

    private float speed = 1;
    private float radius = 0;
    private Paint paint = new Paint();
    private float endRadius = 0;
    private float rippleX = 0;
    private float rippleY = 0;
    private int width = 0;
    private int height = 0;
    private Handler handler = new Handler();
    private int touchAction;

    public RippleViewCreator(Context context)
    {
        this(context, null, 0);
    }

    public RippleViewCreator(Context context, AttributeSet attrs)
    {
        this(context, attrs, 0);
    }

    public RippleViewCreator(Context context, AttributeSet attrs, int defStyleAttr)
    {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init()
    {
        if (isInEditMode())
            return;

        paint.setStyle(Paint.Style.FILL);
        paint.setColor(getResources().getColor(R.color.control_highlight_color));
        paint.setAntiAlias(true);

        setWillNotDraw(true);
        setDrawingCacheEnabled(true);
        setClickable(true);
    }

    public static void addRippleToView(View v)
    {
        ViewGroup parent = (ViewGroup)v.getParent();
        int index = -1;
        if(parent != null)
        {
            index = parent.indexOfChild(v);
            parent.removeView(v);
        }
        RippleViewCreator rippleViewCreator = new RippleViewCreator(v.getContext());
        rippleViewCreator.setLayoutParams(v.getLayoutParams());
        if(index == -1)
            parent.addView(rippleViewCreator, index);
        else
            parent.addView(rippleViewCreator);
        rippleViewCreator.addView(v);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh)
    {
        super.onSizeChanged(w, h, oldw, oldh);
        width = w;
        height = h;
    }

    @Override
    protected void dispatchDraw(@NonNull Canvas canvas)
    {
        super.dispatchDraw(canvas);

        if(radius > 0 && radius < endRadius)
        {
            canvas.drawCircle(rippleX, rippleY, radius, paint);
            if(touchAction == MotionEvent.ACTION_UP)
                invalidate();
        }
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event)
    {
        return true;
    }

    @Override
    public boolean onTouchEvent(@NonNull MotionEvent event)
    {
        rippleX = event.getX();
        rippleY = event.getY();

        touchAction = event.getAction();
        switch(event.getAction())
        {
            case MotionEvent.ACTION_UP:
            {
                getParent().requestDisallowInterceptTouchEvent(false);

                radius = 1;
                endRadius = Math.max(Math.max(Math.max(width - rippleX, rippleX), rippleY), height - rippleY);
                speed = endRadius / duration * frameRate;
                handler.postDelayed(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        if(radius < endRadius)
                        {
                            radius += speed;
                            paint.setAlpha(90 - (int) (radius / endRadius * 90));
                            handler.postDelayed(this, frameRate);
                        }
                        else if(getChildAt(0) != null)
                        {
                            getChildAt(0).performClick();
                        }
                    }
                }, frameRate);
                break;
            }
            case MotionEvent.ACTION_CANCEL:
            {
                getParent().requestDisallowInterceptTouchEvent(false);
                break;
            }
            case MotionEvent.ACTION_DOWN:
            {
                getParent().requestDisallowInterceptTouchEvent(true);
                endRadius = Math.max(Math.max(Math.max(width - rippleX, rippleX), rippleY), height - rippleY);
                paint.setAlpha(90);
                radius = endRadius/3;
                invalidate();
                return true;
            }
            case MotionEvent.ACTION_MOVE:
            {
                if(rippleX < 0 || rippleX > width || rippleY < 0 || rippleY > height)
                {
                    getParent().requestDisallowInterceptTouchEvent(false);
                    touchAction = MotionEvent.ACTION_CANCEL;
                    break;
                }
                else
                {
                    invalidate();
                    return true;
                }
            }
        }
        invalidate();
        return false;
    }

    @Override
    public final void addView(@NonNull View child, int index, ViewGroup.LayoutParams params)
    {
        //limit one view
        if (getChildCount() > 0)
        {
            throw new IllegalStateException(this.getClass().toString()+" can only have one child.");
        }
        super.addView(child, index, params);
    }
}

Check OS version in Swift?

Most of sample codes written here will get unexpected result with extra-zero versions. For example,

func SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(version: String) -> Bool {
return UIDevice.current.systemVersion.compare(version, options: .numeric) != ComparisonResult.orderedAscending
}

This method won't return true with passed version "10.3.0" in iOS "10.3". This kind of result does not make sense and they must be regarded as same version. To get accurate comparison result, we must consider comparing all of number components in version string. Plus, providing global methods in all capital letters is not a good way to go. As version type we use in our SDK is a String, it's make sense that extending comparing functionality in String.

To compare system version, all of the following examples should work.

XCTAssertTrue(UIDevice.current.systemVersion.isVersion(lessThan: "99.0.0"))
XCTAssertTrue(UIDevice.current.systemVersion.isVersion(equalTo: UIDevice.current.systemVersion))
XCTAssertTrue(UIDevice.current.systemVersion.isVersion(greaterThan: "3.5.99"))
XCTAssertTrue(UIDevice.current.systemVersion.isVersion(lessThanOrEqualTo: "10.3.0.0.0.0.0.0"))
XCTAssertTrue(UIDevice.current.systemVersion.isVersion(greaterThanOrEqualTo: "10.3"))

You can check it out in my repository here https://github.com/DragonCherry/VersionCompare

In jQuery, what's the best way of formatting a number to 2 decimal places?

Maybe something like this, where you could select more than one element if you'd like?

$("#number").each(function(){
    $(this).val(parseFloat($(this).val()).toFixed(2));
});

Any reason not to use '+' to concatenate two strings?

I have done a quick test:

import sys

str = e = "a xxxxxxxxxx very xxxxxxxxxx long xxxxxxxxxx string xxxxxxxxxx\n"

for i in range(int(sys.argv[1])):
    str = str + e

and timed it:

mslade@mickpc:/binks/micks/ruby/tests$ time python /binks/micks/junk/strings.py  8000000
8000000 times

real    0m2.165s
user    0m1.620s
sys     0m0.540s
mslade@mickpc:/binks/micks/ruby/tests$ time python /binks/micks/junk/strings.py  16000000
16000000 times

real    0m4.360s
user    0m3.480s
sys     0m0.870s

There is apparently an optimisation for the a = a + b case. It does not exhibit O(n^2) time as one might suspect.

So at least in terms of performance, using + is fine.

javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake during web service communicaiton

You May Write this below code insdie your current java programme

System.setProperty("https.protocols", "TLSv1.1");

or

System.setProperty("http.proxyHost", "proxy.com");

System.setProperty("http.proxyPort", "911");

Disposing WPF User Controls

An UserControl has a Destructor, why don't you use that?

~MyWpfControl()
    {
        // Dispose of any Disposable items here
    }

What is the difference between Hibernate and Spring Data JPA

Hibernate is implementation of "JPA" which is a specification for Java objects in Database.

I would recommend to use w.r.t JPA as you can switch between different ORMS.

When you use JDBC then you need to use SQL Queries, so if you are proficient in SQL then go for JDBC.

Angular @ViewChild() error: Expected 2 arguments, but got 1

That also resolved my issue.

@ViewChild('map', {static: false}) googleMap;

SQL count rows in a table

select sum([rows])
from sys.partitions
where object_id=object_id('tablename')
 and index_id in (0,1)

is very fast but very rarely inaccurate.

Method to get all files within folder and subfolders that will return a list

I am not sure of why you're adding the strings to files, which is declared as a field rather than a temporary variable. You could change the signature of DirSearch to:

private List<string> DirSearch(string sDir)

And, after the catch block, add:

return files;

Alternatively, you could create a temporary variable inside of your method and return it, which seems to me the approach you might desire. Otherwise, each time you call that method, the newly found strings will be added to the same list as before and you'll have duplicates.

Easy way to export multiple data.frame to multiple Excel worksheets

I do this all the time, all I do is

WriteXLS::WriteXLS(
    all.dataframes,
    ExcelFileName = xl.filename,
    AdjWidth = T,
    AutoFilter = T,
    FreezeRow = 1,
    FreezeCol = 2,
    BoldHeaderRow = T,
    verbose = F,
    na = '0'
  )

and all those data frames come from here

all.dataframes <- vector()
for (obj.iter in all.objects) {
  obj.name <- obj.iter
  obj.iter <- get(obj.iter)
  if (class(obj.iter) == 'data.frame') {
      all.dataframes <- c(all.dataframes, obj.name)
}

obviously sapply routine would be better here

How can I get my webapp's base URL in ASP.NET MVC?

You could have a static method that looks at HttpContext.Current and decides which URL to use (development or live server) depending on the host ID. HttpContext might even offer some easier way to do it, but this is the first option I found and it works fine.

How to manually include external aar package using new Gradle Android Build System

In my case just work when i add "project" to compile:

repositories {
    mavenCentral()
    flatDir {
        dirs 'libs'
    }
}


dependencies {
   compile project('com.x.x:x:1.0.0')
}

Programmatically set TextBlock Foreground Color

 textBlock.Foreground = new SolidColorBrush(Colors.White);

get selected value in datePicker and format it

var dateObject = $("#datePickerInput").datepicker('getDate');
$.datepicker.formatDate('dd MM, yy', dateObject);

How to delete all records from table in sqlite with Android?

    getContentResolver().delete(DB.TableName.CONTENT_URI, null, null);

How can I find the number of arguments of a Python function?

someMethod.func_code.co_argcount

or, if the current function name is undetermined:

import sys

sys._getframe().func_code.co_argcount

SQL: Select columns with NULL values only

I would also recommend to search for fields which all have the same value, not just NULL.

That is, for each column in each table do the query:

SELECT COUNT(DISTINCT field) FROM tableName

and concentrate on those which return 1 as a result.

Access nested dictionary items via a list of keys?

If you also want the ability to work with arbitrary json including nested lists and dicts, and nicely handle invalid lookup paths, here's my solution:

from functools import reduce


def get_furthest(s, path):
    '''
    Gets the furthest value along a given key path in a subscriptable structure.

    subscriptable, list -> any
    :param s: the subscriptable structure to examine
    :param path: the lookup path to follow
    :return: a tuple of the value at the furthest valid key, and whether the full path is valid
    '''

    def step_key(acc, key):
        s = acc[0]
        if isinstance(s, str):
            return (s, False)
        try:
            return (s[key], acc[1])
        except LookupError:
            return (s, False)

    return reduce(step_key, path, (s, True))


def get_val(s, path):
    val, successful = get_furthest(s, path)
    if successful:
        return val
    else:
        raise LookupError('Invalid lookup path: {}'.format(path))


def set_val(s, path, value):
    get_val(s, path[:-1])[path[-1]] = value

'printf' vs. 'cout' in C++

And I quote:

In high level terms, the main differences are type safety (cstdio doesn't have it), performance (most iostreams implementations are slower than the cstdio ones) and extensibility (iostreams allows custom output targets and seamless output of user defined types).

Android overlay a view ontop of everything?

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/root_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<LinearLayout
    android:id = "@+id/Everything"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <!-- other actual layout stuff here EVERYTHING HERE -->

   </LinearLayout>

<LinearLayout
    android:id="@+id/overlay"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="right" >
</LinearLayout>

Now any view you add under LinearLayout with android:id = "@+id/overlay" will appear as overlay with gravity = right on Linear Layout with android:id="@+id/Everything"

How can I align YouTube embedded video in the center in bootstrap

Using Bootstrap's built in .center-block class, which sets margin left and right to auto:

<iframe class="center-block" width="560" height="315" src="https://www.youtube.com/embed/ig3qHRVZRvM" frameborder="0" allowfullscreen=""></iframe>

Or using the built in .text-center class, which sets text-align: center:

<div class="text-center">
  <iframe width="560" height="315" src="https://www.youtube.com/embed/ig3qHRVZRvM" frameborder="0" allowfullscreen=""></iframe>
</div>

Get age from Birthdate

JsFiddle

You can calculate with Dates.

var birthdate = new Date("1990/1/1");
var cur = new Date();
var diff = cur-birthdate; // This is the difference in milliseconds
var age = Math.floor(diff/31557600000); // Divide by 1000*60*60*24*365.25

How to enable TLS 1.2 support in an Android application (running on Android 4.1 JB)

I have some additions to above mentioned answers Its infact a hack mentioned by Jesse Wilson from okhttp, square here. According to this hack, i had to rename my SSLSocketFactory variable to

private SSLSocketFactory delegate;

This is my TLSSocketFactory class

public class TLSSocketFactory extends SSLSocketFactory {

private SSLSocketFactory delegate;

public TLSSocketFactory() throws KeyManagementException, NoSuchAlgorithmException {
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, null, null);
    delegate = context.getSocketFactory();
}

@Override
public String[] getDefaultCipherSuites() {
    return delegate.getDefaultCipherSuites();
}

@Override
public String[] getSupportedCipherSuites() {
    return delegate.getSupportedCipherSuites();
}

@Override
public Socket createSocket() throws IOException {
    return enableTLSOnSocket(delegate.createSocket());
}

@Override
public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
    return enableTLSOnSocket(delegate.createSocket(s, host, port, autoClose));
}

@Override
public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
    return enableTLSOnSocket(delegate.createSocket(host, port));
}

@Override
public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException {
    return enableTLSOnSocket(delegate.createSocket(host, port, localHost, localPort));
}

@Override
public Socket createSocket(InetAddress host, int port) throws IOException {
    return enableTLSOnSocket(delegate.createSocket(host, port));
}

@Override
public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
    return enableTLSOnSocket(delegate.createSocket(address, port, localAddress, localPort));
}

private Socket enableTLSOnSocket(Socket socket) {
    if(socket != null && (socket instanceof SSLSocket)) {
        ((SSLSocket)socket).setEnabledProtocols(new String[] {"TLSv1.1", "TLSv1.2"});
    }
    return socket;
}
}

and this is how i used it with okhttp and retrofit

 OkHttpClient client=new OkHttpClient();
    try {
        client = new OkHttpClient.Builder()
                .sslSocketFactory(new TLSSocketFactory())
                .build();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(URL)
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

What does "|=" mean? (pipe equal operator)

It's a shortening for this:

notification.defaults = notification.defaults | Notification.DEFAULT_SOUND;

And | is a bit-wise OR.

Laravel Escaping All HTML in Blade Template

I had the same issue. Thanks for the answers above, I solved my issue. If there are people facing the same problem, here is two way to solve it:

  • You can use {!! $news->body !!}
  • You can use traditional php openning (It is not recommended) like: <?php echo $string ?>

I hope it helps.

Retrieve a Fragment from a ViewPager

Easy way to iterate over fragments in fragment manager. Find viewpager, that has section position argument, placed in public static PlaceholderFragment newInstance(int sectionNumber).

public PlaceholderFragment getFragmentByPosition(Integer pos){
    for(Fragment f:getChildFragmentManager().getFragments()){
        if(f.getId()==R.id.viewpager && f.getArguments().getInt("SECTNUM") - 1 == pos) {
            return (PlaceholderFragment) f;
        }
    }
    return null;
}

SQL Server: Multiple table joins with a WHERE clause

try this

DECLARE @Application TABLE(Id INT PRIMARY KEY, NAME VARCHAR(20))
INSERT @Application ( Id, NAME )
VALUES  ( 1,'Word' ), ( 2,'Excel' ), ( 3,'PowerPoint' )
DECLARE @software TABLE(Id INT PRIMARY KEY, ApplicationId INT, Version INT)
INSERT @software ( Id, ApplicationId, Version )
VALUES  ( 1,1, 2003 ), ( 2,1,2007 ), ( 3,2, 2003 ), ( 4,2,2007 ),( 5,3, 2003 ), ( 6,3,2007 )

DECLARE @Computer TABLE(Id INT PRIMARY KEY, NAME VARCHAR(20))
INSERT @Computer ( Id, NAME )
VALUES  ( 1,'Name1' ), ( 2,'Name2' )

DECLARE @Software_Computer  TABLE(Id INT PRIMARY KEY, SoftwareId int, ComputerId int)
INSERT @Software_Computer ( Id, SoftwareId, ComputerId )
VALUES  ( 1,1, 1 ), ( 2,4,1 ), ( 3,2, 2 ), ( 4,5,2 )

SELECT Computer.Name ComputerName, Application.Name ApplicationName, MAX(Software2.Version) Version
FROM @Application Application 
JOIN @Software Software
    ON Application.ID = Software.ApplicationID
CROSS JOIN @Computer Computer
LEFT JOIN @Software_Computer Software_Computer
    ON Software_Computer.ComputerId = Computer.Id AND Software_Computer.SoftwareId = Software.Id
LEFT JOIN @Software Software2
    ON Software2.ID = Software_Computer.SoftwareID
WHERE Computer.ID = 1 
GROUP BY Computer.Name, Application.Name

VBA ADODB excel - read data from Recordset

I am surprised that the connection string works for you, because it is missing a semi-colon. Set is only used with objects, so you would not say Set strNaam.

Set cn = CreateObject("ADODB.Connection")
With cn
 .Provider = "Microsoft.Jet.OLEDB.4.0"
  .ConnectionString = "Data Source=D:\test.xls " & _
  ";Extended Properties=""Excel 8.0;HDR=Yes;"""
.Open
End With
strQuery = "SELECT * FROM [Sheet1$E36:E38]"
Set rs = cn.Execute(strQuery)
Do While Not rs.EOF
  For i = 0 To rs.Fields.Count - 1
    Debug.Print rs.Fields(i).Name, rs.Fields(i).Value
    strNaam = rs.Fields(0).Value
  Next
  rs.MoveNext
Loop
rs.Close

There are other ways, depending on what you want to do, such as GetString (GetString Method Description).

Could not load file or assembly Exception from HRESULT: 0x80131040

Add following dll files to bin folder:

DotNetOpenAuth.AspNet.dll
DotNetOpenAuth.Core.dll
DotNetOpenAuth.OAuth.Consumer.dll
DotNetOpenAuth.OAuth.dll
DotNetOpenAuth.OpenId.dll
DotNetOpenAuth.OpenId.RelyingParty.dll

If you will not need them, delete dependentAssemblies from config named 'DotNetOpenAuth.Core' etc..

Access the css ":after" selector with jQuery

You can add style for :after a like html code.
For example:

var value = 22;
body.append('<style>.wrapper:after{border-top-width: ' + value + 'px;}</style>');

summing two columns in a pandas dataframe

df['variance'] = df.loc[:,['budget','actual']].sum(axis=1)

How to convert a datetime to string in T-SQL

Try below :

DECLARE @myDateTime DATETIME
SET @myDateTime = '2013-02-02'

-- Convert to string now
SELECT LEFT(CONVERT(VARCHAR, @myDateTime, 120), 10)

react-native - Fit Image in containing View, not the whole screen size

I think it's because you didn't specify the width and height for the item.

If you only want to have 2 images in a row, you can try something like this instead of using flex:

item: {
    width: '50%',
    height: '100%',
    overflow: 'hidden',
    alignItems: 'center',
    backgroundColor: 'orange',
    position: 'relative',
    margin: 10,
},

This works for me, hope it helps.

How to Toggle a div's visibility by using a button click

Try following logic:

<script type="text/javascript">
function showHideDiv(id) {
    var e = document.getElementById(id);
    if(e.style.display == null || e.style.display == "none") {
        e.style.display = "block";
    } else {
        e.style.display = "none";
    }
}
</script>

PHP - remove all non-numeric characters from a string

You can use preg_replace in this case;

$res = preg_replace("/[^0-9]/", "", "Every 6 Months" );

$res return 6 in this case.

If want also to include decimal separator or thousand separator check this example:

$res = preg_replace("/[^0-9.]/", "", "$ 123.099");

$res returns "123.099" in this case

Include period as decimal separator or thousand separator: "/[^0-9.]/"

Include coma as decimal separator or thousand separator: "/[^0-9,]/"

Include period and coma as decimal separator and thousand separator: "/[^0-9,.]/"

What are some alternatives to ReSharper?

The main alternative is:

  • CodeRush, by DevExpress. Most consider either this or ReSharper the way to go. You cannot go wrong with either. Both have their fans, both are powerful, and both have talented teams constantly improving them. We have all benefited from the competition between these two. I won't repeat the many good discussions/comparisons about them that can be found on Stack Overflow and elsewhere.

Another alternative worth checking out:

  • JustCode, by Telerik. This is new, still with kinks, but initial reports are positive. An advantage could be licensing with other Telerik products and integration with them. There are bundled licenses available that could make things cheaper / easier to handle.

MySQL - how to front pad zip code with "0"?

Store your zipcodes as CHAR(5) instead of a numeric type, or have your application pad it with zeroes when you load it from the DB. A way to do it with PHP using sprintf():

echo sprintf("%05d", 205); // prints 00205
echo sprintf("%05d", 1492); // prints 01492

Or you could have MySQL pad it for you with LPAD():

SELECT LPAD(zip, 5, '0') as zipcode FROM table;

Here's a way to update and pad all rows:

ALTER TABLE `table` CHANGE `zip` `zip` CHAR(5); #changes type
UPDATE table SET `zip`=LPAD(`zip`, 5, '0'); #pads everything

Using ExcelDataReader to read Excel data starting from a particular cell

One way to do it :

FileStream stream = File.Open(@"c:\working\test.xls", FileMode.Open, FileAccess.Read);

IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);

excelReader.IsFirstRowAsColumnNames = true;

DataSet result = excelReader.AsDataSet();

The result.Tables contains the sheets and the result.tables[0].Rows contains the cell rows.

Java command not found on Linux

I use the following script to update the default alternative after install jdk.

#!/bin/bash
export JAVA_BIN_DIR=/usr/java/default/bin # replace with your installed directory
cd ${JAVA_BIN_DIR}
a=(java javac javadoc javah javap javaws)
for exe in ${a[@]}; do
    sudo update-alternatives --install "/usr/bin/${exe}" "${exe}" "${JAVA_BIN_DIR}/${exe}" 1
    sudo update-alternatives --set ${exe} ${JAVA_BIN_DIR}/${exe}
done

How to split a string, but also keep the delimiters?

Pass the 3rd aurgument as "true". It will return delimiters as well.

StringTokenizer(String str, String delimiters, true);

gcc: undefined reference to

Are you mixing C and C++? One issue that can occur is that the declarations in the .h file for a .c file need to be surrounded by:

#if defined(__cplusplus)
  extern "C" {                 // Make sure we have C-declarations in C++ programs
#endif

and:

#if defined(__cplusplus)
  }
#endif

Note: if unable / unwilling to modify the .h file(s) in question, you can surround their inclusion with extern "C":

extern "C" {
#include <abc.h>
} //extern

How to open URL in Microsoft Edge from the command line?

While the accepted answer is correct, it has the unwanted artifact of flashing a console window when running from a non-console application.

The solution I found works best, which is only mentioned here in a comments to the question, is the following command line:

explorer.exe "microsoft-edge:<URL>"

Keep in mind that if contains the % sign you will need to type %% as Windows uses the symbol for variable expansion.

Hope someone finds this helpful.

How to get maximum value from the Collection (for example ArrayList)?

Java 8

As integers are comparable we can use the following one liner in:

List<Integer> ints = Stream.of(22,44,11,66,33,55).collect(Collectors.toList());
Integer max = ints.stream().mapToInt(i->i).max().orElseThrow(NoSuchElementException::new); //66
Integer min = ints.stream().mapToInt(i->i).min().orElseThrow(NoSuchElementException::new); //11

Another point to note is we cannot use Funtion.identity() in place of i->i as mapToInt expects ToIntFunction which is a completely different interface and is not related to Function. Moreover this interface has only one method applyAsInt and no identity() method.

How to include Javascript file in Asp.Net page

ScriptManager control can also be used to reference javascript files. One catch is that the ScriptManager control needs to be place inside the form tag. I myself prefer ScriptManager control and generally place it just above the closing form tag.

<asp:ScriptManager ID="sm" runat="server">
    <Scripts>
        <asp:ScriptReference Path="~/Scripts/yourscript.min.js" />
    </Scripts>
</asp:ScriptManager>

Find in Files: Search all code in Team Foundation Server

There is another alternative solution, that seems to be more attractive.

  1. Setup a search server - could be any windows machine/server
  2. Setup a TFS notification service* (Bissubscribe) to get, delete, update files everytime a checkin happens. So this is a web service that acts like a listener on the TFS server, and updates/syncs the files and folders on the Search server. - this will dramatically improve the accuracy (live search), and avoid the one-time load of making periodic gets
  3. Setup an indexing service/windows indexed search on the Search server for the root folder
  4. Expose a web service to return search results

Now with all the above setup, you have a few options for the client:

  1. Setup a web page to call the search service and format the results to show on the webpage - you can also integrate this webpage inside visual studio (through a macro or a add-in)
  2. Create a windows client interface(winforms/wpf) to call the search service and format the results and show them on the UI - you can also integrate this client tool inside visual studio via VSPackages or add-in

Update: I did go this route, and it has been working nicely. Just wanted to add to this.

Reference links:

  1. Use this tool instead of bissubscribe.exe
  2. Handling TFS events
  3. Team System Notifications

Setting CSS pseudo-class rules from JavaScript

As already stated this is not something that browsers support.

If you aren't coming up with the styles dynamically (i.e. pulling them out of a database or something) you should be able to work around this by adding a class to the body of the page.

The css would look something like:

a:hover { background: red; }
.theme1 a:hover { background: blue; }

And the javascript to change this would be something like:

// Look up some good add/remove className code if you want to do this
// This is really simplified

document.body.className += " theme1";  

HtmlSpecialChars equivalent in Javascript?

Underscore.js provides a function for this:

_.escape(string)

Escapes a string for insertion into HTML, replacing &, <, >, ", and ' characters.

http://underscorejs.org/#escape

It's not a built-in Javascript function, but if you are already using Underscore it is a better alternative than writing your own function if your strings to convert are not too large.

Limiting the number of characters per line with CSS

Depending on what font you're using you can set max-width on the paragraph with a calculated value. It will not be exact, but I've found that in most cases that does not matter.

p {
  max-width: calc(30em * 0.5);
}

The number you multiply with depends on what font it is, and how much a character takes up in a em square. More characters = less accurate.

Create folder with batch but only if it doesn't already exist

if exist C:\VTS\NUL echo "Folder already exists"

if not exist C:\VTS\NUL echo "Folder does not exist"

See also https://support.microsoft.com/en-us/kb/65994

(Update March 7, 2018; Microsoft article is down, archive on https://web.archive.org/web/20150609092521/https://support.microsoft.com/en-us/kb/65994 )

HTTP Error 503, the service is unavailable

This might be because of number of connections to the database. I had such a situation and so, wrote a de-constructor and killed db open connection and it resolved.

How can I install the VS2017 version of msbuild on a build server without installing the IDE?

The Visual Studio Build tools are a different download than the IDE. They appear to be a pretty small subset, and they're called Build Tools for Visual Studio 2019 (download).

You can use the GUI to do the installation, or you can script the installation of msbuild:

vs_buildtools.exe --add Microsoft.VisualStudio.Workload.MSBuildTools --quiet

Microsoft.VisualStudio.Workload.MSBuildTools is a "wrapper" ID for the three subcomponents you need:

  • Microsoft.Component.MSBuild
  • Microsoft.VisualStudio.Component.CoreBuildTools
  • Microsoft.VisualStudio.Component.Roslyn.Compiler

You can find documentation about the other available CLI switches here.

The build tools installation is much quicker than the full IDE. In my test, it took 5-10 seconds. With --quiet there is no progress indicator other than a brief cursor change. If the installation was successful, you should be able to see the build tools in %programfiles(x86)%\Microsoft Visual Studio\2019\BuildTools\MSBuild\Current\Bin.

If you don't see them there, try running without --quiet to see any error messages that may occur during installation.

How to get the index with the key in Python dictionary?

Use OrderedDicts: http://docs.python.org/2/library/collections.html#collections.OrderedDict

>>> x = OrderedDict((("a", "1"), ("c", '3'), ("b", "2")))
>>> x["d"] = 4
>>> x.keys().index("d")
3
>>> x.keys().index("c")
1

For those using Python 3

>>> list(x.keys()).index("c")
1

Save modifications in place with awk

Using tee

 awk '{awk code}' file | tee file

the tee command take place and executed after the awk command is finished due to the |.

Using Javamail to connect to Gmail smtp server ignores specified port and tries to use 25

For anyone looking for a full solution, I got this working with the following code based on maximdim's answer:

import javax.mail.*
import javax.mail.internet.*

private class SMTPAuthenticator extends Authenticator
{
    public PasswordAuthentication getPasswordAuthentication()
    {
        return new PasswordAuthentication('[email protected]', 'test1234');
    }
}

def  d_email = "[email protected]",
        d_uname = "email",
        d_password = "password",
        d_host = "smtp.gmail.com",
        d_port  = "465", //465,587
        m_to = "[email protected]",
        m_subject = "Testing",
        m_text = "Hey, this is the testing email."

def props = new Properties()
props.put("mail.smtp.user", d_email)
props.put("mail.smtp.host", d_host)
props.put("mail.smtp.port", d_port)
props.put("mail.smtp.starttls.enable","true")
props.put("mail.smtp.debug", "true");
props.put("mail.smtp.auth", "true")
props.put("mail.smtp.socketFactory.port", d_port)
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory")
props.put("mail.smtp.socketFactory.fallback", "false")

def auth = new SMTPAuthenticator()
def session = Session.getInstance(props, auth)
session.setDebug(true);

def msg = new MimeMessage(session)
msg.setText(m_text)
msg.setSubject(m_subject)
msg.setFrom(new InternetAddress(d_email))
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to))

Transport transport = session.getTransport("smtps");
transport.connect(d_host, 465, d_uname, d_password);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();

ASP.NET MVC View Engine Comparison

Check this SharpDOM . This is a c# 4.0 internal dsl for generating html and also asp.net mvc view engine.

How to use std::sort to sort an array in C++

With the Ranges library that is coming in C++20, you can use

ranges::sort(arr);

directly, where arr is a builtin array.

How to redirect DNS to different ports

Possible solutions:

  1. Use nginx on the server as a proxy that will listen to port A and multiplex to port B or C.

  2. If you use AWS you can use the load balancer to redirect the request to specific port based on the host.

Scala check if element is present in a list

In your case I would consider using Set and not List, to ensure you have unique values only. unless you need sometimes to include duplicates.

In this case, you don't need to add any wrapper functions around lists.

video as site background? HTML 5

First, your HTML markup looks like this:

<video id="awesome_video" src="first_video.mp4" autoplay />

Second, your JavaScript code will look like this:

<script type="text/javascript">
  var index = 1,
      playlist = ['first_video.mp4', 'second_video.mp4', 'third_video.mp4'],
      video = document.getElementById('awesome_video');

  video.addEventListener('ended', rotate_video, false);

  function rotate_video() {
    video.setAttribute('src', playlist[index]);
    video.load();
    index++;
    if (index >= playlist.length) { index = 0; }
  }
</script>

And last but not least, your CSS:

#awesome_video { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }

This will create a video element on your page that starts playing the first video right away, then iterates through the playlist defined by the JavaScript variable. Your mileage with the CSS may vary depending on the CSS for the rest of the site, but 100% width/height should do it on a basic page.

Rotating a point about another point (2D)

I struggled while working MS OCR Read API which returns back angle of rotation in range (-180, 180]. So I have to do an extra step of converting negative angles to positive. I hope someone struggling with point rotation with negative or positive angles can use the following.

def rotate(origin, point, angle):
    """
    Rotate a point counter-clockwise by a given angle around a given origin.
    """
    # Convert negative angles to positive
    angle = normalise_angle(angle)

    # Convert to radians
    angle = math.radians(angle)

    # Convert to radians
    ox, oy = origin
    px, py = point
    
    # Move point 'p' to origin (0,0)
    _px = px - ox
    _py = py - oy
    
    # Rotate the point 'p' 
    qx = (math.cos(angle) * _px) - (math.sin(angle) * _py)
    qy = (math.sin(angle) * _px) + (math.cos(angle) * _py)
    
    # Move point 'p' back to origin (ox, oy)
    qx = ox + qx
    qy = oy + qy
    
    return [qx, qy]


def normalise_angle(angle):
    """ If angle is negative then convert it to positive. """
    if (angle != 0) & (abs(angle) == (angle * -1)):
        angle = 360 + angle
    return angle

Google Maps API 3 - Custom marker color for default (dot) marker

Combine a symbol-based marker whose path draws the outline, with a '?' character for the center. You can substitute the dot with other text ('A', 'B', etc.) as desired.

This function returns options for a marker with the a given text (if any), text color, and fill color. It uses the text color for the outline.

function createSymbolMarkerOptions(text, textColor, fillColor) {
    return {
        icon: {
            path: 'M 0,0 C -2,-20 -10,-22 -10,-30 A 10,10 0 1,1 10,-30 C 10,-22 2,-20 0,0 z',
            fillColor: fillColor,
            fillOpacity: 1,
            strokeColor: textColor,
            strokeWeight: 1.8,
            labelOrigin: { x: 0, y: -30 }
        },
        label: {
            text: text || '?',
            color: textColor
        }
    };
}

How to compare times in Python?

Another way to do this without adding dependencies or using datetime is to simply do some math on the attributes of the time object. It has hours, minutes, seconds, milliseconds, and a timezone. For very simple comparisons, hours and minutes should be sufficient.

d = datetime.utcnow()
t = d.time()
print t.hour,t.minute,t.second

I don't recommend doing this unless you have an incredibly simple use-case. For anything requiring timezone awareness or awareness of dates, you should be using datetime.

How do you know if Tomcat Server is installed on your PC

You can check in windows services if tomcat is installed it will be listed in windows services.

To check the windows service list of services installed on windows machine use

  WINDOWS KEY + R   and type services.msc

There you can find all the services related with Jasperreport server like Tomcat and MySQL with name starting Jasperreport server Tomcat and MySQL only if these services are installed and its need to be started by selecting the option.Then you can access it through browser using this link :-

   http://localhost:8080

default port for tomcat is 8080.

Get button click inside UITableViewCell

Swift 2.2

You need to add target for that button.

myButton.addTarget(self, action: #selector(ClassName.FunctionName(_:), forControlEvents: .TouchUpInside)

FunctionName: connected // for example

And of course you need to set tag of that button since you are using it.

myButton.tag = indexPath.row

You can achieve this by subclassing UITableViewCell. Use it in interface builder, drop a button on that cell, connect it via outlet and there you go.

To get the tag in the connected function:

func connected(sender: UIButton) {
    let buttonTag = sender.tag
    // Do any additional setup
}

Does VBScript have a substring() function?

Yes, Mid.

Dim sub_str
sub_str = Mid(source_str, 10, 5)

The first parameter is the source string, the second is the start index, and the third is the length.

@bobobobo: Note that VBScript strings are 1-based, not 0-based. Passing 0 as an argument to Mid results in "invalid procedure call or argument Mid".

How to convert Blob to String and String to Blob in java

Use this to convert String to Blob. Where connection is the connection to db object.

    String strContent = s;
    byte[] byteConent = strContent.getBytes();
    Blob blob = connection.createBlob();//Where connection is the connection to db object. 
    blob.setBytes(1, byteContent);

Calling a method every x minutes

while (true)
{
    Thread.Sleep(60 * 5 * 1000);
    Console.WriteLine("*** calling MyMethod *** ");
    MyMethod();
}

What's the best way to set a single pixel in an HTML5 canvas?

Since different browsers seems to prefer different methods, maybe it would make sense to do a smaller test with all three methods as a part of the loading process to find out which is best to use and then use that throughout the application?

"date(): It is not safe to rely on the system's timezone settings..."

If you are using CodeIgniter and can't change php.ini, I added the following to the beginning of index.php:

date_default_timezone_set('GMT');

Number of lines in a file in Java

If you don't have any index structures, you'll not get around the reading of the complete file. But you can optimize it by avoiding to read it line by line and use a regex to match all line terminators.

How to declare a global variable in C++

I have read that any variable declared outside a function is a global variable. I have done so, but in another *.cpp File that variable could not be found. So it was not realy global.

According to the concept of scope, your variable is global. However, what you've read/understood is overly-simplified.


Possibility 1

Perhaps you forgot to declare the variable in the other translation unit (TU). Here's an example:

a.cpp

int x = 5; // declaration and definition of my global variable

b.cpp

// I want to use `x` here, too.
// But I need b.cpp to know that it exists, first:
extern int x; // declaration (not definition)

void foo() {
   cout << x;  // OK
}

Typically you'd place extern int x; in a header file that gets included into b.cpp, and also into any other TU that ends up needing to use x.


Possibility 2

Additionally, it's possible that the variable has internal linkage, meaning that it's not exposed across translation units. This will be the case by default if the variable is marked const ([C++11: 3.5/3]):

a.cpp

const int x = 5; // file-`static` by default, because `const`

b.cpp

extern const int x;    // says there's a `x` that we can use somewhere...

void foo() {
   cout << x;    // ... but actually there isn't. So, linker error.
}

You could fix this by applying extern to the definition, too:

a.cpp

extern const int x = 5;

This whole malarky is roughly equivalent to the mess you go through making functions visible/usable across TU boundaries, but with some differences in how you go about it.

Where does Jenkins store configuration files for the jobs it runs?

On Linux one can find the home directory of Jenkins looking for a file, that Jenkins' home contains, e.g.:

$ find / -name "config.xml" | grep "jenkins"
/var/lib/jenkins/config.xml

Java split string to array

Consider this example:

public class StringSplit {
  public static void main(String args[]) throws Exception{
    String testString = "Real|How|To|||";
    System.out.println
       (java.util.Arrays.toString(testString.split("\\|")));
    // output : [Real, How, To]
  }
}

The result does not include the empty strings between the "|" separator. To keep the empty strings :

public class StringSplit {
  public static void main(String args[]) throws Exception{
    String testString = "Real|How|To|||";
    System.out.println
       (java.util.Arrays.toString(testString.split("\\|", -1)));
    // output : [Real, How, To, , , ]
  }
}

For more details go to this website: http://www.rgagnon.com/javadetails/java-0438.html

How to check if a service is running via batch file and start it, if it is not running?

@Echo off

Set ServiceName=wampapache64

SC queryex "%ServiceName%"|Find "STATE"|Find /v "RUNNING">Nul&&(

echo %ServiceName% not running
echo  

Net start "%ServiceName%"


    SC queryex "%ServiceName%"|Find "STATE"|Find /v "RUNNING">Nul&&(
        Echo "%ServiceName%" wont start
    )
        echo "%ServiceName%" started

)||(
    echo "%ServiceName%" was working and stopping
    echo  

    Net stop "%ServiceName%"

)


pause

Why do we need virtual functions in C++?

You have to distinguish between overriding and overloading. Without the virtual keyword you only overload a method of a base class. This means nothing but hiding. Let's say you have a base class Base and a derived class Specialized which both implement void foo(). Now you have a pointer to Base pointing to an instance of Specialized. When you call foo() on it you can observe the difference that virtual makes: If the method is virtual, the implementation of Specialized will be used, if it is missing, the version from Base will be chosen. It is best practice to never overload methods from a base class. Making a method non-virtual is the way of its author to tell you that its extension in subclasses is not intended.

How to implement onBackPressed() in Fragments?

This line of code will do the trick from within any fragment, it will pop the current fragment on the backstack.

getActivity().getSupportFragmentManager().popBackStack();

Using node.js as a simple web server

Node.js webserver from scratch


No 3rd-party frameworks; Allows query string; Adds trailing slash; Handles 404


Create a public_html subfolder and place all of your content in it.


Gist: https://gist.github.com/veganaize/fc3b9aa393ca688a284c54caf43a3fc3

var fs = require('fs');

require('http').createServer(function(request, response) {
  var path = 'public_html'+ request.url.slice(0,
      (request.url.indexOf('?')+1 || request.url.length+1) - 1);
      
  fs.stat(path, function(bad_path, path_stat) {
    if (bad_path) respond(404);
    else if (path_stat.isDirectory() && path.slice(-1) !== '/') {
      response.setHeader('Location', path.slice(11)+'/');
      respond(301);
    } else fs.readFile(path.slice(-1)==='/' ? path+'index.html' : path,
          function(bad_file, file_content) {
      if (bad_file) respond(404);
      else respond(200, file_content);
    });
  });
 
  function respond(status, content) {
    response.statusCode = status;
    response.end(content);
  }
}).listen(80, function(){console.log('Server running on port 80...')});

Sorting an ArrayList of objects using a custom sorting order

BalusC and bguiz have already given very complete answers on how to use Java's built-in Comparators.

I just want to add that google-collections has an Ordering class which is more "powerful" than the standard Comparators. It might be worth checking out. You can do cool things such as compounding Orderings, reversing them, ordering depending on a function's result for your objects...

Here is a blog post that mentions some of its benefits.

How to get names of enum entries?

Let ts-enum-util (github, npm) do the work for you and provide a lot of additional type-safe utilities. Works with both string and numeric enums, properly ignoring the numeric index reverse lookup entries for numeric enums:

String enum:

import {$enum} from "ts-enum-util";

enum Option {
    OPTION1 = 'this is option 1',
    OPTION2 = 'this is option 2'
}

// type: ("OPTION1" | "OPTION2")[]
// value: ["OPTION1", "OPTION2"]
const keys= $enum(Option).getKeys();

// type: Option[]
// value: ["this is option 1", "this is option 2"]
const values = $enum(Option).getValues();

Numeric enum:

enum Option {
    OPTION1,
    OPTION2
}

// type: ("OPTION1" | "OPTION2")[]
// value: ["OPTION1", "OPTION2"]
const keys= $enum(Option).getKeys();

// type: Option[]
// value: [0, 1]
const values = $enum(Option).getValues();

LINQ .Any VS .Exists - What's the difference?

TLDR; Performance-wise Any seems to be slower (if I have set this up properly to evaluate both values at almost same time)

        var list1 = Generate(1000000);
        var forceListEval = list1.SingleOrDefault(o => o == "0123456789012");
        if (forceListEval != "sdsdf")
        {
            var s = string.Empty;
            var start2 = DateTime.Now;
            if (!list1.Exists(o => o == "0123456789012"))
            {
                var end2 = DateTime.Now;
                s += " Exists: " + end2.Subtract(start2);
            }

            var start1 = DateTime.Now;
            if (!list1.Any(o => o == "0123456789012"))
            {
                var end1 = DateTime.Now;
                s +=" Any: " +end1.Subtract(start1);
            }

            if (!s.Contains("sdfsd"))
            {

            }

testing list generator:

private List<string> Generate(int count)
    {
        var list = new List<string>();
        for (int i = 0; i < count; i++)
        {
            list.Add( new string(
            Enumerable.Repeat("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 13)
                .Select(s =>
                {
                    var cryptoResult = new byte[4];
                    new RNGCryptoServiceProvider().GetBytes(cryptoResult);
                    return s[new Random(BitConverter.ToInt32(cryptoResult, 0)).Next(s.Length)];
                })
                .ToArray())); 
        }

        return list;
    }

With 10M records

" Any: 00:00:00.3770377 Exists: 00:00:00.2490249"

With 5M records

" Any: 00:00:00.0940094 Exists: 00:00:00.1420142"

With 1M records

" Any: 00:00:00.0180018 Exists: 00:00:00.0090009"

With 500k, (I also flipped around order in which they get evaluated to see if there is no additional operation associated with whichever runs first.)

" Exists: 00:00:00.0050005 Any: 00:00:00.0100010"

With 100k records

" Exists: 00:00:00.0010001 Any: 00:00:00.0020002"

It would seem Any to be slower by magnitude of 2.

Edit: For 5 and 10M records I changed the way it generates the list and Exists suddenly became slower than Any which implies there's something wrong in the way I am testing.

New testing mechanism:

private static IEnumerable<string> Generate(int count)
    {
        var cripto = new RNGCryptoServiceProvider();
        Func<string> getString = () => new string(
            Enumerable.Repeat("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 13)
                .Select(s =>
                {
                    var cryptoResult = new byte[4];
                    cripto.GetBytes(cryptoResult);
                    return s[new Random(BitConverter.ToInt32(cryptoResult, 0)).Next(s.Length)];
                })
                .ToArray());

        var list = new ConcurrentBag<string>();
        var x = Parallel.For(0, count, o => list.Add(getString()));
        return list;
    }

    private static void Test()
    {
        var list = Generate(10000000);
        var list1 = list.ToList();
        var forceListEval = list1.SingleOrDefault(o => o == "0123456789012");
        if (forceListEval != "sdsdf")
        {
            var s = string.Empty;

            var start1 = DateTime.Now;
            if (!list1.Any(o => o == "0123456789012"))
            {
                var end1 = DateTime.Now;
                s += " Any: " + end1.Subtract(start1);
            }

            var start2 = DateTime.Now;
            if (!list1.Exists(o => o == "0123456789012"))
            {
                var end2 = DateTime.Now;
                s += " Exists: " + end2.Subtract(start2);
            }

            if (!s.Contains("sdfsd"))
            {

            }
        }

Edit2: Ok so to eliminate any influence from generating test data I wrote it all to file and now read it from there.

 private static void Test()
    {
        var list1 = File.ReadAllLines("test.txt").Take(500000).ToList();
        var forceListEval = list1.SingleOrDefault(o => o == "0123456789012");
        if (forceListEval != "sdsdf")
        {
            var s = string.Empty;
            var start1 = DateTime.Now;
            if (!list1.Any(o => o == "0123456789012"))
            {
                var end1 = DateTime.Now;
                s += " Any: " + end1.Subtract(start1);
            }

            var start2 = DateTime.Now;
            if (!list1.Exists(o => o == "0123456789012"))
            {
                var end2 = DateTime.Now;
                s += " Exists: " + end2.Subtract(start2);
            }

            if (!s.Contains("sdfsd"))
            {
            }
        }
    }

10M

" Any: 00:00:00.1640164 Exists: 00:00:00.0750075"

5M

" Any: 00:00:00.0810081 Exists: 00:00:00.0360036"

1M

" Any: 00:00:00.0190019 Exists: 00:00:00.0070007"

500k

" Any: 00:00:00.0120012 Exists: 00:00:00.0040004"

enter image description here

C# Lambda expressions: Why should I use them?

A lot of the times, you are only using the functionality in one place, so making a method just clutters up the class.

How big can a MySQL database get before performance starts to degrade

In general this is a very subtle issue and not trivial whatsoever. I encourage you to read mysqlperformanceblog.com and High Performance MySQL. I really think there is no general answer for this.

I'm working on a project which has a MySQL database with almost 1TB of data. The most important scalability factor is RAM. If the indexes of your tables fit into memory and your queries are highly optimized, you can serve a reasonable amount of requests with a average machine.

The number of records do matter, depending of how your tables look like. It's a difference to have a lot of varchar fields or only a couple of ints or longs.

The physical size of the database matters as well: think of backups, for instance. Depending on your engine, your physical db files on grow, but don't shrink, for instance with innodb. So deleting a lot of rows, doesn't help to shrink your physical files.

There's a lot to this issues and as in a lot of cases the devil is in the details.

Is it possible to change the radio button icon in an android radio button group

The easier way to only change the radio button is simply set selector for drawable right

<RadioButton
    ...
    android:button="@null"
    android:checked="false"
    android:drawableRight="@drawable/radio_button_selector" />

And the selector is:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/ic_checkbox_checked" android:state_checked="true" />
    <item android:drawable="@drawable/ic_checkbox_unchecked" android:state_checked="false" /></selector>

That's all

What are the main differences between JWT and OAuth authentication?

TL;DR If you have very simple scenarios, like a single client application, a single API then it might not pay off to go OAuth 2.0, on the other hand, lots of different clients (browser-based, native mobile, server-side, etc) then sticking to OAuth 2.0 rules might make it more manageable than trying to roll your own system.


As stated in another answer, JWT (Learn JSON Web Tokens) is just a token format, it defines a compact and self-contained mechanism for transmitting data between parties in a way that can be verified and trusted because it is digitally signed. Additionally, the encoding rules of a JWT also make these tokens very easy to use within the context of HTTP.

Being self-contained (the actual token contains information about a given subject) they are also a good choice for implementing stateless authentication mechanisms (aka Look mum, no sessions!). When going this route and the only thing a party must present to be granted access to a protected resource is the token itself, the token in question can be called a bearer token.

In practice, what you're doing can already be classified as based on bearer tokens. However, do consider that you're not using bearer tokens as specified by the OAuth 2.0 related specs (see RFC 6750). That would imply, relying on the Authorization HTTP header and using the Bearer authentication scheme.

Regarding the use of the JWT to prevent CSRF without knowing exact details it's difficult to ascertain the validity of that practice, but to be honest it does not seem correct and/or worthwhile. The following article (Cookies vs Tokens: The Definitive Guide) may be a useful read on this subject, particularly the XSS and XSRF Protection section.

One final piece of advice, even if you don't need to go full OAuth 2.0, I would strongly recommend on passing your access token within the Authorization header instead of going with custom headers. If they are really bearer tokens, follow the rules of RFC 6750. If not, you can always create a custom authentication scheme and still use that header.

Authorization headers are recognized and specially treated by HTTP proxies and servers. Thus, the usage of such headers for sending access tokens to resource servers reduces the likelihood of leakage or unintended storage of authenticated requests in general, and especially Authorization headers.

(source: RFC 6819, section 5.4.1)

C++ printing spaces or tabs given a user input integer

Simply add spaces for { 2 3 4 5 6 } like these:

cout<<"{";

for(){
    cout<<" "<<n;    //n is the element to print !
}

cout<<" }";

How to return PDF to browser in MVC?

HttpContext.Response.AddHeader("content-disposition","attachment; filename=form.pdf");

if the filename is generating dynamically then how to define filename here, it is generating through guid here.

"unmappable character for encoding" warning in Java

For those wondering why this happens on some systems and not on others (with the same source, build parameters, and so on), check your LANG environment variable. I get the warning/error when LANG=C.UTF-8, but not when LANG=en_US.UTF-8.

No route matches "/users/sign_out" devise rails 3

This is what I did (with Rails 3.0 and Devise 1.4.2):

  1. Make sure your page loads rails.js
  2. Use this param: 'data-method' => 'delete'
  3. Good idea to add this param: :rel => 'nofollow'

Count work days between two dates

This is basically CMS's answer without the reliance on a particular language setting. And since we're shooting for generic, that means it should work for all @@datefirst settings as well.

datediff(day, <start>, <end>) + 1 - datediff(week, <start>, <end>) * 2
    /* if start is a Sunday, adjust by -1 */
  + case when datepart(weekday, <start>) = 8 - @@datefirst then -1 else 0 end
    /* if end is a Saturday, adjust by -1 */
  + case when datepart(weekday, <end>) = (13 - @@datefirst) % 7 + 1 then -1 else 0 end

datediff(week, ...) always uses a Saturday-to-Sunday boundary for weeks, so that expression is deterministic and doesn't need to be modified (as long as our definition of weekdays is consistently Monday through Friday.) Day numbering does vary according to the @@datefirst setting and the modified calculations handle this correction with the small complication of some modular arithmetic.

A cleaner way to deal with the Saturday/Sunday thing is to translate the dates prior to extracting a day of week value. After shifting, the values will be back in line with a fixed (and probably more familiar) numbering that starts with 1 on Sunday and ends with 7 on Saturday.

datediff(day, <start>, <end>) + 1 - datediff(week, <start>, <end>) * 2
  + case when datepart(weekday, dateadd(day, @@datefirst, <start>)) = 1 then -1 else 0 end
  + case when datepart(weekday, dateadd(day, @@datefirst, <end>))   = 7 then -1 else 0 end

I've tracked this form of the solution back at least as far as 2002 and an Itzik Ben-Gan article. (https://technet.microsoft.com/en-us/library/aa175781(v=sql.80).aspx) Though it needed a small tweak since newer date types don't allow date arithmetic, it is otherwise identical.

EDIT: I added back the +1 that had somehow been left off. It's also worth noting that this method always counts the start and end days. It also assumes that the end date is on or after the start date.

How to render a PDF file in Android

I used the below code to open and print the PDF using Wi-Fi. I am sending my whole code, and I hope it is helpful.

public class MainActivity extends Activity {

    int Result_code = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button mButton = (Button)findViewById(R.id.button1);

        mButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                 PrintManager printManager = (PrintManager)getSystemService(Context.PRINT_SERVICE);
                String jobName =  " Document";
                printManager.print(jobName, pda, null);
            }
        });
    }


    public void openDocument(String name) {

        Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
        File file = new File(name);
        String extension = android.webkit.MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(file).toString());
        String mimetype = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        if (extension.equalsIgnoreCase("") || mimetype == null) {
            // if there is no extension or there is no definite mimetype, still try to open the file
            intent.setDataAndType(Uri.fromFile(file), "text/*");
        }
        else {
            intent.setDataAndType(Uri.fromFile(file), mimetype);
        }

        // custom message for the intent
        startActivityForResult((Intent.createChooser(intent, "Choose an Application:")), Result_code);
        //startActivityForResult(intent, Result_code);
        //Toast.makeText(getApplicationContext(),"There are no email clients installed.", Toast.LENGTH_SHORT).show();
    }


    @SuppressLint("NewApi")
    PrintDocumentAdapter pda = new PrintDocumentAdapter(){

        @Override
        public void onWrite(PageRange[] pages, ParcelFileDescriptor destination, CancellationSignal cancellationSignal, WriteResultCallback callback){
            InputStream input = null;
            OutputStream output = null;

            try {
                String filename = Environment.getExternalStorageDirectory()    + "/" + "Holiday.pdf";
                File file = new File(filename);
                input = new FileInputStream(file);
                output = new FileOutputStream(destination.getFileDescriptor());

                byte[] buf = new byte[1024];
                int bytesRead;

                while ((bytesRead = input.read(buf)) > 0) {
                     output.write(buf, 0, bytesRead);
                }

                callback.onWriteFinished(new PageRange[]{PageRange.ALL_PAGES});
            }
            catch (FileNotFoundException ee){
                //Catch exception
            }
            catch (Exception e) {
                //Catch exception
            }
            finally {
                try {
                    input.close();
                    output.close();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onLayout(PrintAttributes oldAttributes, PrintAttributes newAttributes, CancellationSignal cancellationSignal, LayoutResultCallback callback, Bundle extras){

            if (cancellationSignal.isCanceled()) {
                callback.onLayoutCancelled();
                return;
            }

           // int pages = computePageCount(newAttributes);

            PrintDocumentInfo pdi = new PrintDocumentInfo.Builder("Name of file").setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT).build();

            callback.onLayoutFinished(pdi, true);
        }
    };
}

Django - iterate number in for loop of a template

Also one can use this:

{% if forloop.first %}

or

{% if forloop.last %}

How to darken an image on mouseover?

I realise this is a little late but you could add the following to your code. This won't work for transparent pngs though, you'd need a cropping mask for that. Which I'm now going to see about.

outerLink {
    overflow: hidden;
    position: relative;
}

outerLink:hover:after {
    background: #000;
    content: "";
    display: block;
    height: 100%;
    left: 0;
    opacity: 0.5;
    position: absolute;
    top: 0;
    width: 100%;
}

How to query GROUP BY Month in a Year

I am doing like this in MSSQL

Getting Monthly Data:

 SELECT YEAR(DATE_CREATED) [Year], MONTH(DATE_CREATED) [Month], 
     DATENAME(MONTH,DATE_CREATED) [Month Name], SUM(Num_of_Pictures) [Pictures Count]
    FROM pictures_table
    GROUP BY YEAR(DATE_CREATED), MONTH(DATE_CREATED), 
     DATENAME(MONTH, DATE_CREATED)
    ORDER BY 1,2

Getting Monthly Data using PIVOT:

SELECT *
FROM (SELECT YEAR(DATE_CREATED) [Year], 
       DATENAME(MONTH, DATE_CREATED) [Month], 
       SUM(Num_of_Pictures) [Pictures Count]
      FROM pictures_table
      GROUP BY YEAR(DATE_CREATED), 
      DATENAME(MONTH, DATE_CREATED)) AS MontlySalesData
PIVOT( SUM([Pictures Count])   
    FOR Month IN ([January],[February],[March],[April],[May],
    [June],[July],[August],[September],[October],[November],
    [December])) AS MNamePivot

Json.NET serialize object with root name

I found an easy way to render this out... simply declare a dynamic object and assign the first item within the dynamic object to be your collection class...This example assumes you're using Newtonsoft.Json

private class YourModelClass
{
    public string firstName { get; set; }
    public string lastName { get; set; }
}

var collection = new List<YourModelClass>();

var collectionWrapper = new {

    myRoot = collection

};

var output = JsonConvert.SerializeObject(collectionWrapper);

What you should end up with is something like this:

{"myRoot":[{"firstName":"John", "lastName": "Citizen"}, {...}]}

How to strip a specific word from a string?

A bit 'lazy' way to do this is to use startswith- it is easier to understand this rather regexps. However regexps might work faster, I haven't measured.

>>> papa = "papa is a good man"
>>> app = "app is important"
>>> strip_word = 'papa'
>>> papa[len(strip_word):] if papa.startswith(strip_word) else papa
' is a good man'
>>> app[len(strip_word):] if app.startswith(strip_word) else app
'app is important'

How to chain scope queries with OR instead of AND?

You would do

Person.where('name=? OR lastname=?', 'John', 'Smith')

Right now, there isn't any other OR support by the new AR3 syntax (that is without using some 3rd party gem).

How to check if a value is not null and not empty string in JS

if (data?.trim().length > 0) {
   //use data
}

the ?. optional chaining operator will short-circuit and return undefined if data is nullish (null or undefined) which will evaluate to false in the if expression.

Python threading. How do I lock a thread?

You can see that your locks are pretty much working as you are using them, if you slow down the process and make them block a bit more. You had the right idea, where you surround critical pieces of code with the lock. Here is a small adjustment to your example to show you how each waits on the other to release the lock.

import threading
import time
import inspect

class Thread(threading.Thread):
    def __init__(self, t, *args):
        threading.Thread.__init__(self, target=t, args=args)
        self.start()

count = 0
lock = threading.Lock()

def incre():
    global count
    caller = inspect.getouterframes(inspect.currentframe())[1][3]
    print "Inside %s()" % caller
    print "Acquiring lock"
    with lock:
        print "Lock Acquired"
        count += 1  
        time.sleep(2)  

def bye():
    while count < 5:
        incre()

def hello_there():
    while count < 5:
        incre()

def main():    
    hello = Thread(hello_there)
    goodbye = Thread(bye)


if __name__ == '__main__':
    main()

Sample output:

...
Inside hello_there()
Acquiring lock
Lock Acquired
Inside bye()
Acquiring lock
Lock Acquired
...

org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/CollegeWebsite]]

This error happens because of your Jre version of Eclipse and Tomcat are mismatched ..either change eclipse one to tomcat one or ViceVersa..

Both should be same ..Java version mismatched ..Check it

How to open adb and use it to send commands

The short answer is adb is used via command line. find adb.exe on your machine, add it to the path and use it from cmd on windows.

"adb devices" will give you a list of devices adb can talk to. your emulation platform should be on the list. just type adb to get a list of commands and what they do.

How to deal with certificates using Selenium?

Creating a profile and then a driver helps us get around the certificate issue in Firefox:

var profile = new FirefoxProfile();
profile.SetPreference("network.automatic-ntlm-auth.trusted-uris","DESIREDURL");
driver = new FirefoxDriver(profile);

Converting double to string

double priceG = Double.parseDouble(priceGal.getText().toString());

double valG = Double.parseDouble(volGal.toString());

double priceG = Double.parseDouble(priceGal.getText().toString());

double valG = Double.parseDouble(volGal.toString());

double priceG = Double.parseDouble(priceGal.getText().toString());

double valG = Double.parseDouble(volGal.toString());

it works. got to be repetitive.

Changing color of Twitter bootstrap Nav-Pills

This is specific to Bootstrap 4.0.

HTML

<ul class="nav nav-pills">
  <li class="nav-item">
    <a class="nav-link nav-link-color" href="#about">home</a>
  </li>
  <li class="nav-item">
    <a class="nav-link nav-link-color"  href="#contact">contact</a>
  </li>
</ul>

CSS

.nav-pills > li > a.active {
  background-color: #ffffff !important;
  color: #ffffff !important;
}

.nav-pills > li > a:hover {
  color: #ffffff !important;
}

.nav-link-color {
  color: #ffffff;
}

How do I timestamp every ping result?

From man ping:

   -D     Print timestamp (unix time + microseconds as in gettimeofday) before each line.

It will produce something like this:

[1337577886.346622] 64 bytes from 4.2.2.2: icmp_req=1 ttl=243 time=47.1 ms

Then timestamp could be parsed out from the ping response and converted to the required format with date.

Get an element by index in jQuery

There is another way of getting an element by index in jQuery using CSS :nth-of-type pseudo-class:

<script>
    // css selector that describes what you need:
    // ul li:nth-of-type(3)
    var selector = 'ul li:nth-of-type(' + index + ')';
    $(selector).css({'background-color':'#343434'});
</script>

There are other selectors that you may use with jQuery to match any element that you need.

file_put_contents(meta/services.json): failed to open stream: Permission denied

For everyone using Laravel 5, Homestead and Mac try this:

mkdir storage/framework/views

Concatenate text files with Windows command line, dropping leading lines

I don't have enough reputation points to comment on the recommendation to use *.csv >> ConcatenatedFile.csv, but I can add a warning:

If you create ConcatenatedFile.csv file in the same directory that you are using for concatenation it will be added to itself.

submitting a GET form with query string params and hidden params disappear

I had a very similar problem where for the form action, I had something like:

<form action="http://www.example.com/?q=content/something" method="GET">
   <input type="submit" value="Go away..." />&nbsp;
</form>

The button would get the user to the site, but the query info disappeared so the user landed on the home page rather than the desired content page. The solution in my case was to find out how to code the URL without the query that would get the user to the desired page. In this case my target was a Drupal site, so as it turned out /content/something also worked. I also could have used a node number (i.e. /node/123).

Python pandas insert list into a cell

As mentionned in this post pandas: how to store a list in a dataframe?; the dtypes in the dataframe may influence the results, as well as calling a dataframe or not to be assigned to.

HTML input arrays

It's just PHP, not HTML.

It parses all HTML fields with [] into an array.

So you can have

<input type="checkbox" name="food[]" value="apple" />
<input type="checkbox" name="food[]" value="pear" />

and when submitted, PHP will make $_POST['food'] an array, and you can access its elements like so:

echo $_POST['food'][0]; // would output first checkbox selected

or to see all values selected:

foreach( $_POST['food'] as $value ) {
    print $value;
}

Anyhow, don't think there is a specific name for it

jQuery return ajax result into outside variable

This is all you need to do:

var myVariable;

$.ajax({
    'async': false,
    'type': "POST",
    'global': false,
    'dataType': 'html',
    'url': "ajax.php?first",
    'data': { 'request': "", 'target': 'arrange_url', 'method': 'method_target' },
    'success': function (data) {
        myVariable = data;
    }
});

NOTE: Use of "async" has been depreciated. See https://xhr.spec.whatwg.org/.

Exposing a port on a live Docker container

While you cannot expose a new port of an existing container, you can start a new container in the same Docker network and get it to forward traffic to the original container.

# docker run \
  --rm \
  -p $PORT:1234 \
  verb/socat \
    TCP-LISTEN:1234,fork \
    TCP-CONNECT:$TARGET_CONTAINER_IP:$TARGET_CONTAINER_PORT

Worked Example

Launch a web-service that listens on port 80, but do not expose its internal port 80 (oops!):

# docker run -ti mkodockx/docker-pastebin   # Forgot to expose PORT 80!

Find its Docker network IP:

# docker inspect 63256f72142a | grep IPAddress
                    "IPAddress": "172.17.0.2",

Launch verb/socat with port 8080 exposed, and get it to forward TCP traffic to that IP's port 80:

# docker run --rm -p 8080:1234 verb/socat TCP-LISTEN:1234,fork TCP-CONNECT:172.17.0.2:80

You can now access pastebin on http://localhost:8080/, and your requests goes to socat:1234 which forwards it to pastebin:80, and the response travels the same path in reverse.

Can you explain the HttpURLConnection connection process?

Tim Bray presented a concise step-by-step, stating that openConnection() does not establish an actual connection. Rather, an actual HTTP connection is not established until you call methods such as getInputStream() or getOutputStream().

http://www.tbray.org/ongoing/When/201x/2012/01/17/HttpURLConnection

Python socket receive - incoming packets always have a different size

I know this is old, but I hope this helps someone.

Using regular python sockets I found that you can send and receive information in packets using sendto and recvfrom

# tcp_echo_server.py
import socket

ADDRESS = ''
PORT = 54321

connections = []
host = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host.setblocking(0)
host.bind((ADDRESS, PORT))
host.listen(10)  # 10 is how many clients it accepts

def close_socket(connection):
    try:
        connection.shutdown(socket.SHUT_RDWR)
    except:
        pass
    try:
        connection.close()
    except:
        pass

def read():
    for i in reversed(range(len(connections))):
        try:
            data, sender = connections[i][0].recvfrom(1500)
            return data
        except (BlockingIOError, socket.timeout, OSError):
            pass
        except (ConnectionResetError, ConnectionAbortedError):
            close_socket(connections[i][0])
            connections.pop(i)
    return b''  # return empty if no data found

def write(data):
    for i in reversed(range(len(connections))):
        try:
            connections[i][0].sendto(data, connections[i][1])
        except (BlockingIOError, socket.timeout, OSError):
            pass
        except (ConnectionResetError, ConnectionAbortedError):
            close_socket(connections[i][0])
            connections.pop(i)

# Run the main loop
while True:
    try:
        con, addr = host.accept()
        connections.append((con, addr))
    except BlockingIOError:
        pass

    data = read()
    if data != b'':
        print(data)
        write(b'ECHO: ' + data)
        if data == b"exit":
            break

# Close the sockets
for i in reversed(range(len(connections))):
    close_socket(connections[i][0])
    connections.pop(i)
close_socket(host)

The client is similar

# tcp_client.py
import socket

ADDRESS = "localhost"
PORT = 54321

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((ADDRESS, PORT))
s.setblocking(0)

def close_socket(connection):
    try:
        connection.shutdown(socket.SHUT_RDWR)
    except:
        pass
    try:
        connection.close()
    except:
        pass

def read():
    """Read data and return the read bytes."""
    try:
        data, sender = s.recvfrom(1500)
        return data
    except (BlockingIOError, socket.timeout, AttributeError, OSError):
        return b''
    except (ConnectionResetError, ConnectionAbortedError, AttributeError):
        close_socket(s)
        return b''

def write(data):
    try:
        s.sendto(data, (ADDRESS, PORT))
    except (ConnectionResetError, ConnectionAbortedError):
        close_socket(s)

while True:
    msg = input("Enter a message: ")
    write(msg.encode('utf-8'))

    data = read()
    if data != b"":
        print("Message Received:", data)

    if msg == "exit":
        break

close_socket(s)

jQuery Ajax Request inside Ajax Request

Here is an example:

$.ajax({
        type: "post",
        url: "ajax/example.php",
        data: 'page=' + btn_page,
        success: function (data) {
            var a = data; // This line shows error.
            $.ajax({
                type: "post",
                url: "example.php",
                data: 'page=' + a,
                success: function (data) {

                }
            });
        }
    });

Difference between declaring variables before or in loop?

Well I ran your A and B examples 20 times each, looping 100 million times.(JVM - 1.5.0)

A: average execution time: .074 sec

B: average execution time : .067 sec

To my surprise B was slightly faster. As fast as computers are now its hard to say if you could accurately measure this. I would code it the A way as well but I would say it doesn't really matter.

How to declare a global variable in React?

I don't know what they're trying to say with this "React Context" stuff - they're talking Greek, to me, but here's how I did it:

Carrying values between functions, on the same page

In your constructor, bind your setter:

this.setSomeVariable = this.setSomeVariable.bind(this);

Then declare a function just below your constructor:

setSomeVariable(propertyTextToAdd) {
    this.setState({
        myProperty: propertyTextToAdd
    });
}

When you want to set it, call this.setSomeVariable("some value");

(You might even be able to get away with this.state.myProperty = "some value";)

When you want to get it, call var myProp = this.state.myProperty;

Using alert(myProp); should give you some value .

Extra scaffolding method to carry values across pages/components

You can assign a model to this (technically this.stores), so you can then reference it with this.state:

import Reflux from 'reflux'
import Actions from '~/actions/actions`

class YourForm extends Reflux.Store
{
    constructor()
    {
        super();
        this.state = {
            someGlobalVariable: '',
        };
        this.listenables = Actions;
        this.baseState = {
            someGlobalVariable: '',
        };
    }

    onUpdateFields(name, value) {
        this.setState({
            [name]: value,
        });
    }

    onResetFields() {
        this.setState({
           someGlobalVariable: '',
        });
    }
}
const reqformdata = new YourForm

export default reqformdata

Save this to a folder called stores as yourForm.jsx.

Then you can do this in another page:

import React from 'react'
import Reflux from 'reflux'
import {Form} from 'reactstrap'
import YourForm from '~/stores/yourForm.jsx'

Reflux.defineReact(React)

class SomePage extends Reflux.Component {
    constructor(props) {
        super(props);
        this.state = {
            someLocalVariable: '',
        }
        this.stores = [
            YourForm,
        ]
    }
    render() {

        const myVar = this.state.someGlobalVariable;
        return (
            <Form>
                <div>{myVar}</div>
            </Form>
        )
    }
}
export default SomePage

If you had set this.state.someGlobalVariable in another component using a function like:

setSomeVariable(propertyTextToAdd) {
    this.setState({
       myGlobalVariable: propertyTextToAdd
   });
}

that you bind in the constructor with:

this.setSomeVariable = this.setSomeVariable.bind(this);

the value in propertyTextToAdd would be displayed in SomePage using the code shown above.

Best HTTP Authorization header type for JWT

The best HTTP header for your client to send an access token (JWT or any other token) is the Authorization header with the Bearer authentication scheme.

This scheme is described by the RFC6750.

Example:

GET /resource HTTP/1.1
Host: server.example.com
Authorization: Bearer eyJhbGciOiJIUzI1NiIXVCJ9TJV...r7E20RMHrHDcEfxjoYZgeFONFh7HgQ

If you need stronger security protection, you may also consider the following IETF draft: https://tools.ietf.org/html/draft-ietf-oauth-pop-architecture. This draft seems to be a good alternative to the (abandoned?) https://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac.

Note that even if this RFC and the above specifications are related to the OAuth2 Framework protocol, they can be used in any other contexts that require a token exchange between a client and a server.

Unlike the custom JWT scheme you mention in your question, the Bearer one is registered at the IANA.

Concerning the Basic and Digest authentication schemes, they are dedicated to authentication using a username and a secret (see RFC7616 and RFC7617) so not applicable in that context.

How to insert the current timestamp into MySQL database using a PHP insert query

Your usage of now() is correct. However, you need to use one type of quotes around the entire query and another around the values.

You can modify your query to use double quotes at the beginning and end, and single quotes around $somename:

$update_query = "UPDATE db.tablename SET insert_time=now() WHERE username='$somename'";

Angular 1 - get current URL parameters

ex: url/:id

var sample= app.controller('sample', function ($scope, $routeParams) {
  $scope.init = function () {
    var qa_id = $routeParams.qa_id;
  }
});

What is a typedef enum in Objective-C?

Apple recommends defining enums like this since Xcode 4.4:

typedef enum ShapeType : NSUInteger {
    kCircle,
    kRectangle,
    kOblateSpheroid
} ShapeType;

They also provide a handy macro NS_ENUM:

typedef NS_ENUM(NSUInteger, ShapeType) {
    kCircle,
    kRectangle,
    kOblateSpheroid
};

These definitions provide stronger type checking and better code completion. I could not find official documentation of NS_ENUM, but you can watch the "Modern Objective-C" video from WWDC 2012 session here.


UPDATE
Link to official documentation here.

Convert a list of objects to an array of one of the object's properties

You are looking for

MyList.Select(x=>x.Name).ToArray();

Since Select is an Extension method make sure to add that namespace by adding a

using System.Linq

to your file - then it will show up with Intellisense.

How do I remove background-image in css?

Doesn't this work:

.clear-background{
background-image: none;
}

Might have problems on older browsers...

Permission denied at hdfs

Start a shell as hduser (from root) and run your command

sudo -u hduser bash
hadoop fs -put /usr/local/input-data/ /input

[update] Also note that the hdfs user is the super user and has all r/w privileges.

Named parameters in JDBC

To avoid including a large framework, I think a simple homemade class can do the trick.

Example of class to handle named parameters:

public class NamedParamStatement {
    public NamedParamStatement(Connection conn, String sql) throws SQLException {
        int pos;
        while((pos = sql.indexOf(":")) != -1) {
            int end = sql.substring(pos).indexOf(" ");
            if (end == -1)
                end = sql.length();
            else
                end += pos;
            fields.add(sql.substring(pos+1,end));
            sql = sql.substring(0, pos) + "?" + sql.substring(end);
        }       
        prepStmt = conn.prepareStatement(sql);
    }

    public PreparedStatement getPreparedStatement() {
        return prepStmt;
    }
    public ResultSet executeQuery() throws SQLException {
        return prepStmt.executeQuery();
    }
    public void close() throws SQLException {
        prepStmt.close();
    }

    public void setInt(String name, int value) throws SQLException {        
        prepStmt.setInt(getIndex(name), value);
    }

    private int getIndex(String name) {
        return fields.indexOf(name)+1;
    }
    private PreparedStatement prepStmt;
    private List<String> fields = new ArrayList<String>();
}

Example of calling the class:

String sql;
sql = "SELECT id, Name, Age, TS FROM TestTable WHERE Age < :age OR id = :id";
NamedParamStatement stmt = new NamedParamStatement(conn, sql);
stmt.setInt("age", 35);
stmt.setInt("id", 2);
ResultSet rs = stmt.executeQuery();

Please note that the above simple example does not handle using named parameter twice. Nor does it handle using the : sign inside quotes.

How do I use a custom deleter with a std::unique_ptr member?

You can simply use std::bind with a your destroy function.

std::unique_ptr<Bar, std::function<void(Bar*)>> bar(create(), std::bind(&destroy,
    std::placeholders::_1));

But of course you can also use a lambda.

std::unique_ptr<Bar, std::function<void(Bar*)>> ptr(create(), [](Bar* b){ destroy(b);});

How to check if a query string value is present via JavaScript?

one more variant, but almost the same as Gumbos solution:

var isDebug = function(){
    return window.location.href.search("[?&]debug=") != -1;
};

How to disable/enable select field using jQuery?

Disabled is a Boolean Attribute of the select element as stated by WHATWG, that means the RIGHT WAY TO DISABLE with jQuery would be

jQuery("#selectId").attr('disabled',true);

This would make this HTML

<select id="selectId" name="gender" disabled="disabled">
    <option value="-1">--Select a Gender--</option>
    <option value="0">Male</option>
    <option value="1">Female</option>
</select>

This works for both XHTML and HTML (W3School reference)

Yet it also can be done using it as property

jQuery("#selectId").prop('disabled', 'disabled');

getting

<select id="selectId" name="gender" disabled>

Which only works for HTML and not XTML

NOTE: A disabled element will not be submitted with the form as answered in this question: The disabled form element is not submitted

NOTE2: A disabled element may be greyed out.

NOTE3:

A form control that is disabled must prevent any click events that are queued on the user interaction task source from being dispatched on the element.

TL;DR

<script>
    var update_pizza = function () {
        if ($("#pizza").is(":checked")) {
            $('#pizza_kind').attr('disabled', false);
        } else {
            $('#pizza_kind').attr('disabled', true);
        }
    };
    $(update_pizza);
    $("#pizza").change(update_pizza);
</script>

Generating Random Passwords

public string GenerateToken(int length)
{
    using (RNGCryptoServiceProvider cryptRNG = new RNGCryptoServiceProvider())
    {
        byte[] tokenBuffer = new byte[length];
        cryptRNG.GetBytes(tokenBuffer);
        return Convert.ToBase64String(tokenBuffer);
    }
}

(You could also have the class where this method lives implement IDisposable, hold a reference to the RNGCryptoServiceProvider, and dispose of it properly, to avoid repeatedly instantiating it.)

It's been noted that as this returns a base-64 string, the output length is always a multiple of 4, with the extra space using = as a padding character. The length parameter specifies the length of the byte buffer, not the output string (and is therefore perhaps not the best name for that parameter, now I think about it). This controls how many bytes of entropy the password will have. However, because base-64 uses a 4-character block to encode each 3 bytes of input, if you ask for a length that's not a multiple of 3, there will be some extra "space", and it'll use = to fill the extra.

If you don't like using base-64 strings for any reason, you can replace the Convert.ToBase64String() call with either a conversion to regular string, or with any of the Encoding methods; eg. Encoding.UTF8.GetString(tokenBuffer) - just make sure you pick a character set that can represent the full range of values coming out of the RNG, and that produces characters that are compatible with wherever you're sending or storing this. Using Unicode, for example, tends to give a lot of Chinese characters. Using base-64 guarantees a widely-compatible set of characters, and the characteristics of such a string shouldn't make it any less secure as long as you use a decent hashing algorithm.

Application Error - The connection to the server was unsuccessful. (file:///android_asset/www/index.html)

As you said, there are many duplicate questions on the same topic. Any how explaining your situation.

The problem might be solved by adding a timeout to call your index.html

ie you need to add super.setIntegerProperty("loadUrlTimeoutValue", 70000); in your activity.java file ( inside src/com/yourProj/--/youractivity.java) above this line: super.loadUrl("file:///android_asset/www/index.html");

Explanation:

This can be happened due to the following reasons

The core reason: the problem is likely due to the speed of the emulator so the network is too slow complete the communication in a timely fashion.

This can be due to:

  1. Your code/data/image is of too much of size ( I guess in your case you are using some images ,as you said you made some UI modifications, may be the size of images are high)
  2. Your script may have a infinite or long loop, so that it takes too much of time to load.
  3. You will be using too much of scripts (jQuery, iscroll, etc etc.. more number of plugins or scripts )

Set a cookie to never expire

Set a far future absolute time:

setcookie("CookieName", "CookieValue", 2147483647);

It is better to use an absolute time than calculating it relative to the present as recommended in the accepted answer.

The maximum value compatible with 32 bits systems is:

2147483647 = 2^31 = ~year 2038

Specific Time Range Query in SQL Server

select * from table where 
(dtColumn between #3/1/2009# and #3/31/2009#) and 
(hour(dtColumn) between 6 and 22) and 
(weekday(dtColumn, 1) between 2 and 4) 

JQuery confirm dialog

Try this one

$('<div></div>').appendTo('body')
  .html('<div><h6>Yes or No?</h6></div>')
  .dialog({
      modal: true, title: 'message', zIndex: 10000, autoOpen: true,
      width: 'auto', resizable: false,
      buttons: {
          Yes: function () {
              doFunctionForYes();
              $(this).dialog("close");
          },
          No: function () {
              doFunctionForNo();
              $(this).dialog("close");
          }
      },
      close: function (event, ui) {
          $(this).remove();
      }
});

Fiddle

Process list on Linux via Python

I would use the subprocess module to execute the command ps with appropriate options. By adding options you can modify which processes you see. Lot's of examples on subprocess on SO. This question answers how to parse the output of ps for example:)

You can, as one of the example answers showed also use the PSI module to access system information (such as the process table in this example).

Can you use CSS to mirror/flip text?

There's also the rotateY for a real mirror one:

transform: rotateY(180deg);

Which, perhaps, is even more clear and understandable.

EDIT: Doesn't seem to work on Opera though… sadly. But it works fine on Firefox. I guess it might required to implicitly say that we are doing some kind of translate3d perhaps? Or something like that.

What is a constant reference? (not a reference to a constant)

This code is ill-formed:

int&const icr=i;

Reference: C++17 [dcl.ref]/1:

Cv-qualified references are ill-formed except when the cv-qualifiers are introduced through the use of a typedef-name or decltype-specifier, in which case the cv-qualifiers are ignored.

This rule has been present in all standardized versions of C++. Because the code is ill-formed:

  • you should not use it, and
  • there is no associated behaviour.

The compiler should reject the program; and if it doesn't, the executable's behaviour is completely undefined.

NB: Not sure how none of the other answers mentioned this yet... nobody's got access to a compiler?

Hive External Table Skip First Row

I am not quite sure if it works with ROW FORMAT serde 'com.bizo.hive.serde.csv.CSVSerde' but I guess that it should be similar to ROW FORMAT DELIMITED FIELDS TERMINATED BY ','.
In your case first row will be treated like normal row. But first field fails to be INT so all fields, for first row, will be set as NULL. You need only one intermediate step to fix it:

INSERT OVERWRITE TABLE Test
SELECT * from Test WHERE RecordId IS NOT NULL

Only one drawback is that your original csv file will be modified. I hope it helps. GL!

PHP "php://input" vs $_POST

First, a basic truth about PHP.

PHP was not designed to explicitly give you a pure REST (GET, POST, PUT, PATCH, DELETE) like interface for handling HTTP requests.

However, the $_SERVER, $_COOKIE, $_POST, $_GET, and $_FILES superglobals, and the function filter_input_array() are very useful for the average person's / layman's needs.

The number one hidden advantage of $_POST (and $_GET) is that your input data is url-decoded automatically by PHP. You never even think about having to do it, especially for query string parameters within a standard GET request, or HTTP body data submitted with a POST request.

Other HTTP Request Methods

Those studying the underlying HTTP protocol and its various request methods come to understand that there are many HTTP request methods, including the often referenced PUT, PATCH (not used in Google's Apigee), and DELETE.

In PHP, there are no superglobals or input filter functions for getting HTTP request body data when POST is not used. What are disciples of Roy Fielding to do? ;-)

However, then you learn more ...

That being said, as you advance in your PHP programming knowledge and want to use JavaScript's XmlHttpRequest object (jQuery for some), you come to see the limitation of this scheme.

$_POST limits you to the use of two media types in the HTTP Content-Type header:

  1. application/x-www-form-urlencoded, and
  2. multipart/form-data

Thus, if you want to send data values to PHP on the server, and have it show up in the $_POST superglobal, then you must urlencode it on the client-side and send said data as key/value pairs--an inconvenient step for novices (especially when trying to figure out if different parts of the URL require different forms of urlencoding: normal, raw, etc..).

For all you jQuery users, the $.ajax() method is converting your JSON to URL encoded key/value pairs before transmitting them to the server. You can override this behavior by setting processData: false. Just read the $.ajax() documentation, and don't forget to send the correct media type in the Content-Type header.

php://input, but ...

Even if you use php://input instead of $_POST for your HTTP POST request body data, it will not work with an HTTP Content-Type of multipart/form-data This is the content type that you use on an HTML form when you want to allow file uploads!

<form enctype="multipart/form-data" accept-charset="utf-8" action="post">
    <input type="file" name="resume">
</form>

Therefore, in traditional PHP, to deal with a diversity of content types from an HTTP POST request, you will learn to use $_POST or filter_input_array(POST), $_FILES, and php://input. There is no way to just use one, universal input source for HTTP POST requests in PHP.

You cannot get files through $_POST, filter_input_array(POST), or php://input, and you cannot get JSON/XML/YAML in either filter_input_array(POST) or $_POST.

PHP Manual: php://input

php://input is a read-only stream that allows you to read raw data from the request body...php://input is not available with enctype="multipart/form-data".

PHP Frameworks to the rescue?

PHP frameworks like Codeigniter 4 and Laravel use a facade to provide a cleaner interface (IncomingRequest or Request objects) to the above. This is why professional PHP developers use frameworks instead of raw PHP.

Of course, if you like to program, you can devise your own facade object to provide what frameworks do. It is because I have taken time to investigate this issue that I am able to write this answer.

URL encoding? What the heck!!!???

Typically, if you are doing a normal, synchronous (when the entire page redraws) HTTP requests with an HTML form, the user-agent (web browser) will urlencode your form data for you. If you want to do an asynchronous HTTP requests using the XmlHttpRequest object, then you must fashion a urlencoded string and send it, if you want that data to show up in the $_POST superglobal.

How in touch are you with JavaScript? :-)

Converting from a JavaScript array or object to a urlencoded string bothers many developers (even with new APIs like Form Data). They would much rather just be able to send JSON, and it would be more efficient for the client code to do so.

Remember (wink, wink), the average web developer does not learn to use the XmlHttpRequest object directly, global functions, string functions, array functions, and regular expressions like you and I ;-). Urlencoding for them is a nightmare. ;-)

PHP, what gives?

PHP's lack of intuitive XML and JSON handling turns many people off. You would think it would be part of PHP by now (sigh).

So many media types (MIME types in the past)

XML, JSON, and YAML all have media types that can be put into an HTTP Content-Type header.

  • application/xml
  • applicaiton/json
  • application/yaml (although IANA has no official designation listed)

Look how many media-types (formerly, MIME types) are defined by IANA.

Look how many HTTP headers there are.

php://input or bust

Using the php://input stream allows you to circumvent the baby-sitting / hand holding level of abstraction that PHP has forced on the world. :-) With great power comes great responsibility!

Now, before you deal with data values streamed through php://input, you should / must do a few things.

  1. Determine if the correct HTTP method has been indicated (GET, POST, PUT, PATCH, DELETE, ...)
  2. Determine if the HTTP Content-Type header has been transmitted.
  3. Determine if the value for the Content-Type is the desired media type.
  4. Determine if the data sent is well formed XML / JSON / YAML / etc.
  5. If necessary, convert the data to a PHP datatype: array or object.
  6. If any of these basic checks or conversions fails, throw an exception!

What about the character encoding?

AH, HA! Yes, you might want the data stream being sent into your application to be UTF-8 encoded, but how can you know if it is or not?

Two critical problems.

  1. You do not know how much data is coming through php://input.
  2. You do not know for certain the current encoding of the data stream.

Are you going to attempt to handle stream data without knowing how much is there first? That is a terrible idea. You cannot rely exclusively on the HTTP Content-Length header for guidance on the size of streamed input because it can be spoofed.

You are going to need a:

  1. Stream size detection algorithm.
  2. Application defined stream size limits (Apache / Nginx / PHP limits may be too broad).

Are you going to attempt to convert stream data to UTF-8 without knowing the current encoding of the stream? How? The iconv stream filter (iconv stream filter example) seems to want a starting and ending encoding, like this.

'convert.iconv.ISO-8859-1/UTF-8'

Thus, if you are conscientious, you will need:

  1. Stream encoding detection algorithm.
  2. Dynamic / runtime stream filter definition algorithm (because you cannot know the starting encoding a priori).

(Update: 'convert.iconv.UTF-8/UTF-8' will force everything to UTF-8, but you still have to account for characters that the iconv library might not know how to translate. In other words, you have to some how define what action to take when a character cannot be translated: 1) Insert a dummy character, 2) Fail / throw and exception).

You cannot rely exclusively on the HTTP Content-Encoding header, as this might indicate something like compression as in the following. This is not what you want to make a decision off of in regards to iconv.

Content-Encoding: gzip

Therefore, the general steps might be ...

Part I: HTTP Request Related

  1. Determine if the correct HTTP method has been indicated (GET, POST, PUT, PATCH, DELETE, ...)
  2. Determine if the HTTP Content-Type header has been transmitted.
  3. Determine if the value for the Content-Type is the desired media type.

Part II: Stream Data Related

  1. Determine the size of the input stream (optional, but recommended).
  2. Determine the encoding of the input stream.
  3. If necessary, convert the input stream to the desired character encoding (UTF-8).
  4. If necessary, reverse any application level compression or encryption, and then repeat steps 4, 5, and 6.

Part III: Data Type Related

  1. Determine if the data sent is well formed XML / JSON / YMAL / etc.

(Remember, the data can still be a URL encoded string which you must then parse and URL decode).

  1. If necessary, convert the data to a PHP datatype: array or object.

Part IV: Data Value Related

  1. Filter input data.

  2. Validate input data.

Now do you see?

The $_POST superglobal, along with php.ini settings for limits on input, are simpler for the layman. However, dealing with character encoding is much more intuitive and efficient when using streams because there is no need to loop through superglobals (or arrays, generally) to check input values for the proper encoding.

How to get progress from XMLHttpRequest

For the total uploaded there doesn't seem to be a way to handle that, but there's something similar to what you want for download. Once readyState is 3, you can periodically query responseText to get all the content downloaded so far as a String (this doesn't work in IE), up until all of it is available at which point it will transition to readyState 4. The total bytes downloaded at any given time will be equal to the total bytes in the string stored in responseText.

For a all or nothing approach to the upload question, since you have to pass a string for upload (and it's possible to determine the total bytes of that) the total bytes sent for readyState 0 and 1 will be 0, and the total for readyState 2 will be the total bytes in the string you passed in. The total bytes both sent and received in readyState 3 and 4 will be the sum of the bytes in the original string plus the total bytes in responseText.

How to set cornerRadius for only top-left and top-right corner of a UIView?

Simple extension

extension UIView {
    func roundCorners(corners: UIRectCorner, radius: CGFloat) {
        if #available(iOS 11, *) {
            self.clipsToBounds = true
            self.layer.cornerRadius = radius
            var masked = CACornerMask()
            if corners.contains(.topLeft) { masked.insert(.layerMinXMinYCorner) }
            if corners.contains(.topRight) { masked.insert(.layerMaxXMinYCorner) }
            if corners.contains(.bottomLeft) { masked.insert(.layerMinXMaxYCorner) }
            if corners.contains(.bottomRight) { masked.insert(.layerMaxXMaxYCorner) }
            self.layer.maskedCorners = masked
        }
        else {
            let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
            let mask = CAShapeLayer()
            mask.path = path.cgPath
            layer.mask = mask
        }
    }
}

Usage:

view.roundCorners(corners: [.bottomLeft, .bottomRight], radius: 12)

Counter increment in Bash loop not working

COUNTER=1
while [ Your != "done" ]
do
     echo " $COUNTER "
     COUNTER=$[$COUNTER +1]
done

TESTED BASH: Centos, SuSE, RH

Right query to get the current number of connections in a PostgreSQL DB

Number of TCP connections will help you. Remember that it is not for a particular database

netstat -a -n | find /c "127.0.0.1:13306"

Two submit buttons in one form

HTML example to send different form action on different button click:

<form action="/login" method="POST">
        <input type="text" name="username" value="your_username" />
        <input type="password" name="password" value="your_password" />
        <button type="submit">Login</button>
        <button type="submit" formaction="/users" formmethod="POST">Add User</button>
</form>

Same form is being used to add a new user and login user.