Programs & Examples On #Nano

GNU nano is an open source, curses-based text editor for Unix systems. It is a clone of [tag:pico], the proprietary Pine e-mail client editor.

How to make the tab character 4 spaces instead of 8 spaces in nano?

Command-line flag

From man nano:

-T cols (--tabsize=cols)
    Set the size (width) of a tab to cols columns.
    The value of cols must be greater than 0. The default value is 8.
-E (--tabstospaces)
    Convert typed tabs to spaces.

For example, to set the tab size to 4, replace tabs with spaces, and edit the file "foo.txt", you would run the command:

nano -ET4 foo.txt

Config file

From man nanorc:

set tabsize n
    Use a tab size of n columns. The value of n must be greater than 0.
    The default value is 8.
set/unset tabstospaces
    Convert typed tabs to spaces.

Edit your ~/.nanorc file (create it if it does not exist), and add those commands to it. For example:

set tabsize 4
set tabstospaces

Nano will use these settings by default whenever it is launched, but command-line flags will override them.

nano error: Error opening terminal: xterm-256color

After upgrading to OSX Lion, I started getting this error on certain (Debian/Ubuntu) servers. The fix is simply to install the “ncurses-term” package which provides the file /usr/share/terminfo/x/xterm-256color.

This worked for me on a Ubuntu server, via Erik Osterman.

Copy text from nano editor to shell

1) Ctrl + 6 to mark the text that you want to copy

2) Ctrl + k to cut the text and Ctrl + u to paste back to the original place

3) Go to the desired line where you want to paste the code marked in step (2). Ctrl + u to paste it.

Hope it helps.

jump to line X in nano editor

In the nano editor

Ctrl+_

On openning a file

nano +10 file.txt

Setting an environment variable before a command in Bash is not working for the second command in a pipe

How about exporting the variable, but only inside the subshell?:

(export FOO=bar && somecommand someargs | somecommand2)

Keith has a point, to unconditionally execute the commands, do this:

(export FOO=bar; somecommand someargs | somecommand2)

check if a file is open in Python

if myfile.closed == False:
   print("File is still open ################")

open new tab(window) by clicking a link in jquery

Try this:

window.open(url, '_blank');

This will open in new tab (if your code is synchronous and in this case it is. in other case it would open a window)

Starting iPhone app development in Linux?

You will never get your app approved by Apple if it is not developed using Xcode. Never. And if you do hack the SDK to develop on Linux and Apple finds out, don't be surprised when you are served. I am a member of the ADC and the iPhone developer program. Trust, Apple is VERY serious about this.

Don't take the risk, Buy a Macbook or Mac mini (yes a mini can run Xcode - though slowly - boost the RAM if you go with the mini). Also, while I've seen OS X hacked to run on VMware I've never seen anyone running Xcode on VM. So good luck. And I'd check the EULA before you go through the trouble.

PS: After reading the above, yes I agree If you do hack the SDK and develop on Linux at least do the final packaging on a Mac. And submit it via a Mac. Apple doesn't run through the code line by line so i doubt they'd catch that. But man, that's a lot of if's and work. Be fun to do though. :)

How do I load a file from resource folder?

Import the following:

import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.util.ArrayList;

The following method returns a file in an ArrayList of Strings:

public ArrayList<String> loadFile(String filename){

  ArrayList<String> lines = new ArrayList<String>();

  try{

    ClassLoader classloader = Thread.currentThread().getContextClassLoader();
    InputStream inputStream = classloader.getResourceAsStream(filename);
    InputStreamReader streamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
    BufferedReader reader = new BufferedReader(streamReader);
    for (String line; (line = reader.readLine()) != null;) {
      lines.add(line);
    }

  }catch(FileNotFoundException fnfe){
    // process errors
  }catch(IOException ioe){
    // process errors
  }
  return lines;
}

How to use PHP's password_hash to hash and verify passwords

I’ve built a function I use all the time for password validation and to create passwords, e.g. to store them in a MySQL database. It uses a randomly generated salt which is way more secure than using a static salt.

function secure_password($user_pwd, $multi) {

/*
    secure_password ( string $user_pwd, boolean/string $multi ) 

    *** Description: 
        This function verifies a password against a (database-) stored password's hash or
        returns $hash for a given password if $multi is set to either true or false

    *** Examples:
        // To check a password against its hash
        if(secure_password($user_password, $row['user_password'])) {
            login_function();
        } 
        // To create a password-hash
        $my_password = 'uber_sEcUrE_pass';
        $hash = secure_password($my_password, true);
        echo $hash;
*/

// Set options for encryption and build unique random hash
$crypt_options = ['cost' => 11, 'salt' => mcrypt_create_iv(22, MCRYPT_DEV_URANDOM)];
$hash = password_hash($user_pwd, PASSWORD_BCRYPT, $crypt_options);

// If $multi is not boolean check password and return validation state true/false
if($multi!==true && $multi!==false) {
    if (password_verify($user_pwd, $table_pwd = $multi)) {
        return true; // valid password
    } else {
        return false; // invalid password
    }
// If $multi is boolean return $hash
} else return $hash;

}

bash: npm: command not found?

You need to install Node . Visiti this link

[1]: https://nodejs.org/en/ and follow the instructions.

How to update Ruby to 1.9.x on Mac?

Dan Benjamin's Hivelogic article Installing Ruby, RubyGems, and Rails on Snow Leopard is the recommended place to go although the article is for 1.8, so here's a Ruby 1.9-specific install on Snow Leopard. Watch out for the 64-bit thing... either go all 64-bit 'fat' (as is - for example - Apache on OS X, which can cause problems with 32-bit libraries) or check any gems you're likely to use to make sure they're okay for 64-bit.

What is an .axd file?

Those are not files (they don't exist on disk) - they are just names under which some HTTP handlers are registered. Take a look at the web.config in .NET Framework's directory (e.g. C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\web.config):

<configuration>
  <system.web>
    <httpHandlers>
      <add path="eurl.axd" verb="*" type="System.Web.HttpNotFoundHandler" validate="True" />
      <add path="trace.axd" verb="*" type="System.Web.Handlers.TraceHandler" validate="True" />
      <add path="WebResource.axd" verb="GET" type="System.Web.Handlers.AssemblyResourceLoader" validate="True" />
      <add verb="*" path="*_AppService.axd" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="False" />
      <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="False"/>
      <add path="*.axd" verb="*" type="System.Web.HttpNotFoundHandler" validate="True" />
    </httpHandlers>
  </system.web>
<configuration>

You can register your own handlers with a whatever.axd name in your application's web.config. While you can bind your handlers to whatever names you like, .axd has the upside of working on IIS6 out of the box by default (IIS6 passes requests for *.axd to the ASP.NET runtime by default). Using an arbitrary path for the handler, like Document.pdf (or really anything except ASP.NET-specific extensions), requires more configuration work. In IIS7 in integrated pipeline mode this is no longer a problem, as all requests are processed by the ASP.NET stack.

JUnit Testing Exceptions

Though @Test(expected = MyException.class) and the ExpectedException rule are very good choices, there are some instances where the JUnit3-style exception catching is still the best way to go:

@Test public void yourTest() {
  try {
    systemUnderTest.doStuff();
    fail("MyException expected.");
  } catch (MyException expected) {

    // Though the ExpectedException rule lets you write matchers about
    // exceptions, it is sometimes useful to inspect the object directly.

    assertEquals(1301, expected.getMyErrorCode());
  }

  // In both @Test(expected=...) and ExpectedException code, the
  // exception-throwing line will be the last executed line, because Java will
  // still traverse the call stack until it reaches a try block--which will be
  // inside the JUnit framework in those cases. The only way to prevent this
  // behavior is to use your own try block.

  // This is especially useful to test the state of the system after the
  // exception is caught.

  assertTrue(systemUnderTest.isInErrorState());
}

Another library that claims to help here is catch-exception; however, as of May 2014, the project appears to be in maintenance mode (obsoleted by Java 8), and much like Mockito catch-exception can only manipulate non-final methods.

How do I assign a null value to a variable in PowerShell?

If the goal simply is to list all computer objects with an empty description attribute try this

import-module activedirectory  
$domain = "domain.example.com" 
Get-ADComputer -Filter '*' -Properties Description | where { $_.Description -eq $null }

"make_sock: could not bind to address [::]:443" when restarting apache (installing trac and mod_wsgi)

You guys are going to laugh at this. I had an extra Listen 443 in ports.conf that shouldn't have been there. Removing that solved this.

Error: invalid operands of types ‘const char [35]’ and ‘const char [2]’ to binary ‘operator+’

Consider this:

std::string str = "Hello " + "world"; // bad!

Both the rhs and the lhs for operator + are char*s. There is no definition of operator + that takes two char*s (in fact, the language doesn't permit you to write one). As a result, on my compiler this produces a "cannot add two pointers" error (yours apparently phrases things in terms of arrays, but it's the same problem).

Now consider this:

std::string str = "Hello " + std::string("world"); // ok

There is a definition of operator + that takes a const char* as the lhs and a std::string as the rhs, so now everyone is happy.

You can extend this to as long a concatenation chain as you like. It can get messy, though. For example:

std::string str = "Hello " + "there " + std::string("world"); // no good!

This doesn't work because you are trying to + two char*s before the lhs has been converted to std::string. But this is fine:

std::string str = std::string("Hello ") + "there " + "world"; // ok

Because once you've converted to std::string, you can + as many additional char*s as you want.

If that's still confusing, it may help to add some brackets to highlight the associativity rules and then replace the variable names with their types:

((std::string("Hello ") + "there ") + "world");
((string + char*) + char*)

The first step is to call string operator+(string, char*), which is defined in the standard library. Replacing those two operands with their result gives:

((string) + char*)

Which is exactly what we just did, and which is still legal. But try the same thing with:

((char* + char*) + string)

And you're stuck, because the first operation tries to add two char*s.

Moral of the story: If you want to be sure a concatenation chain will work, just make sure one of the first two arguments is explicitly of type std::string.

Converting a double to an int in Javascript without rounding

I find the "parseInt" suggestions to be pretty curious, because "parseInt" operates on strings by design. That's why its name has the word "parse" in it.

A trick that avoids a function call entirely is

var truncated = ~~number;

The double application of the "~" unary operator will leave you with a truncated version of a double-precision value. However, the value is limited to 32 bit precision, as with all the other JavaScript operations that implicitly involve considering numbers to be integers (like array indexing and the bitwise operators).

edit — In an update quite a while later, another alternative to the ~~ trick is to bitwise-OR the value with zero:

var truncated = number|0;

JMS Topic vs Queues

That means a topic is appropriate. A queue means a message goes to one and only one possible subscriber. A topic goes to each and every subscriber.

How to evaluate a math expression given in string form?

It's too late to answer but I came across same situation to evaluate expression in java, it might help someone

MVEL does runtime evaluation of expressions, we can write a java code in String to get it evaluated in this.

    String expressionStr = "x+y";
    Map<String, Object> vars = new HashMap<String, Object>();
    vars.put("x", 10);
    vars.put("y", 20);
    ExecutableStatement statement = (ExecutableStatement) MVEL.compileExpression(expressionStr);
    Object result = MVEL.executeExpression(statement, vars);

PHP json_decode() returns NULL with valid JSON?

this help you to understand what is the type of error

<?php
// A valid json string
$json[] = '{"Organization": "PHP Documentation Team"}';

// An invalid json string which will cause an syntax 
// error, in this case we used ' instead of " for quotation
$json[] = "{'Organization': 'PHP Documentation Team'}";


foreach ($json as $string) {
    echo 'Decoding: ' . $string;
    json_decode($string);

    switch (json_last_error()) {
        case JSON_ERROR_NONE:
            echo ' - No errors';
        break;
        case JSON_ERROR_DEPTH:
            echo ' - Maximum stack depth exceeded';
        break;
        case JSON_ERROR_STATE_MISMATCH:
            echo ' - Underflow or the modes mismatch';
        break;
        case JSON_ERROR_CTRL_CHAR:
            echo ' - Unexpected control character found';
        break;
        case JSON_ERROR_SYNTAX:
            echo ' - Syntax error, malformed JSON';
        break;
        case JSON_ERROR_UTF8:
            echo ' - Malformed UTF-8 characters, possibly incorrectly encoded';
        break;
        default:
            echo ' - Unknown error';
        break;
    }

    echo PHP_EOL;
}
?>

Set a default parameter value for a JavaScript function

In ECMAScript 6 you will actually be able to write exactly what you have:

function read_file(file, delete_after = false) {
  // Code
}

This will set delete_after to false if it s not present or undefined. You can use ES6 features like this one today with transpilers such as Babel.

See the MDN article for more information.

Enabling error display in PHP via htaccess only

php_flag display_errors on

To turn the actual display of errors on.

To set the types of errors you are displaying, you will need to use:

php_value error_reporting <integer>

Combined with the integer values from this page: http://php.net/manual/en/errorfunc.constants.php

Note if you use -1 for your integer, it will show all errors, and be future proof when they add in new types of errors.

How to persist a property of type List<String> in JPA?

My fix for this issue was to separate the primary key with the foreign key. If you are using eclipse and made the above changes please remember to refresh the database explorer. Then recreate the entities from the tables.

How to programmatically get iOS status bar height

Go with Martin's suggestion to the question: Get iPhone Status Bar Height.

CGFloat AACStatusBarHeight()
{
    CGSize statusBarSize = [[UIApplication sharedApplication] statusBarFrame].size;
    return MIN(statusBarSize.width, statusBarSize.height);
}

And in Swift

func statusBarHeight() -> CGFloat {
    let statusBarSize = UIApplication.shared.statusBarFrame.size
    return Swift.min(statusBarSize.width, statusBarSize.height)
}

It seems like a hack, but it's actually pretty solid. Anyway, it's the only working solution.

Old Answer

The following code, which would go in your custom subclass of UIViewController, almost worked to support landscape. But, I noticed a corner case (when rotating from right > unsupported upside-down > left) for which it didn't work (switched height & width).

BOOL isPortrait = self.interfaceOrientation == UIInterfaceOrientationPortrait;
CGSize statusBarSize = [UIApplication sharedApplication].statusBarFrame.size;
CGFloat statusBarHeight = (isPortrait ? statusBarSize.height : statusBarSize.width);

Set SSH connection timeout

The problem may be that ssh is trying to connect to all the different IPs that www.google.com resolves to. For example on my machine:

# ssh -v -o ConnectTimeout=1 -o ConnectionAttempts=1 www.google.com
OpenSSH_5.9p1, OpenSSL 0.9.8t 18 Jan 2012
debug1: Connecting to www.google.com [173.194.43.20] port 22.
debug1: connect to address 173.194.43.20 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.19] port 22.
debug1: connect to address 173.194.43.19 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.18] port 22.
debug1: connect to address 173.194.43.18 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.17] port 22.
debug1: connect to address 173.194.43.17 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.16] port 22.
debug1: connect to address 173.194.43.16 port 22: Connection timed out
ssh: connect to host www.google.com port 22: Connection timed out

If I run it with a specific IP, it returns much faster.

EDIT: I've timed it (with time) and the results are:

  • www.google.com - 5.086 seconds
  • 173.94.43.16 - 1.054 seconds

How to join two JavaScript Objects, without using JQUERY

WORKING FIDDLE

Simplest Way with Jquery -

var finalObj = $.extend(obj1, obj2);

Without Jquery -

var finalobj={};
for(var _obj in obj1) finalobj[_obj ]=obj1[_obj];
for(var _obj in obj2) finalobj[_obj ]=obj2[_obj];

Can I load a .NET assembly at runtime and instantiate a type knowing only the name?

((ISomeInterface)Activator.CreateInstance(Assembly.LoadFile("somePath").GetTypes()[0])).SomeInterfaceMethod();

On - window.location.hash - Change?

HTML5 specifies a hashchange event. This event is now supported by all modern browsers. Support was added in the following browser versions:

  • Internet Explorer 8
  • Firefox 3.6
  • Chrome 5
  • Safari 5
  • Opera 10.6

Getting Python error "from: can't read /var/mail/Bio"

Put this at the top of your .py file (for python 2.x)

#!/usr/bin/env python 

or for python 3.x

#!/usr/bin/env python3

This should look up the python environment, without it, it will execute the code as if it were not python code, but straight to the CLI. If you need to specify a manual location of python environment put

#!/#path/#to/#python

How can I alter a primary key constraint using SQL syntax?

Performance wise there is no point to keep non clustered indexes during this as they will get re-updated on drop and create. If it is a big data set you should consider renaming the table (if possible , any security settings on it?), re-creating an empty table with the correct keys migrate all data there. You have to make sure you have enough space for this.

How to automatically convert strongly typed enum into int?

Short answer is you can't as above posts point out. But for my case, I simply didn't want to clutter the namespace but still have implicit conversions, so I just did:

#include <iostream>

using namespace std;

namespace Foo {
   enum Foo { bar, baz };
}

int main() {
   cout << Foo::bar << endl; // 0
   cout << Foo::baz << endl; // 1
   return 0;
}

The namespacing sort of adds a layer of type-safety while I don't have to static cast any enum values to the underlying type.

iReport not starting using JRE 8

It works only with JRE 1.7 just download it and extract to your prefered location

and use the following command to open the iReport

ireport --jdkhome Path To JDK Home

How to remove unused dependencies from composer?

Just run composer install - it will make your vendor directory reflect dependencies in composer.lock file.

In other words - it will delete any vendor which is missing in composer.lock.

Please update the composer itself before running this.

Writelines writes lines without newline, Just fills the file

As others have noted, writelines is a misnomer (it ridiculously does not add newlines to the end of each line).

To do that, explicitly add it to each line:

with open(dst_filename, 'w') as f:
    f.writelines(s + '\n' for s in lines)

Can you get the column names from a SqlDataReader?

It is easier to achieve it in SQL

var columnsList = dbContext.Database.SqlQuery<string>("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'SCHEMA_OF_YOUE_TABLE' AND TABLE_NAME = 'YOUR_TABLE_NAME'").ToList();

HEAD and ORIG_HEAD in Git

HEAD is (direct or indirect, i.e. symbolic) reference to the current commit. It is a commit that you have checked in the working directory (unless you made some changes, or equivalent), and it is a commit on top of which "git commit" would make a new one. Usually HEAD is symbolic reference to some other named branch; this branch is currently checked out branch, or current branch. HEAD can also point directly to a commit; this state is called "detached HEAD", and can be understood as being on unnamed, anonymous branch.

And @ alone is a shortcut for HEAD, since Git 1.8.5

ORIG_HEAD is previous state of HEAD, set by commands that have possibly dangerous behavior, to be easy to revert them. It is less useful now that Git has reflog: HEAD@{1} is roughly equivalent to ORIG_HEAD (HEAD@{1} is always last value of HEAD, ORIG_HEAD is last value of HEAD before dangerous operation).

For more information read git(1) manpage / [gitrevisions(7) manpage][git-revisions], Git User's Manual, the Git Community Book and Git Glossary

Duplicate and rename Xcode project & associated folders

One more thing to try!

When I copied all of my files, opened the project, and renamed it, everything changed to my new project name except for the test target! I got a linker error that said I was missing a file called "myOldProjectname.app". Here's what fixed it:

  1. Click on your project settings and select your test target enter image description here

  2. Click on build settings and search for "test host" enter image description here

  3. Check those 2 file paths. Chances are that those 2 paths are still pointing at your old project name. enter image description here

Hope that helps!

How to export html table to excel using javascript

Check https://github.com/linways/table-to-excel. Its a wrapper for exceljs/exceljs to export html tables to xlsx.

_x000D_
_x000D_
TableToExcel.convert(document.getElementById("simpleTable1"));
_x000D_
<script src="https://cdn.jsdelivr.net/gh/linways/[email protected]/dist/tableToExcel.js"></script>_x000D_
<table id="simpleTable1" data-cols-width="70,15,10">_x000D_
<tbody>_x000D_
    <tr>_x000D_
        <td class="header" colspan="5" data-f-sz="25" data-f-color="FFFFAA00" data-a-h="center" data-a-v="middle" data-f-underline="true">_x000D_
            Sample Excel_x000D_
        </td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td colspan="5" data-f-italic="true" data-a-h="center" data-f-name="Arial" data-a-v="top">_x000D_
            Italic and horizontal center in Arial_x000D_
        </td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <th data-a-text-rotation="90">Col 1 (number)</th>_x000D_
        <th data-a-text-rotation="vertical">Col 2</th>_x000D_
        <th data-a-wrap="true">Wrapped Text</th>_x000D_
        <th data-a-text-rotation="-45">Col 4 (date)</th>_x000D_
        <th data-a-text-rotation="-90">Col 5</th>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td rowspan="1" data-t="n">1</td>_x000D_
        <td rowspan="1" data-b-b-s="thick" data-b-l-s="thick" data-b-r-s="thick">_x000D_
            ABC1_x000D_
        </td>_x000D_
        <td rowspan="1" data-f-strike="true">Striked Text</td>_x000D_
        <td data-t="d">05-20-2018</td>_x000D_
        <td data-t="n" data-num-fmt="$ 0.00">2210.00</td>_x000D_
    </tr>_x000D_
_x000D_
    <tr>_x000D_
        <td rowspan="2" data-t="n">2</td>_x000D_
        <td rowspan="2" data-fill-color="FFFF0000" data-f-color="FFFFFFFF">_x000D_
            ABC 2_x000D_
        </td>_x000D_
        <td rowspan="2" data-a-indent="3">Merged cell</td>_x000D_
        <td data-t="d">05-21-2018</td>_x000D_
        <td data-t="n" data-b-a-s="dashed" data-num-fmt="$ 0.00">230.00</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td data-t="d">05-22-2018</td>_x000D_
_x000D_
        <td data-t="n" data-num-fmt="$ 0.00">2493.00</td>_x000D_
    </tr>_x000D_
_x000D_
    <tr>_x000D_
        <td colspan="4" align="right" data-f-bold="true" data-a-h="right" data-hyperlink="https://google.com">_x000D_
            <b><a href="https://google.com">Hyperlink</a></b>_x000D_
        </td>_x000D_
        <td colspan="1" align="right" data-t="n" data-f-bold="true" data-num-fmt="$ 0.00">_x000D_
            <b>4933.00</b>_x000D_
        </td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td colspan="4" align="right" data-f-bold="true" data-a-rtl="true">_x000D_
            ?????_x000D_
        </td>_x000D_
        <td colspan="1" align="right" data-t="n" data-f-bold="true" data-num-fmt="$ 0.00">_x000D_
            <b>2009.00</b>_x000D_
        </td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td data-b-a-s="dashed" data-b-a-c="FFFF0000">All borders</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td data-t="b">true</td>_x000D_
        <td data-t="b">false</td>_x000D_
        <td data-t="b">1</td>_x000D_
        <td data-t="b">0</td>_x000D_
        <td data-error="#VALUE!">Value Error</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td data-b-t-s="thick" data-b-l-s="thick" data-b-b-s="thick" data-b-r-s="thick" data-b-t-c="FF00FF00" data-b-l-c="FF00FF00" data-b-b-c="FF00FF00" data-b-r-c="FF00FF00">_x000D_
            All borders separately_x000D_
        </td>_x000D_
    </tr>_x000D_
    <tr data-exclude="true">_x000D_
        <td>Excluded row</td>_x000D_
        <td>Something</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>Included Cell</td>_x000D_
        <td data-exclude="true">Excluded Cell</td>_x000D_
        <td>Included Cell</td>_x000D_
    </tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

This creates valid xlsx on the client side. Also supports some basic styling. Check https://codepen.io/rohithb/pen/YdjVbb for a working example.

percentage of two int?

If you don't add .0f it will be treated like it is an integer, and an integer division is a lot different from a floating point division indeed :)

float percent = (n * 100.0f) / v;

If you need an integer out of this you can of course cast the float or the double again in integer.

int percent = (int)((n * 100.0f) / v);

If you know your n value is less than 21474836 (that is (2 ^ 31 / 100)), you can do all using integer operations.

int percent = (n * 100) / v;

If you get NaN is because wathever you do you cannot divide for zero of course... it doesn't make sense.

How to call code behind server method from a client side JavaScript function?

Try creating a new service and calling it. The processing can be done there, and returned back.

http://code.msdn.microsoft.com/windowsazure/WCF-Azure-AJAX-Calculator-4cf3099e

function makeCall(operation){
    var n1 = document.getElementById("num1").value;
    var n2 = document.getElementById("num2").value;
if(n1 && n2){

        // Instantiate a service proxy
        var proxy = new Service();

        // Call correct operation on vf cproxy       
        switch(operation){

            case "gridOne":
                proxy.Calculate(AjaxService.Operation.getWeather, n1, n2,
 onSuccess, onFail, null);

****HTML CODE****
<p>Major City: <input type="text" id="num1" onclick="return num1_onclick()"
/></p>
<p>Country: <input type="text" id="num2" onclick="return num2_onclick()"
/></p> 
<input id="btnDivide" type="button" onclick="return makeCall('gridOne');" 

Greater than less than, python

Check to make sure that both score and array[x] are numerical types. You might be comparing an integer to a string...which is heartbreakingly possible in Python 2.x.

>>> 2 < "2"
True
>>> 2 > "2"
False
>>> 2 == "2"
False

Edit

Further explanation: How does Python compare string and int?

D3.js: How to get the computed width and height for an arbitrary element?

.getBoundingClientRect() returns the size of an element and its position relative to the viewport.We can easily get following

  • left, right
  • top, bottom
  • height, width

Example :

var element = d3.select('.elementClassName').node();
element.getBoundingClientRect().width;

Does JavaScript have a method like "range()" to generate a range within the supplied bounds?

An interesting challenge would be to write the shortest function to do this. Recursion to the rescue!

function r(a,b){return a>b?[]:[a].concat(r(++a,b))}

Tends to be slow on large ranges, but luckily quantum computers are just around the corner.

An added bonus is that it's obfuscatory. Because we all know how important it is to hide our code from prying eyes.

To truly and utterly obfuscate the function, do this:

function r(a,b){return (a<b?[a,b].concat(r(++a,--b)):a>b?[]:[a]).sort(function(a,b){return a-b})}

How to run .APK file on emulator

Steps (These apply for Linux. For other OS, visit here) -

  1. Copy the apk file to platform-tools in android-sdk linux folder.
  2. Open Terminal and navigate to platform-tools folder in android-sdk.
  3. Then Execute this command -

    ./adb install FileName.apk

  4. If the operation is successful (the result is displayed on the screen), then you will find your file in the launcher of your emulator.

For more info can check this link : android videos

Is there a way to add/remove several classes in one single instruction with classList?

Another polyfill for element.classList is here. I found it via MDN.

I include that script and use element.classList.add("first","second","third") as it's intended.

Multiple WHERE Clauses with LINQ extension methods

you can use && and write all conditions in to the same where clause, or you can .Where().Where().Where()... and so on.

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

The Global.asax can be used to handle events arising from the application. This link provides a good explanation: http://aspalliance.com/1114

regex match any single character (one character only)

Match any single character

  • Use the dot . character as a wildcard to match any single character.

Example regex: a.c

abc   // match
a c   // match
azc   // match
ac    // no match
abbc  // no match

Match any specific character in a set

  • Use square brackets [] to match any characters in a set.
  • Use \w to match any single alphanumeric character: 0-9, a-z, A-Z, and _ (underscore).
  • Use \d to match any single digit.
  • Use \s to match any single whitespace character.

Example 1 regex: a[bcd]c

abc   // match
acc   // match
adc   // match
ac    // no match
abbc  // no match

Example 2 regex: a[0-7]c

a0c   // match
a3c   // match
a7c   // match
a8c   // no match
ac    // no match
a55c  // no match

Match any character except ...

Use the hat in square brackets [^] to match any single character except for any of the characters that come after the hat ^.

Example regex: a[^abc]c

aac   // no match
abc   // no match
acc   // no match
a c   // match
azc   // match
ac    // no match
azzc  // no match

(Don't confuse the ^ here in [^] with its other usage as the start of line character: ^ = line start, $ = line end.)

Match any character optionally

Use the optional character ? after any character to specify zero or one occurrence of that character. Thus, you would use .? to match any single character optionally.

Example regex: a.?c

abc   // match
a c   // match
azc   // match
ac    // match
abbc  // no match

See also

Git "error: The branch 'x' is not fully merged"

I did not have the upstream branch on my local git. I had created a local branch from master, git checkout -b mybranch . I created a branch with bitbucket GUI on the upstream git and pushed my local branch (mybranch) to that upstream branch. Once I did a git fetch on my local git to retrieve the upstream branch, I could do a git branch -d mybranch.

What is the shortcut in IntelliJ IDEA to find method / functions?

Android Studio on Mac

Command + Option + O

Opens up the Symbol lookup that you can jump to most of the methods/functions in your currently opened document.

Getting key with maximum value in dictionary?

Much simpler to understand approach:

dict = { 'a':302, 'e':53, 'g':302, 'h':100 }
max_value_keys = [key for key in dict.keys() if dict[key] == max(dict.values())]
print(max_value_keys) # prints a list of keys with max value

Output: ['a', 'g']

Now you can choose only one key:

maximum = dict[max_value_keys[0]]

Using comma as list separator with AngularJS

Also:

angular.module('App.filters', [])
    .filter('joinBy', function () {
        return function (input,delimiter) {
            return (input || []).join(delimiter || ',');
        };
    });

And in template:

{{ itemsArray | joinBy:',' }}

Detecting negative numbers

if ($profitloss < 0)
{
   echo "The profitloss is negative";
}

Edit: I feel like this was too simple an answer for the rep so here's something that you may also find helpful.

In PHP we can find the absolute value of an integer by using the abs() function. For example if I were trying to work out the difference between two figures I could do this:

$turnover = 10000;
$overheads = 12500;

$difference = abs($turnover-$overheads);

echo "The Difference is ".$difference;

This would produce The Difference is 2500.

Is there a link to the "latest" jQuery library on Google APIs?

No. There isn't..

But, for development there is such a link on the jQuery code site.

Formatting Decimal places in R

Note that numeric objects in R are stored with double precision, which gives you (roughly) 16 decimal digits of precision - the rest will be noise. I grant that the number shown above is probably just for an example, but it is 22 digits long.

Restrict varchar() column to specific values?

When you are editing a table
Right Click -> Check Constraints -> Add -> Type something like Frequency IN ('Daily', 'Weekly', 'Monthly', 'Yearly') in expression field and a good constraint name in (Name) field.
You are done.

How do I duplicate a line or selection within Visual Studio Code?

Note that for Ubuntu users (<= 17.4), Unity uses CTRL + ALT + SHIFT + Arrow Key for moving programs across virtual workspaces, which conflicts with the VS Code shortcuts. You'll need to rebind editor.action.copyLinesDownAction and editor.action.copyLinesUpAction to avoid the conflict (or change your workspace keybindings).

For Ubuntu 17.10+ that uses GNOME, it seems that GNOME does not use this keybinding in the same way according to its documentation, though if someone using vanilla workspaces on 17.10 can confirm this, it might be helpful for future answer seekers.

What are the best JVM settings for Eclipse?

You can also try running with JRockit. It's a JVM optimized for servers, but many long running client applications, like IDE's, run very well on JRockit. Eclipse is no exception. JRockit doesn't have a perm-space so you don't need to configure it.

It's possible set a pause time target(ms) to avoid long gc pauses stalling the UI.

-showsplash
org.eclipse.platform
-vm
 C:\jrmc-3.1.2-1.6.0\bin\javaw.exe 
-vmargs
-XgcPrio:deterministic
-XpauseTarget:20

I usually don't bother setting -Xmx and -Xms and let JRockit grow the heap as it sees necessary. If you launch your Eclipse application with JRockit you can also monitor, profile and find memory leaks in your application using the JRockit Mission Control tools suite. You download the plugins from this update site. Note, only works for Eclipse 3.3 and Eclipse 3.4

Why avoid increment ("++") and decrement ("--") operators in JavaScript?

The most important rationale for avoiding ++ or -- is that the operators return values and cause side effects at the same time, making it harder to reason about the code.

For efficiency's sake, I prefer:

  • ++i when not using the return value (no temporary)
  • i++ when using the return value (no pipeline stall)

I am a fan of Mr. Crockford, but in this case I have to disagree. ++i is 25% less text to parse than i+=1 and arguably clearer.

Pandas: Looking up the list of sheets in an excel file

This is the fastest way I have found, inspired by @divingTobi's answer. All The answers based on xlrd, openpyxl or pandas are slow for me, as they all load the whole file first.

from zipfile import ZipFile
from bs4 import BeautifulSoup  # you also need to install "lxml" for the XML parser

with ZipFile(file) as zipped_file:
    summary = zipped_file.open(r'xl/workbook.xml').read()
soup = BeautifulSoup(summary, "xml")
sheets = [sheet.get("name") for sheet in soup.find_all("sheet")]

Calculate last day of month in JavaScript

I would use an intermediate date with the first day of the next month, and return the date from the previous day:

int_d = new Date(2008, 11+1,1);
d = new Date(int_d - 1);

Change GitHub Account username

Yes, this is an old question. But it's misleading, as this was the first result in my search, and both the answers aren't correct anymore.

You can change your Github account name at any time.

To do this, click your profile picture > Settings > Account Settings > Change Username.

Links to your repositories will redirect to the new URLs, but they should be updated on other sites because someone who chooses your abandoned username can override the links. Links to your profile page will be 404'd.

For more information, see the official help page.

And furthermore, if you want to change your username to something else, but that specific username is being taken up by someone else who has been completely inactive for the entire time their account has existed, you can report their account for name squatting.

Making text bold using attributed string in swift

Super easy way to do this.

    let text = "This string is having multiple font"
    let attributedText = 
    NSMutableAttributedString.getAttributedString(fromString: text)

    attributedText.apply(font: UIFont.boldSystemFont(ofSize: 24), subString: 
    "This")

    attributedText.apply(font: UIFont.boldSystemFont(ofSize: 24), onRange: 
    NSMakeRange(5, 6))

For more detail click here: https://github.com/iOSTechHub/AttributedString

How to solve error message: "Failed to map the path '/'."

I experienced this after updating to Windows 10 Fall Creators edition version 1709. None of the solutions above worked for me. I was able to fix the error this way:

  1. Go to “Control Panel” > “Administrative Tools” > “IIS Manager”.
  2. Choose “Change .NET Framework Version” from the “Actions” in the right margin.
  3. I chose the latest version shown and clicked “OK”.

If IIS Manager is not available under Administrative Tools, you can enable it this way:

  1. Press the Windows key and type "Turn Windows Features On or Off" then select the search result.
  2. In dialog that appears, check the box by “Internet Information Services” and click OK.

How to submit a form using Enter key in react.js?

It's been quite a few years since this question was last answered. React introduced "Hooks" back in 2017, and "keyCode" has been deprecated.

Now we can write this:

  useEffect(() => {
    const listener = event => {
      if (event.code === "Enter" || event.code === "NumpadEnter") {
        console.log("Enter key was pressed. Run your function.");
        // callMyFunction();
      }
    };
    document.addEventListener("keydown", listener);
    return () => {
      document.removeEventListener("keydown", listener);
    };
  }, []);

This registers a listener on the keydown event, when the component is loaded for the first time. It removes the event listener when the component is destroyed.

How to check if a file is a valid image file?

format = [".jpg",".png",".jpeg"]
 for (path,dirs,files) in os.walk(path):
     for file in files:
         if file.endswith(tuple(format)):
             print(path)
             print ("Valid",file)
         else:
             print(path)
             print("InValid",file)

In Python, what is the difference between ".append()" and "+= []"?

let's take an example first

list1=[1,2,3,4]
list2=list1     (that means they points to same object)

if we do 
list1=list1+[5]    it will create a new object of list
print(list1)       output [1,2,3,4,5] 
print(list2)       output [1,2,3,4]

but if we append  then 
list1.append(5)     no new object of list created
print(list1)       output [1,2,3,4,5] 
print(list2)       output [1,2,3,4,5]

extend(list) also do the same work as append it just append a list instead of a 
single variable 

Query to list all users of a certain group

If the DC is Win2k3 SP2 or above, you can use something like:

(&(objectCategory=user)(memberOf:1.2.840.113556.1.4.1941:=CN=GroupOne,OU=Security Groups,OU=Groups,DC=example,DC=com))

to get the nested group membership.

Source: https://ldapwiki.com/wiki/Active%20Directory%20Group%20Related%20Searches

Get HTML inside iframe using jQuery

Try this code:

$('#iframe').contents().find("html").html();

This will return all the html in your iframe. Instead of .find("html") you can use any selector you want eg: .find('body'),.find('div#mydiv').

Can an AWS Lambda function call another

I was looking at cutting out SNS until I saw this in the Lambda client docs (Java version):

Client for accessing AWS Lambda. All service calls made using this client are blocking, and will not return until the service call completes.

So SNS has an obvious advantage: it's asynchronous. Your lambda won't wait for the subsequent lambda to complete.

MVC Razor view nested foreach's model

The quick answer is to use a for() loop in place of your foreach() loops. Something like:

@for(var themeIndex = 0; themeIndex < Model.Theme.Count(); themeIndex++)
{
   @Html.LabelFor(model => model.Theme[themeIndex])

   @for(var productIndex=0; productIndex < Model.Theme[themeIndex].Products.Count(); productIndex++)
   {
      @Html.LabelFor(model=>model.Theme[themeIndex].Products[productIndex].name)
      @for(var orderIndex=0; orderIndex < Model.Theme[themeIndex].Products[productIndex].Orders; orderIndex++)
      {
          @Html.TextBoxFor(model => model.Theme[themeIndex].Products[productIndex].Orders[orderIndex].Quantity)
          @Html.TextAreaFor(model => model.Theme[themeIndex].Products[productIndex].Orders[orderIndex].Note)
          @Html.EditorFor(model => model.Theme[themeIndex].Products[productIndex].Orders[orderIndex].DateRequestedDeliveryFor)
      }
   }
}

But this glosses over why this fixes the problem.

There are three things that you have at least a cursory understanding before you can resolve this issue. I have to admit that I cargo-culted this for a long time when I started working with the framework. And it took me quite a while to really get what was going on.

Those three things are:

  • How do the LabelFor and other ...For helpers work in MVC?
  • What is an Expression Tree?
  • How does the Model Binder work?

All three of these concepts link together to get an answer.

How do the LabelFor and other ...For helpers work in MVC?

So, you've used the HtmlHelper<T> extensions for LabelFor and TextBoxFor and others, and you probably noticed that when you invoke them, you pass them a lambda and it magically generates some html. But how?

So the first thing to notice is the signature for these helpers. Lets look at the simplest overload for TextBoxFor

public static MvcHtmlString TextBoxFor<TModel, TProperty>(
    this HtmlHelper<TModel> htmlHelper,
    Expression<Func<TModel, TProperty>> expression
) 

First, this is an extension method for a strongly typed HtmlHelper, of type <TModel>. So, to simply state what happens behind the scenes, when razor renders this view it generates a class. Inside of this class is an instance of HtmlHelper<TModel> (as the property Html, which is why you can use @Html...), where TModel is the type defined in your @model statement. So in your case, when you are looking at this view TModel will always be of the type ViewModels.MyViewModels.Theme.

Now, the next argument is a bit tricky. So lets look at an invocation

@Html.TextBoxFor(model=>model.SomeProperty);

It looks like we have a little lambda, And if one were to guess the signature, one might think that the type for this argument would simply be a Func<TModel, TProperty>, where TModel is the type of the view model and TProperty is inferred as the type of the property.

But thats not quite right, if you look at the actual type of the argument its Expression<Func<TModel, TProperty>>.

So when you normally generate a lambda, the compiler takes the lambda and compiles it down into MSIL, just like any other function (which is why you can use delegates, method groups, and lambdas more or less interchangeably, because they are just code references.)

However, when the compiler sees that the type is an Expression<>, it doesn't immediately compile the lambda down to MSIL, instead it generates an Expression Tree!

What is an Expression Tree?

So, what the heck is an expression tree. Well, it's not complicated but its not a walk in the park either. To quote ms:

| Expression trees represent code in a tree-like data structure, where each node is an expression, for example, a method call or a binary operation such as x < y.

Simply put, an expression tree is a representation of a function as a collection of "actions".

In the case of model=>model.SomeProperty, the expression tree would have a node in it that says: "Get 'Some Property' from a 'model'"

This expression tree can be compiled into a function that can be invoked, but as long as it's an expression tree, it's just a collection of nodes.

So what is that good for?

So Func<> or Action<>, once you have them, they are pretty much atomic. All you can really do is Invoke() them, aka tell them to do the work they are supposed to do.

Expression<Func<>> on the other hand, represents a collection of actions, which can be appended, manipulated, visited, or compiled and invoked.

So why are you telling me all this?

So with that understanding of what an Expression<> is, we can go back to Html.TextBoxFor. When it renders a textbox, it needs to generate a few things about the property that you are giving it. Things like attributes on the property for validation, and specifically in this case it needs to figure out what to name the <input> tag.

It does this by "walking" the expression tree and building a name. So for an expression like model=>model.SomeProperty, it walks the expression gathering the properties that you are asking for and builds <input name='SomeProperty'>.

For a more complicated example, like model=>model.Foo.Bar.Baz.FooBar, it might generate <input name="Foo.Bar.Baz.FooBar" value="[whatever FooBar is]" />

Make sense? It is not just the work that the Func<> does, but how it does its work is important here.

(Note other frameworks like LINQ to SQL do similar things by walking an expression tree and building a different grammar, that this case a SQL query)

How does the Model Binder work?

So once you get that, we have to briefly talk about the model binder. When the form gets posted, it's simply like a flat Dictionary<string, string>, we have lost the hierarchical structure our nested view model may have had. It's the model binder's job to take this key-value pair combo and attempt to rehydrate an object with some properties. How does it do this? You guessed it, by using the "key" or name of the input that got posted.

So if the form post looks like

Foo.Bar.Baz.FooBar = Hello

And you are posting to a model called SomeViewModel, then it does the reverse of what the helper did in the first place. It looks for a property called "Foo". Then it looks for a property called "Bar" off of "Foo", then it looks for "Baz"... and so on...

Finally it tries to parse the value into the type of "FooBar" and assign it to "FooBar".

PHEW!!!

And voila, you have your model. The instance the Model Binder just constructed gets handed into requested Action.


So your solution doesn't work because the Html.[Type]For() helpers need an expression. And you are just giving them a value. It has no idea what the context is for that value, and it doesn't know what to do with it.

Now some people suggested using partials to render. Now this in theory will work, but probably not the way that you expect. When you render a partial, you are changing the type of TModel, because you are in a different view context. This means that you can describe your property with a shorter expression. It also means when the helper generates the name for your expression, it will be shallow. It will only generate based on the expression it's given (not the entire context).

So lets say you had a partial that just rendered "Baz" (from our example before). Inside that partial you could just say:

@Html.TextBoxFor(model=>model.FooBar)

Rather than

@Html.TextBoxFor(model=>model.Foo.Bar.Baz.FooBar)

That means that it will generate an input tag like this:

<input name="FooBar" />

Which, if you are posting this form to an action that is expecting a large deeply nested ViewModel, then it will try to hydrate a property called FooBar off of TModel. Which at best isn't there, and at worst is something else entirely. If you were posting to a specific action that was accepting a Baz, rather than the root model, then this would work great! In fact, partials are a good way to change your view context, for example if you had a page with multiple forms that all post to different actions, then rendering a partial for each one would be a great idea.


Now once you get all of this, you can start to do really interesting things with Expression<>, by programatically extending them and doing other neat things with them. I won't get into any of that. But, hopefully, this will give you a better understanding of what is going on behind the scenes and why things are acting the way that they are.

jquery smooth scroll to an anchor?

Using hanoo's script I created a jQuery function:

$.fn.scrollIntoView = function(duration, easing) {
    var dest = 0;
    if (this.offset().top > $(document).height() - $(window).height()) {
        dest = $(document).height() - $(window).height();
    } else {
        dest = this.offset().top;
    }
    $('html,body').animate({
        scrollTop: dest
    }, duration, easing);
    return this;
};

usage:

$('#myelement').scrollIntoView();

Defaults for duration and easing are 400ms and "swing".

SQL Server: Database stuck in "Restoring" state

In my case, it was sufficient to drop the database which was hanging in state "Restoring..." with the SQL command

 drop database <dbname> 

in a query window.

Then I right-clicked on Databases and selected Refresh which removed the entry in Management Studio. Afterwards I did a new restore which worked fine (note that bringing it offline did not work, a restart of the SQL service did not work, a server reboot did not work as well).

Reverting single file in SVN to a particular revision

So far all answers here seem to have significant downsides, are complicated (need to find the repo URI) or they don't do what the question probably asked for: How to get the Repo in a working state again with that older version of the file.

svn merge -r head:[revision-number-to-revert-to] [file-path] is IMO the cleanest and simplest way to do this. Please note that bringing back a deleted file does not seem to work this way[1]. See also the following question: Better way to revert to a previous SVN revision of a file?

[1] For that you want svn cp -r [rev-number] [repo-URI/file-path]@[rev-number] [repo-URI/file-path] && svn up, see also What is the correct way to restore a deleted file from SVN?

"Keep Me Logged In" - the best approach

Introduction

Your title “Keep Me Logged In” - the best approach make it difficult for me to know where to start because if you are looking at best approach then you would have to consideration the following :

  • Identification
  • Security

Cookies

Cookies are vulnerable, Between common browser cookie-theft vulnerabilities and cross-site scripting attacks we must accept that cookies are not safe. To help improve security you must note that php setcookies has additional functionality such as

bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )

  • secure (Using HTTPS connection)
  • httponly (Reduce identity theft through XSS attack)

Definitions

  • Token ( Unpredictable random string of n length eg. /dev/urandom)
  • Reference ( Unpredictable random string of n length eg. /dev/urandom)
  • Signature (Generate a keyed hash value using the HMAC method)

Simple Approach

A simple solution would be :

  • User is logged on with Remember Me
  • Login Cookie issued with token & Signature
  • When is returning, Signature is checked
  • If Signature is ok .. then username & token is looked up in the database
  • if not valid .. return to login page
  • If valid automatically login

The above case study summarizes all example given on this page but they disadvantages is that

  • There is no way to know if the cookies was stolen
  • Attacker may be access sensitive operations such as change of password or data such as personal and baking information etc.
  • The compromised cookie would still be valid for the cookie life span

Better Solution

A better solution would be

  • User is logged in and remember me is selected
  • Generate Token & signature and store in cookie
  • The tokens are random and are only valid for single autentication
  • The token are replace on each visit to the site
  • When a non-logged user visit the site the signature, token and username are verified
  • Remember me login should have limited access and not allow modification of password, personal information etc.

Example Code

// Set privateKey
// This should be saved securely 
$key = 'fc4d57ed55a78de1a7b31e711866ef5a2848442349f52cd470008f6d30d47282';
$key = pack("H*", $key); // They key is used in binary form

// Am Using Memecahe as Sample Database
$db = new Memcache();
$db->addserver("127.0.0.1");

try {
    // Start Remember Me
    $rememberMe = new RememberMe($key);
    $rememberMe->setDB($db); // set example database

    // Check if remember me is present
    if ($data = $rememberMe->auth()) {
        printf("Returning User %s\n", $data['user']);

        // Limit Acces Level
        // Disable Change of password and private information etc

    } else {
        // Sample user
        $user = "baba";

        // Do normal login
        $rememberMe->remember($user);
        printf("New Account %s\n", $user);
    }
} catch (Exception $e) {
    printf("#Error  %s\n", $e->getMessage());
}

Class Used

class RememberMe {
    private $key = null;
    private $db;

    function __construct($privatekey) {
        $this->key = $privatekey;
    }

    public function setDB($db) {
        $this->db = $db;
    }

    public function auth() {

        // Check if remeber me cookie is present
        if (! isset($_COOKIE["auto"]) || empty($_COOKIE["auto"])) {
            return false;
        }

        // Decode cookie value
        if (! $cookie = @json_decode($_COOKIE["auto"], true)) {
            return false;
        }

        // Check all parameters
        if (! (isset($cookie['user']) || isset($cookie['token']) || isset($cookie['signature']))) {
            return false;
        }

        $var = $cookie['user'] . $cookie['token'];

        // Check Signature
        if (! $this->verify($var, $cookie['signature'])) {
            throw new Exception("Cokies has been tampared with");
        }

        // Check Database
        $info = $this->db->get($cookie['user']);
        if (! $info) {
            return false; // User must have deleted accout
        }

        // Check User Data
        if (! $info = json_decode($info, true)) {
            throw new Exception("User Data corrupted");
        }

        // Verify Token
        if ($info['token'] !== $cookie['token']) {
            throw new Exception("System Hijacked or User use another browser");
        }

        /**
         * Important
         * To make sure the cookie is always change
         * reset the Token information
         */

        $this->remember($info['user']);
        return $info;
    }

    public function remember($user) {
        $cookie = [
                "user" => $user,
                "token" => $this->getRand(64),
                "signature" => null
        ];
        $cookie['signature'] = $this->hash($cookie['user'] . $cookie['token']);
        $encoded = json_encode($cookie);

        // Add User to database
        $this->db->set($user, $encoded);

        /**
         * Set Cookies
         * In production enviroment Use
         * setcookie("auto", $encoded, time() + $expiration, "/~root/",
         * "example.com", 1, 1);
         */
        setcookie("auto", $encoded); // Sample
    }

    public function verify($data, $hash) {
        $rand = substr($hash, 0, 4);
        return $this->hash($data, $rand) === $hash;
    }

    private function hash($value, $rand = null) {
        $rand = $rand === null ? $this->getRand(4) : $rand;
        return $rand . bin2hex(hash_hmac('sha256', $value . $rand, $this->key, true));
    }

    private function getRand($length) {
        switch (true) {
            case function_exists("mcrypt_create_iv") :
                $r = mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
                break;
            case function_exists("openssl_random_pseudo_bytes") :
                $r = openssl_random_pseudo_bytes($length);
                break;
            case is_readable('/dev/urandom') : // deceze
                $r = file_get_contents('/dev/urandom', false, null, 0, $length);
                break;
            default :
                $i = 0;
                $r = "";
                while($i ++ < $length) {
                    $r .= chr(mt_rand(0, 255));
                }
                break;
        }
        return substr(bin2hex($r), 0, $length);
    }
}

Testing in Firefox & Chrome

enter image description here

Advantage

  • Better Security
  • Limited access for attacker
  • When cookie is stolen its only valid for single access
  • When next the original user access the site you can automatically detect and notify the user of theft

Disadvantage

  • Does not support persistent connection via multiple browser (Mobile & Web)
  • The cookie can still be stolen because the user only gets the notification after the next login.

Quick Fix

  • Introduction of approval system for each system that must have persistent connection
  • Use multiple cookies for the authentication

Multiple Cookie Approach

When an attacker is about to steal cookies the only focus it on a particular website or domain eg. example.com

But really you can authenticate a user from 2 different domains (example.com & fakeaddsite.com) and make it look like "Advert Cookie"

  • User Logged on to example.com with remember me
  • Store username, token, reference in cookie
  • Store username, token, reference in Database eg. Memcache
  • Send refrence id via get and iframe to fakeaddsite.com
  • fakeaddsite.com uses the reference to fetch user & token from Database
  • fakeaddsite.com stores the signature
  • When a user is returning fetch signature information with iframe from fakeaddsite.com
  • Combine it data and do the validation
  • ..... you know the remaining

Some people might wonder how can you use 2 different cookies ? Well its possible, imagine example.com = localhost and fakeaddsite.com = 192.168.1.120. If you inspect the cookies it would look like this

enter image description here

From the image above

  • The current site visited is localhost
  • It also contains cookies set from 192.168.1.120

192.168.1.120

  • Only accepts defined HTTP_REFERER
  • Only accepts connection from specified REMOTE_ADDR
  • No JavaScript, No content but consist nothing rather than sign information and add or retrieve it from cookie

Advantage

  • 99% percent of the time you have tricked the attacker
  • You can easily lock the account in the attacker first attempt
  • Attack can be prevented even before the next login like the other methods

Disadvantage

  • Multiple Request to server just for a single login

Improvement

  • Done use iframe use ajax

Get AVG ignoring Null or Zero values

In Case of not considering '0' or 'NULL' in average function. Simply use

AVG(NULLIF(your_column_name,0))

How to jQuery clone() and change id?

This is the simplest solution working for me.

$('#your_modal_id').clone().prop("id", "new_modal_id").appendTo("target_container");

.attr("disabled", "disabled") issue

Try this updated code :

$(bla).click(function(){        
  if (something) {
     console.log($target.prev("input")) // gives out the right object
     $target.toggleClass("open").prev("input").attr("disabled", "true");
  }else{
     $target.toggleClass("open").prev("input").removeAttr("disabled"); //this works
  }
})

Using {% url ??? %} in django templates

Instead of importing the logout_view function, you should provide a string in your urls.py file:

So not (r'^login/', login_view),

but (r'^login/', 'login.views.login_view'),

That is the standard way of doing things. Then you can access the URL in your templates using:

{% url login.views.login_view %}

How to create a trie in Python

Python Class for Trie


Trie Data Structure can be used to store data in O(L) where L is the length of the string so for inserting N strings time complexity would be O(NL) the string can be searched in O(L) only same goes for deletion.

Can be clone from https://github.com/Parikshit22/pytrie.git

class Node:
    def __init__(self):
        self.children = [None]*26
        self.isend = False
        
class trie:
    def __init__(self,):
        self.__root = Node()
        
    def __len__(self,):
        return len(self.search_byprefix(''))
    
    def __str__(self):
        ll =  self.search_byprefix('')
        string = ''
        for i in ll:
            string+=i
            string+='\n'
        return string
        
    def chartoint(self,character):
        return ord(character)-ord('a')
    
    def remove(self,string):
        ptr = self.__root
        length = len(string)
        for idx in range(length):
            i = self.chartoint(string[idx])
            if ptr.children[i] is not None:
                ptr = ptr.children[i]
            else:
                raise ValueError("Keyword doesn't exist in trie")
        if ptr.isend is not True:
            raise ValueError("Keyword doesn't exist in trie")
        ptr.isend = False
        return
    
    def insert(self,string):
        ptr = self.__root
        length = len(string)
        for idx in range(length):
            i = self.chartoint(string[idx])
            if ptr.children[i] is not None:
                ptr = ptr.children[i]
            else:
                ptr.children[i] = Node()
                ptr = ptr.children[i]
        ptr.isend = True
        
    def search(self,string):
        ptr = self.__root
        length = len(string)
        for idx in range(length):
            i = self.chartoint(string[idx])
            if ptr.children[i] is not None:
                ptr = ptr.children[i]
            else:
                return False
        if ptr.isend is not True:
            return False
        return True
    
    def __getall(self,ptr,key,key_list):
        if ptr is None:
            key_list.append(key)
            return
        if ptr.isend==True:
            key_list.append(key)
        for i in range(26):
            if ptr.children[i]  is not None:
                self.__getall(ptr.children[i],key+chr(ord('a')+i),key_list)
        
    def search_byprefix(self,key):
        ptr = self.__root
        key_list = []
        length = len(key)
        for idx in range(length):
            i = self.chartoint(key[idx])
            if ptr.children[i] is not None:
                ptr = ptr.children[i]
            else:
                return None
        
        self.__getall(ptr,key,key_list)
        return key_list
        

t = trie()
t.insert("shubham")
t.insert("shubhi")
t.insert("minhaj")
t.insert("parikshit")
t.insert("pari")
t.insert("shubh")
t.insert("minakshi")
print(t.search("minhaj"))
print(t.search("shubhk"))
print(t.search_byprefix('m'))
print(len(t))
print(t.remove("minhaj"))
print(t)

Code Oputpt

True
False
['minakshi', 'minhaj']
7
minakshi
minhajsir
pari
parikshit
shubh
shubham
shubhi

If Else If In a Sql Server Function

If yes_ans > no_ans and yes_ans > na_ans  

You're using column names in a statement (outside of a query). If you want variables, you must declare and assign them.

How can I check if a scrollbar is visible?

Here's my improvement: added parseInt. for some weird reason it didn't work without it.

// usage: jQuery('#my_div1').hasVerticalScrollBar();
// Credit: http://stackoverflow.com/questions/4814398/how-can-i-check-if-a-scrollbar-is-visible
(function($) {
    $.fn.hasVerticalScrollBar = function() {
        return this.get(0) ? parseInt( this.get(0).scrollHeight ) > parseInt( this.innerHeight() ) : false;
    };
})(jQuery);

C# Linq Group By on multiple columns

Given a list:

var list = new List<Child>()
{
    new Child()
        {School = "School1", FavoriteColor = "blue", Friend = "Bob", Name = "John"},
    new Child()
        {School = "School2", FavoriteColor = "blue", Friend = "Bob", Name = "Pete"},
    new Child()
        {School = "School1", FavoriteColor = "blue", Friend = "Bob", Name = "Fred"},
    new Child()
        {School = "School2", FavoriteColor = "blue", Friend = "Fred", Name = "Bob"},
};

The query would look like:

var newList = list
    .GroupBy(x => new {x.School, x.Friend, x.FavoriteColor})
    .Select(y => new ConsolidatedChild()
        {
            FavoriteColor = y.Key.FavoriteColor,
            Friend = y.Key.Friend,
            School = y.Key.School,
            Children = y.ToList()
        }
    );

Test code:

foreach(var item in newList)
{
    Console.WriteLine("School: {0} FavouriteColor: {1} Friend: {2}", item.School,item.FavoriteColor,item.Friend);
    foreach(var child in item.Children)
    {
        Console.WriteLine("\t Name: {0}", child.Name);
    }
}

Result:

School: School1 FavouriteColor: blue Friend: Bob
    Name: John
    Name: Fred
School: School2 FavouriteColor: blue Friend: Bob
    Name: Pete
School: School2 FavouriteColor: blue Friend: Fred
    Name: Bob

How to find and replace all occurrences of a string recursively in a directory tree?

For me works the next command:

find /path/to/dir -name "file.txt" | xargs sed -i 's/string_to_replace/new_string/g'

if string contains slash 'path/to/dir' it can be replace with another character to separate, like '@' instead '/'.

For example: 's@string/to/replace@new/string@g'

How to nicely format floating numbers to string without unnecessary decimal 0's

I am using this for formatting numbers without trailing zeroes in our JSF application. The original built-in formatters required you to specify max numbers of fractional digits which could be useful here also in case you have too many fractional digits.

/**
 * Formats the given Number as with as many fractional digits as precision
 * available.<br>
 * This is a convenient method in case all fractional digits shall be
 * rendered and no custom format / pattern needs to be provided.<br>
 * <br>
 * This serves as a workaround for {@link NumberFormat#getNumberInstance()}
 * which by default only renders up to three fractional digits.
 *
 * @param number
 * @param locale
 * @param groupingUsed <code>true</code> if grouping shall be used
 *
 * @return
 */
public static String formatNumberFraction(final Number number, final Locale locale, final boolean groupingUsed)
{
    if (number == null)
        return null;

    final BigDecimal bDNumber = MathUtils.getBigDecimal(number);

    final NumberFormat numberFormat = NumberFormat.getNumberInstance(locale);
    numberFormat.setMaximumFractionDigits(Math.max(0, bDNumber.scale()));
    numberFormat.setGroupingUsed(groupingUsed);

    // Convert back for locale percent formatter
    return numberFormat.format(bDNumber);
}

/**
 * Formats the given Number as percent with as many fractional digits as
 * precision available.<br>
 * This is a convenient method in case all fractional digits shall be
 * rendered and no custom format / pattern needs to be provided.<br>
 * <br>
 * This serves as a workaround for {@link NumberFormat#getPercentInstance()}
 * which does not renders fractional digits.
 *
 * @param number Number in range of [0-1]
 * @param locale
 *
 * @return
 */
public static String formatPercentFraction(final Number number, final Locale locale)
{
    if (number == null)
        return null;

    final BigDecimal bDNumber = MathUtils.getBigDecimal(number).multiply(new BigDecimal(100));

    final NumberFormat percentScaleFormat = NumberFormat.getPercentInstance(locale);
    percentScaleFormat.setMaximumFractionDigits(Math.max(0, bDNumber.scale() - 2));

    final BigDecimal bDNumberPercent = bDNumber.multiply(new BigDecimal(0.01));

    // Convert back for locale percent formatter
    final String strPercent = percentScaleFormat.format(bDNumberPercent);

    return strPercent;
}

Error in Process.Start() -- The system cannot find the file specified

I had the same problem, but none of the solutions worked for me, because the message The system cannot find the file specified can be misleading in some special cases.

In my case, I use Notepad++ in combination with the registry redirect for notepad.exe. Unfortunately my path to Notepad++ in the registry was wrong.

So in fact the message The system cannot find the file specified was telling me, that it cannot find the application (Notepad++) associated with the file type(*.txt), not the file itself.

.gitignore exclude folder but include specific subfolder

I often use this workaround in CLI where instead of configuring my .gitignore, I create a separate .include file where I define the (sub)directories I want included in spite of directories directly or recursively ignored by .gitignore.

Thus, I additionally use

git add `cat .include`

during staging, before committing.

To the OP, I suggest using a .include which has these lines:

<parent_folder_path>/application/language/gr/*

NOTE: Using cat does not allow usage of aliases (within .include) for specifying $HOME (or any other specific directory). This is because the line homedir/app1/* when passed to git add using the above command appears as git add 'homedir/app1/*', and enclosing characters in single quotes ('') preserves the literal value of each character within the quotes, thus preventing aliases (such as homedir) from functioning (see Bash Single Quotes).

Here is an example of a .include file I use in my repo here.

/home/abhirup/token.txt
/home/abhirup/.include
/home/abhirup/.vim/*
/home/abhirup/.viminfo
/home/abhirup/.bashrc
/home/abhirup/.vimrc
/home/abhirup/.condarc

How do you push a tag to a remote repository using Git?

I am using git push <remote-name> tag <tag-name> to ensure that I am pushing a tag. I use it like: git push origin tag v1.0.1. This pattern is based upon the documentation (man git-push):

OPTIONS
   ...
   <refspec>...
       ...
       tag <tag> means the same as refs/tags/<tag>:refs/tags/<tag>.

convert '1' to '0001' in JavaScript

I use the following object:

function Padder(len, pad) {
  if (len === undefined) {
    len = 1;
  } else if (pad === undefined) {
    pad = '0';
  }

  var pads = '';
  while (pads.length < len) {
    pads += pad;
  }

  this.pad = function (what) {
    var s = what.toString();
    return pads.substring(0, pads.length - s.length) + s;
  };
}

With it you can easily define different "paddings":

var zero4 = new Padder(4);
zero4.pad(12); // "0012"
zero4.pad(12345); // "12345"
zero4.pad("xx"); // "00xx"
var x3 = new Padder(3, "x");
x3.pad(12); // "x12"

Read properties file outside JAR file

This works for me. Load your properties file from current directory.

Attention: The method Properties#load uses ISO-8859-1 encoding.

Properties properties = new Properties();
properties.load(new FileReader(new File(".").getCanonicalPath() + File.separator + "java.properties"));
properties.forEach((k, v) -> {
            System.out.println(k + " : " + v);
        });

Make sure, that java.properties is at the current directory . You can just write a little startup script that switches into to the right directory in before, like

#! /bin/bash
scriptdir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" 
cd $scriptdir
java -jar MyExecutable.jar
cd -

In your project just put the java.properties file in your project root, in order to make this code work from your IDE as well.

How can I break up this long line in Python?

You can use textwrap module to break it in multiple lines

import textwrap
str="ABCDEFGHIJKLIMNO"
print("\n".join(textwrap.wrap(str,8)))

ABCDEFGH
IJKLIMNO

From the documentation:

textwrap.wrap(text[, width[, ...]])
Wraps the single paragraph in text (a string) so every line is at most width characters long. Returns a list of output lines, without final newlines.

Optional keyword arguments correspond to the instance attributes of TextWrapper, documented below. width defaults to 70.

See the TextWrapper.wrap() method for additional details on how wrap() behaves.

Nested objects in javascript, best practices

var defaultSettings = {
    ajaxsettings: {},
    uisettings: {}
};

Take a look at this site: http://www.json.org/

Also, you can try calling JSON.stringify() on one of your objects from the browser to see the json format. You'd have to do this in the console or a test page.

How to import/include a CSS file using PHP code and not HTML code?

Just put

echo "<link rel='stylesheet' type='text/css' href='CSS/main.css'>";

inside the php code, then your style is incuded. Worked for me, I tried.

How to define custom exception class in Java, the easiest way?

If you inherit from Exception, you have to provide a constructor that takes a String as a parameter (it will contain the error message).

Excel - match data from one range to another and get the value from the cell to the right of the matched data

Thanks a bundle, guys. You are great.

I used Chuff's answer and modified it a little to do what I wanted.

I have 2 worksheets in the same workbook.

On 1st worksheet I have a list of SMS in 3 columns: phone number, date & time, message

Then I inserted a new blank column next to the phone number

On worksheet 2 I have two columns: phone number, name of person

Used the formula to check the cell on the left, and match against the range in worksheet 2, pick the name corresponding to the number and input it into the blank cell in worksheet 1.

Then just copy the formula down the whole column until last sms It worked beautifully.

=VLOOKUP(A3,Sheet2!$A$1:$B$31,2,0)

ValueError: unconverted data remains: 02:05

The value of st at st = datetime.strptime(st, '%A %d %B') line something like 01 01 2013 02:05 and the strptime can't parse this. Indeed, you get an hour in addition of the date... You need to add %H:%M at your strptime.

How can I get the request URL from a Java Filter?

Is this what you're looking for?

if (request instanceof HttpServletRequest) {
 String url = ((HttpServletRequest)request).getRequestURL().toString();
 String queryString = ((HttpServletRequest)request).getQueryString();
}

To Reconstruct:

System.out.println(url + "?" + queryString);

Info on HttpServletRequest.getRequestURL() and HttpServletRequest.getQueryString().

VBA Copy Sheet to End of Workbook (with Hidden Worksheets)

Answer : I found this and wants to share it with you.

Sub Copier4()
   Dim x As Integer

   For x = 1 To ActiveWorkbook.Sheets.Count
      'Loop through each of the sheets in the workbook
      'by using x as the sheet index number.
      ActiveWorkbook.Sheets(x).Copy _
         After:=ActiveWorkbook.Sheets(ActiveWorkbook.Sheets.Count)
         'Puts all copies after the last existing sheet.
   Next
End Sub

But the question, can we use it with following code to rename the sheets, if yes, how can we do so?

Sub CreateSheetsFromAList()
Dim MyCell As Range, MyRange As Range
Set MyRange = Sheets("Summary").Range("A10")
Set MyRange = Range(MyRange, MyRange.End(xlDown))
For Each MyCell In MyRange
Sheets.Add After:=Sheets(Sheets.Count) 'creates a new worksheet
Sheets(Sheets.Count).Name = MyCell.Value ' renames the new worksheet
Next MyCell
End Sub

What is the difference between URL parameters and query strings?

The query component is indicated by the first ? in a URI. "Query string" might be a synonym (this term is not used in the URI standard).

Some examples for HTTP URIs with query components:

http://example.com/foo?bar
http://example.com/foo/foo/foo?bar/bar/bar
http://example.com/?bar
http://example.com/?@bar._=???/1:
http://example.com/?bar1=a&bar2=b

(list of allowed characters in the query component)

The "format" of the query component is up to the URI authors. A common convention (but nothing more than a convention, as far as the URI standard is concerned¹) is to use the query component for key-value pairs, aka. parameters, like in the last example above: bar1=a&bar2=b.

Such parameters could also appear in the other URI components, i.e., the path² and the fragment. As far as the URI standard is concerned, it’s up to you which component and which format to use.

Example URI with parameters in the path, the query, and the fragment:

http://example.com/foo;key1=value1?key2=value2#key3=value3

¹ The URI standard says about the query component:

[…] query components are often used to carry identifying information in the form of "key=value" pairs […]

² The URI standard says about the path component:

[…] the semicolon (";") and equals ("=") reserved characters are often used to delimit parameters and parameter values applicable to that segment. The comma (",") reserved character is often used for similar purposes.

What is the right way to treat argparse.Namespace() as a dictionary?

Is it proper to "reach into" an object and use its dict property?

In general, I would say "no". However Namespace has struck me as over-engineered, possibly from when classes couldn't inherit from built-in types.

On the other hand, Namespace does present a task-oriented approach to argparse, and I can't think of a situation that would call for grabbing the __dict__, but the limits of my imagination are not the same as yours.

How do I enable EF migrations for multiple contexts to separate databases?

In case you already have a "Configuration" with many migrations and want to keep this as is, you can always create a new "Configuration" class, give it another name, like

class MyNewContextConfiguration : DbMigrationsConfiguration<MyNewDbContext>
{
   ...
}

then just issue the command

Add-Migration -ConfigurationTypeName MyNewContextConfiguration InitialMigrationName

and EF will scaffold the migration without problems. Finally update your database, from now on, EF will complain if you don't tell him which configuration you want to update:

Update-Database -ConfigurationTypeName MyNewContextConfiguration 

Done.

You don't need to deal with Enable-Migrations as it will complain "Configuration" already exists, and renaming your existing Configuration class will bring issues to the migration history.

You can target different databases, or the same one, all configurations will share the __MigrationHistory table nicely.

jQuery: select an element's class and id at the same time?

In the end the same rules as for css apply.

So I think this reference could be of some valuable use.

runOnUiThread in fragment

I used this for getting Date and Time in a fragment.

private Handler mHandler = new Handler(Looper.getMainLooper());
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    // Inflate the layout for this fragment
    View root = inflater.inflate(R.layout.fragment_head_screen, container, false);

    dateTextView =  root.findViewById(R.id.dateView);
    hourTv = root.findViewById(R.id.hourView);

        Thread thread = new Thread() {
        @Override
        public void run() {
            try {
                while (!isInterrupted()) {
                    Thread.sleep(1000);
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            //Calendario para obtener fecha & hora
                            Date currentTime = Calendar.getInstance().getTime();
                            SimpleDateFormat date_sdf = new SimpleDateFormat("dd/MM/yyyy");
                            SimpleDateFormat hour_sdf = new SimpleDateFormat("HH:mm a");

                            String currentDate = date_sdf.format(currentTime);
                            String currentHour = hour_sdf.format(currentTime);

                            dateTextView.setText(currentDate);
                            hourTv.setText(currentHour);
                        }
                    });
                }
            } catch (InterruptedException e) {
                Log.v("InterruptedException", e.getMessage());
            }
        }
    };
}

How do I update the password for Git?

If you are MAC user then you can open KeyChain Access Application from finder and then look for your account listed there. Just click on it and update your password. Now give a try and things will fall in place.

link for reference: Updating your credentials via Keychain Access

Worked for me. :)

VBScript -- Using error handling

I'm exceptionally new to VBScript, so this may not be considered best practice or there may be a reason it shouldn't be done this that way I'm not yet aware of, but this is the solution I came up with to trim down the amount of error logging code in my main code block.

Dim oConn, connStr
Set oConn = Server.CreateObject("ADODB.Connection")
connStr = "Provider=SQLOLEDB;Server=XX;UID=XX;PWD=XX;Databse=XX"

ON ERROR RESUME NEXT

oConn.Open connStr
If err.Number <> 0 Then : showError() : End If


Sub ShowError()

    'You could write the error details to the console...
    errDetail = "<script>" & _
    "console.log('Description: " & err.Description & "');" & _
    "console.log('Error number: " & err.Number & "');" & _
    "console.log('Error source: " & err.Source & "');" & _
    "</script>"

    Response.Write(errDetail)       

    '...you could display the error info directly in the page...
    Response.Write("Error Description: " & err.Description)
    Response.Write("Error Source: " & err.Source)
    Response.Write("Error Number: " & err.Number)

    '...or you could execute additional code when an error is thrown...
    'Insert error handling code here

    err.clear
End Sub

What is the best way to get all the divisors of a number?

I like Greg solution, but I wish it was more python like. I feel it would be faster and more readable; so after some time of coding I came out with this.

The first two functions are needed to make the cartesian product of lists. And can be reused whnever this problem arises. By the way, I had to program this myself, if anyone knows of a standard solution for this problem, please feel free to contact me.

"Factorgenerator" now returns a dictionary. And then the dictionary is fed into "divisors", who uses it to generate first a list of lists, where each list is the list of the factors of the form p^n with p prime. Then we make the cartesian product of those lists, and we finally use Greg' solution to generate the divisor. We sort them, and return them.

I tested it and it seem to be a bit faster than the previous version. I tested it as part of a bigger program, so I can't really say how much is it faster though.

Pietro Speroni (pietrosperoni dot it)

from math import sqrt


##############################################################
### cartesian product of lists ##################################
##############################################################

def appendEs2Sequences(sequences,es):
    result=[]
    if not sequences:
        for e in es:
            result.append([e])
    else:
        for e in es:
            result+=[seq+[e] for seq in sequences]
    return result


def cartesianproduct(lists):
    """
    given a list of lists,
    returns all the possible combinations taking one element from each list
    The list does not have to be of equal length
    """
    return reduce(appendEs2Sequences,lists,[])

##############################################################
### prime factors of a natural ##################################
##############################################################

def primefactors(n):
    '''lists prime factors, from greatest to smallest'''  
    i = 2
    while i<=sqrt(n):
        if n%i==0:
            l = primefactors(n/i)
            l.append(i)
            return l
        i+=1
    return [n]      # n is prime


##############################################################
### factorization of a natural ##################################
##############################################################

def factorGenerator(n):
    p = primefactors(n)
    factors={}
    for p1 in p:
        try:
            factors[p1]+=1
        except KeyError:
            factors[p1]=1
    return factors

def divisors(n):
    factors = factorGenerator(n)
    divisors=[]
    listexponents=[map(lambda x:k**x,range(0,factors[k]+1)) for k in factors.keys()]
    listfactors=cartesianproduct(listexponents)
    for f in listfactors:
        divisors.append(reduce(lambda x, y: x*y, f, 1))
    divisors.sort()
    return divisors



print divisors(60668796879)

P.S. it is the first time I am posting to stackoverflow. I am looking forward for any feedback.

Set The Window Position of an application via command line

This probably should be a comment under the cmdow.exe answer, but here is a simple batch file I wrote to allow for fairly sophisticated and simple control over all windows that you can see in the taskbar.

First step is to run cmdow /t to display a list of those windows. Look at what the image name is in the column Image, then command line:

mycmdowscript.cmd imagename

Here are the contents of the batch file:

:: mycmdowscript.cmd

@echo off
SETLOCAL ENABLEDELAYEDEXPANSION

SET IMAGE=%1
SET ACTION=/%2
SET REST=1
SET PARAMS=

:: GET ANY ADDITIONAL PARAMS AND STORE THEM IN A VARIABLE

FOR %%I in (%*) DO (
   IF !REST! geq 3 (
      SET PARAMS=!PARAMS! %%I
   )
   SET /A REST+=1
)

FOR /F "USEBACKQ tokens=1,8" %%I IN (`CMDOW /t`) DO (
     IF %IMAGE%==%%J (

     :: you now have access to the handle in %%I
     cmdow %%I %ACTION% !PARAMS!

     )
)

ENDLOCAL
@echo on

EXIT /b

example usage

:: will set notepad to 500 500

mycmdowscript.cmd notepad siz 500 500

You could probably rewrite this to allow for multiple actions on a single command, but I haven't tried yet.

For this to work, cmdow.exe must be located in your path. Beware that when you download this, your AV program might yell at you. This tool has (I guess) in the past been used by malware authors to manipulate windows. It is not harmful by itself.

Sequence contains no matching element

For those of you who faced this issue while creating a controller through the context menu, reopening Visual Studio as an administrator fixed it.

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

The signature:

bool operator<<(const obj&, const obj&);

Seems rather suspect, this does not fit the stream convention nor the bitwise convention so it looks like a case of operator overloading abuse, operator < should return bool but operator << should probably return something else.

If you meant so say:

ostream& operator<<(ostream&, const obj&); 

Then since you can't add functions to ostream by necessity the function must be a free function, whether it a friend or not depends on what it has to access (if it doesn't need to access private or protected members there's no need to make it friend).

How to disable <br> tags inside <div> by css?

<p style="color:black">Shop our collection of beautiful women's <br> <span> wedding ring in classic &amp; modern design.</span></p>

Remove <br> effect using CSS.

<style> p br{ display:none; } </style>

Java: How to check if object is null?

if (yourObject instanceof yourClassName) will evaluate to false if yourObject is null.

Get counts of all tables in a schema

Get counts of all tables in a schema and order by desc

select 'with tmp(table_name, row_number) as (' from dual 
union all 
select 'select '''||table_name||''',count(*) from '||table_name||' union  ' from USER_TABLES 
union all
select 'select '''',0 from dual) select table_name,row_number from tmp order by row_number desc ;' from dual;

Copy the entire result and execute

How to get a context in a recycler view adapter

you can use this:

itemView.getContext()

Programmatically go back to previous ViewController in Swift

I can redirect to root page by writing code in "viewDidDisappear" of navigated controller,

override func viewDidDisappear(_ animated: Bool) { self.navigationController?.popToRootViewController(animated: true) }

How do I get IntelliJ to recognize common Python modules?

Even my Intellisense in Pycharm was not working for modules like time Problem in my system was no Interpreter was selected Go to File --> Settings... (Ctrl+Alt+S) Open Project Interpreter

Project Interpreter In my case was selected. I selected the available python interpreter. If not available you can add a new interpreter.

Sass nth-child nesting

I'd be careful about trying to get too clever here. I think it's confusing as it is and using more advanced nth-child parameters will only make it more complicated. As for the background color I'd just set that to a variable.

Here goes what I came up with before I realized trying to be too clever might be a bad thing.

#romtest {
 $bg: #e5e5e5;
 .detailed {
    th {
      &:nth-child(-2n+6) {
        background-color: $bg;
      }
    }
    td {
      &:nth-child(3n), &:nth-child(2), &:nth-child(7) {
        background-color: $bg;
      }
      &.last {
        &:nth-child(-2n+4){
          background-color: $bg;
        }
      }
    }
  }
}

and here is a quick demo: http://codepen.io/anon/pen/BEImD

----EDIT----

Here's another approach to avoid retyping background-color:

#romtest {
  %highlight {
    background-color: #e5e5e5; 
  }
  .detailed {
    th {
      &:nth-child(-2n+6) {
        @extend %highlight;
      }
    }

    td {
      &:nth-child(3n), &:nth-child(2), &:nth-child(7) {
        @extend %highlight;
      }
      &.last {
        &:nth-child(-2n+4){
          @extend %highlight;
        }
      }
    }
  }
}

CSS Flex Box Layout: full-width row and columns

This is copied from above, but condensed slightly and re-written in semantic terms. Note: #Container has display: flex; and flex-direction: column;, while the columns have flex: 3; and flex: 2; (where "One value, unitless number" determines the flex-grow property) per MDN flex docs.

_x000D_
_x000D_
#Container {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  height: 600px;_x000D_
  width: 580px;_x000D_
}_x000D_
_x000D_
.Content {_x000D_
  display: flex;_x000D_
  flex: 1;_x000D_
}_x000D_
_x000D_
#Detail {_x000D_
  flex: 3;_x000D_
  background-color: lime;_x000D_
}_x000D_
_x000D_
#ThumbnailContainer {_x000D_
  flex: 2;_x000D_
  background-color: black;_x000D_
}
_x000D_
<div id="Container">_x000D_
  <div class="Content">_x000D_
    <div id="Detail"></div>_x000D_
    <div id="ThumbnailContainer"></div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Exporting functions from a DLL with dllexport

For C++ :

I just faced the same issue and I think it is worth mentioning a problem comes up when one use both __stdcall (or WINAPI) and extern "C":

As you know extern "C" removes the decoration so that instead of :

__declspec(dllexport) int Test(void)                        --> dumpbin : ?Test@@YaHXZ

you obtain a symbol name undecorated:

extern "C" __declspec(dllexport) int Test(void)             --> dumpbin : Test

However the _stdcall ( = macro WINAPI, that changes the calling convention) also decorates names so that if we use both we obtain :

   extern "C" __declspec(dllexport) int WINAPI Test(void)   --> dumpbin : _Test@0

and the benefit of extern "C" is lost because the symbol is decorated (with _ @bytes)

Note that this only occurs for x86 architecture because the __stdcall convention is ignored on x64 (msdn : on x64 architectures, by convention, arguments are passed in registers when possible, and subsequent arguments are passed on the stack.).

This is particularly tricky if you are targeting both x86 and x64 platforms.


Two solutions

  1. Use a definition file. But this forces you to maintain the state of the def file.

  2. the simplest way : define the macro (see msdn) :

#define EXPORT comment(linker, "/EXPORT:" __FUNCTION__ "=" __FUNCDNAME__)

and then include the following pragma in the function body:

#pragma EXPORT

Full Example :

 int WINAPI Test(void)
{
    #pragma EXPORT
    return 1;
}

This will export the function undecorated for both x86 and x64 targets while preserving the __stdcall convention for x86. The __declspec(dllexport) is not required in this case.

How to delete a column from a table in MySQL

ALTER TABLE tbl_Country DROP COLUMN IsDeleted;

Here's a working example.

Note that the COLUMN keyword is optional, as MySQL will accept just DROP IsDeleted. Also, to drop multiple columns, you have to separate them by commas and include the DROP for each one.

ALTER TABLE tbl_Country
  DROP COLUMN IsDeleted,
  DROP COLUMN CountryName;

This allows you to DROP, ADD and ALTER multiple columns on the same table in the one statement. From the MySQL reference manual:

You can issue multiple ADD, ALTER, DROP, and CHANGE clauses in a single ALTER TABLE statement, separated by commas. This is a MySQL extension to standard SQL, which permits only one of each clause per ALTER TABLE statement.

How do you implement a re-try-catch?

The issue with the remaining solutions is that, the correspondent function tries continuously without a time interval in-between, thus over flooding the stack.

Why not just trying only every second and ad eternum?

Here a solution using setTimeout and a recursive function:

_x000D_
_x000D_
(function(){_x000D_
  try{_x000D_
    Run(); //tries for the 1st time, but Run() as function is not yet defined_x000D_
  }_x000D_
  catch(e){_x000D_
    (function retry(){_x000D_
      setTimeout(function(){_x000D_
        try{_x000D_
          console.log("trying...");_x000D_
          Run();_x000D_
          console.log("success!");_x000D_
        }_x000D_
        catch(e){_x000D_
          retry(); //calls recursively_x000D_
        }_x000D_
      }, 1000); //tries every second_x000D_
    }());_x000D_
  }_x000D_
})();_x000D_
_x000D_
_x000D_
_x000D_
//after 5 seconds, defines Run as a global function_x000D_
var Run;_x000D_
setTimeout(function(){_x000D_
  Run = function(){};_x000D_
}, 5000);
_x000D_
_x000D_
_x000D_

Replace the function Run() by the function or code that you'd like to retry every second.

Laravel 5 error SQLSTATE[HY000] [1045] Access denied for user 'homestead'@'localhost' (using password: YES)

I had the same problem, so I realized that the .env file does not accept special characters, as my password has these characters, I added the password in the config/database.php file.

Are there any HTTP/HTTPS interception tools like Fiddler for mac OS X?

I think the possibilities are less, but FireBug (addon of FireFox) has some network analysis tools, too.

Returning a boolean from a Bash function

Following up on @Bruno Bronosky and @mrteatime, I offer the suggestion that you just write your boolean return "backwards". This is what I mean:

foo()
{
    if [ "$1" == "bar" ]; then
        true; return
    else
        false; return
    fi;
}

That eliminates the ugly two line requirement for every return statement.

Could not insert new outlet connection: Could not find any information for the class named

Just perform the two following steps to get rid of this error

  1. Clean project using Product > clean
  2. Run the project

Now try to add the action or outlet. That's it.

Happy Coding

jQuery datepicker, onSelect won't work

datePicker's onSelect equivalent is the dateSelected event.

$(function() {
    $('.date-pick').datePicker( {
        selectWeek: true,
        inline: true,
        startDate: '01/01/2000',
        firstDay: 1,
    }).bind('dateSelected', function(e, selectedDate, $td) {
        alert(selectedDate);
    });
});

This page has a good example showing the dateSelected event and other events being bound.

How can I create an observable with a delay

It's little late to answer ... but just in case may be someone return to this question looking for an answer

'delay' is property(function) of an Observable

fakeObservable = Observable.create(obs => {
  obs.next([1, 2, 3]);
  obs.complete();
}).delay(3000);

This worked for me ...

For loop in Oracle SQL

You are pretty confused my friend. There are no LOOPS in SQL, only in PL/SQL. Here's a few examples based on existing Oracle table - copy/paste to see results:

-- Numeric FOR loop --
set serveroutput on -->> do not use in TOAD --
DECLARE
  k NUMBER:= 0;
BEGIN
  FOR i IN 1..10 LOOP
    k:= k+1;
    dbms_output.put_line(i||' '||k);
 END LOOP;
END;
/

-- Cursor FOR loop --
set serveroutput on
DECLARE
   CURSOR c1 IS SELECT * FROM scott.emp;
   i NUMBER:= 0;
BEGIN
  FOR e_rec IN c1 LOOP
  i:= i+1;
    dbms_output.put_line(i||chr(9)||e_rec.empno||chr(9)||e_rec.ename);
  END LOOP;
END;
/

-- SQL example to generate 10 rows --
SELECT 1 + LEVEL-1 idx
  FROM dual
CONNECT BY LEVEL <= 10
/

Swift 3 URLSession.shared() Ambiguous reference to member 'dataTask(with:completionHandler:) error (bug)

In my case error was in NSURL

let url = NSURL(string: urlString)

In Swift 3 you must write just URL:

let url = URL(string: urlString)

I ran into a merge conflict. How can I abort the merge?

Sourcetree

Because you not commit your merge, then just double click on another branch (which mean checkout it) and when sourcetree ask you about discarding all changes then agree :)

Update

I see many down-votes but any commet... I will left this answer which is addressed for those who use SourceTree as git client (as I - when I looking for solution for question asked by OP)

Change class on mouseover in directive

This is my solution for my scenario:

<div class="btn-group btn-group-justified">
    <a class="btn btn-default" ng-class="{'btn-success': hover.left, 'btn-danger': hover.right}" ng-click="setMatch(-1)" role="button" ng-mouseenter="hover.left = true;" ng-mouseleave="hover.left = false;">
        <i class="fa fa-thumbs-o-up fa-5x pull-left" ng-class="{'fa-rotate-90': !hover.left && !hover.right, 'fa-flip-vertical': hover.right}"></i>
        {{ song.name }}
    </a>
    <a class="btn btn-default" ng-class="{'btn-success': hover.right, 'btn-danger': hover.left}" ng-click="setMatch(1)" role="button" ng-mouseenter="hover.right = true;" ng-mouseleave="hover.right = false;">
        <i class="fa fa-thumbs-o-up fa-5x pull-right" ng-class="{'fa-rotate-270': !hover.left && !hover.right, 'fa-flip-vertical': hover.left}"></i>
        {{ match.name }}
    </a>
</div>

default state: enter image description here

on hover: enter image description here

Can you delete multiple branches in one command with Git?

Use the following command to remove all branches (checked out branch will not be deleted).

git branch | cut -d '*' -f 1 | tr -d " \t\r" | xargs git branch -d

Edit: I am using a Mac Os

How do I use sudo to redirect output to a location I don't have permission to write to?

Make sudo run a shell, like this:

sudo sh -c "echo foo > ~root/out"

pip cannot install anything

I had this error message occur as I had set a Windows Environment Variable to an invalid certificate file.

Check if you have a CURL_CA_BUNDLE variable by typing SET at the command prompt.

You can override it for the current session with SET CURL_CA_BUNDLE=

The pip.log contained the following:

Getting page https://pypi.python.org/simple/pip/
Could not fetch URL https://pypi.python.org/simple/pip/: connection error: [Errno 185090050] _ssl.c:340: error:0B084002:x509 certificate routines:X509_load_cert_crl_file:system lib

How to plot time series in python

Convert your x-axis data from text to datetime.datetime, use datetime.strptime:

>>> from datetime import datetime
>>> datetime.strptime("2012-may-31 19:00", "%Y-%b-%d %H:%M")
 datetime.datetime(2012, 5, 31, 19, 0)

This is an example of how to plot data once you have an array of datetimes:

import matplotlib.pyplot as plt
import datetime
import numpy as np

x = np.array([datetime.datetime(2013, 9, 28, i, 0) for i in range(24)])
y = np.random.randint(100, size=x.shape)

plt.plot(x,y)
plt.show()

enter image description here

How can I make an svg scale with its parent container?

To specify the coordinates within the SVG image independently of the scaled size of the image, use the viewBox attribute on the SVG element to define what the bounding box of the image is in the coordinate system of the image, and use the width and height attributes to define what the width or height are with respect to the containing page.

For instance, if you have the following:

<svg>
    <polygon fill=red stroke-width=0 
             points="0,10 20,10 10,0" />
</svg>

It will render as a 10px by 20px triangle:

10x20 triangle

Now, if you set only the width and height, that will change the size of the SVG element, but not scale the triangle:

<svg width=100 height=50>
    <polygon fill=red stroke-width=0 
             points="0,10 20,10 10,0" />
</svg>

10x20 triangle

If you set the view box, that causes it to transform the image such that the given box (in the coordinate system of the image) is scaled up to fit within the given width and height (in the coordinate system of the page). For instance, to scale up the triangle to be 100px by 50px:

<svg width=100 height=50 viewBox="0 0 20 10">
    <polygon fill=red stroke-width=0 
             points="0,10 20,10 10,0" />
</svg>

100x50 triangle

If you want to scale it up to the width of the HTML viewport:

<svg width="100%" viewBox="0 0 20 10">
    <polygon fill=red stroke-width=0 
             points="0,10 20,10 10,0" />
</svg>

300x150 triangle

Note that by default, the aspect ratio is preserved. So if you specify that the element should have a width of 100%, but a height of 50px, it will actually only scale up to the height of 50px (unless you have a very narrow window):

<svg width="100%" height="50px" viewBox="0 0 20 10">
    <polygon fill=red stroke-width=0 
             points="0,10 20,10 10,0" />
</svg>

100x50 triangle

If you actually want it to stretch horizontally, disable aspect ratio preservation with preserveAspectRatio=none:

<svg width="100%" height="50px" viewBox="0 0 20 10" preserveAspectRatio="none">
    <polygon fill=red stroke-width=0 
             points="0,10 20,10 10,0" />
</svg>

300x50 triangle

(note that while in my examples I use syntax that works for HTML embedding, to include the examples as an image in StackOverflow I am instead embedding within another SVG, so I need to use valid XML syntax)

How do you check if a JavaScript Object is a DOM Object?

How about Lo-Dash's _.isElement?

$ npm install lodash.iselement

And in the code:

var isElement = require("lodash.iselement");
isElement(document.body);

How to return a custom object from a Spring Data JPA GROUP BY query

define a custom pojo class say sureveyQueryAnalytics and store the query returned value in your custom pojo class

@Query(value = "select new com.xxx.xxx.class.SureveyQueryAnalytics(s.answer, count(sv)) from Survey s group by s.answer")
List<SureveyQueryAnalytics> calculateSurveyCount();

Cant get text of a DropDownList in code - can get value but not text

AppendDataBoundItems="true" needs to be set.

How to get random value out of an array?

You get a random number out of an array as follows:

$randomValue = $rand[array_rand($rand,1)];

iOS 11, 12, and 13 installed certificates not trusted automatically (self signed)

If you are not seeing the certificate under General->About->Certificate Trust Settings, then you probably do not have the ROOT CA installed. Very important -- needs to be a ROOT CA, not an intermediary CA.

I just answered a question here explaining how to obtain the ROOT CA and get things to show up: How to install self-signed certificates in iOS 11

How to use tick / checkmark symbol (?) instead of bullets in unordered list?

You can use a pseudo-element to insert that character before each list item:

_x000D_
_x000D_
ul {_x000D_
  list-style: none;_x000D_
}_x000D_
_x000D_
ul li:before {_x000D_
  content: '?';_x000D_
}
_x000D_
<ul>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

How does one use the onerror attribute of an img element

This is actually tricky, especially if you plan on returning an image url for use cases where you need to concatenate strings with the onerror condition image URL, e.g. you might want to programatically set the url parameter in CSS.

The trick is that image loading is asynchronous by nature so the onerror doesn't happen sunchronously, i.e. if you call returnPhotoURL it immediately returns undefined bcs the asynchronous method of loading/handling the image load just began.

So, you really need to wrap your script in a Promise then call it like below. NOTE: my sample script does some other things but shows the general concept:

returnPhotoURL().then(function(value){
    doc.getElementById("account-section-image").style.backgroundImage = "url('" + value + "')";
}); 


function returnPhotoURL(){
    return new Promise(function(resolve, reject){
        var img = new Image();
        //if the user does not have a photoURL let's try and get one from gravatar
        if (!firebase.auth().currentUser.photoURL) {
            //first we have to see if user han an email
            if(firebase.auth().currentUser.email){
                //set sign-in-button background image to gravatar url
                img.addEventListener('load', function() {
                    resolve (getGravatar(firebase.auth().currentUser.email, 48));
                }, false);
                img.addEventListener('error', function() {
                    resolve ('//rack.pub/media/fallbackImage.png');
                }, false);            
                img.src = getGravatar(firebase.auth().currentUser.email, 48);
            } else {
                resolve ('//rack.pub/media/fallbackImage.png');
            }
        } else {
            img.addEventListener('load', function() {
                resolve (firebase.auth().currentUser.photoURL);
            }, false);
            img.addEventListener('error', function() {
                resolve ('https://rack.pub/media/fallbackImage.png');
            }, false);      
            img.src = firebase.auth().currentUser.photoURL;
        }
    });
}

Intellij Idea: Importing Gradle project - getting JAVA_HOME not defined yet

Try starting IntelliJ from terminal. You can find application file under: /Applications/IntelliJ\ IDEA\ 14.app/Contents/MacOS

Passing Arrays to Function in C++

The syntaxes

int[]

and

int[X] // Where X is a compile-time positive integer

are exactly the same as

int*

when in a function parameter list (I left out the optional names).

Additionally, an array name decays to a pointer to the first element when passed to a function (and not passed by reference) so both int firstarray[3] and int secondarray[5] decay to int*s.

It also happens that both an array dereference and a pointer dereference with subscript syntax (subscript syntax is x[y]) yield an lvalue to the same element when you use the same index.

These three rules combine to make the code legal and work how you expect; it just passes pointers to the function, along with the length of the arrays which you cannot know after the arrays decay to pointers.

Create XML in Javascript

this work for me..

var xml  = parser.parseFromString('<?xml version="1.0" encoding="utf-8"?><root></root>', "application/xml");

developer.mozilla.org/en-US/docs/Web/API/DOMParser

Notepad++: Multiple words search in a file (may be in different lines)?

If you are using Notepad++ editor (like the tag of the question suggests), you can use the great "Find in Files" functionality.

Go to SearchFind in Files (Ctrl+Shift+F for the keyboard addicted) and enter:

  • Find What = (cat|town)

  • Filters = *.txt

  • Directory = enter the path of the directory you want to search in. You can check Follow current doc. to have the path of the current file to be filled.

  • Search mode = Regular Expression

Drag and drop a DLL to the GAC ("assembly") in windows server 2008 .net 4.0

In may case, I nedded to copy the gacutil.exe, gacutil.exe.config AND ALSO the gacutlrc.dll (from the 1033 directory)

Spring Data: "delete by" is supported?

@Query(value = "delete from addresses u where u.ADDRESS_ID LIKE %:addressId%", nativeQuery = true)
void deleteAddressByAddressId(@Param("addressId") String addressId);

Unable to install Maven on Windows: "JAVA_HOME is set to an invalid directory"

I ran into this issue with a Grails install.

The problem was my JAVA_HOME was c:\sun\jdk\ and my PATH has %JAVA_HOME%bin

I changed it to: JAVA_HOME= "c:\sun\jdk" and PATH="%JAVA_HOME%\bin"

It worked after that.

How To: Best way to draw table in console app (C#)

In case if this helps someone, this is a simple class I wrote for my need. You can change it easily to fit your needs.

using System.Collections.Generic;
using System.Linq;

namespace Utilities
{
    public class TablePrinter
    {
        private readonly string[] titles;
        private readonly List<int> lengths;
        private readonly List<string[]> rows = new List<string[]>();

        public TablePrinter(params string[] titles)
        {
            this.titles = titles;
            lengths = titles.Select(t => t.Length).ToList();
        }

        public void AddRow(params object[] row)
        {
            if (row.Length != titles.Length)
            {
                throw new System.Exception($"Added row length [{row.Length}] is not equal to title row length [{titles.Length}]");
            }
            rows.Add(row.Select(o => o.ToString()).ToArray());
            for (int i = 0; i < titles.Length; i++)
            {
                if (rows.Last()[i].Length > lengths[i])
                {
                    lengths[i] = rows.Last()[i].Length;
                }
            }
        }

        public void Print()
        {
            lengths.ForEach(l => System.Console.Write("+-" + new string('-', l) + '-'));
            System.Console.WriteLine("+");

            string line = "";
            for (int i = 0; i < titles.Length; i++)
            {
                line += "| " + titles[i].PadRight(lengths[i]) + ' ';
            }
            System.Console.WriteLine(line + "|");

            lengths.ForEach(l => System.Console.Write("+-" + new string('-', l) + '-'));
            System.Console.WriteLine("+");

            foreach (var row in rows)
            {
                line = "";
                for (int i = 0; i < row.Length; i++)
                {
                    if (int.TryParse(row[i], out int n))
                    {
                        line += "| " + row[i].PadLeft(lengths[i]) + ' ';  // numbers are padded to the left
                    }
                    else
                    {
                        line += "| " + row[i].PadRight(lengths[i]) + ' ';
                    }
                }
                System.Console.WriteLine(line + "|");
            }

            lengths.ForEach(l => System.Console.Write("+-" + new string('-', l) + '-'));
            System.Console.WriteLine("+");
        }
    }
}

Sample usage:

var t = new TablePrinter("id", "Column A", "Column B");
t.AddRow(1, "Val A1", "Val B1");
t.AddRow(2, "Val A2", "Val B2");
t.AddRow(100, "Val A100", "Val B100");
t.Print();

Output:

+-----+----------+----------+
| id  | Column A | Column B |
+-----+----------+----------+
|   1 | Val A1   | Val B1   |
|   2 | Val A2   | Val B2   |
| 100 | Val A100 | Val B100 |
+-----+----------+----------+

How to Set/Update State of StatefulWidget from other StatefulWidget in Flutter?

OLD: Create a global instance of _MyHomePageState. Use this instance in _SubState as _myHomePageState.setState

NEW: No need to create global instance. Instead just pass the parent instance to the child widget

CODE UPDATED AS PER FLUTTER 0.8.2:

import 'package:flutter/material.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(),
    );
  }
}

EdgeInsets globalMargin =
    const EdgeInsets.symmetric(horizontal: 20.0, vertical: 20.0);
TextStyle textStyle = const TextStyle(
  fontSize: 100.0,
  color: Colors.black,
);

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int number = 0;

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('SO Help'),
      ),
      body: new Column(
        children: <Widget>[
          new Text(
            number.toString(),
            style: textStyle,
          ),
          new GridView.count(
            crossAxisCount: 2,
            shrinkWrap: true,
            scrollDirection: Axis.vertical,
            children: <Widget>[
              new InkResponse(
                child: new Container(
                    margin: globalMargin,
                    color: Colors.green,
                    child: new Center(
                      child: new Text(
                        "+",
                        style: textStyle,
                      ),
                    )),
                onTap: () {
                  setState(() {
                    number = number + 1;
                  });
                },
              ),
              new Sub(this),
            ],
          ),
        ],
      ),
      floatingActionButton: new FloatingActionButton(
        onPressed: () {
          setState(() {});
        },
        child: new Icon(Icons.update),
      ),
    );
  }
}

class Sub extends StatelessWidget {

  _MyHomePageState parent;

  Sub(this.parent);

  @override
  Widget build(BuildContext context) {
    return new InkResponse(
      child: new Container(
          margin: globalMargin,
          color: Colors.red,
          child: new Center(
            child: new Text(
              "-",
              style: textStyle,
            ),
          )),
      onTap: () {
        this.parent.setState(() {
          this.parent.number --;
        });
      },
    );
  }
}

Just let me know if it works.

Debugging iframes with Chrome developer tools

When the iFrame points to your site like this:

<html>
  <head>
    <script type="text/javascript" src="/jquery.js"></script>
  </head>
  <body>
    <iframe id="my_frame" src="/wherev"></iframe>
  </body>
</html>

You can access iFrame DOM through this kind of thing.

var iframeBody = $(window.my_frame.document.getElementsByTagName("body")[0]);
iframeBody.append($("<h1/>").html("Hello world!"));

ImportError: No module named 'Queue'

import queue is lowercase q in Python 3.

Change Q to q and it will be fine.

(See code in https://stackoverflow.com/a/29688081/632951 for smart switching.)

Android 5.0 - Add header/footer to a RecyclerView

I haven't tried this, but I would simply add 1 (or 2, if you want both a header and footer) to the integer returned by getItemCount in your adapter. You can then override getItemViewType in your adapter to return a different integer when i==0: https://developer.android.com/reference/android/support/v7/widget/RecyclerView.Adapter.html#getItemViewType(int)

createViewHolder is then passed the integer you returned from getItemViewType, allowing you to create or configure the view holder differently for the header view: https://developer.android.com/reference/android/support/v7/widget/RecyclerView.Adapter.html#createViewHolder(android.view.ViewGroup, int)

Don't forget to subtract one from the position integer passed to bindViewHolder.

Groovy method with optional parameters

Can't be done as it stands... The code

def myMethod(pParm1='1', pParm2='2'){
    println "${pParm1}${pParm2}"
}

Basically makes groovy create the following methods:

Object myMethod( pParm1, pParm2 ) {
    println "$pParm1$pParm2"
}

Object myMethod( pParm1 ) {
    this.myMethod( pParm1, '2' )
}

Object myMethod() {
    this.myMethod( '1', '2' )
}

One alternative would be to have an optional Map as the first param:

def myMethod( Map map = [:], String mandatory1, String mandatory2 ){
    println "${mandatory1} ${mandatory2} ${map.parm1 ?: '1'} ${map.parm2 ?: '2'}"
}

myMethod( 'a', 'b' )                // prints 'a b 1 2'
myMethod( 'a', 'b', parm1:'value' ) // prints 'a b value 2'
myMethod( 'a', 'b', parm2:'2nd')    // prints 'a b 1 2nd'

Obviously, documenting this so other people know what goes in the magical map and what the defaults are is left to the reader ;-)

C++ create string of text and variables

In C++11 you can use std::to_string:

std::string var = "sometext" + std::to_string(somevar) + "sometext" + std::to_string(somevar);  

Can you force a React component to rerender without calling setState?

forceUpdate should be avoided because it deviates from a React mindset. The React docs cite an example of when forceUpdate might be used:

By default, when your component's state or props change, your component will re-render. However, if these change implicitly (eg: data deep within an object changes without changing the object itself) or if your render() method depends on some other data, you can tell React that it needs to re-run render() by calling forceUpdate().

However, I'd like to propose the idea that even with deeply nested objects, forceUpdate is unnecessary. By using an immutable data source tracking changes becomes cheap; a change will always result in a new object so we only need to check if the reference to the object has changed. You can use the library Immutable JS to implement immutable data objects into your app.

Normally you should try to avoid all uses of forceUpdate() and only read from this.props and this.state in render(). This makes your component "pure" and your application much simpler and more efficient.forceUpdate()

Changing the key of the element you want re-rendered will work. Set the key prop on your element via state and then when you want to update set state to have a new key.

<Element key={this.state.key} /> 

Then a change occurs and you reset the key

this.setState({ key: Math.random() });

I want to note that this will replace the element that the key is changing on. An example of where this could be useful is when you have a file input field that you would like to reset after an image upload.

While the true answer to the OP's question would be forceUpdate() I have found this solution helpful in different situations. I also want to note that if you find yourself using forceUpdate you may want to review your code and see if there is another way to do things.

NOTE 1-9-2019:

The above (changing the key) will completely replace the element. If you find yourself updating the key to make changes happen you probably have an issue somewhere else in your code. Using Math.random() in key will re-create the element with each render. I would NOT recommend updating the key like this as react uses the key to determine the best way to re-render things.

Apply function to each column in a data frame observing each columns existing data type

The reason that max works with apply is that apply is coercing your data frame to a matrix first, and a matrix can only hold one data type. So you end up with a matrix of characters. sapply is just a wrapper for lapply, so it is not surprising that both yield the same error.

The default behavior when you create a data frame is for categorical columns to be stored as factors. Unless you specify that it is an ordered factor, operations like max and min will be undefined, since R is assuming that you've created an unordered factor.

You can change this behavior by specifying options(stringsAsFactors = FALSE), which will change the default for the entire session, or you can pass stringsAsFactors = FALSE in the data.frame() construction call itself. Note that this just means that min and max will assume "alphabetical" ordering by default.

Or you can manually specify an ordering for each factor, although I doubt that's what you want to do.

Regardless, sapply will generally yield an atomic vector, which will entail converting everything to characters in many cases. One way around this is as follows:

#Some test data
d <- data.frame(v1 = runif(10), v2 = letters[1:10], 
                v3 = rnorm(10), v4 = LETTERS[1:10],stringsAsFactors = TRUE)

d[4,] <- NA

#Similar function to DWin's answer          
fun <- function(x){
    if(is.numeric(x)){max(x,na.rm = 1)}
    else{max(as.character(x),na.rm=1)}
}   

#Use colwise from plyr package
colwise(fun)(d)
         v1 v2       v3 v4
1 0.8478983  j 1.999435  J

get the value of DisplayName attribute

Try this code:

EnumEntity.item.GetType().GetFields()[(int)EnumEntity.item].CustomAttributes.ToArray()[0].NamedArguments[0].TypedValue.ToString()

It will give you the value of data attribute Name.

How to create and download a csv file from php script?

I don't have enough reputation to reply to @complex857 solution. It works great, but I had to add ; at the end of the Content-Disposition header. Without it the browser adds two dashes at the end of the filename (e.g. instead of "export.csv" the file gets saved as "export.csv--"). Probably it tries to sanitize \r\n at the end of the header line.

Correct line should look like this:

header('Content-Disposition: attachment;filename="'.$filename.'";');

In case when CSV has UTF-8 chars in it, you have to change the encoding to UTF-8 by changing the Content-Type line:

header('Content-Type: application/csv; charset=UTF-8');

Also, I find it more elegant to use rewind() instead of fseek():

rewind($f);

Thanks for your solution!

Java URL encoding of query string parameters

In android I would use this code:

Uri myUI = Uri.parse ("http://example.com/query").buildUpon().appendQueryParameter("q","random word A3500 bank 24").build();

Where Uri is a android.net.Uri

Jquery Ajax beforeSend and success,error & complete

It's actually much easier with jQuery's promise API:

$.ajax(
            type: "GET",
            url: requestURL,
        ).then((success) =>
            console.dir(success)
        ).failure((failureResponse) =>
            console.dir(failureResponse)
        )

Alternatively, you can pass in of bind functions to each result callback; the order of parameters is: (success, failure). So long as you specify a function with at least 1 parameter, you get access to the response. So, for example, if you wanted to check the response text, you could simply do:

$.ajax(
            type: "GET",
            url: @get("url") + "logout",
            beforeSend: (xhr) -> xhr.setRequestHeader("token", currentToken)
        ).failure((response) -> console.log "Request was unauthorized" if response.status is 401

How do I get java logging output to appear on a single line?

Eclipse config

Per screenshot, in Eclipse select "run as" then "Run Configurations..." and add the answer from Trevor Robinson with double quotes instead of quotes. If you miss the double quotes you'll get "could not find or load main class" errors.

How to change button background image on mouseOver?

In the case of winforms:

If you include the images to your resources you can do it like this, very simple and straight forward:

public Form1()
          {
               InitializeComponent();
               button1.MouseEnter += new EventHandler(button1_MouseEnter);
               button1.MouseLeave += new EventHandler(button1_MouseLeave);
          }

          void button1_MouseLeave(object sender, EventArgs e)
          {
               this.button1.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.img1));
          }


          void button1_MouseEnter(object sender, EventArgs e)
          {
               this.button1.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.img2));
          }

I would not recommend hardcoding image paths.

As you have altered your question ...

There is no (on)MouseOver in winforms afaik, there are MouseHover and MouseMove events, but if you change image on those, it will not change back, so the MouseEnter + MouseLeave are what you are looking for I think. Anyway, changing the image on Hover or Move :

in the constructor:
button1.MouseHover += new EventHandler(button1_MouseHover); 
button1.MouseMove += new MouseEventHandler(button1_MouseMove);

void button1_MouseMove(object sender, MouseEventArgs e)
          {
               this.button1.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.img2));
          }

          void button1_MouseHover(object sender, EventArgs e)
          {
               this.button1.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.img2));
          }

To add images to your resources: Projectproperties/resources/add/existing file

How to trace the path in a Breadth-First Search?

Very easy code. You keep appending the path each time you discover a node.

graph = {
         'A': set(['B', 'C']),
         'B': set(['A', 'D', 'E']),
         'C': set(['A', 'F']),
         'D': set(['B']),
         'E': set(['B', 'F']),
         'F': set(['C', 'E'])
         }
def retunShortestPath(graph, start, end):

    queue = [(start,[start])]
    visited = set()

    while queue:
        vertex, path = queue.pop(0)
        visited.add(vertex)
        for node in graph[vertex]:
            if node == end:
                return path + [end]
            else:
                if node not in visited:
                    visited.add(node)
                    queue.append((node, path + [node]))

req.body empty on posts

Even when i was learning node.js for the first time where i started learning it over web-app, i was having all these things done in well manner in my form, still i was not able to receive values in post request. After long debugging, i came to know that in the form i have provided enctype="multipart/form-data" due to which i was not able to get values. I simply removed it and it worked for me.

Pass multiple complex objects to a post/put Web API method

I know this is an old question, but I had the same issue and here is what I came up with and hopefully will be useful to someone. This will allow passing JSON formatted parameters individually in request URL (GET), as one single JSON object after ? (GET) or within single JSON body object (POST). My goal was RPC-style functionality.

Created a custom attribute and parameter binding, inheriting from HttpParameterBinding:

public class JSONParamBindingAttribute : Attribute
{

}

public class JSONParamBinding : HttpParameterBinding
{

    private static JsonSerializer _serializer = JsonSerializer.Create(new JsonSerializerSettings()
    {
        DateTimeZoneHandling = DateTimeZoneHandling.Utc
    });


    public JSONParamBinding(HttpParameterDescriptor descriptor)
        : base(descriptor)
    {
    }

    public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider,
                                                HttpActionContext actionContext,
                                                CancellationToken cancellationToken)
    {
        JObject jobj = GetJSONParameters(actionContext.Request);

        object value = null;

        JToken jTokenVal = null;
        if (!jobj.TryGetValue(Descriptor.ParameterName, out jTokenVal))
        {
            if (Descriptor.IsOptional)
                value = Descriptor.DefaultValue;
            else
                throw new MissingFieldException("Missing parameter : " + Descriptor.ParameterName);
        }
        else
        {
            try
            {
                value = jTokenVal.ToObject(Descriptor.ParameterType, _serializer);
            }
            catch (Newtonsoft.Json.JsonException e)
            {
                throw new HttpParseException(String.Join("", "Unable to parse parameter: ", Descriptor.ParameterName, ". Type: ", Descriptor.ParameterType.ToString()));
            }
        }

        // Set the binding result here
        SetValue(actionContext, value);

        // now, we can return a completed task with no result
        TaskCompletionSource<AsyncVoid> tcs = new TaskCompletionSource<AsyncVoid>();
        tcs.SetResult(default(AsyncVoid));
        return tcs.Task;
    }

    public static HttpParameterBinding HookupParameterBinding(HttpParameterDescriptor descriptor)
    {
        if (descriptor.ActionDescriptor.ControllerDescriptor.GetCustomAttributes<JSONParamBindingAttribute>().Count == 0 
            && descriptor.ActionDescriptor.GetCustomAttributes<JSONParamBindingAttribute>().Count == 0)
            return null;

        var supportedMethods = descriptor.ActionDescriptor.SupportedHttpMethods;

        if (supportedMethods.Contains(HttpMethod.Post) || supportedMethods.Contains(HttpMethod.Get))
        {
            return new JSONParamBinding(descriptor);
        }

        return null;
    }

    private JObject GetJSONParameters(HttpRequestMessage request)
    {
        JObject jobj = null;
        object result = null;
        if (!request.Properties.TryGetValue("ParamsJSObject", out result))
        {
            if (request.Method == HttpMethod.Post)
            {
                jobj = JObject.Parse(request.Content.ReadAsStringAsync().Result);
            }
            else if (request.RequestUri.Query.StartsWith("?%7B"))
            {
                jobj = JObject.Parse(HttpUtility.UrlDecode(request.RequestUri.Query).TrimStart('?'));
            }
            else
            {
                jobj = new JObject();
                foreach (var kvp in request.GetQueryNameValuePairs())
                {
                    jobj.Add(kvp.Key, JToken.Parse(kvp.Value));
                }
            }
            request.Properties.Add("ParamsJSObject", jobj);
        }
        else
        {
            jobj = (JObject)result;
        }

        return jobj;
    }



    private struct AsyncVoid
    {
    }
}

Inject binding rule inside WebApiConfig.cs's Register method:

        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.ParameterBindingRules.Insert(0, JSONParamBinding.HookupParameterBinding);

            config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
        }

This allows for controller actions with default parameter values and mixed complexity, as such:

[JSONParamBinding]
    [HttpPost, HttpGet]
    public Widget DoWidgetStuff(Widget widget, int stockCount, string comment="no comment")
    {
        ... do stuff, return Widget object
    }

example post body:

{ 
    "widget": { 
        "a": 1, 
        "b": "string", 
        "c": { "other": "things" } 
    }, 
    "stockCount": 42, 
    "comment": "sample code"
} 

or GET single param (needs URL encoding)

controllerPath/DoWidgetStuff?{"widget":{..},"comment":"test","stockCount":42}

or GET multiple param (needs URL encoding)

controllerPath/DoWidgetStuff?widget={..}&comment="test"&stockCount=42

Convert Unicode to ASCII without errors in Python

If you have a string line, you can use the .encode([encoding], [errors='strict']) method for strings to convert encoding types.

line = 'my big string'

line.encode('ascii', 'ignore')

For more information about handling ASCII and unicode in Python, this is a really useful site: https://docs.python.org/2/howto/unicode.html

How to format font style and color in echo

Are you trying to echo out a style or an inline style? An inline style would be like

echo "<p style=\"font-color: #ff0000;\">text here</p>";

SyntaxError: import declarations may only appear at top level of a module

I got this on Firefox (FF58). I fixed this with:

  1. It is still experimental on Firefox (from v54): You have to set to true the variable dom.moduleScripts.enabled in about:config

Source: Import page on mozilla (See Browser compatibility)

  1. Add type="module" to your script tag where you import the js file

<script type="module" src="appthatimports.js"></script>

  1. Import files have to be prefixed (./, /, ../ or http:// before)

import * from "./mylib.js"

For more examples, this blog post is good.

Python: How to get stdout after running os.system?

I would like to expand on the Windows solution. Using IDLE with Python 2.7.5, When I run this code from file Expts.py:

import subprocess
r = subprocess.check_output('cmd.exe dir',shell=False) 
print r

...in the Python Shell, I ONLY get the output corresponding to "cmd.exe"; the "dir" part is ignored. HOWEVER, when I add a switch such as /K or /C ...

import subprocess
r = subprocess.check_output('cmd.exe /K dir',shell=False) 
print r

...then in the Python Shell, I get all that I expect including the directory listing. Woohoo !

Now, if I try any of those same things in DOS Python command window, without the switch, or with the /K switch, it appears to make the window hang because it is running a subprocess cmd.exe and it awaiting further input - type 'exit' then hit [enter] to release. But with the /K switch it works perfectly and returns you to the python prompt. Allrightee then.

Went a step further...I thought this was cool...When I instead do this in Expts.py:

import subprocess
r = subprocess.call("cmd.exe dir",shell=False) 
print r

...a new DOS window pops open and remains there displaying only the results of "cmd.exe" not of "dir". When I add the /C switch, the DOS window opens and closes very fast before I can see anything (as expected, because /C terminates when done). When I instead add the /K switch, the DOS window pops open and remain, AND I get all the output I expect including the directory listing.

If I try the same thing (subprocess.call instead of subprocess.check_output) from a DOS Python command window; all output is within the same window, there are no popup windows. Without the switch, again the "dir" part is ignored, AND the prompt changes from the python prompt to the DOS prompt (since a cmd.exe subprocess is running in python; again type 'exit' and you will revert to the python prompt). Adding the /K switch prints out the directory listing and changes the prompt from python to DOS since /K does not terminate the subprocess. Changing the switch to /C gives us all the output expected AND returns to the python prompt since the subprocess terminates in accordance with /C.

Sorry for the long-winded response, but I am frustrated on this board with the many terse 'answers' which at best don't work (seems because they are not tested - like Eduard F's response above mine which is missing the switch) or worse, are so terse that they don't help much at all (e.g., 'try subprocess instead of os.system' ... yeah, OK, now what ??). In contrast, I have provided solutions which I tested, and showed how there are subtle differences between them. Took a lot of time but... Hope this helps.

Cannot use Server.MapPath

I know this post is a few years old, but what I do is add this line to the top of your class and you will still be able to user Server.MapPath

Dim Server = HttpContext.Current.Server

or u can make a function

Public Function MapPath(sPath as String)
    return HttpContext.Current.Server.MapPath(sPath)
End Function

I am all about making things easier. I have also added it to my Utilities class just in case i run into this again.

HTML+CSS: How to force div contents to stay in one line?

Everybody jumped on this one!!! I too made a fiddle:

http://jsfiddle.net/audetwebdesign/kh4aR/

RobAgar gets a point for pointing out white-space:nowrap first.

Couple of things here, you need overflow: hidden if you don't want to see the extra characters poking out into your layout.

Also, as mentioned, you could use white-space: pre (see EnderMB) keeping in mind that pre will not collapse white space whereas white-space: nowrap will.

How to validate phone numbers using regex

For anyone interested in doing something similar with Irish mobile phone numbers, here's a straightforward way of accomplishing it:

http://ilovenicii.com/?p=87

PHP


<?php
$pattern = "/^(083|086|085|086|087)\d{7}$/";
$phone = "087343266";

if (preg_match($pattern,$phone)) echo "Match";
else echo "Not match";

There is also a JQuery solution on that link.

EDIT:

jQuery solution:

    $(function(){
    //original field values
    var field_values = {
            //id        :  value
            'url'       : 'url',
            'yourname'  : 'yourname',
            'email'     : 'email',
            'phone'     : 'phone'
    };

        var url =$("input#url").val();
        var yourname =$("input#yourname").val();
        var email =$("input#email").val();
        var phone =$("input#phone").val();


    //inputfocus
    $('input#url').inputfocus({ value: field_values['url'] });
    $('input#yourname').inputfocus({ value: field_values['yourname'] });
    $('input#email').inputfocus({ value: field_values['email'] }); 
    $('input#phone').inputfocus({ value: field_values['phone'] });



    //reset progress bar
    $('#progress').css('width','0');
    $('#progress_text').html('0% Complete');

    //first_step
    $('form').submit(function(){ return false; });
    $('#submit_first').click(function(){
        //remove classes
        $('#first_step input').removeClass('error').removeClass('valid');

        //ckeck if inputs aren't empty
        var fields = $('#first_step input[type=text]');
        var error = 0;
        fields.each(function(){
            var value = $(this).val();
            if( value.length<12 || value==field_values[$(this).attr('id')] ) {
                $(this).addClass('error');
                $(this).effect("shake", { times:3 }, 50);

                error++;
            } else {
                $(this).addClass('valid');
            }
        });        

        if(!error) {
            if( $('#password').val() != $('#cpassword').val() ) {
                    $('#first_step input[type=password]').each(function(){
                        $(this).removeClass('valid').addClass('error');
                        $(this).effect("shake", { times:3 }, 50);
                    });

                    return false;
            } else {   
                //update progress bar
                $('#progress_text').html('33% Complete');
                $('#progress').css('width','113px');

                //slide steps
                $('#first_step').slideUp();
                $('#second_step').slideDown();     
            }               
        } else return false;
    });

    //second section
    $('#submit_second').click(function(){
        //remove classes
        $('#second_step input').removeClass('error').removeClass('valid');

        var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;  
        var fields = $('#second_step input[type=text]');
        var error = 0;
        fields.each(function(){
            var value = $(this).val();
            if( value.length<1 || value==field_values[$(this).attr('id')] || ( $(this).attr('id')=='email' && !emailPattern.test(value) ) ) {
                $(this).addClass('error');
                $(this).effect("shake", { times:3 }, 50);

                error++;
            } else {
                $(this).addClass('valid');
            }


        function validatePhone(phone) {
        var a = document.getElementById(phone).value;
        var filter = /^[0-9-+]+$/;
            if (filter.test(a)) {
                return true;
            }
            else {
                return false;
            }
        }

        $('#phone').blur(function(e) {
            if (validatePhone('txtPhone')) {
                $('#spnPhoneStatus').html('Valid');
                $('#spnPhoneStatus').css('color', 'green');
            }
            else {
                $('#spnPhoneStatus').html('Invalid');
            $('#spnPhoneStatus').css('color', 'red');
            }
        });

     });

        if(!error) {
                //update progress bar
                $('#progress_text').html('66% Complete');
                $('#progress').css('width','226px');

                //slide steps
                $('#second_step').slideUp();
                $('#fourth_step').slideDown();     
        } else return false;

    });


    $('#submit_second').click(function(){
        //update progress bar
        $('#progress_text').html('100% Complete');
        $('#progress').css('width','339px');

        //prepare the fourth step
        var fields = new Array(
            $('#url').val(),
            $('#yourname').val(),
            $('#email').val(),
            $('#phone').val()

        );
        var tr = $('#fourth_step tr');
        tr.each(function(){
            //alert( fields[$(this).index()] )
            $(this).children('td:nth-child(2)').html(fields[$(this).index()]);
        });

        //slide steps
        $('#third_step').slideUp();
        $('#fourth_step').slideDown();            
    });


    $('#submit_fourth').click(function(){

        url =$("input#url").val();
        yourname =$("input#yourname").val();
        email =$("input#email").val();
        phone =$("input#phone").val();

        //send information to server
        var dataString = 'url='+ url + '&yourname=' + yourname + '&email=' + email + '&phone=' + phone;  



        alert (dataString);//return false;  
            $.ajax({  
                type: "POST",  
                url: "http://clients.socialnetworkingsolutions.com/infobox/contact/",  
                data: "url="+url+"&yourname="+yourname+"&email="+email+'&phone=' + phone,
                cache: false,
                success: function(data) {  
                    console.log("form submitted");
                    alert("success");
                }
                });  
        return false;

   });


    //back button
    $('.back').click(function(){
        var container = $(this).parent('div'),
        previous  = container.prev();

        switch(previous.attr('id')) {
            case 'first_step' : $('#progress_text').html('0% Complete');
                  $('#progress').css('width','0px');
                       break;
            case 'second_step': $('#progress_text').html('33% Complete');
                  $('#progress').css('width','113px');
                       break;

            case 'third_step' : $('#progress_text').html('66% Complete');
                  $('#progress').css('width','226px');
                       break;

        default: break;
    }

    $(container).slideUp();
    $(previous).slideDown();
});


});

Source.

How do I select an element that has a certain class?

h2.myClass refers to all h2 with class="myClass".

.myClass h2 refers to all h2 that are children of (i.e. nested in) elements with class="myClass".

If you want the h2 in your HTML to appear blue, change the CSS to the following:

.myClass h2 {
    color: blue;
}

If you want to be able to reference that h2 by a class rather than its tag, you should leave the CSS as it is and give the h2 a class in the HTML:

<h2 class="myClass">This header should be BLUE to match the element.class selector</h2>

How to bring back "Browser mode" in IE11?

In IE11 we can change user agent to IE10, IE9 and even as windows phone. It is really good

Download File Using jQuery

By stating window.location.href = 'uploads/file.doc'; you show where you store your files. You might of course use .htacess to force the required behaviour for stored files, but this might not always be handful....

It is better to create a server side php-file and place this content in it:

header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.$_REQUEST['f']);
readfile('../some_folder/some_subfolder/'.$_REQUEST['f']); 
exit;

This code will return ANY file as a download without showing where you actually store it.

You open this php-file via window.location.href = 'scripts/this_php_file.php?f=downloaded_file';

Disabling vertical scrolling in UIScrollView

You need to pass 0 in content size to disable in which direction you want.

To disable vertical scrolling

scrollView.contentSize = CGSizeMake(scrollView.contentSize.width,0);

To disable horizontal scrolling

scrollView.contentSize = CGSizeMake(0,scrollView.contentSize.height);

Forcing Internet Explorer 9 to use standards document mode

To prevent quirks mode, define a 'doctype' like :

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">

To make IE render the page in IE9 document mode :

<meta http-equiv="x-ua-compatible" content="IE=9">

Please note that "IE=edge" will make IE render the page with the most recent document mode, rather than IE9 document mode.

How to loop through key/value object in Javascript?

for (var key in data) {
    alert("User " + data[key] + " is #" + key); // "User john is #234"
}

How do you add Boost libraries in CMakeLists.txt?

Adapting @LainIwakura's answer for modern CMake syntax with imported targets, this would be:

set(Boost_USE_STATIC_LIBS OFF) 
set(Boost_USE_MULTITHREADED ON)  
set(Boost_USE_STATIC_RUNTIME OFF) 
find_package(Boost 1.45.0 COMPONENTS filesystem regex) 

if(Boost_FOUND)
    add_executable(progname file1.cxx file2.cxx) 
    target_link_libraries(progname Boost::filesystem Boost::regex)
endif()

Note that it is not necessary anymore to specify the include directories manually, since it is already taken care of through the imported targets Boost::filesystem and Boost::regex.
regex and filesystem can be replaced by any boost libraries you need.

Best HTTP Authorization header type for JWT

Short answer

The Bearer authentication scheme is what you are looking for.

Long answer

Is it related to bears?

Errr... No :)

According to the Oxford Dictionaries, here's the definition of bearer:

bearer /'b??r?/
noun

  1. A person or thing that carries or holds something.

  2. A person who presents a cheque or other order to pay money.

The first definition includes the following synonyms: messenger, agent, conveyor, emissary, carrier, provider.

And here's the definition of bearer token according to the RFC 6750:

1.2. Terminology

Bearer Token

A security token with the property that any party in possession of the token (a "bearer") can use the token in any way that any other party in possession of it can. Using a bearer token does not require a bearer to prove possession of cryptographic key material (proof-of-possession).

The Bearer authentication scheme is registered in IANA and originally defined in the RFC 6750 for the OAuth 2.0 authorization framework, but nothing stops you from using the Bearer scheme for access tokens in applications that don't use OAuth 2.0.

Stick to the standards as much as you can and don't create your own authentication schemes.


An access token must be sent in the Authorization request header using the Bearer authentication scheme:

2.1. Authorization Request Header Field

When sending the access token in the Authorization request header field defined by HTTP/1.1, the client uses the Bearer authentication scheme to transmit the access token.

For example:

GET /resource HTTP/1.1
Host: server.example.com
Authorization: Bearer mF_9.B5f-4.1JqM

[...]

Clients SHOULD make authenticated requests with a bearer token using the Authorization request header field with the Bearer HTTP authorization scheme. [...]

In case of invalid or missing token, the Bearer scheme should be included in the WWW-Authenticate response header:

3. The WWW-Authenticate Response Header Field

If the protected resource request does not include authentication credentials or does not contain an access token that enables access to the protected resource, the resource server MUST include the HTTP WWW-Authenticate response header field [...].

All challenges defined by this specification MUST use the auth-scheme value Bearer. This scheme MUST be followed by one or more auth-param values. [...].

For example, in response to a protected resource request without authentication:

HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="example"

And in response to a protected resource request with an authentication attempt using an expired access token:

HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="example",
                         error="invalid_token",
                         error_description="The access token expired"

How to get the current date and time of your timezone in Java?

To get date and time of your zone.

Date date = new Date();
DateFormat df = new SimpleDateFormat("MM/dd/YYYY HH:mm a");
df.setTimeZone(TimeZone.getDefault());
df.format(date);

Getting data from selected datagridview row and which event?

You should check your designer file. Open Form1.Designer.cs and
find this line: windows Form Designer Generated Code.
Expand this and you will see a lot of code. So check Whether this line is there inside datagridview1 controls if not place it.

this.dataGridView1.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellClick); 

I hope it helps.

how to add values to an array of objects dynamically in javascript?

In Year 2019, we can use Javascript's ES6 Spread syntax to do it concisely and efficiently

data = [...data, {"label": 2, "value": 13}]

Examples

_x000D_
_x000D_
var data = [_x000D_
      {"label" : "1", "value" : 12},_x000D_
      {"label" : "1", "value" : 12},_x000D_
      {"label" : "1", "value" : 12},_x000D_
    ];_x000D_
    _x000D_
data = [...data, {"label" : "2", "value" : 14}] _x000D_
console.log(data)
_x000D_
_x000D_
_x000D_

For your case (i know it was in 2011), we can do it with map() & forEach() like below

_x000D_
_x000D_
var lab = ["1","2","3","4"];_x000D_
var val = [42,55,51,22];_x000D_
_x000D_
//Using forEach()_x000D_
var data = [];_x000D_
val.forEach((v,i) => _x000D_
   data= [...data, {"label": lab[i], "value":v}]_x000D_
)_x000D_
_x000D_
//Using map()_x000D_
var dataMap = val.map((v,i) => _x000D_
 ({"label": lab[i], "value":v})_x000D_
)_x000D_
_x000D_
console.log('data: ', data);_x000D_
console.log('dataMap : ', dataMap);
_x000D_
_x000D_
_x000D_

How to view method information in Android Studio?

It comes very handy if you create a keymap for functionalities you use very frequently. By default (if you select OSX 10.5+ keymap) :

  1. Ctrl+P : To see what parameters are expected by the function
  2. Command+J : To see the documentation
  3. Ctrl+Space : To see the autocomplete suggestions

enter image description here

Add a property to a JavaScript object using a variable as the name?

You can even make List of objects like this

var feeTypeList = [];
$('#feeTypeTable > tbody > tr').each(function (i, el) {
    var feeType = {};

    var $ID = $(this).find("input[id^=txtFeeType]").attr('id');

    feeType["feeTypeID"] = $('#ddlTerm').val();
    feeType["feeTypeName"] = $('#ddlProgram').val();
    feeType["feeTypeDescription"] = $('#ddlBatch').val();

    feeTypeList.push(feeType);
});

Add new element to an existing object

Use this:

myFunction.bookName = 'mybook';
myFunction.bookdesc = 'new';

Or, if you are using jQuery:

$(myFunction).extend({
    bookName:'mybook',
    bookdesc: 'new'
});

The push method is wrong because it belongs to the Array.prototype object.

To create a named object, try this:

var myObj = function(){
    this.property = 'foo';
    this.bar = function(){
    }
}
myObj.prototype.objProp = true;
var newObj = new myObj();

How to clear exisiting dropdownlist items when its content changes?

Just 2 simple steps to solve your issue

First of all check AppendDataBoundItems property and make it assign false

Secondly clear all the items using property .clear()

{
ddl1.Items.Clear();
ddl1.datasource = sql1;
ddl1.DataBind();
}

Can I set variables to undefined or pass undefined as an argument?

I'm a bit confused about Javascript undefined & null.

null generally behaves similarly to other scripting languages' concepts of the out-of-band ‘null’, ‘nil’ or ‘None’ objects.

undefined, on the other hand, is a weird JavaScript quirk. It's a singleton object that represents out-of-band values, essentially a second similar-but-different null. It comes up:

  1. When you call a function with fewer arguments than the arguments list in the function statement lists, the unpassed arguments are set to undefined. You can test for that with eg.:

    function dosomething(arg1, arg2) {
        if (arg2===undefined)
        arg2= DEFAULT_VALUE_FOR_ARG2;
        ...
    }
    

    With this method you can't tell the difference between dosomething(1) and dosomething(1, undefined); arg2 will be the same value in both. If you need to tell the difference you can look at arguments.length, but doing optional arguments like that isn't generally very readable.

  2. When a function has no return value;, it returns undefined. There's generally no need to use such a return result.

  3. When you declare a variable by having a var a statement in a block, but haven't yet assigned a value to it, it is undefined. Again, you shouldn't really ever need to rely on that.

  4. The spooky typeof operator returns 'undefined' when its operand is a simple variable that does not exist, instead of throwing an error as would normally happen if you tried to refer to it. (You can also give it a simple variable wrapped in parentheses, but not a full expression involving a non-existant variable.) Not much use for that, either.

  5. This is the controversial one. When you access a property of an object which doesn't exist, you don't immediately get an error like in every other language. Instead you get an undefined object. (And then when you try to use that undefined object later on in the script it'll go wrong in a weird way that's much more difficult to track down than if JavaScript had just thrown an error straight away.)

    This is often used to check for the existence of properties:

    if (o.prop!==undefined) // or often as truthiness test, if (o.prop)
       ...do something...
    

    However, because you can assign undefined like any other value:

    o.prop= undefined;
    

    that doesn't actually detect whether the property is there reliably. Better to use the in operator, which wasn't in the original Netscape version of JavaScript, but is available everywhere now:

    if ('prop' in o)
        ...
    

In summary, undefined is a JavaScript-specific mess, which confuses everyone. Apart from optional function arguments, where JS has no other more elegant mechanism, undefined should be avoided. It should never have been part of the language; null would have worked just fine for (2) and (3), and (4) is a misfeature that only exists because in the beginning JavaScript had no exceptions.

what does if (!testvar) actually do? Does it test for undefined and null or just undefined?

Such a ‘truthiness’ test checks against false, undefined, null, 0, NaN and empty strings. But in this case, yes, it is really undefined it is concerned with. IMO, it should be more explicit about that and say if (testvar!==undefined).

once a variable is defined can I clear it back to undefined (therefore deleting the variable).

You can certainly assign undefined to it, but that won't delete the variable. Only the delete object.property operator really removes things.

delete is really meant for properties rather than variables as such. Browsers will let you get away with straight delete variable, but it's not a good idea and won't work in ECMAScript Fifth Edition's strict mode. If you want to free up a reference to something so it can be garbage-collected, it would be more usual to say variable= null.

can I pass undefined as a parameter?

Yes.

SQL Query with Join, Count and Where

You have to use GROUP BY so you will have multiple records returned,

SELECT  COUNT(*) TotalCount, 
        b.category_id, 
        b.category_name 
FROM    table1 a
        INNER JOIN table2 b
            ON a.category_id = b.category_id 
WHERE   a.colour <> 'red'
GROUP   BY b.category_id, b.category_name

MongoDB and "joins"

It's no join since the relationship will only be evaluated when needed. A join (in a SQL database) on the other hand will resolve relationships and return them as if they were a single table (you "join two tables into one").

You can read more about DBRef here: http://docs.mongodb.org/manual/applications/database-references/

There are two possible solutions for resolving references. One is to do it manually, as you have almost described. Just save a document's _id in another document's other_id, then write your own function to resolve the relationship. The other solution is to use DBRefs as described on the manual page above, which will make MongoDB resolve the relationship client-side on demand. Which solution you choose does not matter so much because both methods will resolve the relationship client-side (note that a SQL database resolves joins on the server-side).

Change the location of the ~ directory in a Windows install of Git Bash

1.Right click to Gitbash shortcut choose Properties
2.Choose "Shortcut" tab
3.Type your starting directory to "Start in" field
4.Remove "--cd-to-home" part from "Target" field

SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) symfony2

'default' => env('DB_CONNECTION', 'mysql'),

add this in your code

Resize jqGrid when browser is resized?

As a follow-up:

The previous code shown in this post was eventually abandoned because it was unreliable. I am now using the following API function to resize the grid, as recommended by the jqGrid documentation:

jQuery("#targetGrid").setGridWidth(width);

To do the actual resizing, a function implementing the following logic is bound to the window's resize event:

  • Calculate the width of the grid using its parent's clientWidth and (if that is not available) its offsetWidth attribute.

  • Perform a sanity check to make sure width has changed more than x pixels (to work around some application-specific problems)

  • Finally, use setGridWidth() to change the grid's width

Here is example code to handle resizing:

jQuery(window).bind('resize', function() {

    // Get width of parent container
    var width = jQuery(targetContainer).attr('clientWidth');
    if (width == null || width < 1){
        // For IE, revert to offsetWidth if necessary
        width = jQuery(targetContainer).attr('offsetWidth');
    }
    width = width - 2; // Fudge factor to prevent horizontal scrollbars
    if (width > 0 &&
        // Only resize if new width exceeds a minimal threshold
        // Fixes IE issue with in-place resizing when mousing-over frame bars
        Math.abs(width - jQuery(targetGrid).width()) > 5)
    {
        jQuery(targetGrid).setGridWidth(width);
    }

}).trigger('resize');

And example markup:

<div id="grid_container">
    <table id="grid"></table>
    <div id="grid_pgr"></div>
</div>

how to convert current date to YYYY-MM-DD format with angular 2

Example as per doc

@Component({
  selector: 'date-pipe',
  template: `<div>
    <p>Today is {{today | date}}</p>
    <p>Or if you prefer, {{today | date:'fullDate'}}</p>
    <p>The time is {{today | date:'jmZ'}}</p>
  </div>`
})
export class DatePipeComponent {
  today: number = Date.now();
}

Template

{{ dateObj | date }}               // output is 'Jun 15, 2015'
{{ dateObj | date:'medium' }}      // output is 'Jun 15, 2015, 9:43:11 PM'
{{ dateObj | date:'shortTime' }}   // output is '9:43 PM'
{{ dateObj | date:'mmss' }}        // output is '43:11'
{{dateObj  | date: 'dd/MM/yyyy'}} // 15/06/2015

To Use in your component.

@Injectable()
import { DatePipe } from '@angular/common';
class MyService {

  constructor(private datePipe: DatePipe) {}

  transformDate(date) {
    this.datePipe.transform(myDate, 'yyyy-MM-dd'); //whatever format you need. 
  }
}

In your app.module.ts

providers: [DatePipe,...] 

all you have to do is use this service now.

How to make div go behind another div?

To answer the question in a general manner:

Using z-index will allow you to control this. see z-index at csstricks.

The element of higher z-index will be displayed on top of elements of lower z-index.

For instance, take the following HTML:

<div id="first">first</div>
<div id="second">second</div>

If I have the following CSS:

#first {
    position: fixed;
    z-index: 2;
}

#second {
    position: fixed;
    z-index: 1;
}

#first wil be on top of #second.

But specifically in your case:

The div element is a child of the div that you wish to put in front. This is not logically possible.

How to efficiently use try...catch blocks in PHP

It's more readable a single try catch block. If its important identify a kind of error I recommend customize your Exceptions.

try {
  $tableAresults = $dbHandler->doSomethingWithTableA();
  $tableBresults = $dbHandler->doSomethingElseWithTableB();
} catch (TableAException $e){
  throw $e;
} catch (Exception $e) {
  throw $e;
}

How can I get npm start at a different directory?

I came here from google so it might be relevant to others: for yarn you could use:

yarn --cwd /path/to/your/app run start 

Rails - passing parameters in link_to

link_to "+ Service", controller_action_path(:account_id => acct.id)

If it is still not working check the path:

$ rake routes

pandas python how to count the number of records or rows in a dataframe

Regards to your question... counting one Field? I decided to make it a question, but I hope it helps...

Say I have the following DataFrame

import numpy as np
import pandas as pd

df = pd.DataFrame(np.random.normal(0, 1, (5, 2)), columns=["A", "B"])

You could count a single column by

df.A.count()
#or
df['A'].count()

both evaluate to 5.

The cool thing (or one of many w.r.t. pandas) is that if you have NA values, count takes that into consideration.

So if I did

df['A'][1::2] = np.NAN
df.count()

The result would be

 A    3
 B    5