Programs & Examples On #Openform

How to change column width in DataGridView?

Set the "AutoSizeColumnsMode" property to "Fill".. By default it is set to 'NONE'. Now columns will be filled across the DatagridView. Then you can set the width of other columns accordingly.

DataGridView1.Columns[0].Width=100;// The id column 
DataGridView1.Columns[1].Width=200;// The abbrevation columln
//Third Colulmns 'description' will automatically be resized to fill the remaining 
//space

replace anchor text with jquery

Try this, in case of id

$("#YourId").text('Your text');

OR this, in case of class

$(".YourClassName").text('Your text');

How to check if variable's type matches Type stored in a variable

The other answers all contain significant omissions.

The is operator does not check if the runtime type of the operand is exactly the given type; rather, it checks to see if the runtime type is compatible with the given type:

class Animal {}
class Tiger : Animal {}
...
object x = new Tiger();
bool b1 = x is Tiger; // true
bool b2 = x is Animal; // true also! Every tiger is an animal.

But checking for type identity with reflection checks for identity, not for compatibility

bool b5 = x.GetType() == typeof(Tiger); // true
bool b6 = x.GetType() == typeof(Animal); // false! even though x is an animal

or with the type variable
bool b7 = t == typeof(Tiger); // true
bool b8 = t == typeof(Animal); // false! even though x is an 

If that's not what you want, then you probably want IsAssignableFrom:

bool b9 = typeof(Tiger).IsAssignableFrom(x.GetType()); // true
bool b10 = typeof(Animal).IsAssignableFrom(x.GetType()); // true! A variable of type Animal may be assigned a Tiger.

or with the type variable
bool b11 = t.IsAssignableFrom(x.GetType()); // true
bool b12 = t.IsAssignableFrom(x.GetType()); // true! A 

How to disable EditText in Android

The XML editable property is deprecated since API LEVEL 15.

You should use now the inputType property with the value none. But there is a bug that makes this functionality useless.

Here you can follow the issue status.

Get the distance between two geo points

a = sin²(?f/2) + cos f1 · cos f2 · sin²(??/2)

c = 2 · atan2( va, v(1-a) )

distance = R · c

where f is latitude, ? is longitude, R is earth’s radius (mean radius = 6,371km);

note that angles need to be in radians to pass to trig functions!

fun distanceInMeter(firstLocation: Location, secondLocation: Location): Double {
    val earthRadius = 6371000.0
    val deltaLatitudeDegree = (firstLocation.latitude - secondLocation.latitude) * Math.PI / 180f
    val deltaLongitudeDegree = (firstLocation.longitude - secondLocation.longitude) * Math.PI / 180f
    val a = sin(deltaLatitudeDegree / 2).pow(2) +
            cos(firstLocation.latitude * Math.PI / 180f) * cos(secondLocation.latitude * Math.PI / 180f) *
            sin(deltaLongitudeDegree / 2).pow(2)
    val c = 2f * atan2(sqrt(a), sqrt(1 - a))
    return earthRadius * c
}


data class Location(val latitude: Double, val longitude: Double)

Combine two data frames by rows (rbind) when they have different sets of columns

Just for the documentation. You can try the Stack library and its function Stack in the following form:

Stack(df_1, df_2)

I have also the impression that it is faster than other methods for large data sets.

How to make link not change color after visited?

For application on all the anchor tags, use

CSS

a:visited{
    color:blue;
}

For application on only some of the anchor tags, use

CSS

.linkcolor a:visited{
    color:blue;
}

HTML

<span class="linkcolor"><a href="http://stackoverflow.com/" target="_blank">Go to Home</a></span>

Error :The remote server returned an error: (401) Unauthorized

Shouldn't you be providing the credentials for your site, instead of passing the DefaultCredentials?

Something like request.Credentials = new NetworkCredential("UserName", "PassWord");

Also, remove request.UseDefaultCredentials = true; request.PreAuthenticate = true;

Change Name of Import in Java, or import two classes with the same name

Today I filed a JEP draft to OpenJDK about this aliasing feature. I hope they will reconsider it.

If you are interested, you can find a JEP draft here: https://gist.github.com/cardil/b29a81efd64a09585076fe00e3d34de7

app-release-unsigned.apk is not signed

i also appear this problem,and my code below

        storeFile file(properties.getProperty("filepath"))
        storePassword properties.getProperty("keypassword")
        keyAlias properties.getProperty("keyAlias")
        keyPassword properties.getProperty("keypassword")

the reason is property name error,it should be keyPassword not keypassword

How do I make CMake output into a 'bin' dir?

As to me I am using cmake 3.5, the below(set variable) does not work:

set(
      ARCHIVE_OUTPUT_DIRECTORY "/home/xy/cmake_practice/lib/"
      LIBRARY_OUTPUT_DIRECTORY "/home/xy/cmake_practice/lib/"
      RUNTIME_OUTPUT_DIRECTORY "/home/xy/cmake_practice/bin/"
)

but this works(set set_target_properties):

set_target_properties(demo5
    PROPERTIES
    ARCHIVE_OUTPUT_DIRECTORY "/home/xy/cmake_practice/lib/"
    LIBRARY_OUTPUT_DIRECTORY "/home/xy/cmake_practice/lib/"
    RUNTIME_OUTPUT_DIRECTORY "/home/xy/cmake_practice/bin/"
)

How can I access an internal class from an external assembly?

Well, you can't. Internal classes can't be visible outside of their assembly, so no explicit way to access it directly -AFAIK of course. The only way is to use runtime late-binding via reflection, then you can invoke methods and properties from the internal class indirectly.

Getting a machine's external IP address with Python

If the machine is being a firewall then your solution is a very sensible one: the alternative being able to query the firewall which ends-up being very dependent on the type of firewall (if at all possible).

What is VanillaJS?

VanillaJS === JavaScript i.e.VanillaJS is native JavaScript

Why, Vanilla says it all!!!

Computer software, and sometimes also other computing-related systems like computer hardware or algorithms, are called vanilla when not customized from their original form, meaning that they are used without any customization or updates applied to them (Refer this article). So Vanilla often refers to pure or plain.

In the English language Vanilla has a similar meaning, In information technology, vanilla (pronounced vah-NIHL-uh ) is an adjective meaning plain or basic. Or having no special or extra features, ordinary or standard.

So why name it VanillaJS? As the accepted answer says some bosses want to work with a framework (because it's more organized and flexible and do all the things we want??) but simply JavaScript will do the job. Yet you need to add a framework somewhere. Use VanillaJS...

Is it a Joke? YES

Want some fun? Where can you find it, http://vanilla-js.com/ Download and see for yourself!!! It's 0 bytes uncompressed, 25 bytes gzipped :D

Found this pun on internet regarding JS frameworks (Not to condemn the existing JS frameworks though, they'll make life really easy :)), enter image description here

Also refer,

How do I install boto?

Installing Boto depends on the Operating system. For e.g in Ubuntu you can use the aptitude command:

sudo apt-get install python-boto

Or you can download the boto code from their site and move into the unzipped directory to run

python setup.py install

how to return index of a sorted list?

You can do this with numpy's argsort method if you have numpy available:

>>> import numpy
>>> vals = numpy.array([2,3,1,4,5])
>>> vals
array([2, 3, 1, 4, 5])
>>> sort_index = numpy.argsort(vals)
>>> sort_index
array([2, 0, 1, 3, 4])

If not available, taken from this question, this is the fastest method:

>>> vals = [2,3,1,4,5]
>>> sorted(range(len(vals)), key=vals.__getitem__)
[2, 0, 1, 3, 4]

removing html element styles via javascript

Remove removeProperty

_x000D_
_x000D_
var el=document.getElementById("id");


el.style.removeProperty('display')

console.log("display removed"+el.style["display"])

console.log("color "+el.style["color"])
_x000D_
<div id="id" style="display:block;color:red">s</div>
_x000D_
_x000D_
_x000D_

CMake not able to find OpenSSL library

@Morwenn is right. You need to config the openssl DIR. Before that you may need to make sure you have it. you should check whether you have it. first run openssl version,then if you have it you can win + r run openssl and you win find the core dir since it may not name as openssl in your system.

enter image description here

enter image description here

How do I configure HikariCP in my Spring Boot app in my application.properties files?

I was facing issues and the problem was a whitespace at the end of spring.datasource.type = com.zaxxer.hikari.HikariDataSource

Failed to decode downloaded font

For me, the mistake was forgetting to put FTP into binary mode before uploading the font files.

Edit

You can test for this by uploading other types of binary data like images. If they also fail to display, then this may be your issue.

How to add RSA key to authorized_keys file?

There is already a command in the ssh suite to do this automatically for you. I.e log into a remote host and add the public key to that computers authorized_keys file.

ssh-copy-id -i /path/to/key/file [email protected]

If the key you are installing is ~/.ssh/id_rsa then you can even drop the -i flag completely.

Much better than manually doing it!

What is difference between cacerts and keystore?

Check your JAVA_HOME path. As systems looks for a java.policy file which is located in JAVA_HOME/jre/lib/security. Your JAVA_HOME should always be ../JAVA/JDK.

Convert seconds to Hour:Minute:Second

Just in case anyone else is looking for a simple function to return this nicely formatted (I know it is not the format the OP asked for), this is what I've just come up with. Thanks to @mughal for the code this was based on.

function format_timer_result($time_in_seconds){
    $time_in_seconds = ceil($time_in_seconds);

    // Check for 0
    if ($time_in_seconds == 0){
        return 'Less than a second';
    }

    // Days
    $days = floor($time_in_seconds / (60 * 60 * 24));
    $time_in_seconds -= $days * (60 * 60 * 24);

    // Hours
    $hours = floor($time_in_seconds / (60 * 60));
    $time_in_seconds -= $hours * (60 * 60);

    // Minutes
    $minutes = floor($time_in_seconds / 60);
    $time_in_seconds -= $minutes * 60;

    // Seconds
    $seconds = floor($time_in_seconds);

    // Format for return
    $return = '';
    if ($days > 0){
        $return .= $days . ' day' . ($days == 1 ? '' : 's'). ' ';
    }
    if ($hours > 0){
        $return .= $hours . ' hour' . ($hours == 1 ? '' : 's') . ' ';
    }
    if ($minutes > 0){
        $return .= $minutes . ' minute' . ($minutes == 1 ? '' : 's') . ' ';
    }
    if ($seconds > 0){
        $return .= $seconds . ' second' . ($seconds == 1 ? '' : 's') . ' ';
    }
    $return = trim($return);

    return $return;
}

Take a screenshot via a Python script on Linux

import ImageGrab
img = ImageGrab.grab()
img.save('test.jpg','JPEG')

this requires Python Imaging Library

Finding first and last index of some value in a list in Python

Python lists have the index() method, which you can use to find the position of the first occurrence of an item in a list. Note that list.index() raises ValueError when the item is not present in the list, so you may need to wrap it in try/except:

try:
    idx = lst.index(value)
except ValueError:
    idx = None

To find the position of the last occurrence of an item in a list efficiently (i.e. without creating a reversed intermediate list) you can use this function:

def rindex(lst, value):
    for i, v in enumerate(reversed(lst)):
        if v == value:
            return len(lst) - i - 1  # return the index in the original list
    return None    

print(rindex([1, 2, 3], 3))     # 2
print(rindex([3, 2, 1, 3], 3))  # 3
print(rindex([3, 2, 1, 3], 4))  # None

How to round up a number in Javascript?

Little late but, can create a reusable javascript function for this purpose:

// Arguments: number to round, number of decimal places
function roundNumber(rnum, rlength) { 
    var newnumber = Math.round(rnum * Math.pow(10, rlength)) / Math.pow(10, rlength);
    return newnumber;
}

Call the function as

alert(roundNumber(192.168,2));

java.io.StreamCorruptedException: invalid stream header: 7371007E

when I send only one object from the client to server all works well.

when I attempt to send several objects one after another on the same stream I get StreamCorruptedException.

Actually, your client code is writing one object to the server and reading multiple objects from the server. And there is nothing on the server side that is writing the objects that the client is trying to read.

Cannot GET / Nodejs Error

Much like leonardocsouza, I had the same problem. To clarify a bit, this is what my folder structure looked like when I ran node server.js

node_modules/
app/
  index.html
  server.js

After printing out the __dirname path, I realized that the __dirname path was where my server was running (app/).

So, the answer to your question is this:

If your server.js file is in the same folder as the files you are trying to render, then

app.use( express.static( path.join( application_root, 'site') ) );

should actually be

app.use(express.static(application_root));

The only time you would want to use the original syntax that you had would be if you had a folder tree like so:

app/
  index.html
node_modules
server.js

where index.html is in the app/ directory, whereas server.js is in the root directory (i.e. the same level as the app/ directory).

Side note: Intead of calling the path utility, you can use the syntax application_root + 'site' to join a path.

Overall, your code could look like:

// Module dependencies.
var application_root = __dirname,
express = require( 'express' ), //Web framework
mongoose = require( 'mongoose' ); //MongoDB integration

//Create server
var app = express();

// Configure server
app.configure( function() {

    //Don't change anything here...

    //Where to serve static content
    app.use( express.static( application_root ) );

    //Nothing changes here either...
});

//Start server --- No changes made here
var port = 5000;
app.listen( port, function() {
    console.log( 'Express server listening on port %d in %s mode', port, app.settings.env );
});

Batch script to find and replace a string in text file without creating an extra output file for storing the modified file

@echo off 
    setlocal enableextensions disabledelayedexpansion

    set "search=%1"
    set "replace=%2"

    set "textFile=Input.txt"

    for /f "delims=" %%i in ('type "%textFile%" ^& break ^> "%textFile%" ') do (
        set "line=%%i"
        setlocal enabledelayedexpansion
        >>"%textFile%" echo(!line:%search%=%replace%!
        endlocal
    )

for /f will read all the data (generated by the type comamnd) before starting to process it. In the subprocess started to execute the type, we include a redirection overwritting the file (so it is emptied). Once the do clause starts to execute (the content of the file is in memory to be processed) the output is appended to the file.

Can't run Curl command inside my Docker Container

Ran into this same issue while using the CURL command inside my Dockerfile. As Gilles pointed out, we have to install curl first. These are the commands to be added in the 'Dockerfile'.

FROM ubuntu:16.04

# Install prerequisites
RUN apt-get update && apt-get install -y \
curl
CMD /bin/bash

How can I use JavaScript in Java?

Rhino is what you are looking for.

Rhino is an open-source implementation of JavaScript written entirely in Java. It is typically embedded into Java applications to provide scripting to end users.

Update: Now Nashorn, which is more performant JavaScript Engine for Java, is available with jdk8.

How to check the function's return value if true or false

Wrong syntax. You can't compare a Boolean to a string like "false" or "true". In your case, just test it's inverse:

if(!ValidateForm()) { ...

You could test against the constant false, but it's rather ugly and generally frowned upon:

if(ValidateForm() == false) { ...

Java: String - add character n-times

public String appendNewStringToExisting(String exisitingString, String newString, int number) {
    StringBuilder builder = new StringBuilder(exisitingString);
    for(int iDx = 0; iDx < number; iDx++){
        builder.append(newString);
    }
    return builder.toString();
}

How can I append a string to an existing field in MySQL?

You need to use the CONCAT() function in MySQL for string concatenation:

UPDATE categories SET code = CONCAT(code, '_standard') WHERE id = 1;

Looking for a 'cmake clean' command to clear up CMake output

Simply issuing rm CMakeCache.txt works for me too.

Postgresql -bash: psql: command not found

In case you are running it on Fedora or CentOS, this is what worked for me (PostgreSQL 9.6):

In terminal:

$ sudo visudo -f /etc/sudoers

modify the following text from:

Defaults    secure_path = /sbin:/bin:/usr/sbin:/usr/bin

to

Defaults    secure_path = /sbin:/bin:/usr/sbin:/usr/bin:/usr/pgsql-9.6/bin

exit, then:

$ printenv PATH

$ sudo su postgres

$ psql

To exit postgreSQL terminal, you need to digit:

$ \q

Source: https://serverfault.com/questions/541847/why-doesnt-sudo-know-where-psql-is#comment623883_541880

How do I bind the enter key to a function in tkinter?

Another alternative is to use a lambda:

ent.bind("<Return>", (lambda event: name_of_function()))

Full code:

from tkinter import *
from tkinter.messagebox import showinfo

def reply(name):
    showinfo(title="Reply", message = "Hello %s!" % name)


top = Tk()
top.title("Echo")
top.iconbitmap("Iconshock-Folder-Gallery.ico")

Label(top, text="Enter your name:").pack(side=TOP)
ent = Entry(top)
ent.bind("<Return>", (lambda event: reply(ent.get())))
ent.pack(side=TOP)
btn = Button(top,text="Submit", command=(lambda: reply(ent.get())))
btn.pack(side=LEFT)

top.mainloop()

As you can see, creating a lambda function with an unused variable "event" solves the problem.

How can I run an EXE program from a Windows Service using C#?

First, we are going to create a Windows Service that runs under the System account. This service will be responsible for spawning an interactive process within the currently active User’s Session. This newly created process will display a UI and run with full admin rights. When the first User logs on to the computer, this service will be started and will be running in Session0; however the process that this service spawns will be running on the desktop of the currently logged on User. We will refer to this service as the LoaderService.

Next, the winlogon.exe process is responsible for managing User login and logout procedures. We know that every User who logs on to the computer will have a unique Session ID and a corresponding winlogon.exe process associated with their Session. Now, we mentioned above, the LoaderService runs under the System account. We also confirmed that each winlogon.exe process on the computer runs under the System account. Because the System account is the owner of both the LoaderService and the winlogon.exe processes, our LoaderService can copy the access token (and Session ID) of the winlogon.exe process and then call the Win32 API function CreateProcessAsUser to launch a process into the currently active Session of the logged on User. Since the Session ID located within the access token of the copied winlogon.exe process is greater than 0, we can launch an interactive process using that token.

Try this one. Subverting Vista UAC in Both 32 and 64 bit Architectures

web-api POST body object always null

This is a little old one and my answer will go down to the last place but even so I would like to share my experience.

Tried every suggestion but still having the same "null" value in a PUT [FromBody].

Finally found it was all about Date format while JSON serializing the EndDate property of my Angular Object.

No error was thrown, just received an empty FromBody object....

SPAN vs DIV (inline-block)

I know this Q is old, but why not use all DIVs instead of the SPANs? Then everything plays all happy together.

Example:

<div> 
   <div> content1(divs,p, spans, etc) </div> 
   <div> content2(divs,p, spans, etc) </div> 
   <div> content3(divs,p, spans, etc) </div> 
</div> 
<div> 
   <div> content4(divs,p, spans, etc) </div> 
   <div> content5(divs,p, spans, etc) </div> 
   <div> content6(divs,p, spans, etc) </div> 
</div>

TortoiseSVN icons overlay not showing after updating to Windows 10

svn upgrade the working copy. In my case, Jenkins never did a complete fresh checkout and hence the working copy was out of date.

DataGridView checkbox column - value and functionality

Here's a one liner answer for this question

List<DataGridViewRow> list = DataGridView1.Rows.Cast<DataGridViewRow>().Where(k => Convert.ToBoolean(k.Cells[CheckBoxColumn1.Name].Value) == true).ToList();

Change bootstrap navbar background color and font color

Most likely these classes are already defined by Bootstrap, make sure that your CSS file that you want to override the classes with is called AFTER the Bootstrap CSS.

<link rel="stylesheet" href="css/bootstrap.css" /> <!-- Call Bootstrap first -->
<link rel="stylesheet" href="css/bootstrap-override.css" /> <!-- Call override CSS second -->

Otherwise, you can put !important at the end of your CSS like this: color:#ffffff!important; but I would advise against using !important at all costs.

JUNIT Test class in Eclipse - java.lang.ClassNotFoundException

what worked for me is to remove the runconfiguration of the test. Then right click the testclass and click run as junit test.

now it recreates a correct run config for me.

Axios Delete request with body and headers?

I encountered the same problem... I solved it by creating a custom axios instance. and using that to make a authenticated delete request..

const token = localStorage.getItem('token');
const request = axios.create({
        headers: {
            Authorization: token
        }
    });

await request.delete('<your route>, { data: { <your data> }});

Installing PHP Zip Extension

The best way to install the Zip extension in php7.2 on CentOS would be as below:

  1. Find the available extention by searching with yum command

    yum search zip

  2. This will list all the zip packages. We need to look for the php7.2 zip package enter image description here

  1. Then if your php version is 7.2 then run the command

    yum install ea-php72-php-zip

This will definetly resolve your issue.

Cheers !!

OpenSSL: PEM routines:PEM_read_bio:no start line:pem_lib.c:703:Expecting: TRUSTED CERTIFICATE

Change encoding in notepad++ UTF-8 with BOM. That is how it worked for me

How to fix: "You need to use a Theme.AppCompat theme (or descendant) with this activity"

If you add the android:theme="@style/Theme.AppCompat.Light" to <application> in AndroidManifest.xml file, problem is solving.

Using 'sudo apt-get install build-essentials'

Try 'build-essential' instead.

How to simulate "Press any key to continue?"

On Windows:

system("pause");

and on Mac and Linux:

system("read");

will output "Press any key to continue..." and obviously, wait for any key to be pressed. I hope thats what you meant

React Native: Possible unhandled promise rejection

You should add the catch() to the end of the Api call. When your code hits the catch() it doesn't return anything, so data is undefined when you try to use setState() on it. The error message actually tells you this too :)

Create a string of variable length, filled with a repeated character

You can use the first line of the function as a one-liner if you like:

function repeat(str, len) {
    while (str.length < len) str += str.substr(0, len-str.length);
    return str;
}

Using Tkinter in python to edit the title bar

Having just done this myself you can do it this way:

from tkinter import Tk, Button, Frame, Entry, END

class ABC(Frame):
    def __init__(self, parent=None):
        Frame.__init__(self, parent)
        self.parent = parent
        self.pack()
        ABC.make_widgets(self)

    def make_widgets(self):
        self.parent.title("Simple Prog")

You will see the title change, and you won't get two windows. I've left my parent as master as in the Tkinter reference stuff in the python library documentation.

Getting error "The package appears to be corrupt" while installing apk file

In my case; If you receive this error while updating your application, It may be because of the target SDK version. In such case you will receive this error on logs;

"Package com.android.myapp new target SDK 22 doesn't support runtime permissions but the old target SDK 23 does"

This is because your previous aplication was build with a higher version of sdk. If your new app was build with 22 and your installed application was build with 23, you will get The package appears to be corrupt error on update.

Is there a way to iterate over a dictionary?

This is iteration using block approach:

    NSDictionary *dict = @{@"key1":@1, @"key2":@2, @"key3":@3};

    [dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        NSLog(@"%@->%@",key,obj);
        // Set stop to YES when you wanted to break the iteration.
    }];

With autocompletion is very fast to set, and you do not have to worry about writing iteration envelope.

Describe table structure

SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'student'

await is only valid in async function

If you are writing a Chrome Extension and you get this error for your code at root, you can fix it using the following "workaround":

async function run() {
    // Your async code here
    const beers = await fetch("https://api.punkapi.com/v2/beers");
}

run();

Basically you have to wrap your async code in an async function and then call the function without awaiting it.

Room persistance library. Delete all

Use clearAllTables() with RXJava like below inorder to avoid java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time.

Completable.fromAction(new Action() {
        @Override
        public void run() throws Exception {
            getRoomDatabase().clearAllTables();
        }
    }).subscribeOn(getSchedulerProvider().io())
            .observeOn(getSchedulerProvider().ui())
            .subscribe(new Action() {
                @Override
                public void run() throws Exception {
                    Log.d(TAG, "--- clearAllTables(): run() ---");
                    getInteractor().setUserAsLoggedOut();
                    getMvpView().openLoginActivity();
                }
            }, new Consumer<Throwable>() {
                @Override
                public void accept(Throwable throwable) throws Exception {
                    Log.d(TAG, "--- clearAllTables(): accept(Throwable throwable) ----");
                    Log.d(TAG, "throwable.getMessage(): "+throwable.getMessage());


                }
            });

Export to csv in jQuery

Just try the following coding...very simple to generate CSV with the values of HTML Tables. No browser issues will come

<!DOCTYPE html>
<html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>        
        <script src="http://www.csvscript.com/dev/html5csv.js"></script>
<script>
$(document).ready(function() {

 $('table').each(function() {
    var $table = $(this);

    var $button = $("<button type='button'>");
    $button.text("Export to CSV");
    $button.insertAfter($table);

    $button.click(function() {     
         CSV.begin('table').download('Export.csv').go();
    });
  });  
})

</script>
    </head>
<body>
<div id='PrintDiv'>
<table style="width:100%">
  <tr>
    <td>Jill</td>
    <td>Smith</td>      
    <td>50</td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td>        
    <td>94</td>
  </tr>
  <tr>
    <td>John</td>
    <td>Doe</td>        
    <td>80</td>
  </tr>
</table>
</div>
</body>
</html>

I cannot start SQL Server browser

My approach was similar to @SoftwareFactor, but different, perhaps because I'm running a different OS, Windows Server 2012. These steps worked for me.

Control Panel > System and Security > Administrative Tools > Services, right-click SQL Server Browser > Properties > General tab, change Startup type to Automatic, click Apply button, then click Start button in Service Status area.

How to use not contains() in xpath?

Should be xpath with not contains() method, //production[not(contains(category,'business'))]

How do you declare an object array in Java?

This is the correct way:

You should declare the length of the array after "="

Veicle[] cars = new Veicle[N];

Datatables - Setting column width

I can tell you another simple way to fix the width of data table in html itself.

use

<colgroup>
    <col width="3%">
    <col width="3%">
</colgroup>

here is a sample code of data table below:

         <table class="table datatable">
                                <colgroup>
                                    <col width="33%">
                                    <col width="33%">
                                    <col width="33%">
                                    <col width="33%">
                                </colgroup>
                                   <thead>
                                        <tr>
                                            <th>User Id</th>
                                            <th>Name</th>
                                            <th>Email</th>
                                            <th>Phone</th>
                                        </tr>
                                    </thead>
                                        <tr>
                                            <th>alpha</th>
                                            <th>beta</th>
                                            <th>gama</th>
                                            <th>delta</th>
                                        </tr>
                                        <tr>
                                            <th>alpha</th>
                                            <th>beta</th>
                                            <th>gama</th>
                                            <th>delta</th>
                                        </tr>
                                        <tr>
                                            <th>alpha</th>
                                            <th>beta</th>
                                            <th>gama</th>
                                            <th>delta</th>
                                        </tr>
                            </table>

R: "Unary operator error" from multiline ggplot2 command

This is a well-known nuisance when posting multiline commands in R. (You can get different behavior when you source() a script to when you copy-and-paste the lines, both with multiline and comments)

Rule: always put the dangling '+' at the end of a line so R knows the command is unfinished:

ggplot(...) + geom_whatever1(...) +
  geom_whatever2(...) +
  stat_whatever3(...) +
  geom_title(...) + scale_y_log10(...)

Don't put the dangling '+' at the start of the line, since that tickles the error:

Error in "+ geom_whatever2(...) invalid argument to unary operator"

And obviously don't put dangling '+' at both end and start since that's a syntax error.

So, learn a habit of being consistent: always put '+' at end-of-line.

cf. answer to "Split code over multiple lines in an R script"

jQuery get input value after keypress

I think what you need is the below prototype

$(element).on('input',function(){code})

Finding the number of days between two dates

If you want to echo all days between the start and end date, I came up with this :

$startdatum = $_POST['start']; // starting date
$einddatum = $_POST['eind']; // end date

$now = strtotime($startdatum);
$your_date = strtotime($einddatum);
$datediff = $your_date - $now;
$number = floor($datediff/(60*60*24));

for($i=0;$i <= $number; $i++)
{
    echo date('d-m-Y' ,strtotime("+".$i." day"))."<br>";
}

try/catch with InputMismatchException creates infinite loop

You need to call next(); when you get the error. Also it is advisable to use hasNextInt()

       catch (Exception e) {
            System.out.println("Error!");
           input.next();// Move to next other wise exception
        }

Before reading integer value you need to make sure scanner has one. And you will not need exception handling like that.

    Scanner scanner = new Scanner(System.in);
    int n1 = 0, n2 = 0;
    boolean bError = true;
    while (bError) {
        if (scanner.hasNextInt())
            n1 = scanner.nextInt();
        else {
            scanner.next();
            continue;
        }
        if (scanner.hasNextInt())
            n2 = scanner.nextInt();
        else {
            scanner.next();
            continue;
        }
        bError = false;
    }
    System.out.println(n1);
    System.out.println(n2);

Javadoc of Scanner

When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.

How to get value by class name in JavaScript or jquery?

If you get the the text inside the element use

Text()

$(".element-classname").text();

In your code:

$('.HOEnZb').text();

if you want get all the data including html Tags use:

html()

 $(".element-classname").html();

In your code:

$('.HOEnZb').html();

Hope it helps:)

Regex using javascript to return just numbers

Everything that other solutions have, but with a little validation

// value = '675-805-714'
const validateNumberInput = (value) => { 
    let numberPattern = /\d+/g 
    let numbers = value.match(numberPattern)

    if (numbers === null) {
        return 0
    }  

    return parseInt(numbers.join([]))
}
// 675805714

The 'Access-Control-Allow-Origin' header contains multiple values

Apache Server:

I spend the same, but it was because I had no quotation marks (") the asterisk in my file that provided access to the server, eg '.htaccess.':

Header add Access-Control-Allow-Origin: * 
Header add Access-Control-Allow-Origin "*" 

You may also have a file '.htaccess' in a folder with another '.htaccess' out, eg

/ 
- .htaccess 
- public_html / .htaccess (problem here)

In your case instead of '*' asterisk would be the ip (http://127.0.0.1:9000) server that you give permission to serve data.

ASP.NET:

Check that there is no 'Access-Control-Allow-Origin' duplicate in your code.

Developer Tools:

With Chrome you can verify your request headers. Press the F12 key and go to the 'Network' tab, now run the AJAX request and will appear on the list, click and give all the information is there.

Access-Control-Allow-Origin: *

Does :before not work on img elements?

The before and after pseudo-selectors don't insert HTML elements — they insert text before or after the existing content of the targeted element. Because image elements don't contain text or have descendants, neither img:before or img:after will do you any good. This is also the case for elements like <br> and <hr> for the same reason.

AngularJS - $http.post send data as json

Consider explicitly setting the header in the $http.post (I put application/json, as I am not sure which of the two versions in your example is the working one, but you can use application/x-www-form-urlencoded if it's the other one):

$http.post("/customer/data/autocomplete", {term: searchString}, {headers: {'Content-Type': 'application/json'} })
        .then(function (response) {
            return response;
        });

An array of List in c#

use

List<int>[] a = new List<int>[100];

Multiple Python versions on the same machine?

On Windows they get installed to separate folders, "C:\python26" and "C:\python31", but the executables have the same "python.exe" name.

I created another "C:\python" folder that contains "python.bat" and "python3.bat" that serve as wrappers to "python26" and "python31" respectively, and added "C:\python" to the PATH environment variable.

This allows me to type python or python3 in my .bat Python wrappers to start the one I desire.

On Linux, you can use the #! trick to specify which version you want a script to use.

Setting Remote Webdriver to run tests in a remote computer using Java

You have to install a Selenium Server (a Hub) and register your remote WebDriver to it. Then, your client will talk to the Hub which will find a matching WebDriver to execute your test.

You can have a look at here for more information.

What does %>% mean in R

Use ?'%*%' to get the documentation.

%*% is matrix multiplication. For matrix multiplication, you need an m x n matrix times an n x p matrix.

T-SQL: Deleting all duplicate rows but keeping one

You didn't say what version you were using, but in SQL 2005 and above, you can use a common table expression with the OVER Clause. It goes a little something like this:

WITH cte AS (
  SELECT[foo], [bar], 
     row_number() OVER(PARTITION BY foo, bar ORDER BY baz) AS [rn]
  FROM TABLE
)
DELETE cte WHERE [rn] > 1

Play around with it and see what you get.

(Edit: In an attempt to be helpful, someone edited the ORDER BY clause within the CTE. To be clear, you can order by anything you want here, it needn't be one of the columns returned by the cte. In fact, a common use-case here is that "foo, bar" are the group identifier and "baz" is some sort of time stamp. In order to keep the latest, you'd do ORDER BY baz desc)

Display Yes and No buttons instead of OK and Cancel in Confirm box?

Create your own confirm box:

<div id="confirmBox">
    <div class="message"></div>
    <span class="yes">Yes</span>
    <span class="no">No</span>
</div>

Create your own confirm() method:

function doConfirm(msg, yesFn, noFn)
{
    var confirmBox = $("#confirmBox");
    confirmBox.find(".message").text(msg);
    confirmBox.find(".yes,.no").unbind().click(function()
    {
        confirmBox.hide();
    });
    confirmBox.find(".yes").click(yesFn);
    confirmBox.find(".no").click(noFn);
    confirmBox.show();
}

Call it by your code:

doConfirm("Are you sure?", function yes()
{
    form.submit();
}, function no()
{
    // do nothing
});

You'll need to add CSS to style and position your confirm box appropriately.

Working demo: jsfiddle.net/Xtreu

SQL Server: Null VS Empty String

An empty string is a string with zero length or no character. Null is absence of data.

How to stop VBA code running?

How about Application.EnableCancelKey - Use the Esc button

On Error GoTo handleCancel
Application.EnableCancelKey = xlErrorHandler
MsgBox "This may take a long time: press ESC to cancel"
For x = 1 To 1000000    ' Do something 1,000,000 times (long!)
    ' do something here
Next x

handleCancel:
If Err = 18 Then
    MsgBox "You cancelled"
End If

Snippet from http://msdn.microsoft.com/en-us/library/aa214566(office.11).aspx

What is initial scale, user-scalable, minimum-scale, maximum-scale attribute in meta tag?

They are viewport meta tags, and is most applicable on mobile browsers.

width=device-width

This means, we are telling to the browser “my website adapts to your device width”.

initial-scale

This defines the scale of the website, This parameter sets the initial zoom level, which means 1 CSS pixel is equal to 1 viewport pixel. This parameter help when you're changing orientation, or preventing default zooming. Without this parameter, responsive site won't work.

maximum-scale

Maximum-scale defines the maximum zoom. When you access the website, top priority is maximum-scale=1, and it won’t allow the user to zoom.

minimum-scale

Minimum-scale defines the minimum zoom. This works the same as above, but it defines the minimum scale. This is useful, when maximum-scale is large, and you want to set minimum-scale.

user-scalable

User-scalable assigned to 1.0 means the website is allowing the user to zoom in or zoom out.

But if you assign it to user-scalable=no, it means the website is not allowing the user to zoom in or zoom out.

correct way to define class variables in Python

I think this sample explains the difference between the styles:

james@bodacious-wired:~$cat test.py 
#!/usr/bin/env python

class MyClass:
    element1 = "Hello"

    def __init__(self):
        self.element2 = "World"

obj = MyClass()

print dir(MyClass)
print "--"
print dir(obj)
print "--"
print obj.element1 
print obj.element2
print MyClass.element1 + " " + MyClass.element2
james@bodacious-wired:~$./test.py 
['__doc__', '__init__', '__module__', 'element1']
--
['__doc__', '__init__', '__module__', 'element1', 'element2']
--
Hello World
Hello
Traceback (most recent call last):
  File "./test.py", line 17, in <module>
    print MyClass.element2
AttributeError: class MyClass has no attribute 'element2'

element1 is bound to the class, element2 is bound to an instance of the class.

SyntaxError: Cannot use import statement outside a module

My solution was to include babel-node path while running nodemon as follows:

nodemon node_modules/.bin/babel-node index.js

you can add in your package.json script as :

debug: nodemon node_modules/.bin/babel-node index.js

NOTE: My entry file is index.js replace it with your entry file (many have app.js/server.js).

How to name and retrieve a stash by name in git?

Stashes are not meant to be permanent things like you want. You'd probably be better served using tags on commits. Construct the thing you want to stash. Make a commit out of it. Create a tag for that commit. Then roll back your branch to HEAD^. Now when you want to reapply that stash you can use git cherry-pick -n tagname (-n is --no-commit).

Clearing content of text file using C#

File.WriteAllText(path, String.Empty);

Alternatively,

File.Create(path).Close();

How can I show a combobox in Android?

For a combobox (http://en.wikipedia.org/wiki/Combo_box) which allows free text input and has a dropdown listbox I used a AutoCompleteTextView as suggested by vbence.

I used the onClickListener to display the dropdown list box when the user selects the control.

I believe this resembles this kind of a combobox best.

private static final String[] STUFF = new String[] { "Thing 1", "Thing 2" };

public void onCreate(Bundle b) {
    final AutoCompleteTextView view = 
        (AutoCompleteTextView) findViewById(R.id.myAutoCompleteTextView);

    view.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
                view.showDropDown();
        }
    });

    final ArrayAdapter<String> adapter = new ArrayAdapter<String>(
        this, 
        android.R.layout.simple_dropdown_item_1line,
        STUFF
    );
    view.setAdapter(adapter);
}

Download and install an ipa from self hosted url on iOS

Yes, safari will detect the *.ipa and will try to install it, but the ipa needs to be correctly signed and only allowed devices would be able to install it.

http://www.diawi.com is a service that will help you with this process.

All of this is for Ad-hoc distribution, not for production apps.

More information on below link : Is there a way to install iPhone App via browser?

gcc/g++: "No such file or directory"

Your compiler just tried to compile the file named foo.cc. Upon hitting line number line, the compiler finds:

#include "bar"

or

#include <bar>

The compiler then tries to find that file. For this, it uses a set of directories to look into, but within this set, there is no file bar. For an explanation of the difference between the versions of the include statement look here.

How to tell the compiler where to find it

g++ has an option -I. It lets you add include search paths to the command line. Imagine that your file bar is in a folder named frobnicate, relative to foo.cc (assume you are compiling from the directory where foo.cc is located):

g++ -Ifrobnicate foo.cc

You can add more include-paths; each you give is relative to the current directory. Microsoft's compiler has a correlating option /I that works in the same way, or in Visual Studio, the folders can be set in the Property Pages of the Project, under Configuration Properties->C/C++->General->Additional Include Directories.

Now imagine you have multiple version of bar in different folders, given:


// A/bar
#include<string>
std::string which() { return "A/bar"; }

// B/bar
#include<string>
std::string which() { return "B/bar"; }

// C/bar
#include<string>
std::string which() { return "C/bar"; }

// foo.cc
#include "bar"
#include <iostream>

int main () {
    std::cout << which() << std::endl;
}

The priority with #include "bar" is leftmost:

$ g++ -IA -IB -IC foo.cc
$ ./a.out
A/bar

As you see, when the compiler started looking through A/, B/ and C/, it stopped at the first or leftmost hit.

This is true of both forms, include <> and incude "".

Difference between #include <bar> and #include "bar"

Usually, the #include <xxx> makes it look into system folders first, the #include "xxx" makes it look into the current or custom folders first.

E.g.:

Imagine you have the following files in your project folder:

list
main.cc

with main.cc:

#include "list"
....

For this, your compiler will #include the file list in your project folder, because it currently compiles main.cc and there is that file list in the current folder.

But with main.cc:

#include <list>
....

and then g++ main.cc, your compiler will look into the system folders first, and because <list> is a standard header, it will #include the file named list that comes with your C++ platform as part of the standard library.

This is all a bit simplified, but should give you the basic idea.

Details on <>/""-priorities and -I

According to the gcc-documentation, the priority for include <> is, on a "normal Unix system", as follows:

 /usr/local/include
 libdir/gcc/target/version/include
 /usr/target/include
 /usr/include

For C++ programs, it will also look in /usr/include/c++/version, first. In the above, target is the canonical name of the system GCC was configured to compile code for; [...].

The documentation also states:

You can add to this list with the -Idir command line option. All the directories named by -I are searched, in left-to-right order, before the default directories. The only exception is when dir is already searched by default. In this case, the option is ignored and the search order for system directories remains unchanged.

To continue our #include<list> / #include"list" example (same code):

g++ -I. main.cc

and

#include<list>
int main () { std::list<int> l; }

and indeed, the -I. prioritizes the folder . over the system includes and we get a compiler error.

Thread-safe List<T> property

Even as it got the most votes, one usually can't take System.Collections.Concurrent.ConcurrentBag<T> as a thread-safe replacement for System.Collections.Generic.List<T> as it is (Radek Stromský already pointed it out) not ordered.

But there is a class called System.Collections.Generic.SynchronizedCollection<T> that is already since .NET 3.0 part of the framework, but it is that well hidden in a location where one does not expect it that it is little known and probably you have never ever stumbled over it (at least I never did).

SynchronizedCollection<T> is compiled into assembly System.ServiceModel.dll (which is part of the client profile but not of the portable class library).

Python - converting a string of numbers into a list of int

I guess the dirtiest solution is this:

list(eval('0, 0, 0, 11, 0, 0, 0, 11'))

add scroll bar to table body

These solutions often have issues with the header columns aligning with the body columns, and may not work properly when resizing. I know you didn't want to use an additional library, but if you happen to be using jQuery, this one is really small. It supports fixed header, footer, column spanning (colspan), horizontal scrolling, resizing, and an optional number of rows to display before scrolling starts.

jQuery.scrollTableBody (GitHub)

As long as you have a table with proper <thead>, <tbody>, and (optional) <tfoot>, all you need to do is this:

$('table').scrollTableBody();

Manually adding a Userscript to Google Chrome

Share and install userscript with one-click

To make auto-install (but mannually confirm), You can make gist (gist.github.com) with <filename>.user.js filename to get on-click installation when you click on Raw and get this page:

Installation page

How to do this ?

  1. Name your gist <filename>.user.js, write your code and click on "Create".
    Make file on gist

  2. In the gist page, click on Raw to get installation page (first screen).
    Raw button

  3. Check the code and install it.

How to perform OR condition in django queryset?

from django.db.models import Q
User.objects.filter(Q(income__gte=5000) | Q(income__isnull=True))

via Documentation

How to filter by IP address in Wireshark?

Try

ip.dst == 172.16.3.255

JavaScript for detecting browser language preference

For what it's worth, Wikimedia's Universal Language Selector library has hooks for doing this: https://www.mediawiki.org/wiki/Extension:UniversalLanguageSelector

See the function getFrequentLanguageList in resources/js/ext.uls.init.js . Direct link: https://gerrit.wikimedia.org/r/gitweb?p=mediawiki/extensions/UniversalLanguageSelector.git;a=blob;f=resources/js/ext.uls.init.js;hb=HEAD

It still depends on the server, or more specifically, the MediaWiki API. The reason I'm showing it is that it may provide a good example of getting all the useful information about the user's language: browser language, Accept-Language, geolocation (with getting country/language info from the CLDR), and of course, user's own site preferences.

Check if a parameter is null or empty in a stored procedure

Here is the general pattern:

IF(@PreviousStartDate IS NULL OR @PreviousStartDate = '')

'' is an empty string in SQL Server.

What is a callback function?

I believe this "callback" jargon has been mistakenly used in a lot of places. My definition would be something like:

A callback function is a function that you pass to someone and let them call it at some point of time.

I think people just read the first sentence of the wiki definition:

a callback is a reference to executable code, or a piece of executable code, that is passed as an argument to other code.

I've been working with lots of APIs, see various of bad examples. Many people tend to name a function pointer (a reference to executable code) or anonymous functions(a piece of executable code) "callback", if they are just functions why do you need another name for this?

Actually only the second sentence in wiki definition reveals the differences between a callback function and a normal function:

This allows a lower-level software layer to call a subroutine (or function) defined in a higher-level layer.

so the difference is who you are going to pass the function and how your passed in function is going to be called. If you just define a function and pass it to another function and called it directly in that function body, don't call it a callback. The definition says your passed in function is gonna be called by "lower-level" function.

I hope people can stop using this word in ambiguous context, it can't help people to understand better only worse.

Java - Writing strings to a CSV file

    String filepath="/tmp/employee.csv";
    FileWriter sw = new FileWriter(new File(filepath));
    CSVWriter writer = new CSVWriter(sw);
    writer.writeAll(allRows);

    String[] header= new String[]{"ErrorMessage"};
    writer.writeNext(header);

    List<String[]> errorData = new ArrayList<String[]>();
    for(int i=0;i<1;i++){
        String[] data = new String[]{"ErrorMessage"+i};
        errorData.add(data);
    }
    writer.writeAll(errorData);

    writer.close();

Excel: Creating a dropdown using a list in another sheet?

As cardern has said list will do the job.

Here is how you can use a named range.

Select your range and enter a new name:

Select your range and enter a new name

Select your cell that you want a drop down to be in and goto data tab -> data validation.

Select 'List' from the 'Allow' Drop down menu.

Enter your named range like this:

enter image description here

Now you have a drop down linked to your range. If you insert new rows in your range everything will update automatically.

enter image description here

Alternative to Intersect in MySQL

SELECT
  campo1,
  campo2,
  campo3,
  campo4
FROM tabela1
WHERE CONCAT(campo1,campo2,campo3,IF(campo4 IS NULL,'',campo4))
NOT IN
(SELECT CONCAT(campo1,campo2,campo3,IF(campo4 IS NULL,'',campo4))
FROM tabela2);

How to manage a redirect request after a jQuery Ajax call

Some might find the below useful:

I wanted clients to be redirected to the login page for any rest-action that is sent without an authorization token. Since all of my rest-actions are Ajax based, I needed a good generic way to redirect to the login page instead of handling the Ajax success function.

This is what I've done:

On any Ajax request my server will return a Json 200 response "NEED TO AUTHENTICATE" (if the client needs to authenticate).

Simple example in Java (server side):

@Secured
@Provider
@Priority(Priorities.AUTHENTICATION)
public class AuthenticationFilter implements ContainerRequestFilter {

    private final Logger m_logger = LoggerFactory.getLogger(AuthenticationFilter.class);

    public static final String COOKIE_NAME = "token_cookie"; 

    @Override
    public void filter(ContainerRequestContext context) throws IOException {        
        // Check if it has a cookie.
        try {
            Map<String, Cookie> cookies = context.getCookies();

            if (!cookies.containsKey(COOKIE_NAME)) {
                m_logger.debug("No cookie set - redirect to login page");
                throw new AuthenticationException();
            }
        }
        catch (AuthenticationException e) {
            context.abortWith(Response.ok("\"NEED TO AUTHENTICATE\"").type("json/application").build());
        }
    }
}

In my Javascript I've added the following code:

$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
    var originalSuccess = options.success;

    options.success = function(data) {
        if (data == "NEED TO AUTHENTICATE") {
            window.location.replace("/login.html");
        }
        else {
            originalSuccess(data);
        }
    };      
});

And that's about it.

How can I convert a series of images to a PDF from the command line on linux?

Using imagemagick, you can try:

convert page.png page.pdf

Or for multiple images:

convert page*.png mydoc.pdf

comparing strings in vb

I would suggest using the String.Compare method. Using that method you can also control whether to to have it perform case-sensitive comparisons or not.

Sample:

Dim str1 As String = "String one"
Dim str2 As String = str1
Dim str3 As String = "String three"
Dim str4 As String = str3

If String.Compare(str1, str2) = 0 And String.Compare(str3, str4) = 0 Then
    MessageBox.Show("str1 = str2 And str3 = str4")
Else
    MessageBox.Show("Else")
End If

Edit: if you want to perform a case-insensitive search you can use the StringComparison parameter:

If String.Compare(str1, str2, StringComparison.InvariantCultureIgnoreCase) = 0 And String.Compare(str3, str4, StringComparison.InvariantCultureIgnoreCase) = 0 Then

Css height in percent not working

You can achieve that by using positioning.

Try

position: absolute;

to get the 100% height.

How to use EditText onTextChanged event when I press the number?

put the logic in

afterTextChanged(Editable s) {
    string str = s.toString()
    // use the string str
}

documentation on TextWatcher

Why are C++ inline functions in the header?

Because the compiler needs to see them in order to inline them. And headers files are the "components" which are commonly included in other translation units.

#include "file.h"
// Ok, now me (the compiler) can see the definition of that inline function. 
// So I'm able to replace calls for the actual implementation.

Convert INT to DATETIME (SQL)

you need to convert to char first because converting to int adds those days to 1900-01-01

select CONVERT (datetime,convert(char(8),rnwl_efctv_dt ))

here are some examples

select CONVERT (datetime,5)

1900-01-06 00:00:00.000

select CONVERT (datetime,20100101)

blows up, because you can't add 20100101 days to 1900-01-01..you go above the limit

convert to char first

declare @i int
select @i = 20100101
select CONVERT (datetime,convert(char(8),@i))

Plot multiple lines (data series) each with unique color in R

More than one line can be drawn on the same chart by using the lines()function

# Create the data for the chart.
v <- c(7,12,28,3,41)
t <- c(14,7,6,19,3)

# Give the chart file a name.
png(file = "line_chart_2_lines.jpg")

# Plot the bar chart.
plot(v,type = "o",col = "red", xlab = "Month", ylab = "Rain fall", 
   main = "Rain fall chart")

lines(t, type = "o", col = "blue")

# Save the file.
dev.off()

OUTPUT enter image description here

How can I extract a number from a string in JavaScript?

Try the following: string.replace(/[^0-9]/g, ''); This will delete all non-digit characters, leaving only digits in the string

function retnum(str) { 
    var num = str.replace(/[^0-9]/g, ''); 
    return parseInt(num,10); 
}

_x000D_
_x000D_
console.log('abca12bc45qw'.replace(/[^0-9]/g, ''));_x000D_
console.log('#box2'.replace(/[^0-9]/g, ''));
_x000D_
_x000D_
_x000D_

ORA-00904: invalid identifier

Are you sure you have a column DEPARTEMENT_CODE on your table PS_TBL_DEPARTMENT_DETAILS

More informations about your ERROR

ORA-00904: string: invalid identifier Cause: The column name entered is either missing or invalid. Action: Enter a valid column name. A valid column name must begin with a letter, be less than or equal to 30 characters, and consist of only alphanumeric characters and the special characters $, _, and #. If it contains other characters, then it must be enclosed in d double quotation marks. It may not be a reserved word.

How to get HQ youtube thumbnails?

You need to get id from:

youtube.com/watch?v=VIDEO_ID

And put this in:

i.ytimg.com/vi/VIDEO_ID/maxresdefault.jpg

I hope that I helped :D

How to improve Netbeans performance?

I use Windows 7. I suggest right-clicking the NetBeans shortcut, go to Properties, and on the Shortcut tab at the Target, add -J-Xmx1024m -J-Xms256m.

This sets the memory usage of the JVM. Xms is the minimal value, while Xmx is the max.

This is the value of target textfield:

"C:\Program Files\NetBeans 7.1\bin\netbeans.exe" --jdkhome "C:\Program Files\Java\jdk1.6.0_10" -J-Dorg.netbeans.modules.php.dbgp.level=400 -J-Xmx1024m -J-Xms256m

Since I add that attribute, my NetBeans run so fast!

Another way to try More Reference Here

In the etc directory under your Netbeans-Home, edit the file netbeans.conf file. -Xms and -Xmx should be increased to the values that allow your program to compile.

instructions in netbeans.conf :

# Note that default -Xmx and -XX:MaxPermSize are selected for you automatically.
# You can find these values in var/log/messages.log file in your userdir.
# The automatically selected value can be overridden by specifying -J-Xmx or
# -J-XX:MaxPermSize= here or on the command line.

Put the values in the netbeans_default_options string. Example :

netbeans_default_options="-J-client -J-Xss2m -J-Xms32m -J-XX:PermSize=32m -J-Dapple.laf.useScreenMenuBar=true -J-Dapple.awt.graphics.UseQuartz=true -J-Dsun.java2d.noddraw=true -J-Dsun.java2d.dpiaware=true -J-Dsun.zip.disableMemoryMapping=true  -J-Dsun.awt.disableMixing=true -J-Dswing.aatext=true -J-Dawt.useSystemAAFontSettings=lcd --laf Nimbus"

What to do to speed up / free up memory windows:

  1. Disable Windows Update :

    • Open Task Manager, open tab Services, disable Windows Update:

disable win update

  1. Hit Ctrl + R and type Services.msc and press enter.
    • Sort by Startup Type
    • Select Services from 3rd party (non windows) which run Automatic, Right click, click Properties and change startup type to Manual

services

  • Sort by Status and Stop services from (3rd party) app you think unused

How to remove a row from JTable?

The correct way to apply a filter to a JTable is through the RowFilter interface added to a TableRowSorter. Using this interface, the view of a model can be changed without changing the underlying model. This strategy preserves the Model-View-Controller paradigm, whereas removing the rows you wish hidden from the model itself breaks the paradigm by confusing your separation of concerns.

csv.Error: iterator should return strings, not bytes

I had this error when running an old python script developped with Python 2.6.4

When updating to 3.6.2, I had to remove all 'rb' parameters from open calls in order to fix this csv reading error.

Differences between ConstraintLayout and RelativeLayout

Relative Layout and Constraint Layout equivalent properties

Relative Layout and Constraint Layout equivalent properties

(1) Relative Layout:

android:layout_centerInParent="true"    

(1) Constraint Layout equivalent :

app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"

(2) Relative Layout:

android:layout_centerHorizontal="true"

(2) Constraint Layout equivalent:

app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintEnd_toEndOf="parent"

(3) Relative Layout:

android:layout_centerVertical="true"    

(3) Constraint Layout equivalent:

app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toTopOf="parent"

(4) Relative Layout:

android:layout_alignParentLeft="true"   

(4) Constraint Layout equivalent:

app:layout_constraintLeft_toLeftOf="parent"

(5) Relative Layout:

android:layout_alignParentStart="true"

(5) Constraint Layout equivalent:

app:layout_constraintStart_toStartOf="parent"

(6) Relative Layout:

android:layout_alignParentRight="true"

(6) Constraint Layout equivalent:

app:layout_constraintRight_toRightOf="parent"

(7) Relative Layout:

android:layout_alignParentEnd="true"    

(7) Constraint Layout equivalent:

app:layout_constraintEnd_toEndOf="parent"

(8) Relative Layout:

android:layout_alignParentTop="true"

(8) Constraint Layout equivalent:

app:layout_constraintTop_toTopOf="parent"

(9) Relative Layout:

android:layout_alignParentBottom="true" 

(9) Constraint Layout equivalent:

app:layout_constraintBottom_toBottomOf="parent"

(10) Relative Layout:

android:layout_alignStart="@id/view"

(10) Constraint Layout equivalent:

app:layout_constraintStart_toStartOf="@id/view"

(11) Relative Layout:

android:layout_alignLeft="@id/view" 

(11) Constraint Layout equivalent:

app:layout_constraintLeft_toLeftOf="@id/view"

(12) Relative Layout:

android:layout_alignEnd="@id/view"  

(12) Constraint Layout equivalent:

app:layout_constraintEnd_toEndOf="@id/view"

(13) Relative Layout:

android:layout_alignRight="@id/view"

(13) Constraint Layout equivalent:

app:layout_constraintRight_toRightOf="@id/view"

(14) Relative Layout:

android:layout_alignTop="@id/view"  

(14) Constraint Layout equivalent:

app:layout_constraintTop_toTopOf="@id/view"

(15) Relative Layout:

android:layout_alignBaseline="@id/view" 

(15) Constraint Layout equivalent:

app:layout_constraintBaseline_toBaselineOf="@id/view"

(16) Relative Layout:

android:layout_alignBottom="@id/view"

(16) Constraint Layout equivalent:

app:layout_constraintBottom_toBottomOf="@id/view"

(17) Relative Layout:

android:layout_toStartOf="@id/view"

(17) Constraint Layout equivalent:

app:layout_constraintEnd_toStartOf="@id/view"

(18) Relative Layout:

android:layout_toLeftOf="@id/view"  

(18) Constraint Layout equivalent:

app:layout_constraintRight_toLeftOf="@id/view"

(19) Relative Layout:

android:layout_toEndOf="@id/view"

(19) Constraint Layout equivalent:

app:layout_constraintStart_toEndOf="@id/view"

(20) Relative Layout:

android:layout_toRightOf="@id/view"

(20) Constraint Layout equivalent:

app:layout_constraintLeft_toRightOf="@id/view"

(21) Relative Layout:

android:layout_above="@id/view" 

(21) Constraint Layout equivalent:

app:layout_constraintBottom_toTopOf="@id/view"

(22) Relative Layout:

android:layout_below="@id/view" 

(22) Constraint Layout equivalent:

app:layout_constraintTop_toBottomOf="@id/view"

Error "The goal you specified requires a project to execute but there is no POM in this directory" after executing maven command

1.create a lib folder in your project file,

2.copy your jarFiles to the lib folder

3.right click on to your jarFile go to build path>Add to build path (now your jar file is part of your refrerenced libraries )

4.open command prompt and navigate to your project directory and write

mvn install: install-file "-Dfile=<yourJarFileName>.jar" "-DgroupId=<yourGroupID>" "-DartifactId=<yourArtifactId>" "-Dversion=<yourVersion>" "-Dpackaging=jar" 

6.Rebuild your local repository index by opening in eclipse- go to window>show view>other>maven>maven Repositories. Right click on local Repositores and hit "RebuildIndex"

5.open your pom.xml file and add your dependency

    <dependency>
        <groupId><yourGroupID></groupId>
        <artifactId><yourArtifactId></artifactId>
        <version><yourVersion></version>
    </dependency>

and run

mvn clean
mvn compile 
mvn test 

mysql update column with value from another table

The second option is feasible also if you're using safe updates mode (and you're getting an error indicating that you've tried to update a table without a WHERE that uses a KEY column), by adding:

UPDATE TableB  
SET TableB.value = (  
SELECT TableA.value  
    FROM TableA  
    WHERE TableA.name = TableB.name  
)  
**where TableB.id < X**  
;

Visual Studio - How to change a project's folder name and solution name without breaking the solution

This is what I did:

  1. Change project and solution name in Visual Studio
  2. Close the project and open the folder containing the project (The Visual studio solution name is already changed).
  3. Change the old project folder names to the new project name
  4. Open the .sln file and the change the project folder names manually from old to new folder names.
  5. Save the .sln file in the text editor
  6. Open the project again with Visual Studio and the solution is ready to modify

Why is this jQuery click function not working?

I found the best solution for this problem by using ON with $(document).

 $(document).on('click', '#yourid', function() { alert("hello"); });

for id start with see below:

$(document).on('click', 'div[id^="start"]', function() {
alert ('hello'); });

finally after 1 week I not need to add onclick triger. I hope this will help many people

How to convert an NSTimeInterval (seconds) into minutes

How I did this in Swift (including the string formatting to show it as "01:23"):

let totalSeconds: Double = someTimeInterval
let minutes = Int(floor(totalSeconds / 60))
let seconds = Int(round(totalSeconds % 60))        
let timeString = String(format: "%02d:%02d", minutes, seconds)
NSLog(timeString)

Can someone explain __all__ in Python?

Short answer

__all__ affects from <module> import * statements.

Long answer

Consider this example:

foo
+-- bar.py
+-- __init__.py

In foo/__init__.py:

  • (Implicit) If we don't define __all__, then from foo import * will only import names defined in foo/__init__.py.

  • (Explicit) If we define __all__ = [], then from foo import * will import nothing.

  • (Explicit) If we define __all__ = [ <name1>, ... ], then from foo import * will only import those names.

Note that in the implicit case, python won't import names starting with _. However, you can force importing such names using __all__.

You can view the Python document here.

Length of array in function argument

The array decays to a pointer when passed.

Section 6.4 of the C FAQ covers this very well and provides the K&R references etc.


That aside, imagine it were possible for the function to know the size of the memory allocated in a pointer. You could call the function two or more times, each time with different input arrays that were potentially different lengths; the length would therefore have to be passed in as a secret hidden variable somehow. And then consider if you passed in an offset into another array, or an array allocated on the heap (malloc and all being library functions - something the compiler links to, rather than sees and reasons about the body of).

Its getting difficult to imagine how this might work without some behind-the-scenes slice objects and such right?


Symbian did have a AllocSize() function that returned the size of an allocation with malloc(); this only worked for the literal pointer returned by the malloc, and you'd get gobbledygook or a crash if you asked it to know the size of an invalid pointer or a pointer offset from one.

You don't want to believe its not possible, but it genuinely isn't. The only way to know the length of something passed into a function is to track the length yourself and pass it in yourself as a separate explicit parameter.

Python "\n" tag extra line

use join(), don't rely on the , for formatting, and also print automatically puts the cursor on a newline every time, so no need of adding another '\n' in your print.

In [24]: for x in board:
    print " ".join(map(str,x))
   ....:     
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 3 2 1 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0

scp or sftp copy multiple files with single command

Copy multiple directories:

scp -r dir1 dir2 dir3 [email protected]:~/

Magento: Set LIMIT on collection

There are several ways to do this:

$collection = Mage::getModel('...')
            ->getCollection()
            ->setPageSize(20)
            ->setCurPage(1);

Will get first 20 records.

Here is the alternative and maybe more readable way:

$collection = Mage::getModel('...')->getCollection();
$collection->getSelect()->limit(20);

This will call Zend Db limit. You can set offset as second parameter.

use current date as default value for a column

Right click on the table and click on Design,then click on column that you want to set default value.

Then in bottom of page in column properties set Default value or binding to : 'getdate()'

JUnit: how to avoid "no runnable methods" in test utils classes

My specific case has the following scenario. Our tests

public class VenueResourceContainerTest extends BaseTixContainerTest

all extend

BaseTixContainerTest

and JUnit was trying to run BaseTixContainerTest. Poor BaseTixContainerTest was just trying to setup the container, setup the client, order some pizza and relax... man.

As mentioned previously, you can annotate the class with

@Ignore

But that caused JUnit to report that test as skipped (as opposed to completely ignored).

Tests run: 4, Failures: 0, Errors: 0, Skipped: 1

That kind of irritated me.

So I made BaseTixContainerTest abstract, and now JUnit truly ignores it.

Tests run: 3, Failures: 0, Errors: 0, Skipped: 0

jQuery Change event on an <input> element - any way to retain previous value?

In Russ answer he binds the focus event. I don't think it is necessary.

You can store the old value in the change event.

<script>
    $(document).ready(function(){

        var newValue = $('#myInputElement').val();
        var oldValue;

        $('#myInputElement').change(function(){
            oldValue = newValue;
            newValue = $(this).val();
        });
    });
</script>
<input id="myInputElement" type="text">

how to load CSS file into jsp

I use this version

<style><%@include file="/WEB-INF/css/style.css"%></style>

How to overwrite styling in Twitter Bootstrap

I know this is an old question but still, I came across a similar problem and i realized that my "not working" css code in my bootstrapOverload.css file was written after the media queries. when I moved it above media queries it started working.

Just in case someone else is facing the same problem

Search for executable files using find command

So as to have another possibility1 to find the files that are executable by the current user:

find . -type f -exec test -x {} \; -print

(the test command here is the one found in PATH, very likely /usr/bin/test, not the builtin).


1 Only use this if the -executable flag of find is not available! this is subtly different from the -perm +111 solution.

Install numpy on python3.3 - Install pip for python3

The normal way to install Python libraries is with pip. Your way of installing it for Python 3.2 works because it's the system Python, and that's the way to install things for system-provided Pythons on Debian-based systems.

If your Python 3.3 is system-provided, you should probably use a similar command. Otherwise you should probably use pip.

I took my Python 3.3 installation, created a virtualenv and run pip install in it, and that seems to have worked as expected:

$ virtualenv-3.3 testenv
$ cd testenv
$ bin/pip install numpy
blablabl

$ bin/python3
Python 3.3.2 (default, Jun 17 2013, 17:49:21) 
[GCC 4.6.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy
>>> 

Force IE8 Into IE7 Compatiblity Mode

A note to this:

IE 8.0s emulation only promises to display the page the same. There are subtle differences that might cause functionality to break. I recently had a problem with just that. Where IE 7.0 uses a javascript wrapper-function called "anonymous()" in IE 8.0 the wrapper was named differently.

So do not expect things like JavaScript to "just work", because you turn on emulation.

How to 'bulk update' with Django?

IT returns number of objects are updated in table.

update_counts = ModelClass.objects.filter(name='bar').update(name="foo")

You can refer this link to get more information on bulk update and create. Bulk update and Create

Convert from List into IEnumerable format

As far as I know List<T> implements IEnumerable<T>. It means that you do not have to convert or cast anything.

Java JTable setting Column Width

This code is worked for me without setAutoResizeModes.

        TableColumnModel columnModel = jTable1.getColumnModel();
        columnModel.getColumn(1).setPreferredWidth(170);
        columnModel.getColumn(1).setMaxWidth(170);
        columnModel.getColumn(2).setPreferredWidth(150);
        columnModel.getColumn(2).setMaxWidth(150);
        columnModel.getColumn(3).setPreferredWidth(40);
        columnModel.getColumn(3).setMaxWidth(40);

LISTAGG function: "result of string concatenation is too long"

Managing overflows in LISTAGG

We can use the Database 12c SQL pattern matching function, MATCH_RECOGNIZE, to return a list of values that does not exceed limit.

Example code and more explanation in below link.

https://blogs.oracle.com/datawarehousing/entry/managing_overflows_in_listagg

Clicking HTML 5 Video element to play, pause video, breaks play button

I had this same problem and solved it by adding an event handler for the play action in addition to the click action. I hide the controls while playing to avoid the pause button issue.

    var v = document.getElementById('videoID');
    v.addEventListener(
       'play', 
          function() { 
             v.play();
          }, 
        false);

    v.onclick = function() {
      if (v.paused) {
        v.play();
        v.controls=null;
      } else {
        v.pause();
        v.controls="controls";
      }
    };

Seeking still acts funny though, but at least the confusion with the play control is gone. Hope this helps.

Anyone have a solution to that?

Preferred Java way to ping an HTTP URL for availability

Is this any good at all (will it do what I want?)

You can do so. Another feasible way is using java.net.Socket.

public static boolean pingHost(String host, int port, int timeout) {
    try (Socket socket = new Socket()) {
        socket.connect(new InetSocketAddress(host, port), timeout);
        return true;
    } catch (IOException e) {
        return false; // Either timeout or unreachable or failed DNS lookup.
    }
}

There's also the InetAddress#isReachable():

boolean reachable = InetAddress.getByName(hostname).isReachable();

This however doesn't explicitly test port 80. You risk to get false negatives due to a Firewall blocking other ports.


Do I have to somehow close the connection?

No, you don't explicitly need. It's handled and pooled under the hoods.


I suppose this is a GET request. Is there a way to send HEAD instead?

You can cast the obtained URLConnection to HttpURLConnection and then use setRequestMethod() to set the request method. However, you need to take into account that some poor webapps or homegrown servers may return HTTP 405 error for a HEAD (i.e. not available, not implemented, not allowed) while a GET works perfectly fine. Using GET is more reliable in case you intend to verify links/resources not domains/hosts.


Testing the server for availability is not enough in my case, I need to test the URL (the webapp may not be deployed)

Indeed, connecting a host only informs if the host is available, not if the content is available. It can as good happen that a webserver has started without problems, but the webapp failed to deploy during server's start. This will however usually not cause the entire server to go down. You can determine that by checking if the HTTP response code is 200.

HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestMethod("HEAD");
int responseCode = connection.getResponseCode();
if (responseCode != 200) {
    // Not OK.
}

// < 100 is undetermined.
// 1nn is informal (shouldn't happen on a GET/HEAD)
// 2nn is success
// 3nn is redirect
// 4nn is client error
// 5nn is server error

For more detail about response status codes see RFC 2616 section 10. Calling connect() is by the way not needed if you're determining the response data. It will implicitly connect.

For future reference, here's a complete example in flavor of an utility method, also taking account with timeouts:

/**
 * Pings a HTTP URL. This effectively sends a HEAD request and returns <code>true</code> if the response code is in 
 * the 200-399 range.
 * @param url The HTTP URL to be pinged.
 * @param timeout The timeout in millis for both the connection timeout and the response read timeout. Note that
 * the total timeout is effectively two times the given timeout.
 * @return <code>true</code> if the given HTTP URL has returned response code 200-399 on a HEAD request within the
 * given timeout, otherwise <code>false</code>.
 */
public static boolean pingURL(String url, int timeout) {
    url = url.replaceFirst("^https", "http"); // Otherwise an exception may be thrown on invalid SSL certificates.

    try {
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setConnectTimeout(timeout);
        connection.setReadTimeout(timeout);
        connection.setRequestMethod("HEAD");
        int responseCode = connection.getResponseCode();
        return (200 <= responseCode && responseCode <= 399);
    } catch (IOException exception) {
        return false;
    }
}

No connection could be made because the target machine actively refused it 127.0.0.1

Add new WebProxy() for the proxy setting , where you are creating a web request.

Example :-

  string url =  "Your URL";
  System.Net.WebRequest req = System.Net.WebRequest.Create(url);
  req.Proxy = new WebProxy();
  System.Net.WebResponse resp = req.GetResponse();

Where req.Proxy = new WebProxy() handle the proxy setting & helps the code to work fine.

remote rejected master -> master (pre-receive hook declined)

Make sure that your Rails app is in the root of the repo, the Gemfile is present and properly named. It is basically not able to detect your code base as one of the supported project types and hence failing it. Also, even if you do have a proper project, make sure it is part of the repository and you have committed it fine (git status will help you here and a ls should help you verify the project structure).

Sublime Text 2 multiple line edit

I'm not sure it's possible "out of the box". And, unfortunately, I don't know an appropriate plugin either. To solve the problem you suggested you could use regular expressions.

  1. Cmd + F (Find)
  2. Regexp: [^ ]+ (or \d+, or whatever you prefer)
  3. Option + F (Find All)
  4. Edit it

Hotkeys may vary depending on you OS and personal preferences (mine are for OS X).

ASP.Net MVC: How to display a byte array image from model

This is an modified version of Manoj's answer that I use on a project. Just updated to take a class, html attributes and use the TagBuilder.

    public static IHtmlString Image(this HtmlHelper helper, byte[] image, string imgclass, 
                                     object htmlAttributes = null)
    {
        var builder = new TagBuilder("img");
        builder.MergeAttribute("class", imgclass);
        builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));

        var imageString = image != null ? Convert.ToBase64String(image) : "";
        var img = string.Format("data:image/jpg;base64,{0}", imageString);
        builder.MergeAttribute("src", img);

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

Which can be used then as follows:

    @Html.Image(Model.Image, "img-cls", new { width="200", height="200" })

Count number of vector values in range with R

There are also the %<% and %<=% comparison operators in the TeachingDemos package which allow you to do this like:

sum( 2 %<% x %<% 5 )
sum( 2 %<=% x %<=% 5 )

which gives the same results as:

sum( 2 < x & x < 5 )
sum( 2 <= x & x <= 5 )

Which is better is probably more a matter of personal preference.

How can I get a specific field of a csv file?

import csv
inf = csv.reader(open('yourfile.csv','r'))
for row in inf:
  print row[1]

Change border color on <select> HTML form

As Diodeus stated, IE doesn't allow anything but the default border for <select> elements. However, I know of two hacks to achieve a similar effect :

  1. Use a DIV that is placed absolutely at the same position as the dropdown and set it's borders. It will appear that the dropdown has a border.

  2. Use a Javascript solution, for instance, the one provided here.

It may however prove to be too much effort, so you should evaluate if you really require the border.

Copy array items into another array

Provided your arrays are not huge (see caveat below), you can use the push() method of the array to which you wish to append values. push() can take multiple parameters so you can use its apply() method to pass the array of values to be pushed as a list of function parameters. This has the advantage over using concat() of adding elements to the array in place rather than creating a new array.

However, it seems that for large arrays (of the order of 100,000 members or more), this trick can fail. For such arrays, using a loop is a better approach. See https://stackoverflow.com/a/17368101/96100 for details.

var newArray = [];
newArray.push.apply(newArray, dataArray1);
newArray.push.apply(newArray, dataArray2);

You might want to generalize this into a function:

function pushArray(arr, arr2) {
    arr.push.apply(arr, arr2);
}

... or add it to Array's prototype:

Array.prototype.pushArray = function(arr) {
    this.push.apply(this, arr);
};

var newArray = [];
newArray.pushArray(dataArray1);
newArray.pushArray(dataArray2);

... or emulate the original push() method by allowing multiple parameters using the fact that concat(), like push(), allows multiple parameters:

Array.prototype.pushArray = function() {
    this.push.apply(this, this.concat.apply([], arguments));
};

var newArray = [];
newArray.pushArray(dataArray1, dataArray2);

Here's a loop-based version of the last example, suitable for large arrays and all major browsers, including IE <= 8:

Array.prototype.pushArray = function() {
    var toPush = this.concat.apply([], arguments);
    for (var i = 0, len = toPush.length; i < len; ++i) {
        this.push(toPush[i]);
    }
};

Converting JSONarray to ArrayList

 JSONArray array = new JSONArray(json);
 List<JSONObject> list = new ArrayList();
 for (int i = 0; i < array.length();list.add(array.getJSONObject(i++)));

How to convert an IPv4 address into a integer in C#?

    public static Int32 getLongIPAddress(string ipAddress)
    {
        return IPAddress.NetworkToHostOrder(BitConverter.ToInt32(IPAddress.Parse(ipAddress).GetAddressBytes(), 0));
    }

The above example would be the way I go.. Only thing you might have to do is convert to a UInt32 for display purposes, or string purposes including using it as a long address in string form.

Which is what is needed when using the IPAddress.Parse(String) function. Sigh.

Notepad++ incrementally replace

(Posting in case someone might have a use of it).

I was looking for a solution for a problem a bit more sophisticated than OP - replacing EVERY occurrence of something with the number by same thing with incremented number

E.g. Replacing something like this:

<row id="1" />
<row id="2" />
<row id="1" />
<row id="3" />
<row id="1" />

By this:

<row id="2" />
<row id="3" />
<row id="2" />
<row id="4" />
<row id="2" />

Couldnt find the solution online so I wrote my own script in groovy (a bit ugly but does the job):

 /**
 * <p> Finds words that matches template and increases them by 1.
 * '_' in word template represents number.
 *
 * <p> E.g. if template equals 'Row="_"', then:
 * ALL Row=0 will be replaced by Row="1"
 * All Row=1 will be replaced by Row="2"
 * <p> Warning - your find template might not work properly if _ is the last character of it
 * etc.
 * <p> Requirments:
 * - Original text does not contain tepmlate string
 * - Only numbers in non-disrupted sequence are incremented and replaced
 * (i.e. from example below, if Row=4 exists in original text, but Row=3 not, than Row=4 will NOT be 
 * replaced by Row=5)
 */
def replace_inc(String text, int startingIndex, String findTemplate) {
    assert findTemplate.contains('_') : 'search template needs to contain "_" placeholder'
    assert !(findTemplate.replaceFirst('_','').contains('_')) : 'only one "_" placeholder is allowed'
    assert !text.contains('_____') : 'input text should not contain "______" (5 underscores)'
    while (true) {
        findString = findTemplate.replace("_",(startingIndex).toString())
        if (!text.contains(findString)) break;
        replaceString = findTemplate.replace("_", "_____"+(++startingIndex).toString())
        text = text.replaceAll(findString, replaceString)
    }
    return text.replaceAll("_____","") // get rid of '_____' character
}

// input
findTemplate = 'Row="_"'
path = /C:\TEMP\working_copy.txt/
startingIndex = 0

// do stuff
f = new File(path)
outText = replace_inc(f.text,startingIndex,findTemplate)
println "Results \n: " + outText
f.withWriter { out -> out.println outText }
println "Results written to $f"

How to define constants in Visual C# like #define in C?

In C#, per MSDN library, we have the "const" keyword that does the work of the "#define" keyword in other languages.

"...when the compiler encounters a constant identifier in C# source code (for example, months), it substitutes the literal value directly into the intermediate language (IL) code that it produces." ( https://msdn.microsoft.com/en-us/library/ms173119.aspx )

Initialize constants at time of declaration since there is no changing them.

public const int cMonths = 12;

Nullable types: better way to check for null or zero in c#

Using generics:

static bool IsNullOrDefault<T>(T value)
{
    return object.Equals(value, default(T));
}

//...
double d = 0;
IsNullOrDefault(d); // true
MyClass c = null;
IsNullOrDefault(c); // true

If T it's a reference type, value will be compared with null ( default(T) ), otherwise, if T is a value type, let's say double, default(t) is 0d, for bool is false, for char is '\0' and so on...

What is the difference between SAX and DOM?

Here in simpler words:

DOM

  • Tree model parser (Object based) (Tree of nodes).

  • DOM loads the file into the memory and then parse- the file.

  • Has memory constraints since it loads the whole XML file before parsing.

  • DOM is read and write (can insert or delete nodes).

  • If the XML content is small, then prefer DOM parser.

  • Backward and forward search is possible for searching the tags and evaluation of the information inside the tags. So this gives the ease of navigation.

  • Slower at run time.

SAX

  • Event based parser (Sequence of events).

  • SAX parses the file as it reads it, i.e. parses node by node.

  • No memory constraints as it does not store the XML content in the memory.

  • SAX is read only i.e. can’t insert or delete the node.

  • Use SAX parser when memory content is large.

  • SAX reads the XML file from top to bottom and backward navigation is not possible.

  • Faster at run time.

push multiple elements to array

Now in ECMAScript2015 (a.k.a. ES6), you can use the spread operator to append multiple items at once:

_x000D_
_x000D_
var arr = [1];_x000D_
var newItems = [2, 3];_x000D_
arr.push(...newItems);_x000D_
console.log(arr);
_x000D_
_x000D_
_x000D_

See Kangax's ES6 compatibility table to see what browsers are compatible

Getting NetworkCredential for current user (C#)

If the web service being invoked uses windows integrated security, creating a NetworkCredential from the current WindowsIdentity should be sufficient to allow the web service to use the current users windows login. However, if the web service uses a different security model, there isn't any way to extract a users password from the current identity ... that in and of itself would be insecure, allowing you, the developer, to steal your users passwords. You will likely need to provide some way for your user to provide their password, and keep it in some secure cache if you don't want them to have to repeatedly provide it.

Edit: To get the credentials for the current identity, use the following:

Uri uri = new Uri("http://tempuri.org/");
ICredentials credentials = CredentialCache.DefaultCredentials;
NetworkCredential credential = credentials.GetCredential(uri, "Basic");

Resource leak: 'in' is never closed

As others have said, you need to call 'close' on IO classes. I'll add that this is an excellent spot to use the try - finally block with no catch, like this:

public void readShapeData() throws IOException {
    Scanner in = new Scanner(System.in);
    try {
        System.out.println("Enter the width of the Rectangle: ");
        width = in.nextDouble();
        System.out.println("Enter the height of the Rectangle: ");
        height = in.nextDouble();
    } finally {
        in.close();
    }
}

This ensures that your Scanner is always closed, guaranteeing proper resource cleanup.

Equivalently, in Java 7 or greater, you can use the "try-with-resources" syntax:

try (Scanner in = new Scanner(System.in)) {
    ... 
}

git ignore vim temporary files

This is something that should only be done on a per-user basis, not per-repository. If Joe uses emacs, he will want to have emacs backup files ignored, but Betty (who uses vi) will want vi backup files ignored (in many cases, they are similar, but there are about 24,893 common editors in existence and it is pretty ridiculous to try to ignore all of the various backup extensions.)

In other words, do not put anything in .gitignore or in core.excludes in $GIT_DIR/config. Put the info in $HOME/.gitconfig instead (as nunopolonia suggests with --global.) Note that "global" means per-user, not per-system.

If you want configuration across the system for all users (which you don't), you'll need a different mechanism. (Possibly with templates setup prior to initialization of the repository.)

How can I find all matches to a regular expression in Python?

Use re.findall or re.finditer instead.

re.findall(pattern, string) returns a list of matching strings.

re.finditer(pattern, string) returns an iterator over MatchObject objects.

Example:

re.findall( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')
# Output: ['cats', 'dogs']

[x.group() for x in re.finditer( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')]
# Output: ['all cats are', 'all dogs are']

How can I hide or encrypt JavaScript code?

One of the best compressors (not specifically an obfuscator) is the YUI Compressor.

How to check empty DataTable

Don't use rows.Count. That's asking for how many rows exist. If there are many, it will take some time to count them. All you really want to know is "is there at least one?" You don't care if there are 10 or 1000 or a billion. You just want to know if there is at least one. If I give you a box and ask you if there are any marbles in it, will you dump the box on the table and start counting? Of course not. Using LINQ, you might think that this would work:

bool hasRows = dataTable1.Rows.Any()

But unfortunately, DataRowCollection does not implement IEnumerable. So instead, try this:

bool hasRows = dataTable1.Rows.GetEnumerator().MoveNext()

You will of course need to check if the dataTable1 is null first. if it's not, this will tell you if there are any rows without enumerating the whole lot.

Get sum of MySQL column in PHP

Let us use the following image as an example for the data in our MySQL Database:

enter image description here

Now, as the question mentions, we need to find the sum of a particular column in a table. For example, let us add all the values of column "duration_sec" for the date '09-10-2018' and only status 'off'

For this condition, the following would be the sql query and code:

$sql_qry = "SELECT SUM(duration_sec) AS count 
    FROM tbl_npt 
    WHERE date='09-10-2018' AND status='off'";

$duration = $connection->query($sql_qry);
$record = $duration->fetch_array();
$total = $record['count'];

echo $total;

Pinging servers in Python

I ended up finding this question regarding a similar scenario. I tried out pyping but the example given by Naveen didn't work for me in Windows under Python 2.7.

An example that worked for me is:

import pyping

response = pyping.send('Your IP')

if response['ret_code'] == 0:
    print("reachable")
else:
    print("unreachable")

How can I parse a time string containing milliseconds in it with python?

from python mailing lists: parsing millisecond thread. There is a function posted there that seems to get the job done, although as mentioned in the author's comments it is kind of a hack. It uses regular expressions to handle the exception that gets raised, and then does some calculations.

You could also try do the regular expressions and calculations up front, before passing it to strptime.

Convert array of indices to 1-hot encoded numpy array

Here is what I find useful:

def one_hot(a, num_classes):
  return np.squeeze(np.eye(num_classes)[a.reshape(-1)])

Here num_classes stands for number of classes you have. So if you have a vector with shape of (10000,) this function transforms it to (10000,C). Note that a is zero-indexed, i.e. one_hot(np.array([0, 1]), 2) will give [[1, 0], [0, 1]].

Exactly what you wanted to have I believe.

PS: the source is Sequence models - deeplearning.ai

spark submit add multiple jars in classpath

You can use --jars $(echo /Path/To/Your/Jars/*.jar | tr ' ' ',') to include entire folder of Jars. So, spark-submit -- class com.yourClass \ --jars $(echo /Path/To/Your/Jars/*.jar | tr ' ' ',') \ ...

Spring-Security-Oauth2: Full authentication is required to access this resource

With Spring OAuth 2.0.7-RELEASE the following command works for me

curl -v -u [email protected]:12345678 -d "grant_type=client_credentials" http://localhost:9999/uaa/oauth/token

It works with Chrome POSTMAN too, just make sure you client and secret in "Basic Auth" tab, set method to "POST" and add grant type in "form data" tab.

Convert a numpy.ndarray to string(or bytes) and convert it back to numpy.ndarray

I know, I am late but here is the correct way of doing it. using base64. This technique will convert the array to string.

import base64
import numpy as np
random_array = np.random.randn(32,32)
string_repr = base64.binascii.b2a_base64(random_array).decode("ascii")
array = np.frombuffer(base64.binascii.a2b_base64(string_repr.encode("ascii"))) 

For array to string

Convert binary data to a line of ASCII characters in base64 coding and decode to ASCII to get string repr.

For string to array

First, encode the string in ASCII format then Convert a block of base64 data back to binary and return the binary data.

Android EditText Max Length

Possible duplicate of Limit text length of EditText in Android

Use android:maxLength="140"

That should work. :)

Hope that helps

How are parameters sent in an HTTP POST request?

The content is put after the HTTP headers. The format of an HTTP POST is to have the HTTP headers, followed by a blank line, followed by the request body. The POST variables are stored as key-value pairs in the body.

You can see this in the raw content of an HTTP Post, shown below:

POST /path/script.cgi HTTP/1.0
From: [email protected]
User-Agent: HTTPTool/1.0
Content-Type: application/x-www-form-urlencoded
Content-Length: 32

home=Cosby&favorite+flavor=flies

You can see this using a tool like Fiddler, which you can use to watch the raw HTTP request and response payloads being sent across the wire.

OpenCV error: the function is not implemented

If it's giving you errors with gtk, try qt.

sudo apt-get install libqt4-dev
cmake -D WITH_QT=ON ..
make
sudo make install

If this doesn't work, there's an easy way out.

sudo apt-get install libopencv-*

This will download all the required dependencies(although it seems that you have all the required libraries installed, but still you could try it once). This will probably install OpenCV 2.3.1 (Ubuntu 12.04). But since you have OpenCV 2.4.3 in /usr/local/lib include this path in /etc/ld.so.conf and do ldconfig. So now whenever you use OpenCV, you'd use the latest version. This is not the best way to do it but if you're still having problems with qt or gtk, try this once. This should work.

Update - 18th Jun 2019

I got this error on my Ubuntu(18.04.1 LTS) system for openCV 3.4.2, as the method call to cv2.imshow was failing (e.g., at the line of cv2.namedWindow(name) with error: cv2.error: OpenCV(3.4.2). The function is not implemented.). I am using anaconda. Just the below 2 steps helped me resolve:

conda remove opencv
conda install -c conda-forge opencv=4.1.0

If you are using pip, you can try

pip install opencv-contrib-python

Java: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

For Windows only, follow these steps:

  1. In Chrome go to settings.
  2. In Settings click show advance settings.
  3. Under HTTPS/SSL Click on Manage Certificates.
  4. Export Your Certificate.
  5. In Windows searchs (Pressing windows key on keyboard) type java.
  6. Select (Configure Java) Option Which will open Java Control Panel
  7. Select Security tab in Java Control Panel
  8. Select Manage Certificates
  9. Click Import
  10. Under (User) tab selected and certificate type as (Trusted Certificates)
  11. Click import button and browse to downloaded certificate and import it.

How to use the onClick event for Hyperlink using C# code?

this may help you.

In .cs page,

//Declare a string
   public string usertypeurl = "";
  //check who is the user
       //place your code to check who is the user
       //if it is admin
       usertypeurl = "help/AdminTutorial.html";
       //if it is other 
        usertypeurl = "help/UserTutorial.html";

In .aspx age pass this variabe

  <a href='<%=usertypeurl%>'>Tutorial</a>

No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API

I was working with Spring REST, and I solved it adding the AllowedMethods into the WebMvcConfigurer.

@Value( "${app.allow.origins}" )
    private String allowOrigins;    
@Bean
public WebMvcConfigurer corsConfigurer() {
            System.out.println("allow origin: "+allowOrigins);
            return new WebMvcConfigurerAdapter() {
                @Override
                public void addCorsMappings(CorsRegistry registry) {
                    registry.addMapping("/**")
                    //.allowedOrigins("http://localhost")
                    .allowedOrigins(allowOrigins)
                    .allowedMethods("PUT", "DELETE","GET", "POST");
                }
            };
        }

How to do a SQL NOT NULL with a DateTime?

SELECT * FROM Table where codtable not in (Select codtable from Table where fecha is null)

Hashmap holding different data types as values for instance Integer, String and Object

Create an object holding following properties with an appropriate name.

  1. message
  2. timestamp
  3. count
  4. version

and use this as a value in your map.

Also consider overriding the equals() and hashCode() method accordingly if you do not want object equality to be used for comparison (e.g. when inserting values into your map).

How to build query string with Javascript

Is is probably too late to answer your question.
I had the same question and I didn't like to keep appending strings to create a URL. So, I started using $.param as techhouse explained.
I also found a URI.js library that creates the URLs easily for you. There are several examples that will help you: URI.js Documentation.
Here is one of them:

var uri = new URI("?hello=world");
uri.setSearch("hello", "mars"); // returns the URI instance for chaining
// uri == "?hello=mars"

uri.setSearch({ foo: "bar", goodbye : ["world", "mars"] });
// uri == "?hello=mars&foo=bar&goodbye=world&goodbye=mars"

uri.setSearch("goodbye", "sun");
// uri == "?hello=mars&foo=bar&goodbye=sun"

// CAUTION: beware of arrays, the following are not quite the same
// If you're dealing with PHP, you probably want the latter…
uri.setSearch("foo", ["bar", "baz"]);
uri.setSearch("foo[]", ["bar", "baz"]);`

How do I read a specified line in a text file?

Tried and tested. It's as simple as follows:

string line = File.ReadLines(filePath).ElementAt(actualLineNumber - 1);

As long as you have a text file, this should work. Later, depending upon what data you expect to read, you can cast the string accordingly and use it.

Making PHP var_dump() values display one line per value

Personally I like the replacement function provided by Symfony's var dumper component

Install with composer require symfony/var-dumper and just use dump($var)

It takes care of the rest. I believe there's also a bit of JS injected there to allow you to interact with the output a bit.

What is JSONP, and why was it created?

JSONP is really a simple trick to overcome the XMLHttpRequest same domain policy. (As you know one cannot send AJAX (XMLHttpRequest) request to a different domain.)

So - instead of using XMLHttpRequest we have to use script HTML tags, the ones you usually use to load js files, in order for js to get data from another domain. Sounds weird?

Thing is - turns out script tags can be used in a fashion similar to XMLHttpRequest! Check this out:

script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://www.someWebApiServer.com/some-data';

You will end up with a script segment that looks like this after it loads the data:

<script>
{['some string 1', 'some data', 'whatever data']}
</script>

However this is a bit inconvenient, because we have to fetch this array from script tag. So JSONP creators decided that this will work better(and it is):

script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://www.someWebApiServer.com/some-data?callback=my_callback';

Notice the my_callback function over there? So - when JSONP server receives your request and finds callback parameter - instead of returning plain js array it'll return this:

my_callback({['some string 1', 'some data', 'whatever data']});

See where the profit is: now we get automatic callback (my_callback) that'll be triggered once we get the data.
That's all there is to know about JSONP: it's a callback and script tags.

NOTE: these are simple examples of JSONP usage, these are not production ready scripts.

Basic JavaScript example (simple Twitter feed using JSONP)

<html>
    <head>
    </head>
    <body>
        <div id = 'twitterFeed'></div>
        <script>
        function myCallback(dataWeGotViaJsonp){
            var text = '';
            var len = dataWeGotViaJsonp.length;
            for(var i=0;i<len;i++){
                twitterEntry = dataWeGotViaJsonp[i];
                text += '<p><img src = "' + twitterEntry.user.profile_image_url_https +'"/>' + twitterEntry['text'] + '</p>'
            }
            document.getElementById('twitterFeed').innerHTML = text;
        }
        </script>
        <script type="text/javascript" src="http://twitter.com/status/user_timeline/padraicb.json?count=10&callback=myCallback"></script>
    </body>
</html>

Basic jQuery example (simple Twitter feed using JSONP)

<html>
    <head>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
        <script>
            $(document).ready(function(){
                $.ajax({
                    url: 'http://twitter.com/status/user_timeline/padraicb.json?count=10',
                    dataType: 'jsonp',
                    success: function(dataWeGotViaJsonp){
                        var text = '';
                        var len = dataWeGotViaJsonp.length;
                        for(var i=0;i<len;i++){
                            twitterEntry = dataWeGotViaJsonp[i];
                            text += '<p><img src = "' + twitterEntry.user.profile_image_url_https +'"/>' + twitterEntry['text'] + '</p>'
                        }
                        $('#twitterFeed').html(text);
                    }
                });
            })
        </script>
    </head>
    <body>
        <div id = 'twitterFeed'></div>
    </body>
</html>


JSONP stands for JSON with Padding. (very poorly named technique as it really has nothing to do with what most people would think of as “padding”.)

How to implement 2D vector array?

Just use the following methods to create a 2-D vector.

int rows, columns;        

// . . .

vector < vector < int > > Matrix(rows, vector< int >(columns,0));

OR

vector < vector < int > > Matrix;

Matrix.assign(rows, vector < int >(columns, 0));

//Do your stuff here...

This will create a Matrix of size rows * columns and initializes it with zeros because we are passing a zero(0) as a second argument in the constructor i.e vector < int > (columns, 0).

Python os.path.join on Windows

to join a windows path, try

mypath=os.path.join('c:\\', 'sourcedir')

basically, you will need to escape the slash

Console.log not working at all

In my case it was caused by console.groupCollapsed().

And collapsed messages don't get detected by ctrl+f apparently.

Maintaining unfamiliar code is scary sometimes...

It even collapsed the exception message, absence of which made me put those console.logs in the first place ^_^

How do I force files to open in the browser instead of downloading (PDF)?

This is for ASP.NET MVC

In your cshtml page:

<section>
    <h4><a href="@Url.Action("Download", "Document", new { id = @Model.GUID })"><i class="fa fa-download"></i> @Model.Name</a></h4>
    <object data="@Url.Action("View", "Document", new { id = @Model.GUID })" type="application/pdf" width="100%" height="800" class="col-md-12">
        <h2>Your browser does not support viewing PDFs, click on the link above to download the document.</h2>
    </object>
</section>

In your controller:

public ActionResult Download(Guid id)
    {
        if (id == Guid.Empty)
            return null;

        var model = GetModel(id);

        return File(model.FilePath, "application/pdf", model.FileName);
    }

public FileStreamResult View(Guid id)
    {
        if (id == Guid.Empty)
            return null;

        var model = GetModel(id);

        FileStream fs = new FileStream(model.FilePath, FileMode.Open, FileAccess.Read);

        return File(fs, "application/pdf");
    }

Html.ActionLink as a button or an image, not a link

<button onclick="location.href='@Url.Action("NewCustomer", "Customers")'">Checkout >></button>

How to expand/collapse a diff sections in Vimdiff?

Aside from the ones you mention, I only use frequently when diffing the following:

  • :diffupdate :diffu -> recalculate the diff, useful when after making several changes vim's isn't showing minimal changes anymore. Note that it only works if the files have been modified inside vimdiff. Otherwise, use:
    • :e to reload the files if they have been modified outside of vimdiff.
  • :set noscrollbind -> temporarily disable simultaneous scrolling on both buffers, reenable by :set scrollbind and scrolling.

Most of what you asked for is folding: vim user manual's chapter on folding. Outside of diffs I sometime use:

  • zo -> open fold.
  • zc -> close fold.

But you'll probably be better served by:

  • zr -> reducing folding level.
  • zm -> one more folding level, please.

or even:

  • zR -> Reduce completely the folding, I said!.
  • zM -> fold Most!.

The other thing you asked for, use n lines of folding, can be found at the vim reference manual section on options, via the section on diff:

  • set diffopt=<TAB>, then update or add context:n.

You should also take a look at the user manual section on diff.

Best way to incorporate Volley (or other library) into Android Studio project

As of today, there is an official Android-hosted copy of Volley available on JCenter:

compile 'com.android.volley:volley:1.0.0'

This was compiled from the AOSP volley source code.

How to get RegistrationID using GCM in android

Use this code to get Registration ID using GCM

String regId = "", msg = "";

public void getRegisterationID() {

    new AsyncTask() {
        @Override
        protected Object doInBackground(Object...params) {

            String msg = "";
            try {
                if (gcm == null) {
                    gcm = GoogleCloudMessaging.getInstance(Login.this);
                }
                regId = gcm.register(YOUR_SENDER_ID);
                Log.d("in async task", regId);

                // try
                msg = "Device registered, registration ID=" + regId;

            } catch (IOException ex) {
                msg = "Error :" + ex.getMessage();
            }
            return msg;
        }
    }.execute(null, null, null);
 }

and don't forget to write permissions in manifest...
I hope it helps!

How to move certain commits to be based on another branch in git?

The simplest thing you can do is cherry picking a range. It does the same as the rebase --onto but is easier for the eyes :)

git cherry-pick quickfix1..quickfix2

Javascript form validation with password confirming

add this to your form:

<form  id="regform" action="insert.php" method="post">

add this to your function:

<script>
    function myFunction() {
        var pass1 = document.getElementById("pass1").value;
        var pass2 = document.getElementById("pass2").value;
        if (pass1 != pass2) {
            //alert("Passwords Do not match");
            document.getElementById("pass1").style.borderColor = "#E34234";
            document.getElementById("pass2").style.borderColor = "#E34234";
        }
        else {
            alert("Passwords Match!!!");
            document.getElementById("regForm").submit();
        }
    }
</script>

Erase the current printed console line

echo -e "hello\c" ;sleep 1 ; echo -e "\rbye  "

What the above command will do :

  1. It will print hello and the cursor will remain at "o" (using \c)

  2. Then it will wait for 1 sec (sleep 1)

  3. Then it will replace hello with bye.(using \r)

NOTE : Using ";", We can run multiple command in a single go.

iOS: Convert UTC NSDate to local Timezone

Please use this code.

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"]; 
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
NSDate *date = [dateFormatter dateFromString:@"2015-04-01T11:42:00"]; // create date from string

[dateFormatter setDateFormat:@"EEE, MMM d, yyyy - h:mm a"];
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
NSString *timestamp = [dateFormatter stringFromDate:date];

Control the dashed border stroke length and distance between strokes

Css render is browser specific and I don't know any fine tuning on it, you should work with images as recommended by Ham. Reference: http://www.w3.org/TR/CSS2/box.html#border-style-properties

How to fix Subversion lock error

I have faced same problem. I solved this by Right click on project --->Team----> Refresh/cleanup

Plotting a 3d cube, a sphere and a vector in Matplotlib

My answer is an amalgamation of the above two with extension to drawing sphere of user-defined opacity and some annotation. It finds application in b-vector visualization on a sphere for magnetic resonance image (MRI). Hope you find it useful:

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')

# draw sphere
u, v = np.mgrid[0:2*np.pi:50j, 0:np.pi:50j]
x = np.cos(u)*np.sin(v)
y = np.sin(u)*np.sin(v)
z = np.cos(v)
# alpha controls opacity
ax.plot_surface(x, y, z, color="g", alpha=0.3)


# a random array of 3D coordinates in [-1,1]
bvecs= np.random.randn(20,3)

# tails of the arrows
tails= np.zeros(len(bvecs))

# heads of the arrows with adjusted arrow head length
ax.quiver(tails,tails,tails,bvecs[:,0], bvecs[:,1], bvecs[:,2],
          length=1.0, normalize=True, color='r', arrow_length_ratio=0.15)

ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')

ax.set_title('b-vectors on unit sphere')

plt.show()

Which exception should I raise on bad/illegal argument combinations in Python?

I'm not sure I agree with inheritance from ValueError -- my interpretation of the documentation is that ValueError is only supposed to be raised by builtins... inheriting from it or raising it yourself seems incorrect.

Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError.

-- ValueError documentation

How to debug on a real device (using Eclipse/ADT)

Sometimes you need to reset ADB. To do that, in Eclipse, go:

Window>> Show View >> Android (Might be found in the "Other" option)>>Devices

in the device Tab, click the down arrow, and choose reset adb.

Using OR in SQLAlchemy

This has been really helpful. Here is my implementation for any given table:

def sql_replace(self, tableobject, dictargs):

    #missing check of table object is valid
    primarykeys = [key.name for key in inspect(tableobject).primary_key]

    filterargs = []
    for primkeys in primarykeys:
        if dictargs[primkeys] is not None:
            filterargs.append(getattr(db.RT_eqmtvsdata, primkeys) == dictargs[primkeys])
        else:
            return

    query = select([db.RT_eqmtvsdata]).where(and_(*filterargs))

    if self.r_ExecuteAndErrorChk2(query)[primarykeys[0]] is not None:
        # update
        filter = and_(*filterargs)
        query = tableobject.__table__.update().values(dictargs).where(filter)
        return self.w_ExecuteAndErrorChk2(query)

    else:
        query = tableobject.__table__.insert().values(dictargs)
        return self.w_ExecuteAndErrorChk2(query)

# example usage
inrow = {'eqmtvs_id': eqmtvsid, 'datetime': dtime, 'param_id': paramid}

self.sql_replace(tableobject=db.RT_eqmtvsdata, dictargs=inrow)

OpenCV Error: (-215)size.width>0 && size.height>0 in function imshow

You have to delay

Example Code:

import cv2
import numpy as np
import time

cam = cv2.VideoCapture(0)
time.sleep(2)

while True:
    ret,frame = cam.read()
    cv2.imshow('webcam', frame)
    if cv2.waitKey(1)&0xFF == ord('q'):
        break

cam.release()
cv2.destroyAllWindows()