Programs & Examples On #Xmlunit

XMLUnit is an open source project which enables JUnit-style assertions to be made about the content and structure of XML.

CSS float right not working correctly

You have not used float:left command for your text.

Permission denied on accessing host directory in Docker

In my situation the problem was different. I don't know why, but even if directory on host had chmod 777 run on it, inside docker it was visible as 755.

Running inside container sudo chmod 777 my_volume_dir fixed it.

Declare a variable in DB2 SQL

I imagine this forum posting, which I quote fully below, should answer the question.


Inside a procedure, function, or trigger definition, or in a dynamic SQL statement (embedded in a host program):

BEGIN ATOMIC
 DECLARE example VARCHAR(15) ;
 SET example = 'welcome' ;
 SELECT *
 FROM   tablename
 WHERE  column1 = example ;
END

or (in any environment):

WITH t(example) AS (VALUES('welcome'))
SELECT *
FROM   tablename, t
WHERE  column1 = example

or (although this is probably not what you want, since the variable needs to be created just once, but can be used thereafter by everybody although its content will be private on a per-user basis):

CREATE VARIABLE example VARCHAR(15) ;
SET example = 'welcome' ;
SELECT *
FROM   tablename
WHERE  column1 = example ;

How does one remove a Docker image?

To remove an image from Docker using the image ID:

  1. Get the list of all Images

    docker images
    
  2. Identify the image ID of the image you want to delete, for example:

    REPOSITORY     TAG     IMAGE ID        CREATED        VIRTUAL SIZE
    kweku360/java  latest  08d3a9b8e166    2 weeks ago         5.733 GB`
    
  3. Finally remove the image using the image ID (only the first three digits are required)

    docker rmi 08d
    

What exactly is std::atomic?

std::atomic exists because many ISAs have direct hardware support for it

What the C++ standard says about std::atomic has been analyzed in other answers.

So now let's see what std::atomic compiles to to get a different kind of insight.

The main takeaway from this experiment is that modern CPUs have direct support for atomic integer operations, for example the LOCK prefix in x86, and std::atomic basically exists as a portable interface to those intructions: What does the "lock" instruction mean in x86 assembly? In aarch64, LDADD would be used.

This support allows for faster alternatives to more general methods such as std::mutex, which can make more complex multi-instruction sections atomic, at the cost of being slower than std::atomic because std::mutex it makes futex system calls in Linux, which is way slower than the userland instructions emitted by std::atomic, see also: Does std::mutex create a fence?

Let's consider the following multi-threaded program which increments a global variable across multiple threads, with different synchronization mechanisms depending on which preprocessor define is used.

main.cpp

#include <atomic>
#include <iostream>
#include <thread>
#include <vector>

size_t niters;

#if STD_ATOMIC
std::atomic_ulong global(0);
#else
uint64_t global = 0;
#endif

void threadMain() {
    for (size_t i = 0; i < niters; ++i) {
#if LOCK
        __asm__ __volatile__ (
            "lock incq %0;"
            : "+m" (global),
              "+g" (i) // to prevent loop unrolling
            :
            :
        );
#else
        __asm__ __volatile__ (
            ""
            : "+g" (i) // to prevent he loop from being optimized to a single add
            : "g" (global)
            :
        );
        global++;
#endif
    }
}

int main(int argc, char **argv) {
    size_t nthreads;
    if (argc > 1) {
        nthreads = std::stoull(argv[1], NULL, 0);
    } else {
        nthreads = 2;
    }
    if (argc > 2) {
        niters = std::stoull(argv[2], NULL, 0);
    } else {
        niters = 10;
    }
    std::vector<std::thread> threads(nthreads);
    for (size_t i = 0; i < nthreads; ++i)
        threads[i] = std::thread(threadMain);
    for (size_t i = 0; i < nthreads; ++i)
        threads[i].join();
    uint64_t expect = nthreads * niters;
    std::cout << "expect " << expect << std::endl;
    std::cout << "global " << global << std::endl;
}

GitHub upstream.

Compile, run and disassemble:

comon="-ggdb3 -O3 -std=c++11 -Wall -Wextra -pedantic main.cpp -pthread"
g++ -o main_fail.out                    $common
g++ -o main_std_atomic.out -DSTD_ATOMIC $common
g++ -o main_lock.out       -DLOCK       $common

./main_fail.out       4 100000
./main_std_atomic.out 4 100000
./main_lock.out       4 100000

gdb -batch -ex "disassemble threadMain" main_fail.out
gdb -batch -ex "disassemble threadMain" main_std_atomic.out
gdb -batch -ex "disassemble threadMain" main_lock.out

Extremely likely "wrong" race condition output for main_fail.out:

expect 400000
global 100000

and deterministic "right" output of the others:

expect 400000
global 400000

Disassembly of main_fail.out:

   0x0000000000002780 <+0>:     endbr64 
   0x0000000000002784 <+4>:     mov    0x29b5(%rip),%rcx        # 0x5140 <niters>
   0x000000000000278b <+11>:    test   %rcx,%rcx
   0x000000000000278e <+14>:    je     0x27b4 <threadMain()+52>
   0x0000000000002790 <+16>:    mov    0x29a1(%rip),%rdx        # 0x5138 <global>
   0x0000000000002797 <+23>:    xor    %eax,%eax
   0x0000000000002799 <+25>:    nopl   0x0(%rax)
   0x00000000000027a0 <+32>:    add    $0x1,%rax
   0x00000000000027a4 <+36>:    add    $0x1,%rdx
   0x00000000000027a8 <+40>:    cmp    %rcx,%rax
   0x00000000000027ab <+43>:    jb     0x27a0 <threadMain()+32>
   0x00000000000027ad <+45>:    mov    %rdx,0x2984(%rip)        # 0x5138 <global>
   0x00000000000027b4 <+52>:    retq

Disassembly of main_std_atomic.out:

   0x0000000000002780 <+0>:     endbr64 
   0x0000000000002784 <+4>:     cmpq   $0x0,0x29b4(%rip)        # 0x5140 <niters>
   0x000000000000278c <+12>:    je     0x27a6 <threadMain()+38>
   0x000000000000278e <+14>:    xor    %eax,%eax
   0x0000000000002790 <+16>:    lock addq $0x1,0x299f(%rip)        # 0x5138 <global>
   0x0000000000002799 <+25>:    add    $0x1,%rax
   0x000000000000279d <+29>:    cmp    %rax,0x299c(%rip)        # 0x5140 <niters>
   0x00000000000027a4 <+36>:    ja     0x2790 <threadMain()+16>
   0x00000000000027a6 <+38>:    retq   

Disassembly of main_lock.out:

Dump of assembler code for function threadMain():
   0x0000000000002780 <+0>:     endbr64 
   0x0000000000002784 <+4>:     cmpq   $0x0,0x29b4(%rip)        # 0x5140 <niters>
   0x000000000000278c <+12>:    je     0x27a5 <threadMain()+37>
   0x000000000000278e <+14>:    xor    %eax,%eax
   0x0000000000002790 <+16>:    lock incq 0x29a0(%rip)        # 0x5138 <global>
   0x0000000000002798 <+24>:    add    $0x1,%rax
   0x000000000000279c <+28>:    cmp    %rax,0x299d(%rip)        # 0x5140 <niters>
   0x00000000000027a3 <+35>:    ja     0x2790 <threadMain()+16>
   0x00000000000027a5 <+37>:    retq

Conclusions:

  • the non-atomic version saves the global to a register, and increments the register.

    Therefore, at the end, very likely four writes happen back to global with the same "wrong" value of 100000.

  • std::atomic compiles to lock addq. The LOCK prefix makes the following inc fetch, modify and update memory atomically.

  • our explicit inline assembly LOCK prefix compiles to almost the same thing as std::atomic, except that our inc is used instead of add. Not sure why GCC chose add, considering that our INC generated a decoding 1 byte smaller.

ARMv8 could use either LDAXR + STLXR or LDADD in newer CPUs: How do I start threads in plain C?

Tested in Ubuntu 19.10 AMD64, GCC 9.2.1, Lenovo ThinkPad P51.

JAVA - using FOR, WHILE and DO WHILE loops to sum 1 through 100

Your for loop looks good.

A possible while loop to accomplish the same thing:

int sum = 0;
int i = 1;
while (i <= 100) {
    sum += i;
    i++;
}
System.out.println("The sum is " + sum);

A possible do while loop to accomplish the same thing:

int sum = 0;
int i = 1;
do {
    sum += i;
    i++;
} while (i <= 100);
System.out.println("The sum is " + sum);

The difference between the while and the do while is that, with the do while, at least one iteration is sure to occur.

npm install won't install devDependencies

Check if npm config production value is set to true. If this value is true, it will skip over the dev dependencies.

Run npm config get production

To set it: npm config set -g production false

How to include vars file in a vars file with ansible?

You can put your servers in the default_step group and those vars will apply to it:

# inventory file
[default_step]
prod2
web_v2

Then just move your default_step.yml file to group_vars/default_step.yml.

Cannot execute script: Insufficient memory to continue the execution of the program

use the command-line tool SQLCMD which is much leaner on memory. It is as simple as:

SQLCMD -d <database-name> -i filename.sql

You need valid credentials to access your SQL Server instance or even to access a database

Taken from here.

PYTHONPATH on Linux

1) PYTHONPATH is an environment variable which you can set to add additional directories where python will look for modules and packages. e.g.:

# make python look in the foo subdirectory of your home directory for
# modules and packages 
export PYTHONPATH=${PYTHONPATH}:${HOME}/foo 

Here I use the sh syntax. For other shells (e.g. csh,tcsh), the syntax would be slightly different. To make it permanent, set the variable in your shell's init file (usually ~/.bashrc).

2) Ubuntu comes with python already installed. There may be reasons for installing other (independent) python versions, but I've found that to be rarely necessary.

3) The folder where your modules live is dependent on PYTHONPATH and where the directories were set up when python was installed. For the most part, the installed stuff you shouldn't care about where it lives -- Python knows where it is and it can find the modules. Sort of like issuing the command ls -- where does ls live? /usr/bin? /bin? 99% of the time, you don't need to care -- Just use ls and be happy that it lives somewhere on your PATH so the shell can find it.

4) I'm not sure I understand the question. 3rd party modules usually come with install instructions. If you follow the instructions, python should be able to find the module and you shouldn't have to care about where it got installed.

5) Configure PYTHONPATH to include the directory where your module resides and python will be able to find your module.

Getting values from JSON using Python

Using Python to extract a value from the provided Json

Working sample:-

import json
import sys

//load the data into an element
data={"test1" : "1", "test2" : "2", "test3" : "3"}

//dumps the json object into an element
json_str = json.dumps(data)

//load the json to a string
resp = json.loads(json_str)

//print the resp
print (resp)

//extract an element in the response
print (resp['test1'])

DLL References in Visual C++

You mention adding the additional include directory (C/C++|General) and additional lib dependency (Linker|Input), but have you also added the additional library directory (Linker|General)?

Including a sample error message might also help people answer the question since it's not even clear if the error is during compilation or linking.

CSS Progress Circle

Another pure css based solution that is based on two clipped rounded elements that i rotate to get to the right angle:

http://jsfiddle.net/maayan/byT76/

That's the basic css that enables it:

.clip1 {
    position:absolute;
    top:0;left:0;
    width:200px;
    height:200px;
    clip:rect(0px,200px,200px,100px);
}
.slice1 {
    position:absolute;
    width:200px;
    height:200px;
    clip:rect(0px,100px,200px,0px);
    -moz-border-radius:100px;
    -webkit-border-radius:100px; 
    border-radius:100px;
    background-color:#f7e5e1;
    border-color:#f7e5e1;
    -moz-transform:rotate(0);
    -webkit-transform:rotate(0);
    -o-transform:rotate(0);
    transform:rotate(0);
}

.clip2 
{
    position:absolute;
    top:0;left:0;
    width:200px;
    height:200px;
    clip:rect(0,100px,200px,0px);
}

.slice2
{
    position:absolute;
    width:200px;
    height:200px;
    clip:rect(0px,200px,200px,100px);
    -moz-border-radius:100px;
    -webkit-border-radius:100px; 
    border-radius:100px;
    background-color:#f7e5e1;
    border-color:#f7e5e1;
    -moz-transform:rotate(0);
    -webkit-transform:rotate(0);
    -o-transform:rotate(0);
    transform:rotate(0);
}

and the js rotates it as required.

quite easy to understand..

Hope it helps, Maayan

How do I run Redis on Windows?

You can use Memurai for Windows, a Redis-compatible cache and datastore for Windows, currently compatible with Redis 5. Memurai aims to fulfill the need for a supported Redis-compatible datastore on the Windows platform. At its core, it’s based on Redis source code, ported to run natively on Windows, and it’s designed to provide the level of reliability and performance required for production environments. Memurai is free for development and testing. You can learn more and download Memurai at https://www.memurai.com.

Alexis Campailla
CEO, Memurai

Regex, every non-alphanumeric character except white space or colon

Try this:

[^a-zA-Z0-9 :]

JavaScript example:

"!@#$%* ABC def:123".replace(/[^a-zA-Z0-9 :]/g, ".")

See a online example:

http://jsfiddle.net/vhMy8/

OpenCV with Network Cameras

rtsp protocol did not work for me. mjpeg worked first try. I assume it is built into my camera (Dlink DCS 900).

Syntax found here: http://answers.opencv.org/question/133/how-do-i-access-an-ip-camera/

I did not need to compile OpenCV with ffmpg support.

Unable to locate tools.jar

tools.jar comes with JDK, but what happens in your case it looks for it within /Java/jre6. Change JAVA_HOME env var to one of your JDK home.

g++ undefined reference to typeinfo

Possible solutions for code that deal with RTTI and non-RTTI libraries:

a) Recompile everything with either -frtti or -fno-rtti
b) If a) is not possible for you, try the following:

Assume libfoo is built without RTTI. Your code uses libfoo and compiles with RTTI. If you use a class (Foo) in libfoo that has virtuals, you're likely to run into a link-time error that says: missing typeinfo for class Foo.

Define another class (e.g. FooAdapter) that has no virtual and will forward calls to Foo that you use.

Compile FooAdapter in a small static library that doesn't use RTTI and only depends on libfoo symbols. Provide a header for it and use that instead in your code (which uses RTTI). Since FooAdapter has no virtual function it won't have any typeinfo and you'll be able to link your binary. If you use a lot of different classes from libfoo, this solution may not be convenient, but it's a start.

Retrieving a random item from ArrayList

your print comes after you return -- you can never reach that statement. Also, you never declared anyItem to be a variable. You might want

public Item anyItem()
    {
        int index = randomGenerator.nextInt(catalogue.size());
        Item randomItem = catalogue.get(index);
        System.out.println("Managers choice this week" + randomItem.toString() + "our recommendation to you");
        return randomItem;
    }

The toString part is just a quickie -- you might want to add a method 'getItemDescription' that returns a useful String for this purpose...

Awk if else issues

Try the code

awk '{s=($3==0)?"-":$3/$4; print s}'

Find when a file was deleted in Git

Git log but you need to prefix the path with --

Eg:

dan-mac:test dani$ git log file1.txt
fatal: ambiguous argument 'file1.txt': unknown revision or path not in the working tree.

dan-mac:test dani$ git log -- file1.txt
 commit 0f7c4e1c36e0b39225d10b26f3dea40ad128b976
 Author: Daniel Palacio <[email protected]>
 Date:   Tue Jul 26 23:32:20 2011 -0500

 foo

Compare two folders which has many files inside contents

Diff command in Unix is used to find the differences between files(all types). Since directory is also a type of file, the differences between two directories can easily be figure out by using diff commands. For more option use man diff on your unix box.

 -b              Ignores trailing blanks  (spaces  and  tabs)
                 and   treats  other  strings  of  blanks  as
                 equivalent.

 -i              Ignores the case of  letters.  For  example,
                 `A' will compare equal to `a'.
 -t              Expands <TAB> characters  in  output  lines.
                 Normal or -c output adds character(s) to the
                 front of each line that may adversely affect
                 the indentation of the original source lines
                 and  make  the  output  lines  difficult  to
                 interpret.  This  option  will  preserve the
                 original source's indentation.

 -w              Ignores all blanks (<SPACE> and <TAB>  char-
                 acters)  and  treats  all  other  strings of
                 blanks   as   equivalent.    For    example,
                 `if ( a == b )'   will   compare   equal  to
                 `if(a==b)'.

and there are many more.

What is a Subclass

A subclass in java, is a class that inherits from another class.

Inheritance is a way for classes to add specialized behavior ontop of generalized behavior. This is often represented by the phrase "is a" relationship.

For example, a Triangle is a Shape, so it might make sense to implement a Shape class, and have the Triangle class inherit from it. In this example, Shape is the superclass of Triangle and Triangle is the subclass of Shape

How to delete object?

What you're asking is not possible. There is no mechanism in .Net that would set all references to some object to null.

And I think that the fact that you're trying to do this indicates some sort of design problem. You should probably think about the underlying problem and solve it in another way (the other answers here suggest some options).

Centering image and text in R Markdown for a PDF report

none of the answers worked but this

\newcommand{\bcenter}{\begin{center}}
\newcommand{\ecenter}{\end{center}}

but then the following problem is that it works for only one figure and then will not for any other figures.

I just started learning R I knew it was going to be difficult but what's worst is that there is little to no info that I can refer to.

Java - get the current class name?

I'm assuming this is happening for an anonymous class. When you create an anonymous class you actually create a class that extends the class whose name you got.

The "cleaner" way to get the name you want is:

If your class is an anonymous inner class, getSuperClass() should give you the class that it was created from. If you created it from an interface than you're sort of SOL because the best you can do is getInterfaces() which might give you more than one interface.

The "hacky" way is to just get the name with getClassName() and use a regex to drop the $1.

Best way to replace multiple characters in a string?

FYI, this is of little or no use to the OP but it may be of use to other readers (please do not downvote, I'm aware of this).

As a somewhat ridiculous but interesting exercise, wanted to see if I could use python functional programming to replace multiple chars. I'm pretty sure this does NOT beat just calling replace() twice. And if performance was an issue, you could easily beat this in rust, C, julia, perl, java, javascript and maybe even awk. It uses an external 'helpers' package called pytoolz, accelerated via cython (cytoolz, it's a pypi package).

from cytoolz.functoolz import compose
from cytoolz.itertoolz import chain,sliding_window
from itertools import starmap,imap,ifilter
from operator import itemgetter,contains
text='&hello#hi&yo&'
char_index_iter=compose(partial(imap, itemgetter(0)), partial(ifilter, compose(partial(contains, '#&'), itemgetter(1))), enumerate)
print '\\'.join(imap(text.__getitem__, starmap(slice, sliding_window(2, chain((0,), char_index_iter(text), (len(text),))))))

I'm not even going to explain this because no one would bother using this to accomplish multiple replace. Nevertheless, I felt somewhat accomplished in doing this and thought it might inspire other readers or win a code obfuscation contest.

MySQL foreach alternative for procedure

Here's the mysql reference for cursors. So I'm guessing it's something like this:

  DECLARE done INT DEFAULT 0;
  DECLARE products_id INT;
  DECLARE result varchar(4000);
  DECLARE cur1 CURSOR FOR SELECT products_id FROM sets_products WHERE set_id = 1;
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

  OPEN cur1;

  REPEAT
    FETCH cur1 INTO products_id;
    IF NOT done THEN
      CALL generate_parameter_list(@product_id, @result);
      SET param = param + "," + result; -- not sure on this syntax
    END IF;
  UNTIL done END REPEAT;

  CLOSE cur1;

  -- now trim off the trailing , if desired

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

Async & Await Simple Explanation

Simple Analogy

A person may wait for their morning train. This is all they are doing as this is their primary task that they are currently performing. (synchronous programming (what you normally do!))

Another person may await their morning train whilst they smoke a cigarette and then drink their coffee. (Asynchronous programming)

What is asynchronous programming?

Asynchronous programming is where a programmer will choose to run some of his code on a separate thread from the main thread of execution and then notify the main thread on it's completion.

What does the async keyword actually do?

Prefixing the async keyword to a method name like

async void DoSomething(){ . . .

allows the programmer to use the await keyword when calling asynchronous tasks. That's all it does.

Why is this important?

In a lot of software systems the main thread is reserved for operations specifically relating to the User Interface. If I am running a very complex recursive algorithm that takes 5 seconds to complete on my computer, but I am running this on the Main Thread (UI thread) When the user tries to click on anything on my application, it will appear to be frozen as my main thread has queued and is currently processing far too many operations. As a result the main thread cannot process the mouse click to run the method from the button click.

When do you use Async and Await?

Use the asynchronous keywords ideally when you are doing anything that doesn't involve the user interface.

So lets say you're writing a program that allows the user to sketch on their mobile phone but every 5 seconds it is going to be checking the weather on the internet.

We should be awaiting the call the polling calls every 5 seconds to the network to get the weather as the user of the application needs to keep interacting with the mobile touch screen to draw pretty pictures.

How do you use Async and Await

Following on from the example above, here is some pseudo code of how to write it:

    //ASYNCHRONOUS
    //this is called using the await keyword every 5 seconds from a polling timer or something.

    async Task CheckWeather()
    {
        var weather = await GetWeather();
        //do something with the weather now you have it
    }

    async Task<WeatherResult> GetWeather()
    {

        var weatherJson = await CallToNetworkAddressToGetWeather();
        return deserializeJson<weatherJson>(weatherJson);
    }

    //SYNCHRONOUS
    //This method is called whenever the screen is pressed
    void ScreenPressed()
    {
        DrawSketchOnScreen();
    }

Additional Notes - Update

I forgot to mention in my original notes that in C# you can only await methods that are wrapped in Tasks. for example you may await this method:

// awaiting this will return a string.
// calling this without await (synchronously) will result in a Task<string> object.
async Task<string> FetchHelloWorld() {..

You cannot await methods that are not tasks like this:

async string FetchHelloWorld() {..

Feel free to review the source code for the Task class here.

dropdownlist set selected value in MVC3 Razor

I drilled down the formation of the drop down list instead of using @Html.DropDownList(). This is useful if you have to set the value of the dropdown list at runtime in razor instead of controller:

<select id="NewsCategoriesID" name="NewsCategoriesID">
    @foreach (SelectListItem option in ViewBag.NewsCategoriesID)
    {
        <option value="@option.Value" @(option.Value == ViewBag.ValueToSet ? "selected='selected'" : "")>@option.Text</option>

    }
</select>

Bind event to right mouse click

The function returns too early. I've added a comment to the code below:

$(document).ready(function(){
    $(document).bind("contextmenu",function(e){
        return false;
        $('.alert').fadeToggle(); // this line never gets called
    });
});

Try swapping the return false; with the next line.

Difference between Spring MVC and Struts MVC

Spring provides a very clean division between controllers, JavaBean models, and views.

How to change spinner text size and text color?

Can change the text colour by overriding the getView method as follows:

 new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_dropdown_item, list()){
                @Override
                public View getView(int position, View convertView, @NonNull ViewGroup parent) {
                    View view = super.getView(position, convertView, parent);
                    //change the color to which ever you want                    
                    ((CheckedTextView) view).setTextColor(Color.RED);
                    //change the size to which ever you want                    
                    ((CheckedTextView) view).setTextSize(5);
                    //for using sp values use setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
                    return view;
                }
    }

Installing MySQL Python on Mac OS X

What worked for me is:

LDFLAGS=-L/usr/local/opt/openssl/lib pip install mysql-python

python JSON only get keys in first level

As Karthik mentioned, dct.keys() will work but it will return all the keys in dict_keys type not in list type. So if you want all the keys in a list, then list(dct.keys()) will work.

How to get page content using cURL?

this is how:

   /**
     * Get a web file (HTML, XHTML, XML, image, etc.) from a URL.  Return an
     * array containing the HTTP server response header fields and content.
     */
    function get_web_page( $url )
    {
        $user_agent='Mozilla/5.0 (Windows NT 6.1; rv:8.0) Gecko/20100101 Firefox/8.0';

        $options = array(

            CURLOPT_CUSTOMREQUEST  =>"GET",        //set request type post or get
            CURLOPT_POST           =>false,        //set to GET
            CURLOPT_USERAGENT      => $user_agent, //set user agent
            CURLOPT_COOKIEFILE     =>"cookie.txt", //set cookie file
            CURLOPT_COOKIEJAR      =>"cookie.txt", //set cookie jar
            CURLOPT_RETURNTRANSFER => true,     // return web page
            CURLOPT_HEADER         => false,    // don't return headers
            CURLOPT_FOLLOWLOCATION => true,     // follow redirects
            CURLOPT_ENCODING       => "",       // handle all encodings
            CURLOPT_AUTOREFERER    => true,     // set referer on redirect
            CURLOPT_CONNECTTIMEOUT => 120,      // timeout on connect
            CURLOPT_TIMEOUT        => 120,      // timeout on response
            CURLOPT_MAXREDIRS      => 10,       // stop after 10 redirects
        );

        $ch      = curl_init( $url );
        curl_setopt_array( $ch, $options );
        $content = curl_exec( $ch );
        $err     = curl_errno( $ch );
        $errmsg  = curl_error( $ch );
        $header  = curl_getinfo( $ch );
        curl_close( $ch );

        $header['errno']   = $err;
        $header['errmsg']  = $errmsg;
        $header['content'] = $content;
        return $header;
    }

Example

//Read a web page and check for errors:

$result = get_web_page( $url );

if ( $result['errno'] != 0 )
    ... error: bad url, timeout, redirect loop ...

if ( $result['http_code'] != 200 )
    ... error: no page, no permissions, no service ...

$page = $result['content'];

Flexbox and Internet Explorer 11 (display:flex in <html>?)

Here is an example of using flex that also works in Internet Explorer 11 and Chrome.

HTML

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1" >_x000D_
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" >_x000D_
<title>Flex Test</title>_x000D_
<style>_x000D_
html, body {_x000D_
    margin: 0px;_x000D_
    padding: 0px;_x000D_
    height: 100vh;_x000D_
}_x000D_
.main {_x000D_
    display: -webkit-flex;_x000D_
    display: flex;_x000D_
    -ms-flex-direction: row;_x000D_
    flex-direction: row;_x000D_
    align-items: stretch;_x000D_
    min-height: 100vh;_x000D_
}_x000D_
_x000D_
.main::after {_x000D_
  content: '';_x000D_
  height: 100vh;_x000D_
  width: 0;_x000D_
  overflow: hidden;_x000D_
  visibility: hidden;_x000D_
  float: left;_x000D_
}_x000D_
_x000D_
.left {_x000D_
    width: 200px;_x000D_
    background: #F0F0F0;_x000D_
    flex-shrink: 0;_x000D_
}_x000D_
_x000D_
.right {_x000D_
    flex-grow: 1;_x000D_
    background: yellow;_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<div class="main">_x000D_
    <div class="left">_x000D_
        <div style="height: 300px;">_x000D_
        </div>_x000D_
    </div>_x000D_
_x000D_
    <div class="right">_x000D_
        <div style="height: 1000px;">_x000D_
            test test test_x000D_
        </div>_x000D_
    </div>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to run script as another user without password?

`su -c "Your command right here" -s /bin/sh username`

The above command is correct, but on Red Hat if selinux is enforcing it will not allow cron to execute scripts as another user. example; execl: couldn't exec /bin/sh execl: Permission denied

I had to install setroubleshoot and setools and run the following to allow it:

yum install setroubleshoot setools
sealert -a /var/log/audit/audit.log
grep crond /var/log/audit/audit.log | audit2allow -M mypol
semodule -i mypol.p

base 64 encode and decode a string in angular (2+)

Use btoa() for encode and atob() for decode

text_val:any="your encoding text";

Encoded Text: console.log(btoa(this.text_val)); //eW91ciBlbmNvZGluZyB0ZXh0

Decoded Text: console.log(atob("eW91ciBlbmNvZGluZyB0ZXh0")); //your encoding text

Allow docker container to connect to a local/host postgres database

TL;DR

  1. Use 172.17.0.0/16 as IP address range, not 172.17.0.0/32.
  2. Don't use localhost to connect to the PostgreSQL database on your host, but the host's IP instead. To keep the container portable, start the container with the --add-host=database:<host-ip> flag and use database as hostname for connecting to PostgreSQL.
  3. Make sure PostgreSQL is configured to listen for connections on all IP addresses, not just on localhost. Look for the setting listen_addresses in PostgreSQL's configuration file, typically found in /etc/postgresql/9.3/main/postgresql.conf (credits to @DazmoNorton).

Long version

172.17.0.0/32 is not a range of IP addresses, but a single address (namly 172.17.0.0). No Docker container will ever get that address assigned, because it's the network address of the Docker bridge (docker0) interface.

When Docker starts, it will create a new bridge network interface, that you can easily see when calling ip a:

$ ip a
...
3: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN 
    link/ether 56:84:7a:fe:97:99 brd ff:ff:ff:ff:ff:ff
    inet 172.17.42.1/16 scope global docker0
       valid_lft forever preferred_lft forever

As you can see, in my case, the docker0 interface has the IP address 172.17.42.1 with a netmask of /16 (or 255.255.0.0). This means that the network address is 172.17.0.0/16.

The IP address is randomly assigned, but without any additional configuration, it will always be in the 172.17.0.0/16 network. For each Docker container, a random address from that range will be assigned.

This means, if you want to grant access from all possible containers to your database, use 172.17.0.0/16.

paint() and repaint() in Java

It's not necessary to call repaint unless you need to render something specific onto a component. "Something specific" meaning anything that isn't provided internally by the windowing toolkit you're using.

How to replace multiple patterns at once with sed?

May be a simpler approach for single pattern occurrence you can try as below: echo 'abbc' | sed 's/ab/bc/;s/bc/ab/2'

My output:

 ~# echo 'abbc' | sed 's/ab/bc/;s/bc/ab/2'
 bcab

For multiple occurrences of pattern:

sed 's/\(ab\)\(bc\)/\2\1/g'

Example

~# cat try.txt
abbc abbc abbc
bcab abbc bcab
abbc abbc bcab

~# sed 's/\(ab\)\(bc\)/\2\1/g' try.txt
bcab bcab bcab
bcab bcab bcab
bcab bcab bcab

Hope this helps !!

How do I tell CMake to link in a static library in the source directory?

I found this helpful...

http://www.cmake.org/pipermail/cmake/2011-June/045222.html

From their example:

ADD_LIBRARY(boost_unit_test_framework STATIC IMPORTED)
SET_TARGET_PROPERTIES(boost_unit_test_framework PROPERTIES IMPORTED_LOCATION /usr/lib/libboost_unit_test_framework.a)
TARGET_LINK_LIBRARIES(mytarget A boost_unit_test_framework C)

Creating email templates with Django

Django Mail Templated is a feature-rich Django application to send emails with Django template system.

Installation:

pip install django-mail-templated

Configuration:

INSTALLED_APPS = (
    ...
    'mail_templated'
)

Template:

{% block subject %}
Hello {{ user.name }}
{% endblock %}

{% block body %}
{{ user.name }}, this is the plain text part.
{% endblock %}

Python:

from mail_templated import send_mail
send_mail('email/hello.tpl', {'user': user}, from_email, [user.email])

More info: https://github.com/artemrizhov/django-mail-templated

How to check if a string in Python is in ASCII?

I think you are not asking the right question--

A string in python has no property corresponding to 'ascii', utf-8, or any other encoding. The source of your string (whether you read it from a file, input from a keyboard, etc.) may have encoded a unicode string in ascii to produce your string, but that's where you need to go for an answer.

Perhaps the question you can ask is: "Is this string the result of encoding a unicode string in ascii?" -- This you can answer by trying:

try:
    mystring.decode('ascii')
except UnicodeDecodeError:
    print "it was not a ascii-encoded unicode string"
else:
    print "It may have been an ascii-encoded unicode string"

Angular 4 Pipe Filter

The transform method signature changed somewhere in an RC of Angular 2. Try something more like this:

export class FilterPipe implements PipeTransform {
    transform(items: any[], filterBy: string): any {
        return items.filter(item => item.id.indexOf(filterBy) !== -1);
    }
}

And if you want to handle nulls and make the filter case insensitive, you may want to do something more like the one I have here:

export class ProductFilterPipe implements PipeTransform {

    transform(value: IProduct[], filterBy: string): IProduct[] {
        filterBy = filterBy ? filterBy.toLocaleLowerCase() : null;
        return filterBy ? value.filter((product: IProduct) =>
            product.productName.toLocaleLowerCase().indexOf(filterBy) !== -1) : value;
    }
}

And NOTE: Sorting and filtering in pipes is a big issue with performance and they are NOT recommended. See the docs here for more info: https://angular.io/guide/pipes#appendix-no-filterpipe-or-orderbypipe

'git status' shows changed files, but 'git diff' doesn't

For me, it had something to do with file permissions. Someone with Mac/Linux on my project seems to commit some files with non-default permissions which my Windows git client failed to reproduce. Solution for me was to tell git to ignore file permissions:

git config core.fileMode false

Other insight: How do I make Git ignore file mode (chmod) changes?

Pass by pointer & Pass by reference

Pass by pointer is the only way you could pass "by reference" in C, so you still see it used quite a bit.

The NULL pointer is a handy convention for saying a parameter is unused or not valid, so use a pointer in that case.

References can't be updated once they're set, so use a pointer if you ever need to reassign it.

Prefer a reference in every case where there isn't a good reason not to. Make it const if you can.

Sending SOAP request using Python Requests

It is indeed possible.

Here is an example calling the Weather SOAP Service using plain requests lib:

import requests
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
#headers = {'content-type': 'application/soap+xml'}
headers = {'content-type': 'text/xml'}
body = """<?xml version="1.0" encoding="UTF-8"?>
         <SOAP-ENV:Envelope xmlns:ns0="http://ws.cdyne.com/WeatherWS/" xmlns:ns1="http://schemas.xmlsoap.org/soap/envelope/" 
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
            <SOAP-ENV:Header/>
              <ns1:Body><ns0:GetWeatherInformation/></ns1:Body>
         </SOAP-ENV:Envelope>"""

response = requests.post(url,data=body,headers=headers)
print response.content

Some notes:

  • The headers are important. Most SOAP requests will not work without the correct headers. application/soap+xml is probably the more correct header to use (but the weatherservice prefers text/xml
  • This will return the response as a string of xml - you would then need to parse that xml.
  • For simplicity I have included the request as plain text. But best practise would be to store this as a template, then you can load it using jinja2 (for example) - and also pass in variables.

For example:

from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('myapp', 'templates'))
template = env.get_template('soaprequests/WeatherSericeRequest.xml')
body = template.render()

Some people have mentioned the suds library. Suds is probably the more correct way to be interacting with SOAP, but I often find that it panics a little when you have WDSLs that are badly formed (which, TBH, is more likely than not when you're dealing with an institution that still uses SOAP ;) ).

You can do the above with suds like so:

from suds.client import Client
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
client = Client(url)
print client ## shows the details of this service

result = client.service.GetWeatherInformation() 
print result 

Note: when using suds, you will almost always end up needing to use the doctor!

Finally, a little bonus for debugging SOAP; TCPdump is your friend. On Mac, you can run TCPdump like so:

sudo tcpdump -As 0 

This can be helpful for inspecting the requests that actually go over the wire.

The above two code snippets are also available as gists:

How to set standard encoding in Visual Studio

I work with Windows7.

Control Panel - Region and Language - Administrative - Language for non-Unicode programs.

After I set "Change system locale" to English(United States). My default encoding of vs2010 change to Windows-1252. It was gb2312 before.

I created a new .cpp file for a C++ project, after checking in the new file to TFS the encoding show Windows-1252 from the properties page of the file.

ArrayBuffer to base64 encoded string

function _arrayBufferToBase64(uarr) {
    var strings = [], chunksize = 0xffff;
    var len = uarr.length;

    for (var i = 0; i * chunksize < len; i++){
        strings.push(String.fromCharCode.apply(null, uarr.subarray(i * chunksize, (i + 1) * chunksize)));
    }

    return strings.join("");
}

This is better, if you use JSZip for unpack archive from string

Python Progress Bar

a little more generic answer of jelde015 (credit to him of course)

for updating the loading bar manually will be:

import sys
from math import *


def loadingBar(i, N, size):
    percent = float(i) / float(N)
    sys.stdout.write("\r"
                     + str(int(i)).rjust(3, '0')
                     +"/"
                     +str(int(N)).rjust(3, '0')
                     + ' ['
                     + '='*ceil(percent*size)
                     + ' '*floor((1-percent)*size)
                     + ']')

and calling it by:

loadingBar(7, 220, 40)

will result:

007/220 [=                                       ]  

just call it whenever you want with the current i value.

set the size as the number of chars the bar should be

How to clear Route Caching on server: Laravel 5.2.37

If you are uploading your files through GIT from your local machine then you can use the same command you are using in your local machine while you are connected to your live server using BASH or something like.You can use this as like you use locally.

php artisan cache:clear

php artisan route:cache

It should work.

When is del useful in Python?

Yet another niche usage: In pyroot with ROOT5 or ROOT6, "del" may be useful to remove a python object that referred to a no-longer existing C++ object. This allows the dynamic lookup of pyroot to find an identically-named C++ object and bind it to the python name. So you can have a scenario such as:

import ROOT as R
input_file = R.TFile('inputs/___my_file_name___.root')
tree = input_file.Get('r')
tree.Draw('hy>>hh(10,0,5)')
R.gPad.Close()
R.hy # shows that hy is still available. It can even be redrawn at this stage.
tree.Draw('hy>>hh(3,0,3)') # overwrites the C++ object in ROOT's namespace
R.hy # shows that R.hy is None, since the C++ object it pointed to is gone
del R.hy
R.hy # now finds the new C++ object

Hopefully, this niche will be closed with ROOT7's saner object management.

Angular routerLink does not navigate to the corresponding component

The links are wrong, you have to do this:

<ul class="nav navbar-nav item">
    <li>
        <a [routerLink]="['/home']" routerLinkActive="active">Home</a>
    </li>
    <li>
        <a [routerLink]="['/about']" routerLinkActive="active">About this
        </a>
    </li>
</ul>

You can read this tutorial

Selecting the last value of a column

function lastRow(column){
  var sheet = SpreadsheetApp.getActiveSpreadsheet();
  var lastRow = sheet.getLastRow();
  var lastRowRange=sheet.getRange(column+startRow);
  return lastRowRange.getValue();
}

no hard coding.

How to push a new folder (containing other folders and files) to an existing git repo?

You need to git add my_project to stage your new folder. Then git add my_project/* to stage its contents. Then commit what you've staged using git commit and finally push your changes back to the source using git push origin master (I'm assuming you wish to push to the master branch).

Concatenating multiple text files into a single file in Bash

You can do like this: cat [directory_path]/**/*.[h,m] > test.txt

if you use {} to include the extension of the files you want to find, there is a sequencing problem.

How to use NULL or empty string in SQL

Select *
From Table
Where (col is null or col = '')

Or

Select *
From Table
Where IsNull(col, '') = ''

How to run JUnit test cases from the command line

Alternatively you can use the following methods in JunitCore class http://junit.sourceforge.net/javadoc/org/junit/runner/JUnitCore.html

run (with Request , Class classes and Runner) or runClasses from your java file.

How can I get a list of repositories 'apt-get' is checking?

As far as I know, you can't ask apt for what their current sources are. However, you can do what you want using shell tools.

Getting a list of repositories:

grep -h ^deb /etc/apt/sources.list /etc/apt/sources.list.d/* >> current.repos.list

Applying the list:

apt-add-repository << current.repos.list

Regarding getting the repository from a package (installed or available), this will do the trick:

apt-cache policy package_name | grep -m1 http | awk '{ print $2 " " $3 }'

However, that will show you the repository of the latest version available of that package, and you may have more repositories for the same package with older versions. Remove all the grep/awk stuff if you want to see the full list.

Ignoring SSL certificate in Apache HttpClient 4.3

Slight tweak to answer from @divbyzero above to fix sonar security warnings

CloseableHttpClient getInsecureHttpClient() throws GeneralSecurityException {
            TrustStrategy trustStrategy = (chain, authType) -> true;

            HostnameVerifier hostnameVerifier = (hostname, session) -> hostname.equalsIgnoreCase(session.getPeerHost());

            return HttpClients.custom()
                    .setSSLSocketFactory(new SSLConnectionSocketFactory(new SSLContextBuilder().loadTrustMaterial(trustStrategy).build(), hostnameVerifier))
                    .build();
        }

What is the difference between "word-break: break-all" versus "word-wrap: break-word" in CSS

From the respective W3 specifications —which happen to be pretty unclear due to a lack of context— one can deduce the following:

  • word-break: break-all is for breaking up foreign, non-CJK (say Western) words in CJK (Chinese, Japanese or Korean) character writings.
  • word-wrap: break-word is for word breaking in a non-mixed (let us say solely Western) language.

At least, these were W3's intentions. What actually happened was a major cock-up with browser incompatibilities as a result. Here is an excellent write-up of the various problems involved.

The following code snippet may serve as a summary of how to achieve word wrapping using CSS in a cross browser environment:

-ms-word-break: break-all;
 word-break: break-all;

 /* Non standard for webkit */
 word-break: break-word;

-webkit-hyphens: auto;
   -moz-hyphens: auto;
    -ms-hyphens: auto;
        hyphens: auto;

How to checkout a specific Subversion revision from the command line?

You'll have to use svn directly:

svn checkout URL[@REV]... [PATH]

and

svn help co

gives you a little more help.

Paging UICollectionView by cells, not screen

This is a straight way to do this.

The case is simple, but finally quite common ( typical thumbnails scroller with fixed cell size and fixed gap between cells )

var itemCellSize: CGSize = <your cell size>
var itemCellsGap: CGFloat = <gap in between>

override func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
    let pageWidth = (itemCellSize.width + itemCellsGap)
    let itemIndex = (targetContentOffset.pointee.x) / pageWidth
    targetContentOffset.pointee.x = round(itemIndex) * pageWidth - (itemCellsGap / 2)
}

// CollectionViewFlowLayoutDelegate

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return itemCellSize
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return itemCellsGap
}

Note that there is no reason to call a scrollToOffset or dive into layouts. The native scrolling behaviour already does everything.

Cheers All :)

Use Mockito to mock some methods but not others

What you want is org.mockito.Mockito.CALLS_REAL_METHODS according to the docs:

/**
 * Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)}
 * <p>
 * {@link Answer} can be used to define the return values of unstubbed invocations.
 * <p>
 * This implementation can be helpful when working with legacy code.
 * When this implementation is used, unstubbed methods will delegate to the real implementation.
 * This is a way to create a partial mock object that calls real methods by default.
 * <p>
 * As usual you are going to read <b>the partial mock warning</b>:
 * Object oriented programming is more less tackling complexity by dividing the complexity into separate, specific, SRPy objects.
 * How does partial mock fit into this paradigm? Well, it just doesn't... 
 * Partial mock usually means that the complexity has been moved to a different method on the same object.
 * In most cases, this is not the way you want to design your application.
 * <p>
 * However, there are rare cases when partial mocks come handy: 
 * dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.)
 * However, I wouldn't use partial mocks for new, test-driven & well-designed code.
 * <p>
 * Example:
 * <pre class="code"><code class="java">
 * Foo mock = mock(Foo.class, CALLS_REAL_METHODS);
 *
 * // this calls the real implementation of Foo.getSomething()
 * value = mock.getSomething();
 *
 * when(mock.getSomething()).thenReturn(fakeValue);
 *
 * // now fakeValue is returned
 * value = mock.getSomething();
 * </code></pre>
 */

Thus your code should look like:

import org.junit.Test;
import static org.mockito.Mockito.*;
import static org.junit.Assert.*;

public class StockTest {

    public class Stock {
        private final double price;
        private final int quantity;

        Stock(double price, int quantity) {
            this.price = price;
            this.quantity = quantity;
        }

        public double getPrice() {
            return price;
        }

        public int getQuantity() {
            return quantity;
        }

        public double getValue() {
            return getPrice() * getQuantity();
        }
    }

    @Test
    public void getValueTest() {
        Stock stock = mock(Stock.class, withSettings().defaultAnswer(CALLS_REAL_METHODS));
        when(stock.getPrice()).thenReturn(100.00);
        when(stock.getQuantity()).thenReturn(200);
        double value = stock.getValue();

        assertEquals("Stock value not correct", 100.00 * 200, value, .00001);
    }
}

The call to Stock stock = mock(Stock.class); calls org.mockito.Mockito.mock(Class<T>) which looks like this:

 public static <T> T mock(Class<T> classToMock) {
    return mock(classToMock, withSettings().defaultAnswer(RETURNS_DEFAULTS));
}

The docs of the value RETURNS_DEFAULTS tell:

/**
 * The default <code>Answer</code> of every mock <b>if</b> the mock was not stubbed.
 * Typically it just returns some empty value. 
 * <p>
 * {@link Answer} can be used to define the return values of unstubbed invocations. 
 * <p>
 * This implementation first tries the global configuration. 
 * If there is no global configuration then it uses {@link ReturnsEmptyValues} (returns zeros, empty collections, nulls, etc.)
 */

Upload a file to Amazon S3 with NodeJS

Upload CSV/Excel

const fs = require('fs');
const AWS = require('aws-sdk');

const s3 = new AWS.S3({
    accessKeyId: XXXXXXXXX,
    secretAccessKey: XXXXXXXXX
});

const absoluteFilePath = "C:\\Project\\test.xlsx";

const uploadFile = () => {
  fs.readFile(absoluteFilePath, (err, data) => {
     if (err) throw err;
     const params = {
         Bucket: 'testBucket', // pass your bucket name
         Key: 'folderName/key.xlsx', // file will be saved in <folderName> folder
         Body: data
     };
      s3.upload(params, function (s3Err, data) {
                    if (s3Err) throw s3Err
                    console.log(`File uploaded successfully at ${data.Location}`);
                    debugger;
                });
  });
};

uploadFile();

How do I add a delay in a JavaScript loop?

Simple implementation of showing a piece of text every two seconds as long the loop is running.

for (var i = 0; i < foo.length; i++) {
   setInterval(function(){ 
     console.log("I will appear every 2 seconds"); 
   }, 2000);
  break;
};

less than 10 add 0 to number

You can always do

('0' + deg).slice(-2)

See slice():

You can also use negative numbers to select from the end of an array

Hence

('0' + 11).slice(-2) // '11'
('0' + 4).slice(-2)  // '04'

For ease of access, you could of course extract it to a function, or even extend Number with it:

Number.prototype.pad = function(n) {
    return new Array(n).join('0').slice((n || 2) * -1) + this;
}

Which will allow you to write:

c += deg.pad() + '° '; // "04° "

The above function pad accepts an argument specifying the length of the desired string. If no such argument is used, it defaults to 2. You could write:

deg.pad(4) // "0045"

Note the obvious drawback that the value of n cannot be higher than 11, as the string of 0's is currently just 10 characters long. This could of course be given a technical solution, but I did not want to introduce complexity in such a simple function. (Should you elect to, see alex's answer for an excellent approach to that).

Note also that you would not be able to write 2.pad(). It only works with variables. But then, if it's not a variable, you'll always know beforehand how many digits the number consists of.

What does the percentage sign mean in Python

What does the percentage sign mean?

It's an operator in Python that can mean several things depending on the context. A lot of what follows was already mentioned (or hinted at) in the other answers but I thought it could be helpful to provide a more extensive summary.

% for Numbers: Modulo operation / Remainder / Rest

The percentage sign is an operator in Python. It's described as:

x % y       remainder of x / y

So it gives you the remainder/rest that remains if you "floor divide" x by y. Generally (at least in Python) given a number x and a divisor y:

x == y * (x // y) + (x % y)

For example if you divide 5 by 2:

>>> 5 // 2
2
>>> 5 % 2
1

>>> 2 * (5 // 2) + (5 % 2)
5

In general you use the modulo operation to test if a number divides evenly by another number, that's because multiples of a number modulo that number returns 0:

>>> 15 % 5  # 15 is 3 * 5
0

>>> 81 % 9  # 81 is 9 * 9
0

That's how it's used in your example, it cannot be a prime if it's a multiple of another number (except for itself and one), that's what this does:

if n % x == 0:
    break

If you feel that n % x == 0 isn't very descriptive you could put it in another function with a more descriptive name:

def is_multiple(number, divisor):
    return number % divisor == 0

...

if is_multiple(n, x):
    break

Instead of is_multiple it could also be named evenly_divides or something similar. That's what is tested here.

Similar to that it's often used to determine if a number is "odd" or "even":

def is_odd(number):
    return number % 2 == 1

def is_even(number):
    return number % 2 == 0

And in some cases it's also used for array/list indexing when wrap-around (cycling) behavior is wanted, then you just modulo the "index" by the "length of the array" to achieve that:

>>> l = [0, 1, 2]
>>> length = len(l)
>>> for index in range(10):
...     print(l[index % length])
0
1
2
0
1
2
0
1
2
0

Note that there is also a function for this operator in the standard library operator.mod (and the alias operator.__mod__):

>>> import operator
>>> operator.mod(5, 2)  # equivalent to 5 % 2
1

But there is also the augmented assignment %= which assigns the result back to the variable:

>>> a = 5
>>> a %= 2  # identical to: a = a % 2
>>> a
1

% for strings: printf-style String Formatting

For strings the meaning is completely different, there it's one way (in my opinion the most limited and ugly) for doing string formatting:

>>> "%s is %s." % ("this", "good") 
'this is good'

Here the % in the string represents a placeholder followed by a formatting specification. In this case I used %s which means that it expects a string. Then the string is followed by a % which indicates that the string on the left hand side will be formatted by the right hand side. In this case the first %s is replaced by the first argument this and the second %s is replaced by the second argument (good).

Note that there are much better (probably opinion-based) ways to format strings:

>>> "{} is {}.".format("this", "good")
'this is good.'

% in Jupyter/IPython: magic commands

To quote the docs:

To Jupyter users: Magics are specific to and provided by the IPython kernel. Whether magics are available on a kernel is a decision that is made by the kernel developer on a per-kernel basis. To work properly, Magics must use a syntax element which is not valid in the underlying language. For example, the IPython kernel uses the % syntax element for magics as % is not a valid unary operator in Python. While, the syntax element has meaning in other languages.

This is regularly used in Jupyter notebooks and similar:

In [1]:  a = 10
         b = 20
         %timeit a + b   # one % -> line-magic

54.6 ns ± 2.7 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

In [2]:  %%timeit  # two %% -> cell magic 
         a ** b

362 ns ± 8.4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

The % operator on arrays (in the NumPy / Pandas ecosystem)

The % operator is still the modulo operator when applied to these arrays, but it returns an array containing the remainder of each element in the array:

>>> import numpy as np
>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

>>> a % 2
array([0, 1, 0, 1, 0, 1, 0, 1, 0, 1])

Customizing the % operator for your own classes

Of course you can customize how your own classes work when the % operator is applied to them. Generally you should only use it to implement modulo operations! But that's a guideline, not a hard rule.

Just to provide a simple example that shows how it works:

class MyNumber(object):
    def __init__(self, value):
        self.value = value

    def __mod__(self, other):
        print("__mod__ called on '{!r}'".format(self))
        return self.value % other

    def __repr__(self):
        return "{self.__class__.__name__}({self.value!r})".format(self=self)

This example isn't really useful, it just prints and then delegates the operator to the stored value, but it shows that __mod__ is called when % is applied to an instance:

>>> a = MyNumber(10)
>>> a % 2
__mod__ called on 'MyNumber(10)'
0

Note that it also works for %= without explicitly needing to implement __imod__:

>>> a = MyNumber(10)
>>> a %= 2
__mod__ called on 'MyNumber(10)'

>>> a
0

However you could also implement __imod__ explicitly to overwrite the augmented assignment:

class MyNumber(object):
    def __init__(self, value):
        self.value = value

    def __mod__(self, other):
        print("__mod__ called on '{!r}'".format(self))
        return self.value % other

    def __imod__(self, other):
        print("__imod__ called on '{!r}'".format(self))
        self.value %= other
        return self

    def __repr__(self):
        return "{self.__class__.__name__}({self.value!r})".format(self=self)

Now %= is explicitly overwritten to work in-place:

>>> a = MyNumber(10)
>>> a %= 2
__imod__ called on 'MyNumber(10)'

>>> a
MyNumber(0)

How to set focus on input field?

It's easy.. try this

html

<select id="ddl00">  
 <option>"test 01"</option>  
</select>

javascript

document.getElementById("ddl00").focus();

How to automatically crop and center an image

Example with img tag but without background-image

This solution retains the img tag so that we do not lose the ability to drag or right-click to save the image but without background-image just center and crop with css.

Maintain the aspect ratio fine except in very hight images. (check the link)

(view in action)

Markup

<div class="center-cropped">
    <img src="http://placehold.it/200x150" alt="" />
</div>

? CSS

div.center-cropped {
  width: 100px;
  height: 100px;
  overflow:hidden;
}
div.center-cropped img {
  height: 100%;
  min-width: 100%;
  left: 50%;
  position: relative;
  transform: translateX(-50%);
}

How to truncate the time on a DateTime object in Python?

I think this is what you're looking for...

>>> import datetime
>>> dt = datetime.datetime.now()
>>> dt = dt.replace(hour=0, minute=0, second=0, microsecond=0) # Returns a copy
>>> dt
datetime.datetime(2011, 3, 29, 0, 0)

But if you really don't care about the time aspect of things, then you should really only be passing around date objects...

>>> d_truncated = datetime.date(dt.year, dt.month, dt.day)
>>> d_truncated
datetime.date(2011, 3, 29)

Calling a parent window function from an iframe

You can use

window.top

see the following.

<head>
    <script>
    function abc() {
        alert("sss");
    }
    </script>
</head>
<body>
    <iframe id="myFrame">
        <a onclick="window.top.abc();" href="#">Click Me</a>
    </iframe>
</body>

How to convert a column number (e.g. 127) into an Excel column (e.g. AA)

Here is my solution in python

import math

num = 3500
row_number = str(math.ceil(num / 702))
letters = ''
num = num - 702 * math.floor(num / 702)
while num:
    mod = (num - 1) % 26
    letters += chr(mod + 65)
    num = (num - 1) // 26
result = row_number + ("".join(reversed(letters)))
print(result)

How add class='active' to html menu with php

I know this is old, but none of these answers are very good (sry ppl)

The BEST way to do it (without writing out convoluted classes) is to compare the current $_SERVER['REQUEST_URI'] to the href of the link. You're almost there.

Try this. (Taken from http://ma.tt/scripts/intellimenu/)

$nav = <<<EOD
<div id="nav">
        <ul>
           <li><a href="index.php">Tab1</a></li>
           <li><a href="two.php">Tab2</a></li>
           <li><a href="three.php">Tab3</a></li>
       </ul>
    </div>
EOD;

$lines = explode("\n", $nav);
foreach($lines as $line)
{
    if(preg_match('/href="([^"]+)"/', $line, $url)) {
        if(substr($_SERVER['REQUEST_URI'], 0, 5) == substr($url[1], 0, 5)) {
            $line = str_replace('><a', ' class="current-menu-item"><a', $line);
        }
    }
    echo $line . "\n";
}

AngularJS $resource RESTful example

$resource was meant to retrieve data from an endpoint, manipulate it and send it back. You've got some of that in there, but you're not really leveraging it for what it was made to do.

It's fine to have custom methods on your resource, but you don't want to miss out on the cool features it comes with OOTB.

EDIT: I don't think I explained this well enough originally, but $resource does some funky stuff with returns. Todo.get() and Todo.query() both return the resource object, and pass it into the callback for when the get completes. It does some fancy stuff with promises behind the scenes that mean you can call $save() before the get() callback actually fires, and it will wait. It's probably best just to deal with your resource inside of a promise then() or the callback method.

Standard use

var Todo = $resource('/api/1/todo/:id');

//create a todo
var todo1 = new Todo();
todo1.foo = 'bar';
todo1.something = 123;
todo1.$save();

//get and update a todo
var todo2 = Todo.get({id: 123});
todo2.foo += '!';
todo2.$save();

//which is basically the same as...
Todo.get({id: 123}, function(todo) {
   todo.foo += '!';
   todo.$save();
});

//get a list of todos
Todo.query(function(todos) {
  //do something with todos
  angular.forEach(todos, function(todo) {
     todo.foo += ' something';
     todo.$save();
  });
});

//delete a todo
Todo.$delete({id: 123});

Likewise, in the case of what you posted in the OP, you could get a resource object and then call any of your custom functions on it (theoretically):

var something = src.GetTodo({id: 123});
something.foo = 'hi there';
something.UpdateTodo();

I'd experiment with the OOTB implementation before I went and invented my own however. And if you find you're not using any of the default features of $resource, you should probably just be using $http on it's own.

Update: Angular 1.2 and Promises

As of Angular 1.2, resources support promises. But they didn't change the rest of the behavior.

To leverage promises with $resource, you need to use the $promise property on the returned value.

Example using promises

var Todo = $resource('/api/1/todo/:id');

Todo.get({id: 123}).$promise.then(function(todo) {
   // success
   $scope.todos = todos;
}, function(errResponse) {
   // fail
});

Todo.query().$promise.then(function(todos) {
   // success
   $scope.todos = todos;
}, function(errResponse) {
   // fail
});

Just keep in mind that the $promise property is a property on the same values it was returning above. So you can get weird:

These are equivalent

var todo = Todo.get({id: 123}, function() {
   $scope.todo = todo;
});

Todo.get({id: 123}, function(todo) {
   $scope.todo = todo;
});

Todo.get({id: 123}).$promise.then(function(todo) {
   $scope.todo = todo;
});

var todo = Todo.get({id: 123});
todo.$promise.then(function() {
   $scope.todo = todo;
});

Show/Hide Multiple Divs with Jquery

simple but stupid approach:

$('#showall').click(function(){
    $('div[id^=div]').show();
});

$('#showdiv1').click(function(){
    $('#div1').show();
    $('div[id^=div]').not('#div1').show();
});

as for better one - add common class to all div's, and use some attribute in buttons with id of target divs

How to reload the current state?

I had multiple nested views and the goal was to reload only one with content. I tried different approaches but the only thing that worked for me is:

//to reload
$stateParams.reload = !$stateParams.reload; //flip value of reload param
$state.go($state.current, $stateParams);

//state config
$stateProvider
  .state('app.dashboard', {
    url: '/',
    templateUrl: 'app/components/dashboard/dashboard.tmpl.html',
    controller: 'DashboardController',
    controllerAs: 'vm',
    params: {reload: false} //add reload param to a view you want to reload
  });

In this case only needed view would be reloaded and caching would still work.

How to use if - else structure in a batch file?

Here's my code Example for if..else..if
which do the following

Prompt user for Process Name

If the process name is invalid
Then it's write to user

Error : The Processor above doesn't seem to be exist 

if the process name is services
Then it's write to user

Error : You can't kill the Processor above 

if the process name is valid and not services
Then it's write to user

the process has been killed via taskill

so i called it Process killer.bat
Here's my Code:

@echo off

:Start
Rem preparing the batch  
cls
Title Processor Killer
Color 0B
Echo Type Processor name to kill It (Without ".exe")
set /p ProcessorTokill=%=%  

:tasklist
tasklist|find /i "%ProcessorTokill%.exe">nul & if errorlevel 1 (
REM check if the process name is invalid 
Cls 
Title %ProcessorTokill% Not Found
Color 0A
echo %ProcessorTokill%
echo Error : The Processor above doesn't seem to be exist    

) else if %ProcessorTokill%==services (
REM check if the process name is services and doesn't kill it
Cls 
Color 0c
Title Permission denied 
echo "%ProcessorTokill%.exe"
echo Error : You can't kill the Processor above 

) else (
REM if the process name is valid and not services
Cls 
Title %ProcessorTokill% Found
Color 0e
echo %ProcessorTokill% Found
ping localhost -n 2 -w 1000>nul
echo Killing %ProcessorTokill% ...
taskkill /f /im %ProcessorTokill%.exe /t>nul
echo %ProcessorTokill% Killed...
)

pause>nul



REM If else if Template
REM if thing1 (
REM Command here 2 ! 
REM ) else if thing2 (
REM command here 2 !
REM ) else (
REM command here 3 !
REM )

COPY with docker but with exclusion

Create file .dockerignore in your docker build context directory (so in this case, most likely a directory that is a parent to node_modules) with one line in it:

**/node_modules

although you probably just want:

node_modules

Info about dockerignore: https://docs.docker.com/engine/reference/builder/#dockerignore-file

How can I align text directly beneath an image?

You can use HTML5 <figcaption>:

<figure>
  <img src="img.jpg" alt="my img"/>
  <figcaption> Your text </figcaption>
</figure>

Working example.

Granting Rights on Stored Procedure to another user of Oracle

I'm not sure that I understand what you mean by "rights of ownership".

If User B owns a stored procedure, User B can grant User A permission to run the stored procedure

GRANT EXECUTE ON b.procedure_name TO a

User A would then call the procedure using the fully qualified name, i.e.

BEGIN
  b.procedure_name( <<list of parameters>> );
END;

Alternately, User A can create a synonym in order to avoid having to use the fully qualified procedure name.

CREATE SYNONYM procedure_name FOR b.procedure_name;

BEGIN
  procedure_name( <<list of parameters>> );
END;

How do you set the title color for the new Toolbar?

public class MyToolbar extends android.support.v7.widget.Toolbar {

public MyToolbar(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);
}

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
    super.onLayout(changed, l, t, r, b);
    AppCompatTextView textView = (AppCompatTextView) getChildAt(0);
    if (textView!=null) textView.setTextAppearance(getContext(), R.style.TitleStyle);
}

}

Or simple use from MainActivity:

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbarMain);
setSupportActionBar(toolbar);
((AppCompatTextView) toolbar.getChildAt(0)).setTextAppearance(this, R.style.TitleStyle);

style.xml

<style name="TileStyle" parent="TextAppearance.AppCompat">
    <item name="android:textColor">@color/White</item>
    <item name="android:shadowColor">@color/Black</item>
    <item name="android:shadowDx">-1</item>
    <item name="android:shadowDy">1</item>
    <item name="android:shadowRadius">1</item>
</style>

C# List<string> to string with delimiter

You can also do this with linq if you'd like

var names = new List<string>() { "John", "Anna", "Monica" };
var joinedNames = names.Aggregate((a, b) => a + ", " + b);

Although I prefer the non-linq syntax in Quartermeister's answer and I think Aggregate might perform slower (probably more string concatenation operations).

How to print object array in JavaScript?

There is a wonderful print_r implementation for JavaScript in php.js library.

Note, you should also add echo support in the code.

DEMO: http://jsbin.com/esexiw/1

MATLAB - multiple return values from a function?

Use the following in the function you will call and it will work just fine.

     [a b c] = yourfunction(optional)
     %your code
     a = 5;
     b = 7;
     c = 10;
     return
     end

This is a way to call the function both from another function and from the command terminal

     [aa bb cc] = yourfunction(optional);

The variables aa, bb and cc now hold the return variables.

Dump a mysql database to a plaintext (CSV) backup from the command line

If you can cope with table-at-a-time, and your data is not binary, use the -B option to the mysql command. With this option it'll generate TSV (tab separated) files which can import into Excel, etc, quite easily:

% echo 'SELECT * FROM table' | mysql -B -uxxx -pyyy database

Alternatively, if you've got direct access to the server's file system, use SELECT INTO OUTFILE which can generate real CSV files:

SELECT * INTO OUTFILE 'table.csv'
    FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
    LINES TERMINATED BY '\n'
FROM table

How to sort a list/tuple of lists/tuples by the element at a given index?

@Stephen 's answer is to the point! Here is an example for better visualization,

Shout out for the Ready Player One fans! =)

>>> gunters = [('2044-04-05', 'parzival'), ('2044-04-07', 'aech'), ('2044-04-06', 'art3mis')]
>>> gunters.sort(key=lambda tup: tup[0])
>>> print gunters
[('2044-04-05', 'parzival'), ('2044-04-06', 'art3mis'), ('2044-04-07', 'aech')]

key is a function that will be called to transform the collection's items for comparison.. like compareTo method in Java.

The parameter passed to key must be something that is callable. Here, the use of lambda creates an anonymous function (which is a callable).
The syntax of lambda is the word lambda followed by a iterable name then a single block of code.

Below example, we are sorting a list of tuple that holds the info abt time of certain event and actor name.

We are sorting this list by time of event occurrence - which is the 0th element of a tuple.

Note - s.sort([cmp[, key[, reverse]]]) sorts the items of s in place

How to remove multiple deleted files in Git repository

The built in clean function can also be helpful...

git clean -fd

How to script FTP upload and download?

Batch files don't work that way. They don't just "type" everything - they run system commands, in this case ftp, wait for them to return, and run the next command... so in this case, the interpreter is simply waiting for ftp to exit.

If you must use the ftp command, then prepare a script file (for example, commands.txt and run ftp -s:commands.txt.

But using cURL, or a PHP/Perl/Python/whatever script may be a better idea.

System.BadImageFormatException: Could not load file or assembly

It seems that you are using the 64-bit version of the tool to install a 32-bit/x86 architecture application. Look for the 32-bit version of the tool here:

C:\Windows\Microsoft.NET\Framework\v4.0.30319

and it should install your 32-bit application just fine.

jQuery - multiple $(document).ready ...?

All will get executed and On first Called first run basis!!

<div id="target"></div>

<script>
  $(document).ready(function(){
    jQuery('#target').append('target edit 1<br>');
  });
  $(document).ready(function(){
    jQuery('#target').append('target edit 2<br>');
  });
  $(document).ready(function(){
    jQuery('#target').append('target edit 3<br>');
  });
</script>

Demo As you can see they do not replace each other

Also one thing i would like to mention

in place of this

$(document).ready(function(){});

you can use this shortcut

jQuery(function(){
   //dom ready codes
});

SQL RANK() versus ROW_NUMBER()

ROW_NUMBER : Returns a unique number for each row starting with 1. For rows that have duplicate values,numbers are arbitarily assigned.

Rank : Assigns a unique number for each row starting with 1,except for rows that have duplicate values,in which case the same ranking is assigned and a gap appears in the sequence for each duplicate ranking.

How does HTTP_USER_AGENT work?

http://www.useragentstring.com/

Visit that page, it'll give you a good explanation of each element of your user agent.

Mozilla:

MozillaProductSlice. Claims to be a Mozilla based user agent, which is only true for Gecko browsers like Firefox and Netscape. For all other user agents it means 'Mozilla-compatible'. In modern browsers, this is only used for historical reasons. It has no real meaning anymore

Combining multiple condition in single case statement in Sql Server

select ROUND(CASE 

WHEN  CONVERT( float, REPLACE( isnull( value1,''),',',''))='' AND CONVERT( float, REPLACE( isnull( value2,''),',',''))='' then  CONVERT( float, REPLACE( isnull( value3,''),',',''))

WHEN  CONVERT( float, REPLACE( isnull( value1,''),',',''))='' AND CONVERT( float, REPLACE( isnull( value2,''),',',''))!='' then  CONVERT( float, REPLACE( isnull( value3,''),',',''))

WHEN  CONVERT( float, REPLACE( isnull( value1,''),',',''))!='' AND CONVERT( float, REPLACE( isnull( value2,''),',',''))='' then  CONVERT( float, REPLACE( isnull( value3,''),',',''))

else CONVERT( float, REPLACE(isnull( value1,''),',','')) end,0)  from Tablename where    ID="123" 

Under what conditions is a JSESSIONID created?

Here is some information about one more source of the JSESSIONID cookie:

I was just debugging some Java code that runs on a tomcat server. I was not calling request.getSession() explicitly anywhere in my code but I noticed that a JSESSIONID cookie was still being set.

I finally took a look at the generated Java code corresponding to a JSP in the work directory under Tomcat.

It appears that, whether you like it or not, if you invoke a JSP from a servlet, JSESSIONID will get created!

Added: I just found that by adding the following JSP directive:

<%@ page session="false" %>

you can disable the setting of JSESSIONID by a JSP.

Easy way to use variables of enum types as string in C?

If you are using gcc, it's possible to use:

const char * enum_to_string_map[]={ [enum1]='string1', [enum2]='string2'};

Then just call for instance

enum_to_string_map[enum1]

In MySQL, can I copy one row to insert into the same table?

I might be late in this, but I have a similar solution which has worked for me.

 INSERT INTO `orders` SELECT MAX(`order_id`)+1,`container_id`, `order_date`, `receive_date`, `timestamp` FROM `orders` WHERE `order_id` = 1

This way I don't need to create a temporary table and etc. As the row is copied in the same table the Max(PK)+1 function can be used easily.

I came looking for the solution of this question (had forgotten the syntax) and I ended up making my own query. Funny how things work out some times.

Regards

How to check if an object is defined?

If a class type is not defined, you'll get a compiler error if you try to use the class, so in that sense you should have to check.

If you have an instance, and you want to ensure it's not null, simply check for null:

if (value != null)
{
    // it's not null. 
}

How to change a single value in a NumPy array?

Is this what you are after? Just index the element and assign a new value.

A[2,1]=150

A
Out[345]: 
array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 150, 11, 12],
       [13, 14, 15, 16]])

UIButton: how to center an image and a text using imageEdgeInsets and titleEdgeInsets?

Edit: Updated for Swift 3

In case you're looking for a Swift solution of Jesse Crossen's answer, you can add this to a subclass of UIButton:

override func layoutSubviews() {

    let spacing: CGFloat = 6.0

    // lower the text and push it left so it appears centered
    //  below the image
    var titleEdgeInsets = UIEdgeInsets.zero
    if let image = self.imageView?.image {
        titleEdgeInsets.left = -image.size.width
        titleEdgeInsets.bottom = -(image.size.height + spacing)
    }
    self.titleEdgeInsets = titleEdgeInsets

    // raise the image and push it right so it appears centered
    //  above the text
    var imageEdgeInsets = UIEdgeInsets.zero
    if let text = self.titleLabel?.text, let font = self.titleLabel?.font {
        let attributes = [NSFontAttributeName: font]
        let titleSize = text.size(attributes: attributes)
        imageEdgeInsets.top = -(titleSize.height + spacing)
        imageEdgeInsets.right = -titleSize.width
    }
    self.imageEdgeInsets = imageEdgeInsets

    super.layoutSubviews()
}

How to unlock android phone through ADB

Below commands works both when screen is on and off

To lock the screen:

adb shell input keyevent 82 && adb shell input keyevent 26 && adb shell input keyevent 26

To lock the screen and turn it off

adb shell input keyevent 82 && adb shell input keyevent 26

To unlock the screen without pass

adb shell input keyevent 82 && adb shell input keyevent 66

To unlock the screen that has pass 1234

adb shell input keyevent 82 && adb shell input text 1234 && adb shell input keyevent 66

Slack clean all messages (~8K) in a channel

If you like Python and have obtained a legacy API token from the slack api, you can delete all private messages you sent to a user with the following:

import requests
import sys
import time
from json import loads

# config - replace the bit between quotes with your "token"
token = 'xoxp-854385385283-5438342854238520-513620305190-505dbc3e1c83b6729e198b52f128ad69'

# replace 'Carl' with name of the person you were messaging
dm_name = 'Carl'

# helper methods
api = 'https://slack.com/api/'
suffix = 'token={0}&pretty=1'.format(token)

def fetch(route, args=''):
  '''Make a GET request for data at `url` and return formatted JSON'''
  url = api + route + '?' + suffix + '&' + args
  return loads(requests.get(url).text)

# find the user whose dm messages should be removed
target_user = [i for i in fetch('users.list')['members'] if dm_name in i['real_name']]
if not target_user:
  print(' ! your target user could not be found')
  sys.exit()

# find the channel with messages to the target user
channel = [i for i in fetch('im.list')['ims'] if i['user'] == target_user[0]['id']]
if not channel:
  print(' ! your target channel could not be found')
  sys.exit()

# fetch and delete all messages
print(' * querying for channel', channel[0]['id'], 'with target user', target_user[0]['id'])
args = 'channel=' + channel[0]['id'] + '&limit=100'
result = fetch('conversations.history', args=args)
messages = result['messages']
print(' * has more:', result['has_more'], result.get('response_metadata', {}).get('next_cursor', ''))
while result['has_more']:
  cursor = result['response_metadata']['next_cursor']
  result = fetch('conversations.history', args=args + '&cursor=' + cursor)
  messages += result['messages']
  print(' * next page has more:', result['has_more'])

for idx, i in enumerate(messages):
  # tier 3 method rate limit: https://api.slack.com/methods/chat.delete
  # all rate limits: https://api.slack.com/docs/rate-limits#tiers
  time.sleep(1.05)
  result = fetch('chat.delete', args='channel={0}&ts={1}'.format(channel[0]['id'], i['ts']))
  print(' * deleted', idx+1, 'of', len(messages), 'messages', i['text'])
  if result.get('error', '') == 'ratelimited':
    print('\n ! sorry there have been too many requests. Please wait a little bit and try again.')
    sys.exit()

How to upgrade PowerShell version from 2.0 to 3.0

Download and install from http://www.microsoft.com/en-us/download/details.aspx?id=34595. You need Windows 7 SP1 though.

It's worth keeping in mind that PowerShell 3 on Windows 7 does not have all the cmdlets as PowerShell 3 on Windows 8. So you may still encounter cmdlets that are not present on your system.

Increase max execution time for php

PHP file (for example, my_lengthy_script.php)

ini_set('max_execution_time', 300); //300 seconds = 5 minutes

.htaccess file

<IfModule mod_php5.c>
php_value max_execution_time 300
</IfModule>

More configuration options

<IfModule mod_php5.c>
php_value post_max_size 5M
php_value upload_max_filesize 5M
php_value memory_limit 128M
php_value max_execution_time 300
php_value max_input_time 300
php_value session.gc_maxlifetime 1200
</IfModule>

If wordpress, set this in the config.php file,

define('WP_MEMORY_LIMIT', '128M');

If drupal, sites/default/settings.php

ini_set('memory_limit', '128M');

If you are using other frameworks,

ini_set('memory_limit', '128M');

You can increase memory as gigabyte.

ini_set('memory_limit', '3G'); // 3 Gigabytes

259200 means:-

( 259200/(60x60 minutes) ) / 24 hours ===> 3 Days

More details on my blog

The cast to value type 'Int32' failed because the materialized value is null

Had this error message when I was trying to select from a view.

The problem was the view recently had gained some new null rows (in SubscriberId column), and it had not been updated in EDMX (EF database first).

The column had to be Nullable type for it to work.

var dealer = Context.Dealers.Where(x => x.dealerCode == dealerCode).FirstOrDefault();

Before view refresh:

public int SubscriberId { get; set; }

After view refresh:

public Nullable<int> SubscriberId { get; set; }

Deleting and adding the view back in EDMX worked.

Hope it helps someone.

PHP code to convert a MySQL query to CSV

An update to @jrgns (with some slight syntax differences) solution.

$result = mysql_query('SELECT * FROM `some_table`'); 
if (!$result) die('Couldn\'t fetch records'); 
$num_fields = mysql_num_fields($result); 
$headers = array(); 
for ($i = 0; $i < $num_fields; $i++) 
{     
       $headers[] = mysql_field_name($result , $i); 
} 
$fp = fopen('php://output', 'w'); 
if ($fp && $result) 
{     
       header('Content-Type: text/csv');
       header('Content-Disposition: attachment; filename="export.csv"');
       header('Pragma: no-cache');    
       header('Expires: 0');
       fputcsv($fp, $headers); 
       while ($row = mysql_fetch_row($result)) 
       {
          fputcsv($fp, array_values($row)); 
       }
die; 
} 

What are some good SSH Servers for windows?

I've been using Bitvise SSH Server for a number of years. It is a wonderful product and it is easy to setup and maintain. It gives you great control over how users connect to the server with support for security groups.

How to create a QR code reader in a HTML5 website?

The jsqrcode library by Lazarsoft is now working perfectly using just HTML5, i.e. getUserMedia (WebRTC). You can find it on GitHub.

I also found a great fork which is much simplified. Just one file (plus jQuery) and one call of a method: see html5-qrcode on GitHub.

CSS/HTML: Create a glowing border around an Input Field

input[type="text"]{
   @include transition(all 0.30s ease-in-out);
  outline: none;
  padding: 3px 0px 3px 3px;
  margin: 5px 1px 3px 0px;
  border: 1px solid #DDDDDD;
}
input[type="text"]:focus{
  @include box-shadow(0 0 5px rgba(81, 203, 238, 1));
  -webkit-box-shadow: 0px 0px 5px #007eff;  
  -moz-box-shadow: 0px 0px 5px #007eff;  
  box-shadow: 0px 0px 5px #007eff;
}

ERROR 1067 (42000): Invalid default value for 'created_at'

Just convert it by this line :

for the new table :

CREATE TABLE t1 (
  ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

for Existing Table:

Alter ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

Source :

https://dev.mysql.com/doc/refman/5.5/en/timestamp-initialization.html

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

with JQuery .toggle() you can accomplish it easily

$( ".target" ).toggle();

Random state (Pseudo-random number) in Scikit learn

If you don't mention the random_state in the code, then whenever you execute your code a new random value is generated and the train and test datasets would have different values each time.

However, if you use a particular value for random_state(random_state = 1 or any other value) everytime the result will be same,i.e, same values in train and test datasets. Refer below code:

import pandas as pd 
from sklearn.model_selection import train_test_split
test_series = pd.Series(range(100))
size30split = train_test_split(test_series,random_state = 1,test_size = .3)
size25split = train_test_split(test_series,random_state = 1,test_size = .25)
common = [element for element in size25split[0] if element in size30split[0]]
print(len(common))

Doesn't matter how many times you run the code, the output will be 70.

70

Try to remove the random_state and run the code.

import pandas as pd 
from sklearn.model_selection import train_test_split
test_series = pd.Series(range(100))
size30split = train_test_split(test_series,test_size = .3)
size25split = train_test_split(test_series,test_size = .25)
common = [element for element in size25split[0] if element in size30split[0]]
print(len(common))

Now here output will be different each time you execute the code.

Get java.nio.file.Path object from java.io.File

Yes, you can get it from the File object by using File.toPath(). Keep in mind that this is only for Java 7+. Java versions 6 and below do not have it.

C: Run a System Command and Get Output?

Usually, if the command is an external program, you can use the OS to help you here.

command > file_output.txt

So your C code would be doing something like

exec("command > file_output.txt");

Then you can use the file_output.txt file.

What is the difference between JOIN and JOIN FETCH when using JPA and Hibernate

If you have @oneToOne mapping set to FetchType.LAZY and you use second query (because you need Department objects to be loaded as part of Employee objects) what Hibernate will do is, it will issue queries to fetch Department objects for every individual Employee object it fetches from DB.

Later, in the code you might access Department objects via Employee to Department single-valued association and Hibernate will not issue any query to fetch Department object for the given Employee.

Remember, Hibernate still issues queries equal to the number of Employees it has fetched. Hibernate will issue same number of queries in both above queries, if you wish to access Department objects of all Employee objects

Gradle proxy configuration

Create a file called gradle.properties inside the project folder where the build.gradle file is present. Add the following entry

     systemProp.http.proxyHost=proxy_url
     systemProp.http.proxyPort=proxy_port
     systemProp.http.proxyUser=USER
     systemProp.http.proxyPassword=PWD
     systemProp.https.proxyHost=proxy_url 
     systemProp.https.proxyPort=proxy_port
     systemProp.https.proxyUser=USER
     systemProp.https.proxyPassword=PWD

If you are using DNS for proxy then add it like systemProp.https.proxyHost=www.proxysite.com

For IP just specify the IP with out http:// or https://
Check gradle official doc for more details and setting up proxy at global level

How to pass multiple arguments in processStartInfo?

For makecert, your startInfo.FileName should be the complete path of makecert (or just makecert.exe if it's in standard path) then the Arguments would be -sk server -sky exchange -pe -n CN=localhost -ir LocalMachine -is Root -ic MyCA.cer -sr LocalMachine -ss My MyAdHocTestCert.cer now I'm bit unfamiliar with how certificate store works, but perhaps you'll need to set startInfo.WorkingDirectory if you're referring the .cer files outside the certificate store

SQL Server 2008 - IF NOT EXISTS INSERT ELSE UPDATE

As others have suggested that you should look into MERGE statement but nobody provided a solution using it I'm adding my own answer with this particular TSQL construct. I bet you'll like it.

Important note

Your code has a typo in your if statement in not exists(select...) part. Inner select statement has only one where condition while UserName condition is excluded from the not exists due to invalid brace completion. In any case you cave too many closing braces.

I assume this based on the fact that you're using two where conditions in update statement later on in your code.

Let's continue to my answer...

SQL Server 2008+ support MERGE statement

MERGE statement is a beautiful TSQL gem very well suited for "insert or update" situations. In your case it would look similar to the following code. Take into consideration that I'm declaring variables what are likely stored procedure parameters (I suspect).

declare @clockDate date = '08/10/2012';
declare @userName = 'test';

merge Clock as target
using (select @clockDate, @userName) as source (ClockDate, UserName)
on (target.ClockDate = source.ClockDate and target.UserName = source.UserName)
when matched then
    update
    set BreakOut = getdate()
when not matched then
    insert (ClockDate, UserName, BreakOut)
    values (getdate(), source.UserName, getdate());

Can I use if (pointer) instead of if (pointer != NULL)?

yes, of course! in fact, writing if(pointer) is a more convenient way of writing rather than if(pointer != NULL) because: 1. it is easy to debug 2. easy to understand 3. if accidently, the value of NULL is defined, then also the code will not crash

How to create local notifications?

- (void)applicationDidEnterBackground:(UIApplication *)application
{
   UILocalNotification *notification = [[UILocalNotification alloc]init];
   notification.repeatInterval = NSDayCalendarUnit;
   [notification setAlertBody:@"Hello world"];
   [notification setFireDate:[NSDate dateWithTimeIntervalSinceNow:1]];
   [notification setTimeZone:[NSTimeZone  defaultTimeZone]];
   [application setScheduledLocalNotifications:[NSArray arrayWithObject:notification]];
}

This is worked, but in iOS 8.0 and later, your application must register for user notifications using -[UIApplication registerUserNotificationSettings:] before being able to schedule and present UILocalNotifications, do not forget this.

Case statement in MySQL

MySQL also has IF():

SELECT 
  id, action_heading, 
      IF(action_type='Income',action_amount,0) income, 
      IF(action_type='Expense', action_amount, 0) expense
FROM tbl_transaction

NHibernate.MappingException: No persister for: XYZ

Had a similar problem when find an object by id... All i did was to use the fully qualified name in the class name. That is Before it was :

find("Class",id)

Object so it became like this :

find("assemblyName.Class",id)

What is the difference between C++ and Visual C++?

What is the difference between c++ and visaul c++?

Visual C++ is an IDE. There's also C++Builder from Embarcadero. (Used to be Borland.) There are also a few other C++ IDE's.

I know that c++ has the portability and all so if you know c++ how is it related to visual c++?

C++ is as portable as the libraries that you use in your C++ application. VC++ has some specialized libraries to use with Windows, so if you use those libraries in your C++ application, you're stuck with Windows. But a simple "Hello, World" application that just uses the console as output can be compiled on Windows, Linux, VMS, AS/400, Smartphones, FreeBSD, MS-DOS, CP80 and almost any other system for which you can find a C++ compiler. Injteresting fact: at http://nethack.org/ you can download the C sourcecode for an almost antique game, where you have to walk through a bunch of mazes, kick some monsters around, find treasures and steal some valuable amulet and bring that amulet back out. (It's also a game where you can encounter your characters from previous, failed attempts to get that amulet. :-) The sourcecode of NetHack is a fine example of how portable C (C++) code can be.

Is visual c++ mostly for online apps?

No. But it can be used for online apps. Actually, C# is used more often for server-side web applications while C++ (VC++) is used for all kinds of (server) components that your application will be depending upon.

Would visual basic be better for desktop applications?

Or Embarcadero Delphi. Delphi and Basic are languages that are easier to learn than C++ and both have very good IDE's to develop GUI applications with. Unfortunately, Visual Basic is now running on .NET only, while there are still many developers who need to create WIN32 applications. Those developers often have to choose between Delphi or C++ or else convince management to move to .NET development.

How to get the second column from command output?

This should work to get a specific column out of the command output "docker images":

REPOSITORY                          TAG                 IMAGE ID            CREATED             SIZE
ubuntu                              16.04               12543ced0f6f        10 months ago       122 MB
ubuntu                              latest              12543ced0f6f        10 months ago       122 MB
selenium/standalone-firefox-debug   2.53.0              9f3bab6e046f        12 months ago       613 MB
selenium/node-firefox-debug         2.53.0              d82f2ab74db7        12 months ago       613 MB


docker images | awk '{print $3}'

IMAGE
12543ced0f6f
12543ced0f6f
9f3bab6e046f
d82f2ab74db7

This is going to print the third column

event.preventDefault() function not working in IE

FWIW, in case anyone revisits this question later, you might also check what you are handing to your onKeyPress handler function.

I ran into this error when I mistakenly passed onKeyPress(this) instead of onKeyPress(event).

Just something else to check.

What are libtool's .la file for?

I found very good explanation about .la files here http://openbooks.sourceforge.net/books/wga/dealing-with-libraries.html

Summary (The way I understood): Because libtool deals with static and dynamic libraries internally (through --diable-shared or --disable-static) it creates a wrapper on the library files it builds. They are treated as binary library files with in libtool supported environment.

UITableView load more when scrolling to bottom like Facebook application

Details

  • Swift 5.1, Xcode 11.2.1

Solution

Worked with UIScrollView / UICollectionView / UITableView

import UIKit

class LoadMoreActivityIndicator {

    private let spacingFromLastCell: CGFloat
    private let spacingFromLastCellWhenLoadMoreActionStart: CGFloat
    private weak var activityIndicatorView: UIActivityIndicatorView?
    private weak var scrollView: UIScrollView?

    private var defaultY: CGFloat {
        guard let height = scrollView?.contentSize.height else { return 0.0 }
        return height + spacingFromLastCell
    }

    deinit { activityIndicatorView?.removeFromSuperview() }

    init (scrollView: UIScrollView, spacingFromLastCell: CGFloat, spacingFromLastCellWhenLoadMoreActionStart: CGFloat) {
        self.scrollView = scrollView
        self.spacingFromLastCell = spacingFromLastCell
        self.spacingFromLastCellWhenLoadMoreActionStart = spacingFromLastCellWhenLoadMoreActionStart
        let size:CGFloat = 40
        let frame = CGRect(x: (scrollView.frame.width-size)/2, y: scrollView.contentSize.height + spacingFromLastCell, width: size, height: size)
        let activityIndicatorView = UIActivityIndicatorView(frame: frame)
        if #available(iOS 13.0, *)
        {
            activityIndicatorView.color = .label
        }
        else
        {
            activityIndicatorView.color = .black
        }
        activityIndicatorView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin]
        activityIndicatorView.hidesWhenStopped = true
        scrollView.addSubview(activityIndicatorView)
        self.activityIndicatorView = activityIndicatorView
    }

    private var isHidden: Bool {
        guard let scrollView = scrollView else { return true }
        return scrollView.contentSize.height < scrollView.frame.size.height
    }

    func start(closure: (() -> Void)?) {
        guard let scrollView = scrollView, let activityIndicatorView = activityIndicatorView else { return }
        let offsetY = scrollView.contentOffset.y
        activityIndicatorView.isHidden = isHidden
        if !isHidden && offsetY >= 0 {
            let contentDelta = scrollView.contentSize.height - scrollView.frame.size.height
            let offsetDelta = offsetY - contentDelta
            
            let newY = defaultY-offsetDelta
            if newY < scrollView.frame.height {
                activityIndicatorView.frame.origin.y = newY
            } else {
                if activityIndicatorView.frame.origin.y != defaultY {
                    activityIndicatorView.frame.origin.y = defaultY
                }
            }

            if !activityIndicatorView.isAnimating {
                if offsetY > contentDelta && offsetDelta >= spacingFromLastCellWhenLoadMoreActionStart && !activityIndicatorView.isAnimating {
                    activityIndicatorView.startAnimating()
                    closure?()
                }
            }

            if scrollView.isDecelerating {
                if activityIndicatorView.isAnimating && scrollView.contentInset.bottom == 0 {
                    UIView.animate(withDuration: 0.3) { [weak self] in
                        if let bottom = self?.spacingFromLastCellWhenLoadMoreActionStart {
                            scrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: bottom, right: 0)
                        }
                    }
                }
            }
        }
    }

    func stop(completion: (() -> Void)? = nil) {
        guard let scrollView = scrollView , let activityIndicatorView = activityIndicatorView else { return }
        let contentDelta = scrollView.contentSize.height - scrollView.frame.size.height
        let offsetDelta = scrollView.contentOffset.y - contentDelta
        if offsetDelta >= 0 {
            UIView.animate(withDuration: 0.3, animations: {
                scrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
            }) { _ in completion?() }
        } else {
            scrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
            completion?()
        }
        activityIndicatorView.stopAnimating()
    }
}

Usage

init

activityIndicator = LoadMoreActivityIndicator(scrollView: tableView, spacingFromLastCell: 10, spacingFromLastCellWhenLoadMoreActionStart: 60)

handling

extension ViewController: UITableViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        activityIndicator.start {
            DispatchQueue.global(qos: .utility).async {
                sleep(3)
                DispatchQueue.main.async { [weak self] in
                    self?.activityIndicator.stop()
                }
            }
        }
    }
}

Full Sample

Do not forget to paste the solution code.

import UIKit

class ViewController: UIViewController {
    
    fileprivate var activityIndicator: LoadMoreActivityIndicator!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let tableView = UITableView(frame: view.frame)
        view.addSubview(tableView)
        tableView.translatesAutoresizingMaskIntoConstraints = false
        tableView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
        tableView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
        tableView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
        
        tableView.dataSource = self
        tableView.delegate = self
        tableView.tableFooterView = UIView()
        activityIndicator = LoadMoreActivityIndicator(scrollView: tableView, spacingFromLastCell: 10, spacingFromLastCellWhenLoadMoreActionStart: 60)
    }
}

extension ViewController: UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 30
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        cell.textLabel?.text = "\(indexPath)"
        return cell
    }
}

extension ViewController: UITableViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        activityIndicator.start {
            DispatchQueue.global(qos: .utility).async {
                for i in 0..<3 {
                    print("!!!!!!!!! \(i)")
                    sleep(1)
                }
                DispatchQueue.main.async { [weak self] in
                    self?.activityIndicator.stop()
                }
            }
        }
    }
}

Result

enter image description here

415 Unsupported Media Type - POST json to OData service in lightswitch 2012

It looks like this issue has to do with the difference between the Content-Type and Accept headers. In HTTP, Content-Type is used in request and response payloads to convey the media type of the current payload. Accept is used in request payloads to say what media types the server may use in the response payload.

So, having a Content-Type in a request without a body (like your GET request) has no meaning. When you do a POST request, you are sending a message body, so the Content-Type does matter.

If a server is not able to process the Content-Type of the request, it will return a 415 HTTP error. (If a server is not able to satisfy any of the media types in the request Accept header, it will return a 406 error.)

In OData v3, the media type "application/json" is interpreted to mean the new JSON format ("JSON light"). If the server does not support reading JSON light, it will throw a 415 error when it sees that the incoming request is JSON light. In your payload, your request body is verbose JSON, not JSON light, so the server should be able to process your request. It just doesn't because it sees the JSON light content type.

You could fix this in one of two ways:

  1. Make the Content-Type "application/json;odata=verbose" in your POST request, or
  2. Include the DataServiceVersion header in the request and set it be less than v3. For example:

    DataServiceVersion: 2.0;
    

(Option 2 assumes that you aren't using any v3 features in your request payload.)

How do you create a static class in C++?

This is similar to C#'s way of doing it in C++

In C# file.cs you can have private var inside a public function. When in another file you can use it by calling the namespace with the function as in:

MyNamespace.Function(blah);

Here's how to imp the same in C++:

SharedModule.h

class TheDataToBeHidden
{
  public:
    static int _var1;
    static int _var2;
};

namespace SharedData
{
  void SetError(const char *Message, const char *Title);
  void DisplayError(void);
}

SharedModule.cpp

//Init the data (Link error if not done)
int TheDataToBeHidden::_var1 = 0;
int TheDataToBeHidden::_var2 = 0;


//Implement the namespace
namespace SharedData
{
  void SetError(const char *Message, const char *Title)
  {
    //blah using TheDataToBeHidden::_var1, etc
  }

  void DisplayError(void)
  {
    //blah
  }
}

OtherFile.h

#include "SharedModule.h"

OtherFile.cpp

//Call the functions using the hidden variables
SharedData::SetError("Hello", "World");
SharedData::DisplayError();

How to make a form close when pressing the escape key?

Button cancelBTN = new Button();
cancelBTN.Size = new Size(0, 0);
cancelBTN.TabStop = false;
this.Controls.Add(cancelBTN);
this.CancelButton = cancelBTN;

Android ImageView Animation

Inside the element put:

android:repeatCount="infinite"

Unable to make the session state request to the session state server

Another thing to check is whether you have Windows Firewall enabled, since that might be blocking port 42424.

TSQL Default Minimum DateTime

I think your only option here is a constant. With that said - don't use it - stick with nulls instead of bogus dates.

create table atable
(
  atableID int IDENTITY(1, 1) PRIMARY KEY CLUSTERED,
  Modified datetime DEFAULT '1/1/1753'
)

PHP GuzzleHttp. How to make a post request with params?

$client = new \GuzzleHttp\Client();
$request = $client->post('http://demo.website.com/api', [
    'body' => json_encode($dataArray)
]);
$response = $request->getBody();

Add

openssl.cafile in php.ini file

Html helper for <input type="file" />

Or you could do it properly:

In your HtmlHelper Extension class:

public static MvcHtmlString FileFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression)
    {
        return helper.FileFor(expression, null);
    }

public static MvcHtmlString FileFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes)
    {
        var builder = new TagBuilder("input");

        var id = helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression));
        builder.GenerateId(id);
        builder.MergeAttribute("name", id);
        builder.MergeAttribute("type", "file");

        builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));

        // Render tag
        return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing));
    }

This line:

var id = helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression));

Generates an id unique to the model, you know in lists and stuff. model[0].Name etc.

Create the correct property in the model:

public HttpPostedFileBase NewFile { get; set; }

Then you need to make sure your form will send files:

@using (Html.BeginForm("Action", "Controller", FormMethod.Post, new { enctype = "multipart/form-data" }))

Then here's your helper:

@Html.FileFor(x => x.NewFile)

find_spec_for_exe': can't find gem bundler (>= 0.a) (Gem::GemNotFoundException)

Update:

According @noraj's answer and @Niels Kristian's comment, the following command should do the job.

gem update --system
bundle install

I wrote this in case someone gets into an issue like mine.

gem install bundler shows that everythings installs well.

Fetching: bundler-1.16.0.gem (100%)
Successfully installed bundler-1.16.0
Parsing documentation for bundler-1.16.0
Installing ri documentation for bundler-1.16.0
Done installing documentation for bundler after 7 seconds
1 gem installed

When I typed bundle there was an error:

/Users/nikkov/.rvm/gems/ruby-2.4.0/bin/bundle:23:in `load': cannot load such file -- /Users/nikkov/.rvm/rubies/ruby-2.4.0/lib/ruby/gems/2.4.0/gems/bundler-1.16.0/exe/bundle (LoadError)
    from /Users/nikkov/.rvm/gems/ruby-2.4.0/bin/bundle:23:in `<main>'
    from /Users/nikkov/.rvm/gems/ruby-2.4.0/bin/ruby_executable_hooks:15:in `eval'
    from /Users/nikkov/.rvm/gems/ruby-2.4.0/bin/ruby_executable_hooks:15:in `<main>'

And in the folder /Users/nikkov/.rvm/rubies/ruby-2.4.0/lib/ruby/gems/2.4.0/gems/ there wasn't a bundler-1.16.0 folder.

I fixed this with sudo gem install bundler

How to Set Selected value in Multi-Value Select in Jquery-Select2.?

Using select2 jquery library:

$('#selector').val(arrayOfValues).trigger('change')

How to split a string to 2 strings in C

#include <string.h>

char *token;
char line[] = "SEVERAL WORDS";
char *search = " ";


// Token will point to "SEVERAL".
token = strtok(line, search);


// Token will point to "WORDS".
token = strtok(NULL, search);

Update

Note that on some operating systems, strtok man page mentions:

This interface is obsoleted by strsep(3).

An example with strsep is shown below:

char* token;
char* string;
char* tofree;

string = strdup("abc,def,ghi");

if (string != NULL) {

  tofree = string;

  while ((token = strsep(&string, ",")) != NULL)
  {
    printf("%s\n", token);
  }

  free(tofree);
}

Returning binary file from controller in ASP.NET Web API

For those using .NET Core:

You can make use of the IActionResult interface in an API controller method, like so...

    [HttpGet("GetReportData/{year}")]
    public async Task<IActionResult> GetReportData(int year)
    {
        // Render Excel document in memory and return as Byte[]
        Byte[] file = await this._reportDao.RenderReportAsExcel(year);

        return File(file, "application/vnd.openxmlformats", "fileName.xlsx");
    }

This example is simplified, but should get the point across. In .NET Core this process is so much simpler than in previous versions of .NET - i.e. no setting response type, content, headers, etc.

Also, of course the MIME type for the file and the extension will depend on individual needs.

Reference: SO Post Answer by @NKosi

Generate sha256 with OpenSSL and C++

Using OpenSSL's EVP interface (the following is for OpenSSL 1.1):

#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
#include <openssl/evp.h>

bool computeHash(const std::string& unhashed, std::string& hashed)
{
    bool success = false;

    EVP_MD_CTX* context = EVP_MD_CTX_new();

    if(context != NULL)
    {
        if(EVP_DigestInit_ex(context, EVP_sha256(), NULL))
        {
            if(EVP_DigestUpdate(context, unhashed.c_str(), unhashed.length()))
            {
                unsigned char hash[EVP_MAX_MD_SIZE];
                unsigned int lengthOfHash = 0;

                if(EVP_DigestFinal_ex(context, hash, &lengthOfHash))
                {
                    std::stringstream ss;
                    for(unsigned int i = 0; i < lengthOfHash; ++i)
                    {
                        ss << std::hex << std::setw(2) << std::setfill('0') << (int)hash[i];
                    }

                    hashed = ss.str();
                    success = true;
                }
            }
        }

        EVP_MD_CTX_free(context);
    }

    return success;
}

int main(int, char**)
{
    std::string pw1 = "password1", pw1hashed;
    std::string pw2 = "password2", pw2hashed;
    std::string pw3 = "password3", pw3hashed;
    std::string pw4 = "password4", pw4hashed;

    hashPassword(pw1, pw1hashed);
    hashPassword(pw2, pw2hashed);
    hashPassword(pw3, pw3hashed);
    hashPassword(pw4, pw4hashed);

    std::cout << pw1hashed << std::endl;
    std::cout << pw2hashed << std::endl;
    std::cout << pw3hashed << std::endl;
    std::cout << pw4hashed << std::endl;

    return 0;
}

The advantage of this higher level interface is that you simply need to swap out the EVP_sha256() call with another digest's function, e.g. EVP_sha512(), to use a different digest. So it adds some flexibility.

Named colors in matplotlib

I constantly forget the names of the colors I want to use and keep coming back to this question =)

The previous answers are great, but I find it a bit difficult to get an overview of the available colors from the posted image. I prefer the colors to be grouped with similar colors, so I slightly tweaked the matplotlib answer that was mentioned in a comment above to get a color list sorted in columns. The order is not identical to how I would sort by eye, but I think it gives a good overview.

I updated the image and code to reflect that 'rebeccapurple' has been added and the three sage colors have been moved under the 'xkcd:' prefix since I posted this answer originally.

enter image description here

I really didn't change much from the matplotlib example, but here is the code for completeness.

import matplotlib.pyplot as plt
from matplotlib import colors as mcolors


colors = dict(mcolors.BASE_COLORS, **mcolors.CSS4_COLORS)

# Sort colors by hue, saturation, value and name.
by_hsv = sorted((tuple(mcolors.rgb_to_hsv(mcolors.to_rgba(color)[:3])), name)
                for name, color in colors.items())
sorted_names = [name for hsv, name in by_hsv]

n = len(sorted_names)
ncols = 4
nrows = n // ncols

fig, ax = plt.subplots(figsize=(12, 10))

# Get height and width
X, Y = fig.get_dpi() * fig.get_size_inches()
h = Y / (nrows + 1)
w = X / ncols

for i, name in enumerate(sorted_names):
    row = i % nrows
    col = i // nrows
    y = Y - (row * h) - h

    xi_line = w * (col + 0.05)
    xf_line = w * (col + 0.25)
    xi_text = w * (col + 0.3)

    ax.text(xi_text, y, name, fontsize=(h * 0.8),
            horizontalalignment='left',
            verticalalignment='center')

    ax.hlines(y + h * 0.1, xi_line, xf_line,
              color=colors[name], linewidth=(h * 0.8))

ax.set_xlim(0, X)
ax.set_ylim(0, Y)
ax.set_axis_off()

fig.subplots_adjust(left=0, right=1,
                    top=1, bottom=0,
                    hspace=0, wspace=0)
plt.show()

Additional named colors

Updated 2017-10-25. I merged my previous updates into this section.

xkcd

If you would like to use additional named colors when plotting with matplotlib, you can use the xkcd crowdsourced color names, via the 'xkcd:' prefix:

plt.plot([1,2], lw=4, c='xkcd:baby poop green')

Now you have access to a plethora of named colors!

enter image description here

Tableau

The default Tableau colors are available in matplotlib via the 'tab:' prefix:

plt.plot([1,2], lw=4, c='tab:green')

There are ten distinct colors:

enter image description here

HTML

You can also plot colors by their HTML hex code:

plt.plot([1,2], lw=4, c='#8f9805')

This is more similar to specifying and RGB tuple rather than a named color (apart from the fact that the hex code is passed as a string), and I will not include an image of the 16 million colors you can choose from...


For more details, please refer to the matplotlib colors documentation and the source file specifying the available colors, _color_data.py.


PHP XML how to output nice format

This is a slight variation of the above theme but I'm putting here in case others hit this and cannot make sense of it ...as I did.

When using saveXML(), preserveWhiteSpace in the target DOMdocument does not apply to imported nodes (as at PHP 5.6).

Consider the following code:

$dom = new DOMDocument();                               //create a document
$dom->preserveWhiteSpace = false;                       //disable whitespace preservation
$dom->formatOutput = true;                              //pretty print output
$documentElement = $dom->createElement("Entry");        //create a node
$dom->appendChild ($documentElement);                   //append it 
$message = new DOMDocument();                           //create another document
$message->loadXML($messageXMLtext);                     //populate the new document from XML text
$node=$dom->importNode($message->documentElement,true); //import the new document content to a new node in the original document
$documentElement->appendChild($node);                   //append the new node to the document Element
$dom->saveXML($dom->documentElement);                   //print the original document

In this context, the $dom->saveXML(); statement will NOT pretty print the content imported from $message, but content originally in $dom will be pretty printed.

In order to achieve pretty printing for the entire $dom document, the line:

$message->preserveWhiteSpace = false; 

must be included after the $message = new DOMDocument(); line - ie. the document/s from which the nodes are imported must also have preserveWhiteSpace = false.

How do you install Google frameworks (Play, Accounts, etc.) on a Genymotion virtual device?

EDIT 2

After three months we can say: no more official Google Apps in Genymotion and CyanogenMod-like method is only way to get Google Apps. However, you can still use the previous project of the Genymotion team: AndroVM (download mirror).


EDIT

Google apps will be removed from Genymotion in November. You can find more information on the Genymotion Google Plus page.


Choose virtual device with Google Apps:

Done:

Are there dictionaries in php?

Associative array in PHP actually considered as a dictionary.

An array in PHP is actually an ordered map. A map is a type that associates values to keys. it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more.

<?php
$array = array(
    "foo" => "bar",
    "bar" => "foo",
);

// Using the short array syntax
$array = [
    "foo" => "bar",
    "bar" => "foo",
];
?>

An array is different than a dictionary in that arrays have both an index and a key. Dictionaries only have keys and no index.

How do I include inline JavaScript in Haml?

:javascript
    $(document).ready( function() {
      $('body').addClass( 'test' );
    } );

Docs: http://haml.info/docs/yardoc/file.REFERENCE.html#javascript-filter

how to put image in center of html page?

If:

X is image width,
Y is image height,

then:

img {
    position: absolute;
    top: 50%;
    left: 50%;
    margin-left: -(X/2)px;
    margin-top: -(Y/2)px;
}

But keep in mind this solution is valid only if the only element on your site will be this image. I suppose that's the case here.

Using this method gives you the benefit of fluidity. It won't matter how big (or small) someone's screen is. The image will always stay in the middle.

Add padding on view programmatically

The best way is not to write your own funcion.

Let me explain the motivaion - please lookup the official Android source code.

In TypedValue.java we have:

    public static int complexToDimensionPixelSize(int data,
            DisplayMetrics metrics)
    {
        final float value = complexToFloat(data);
        final float f = applyDimension(
                (data>>COMPLEX_UNIT_SHIFT)&COMPLEX_UNIT_MASK,
                value,
                metrics);
        final int res = (int) ((f >= 0) ? (f + 0.5f) : (f - 0.5f));
        if (res != 0) return res;
        if (value == 0) return 0;
        if (value > 0) return 1;
        return -1;
    }

and:

    public static float applyDimension(int unit, float value,
                                       DisplayMetrics metrics)
    {
        switch (unit) {
        case COMPLEX_UNIT_PX:
            return value;
        case COMPLEX_UNIT_DIP:
            return value * metrics.density;
        case COMPLEX_UNIT_SP:
            return value * metrics.scaledDensity;
        case COMPLEX_UNIT_PT:
            return value * metrics.xdpi * (1.0f/72);
        case COMPLEX_UNIT_IN:
            return value * metrics.xdpi;
        case COMPLEX_UNIT_MM:
            return value * metrics.xdpi * (1.0f/25.4f);
        }
        return 0;
    }

As you can see, DisplayMetrics metrics can differ, which means it would yield different values across Android-OS powered devices.

I strongly recommend putting your dp padding in dimen xml file and use the official Android conversions to have consistent behaviour with regard to how Android framework works.

Help with packages in java - import does not work

You got a bunch of good answers, so I'll just throw out a suggestion. If you are going to be working on this project for more than 2 days, download eclipse or netbeans and build your project in there.

If you are not normally a java programmer, then the help it will give you will be invaluable.

It's not worth the 1/2 hour download/install if you are only spending 2 hours on it.

Both have hotkeys/menu items to "Fix imports", with this you should never have to worry about imports again.

Returning pointer from a function

To my knowledge the use of the keyword new, does relatively the same thing as malloc(sizeof identifier). The code below demonstrates how to use the keyword new.

    void main(void){
        int* test;
        test = tester();
        printf("%d",*test);
        system("pause");
    return;
}
    int* tester(void){
        int *retMe;
        retMe = new int;//<----Here retMe is getting malloc for integer type
        *retMe = 12;<---- Initializes retMe... Note * dereferences retMe 
    return retMe;
}

Vue js error: Component template should contain exactly one root element

For a more complete answer: http://www.compulsivecoders.com/tech/vuejs-component-template-should-contain-exactly-one-root-element/

But basically:

  • Currently, a VueJS template can contain only one root element (because of rendering issue)
  • In cases you really need to have two root elements because HTML structure does not allow you to create a wrapping parent element, you can use vue-fragment.

To install it:

npm install vue-fragment

To use it:

import Fragment from 'vue-fragment';
Vue.use(Fragment.Plugin);

// or

import { Plugin } from 'vue-fragment';
Vue.use(Plugin);

Then, in your component:

<template>
  <fragment>
    <tr class="hola">
      ...
    </tr>
    <tr class="hello">
      ...
    </tr>
  </fragment>
</template>

Most pythonic way to delete a file which may not exist

Another solution with your own message in exception.

import os

try:
    os.remove(filename)
except:
    print("Not able to delete the file %s" % filename)

Copy data from one column to other column (which is in a different table)

I think that all previous answers are correct, this below code is very valid specially if you have to update multiple rows at once, note: it's PL/SQL

DECLARE
    CURSOR myCursor IS 
      Select contacts.BusinessCountry 
      From contacts c WHERE c.Key = t.Key;
    ---------------------------------------------------------------------
BEGIN
    FOR resultValue IN myCursor LOOP
        Update tblindiantime t
        Set CountryName=resultValue.BusinessCountry 
        where t.key=resultValue.key;
    END LOOP;
END;

I wish this could help.

How to sort by two fields in Java?

You can do like this:

List<User> users = Lists.newArrayList(
  new User("Pedro", 12), 
  new User("Maria", 10), 
  new User("Rafael",12)
);

users.sort(
  Comparator.comparing(User::getName).thenComparing(User::getAge)
);

How to create new div dynamically, change it, move it, modify it in every way possible, in JavaScript?

Have you tried JQuery? Vanilla javascript can be tough. Try using this:

$('.container-element').add('<div>Insert Div Content</div>');

.container-element is a JQuery selector that marks the element with the class "container-element" (presumably the parent element in which you want to insert your divs). Then the add() function inserts HTML into the container-element.

How to select only 1 row from oracle sql?

select a.user from (select user from users order by user) a where rownum = 1

will perform the best, another option is:

select a.user 
from ( 
select user, 
row_number() over (order by user) user_rank, 
row_number() over (partition by dept order by user) user_dept_rank 
from users 
) a 
where a.user_rank = 1 or user_dept_rank = 2

in scenarios where you want different subsets, but I guess you could also use RANK() But, I also like row_number() over(...) since no grouping is required.

Column name or number of supplied values does not match table definition

The problem I had that caused this error was that I was trying to insert null values into a NOT NULL column.

Get a list of dates between two dates using a function

A Bit late to the party, but I like this solution quite a bit.

CREATE FUNCTION ExplodeDates(@startDate DateTime, @endDate DateTime)
RETURNS table as
return (
    SELECT  TOP (DATEDIFF(DAY, @startDate, @endDate) + 1)
            DATEADD(DAY, ROW_NUMBER() OVER(ORDER BY a.object_id) - 1, @startDate) AS DATE
    FROM    sys.all_objects a
            CROSS JOIN sys.all_objects b
            )

How to use comparison operators like >, =, < on BigDecimal

You can use method named compareTo, x.compareTo(y). It will return 0 if x and y are equal, 1 if x is greater than y and -1 if x is smaller than y

Confused by python file mode "w+"

All file modes in Python

  • r for reading
  • r+ opens for reading and writing (cannot truncate a file)
  • w for writing
  • w+ for writing and reading (can truncate a file)
  • rb for reading a binary file. The file pointer is placed at the beginning of the file.
  • rb+ reading or writing a binary file
  • wb+ writing a binary file
  • a+ opens for appending
  • ab+ Opens a file for both appending and reading in binary. The file pointer is at the end of the file if the file exists. The file opens in the append mode.
  • x open for exclusive creation, failing if the file already exists (Python 3)

How to resolve git error: "Updates were rejected because the tip of your current branch is behind"

This worked for me:

git branch

Copy the current branch name to clipboard

git pull origin <paste-branch-name>
git push

413 Request Entity Too Large - File Upload Issue

Please enter domain nginx file :

nano /etc/nginx/sites-available/domain.set

Add to file this code

client_max_body_size 24000M;

If you get error use this command

nginx -t

How to remove all CSS classes using jQuery/JavaScript?

Since not all versions of jQuery are created equal, you may run into the same issue I did which means calling $("#item").removeClass(); does not actually remove the class. (Probably a bug)

A more reliable method is to simply use raw JavaScript and remove the class attribute altogether.

document.getElementById("item").removeAttribute("class");

How does internationalization work in JavaScript?

Some of it is native, the rest is available through libraries.

For example Datejs is a good international date library.

For the rest, it's just about language translation, and JavaScript is natively Unicode compatible (as well as all major browsers).

How to use multiprocessing pool.map with multiple arguments?

The answer to this is version- and situation-dependent. The most general answer for recent versions of Python (since 3.3) was first described below by J.F. Sebastian.1 It uses the Pool.starmap method, which accepts a sequence of argument tuples. It then automatically unpacks the arguments from each tuple and passes them to the given function:

import multiprocessing
from itertools import product

def merge_names(a, b):
    return '{} & {}'.format(a, b)

if __name__ == '__main__':
    names = ['Brown', 'Wilson', 'Bartlett', 'Rivera', 'Molloy', 'Opie']
    with multiprocessing.Pool(processes=3) as pool:
        results = pool.starmap(merge_names, product(names, repeat=2))
    print(results)

# Output: ['Brown & Brown', 'Brown & Wilson', 'Brown & Bartlett', ...

For earlier versions of Python, you'll need to write a helper function to unpack the arguments explicitly. If you want to use with, you'll also need to write a wrapper to turn Pool into a context manager. (Thanks to muon for pointing this out.)

import multiprocessing
from itertools import product
from contextlib import contextmanager

def merge_names(a, b):
    return '{} & {}'.format(a, b)

def merge_names_unpack(args):
    return merge_names(*args)

@contextmanager
def poolcontext(*args, **kwargs):
    pool = multiprocessing.Pool(*args, **kwargs)
    yield pool
    pool.terminate()

if __name__ == '__main__':
    names = ['Brown', 'Wilson', 'Bartlett', 'Rivera', 'Molloy', 'Opie']
    with poolcontext(processes=3) as pool:
        results = pool.map(merge_names_unpack, product(names, repeat=2))
    print(results)

# Output: ['Brown & Brown', 'Brown & Wilson', 'Brown & Bartlett', ...

In simpler cases, with a fixed second argument, you can also use partial, but only in Python 2.7+.

import multiprocessing
from functools import partial
from contextlib import contextmanager

@contextmanager
def poolcontext(*args, **kwargs):
    pool = multiprocessing.Pool(*args, **kwargs)
    yield pool
    pool.terminate()

def merge_names(a, b):
    return '{} & {}'.format(a, b)

if __name__ == '__main__':
    names = ['Brown', 'Wilson', 'Bartlett', 'Rivera', 'Molloy', 'Opie']
    with poolcontext(processes=3) as pool:
        results = pool.map(partial(merge_names, b='Sons'), names)
    print(results)

# Output: ['Brown & Sons', 'Wilson & Sons', 'Bartlett & Sons', ...

1. Much of this was inspired by his answer, which should probably have been accepted instead. But since this one is stuck at the top, it seemed best to improve it for future readers.

Delete file from internal storage

This works for me:

Java

File file = new File(photoPath);
file.delete();

MediaScannerConnection.scanFile(context,
                new String[]{file.toString()},
                new String[]{file.getName()},null);

Kotlin

val file = File(photoPath) 
file.delete()

MediaScannerConnection.scanFile(context, arrayOf(file.toString()),
      arrayOf(file.getName()), null)

How do I get a button to open another activity?

Using an OnClickListener

Inside your Activity instance's onCreate() method you need to first find your Button by it's id using findViewById() and then set an OnClickListener for your button and implement the onClick() method so that it starts your new Activity.

Button yourButton = (Button) findViewById(R.id.your_buttons_id);

yourButton.setOnClickListener(new OnClickListener(){
    public void onClick(View v){                        
        startActivity(new Intent(YourCurrentActivity.this, YourNewActivity.class));
    }
});

This is probably most developers preferred method. However, there is a common alternative.

Using onClick in XML

Alternatively you can use the android:onClick="yourMethodName" to declare the method name in your Activity which is called when you click your Button, and then declare your method like so;

public void yourMethodName(View v){
    startActivity(new Intent(YourCurrentActivity.this, YourNewActivity.class));
}

Also, don't forget to declare your new Activity in your manifest.xml. I hope this helps.

References;

Laravel - Pass more than one variable to view

Use compact

function view($view)
{
    $ms = Person::where('name', '=', 'Foo Bar')->first();

    $persons = Person::order_by('list_order', 'ASC')->get();
    return View::make('users', compact('ms','persons'));
}

jQuery ajax upload file in asp.net mvc

You can't upload files via ajax, you need to use an iFrame or some other trickery to do a full postback. This is mainly due to security concerns.

Here's a decent write-up including a sample project using SWFUpload and ASP.Net MVC by Steve Sanderson. It's the first thing I read getting this working properly with Asp.Net MVC (I was new to MVC at the time as well), hopefully it's as helpful for you.

OnChange event using React JS for drop down

var MySelect = React.createClass({
getInitialState: function() {
 

_x000D_
_x000D_
var MySelect = React.createClass({
 getInitialState: function() {
     return {
         value: 'select'
     }
 },
 change: function(event){
     event.persist(); //THE MAIN LINE THAT WILL SET THE VALUE
     this.setState({value: event.target.value});
 },
 render: function(){
    return(
       <div>
           <select id="lang" onChange={this.change.bind(this)} value={this.state.value}>
              <option value="select">Select</option>
              <option value="Java">Java</option>
              <option value="C++">C++</option>
           </select>
           <p></p>
           <p>{this.state.value}</p>
       </div>
    );
 }
});
React.render(<MySelect />, document.body); 
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
_x000D_
_x000D_
_x000D_

Use Toast inside Fragment

As stated by alfo888_ibg:

@Override
public void onClick(View arg0) {
   Toast.makeText(activity,"Text!",Toast.LENGTH_SHORT).show();
}

Just do:

    Toast.makeText(getActivity(),"Text!",Toast.LENGTH_SHORT).show();

this worked for me.

Can't start hostednetwork

Symptoms
You install an application that uses Microsoft Virtual WiFi technology on a computer that is running Windows 7 or Windows Server 2008 R2. However, the application does not work after the computer restarts. Additionally, you receive an error message that resembles the following:

The hosted network couldn't be started. The group or resource is not in the correct state to perform the requested operation.

Cause
This issue occurs because the Virtual Wi-Fi filter driver does not create the Virtual Wi-Fi Adapter correctly when a PNP resource rebalance occurs during the startup process.

Notes
1.This issue may occur when a Plug and Play (PNP) resource rebalance occurs during the startup process. The PNP resource rebalance is usually triggered by a change to the hardware configuration.
2.If you open Device Manager when this issue occurs, you notice that the Virtual WiFi Adapter is not created.

If you can't restart your hostednetwork after rebooting the OS ,just Try this hotfix .It fixed my problem. Or try to figure it out by yourself according to the Symptoms and Cause mentioned at the start of my answer.

Use IntelliJ to generate class diagram

IntelliJ IDEA 14+

  • Show diagram popup

    Right click on a type/class/package > Diagrams > Show Diagram Popup...
    or Ctrl+Alt+U

  • Show diagram (opens a new tab)

    Right click on a type/class/package > Diagrams > Show Diagram...
    or Ctrl+Alt+Shift+U

    right click Diagrams Show Diagram

By default, you see only the classes/interfaces names. If you want to see more details, go to File > Settings... > Tools > Diagrams and check what you want (E.g.: Fields, Methods, etc.)


P.S.: You need IntelliJ IDEA Ultimate, because this feature is not supported in Community Edition. If you go to File > Settings... > Plugins, you can see that there is not UML Support plugin in Community Edition.

C++ for each, pulling from vector elements

The for each syntax is supported as an extension to native c++ in Visual Studio.

The example provided in msdn

#include <vector>
#include <iostream>

using namespace std;

int main() 
{
  int total = 0;

  vector<int> v(6);
  v[0] = 10; v[1] = 20; v[2] = 30;
  v[3] = 40; v[4] = 50; v[5] = 60;

  for each(int i in v) {
    total += i;
  }

  cout << total << endl;
}

(works in VS2013) is not portable/cross platform but gives you an idea of how to use for each.

The standard alternatives (provided in the rest of the answers) apply everywhere. And it would be best to use those.

Populating a ComboBox using C#

Simple way is:

Dictionary<string, string> dict = new Dictionary<string, string>()
{
    {"English ","En" },
    {"Italian  ","It" },
    {"Spainish  ","Sp " }
};

combo.DataSource = new BindingSource(dict, null);
combo.DisplayMember = "Key";
combo.ValueMember = "Value";

input file appears to be a text format dump. Please use psql

From the pg_dump documentation:

Examples

To dump a database called mydb into a SQL-script file:

$ pg_dump mydb > db.sql

To reload such a script into a (freshly created) database named newdb:

$ psql -d newdb -f db.sql

To dump a database into a custom-format archive file:

$ pg_dump -Fc mydb > db.dump

To dump a database into a directory-format archive:

$ pg_dump -Fd mydb -f dumpdir

To reload an archive file into a (freshly created) database named newdb:

$ pg_restore -d newdb db.dump

From the pg_restore documentation:

Examples

Assume we have dumped a database called mydb into a custom-format dump file:

$ pg_dump -Fc mydb > db.dump

To drop the database and recreate it from the dump:

$ dropdb mydb
$ pg_restore -C -d postgres db.dump

Microsoft Visual C++ Compiler for Python 3.4

Unfortunately to be able to use the extension modules provided by others you'll be forced to use the official compiler to compile Python. These are:

Alternatively, you can use MinGw to compile extensions in a way that won't depend on others.

See: https://docs.python.org/2/install/#gnu-c-cygwin-MinGW or https://docs.python.org/3.4/install/#gnu-c-cygwin-mingw

This allows you to have one compiler to build your extensions for both versions of Python, Python 2.x and Python 3.x.

how to convert from int to char*?

I think you can use a sprintf :

int number = 33;
char* numberstring[(((sizeof number) * CHAR_BIT) + 2)/3 + 2];
sprintf(numberstring, "%d", number);

Could not create the Java virtual machine

Make sure the physical available memory is more then VM defined min/max memory.

How to set Android camera orientation properly?

From the Javadocs for setDisplayOrientation(int) (Requires API level 9):

 public static void setCameraDisplayOrientation(Activity activity,
         int cameraId, android.hardware.Camera camera) {
     android.hardware.Camera.CameraInfo info =
             new android.hardware.Camera.CameraInfo();
     android.hardware.Camera.getCameraInfo(cameraId, info);
     int rotation = activity.getWindowManager().getDefaultDisplay()
             .getRotation();
     int degrees = 0;
     switch (rotation) {
         case Surface.ROTATION_0: degrees = 0; break;
         case Surface.ROTATION_90: degrees = 90; break;
         case Surface.ROTATION_180: degrees = 180; break;
         case Surface.ROTATION_270: degrees = 270; break;
     }

     int result;
     if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
         result = (info.orientation + degrees) % 360;
         result = (360 - result) % 360;  // compensate the mirror
     } else {  // back-facing
         result = (info.orientation - degrees + 360) % 360;
     }
     camera.setDisplayOrientation(result);
 }

How to change a string into uppercase

for making uppercase from lowercase to upper just use

"string".upper()

where "string" is your string that you want to convert uppercase

for this question concern it will like this:

s.upper()

for making lowercase from uppercase string just use

"string".lower()

where "string" is your string that you want to convert lowercase

for this question concern it will like this:

s.lower()

If you want to make your whole string variable use

s="sadf"
# sadf

s=s.upper()
# SADF

Ubuntu: Using curl to download an image

For those who don't have nor want to install wget, curl -O (capital "o", not a zero) will do the same thing as wget. E.g. my old netbook doesn't have wget, and is a 2.68 MB install that I don't need.

curl -O https://www.python.org/static/apple-touch-icon-144x144-precomposed.png

Changing tab bar item image and text color iOS

Swift 4: In your UITabBarController change it by this code

tabBar.unselectedItemTintColor = .black

Adding header for HttpURLConnection

I have used the following code in the past and it had worked with basic authentication enabled in TomCat:

URL myURL = new URL(serviceURL);
HttpURLConnection myURLConnection = (HttpURLConnection)myURL.openConnection();

String userCredentials = "username:password";
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userCredentials.getBytes()));

myURLConnection.setRequestProperty ("Authorization", basicAuth);
myURLConnection.setRequestMethod("POST");
myURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
myURLConnection.setRequestProperty("Content-Length", "" + postData.getBytes().length);
myURLConnection.setRequestProperty("Content-Language", "en-US");
myURLConnection.setUseCaches(false);
myURLConnection.setDoInput(true);
myURLConnection.setDoOutput(true);

You can try the above code. The code above is for POST, and you can modify it for GET

SQL Server equivalent to MySQL enum data type?

Found this interesting approach when I wanted to implement enums in SQL Server.

The approach mentioned below in the link is quite compelling, considering all your database enum needs could be satisfied with 2 central tables.

http://blog.sqlauthority.com/2010/03/22/sql-server-enumerations-in-relational-database-best-practice/

Remote JMX connection

I've spend more than a day trying to make JMX to work from outside localhost. It seems that SUN/Oracle failed to provide a good documentation on this.

Be sure that the following command returns you a real IP or HOSTNAME. If it does return something like 127.0.0.1, 127.0.1.1 or localhost it will not work and you will have to update /etc/hosts file.

hostname -i

Here is the command needed to enable JMX even from outside

-Dcom.sun.management.jmxremote 
-Dcom.sun.management.jmxremote.authenticate=false 
-Dcom.sun.management.jmxremote.ssl=false 
-Dcom.sun.management.jmxremote.port=1100
-Djava.rmi.server.hostname=myserver.example.com

Where as you assumed, myserver.example.com must match what hostname -i returns.

Obviously, you need to be sure that the firewall does not block you, but I'm almost sure that this is not your problem, the problem being the last parameter that is not documented.

how to open popup window using jsp or jquery?

Try this:

SCRIPT:

function winOpen()
{
    window.open("yourpage.jsp");
}

HTML:

<a href="javascript:;" onclick="winOpen()">Pop Up</a>

Read https://developer.mozilla.org/en/docs/DOM/window.open for window.open

"pip install json" fails on Ubuntu

json is a built-in module, you don't need to install it with pip.

What is the Python 3 equivalent of "python -m SimpleHTTPServer"

As everyone has mentioned http.server module is equivalent to python -m SimpleHTTPServer.
But as a warning from https://docs.python.org/3/library/http.server.html#module-http.server

Warning: http.server is not recommended for production. It only implements basic security checks.

Usage

http.server can also be invoked directly using the -m switch of the interpreter.

python -m http.server

The above command will run a server by default on port number 8000. You can also give the port number explicitly while running the server

python -m http.server 9000

The above command will run an HTTP server on port 9000 instead of 8000.

By default, server binds itself to all interfaces. The option -b/--bind specifies a specific address to which it should bind. Both IPv4 and IPv6 addresses are supported. For example, the following command causes the server to bind to localhost only:

python -m http.server 8000 --bind 127.0.0.1

or

python -m http.server 8000 -b 127.0.0.1

Python 3.8 version also supports IPv6 in the bind argument.

Directory Binding

By default, server uses the current directory. The option -d/--directory specifies a directory to which it should serve the files. For example, the following command uses a specific directory:

python -m http.server --directory /tmp/

Directory binding is introduced in python 3.7

CSS way to horizontally align table

<style>
    .abc {
        text-align: center;
    }
</style>

<table class="abc">
    <tr>
        <td>Item1</td>
        <td>Item2</td>
    </tr>
</table>

org.hibernate.MappingException: Unknown entity: annotations.Users

Add the following code to hibernate.cfg.xml

  <property name="hibernate.c3p0.min_size">5</property>
  <property name="hibernate.c3p0.max_size">20</property>
  <property name="hibernate.c3p0.timeout">300</property>
  <property name="hibernate.c3p0.max_statements">50</property>
  <property name="hibernate.c3p0.idle_test_period">3000</property>

How to update each dependency in package.json to the latest version?

Updated for npm v2+

npm 2+ (Node 0.12+):


npm outdated
npm update
git commit package-lock.json

Ancient npm (circa 2014):

npm install -g npm-check-updates
npm-check-updates
npm shrinkwrap
git commit package-lock.json

Be sure to shrinkwrap your deps, or you may wind up with a dead project. I pulled out a project the other day and it wouldn't run because my deps were all out of date/updated/a mess. If I'd shrinkwrapped, npm would have installed exactly what I needed.


Details

For the curious who make it this far, here is what I recommend:

Use npm-check-updates or npm outdated to suggest the latest versions.

# `outdated` is part of newer npm versions (2+)
$ npm outdated
# If you agree, update.  
$ npm update

#       OR

# Install and use the `npm-check-updates` package.
$ npm install -g npm-check-updates
# Then check your project
$ npm-check-updates
# If you agree, update package.json.
$ npm-check-updates -u

###Then do a clean install (w/o the rm I got some dependency warnings)

$ rm -rf node_modules
$ npm install 

Lastly, save exact versions to npm-shrinkwrap.json with npm shrinkwrap

$ rm npm-shrinkwrap.json
$ npm shrinkwrap

Now, npm install will now use exact versions in npm-shrinkwrap.json

If you check npm-shrinkwrap.json into git, all installs will use the exact same versions.

This is a way to transition out of development (all updates, all the time) to production (nobody touch nothing).

p.s. Yarn is sending your package list to Facebook.

Sizing elements to percentage of screen width/height

There are several possibilities:

1- The first one is the use of the MediaQuery :

Code :

MediaQuery.of(context).size.width //to get the width of screen
MediaQuery.of(context).size.height //to get height of screen

Example of use :

Container(
        color: Colors.yellow,
        height: MediaQuery.of(context).size.height * 0.65,
        width: MediaQuery.of(context).size.width,
      )

Output :

enter image description here

2- The use of FractionallySizedBox

Creates a widget that sizes its child to a fraction of the total available space.

Example :

FractionallySizedBox(
           widthFactor: 0.65, // between 0 and 1 
           heightFactor: 1.0,
           child:Container(color: Colors.red
           ,),
         )

Output :

enter image description here

3- The use of other widgets such as Expanded , Flexible and AspectRatio and more .

Scala: what is the best way to append an element to an Array?

val array2 = array :+ 4
//Array(1, 2, 3, 4)

Works also "reversed":

val array2 = 4 +: array
Array(4, 1, 2, 3)

There is also an "in-place" version:

var array = Array( 1, 2, 3 )
array +:= 4
//Array(4, 1, 2, 3)
array :+= 0
//Array(4, 1, 2, 3, 0)

How do I start Mongo DB from Windows?

Step 1

Download the mongodb

Step 2

  • Follow normal setup instructions

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

Step 3

  • Create the following folder

C:\data\db

Step 4

  • cd to C:\Program Files\MongoDB\Server\3.2\bin>
  • enter command mongod
  • by default, mongodb server will start at port 27017

enter image description here

Step 5

  • (optionally) download RoboMongo and follow normal setup instructions

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

Step 6

  • Start RoboMongo and create a new connection on localhost:27017

enter image description here

Your MongoDB is started and connected with RoboMongo (now Robo 3T) - a third party GUI tool