Programs & Examples On #Repeat

repeat refers to the action of doing something over again.

Fastest way to count number of occurrences in a Python list

a = ['1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '7', '7', '7', '10', '10']
print a.count("1")

It's probably optimized heavily at the C level.

Edit: I randomly generated a large list.

In [8]: len(a)
Out[8]: 6339347

In [9]: %timeit a.count("1")
10 loops, best of 3: 86.4 ms per loop

Edit edit: This could be done with collections.Counter

a = Counter(your_list)
print a['1']

Using the same list in my last timing example

In [17]: %timeit Counter(a)['1']
1 loops, best of 3: 1.52 s per loop

My timing is simplistic and conditional on many different factors, but it gives you a good clue as to performance.

Here is some profiling

In [24]: profile.run("a.count('1')")
         3 function calls in 0.091 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.091    0.091 <string>:1(<module>)
        1    0.091    0.091    0.091    0.091 {method 'count' of 'list' objects}

        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Prof
iler' objects}



In [25]: profile.run("b = Counter(a); b['1']")
         6339356 function calls in 2.143 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    2.143    2.143 <string>:1(<module>)
        2    0.000    0.000    0.000    0.000 _weakrefset.py:68(__contains__)
        1    0.000    0.000    0.000    0.000 abc.py:128(__instancecheck__)
        1    0.000    0.000    2.143    2.143 collections.py:407(__init__)
        1    1.788    1.788    2.143    2.143 collections.py:470(update)
        1    0.000    0.000    0.000    0.000 {getattr}
        1    0.000    0.000    0.000    0.000 {isinstance}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Prof
iler' objects}
  6339347    0.356    0.000    0.356    0.000 {method 'get' of 'dict' objects}

Repeat rows of a data.frame

If you can repeat the whole thing, or subset it first then repeat that, then this similar question may be helpful. Once again:

library(mefa)
rep(mtcars,10) 

or simply

mefa:::rep.data.frame(mtcars)

do-while loop in R

See ?Control or the R Language Definition:

> y=0
> while(y <5){ print( y<-y+1) }
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5

So do_while does not exist as a separate construct in R, but you can fake it with:

repeat( { expressions}; if (! end_cond_expr ) {break} )

If you want to see the help page you cannot type ?while or ?repeat at the console but rather need to use ?'repeat' or ?'while'. All the "control-constructs" including if are on the same page and all need character quoting after the "?" so the interpreter doesn't see them as incomplete code and give you a continuation "+".

Repeat a string in JavaScript a number of times

Right pads with zeros with no arrays or loops. Just uses repeat() using ES6 2015, which has wide support now. Left pads if you switch the concatenation.

function pad(text, maxLength){ 
  var res = text + "0".repeat(maxLength - text.length);
  return res;
}

console.log(pad('hello', 8)); //hello000

make image( not background img) in div repeat?

You have use to repeat-y as style="background-repeat:repeat-y;width: 200px;" instead of style="repeat-y".

Try this inside the image tag or you can use the below css for the div

.div_backgrndimg
{
    background-repeat: repeat-y;
    background-image: url("/image/layout/lotus-dreapta.png");
    width:200px;
}

Create an array with same element repeated multiple times

In lodash it's not so bad:

_.flatten(_.times(5, function () { return [2]; }));
// [2, 2, 2, 2, 2]

EDIT: Even better:

_.times(5, _.constant(2));
// [2, 2, 2, 2, 2]

EDIT: Even better:

_.fill(Array(5), 2);

Finding repeated words on a string and counting the repetitions

It may help you somehow.

String st="I am am not the one who is thinking I one thing at time";
String []ar = st.split("\\s");
Map<String, Integer> mp= new HashMap<String, Integer>();
int count=0;

for(int i=0;i<ar.length;i++){
    count=0;

    for(int j=0;j<ar.length;j++){
        if(ar[i].equals(ar[j])){
        count++;                
        }
    }

    mp.put(ar[i], count);
}

System.out.println(mp);

Repeat string to certain length

This is pretty pythonic:

newstring = 'abc'*5
print newstring[0:6]

Create sequence of repeated values, in sequence?

You missed the each= argument to rep():

R> n <- 3
R> rep(1:5, each=n)
 [1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5
R> 

so your example can be done with a simple

R> rep(1:8, each=20)

Get time in milliseconds using C#

Use System.DateTime.Now.ToUniversalTime(). That puts your reading in a known reference-based millisecond format that totally eliminates day change, etc.

How to access route, post, get etc. parameters in Zend Framework 2

If You have no access to plugin for instance outside of controller You can get params from servicelocator like this

//from POST
$foo = $this->serviceLocator->get('request')->getPost('foo'); 
//from GET
$foo = $this->serviceLocator->get('request')->getQuery()->foo;
//from route
$foo = $this->serviceLocator->get('application')->getMvcEvent()->getRouteMatch()->getParam('foo');

How to check if the URL contains a given string?

Try this:

<script type="text/javascript">             
    $(document).ready
    (
        function () 
        { 
            var regExp = /franky/g;
            var testString = "something.com/frankyssssddsdfjsdflk?franky";//Inyour case it would be window.location;
            if(regExp.test(testString)) // This doesn't work, any suggestions.                 
            {                      
                alert("your url contains the name franky");                 
            }             
        }
    );         
</script> 

Android ADB stop application command like "force-stop" for non rooted device

If you want to kill the Sticky Service,the following command NOT WORKING:

adb shell am force-stop <PACKAGE>
adb shell kill <PID>

The following command is WORKING:

adb shell pm disable <PACKAGE>

If you want to restart the app,you must run command below first:

adb shell pm enable <PACKAGE>

Visual Studio Code includePath

My c_cpp_properties.json config-

{
    "configurations": [
        {
            "name": "Win32",
            "compilerPath": "C:/MinGW/bin/g++.exe",
            "includePath": [
                "C:/MinGW/lib/gcc/mingw32/9.2.0/include/c++"
            ],
            "defines": [
                "_DEBUG",
                "UNICODE",
                "_UNICODE"
            ],
            "cStandard": "c17",
            "cppStandard": "c++17",
            "intelliSenseMode": "windows-gcc-x64"
       }
    ],
    "version": 4
}

Writing unit tests in Python: How do I start?

The docs for unittest would be a good place to start.

Also, it is a bit late now, but in the future please consider writing unit tests before or during the project itself. That way you can use them to test as you go along, and (in theory) you can use them as regression tests, to verify that your code changes have not broken any existing code. This would give you the full benefit of writing test cases :)

Pytorch reshape tensor dimension

you might use

a.view(1,5)
Out: 

 1  2  3  4  5
[torch.FloatTensor of size 1x5]

Does C# have a String Tokenizer like Java's?

use Regex.Split(string,"#|#");

Why do you use typedef when declaring an enum in C++?

In C, it is good style because you can change the type to something besides an enum.

typedef enum e_TokenType
{
    blah1   = 0x00000000,
    blah2   = 0X01000000,
    blah3   = 0X02000000
} TokenType;

foo(enum e_TokenType token);  /* this can only be passed as an enum */

foo(TokenType token); /* TokenType can be defined to something else later
                         without changing this declaration */

In C++ you can define the enum so that it will compile as C++ or C.

Undefined function mysql_connect()

There must be some syntax error. Copy/paste this code and see if it works:

<?php
    $link = mysql_connect('localhost', 'root', '');
    if (!$link) {
        die('Could not connect:' . mysql_error());
    }
    echo 'Connected successfully';
    ?

I had the same error message. It turns out I was using the msql_connect() function instead of mysql_connect().

Returning a C string from a function

A C string is defined as a pointer to an array of characters.

If you cannot have pointers, by definition you cannot have strings.

Clicking at coordinates without identifying element

If you can see the source code of page, its always the best option to refer to the button by its id or NAME attribute. For example you have button "Login" looking like this:

 <input type="submit" name="login" id="login" />

In that case is best way to do

selenium.click(id="login");

Just out of the curiosity - isnt that HTTP basic authentification? In that case maybe look at this: http://code.google.com/p/selenium/issues/detail?id=34

$(document).on('click', '#id', function() {}) vs $('#id').on('click', function(){})

Consider following code

<ul id="myTask">
  <li>Coding</li>
  <li>Answering</li>
  <li>Getting Paid</li>
</ul>

Now, here goes the difference

// Remove the myTask item when clicked.
$('#myTask').children().click(function () {
  $(this).remove()
});

Now, what if we add a myTask again?

$('#myTask').append('<li>Answer this question on SO</li>');

Clicking this myTask item will not remove it from the list, since it doesn't have any event handlers bound. If instead we'd used .on, the new item would work without any extra effort on our part. Here's how the .on version would look:

$('#myTask').on('click', 'li', function (event) {
  $(event.target).remove()
});

Summary:

The difference between .on() and .click() would be that .click() may not work when the DOM elements associated with the .click() event are added dynamically at a later point while .on() can be used in situations where the DOM elements associated with the .on() call may be generated dynamically at a later point.

Annotation-specified bean name conflicts with existing, non-compatible bean def

I had the same issue. I solved it by using the following steps(Editor: IntelliJ):

  1. View -> Tool Windows -> Maven Project. Opens your projects in a sub-window.
  2. Click on the arrow next to your project.
  3. Click on the lifecycle.
  4. Click on clean.

How to ignore a particular directory or file for tslint?

linterOptions is currently only handled by the CLI. If you're not using CLI then depending on the code base you're using you'll need to set the ignore somewhere else. webpack, tsconfig, etc

How can you represent inheritance in a database?

With the information provided, I'd model the database to have the following:

POLICIES

  • POLICY_ID (primary key)

LIABILITIES

  • LIABILITY_ID (primary key)
  • POLICY_ID (foreign key)

PROPERTIES

  • PROPERTY_ID (primary key)
  • POLICY_ID (foreign key)

...and so on, because I'd expect there to be different attributes associated with each section of the policy. Otherwise, there could be a single SECTIONS table and in addition to the policy_id, there'd be a section_type_code...

Either way, this would allow you to support optional sections per policy...

I don't understand what you find unsatisfactory about this approach - this is how you store data while maintaining referential integrity and not duplicating data. The term is "normalized"...

Because SQL is SET based, it's rather alien to procedural/OO programming concepts & requires code to transition from one realm to the other. ORMs are often considered, but they don't work well in high volume, complex systems.

Could not instantiate mail function. Why this error occurring

"Could not instantiate mail function" is PHPMailer's way of reporting that the call to mail() (in the Mail extension) failed. (So you're using the 'mail' mailer.)

You could try removing the @s before the calls to mail() in PHPMailer::MailSend and seeing what, if any, errors are being silently discarded.

how to run a command at terminal from java program?

You don't actually need to run a command from an xterm session, you can run it directly:

String[] arguments = new String[] {"/path/to/executable", "arg0", "arg1", "etc"};
Process proc = new ProcessBuilder(arguments).start();

If the process responds interactively to the input stream, and you want to inject values, then do what you did before:

OutputStream out = proc.getOutputStream();  
out.write("command\n");  
out.flush();

Don't forget the '\n' at the end though as most apps will use it to identify the end of a single command's input.

Ant is using wrong java version

According to the Ant Documentation, set JAVACMD environment variable to complete path to java.exe of the JRE version that you want to run Ant under.

SQL Server AS statement aliased column within WHERE statement

I am not sure why you cannot use "lat" but, if you must you can rename the columns in a derived table.

select latitude from (SELECT lat AS latitude FROM poi_table) p where latitude < 500

How to run SQL script in MySQL?

If you’re at the MySQL command line mysql> you have to declare the SQL file as source.

mysql> source \home\user\Desktop\test.sql;

How to use continue in jQuery each() loop?

We can break both a $(selector).each() loop and a $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.

return false; // this is equivalent of 'break' for jQuery loop

return;       // this is equivalent of 'continue' for jQuery loop

Note that $(selector).each() and $.each() are different functions.

References:

Resize a picture to fit a JLabel

public void selectImageAndResize(){    
    int returnVal = jFileChooser.showOpenDialog(this); //open jfilechooser
    if (returnVal == jFileChooser.APPROVE_OPTION) {    //select image
        File file = jFileChooser.getSelectedFile();    //get the image
        BufferedImage bi;
        try {
            //
            //transforms selected file to buffer
            //
            bi=ImageIO.read(file);  
            ImageIcon iconimage = new ImageIcon(bi);

            //
            //get image dimensions
            //
            BufferedImage bi2 = new BufferedImage(iconimage.getIconWidth(), iconimage.getIconHeight(), BufferedImage.TYPE_INT_ARGB); 
            Graphics g = bi.createGraphics();
            iconimage.paintIcon(null, g, 0,0);
            g.dispose();

            //
            //resize image according to jlabel
            //
            BufferedImage resizedimage=resize(bi,jLabel2.getWidth(), jLabel2.getHeight()); 
            ImageIcon resizedicon=new ImageIcon(resizedimage);
            jLabel2.setIcon(resizedicon);
        } catch (Exception ex) {
            System.out.println("problem accessing file"+file.getAbsolutePath());
        }
    }
    else {
        System.out.println("File access cancelled by user.");
    }
}

selecting from multi-index pandas

You can also use query which is very readable in my opinion and straightforward to use:

import pandas as pd

df = pd.DataFrame({'A': [1, 2, 3, 4], 'B': [10, 20, 50, 80], 'C': [6, 7, 8, 9]})
df = df.set_index(['A', 'B'])

      C
A B    
1 10  6
2 20  7
3 50  8
4 80  9

For what you had in mind you can now simply do:

df.query('A == 1')

      C
A B    
1 10  6

You can also have more complex queries using and

df.query('A >= 1 and B >= 50')

      C
A B    
3 50  8
4 80  9

and or

df.query('A == 1 or B >= 50')

      C
A B    
1 10  6
3 50  8
4 80  9

You can also query on different index levels, e.g.

df.query('A == 1 or C >= 8')

will return

      C
A B    
1 10  6
3 50  8
4 80  9

If you want to use variables inside your query, you can use @:

b_threshold = 20
c_threshold = 8

df.query('B >= @b_threshold and C <= @c_threshold')

      C
A B    
2 20  7
3 50  8

Databinding an enum property to a ComboBox in WPF

I prefer not to use the name of enum in UI. I prefer use different value for user (DisplayMemberPath) and different for value (enum in this case) (SelectedValuePath). Those two values can be packed to KeyValuePair and stored in dictionary.

XAML

<ComboBox Name="fooBarComboBox" 
          ItemsSource="{Binding Path=ExampleEnumsWithCaptions}" 
          DisplayMemberPath="Value" 
          SelectedValuePath="Key"
          SelectedValue="{Binding Path=ExampleProperty, Mode=TwoWay}" > 

C#

public Dictionary<ExampleEnum, string> ExampleEnumsWithCaptions { get; } =
    new Dictionary<ExampleEnum, string>()
    {
        {ExampleEnum.FooBar, "Foo Bar"},
        {ExampleEnum.BarFoo, "Reversed Foo Bar"},
        //{ExampleEnum.None, "Hidden in UI"},
    };


private ExampleEnum example;
public ExampleEnum ExampleProperty
{
    get { return example; }
    set { /* set and notify */; }
}

EDIT: Compatible with the MVVM pattern.

Create a new line in Java's FileWriter

If you want to get new line characters used in current OS like \r\n for Windows, you can get them by

  • System.getProperty("line.separator");
  • since Java7 System.lineSeparator()
  • or as mentioned by Stewart generate them via String.format("%n");

You can also use PrintStream and its println method which will add OS dependent line separator at the end of your string automatically

PrintStream fileStream = new PrintStream(new File("file.txt"));
fileStream.println("your data");
//         ^^^^^^^ will add OS line separator after data 

(BTW System.out is also instance of PrintStream).

How do you save/store objects in SharedPreferences on Android?

Here's a take on using Kotlin Delegated Properties that I picked up from here, but expanded on and allows for a simple mechanism for getting/setting SharedPreference properties.

For String, Int, Long, Float or Boolean, it uses the standard SharePreference getter(s) and setter(s). However, for all other data classes, it uses GSON to serialize to a String, for the setter. Then deserializes to the data object, for the getter.

Similar to other solutions, this requires adding GSON as a dependency in your gradle file:

implementation 'com.google.code.gson:gson:2.8.6'

Here's an example of a simple data class that we would want to be able to save and store to SharedPreferences:

data class User(val first: String, val last: String)

Here is the one class that implements the property delegates:

object UserPreferenceProperty : PreferenceProperty<User>(
    key = "USER_OBJECT",
    defaultValue = User(first = "Jane", last = "Doe"),
    clazz = User::class.java)

object NullableUserPreferenceProperty : NullablePreferenceProperty<User?, User>(
    key = "NULLABLE_USER_OBJECT",
    defaultValue = null,
    clazz = User::class.java)

object FirstTimeUser : PreferenceProperty<Boolean>(
        key = "FIRST_TIME_USER",
        defaultValue = false,
        clazz = Boolean::class.java
)

sealed class PreferenceProperty<T : Any>(key: String,
                                         defaultValue: T,
                                         clazz: Class<T>) : NullablePreferenceProperty<T, T>(key, defaultValue, clazz)

@Suppress("UNCHECKED_CAST")
sealed class NullablePreferenceProperty<T : Any?, U : Any>(private val key: String,
                                                           private val defaultValue: T,
                                                           private val clazz: Class<U>) : ReadWriteProperty<Any, T> {

    override fun getValue(thisRef: Any, property: KProperty<*>): T = HandstandApplication.appContext().getPreferences()
            .run {
                when {
                    clazz.isAssignableFrom(String::class.java) -> getString(key, defaultValue as String?) as T
                    clazz.isAssignableFrom(Int::class.java) -> getInt(key, defaultValue as Int) as T
                    clazz.isAssignableFrom(Long::class.java) -> getLong(key, defaultValue as Long) as T
                    clazz.isAssignableFrom(Float::class.java) -> getFloat(key, defaultValue as Float) as T
                    clazz.isAssignableFrom(Boolean::class.java) -> getBoolean(key, defaultValue as Boolean) as T
                    else -> getObject(key, defaultValue, clazz)
                }
            }

    override fun setValue(thisRef: Any, property: KProperty<*>, value: T) = HandstandApplication.appContext().getPreferences()
            .edit()
            .apply {
                when {
                    clazz.isAssignableFrom(String::class.java) -> putString(key, value as String?) as T
                    clazz.isAssignableFrom(Int::class.java) -> putInt(key, value as Int) as T
                    clazz.isAssignableFrom(Long::class.java) -> putLong(key, value as Long) as T
                    clazz.isAssignableFrom(Float::class.java) -> putFloat(key, value as Float) as T
                    clazz.isAssignableFrom(Boolean::class.java) -> putBoolean(key, value as Boolean) as T
                    else -> putObject(key, value)
                }
            }
            .apply()

    private fun Context.getPreferences(): SharedPreferences = getSharedPreferences(APP_PREF_NAME, Context.MODE_PRIVATE)

    private fun <T, U> SharedPreferences.getObject(key: String, defValue: T, clazz: Class<U>): T =
            Gson().fromJson(getString(key, null), clazz) as T ?: defValue

    private fun <T> SharedPreferences.Editor.putObject(key: String, value: T) = putString(key, Gson().toJson(value))

    companion object {
        private const val APP_PREF_NAME = "APP_PREF"
    }
}

Note: you shouldn't need to update anything in the sealed class. The delegated properties are the Object/Singletons UserPreferenceProperty, NullableUserPreferenceProperty and FirstTimeUser.

To setup a new data object for saving/getting from SharedPreferences, it's now as easy as adding four lines:

object NewPreferenceProperty : PreferenceProperty<String>(
        key = "NEW_PROPERTY",
        defaultValue = "",
        clazz = String::class.java)

Finally, you can read/write values to SharedPreferences by just using the by keyword:

private var user: User by UserPreferenceProperty
private var nullableUser: User? by NullableUserPreferenceProperty
private var isFirstTimeUser: Boolean by 

Log.d("TAG", user) // outputs the `defaultValue` for User the first time
user = User(first = "John", last = "Doe") // saves this User to the Shared Preferences
Log.d("TAG", user) // outputs the newly retrieved User (John Doe) from Shared Preferences

Omit rows containing specific column of NA

Use is.na

DF <- data.frame(x = c(1, 2, 3), y = c(0, 10, NA), z=c(NA, 33, 22))
DF[!is.na(DF$y),]

Check if element found in array c++

You can do it in a beginners style by using control statements and loops..

#include <iostream>
using namespace std;
int main(){
    int arr[] = {10,20,30,40,50}, toFind= 10, notFound = -1;
    for(int i = 0; i<=sizeof(arr); i++){
        if(arr[i] == toFind){   
            cout<< "Element is found at " <<i <<" index" <<endl;
            return 0;
        }   
    }
    cout<<notFound<<endl;
}

Python: convert string to byte array

This works for me (Python 2)

s = "ABCD"
b = bytearray(s)

# if you print whole b, it still displays it as if its original string
print b

# but print first item from the array to see byte value
print b[0]

Reference: http://www.dotnetperls.com/bytes-python

Angular 2 change event on every keypress

<input type="text" (keypress)="myMethod(myInput.value)" #myInput />

archive .ts

myMethod(value:string){
...
...
}

How can we print line numbers to the log in java

private static final int CLIENT_CODE_STACK_INDEX;

static {
    // Finds out the index of "this code" in the returned stack Trace - funny but it differs in JDK 1.5 and 1.6
    int i = 0;
    for (StackTraceElement ste : Thread.currentThread().getStackTrace()) {
        i++;
        if (ste.getClassName().equals(Trace.class.getName())) {
            break;
        }
    }
    CLIENT_CODE_STACK_INDEX = i;
}

private String methodName() {
    StackTraceElement ste=Thread.currentThread().getStackTrace()[CLIENT_CODE_STACK_INDEX+1];
    return ste.getMethodName()+":"+ste.getLineNumber();
}

How can I display the current branch and folder path in terminal?

Based on 6LYTH3's answer I've decided to post my own due to some improvements that may come in handy:

Simple solution

Open ~/.bash_profile and add the following content

# \[\e[0m\] resets the color to default color
reset_color='\[\e[0m\]'
#  \[\033[33m\] sets the color to yellow
path_color='\[\033[33m\]'
# \e[0;32m\ sets the color to green
git_clean_color='\[\e[0;32m\]'
# \e[0;31m\ sets the color to red
git_dirty_color='\[\e[0;31m\]'

# determines if the git branch you are on is clean or dirty
git_prompt ()
{
  # Is this a git directory?
  if ! git rev-parse --git-dir > /dev/null 2>&1; then
    return 0
  fi
  # Grab working branch name
  git_branch=$(git branch 2>/dev/null| sed -n '/^\*/s/^\* //p')
  # Clean or dirty branch
  if git diff --quiet 2>/dev/null >&2; then
    git_color="${git_clean_color}"
  else
    git_color="${git_dirty_color}"
  fi
  echo " [$git_color$git_branch${reset_color}]"
}

export PS1="${path_color}\w\[\e[0m\]$(git_prompt)\n"

This should:

1) Prompt the path you're in, in color: path_color.
2) Tell you which branch are you.
3) Color the name of the branch based on the status of the branch with git_clean_color 
for a clean work directory and git_dirty_color for a dirty one.
4) The brackets should stay in the default color you established in your computer.
5) Puts the prompt in the next line for readability.

You can customize the colors with this list

Sophisticated Solution

Another option is to use Git Bash Prompt, install with this. I used the option via Homebrew on Mac OS X.

git_prompt_list_themes to see the themes but I didn't like any of them.

git_prompt_color_samples to see available colors.

git_prompt_make_custom_theme [<Name of base theme>] to create a new custom theme, this should create a .git-prompt-colors.sh file.

subl ~/.git-prompt-colors.sh to open git-prompt-colors.sh and customize:

The .git-prompt-colors.sh file should look like this with my customization

    override_git_prompt_colors() {
      GIT_PROMPT_THEME_NAME="Custom"

      # Clean or dirty branch
      if git diff --quiet 2>/dev/null >&2; then
        GIT_PROMPT_BRANCH="${Green}"
      else
        GIT_PROMPT_BRANCH="${Red}"
      fi
    }

    reload_git_prompt_colors "Custom"

Hope this helps, have a great day!

Is it possible to access an SQLite database from JavaScript?

IMHO, the best way is to call Python using POST via AJAX and do everything you need to do with the DB within Python, then return the result to the javascript. json and sqlite support in Python is awesome and it's 100% built-in within even slightly recent versions of Python, so there is no "install this, install that" pain. In Python:

import sqlite3
import json

...that's all you need. It's part of every Python distribution.

@Sedrick Jefferson asked for examples, so (somewhat tardily) I have written up a stand-alone back-and-forth between Javascript and Python here.

How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson

For Jackson versions < 2.0 use this annotation on the class being serialized:

@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)

Generate your own Error code in swift 3

You should use NSError object.

let error = NSError(domain:"", code:401, userInfo:[ NSLocalizedDescriptionKey: "Invalid access token"])

Then cast NSError to Error object

The ScriptManager must appear before any controls that need it

If you are using microsoft ajax on your page you need the script manager control added to your master page or the page that needs it. It Manages ASP.NET Ajax script libraries and script files, partial-page rendering, and client proxy class generation for Web and application services

<asp:ScriptManager ID="ScriptManger1" runat="Server">
</asp:ScriptManager>

The full usage

<asp:ScriptManager
    AllowCustomErrorsRedirect="True|False"
    AsyncPostBackErrorMessage="string"
    AsyncPostBackTimeout="integer"
    AuthenticationService-Path="uri"
    EnablePageMethods="True|False"
    EnablePartialRendering="True|False"
    EnableScriptGlobalization="True|False"
    EnableScriptLocalization="True|False"
    EnableTheming="True|False"
    EnableViewState="True|False"
    ID="string"
    LoadScriptsBeforeUI="True|False"
    OnAsyncPostBackError="AsyncPostBackError event handler"
    OnDataBinding="DataBinding event handler"
    OnDisposed="Disposed event handler"
    OnInit="Init event handler"
    OnLoad="Load event handler"
    OnPreRender="PreRender event handler"
    OnResolveScriptReference="ResolveScriptReference event handler"
    OnUnload="Unload event handler"
    ProfileService-LoadProperties="string"
    ProfileService-Path="uri"
    RoleService-LoadRoles="True|False"
    RoleService-Path="uri"
    runat="server"
    ScriptMode="Auto|Inherit|Debug|Release"
    ScriptPath="string"
    SkinID="string"
    SupportsPartialRendering="True|False"
    Visible="True|False">
        <AuthenticationService
            Path="uri" />
        <ProfileService
            LoadProperties="string"
            Path="uri" />
        <RoleService
            LoadRoles="True|False"
            Path="uri" />
        <Scripts>
            <asp:ScriptReference
                Assembly="string"
                IgnoreScriptPath="True|False"
                Name="string"
                NotifyScriptLoaded="True|False"
                Path="string"
                ResourceUICultures="string"
                ScriptMode="Auto|Debug|Inherit|Release" />
        </Scripts>
        <Services>
            <asp:ServiceReference
                InlineScript="True|False"
                Path="string" />
        </Services>
</asp:ScriptManager>

JavaScript - Get Browser Height

You'll want something like this, taken from http://www.howtocreate.co.uk/tutorials/javascript/browserwindow

function alertSize() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  window.alert( 'Width = ' + myWidth );
  window.alert( 'Height = ' + myHeight );
}

So that's innerHeight for modern browsers, documentElement.clientHeight for IE, body.clientHeight for deprecated/quirks.

Getting an element from a Set

To answer the precise question "Why doesn't Set provide an operation to get an element that equals another element?", the answer would be: because the designers of the collection framework were not very forward looking. They didn't anticipate your very legitimate use case, naively tried to "model the mathematical set abstraction" (from the javadoc) and simply forgot to add the useful get() method.

Now to the implied question "how do you get the element then": I think the best solution is to use a Map<E,E> instead of a Set<E>, to map the elements to themselves. In that way, you can efficiently retrieve an element from the "set", because the get() method of the Map will find the element using an efficient hash table or tree algorithm. If you wanted, you could write your own implementation of Set that offers the additional get() method, encapsulating the Map.

The following answers are in my opinion bad or wrong:

"You don't need to get the element, because you already have an equal object": the assertion is wrong, as you already showed in the question. Two objects that are equal still can have different state that is not relevant to the object equality. The goal is to get access to this state of the element contained in the Set, not the state of the object used as a "query".

"You have no other option but to use the iterator": that is a linear search over a collection which is totally inefficient for large sets (ironically, internally the Set is organized as hash map or tree that could be queried efficiently). Don't do it! I have seen severe performance problems in real-life systems by using that approach. In my opinion what is terrible about the missing get() method is not so much that it is a bit cumbersome to work around it, but that most programmers will use the linear search approach without thinking of the implications.

removing html element styles via javascript

Completly removing style, not only set to NULL

document.getElementById("id").removeAttribute("style")

How to make popup look at the centre of the screen?

If the effect you want is to center in the center of the screen no matter where you've scrolled to, it's even simpler than that:

In your CSS use (for example)

div.centered{
  width: 100px;
  height: 50px;
  position:fixed; 
  top: calc(50% - 25px); // half of width
  left: calc(50% - 50px); // half of height
}

No JS required.

jQuery Keypress Arrow Keys

$(document).keydown(function(e) {
    console.log(e.keyCode);
});

Keypress events do detect arrow keys, but not in all browsers. So it's better to use keydown.

These are keycodes you should be getting in your console log:

  • left = 37
  • up = 38
  • right = 39
  • down = 40

Display help message with python argparse when script is called without any arguments

Set your positional arguments with nargs, and check if positional args are empty.

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('file', nargs='?')
args = parser.parse_args()
if not args.file:
    parser.print_help()

Reference Python nargs

Difference between opening a file in binary vs text

The most important difference to be aware of is that with a stream opened in text mode you get newline translation on non-*nix systems (it's also used for network communications, but this isn't supported by the standard library). In *nix newline is just ASCII linefeed, \n, both for internal and external representation of text. In Windows the external representation often uses a carriage return + linefeed pair, "CRLF" (ASCII codes 13 and 10), which is converted to a single \n on input, and conversely on output.


From the C99 standard (the N869 draft document), §7.19.2/2,

A text stream is an ordered sequence of characters composed into lines, each line consisting of zero or more characters plus a terminating new-line character. Whether the last line requires a terminating new-line character is implementation-defined. Characters may have to be added, altered, or deleted on input and output to conform to differing conventions for representing text in the host environment. Thus, there need not be a one- to-one correspondence between the characters in a stream and those in the external representation. Data read in from a text stream will necessarily compare equal to the data that were earlier written out to that stream only if: the data consist only of printing characters and the control characters horizontal tab and new-line; no new-line character is immediately preceded by space characters; and the last character is a new-line character. Whether space characters that are written out immediately before a new-line character appear when read in is implementation-defined.

And in §7.19.3/2

Binary files are not truncated, except as defined in 7.19.5.3. Whether a write on a text stream causes the associated file to be truncated beyond that point is implementation- defined.

About use of fseek, in §7.19.9.2/4:

For a text stream, either offset shall be zero, or offset shall be a value returned by an earlier successful call to the ftell function on a stream associated with the same file and whence shall be SEEK_SET.

About use of ftell, in §17.19.9.4:

The ftell function obtains the current value of the file position indicator for the stream pointed to by stream. For a binary stream, the value is the number of characters from the beginning of the file. For a text stream, its file position indicator contains unspecified information, usable by the fseek function for returning the file position indicator for the stream to its position at the time of the ftell call; the difference between two such return values is not necessarily a meaningful measure of the number of characters written or read.

I think that’s the most important, but there are some more details.

Detecting request type in PHP (GET, POST, PUT or DELETE)

It is valuable to additionally note, that PHP will populate all the $_GET parameters even when you send a proper request of other type.

Methods in above replies are completely correct, however if you want to additionaly check for GET parameters while handling POST, DELETE, PUT, etc. request, you need to check the size of $_GET array.

Counting the occurrences / frequency of array elements

Check out the code below.

<html>
<head>
<script>
// array with values
var ar = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];

var Unique = []; // we'll store a list of unique values in here
var Counts = []; // we'll store the number of occurances in here

for(var i in ar)
{
    var Index = ar[i];
    Unique[Index] = ar[i];
    if(typeof(Counts[Index])=='undefined')  
        Counts[Index]=1;
    else
        Counts[Index]++;
}

// remove empty items
Unique = Unique.filter(function(){ return true});
Counts = Counts.filter(function(){ return true});

alert(ar.join(','));
alert(Unique.join(','));
alert(Counts.join(','));

var a=[];

for(var i=0; i<Unique.length; i++)
{
    a.push(Unique[i] + ':' + Counts[i] + 'x');
}
alert(a.join(', '));

</script>
</head>
<body>

</body>
</html>

Converting a SimpleXML Object to an Array

I found this in the PHP manual comments:

/**
 * function xml2array
 *
 * This function is part of the PHP manual.
 *
 * The PHP manual text and comments are covered by the Creative Commons 
 * Attribution 3.0 License, copyright (c) the PHP Documentation Group
 *
 * @author  k dot antczak at livedata dot pl
 * @date    2011-04-22 06:08 UTC
 * @link    http://www.php.net/manual/en/ref.simplexml.php#103617
 * @license http://www.php.net/license/index.php#doc-lic
 * @license http://creativecommons.org/licenses/by/3.0/
 * @license CC-BY-3.0 <http://spdx.org/licenses/CC-BY-3.0>
 */
function xml2array ( $xmlObject, $out = array () )
{
    foreach ( (array) $xmlObject as $index => $node )
        $out[$index] = ( is_object ( $node ) ) ? xml2array ( $node ) : $node;

    return $out;
}

It could help you. However, if you convert XML to an array you will loose all attributes that might be present, so you cannot go back to XML and get the same XML.

How does JavaScript .prototype work?

I always like analogies when it comes to understand this type of stuff. 'Prototypical inheritance' is pretty confusing in comparison to class bass inheritance in my opinion, even though prototypes are much simpler paradigm. In fact with prototypes, there really is no inheritance, so the name in and of itself misleading, it's more a type of 'delegation'.

Imagine this ....

You're in high-school, and you're in class and have a quiz that's due today, but you don't have a pen to fill out your answers. Doh!

You're sitting next to your friend Finnius, who might have a pen. You ask, and he looks around his desk unsuccessfully, but instead of saying "I don't have a pen", he's a nice friend he checks with his other friend Derp if he has a pen. Derp does indeed have a spare pen and passes it back to Finnius, who passes it over to you to complete your quiz. Derp has entrusted the pen to Finnius, who has delegated the pen to you for use.

What is important here is that Derp does not give the pen to you, as you don't have a direct relationship with him.

This, is a simplified example of how prototypes work, where a tree of data is searched for the thing you're looking for.

ImportError in importing from sklearn: cannot import name check_build

After installing numpy , scipy ,sklearn still has error

Solution:

Setting Up System Path Variable for Python & the PYTHONPATH Environment Variable

System Variables: add C:\Python34 into path User Variables: add new: (name)PYTHONPATH (value)C:\Python34\Lib\site-packages;

Java 8 - Best way to transform a list: map or foreach?

If you use Eclipse Collections you can use the collectIf() method.

MutableList<Integer> source =
    Lists.mutable.with(1, null, 2, null, 3, null, 4, null, 5);

MutableList<String> result = source.collectIf(Objects::nonNull, String::valueOf);

Assert.assertEquals(Lists.immutable.with("1", "2", "3", "4", "5"), result);

It evaluates eagerly and should be a bit faster than using a Stream.

Note: I am a committer for Eclipse Collections.

How can I rename a conda environment?

conda should have given us a simple tool like cond env rename <old> <new> but it hasn't. Simply renaming the directory, as in this previous answer, of course, breaks the hardcoded hashbangs(#!). Hence, we need to go one more level deeper to achieve what we want.

conda env list
# conda environments:
#
base                  *  /home/tgowda/miniconda3
junkdetect               /home/tgowda/miniconda3/envs/junkdetect
rtg                      /home/tgowda/miniconda3/envs/rtg

Here I am trying to rename rtg --> unsup (please bear with those names, this is my real use case)

$ cd /home/tgowda/miniconda3/envs 
$ OLD=rtg
$ NEW=unsup
$ mv $OLD $NEW   # rename dir

$ conda env list
# conda environments:
#
base                  *  /home/tgowda/miniconda3
junkdetect               /home/tgowda/miniconda3/envs/junkdetect
unsup                    /home/tgowda/miniconda3/envs/unsup


$ conda activate $NEW
$ which python
  /home/tgowda/miniconda3/envs/unsup/bin/python

the previous answer reported upto this, but wait, we are not done yet! the pending task is, $NEW/bin dir has a bunch of executable scripts with hashbangs (#!) pointing to the $OLD env paths.

See jupyter, for example:

$ which jupyter
/home/tgowda/miniconda3/envs/unsup/bin/jupyter

$ head -1 $(which jupyter) # its hashbang is still looking at old
#!/home/tgowda/miniconda3/envs/rtg/bin/python

So, we can easily fix it with a sed

$ sed  -i.bak "s:envs/$OLD/bin:envs/$NEW/bin:" $NEW/bin/*  
# `-i.bak` created backups, to be safe

$ head -1 $(which jupyter) # check if updated
#!/home/tgowda/miniconda3/envs/unsup/bin/python
$ jupyter --version # check if it works
jupyter core     : 4.6.3
jupyter-notebook : 6.0.3

$ rm $NEW/bin/*.bak  # remove backups

Now we are done

I think it should be trivial to write a portable script to do all those and bind it to conda env rename old new.


I tested this on ubuntu. For whatever unforseen reasons, if things break and you wish to revert the above changes:

$ mv $NEW  $OLD
$ sed  -i.bak "s:envs/$NEW/bin:envs/$OLD/bin:" $OLD/bin/*

How to Remove Line Break in String

Clean function can be called from VBA this way:

Range("A1").Value = Application.WorksheetFunction.Clean(Range("A1"))

However as written here, the CLEAN function was designed to remove the first 32 non-printing characters in the 7 bit ASCII code (values 0 through 31) from text. In the Unicode character set, there are additional nonprinting characters (values 127, 129, 141, 143, 144, and 157). By itself, the CLEAN function does not remove these additional nonprinting characters.

Rick Rothstein have written code to handle even this situation here this way:

Function CleanTrim(ByVal S As String, Optional ConvertNonBreakingSpace As Boolean = True) As String
  Dim X As Long, CodesToClean As Variant
  CodesToClean = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, _
                       21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 127, 129, 141, 143, 144, 157)
  If ConvertNonBreakingSpace Then S = Replace(S, Chr(160), " ")
  For X = LBound(CodesToClean) To UBound(CodesToClean)
    If InStr(S, Chr(CodesToClean(X))) Then S = Replace(S, Chr(CodesToClean(X)), "")
  Next
  CleanTrim = WorksheetFunction.Trim(S)
End Function

What is the purpose of using WHERE 1=1 in SQL statements?

As you said:

if you are adding conditions dynamically you don't have to worry about stripping the initial AND that's the only reason could be, you are right.

Tomcat 7 is not running on browser(http://localhost:8080/ )

Many of us get this error after setting up the eclipse and server for first time. This solution is -

  1. go to server tab

  2. select the properties option of your respective server and expand it

  3. in the properties window , select general tab -> click Switch Location -> click apply ->click ok.

This may work .

Git: which is the default configured remote for branch?

You can do it more simply, guaranteeing that your .gitconfig is left in a meaningful state:

Using Git version v1.8.0 and above

git push -u hub master when pushing, or:
git branch -u hub/master

OR

(This will set the remote for the currently checked-out branch to hub/master)
git branch --set-upstream-to hub/master

OR

(This will set the remote for the branch named branch_name to hub/master)
git branch branch_name --set-upstream-to hub/master

If you're using v1.7.x or earlier

you must use --set-upstream:
git branch --set-upstream master hub/master

PHP - Notice: Undefined index:

How are you loading this page? Is it getting anything on POST to load? If it's not, then the $name = $_POST['Name']; assignation doesn't have any 'Name' on POST.

React onClick and preventDefault() link refresh/redirect?

I've had some troubles with anchor tags and preventDefault in the past and I always forget what I'm doing wrong, so here's what I figured out.

The problem I often have is that I try to access the component's attributes by destructuring them directly as with other React components. This will not work, the page will reload, even with e.preventDefault():

function (e, { href }) {
  e.preventDefault();
  // Do something with href
}
...
<a href="/foobar" onClick={clickHndl}>Go to Foobar</a>

It seems the destructuring causes an error (Cannot read property 'href' of undefined) that is not displayed to the console, probably due to the page complete reload. Since the function is in error, the preventDefault doesn't get called. If the href is #, the error is displayed properly since there's no actual reload.

I understand now that I can only access attributes as a second handler argument on custom React components, not on native HTML tags. So of course, to access an HTML tag attribute in an event, this would be the way:

function (e) {
  e.preventDefault();
  const { href } = e.target;
  // Do something with href
}
...
<a href="/foobar" onClick={clickHndl}>Go to Foobar</a>

I hope this helps other people like me puzzled by not shown errors!

How to "log in" to a website using Python's Requests module?

If the information you want is on the page you are directed to immediately after login...

Lets call your ck variable payload instead, like in the python-requests docs:

payload = {'inUserName': 'USERNAME/EMAIL', 'inUserPass': 'PASSWORD'}
url = 'http://www.locationary.com/home/index2.jsp'
requests.post(url, data=payload)

Otherwise...

See https://stackoverflow.com/a/17633072/111362 below.

Simplest PHP example for retrieving user_timeline with Twitter API version 1.1

Thank you Kris!

It worked for me without using parameters to the query, whenever I used more than one parameter it showed me the error: 32 Could not authenticate you.

The problem for me, was in the ampersand encoding. So in your code where it's the following line

$url .= "?".http_build_query($query);

I added the following line below:

$url=str_replace("&amp;","&",$url);

And it worked using two or more parameters like screen_name and count.

The whole code looks like this:

$token = 'YOUR TOKEN';
$token_secret = 'TOKEN SECRET';
$consumer_key = 'YOUR KEY';
$consumer_secret = 'KEY SECRET';

$host = 'api.twitter.com';
$method = 'GET';
$path = '/1.1/statuses/user_timeline.json'; // api call path

$query = array( // query parameters
    'screen_name' => 'twitterapi',
    'count' => '2'
);

$oauth = array(
    'oauth_consumer_key' => $consumer_key,
    'oauth_token' => $token,
    'oauth_nonce' => (string)mt_rand(), // a stronger nonce is recommended
    'oauth_timestamp' => time(),
    'oauth_signature_method' => 'HMAC-SHA1',
    'oauth_version' => '1.0'
);

$oauth = array_map("rawurlencode", $oauth); // must be encoded before sorting
$query = array_map("rawurlencode", $query);

$arr = array_merge($oauth, $query); // combine the values THEN sort

asort($arr); // secondary sort (value)
ksort($arr); // primary sort (key)

// http_build_query automatically encodes, but our parameters
// are already encoded, and must be by this point, so we undo
// the encoding step
$querystring = urldecode(http_build_query($arr, '', '&'));

$url = "https://$host$path";

// mash everything together for the text to hash
$base_string = $method."&".rawurlencode($url)."&".rawurlencode($querystring);

// same with the key
$key = rawurlencode($consumer_secret)."&".rawurlencode($token_secret);

// generate the hash
$signature = rawurlencode(base64_encode(hash_hmac('sha1', $base_string, $key, true)));

// this time we're using a normal GET query, and we're only encoding the query params
// (without the oauth params)
$url .= "?".http_build_query($query);
$url=str_replace("&amp;","&",$url); //Patch by @Frewuill

$oauth['oauth_signature'] = $signature; // don't want to abandon all that work!
ksort($oauth); // probably not necessary, but twitter's demo does it

// also not necessary, but twitter's demo does this too
function add_quotes($str) { return '"'.$str.'"'; }
$oauth = array_map("add_quotes", $oauth);

// this is the full value of the Authorization line
$auth = "OAuth " . urldecode(http_build_query($oauth, '', ', '));

// if you're doing post, you need to skip the GET building above
// and instead supply query parameters to CURLOPT_POSTFIELDS
$options = array( CURLOPT_HTTPHEADER => array("Authorization: $auth"),
                  //CURLOPT_POSTFIELDS => $postfields,
                  CURLOPT_HEADER => false,
                  CURLOPT_URL => $url,
                  CURLOPT_RETURNTRANSFER => true,
                  CURLOPT_SSL_VERIFYPEER => false);

// do our business
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);

$twitter_data = json_decode($json);

Hope It helps somebody with the same problem I had.

Can I use an HTML input type "date" to collect only a year?

_x000D_
_x000D_
 <!--This yearpicker development from Zlatko Borojevic_x000D_
 html elemnts can generate with java function_x000D_
    and then declare as custom type for easy use in all html documents _x000D_
 For this version for implementacion in your document can use:_x000D_
 1. Save this code for example: "yearonly.html"_x000D_
 2. creaate one div with id="yearonly"_x000D_
 3. Include year picker with function: $("#yearonly").load("yearonly.html"); _x000D_
 _x000D_
 <div id="yearonly"></div>_x000D_
 <script>_x000D_
 $("#yearonly").load("yearonly.html"); _x000D_
 </script>_x000D_
 -->_x000D_
_x000D_
 _x000D_
 _x000D_
 <!DOCTYPE html>_x000D_
 <meta name="viewport" content="text-align:center; width=device-width, initial-scale=1.0">_x000D_
 <html>_x000D_
 <body>_x000D_
 <style>_x000D_
 .ydiv {_x000D_
 border:solid 1px;_x000D_
 width:200px;_x000D_
 //height:150px;_x000D_
 background-color:#D8D8D8;_x000D_
 display:none;_x000D_
 position:absolute;_x000D_
 top:40px;_x000D_
 }_x000D_
_x000D_
 .ybutton {_x000D_
_x000D_
    border: none;_x000D_
    width:35px;_x000D_
 height:35px;_x000D_
    background-color:#D8D8D8;_x000D_
 font-size:100%;_x000D_
 }_x000D_
_x000D_
 .yhr {_x000D_
 background-color:black;_x000D_
 color:black;_x000D_
 height:1px">_x000D_
 }_x000D_
_x000D_
 .ytext {_x000D_
 border:none;_x000D_
 text-align:center;_x000D_
 width:118px;_x000D_
 font-size:100%;_x000D_
 background-color:#D8D8D8;_x000D_
 font-weight:bold;_x000D_
_x000D_
 }_x000D_
 </style>_x000D_
 <p>_x000D_
 <!-- input text for display result of yearpicker -->_x000D_
 <input type = "text" id="yeardate"><button style="width:21px;height:21px"onclick="enabledisable()">V</button></p>_x000D_
_x000D_
 <!-- yearpicker panel for change only year-->_x000D_
 <div class="ydiv" id = "yearpicker">_x000D_
 <button class="ybutton" style="font-weight:bold;"onclick="changedecade('back')"><</button>_x000D_
_x000D_
 <input class ="ytext" id="dec"  type="text" value ="2018" >_x000D_
 _x000D_
 <button class="ybutton" style="font-weight:bold;" onclick="changedecade('next')">></button>_x000D_
 <hr></hr>_x000D_
_x000D_
_x000D_
_x000D_
    <!-- subpanel with one year 0-9 -->_x000D_
 <button  class="ybutton"  onclick="yearone = 0;setyear()">0</button>_x000D_
 <button  class="ybutton"  onclick="yearone = 1;setyear()">1</button>_x000D_
 <button  class="ybutton"  onclick="yearone = 2;setyear()">2</button>_x000D_
 <button  class="ybutton"  onclick="yearone = 3;setyear()">3</button>_x000D_
 <button  class="ybutton"  onclick="yearone = 4;setyear()">4</button><br>_x000D_
 <button  class="ybutton"  onclick="yearone = 5;setyear()">5</button>_x000D_
 <button  class="ybutton"  onclick="yearone = 6;setyear()">6</button>_x000D_
 <button  class="ybutton"  onclick="yearone = 7;setyear()">7</button>_x000D_
 <button  class="ybutton"  onclick="yearone = 8;setyear()">8</button>_x000D_
 <button  class="ybutton"  onclick="yearone = 9;setyear()">9</button>_x000D_
 </div>_x000D_
    <!-- end year panel -->_x000D_
_x000D_
_x000D_
_x000D_
 <script>_x000D_
 var date = new Date();_x000D_
 var year = date.getFullYear(); //get current year_x000D_
 //document.getElementById("yeardate").value = year;// can rem if filing text from database_x000D_
_x000D_
 var yearone = 0;_x000D_
 _x000D_
 function changedecade(val1){ //change decade for year_x000D_
_x000D_
 var x = parseInt(document.getElementById("dec").value.substring(0,3)+"0");_x000D_
 if (val1 == "next"){_x000D_
 document.getElementById('dec').value = x + 10;_x000D_
 }else{_x000D_
 document.getElementById('dec').value = x - 10;_x000D_
 }_x000D_
 }_x000D_
 _x000D_
 function setyear(){ //set full year as sum decade and one year in decade_x000D_
 var x = parseInt(document.getElementById("dec").value.substring(0,3)+"0");_x000D_
    var y = parseFloat(yearone);_x000D_
_x000D_
 var suma = x + y;_x000D_
    var d = new Date();_x000D_
    d.setFullYear(suma);_x000D_
 var year = d.getFullYear();_x000D_
 document.getElementById("dec").value = year;_x000D_
 document.getElementById("yeardate").value = year;_x000D_
 document.getElementById("yearpicker").style.display = "none";_x000D_
 yearone = 0;_x000D_
 }_x000D_
 _x000D_
 function enabledisable(){ //enable/disable year panel_x000D_
 if (document.getElementById("yearpicker").style.display == "block"){_x000D_
 document.getElementById("yearpicker").style.display = "none";}else{_x000D_
 document.getElementById("yearpicker").style.display = "block";_x000D_
 }_x000D_
 _x000D_
 }_x000D_
 </script>_x000D_
 </body>_x000D_
 </html>
_x000D_
_x000D_
_x000D_

Is there a C# case insensitive equals operator?

The best way to compare 2 strings ignoring the case of the letters is to use the String.Equals static method specifying an ordinal ignore case string comparison. This is also the fastest way, much faster than converting the strings to lower or upper case and comparing them after that.

I tested the performance of both approaches and the ordinal ignore case string comparison was more than 9 times faster! It is also more reliable than converting strings to lower or upper case (check out the Turkish i problem). So always use the String.Equals method to compare strings for equality:

String.Equals(string1, string2, StringComparison.OrdinalIgnoreCase);

If you want to perform a culture specific string comparison you can use the following code:

String.Equals(string1, string2, StringComparison.CurrentCultureIgnoreCase);

Please note that the second example uses the the string comparison logic of the current culture, which makes it slower than the "ordinal ignore case" comparison in the first example, so if you don't need any culture specific string comparison logic and you are after maximum performance, use the "ordinal ignore case" comparison.

For more information, read the full story on my blog.

Is there a way I can capture my iPhone screen as a video?

Here's my solution in a nutshell:

In recent years, when needing to produce moving visual content from the interface of an iOS app, I would require the developer provide a compiling of the app designed for the Simulator, (must be separately compiled because the apps are, by default compiled to run on the iPhone's ARM processor, whereas the Simulator runs on the Mac's Intel processor). This would then be screen captured on the Mac with something like Snapz Pro, Screenflow or something similar.

Beyond that, typical solutions required jailbreaking the device and installing a screen capture application sourced from the Cydia Store.

With the introduction of the iPad 2, Apple enabled full interface mirrored video output via either an authorized dock connector to HDMI dongle, or a dock connector to VGA dongle. (Note: Apple's composite and component options do not port mirrored content.) While the typical intent for these output mechanisms are to display the interface content to an external projector or High Definition Television, it is possible to record this mirrored content with a device capable of recording or transcoding content from such an incoming source. This option was also made possible with the introduction of the iPhone 4S. Quite often, recording this video content is done with HDMI capture cards installed on the capturing computer, such as those produced by Black Magic or AJA, among others. This is, or course limited to using computers that are capable of having such a capture card installed. Other options may include some HDMI record-enabled DVR devices (though many detect and disable such options) or firewire-based transcoding devices (like the Grass Valley ADVC-HD50, which I use).

Since getting the iPad 2 earlier this year, I have been using the Grass Valley ADVC HD50 to capture iOS screen motion from dock connected HDMI to a HDV compatible video capture application on my Mac. It has thus far worked flawlessly.

Here is an example from a video I recorded showing such captured content from both the iPHone 4S and the iPad 2.

http://youtu.be/k7jlPx8NAmw

However, now that Apple has enabled wireless iOS mirroring via Airplay in iOS 5, I find it is now much more convenient to connect an Apple TV device to the Grass Vally ADVC HD50, and capture the iOS interface screen recording wirelessly.

Here is a recent short video example in which the iPhone 4S interface was captured wirelessly via Airplay mirroring.

http://youtu.be/UKsixjcCXdI

I hope this helps.

Java/ JUnit - AssertTrue vs AssertFalse

I think it's just for your convenience (and the readers of your code)

Your code, and your unit tests should be ideally self documenting which this API helps with,

Think abt what is more clear to read:

AssertTrue(!(a > 3));

or

AssertFalse(a > 3);

When you open your tests after xx months when your tests suddenly fail, it would take you much less time to understand what went wrong in the second case (my opinion). If you disagree, you can always stick with AssertTrue for all cases :)

LAST_INSERT_ID() MySQL

This enables you to insert a row into 2 different tables and creates a reference to both tables too.

START TRANSACTION;
INSERT INTO accounttable(account_username) 
    VALUES('AnAccountName');
INSERT INTO profiletable(profile_account_id) 
    VALUES ((SELECT account_id FROM accounttable WHERE account_username='AnAccountName'));
    SET @profile_id = LAST_INSERT_ID(); 
UPDATE accounttable SET `account_profile_id` = @profile_id;
COMMIT;

Finding the index of elements based on a condition using python list comprehension

Maybe another question is, "what are you going to do with those indices once you get them?" If you are going to use them to create another list, then in Python, they are an unnecessary middle step. If you want all the values that match a given condition, just use the builtin filter:

matchingVals = filter(lambda x : x>2, a)

Or write your own list comprhension:

matchingVals = [x for x in a if x > 2]

If you want to remove them from the list, then the Pythonic way is not to necessarily remove from the list, but write a list comprehension as if you were creating a new list, and assigning back in-place using the listvar[:] on the left-hand-side:

a[:] = [x for x in a if x <= 2]

Matlab supplies find because its array-centric model works by selecting items using their array indices. You can do this in Python, certainly, but the more Pythonic way is using iterators and generators, as already mentioned by @EliBendersky.

ValueError: shape mismatch: objects cannot be broadcast to a single shape

This particular error implies that one of the variables being used in the arithmetic on the line has a shape incompatible with another on the same line (i.e., both different and non-scalar). Since n and the output of np.add.reduce() are both scalars, this implies that the problem lies with xm and ym, the two of which are simply your x and y inputs minus their respective means.

Based on this, my guess is that your x and y inputs have different shapes from one another, making them incompatible for element-wise multiplication.

** Technically, it's not that variables on the same line have incompatible shapes. The only problem is when two variables being added, multiplied, etc., have incompatible shapes, whether the variables are temporary (e.g., function output) or not. Two variables with different shapes on the same line are fine as long as something else corrects the issue before the mathematical expression is evaluated.

No internet on Android emulator - why and how to fix?

If you are using eclipse try:

Window > Preferences > Android > Launch

Default emulator options: -dns-server 8.8.8.8,8.8.4.4

How can I enable cURL for an installed Ubuntu LAMP stack?

Try:

sudo apt-get install php-curl

It worked on a fresh Ubuntu 16.04 (Xenial Xerus) LTS, with lamp-server and php7. I tried with php7-curl - it didn't work and also didn't work with php5-curl.

How can I make the computer beep in C#?

The solution would be,

Console.Beep

Add my custom http header to Spring RestTemplate request / extend RestTemplate

If the goal is to have a reusable RestTemplate which is in general useful for attaching the same header to a series of similar request a org.springframework.boot.web.client.RestTemplateCustomizer parameter can be used with a RestTemplateBuilder:

 String accessToken= "<the oauth 2 token>";
 RestTemplate restTemplate = new RestTemplateBuilder(rt-> rt.getInterceptors().add((request, body, execution) -> {
        request.getHeaders().add("Authorization", "Bearer "+accessToken);
        return execution.execute(request, body);
    })).build();

How can the Euclidean distance be calculated with NumPy?

It can be done like the following. I don't know how fast it is, but it's not using NumPy.

from math import sqrt
a = (1, 2, 3) # Data point 1
b = (4, 5, 6) # Data point 2
print sqrt(sum( (a - b)**2 for a, b in zip(a, b)))

How to access a RowDataPacket object

With Object.prototype approach, JSON.parse(JSON.stringify(rows)) returns object, extract values with Object.values()

const result = Object.values(JSON.parse(JSON.stringify(rows)));

Usage:

result.forEach((v) => console.log(v));

how to read a text file using scanner in Java?

Just another thing... Instead of System.out.println("Error Message Here"), use System.err.println("Error Message Here"). This will allow you to distinguish the differences between errors and normal code functioning by displaying the errors(i.e. everything inside System.err.println()) in red.

NOTE: It also works when used with System.err.print("Error Message Here")

Equivalent of typedef in C#

If you know what you're doing, you can define a class with implicit operators to convert between the alias class and the actual class.

class TypedefString // Example with a string "typedef"
{
    private string Value = "";
    public static implicit operator string(TypedefString ts)
    {
        return ((ts == null) ? null : ts.Value);
    }
    public static implicit operator TypedefString(string val)
    {
        return new TypedefString { Value = val };
    }
}

I don't actually endorse this and haven't ever used something like this, but this could probably work for some specific circumstances.

When use ResponseEntity<T> and @RestController for Spring RESTful applications

According to official documentation: Creating REST Controllers with the @RestController annotation

@RestController is a stereotype annotation that combines @ResponseBody and @Controller. More than that, it gives more meaning to your Controller and also may carry additional semantics in future releases of the framework.

It seems that it's best to use @RestController for clarity, but you can also combine it with ResponseEntity for flexibility when needed (According to official tutorial and the code here and my question to confirm that).

For example:

@RestController
public class MyController {

    @GetMapping(path = "/test")
    @ResponseStatus(HttpStatus.OK)
    public User test() {
        User user = new User();
        user.setName("Name 1");

        return user;
    }

}

is the same as:

@RestController
public class MyController {

    @GetMapping(path = "/test")
    public ResponseEntity<User> test() {
        User user = new User();
        user.setName("Name 1");

        HttpHeaders responseHeaders = new HttpHeaders();
        // ...
        return new ResponseEntity<>(user, responseHeaders, HttpStatus.OK);
    }

}

This way, you can define ResponseEntity only when needed.

Update

You can use this:

    return ResponseEntity.ok().headers(responseHeaders).body(user);

Go build: "Cannot find package" (even though GOPATH is set)

Although the accepted answer is still correct about needing to match directories with package names, you really need to migrate to using Go modules instead of using GOPATH. New users who encounter this problem may be confused about the mentions of using GOPATH (as was I), which are now outdated. So, I will try to clear up this issue and provide guidance associated with preventing this issue when using Go modules.

If you're already familiar with Go modules and are experiencing this issue, skip down to my more specific sections below that cover some of the Go conventions that are easy to overlook or forget.

This guide teaches about Go modules: https://golang.org/doc/code.html

Project organization with Go modules

Once you migrate to Go modules, as mentioned in that article, organize the project code as described:

A repository contains one or more modules. A module is a collection of related Go packages that are released together. A Go repository typically contains only one module, located at the root of the repository. A file named go.mod there declares the module path: the import path prefix for all packages within the module. The module contains the packages in the directory containing its go.mod file as well as subdirectories of that directory, up to the next subdirectory containing another go.mod file (if any).

Each module's path not only serves as an import path prefix for its packages, but also indicates where the go command should look to download it. For example, in order to download the module golang.org/x/tools, the go command would consult the repository indicated by https://golang.org/x/tools (described more here).

An import path is a string used to import a package. A package's import path is its module path joined with its subdirectory within the module. For example, the module github.com/google/go-cmp contains a package in the directory cmp/. That package's import path is github.com/google/go-cmp/cmp. Packages in the standard library do not have a module path prefix.

You can initialize your module like this:

$ go mod init github.com/mitchell/foo-app

Your code doesn't need to be located on github.com for it to build. However, it's a best practice to structure your modules as if they will eventually be published.

Understanding what happens when trying to get a package

There's a great article here that talks about what happens when you try to get a package or module: https://medium.com/rungo/anatomy-of-modules-in-go-c8274d215c16 It discusses where the package is stored and will help you understand why you might be getting this error if you're already using Go modules.

Ensure the imported function has been exported

Note that if you're having trouble accessing a function from another file, you need to ensure that you've exported your function. As described in the first link I provided, a function must begin with an upper-case letter to be exported and made available for importing into other packages.

Names of directories

Another critical detail (as was mentioned in the accepted answer) is that names of directories are what define the names of your packages. (Your package names need to match their directory names.) You can see examples of this here: https://medium.com/rungo/everything-you-need-to-know-about-packages-in-go-b8bac62b74cc With that said, the file containing your main method (i.e., the entry point of your application) is sort of exempt from this requirement.

As an example, I had problems with my imports when using a structure like this:

/my-app
+-- go.mod
+-- /src
   +-- main.go
   +-- /utils
      +-- utils.go

I was unable to import the code in utils into my main package.

However, once I put main.go into its own subdirectory, as shown below, my imports worked just fine:

/my-app
+-- go.mod
+-- /src
   +-- /app
   |  +-- main.go
   +-- /utils
      +-- utils.go

In that example, my go.mod file looks like this:

module git.mydomain.com/path/to/repo/my-app

go 1.14

When I saved main.go after adding a reference to utils.MyFunction(), my IDE automatically pulled in the reference to my package like this:

import "git.mydomain.com/path/to/repo/my-app/src/my-app"

(I'm using VS Code with the Golang extension.)

Notice that the import path included the subdirectory to the package.

Dealing with a private repo

If the code is part of a private repo, you need to run a git command to enable access. Otherwise, you can encounter other errors This article mentions how to do that for private Github, BitBucket, and GitLab repos: https://medium.com/cloud-native-the-gathering/go-modules-with-private-git-repositories-dfe795068db4 This issue is also discussed here: What's the proper way to "go get" a private repository?

Removing empty lines in Notepad++

You can search for the following regex: ^(?:[\t ]*(?:\r?\n|\r))+ and replace it with empty field

ASP.Net Download file to client browser

Just a slight addition to the above solution if you are having problem with downloaded file's name...

Response.AddHeader("Content-Disposition", "attachment; filename=\"" + file.Name + "\"");

This will return the exact file name even if it contains spaces or other characters.

Install MySQL on Ubuntu without a password prompt

This should do the trick

export DEBIAN_FRONTEND=noninteractive
sudo -E apt-get -q -y install mysql-server

Of course, it leaves you with a blank root password - so you'll want to run something like

mysqladmin -u root password mysecretpasswordgoeshere

Afterwards to add a password to the account.

How does a hash table work?

This turns out to be a pretty deep area of theory, but the basic outline is simple.

Essentially, a hash function is just a function that takes things from one space (say strings of arbitrary length) and maps them to a space useful for indexing (unsigned integers, say).

If you only have a small space of things to hash, you might get away with just interpreting those things as integers, and you're done (e.g. 4 byte strings)

Usually, though, you've got a much larger space. If the space of things you allow as keys is bigger than the space of things you are using to index (your uint32's or whatever) then you can't possibly have a unique value for each one. When two or more things hash to the same result, you'll have to handle the redundancy in an appropriate way (this is usually referred to as a collision, and how you handle it or don't will depend a bit on what you are using the hash for).

This implies you want it to be unlikely to have the same result, and you probably also would really like the hash function to be fast.

Balancing these two properties (and a few others) has kept many people busy!

In practice you usually should be able to find a function that is known to work well for your application and use that.

Now to make this work as a hashtable: Imagine you didn't care about memory usage. Then you can create an array as long as your indexing set (all uint32's, for example). As you add something to the table, you hash it's key and look at the array at that index. If there is nothing there, you put your value there. If there is already something there, you add this new entry to a list of things at that address, along with enough information (your original key, or something clever) to find which entry actually belongs to which key.

So as you go a long, every entry in your hashtable (the array) is either empty, or contains one entry, or a list of entries. Retrieving is a simple as indexing into the array, and either returning the value, or walking the list of values and returning the right one.

Of course in practice you typically can't do this, it wastes too much memory. So you do everything based on a sparse array (where the only entries are the ones you actually use, everything else is implicitly null).

There are lots of schemes and tricks to make this work better, but that's the basics.

How to change identity column values programmatically?

I saw a good article which helped me out at the last moment .. I was trying to insert few rows in a table which had identity column but did it wrongly and have to delete back. Once I deleted the rows then my identity column got changed . I was trying to find an way to update the column which was inserted but - no luck. So, while searching on google found a link ..

  1. Deleted the columns which was wrongly inserted
  2. Use force insert using identity on/off (explained below)

http://beyondrelational.com/modules/2/blogs/28/posts/10337/sql-server-how-do-i-insert-an-explicit-value-into-an-identity-column-how-do-i-update-the-value-of-an.aspx

Step out of current function with GDB

You can use the finish command.

finish: Continue running until just after function in the selected stack frame returns. Print the returned value (if any). This command can be abbreviated as fin.

(See 5.2 Continuing and Stepping.)

Fatal error: Maximum execution time of 30 seconds exceeded in C:\xampp\htdocs\wordpress\wp-includes\class-http.php on line 1610

  1. Find file:

    [XAMPP Installation Directory]\php\php.ini
    
  2. open php.ini.
  3. Find max_execution_time and increase the value of it as you required
  4. Restart XAMPP control panel

What is the python keyword "with" used for?

In python the with keyword is used when working with unmanaged resources (like file streams). It is similar to the using statement in VB.NET and C#. It allows you to ensure that a resource is "cleaned up" when the code that uses it finishes running, even if exceptions are thrown. It provides 'syntactic sugar' for try/finally blocks.

From Python Docs:

The with statement clarifies code that previously would use try...finally blocks to ensure that clean-up code is executed. In this section, I’ll discuss the statement as it will commonly be used. In the next section, I’ll examine the implementation details and show how to write objects for use with this statement.

The with statement is a control-flow structure whose basic structure is:

with expression [as variable]:
    with-block

The expression is evaluated, and it should result in an object that supports the context management protocol (that is, has __enter__() and __exit__() methods).

Update fixed VB callout per Scott Wisniewski's comment. I was indeed confusing with with using.

Updating state on props change in React Form

From react documentation : https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html

Erasing state when props change is an Anti Pattern

Since React 16, componentWillReceiveProps is deprecated. From react documentation, the recommended approach in this case is use

  1. Fully controlled component: the ParentComponent of the ModalBody will own the start_time state. This is not my prefer approach in this case since i think the modal should own this state.
  2. Fully uncontrolled component with a key: this is my prefer approach. An example from react documentation : https://codesandbox.io/s/6v1znlxyxn . You would fully own the start_time state from your ModalBody and use getInitialState just like you have already done. To reset the start_time state, you simply change the key from the ParentComponent

.NET data structures: ArrayList, List, HashTable, Dictionary, SortedList, SortedDictionary -- Speed, memory, and when to use each?

.NET data structures:

More to conversation about why ArrayList and List are actually different

Arrays

As one user states, Arrays are the "old school" collection (yes, arrays are considered a collection though not part of System.Collections). But, what is "old school" about arrays in comparison to other collections, i.e the ones you have listed in your title (here, ArrayList and List(Of T))? Let's start with the basics by looking at Arrays.

To start, Arrays in Microsoft .NET are, "mechanisms that allow you to treat several [logically-related] items as a single collection," (see linked article). What does that mean? Arrays store individual members (elements) sequentially, one after the other in memory with a starting address. By using the array, we can easily access the sequentially stored elements beginning at that address.

Beyond that and contrary to programming 101 common conceptions, Arrays really can be quite complex:

Arrays can be single dimension, multidimensional, or jadded (jagged arrays are worth reading about). Arrays themselves are not dynamic: once initialized, an array of n size reserves enough space to hold n number of objects. The number of elements in the array cannot grow or shrink. Dim _array As Int32() = New Int32(100) reserves enough space on the memory block for the array to contain 100 Int32 primitive type objects (in this case, the array is initialized to contain 0s). The address of this block is returned to _array.

According to the article, Common Language Specification (CLS) requires that all arrays be zero-based. Arrays in .NET support non-zero-based arrays; however, this is less common. As a result of the "common-ness" of zero-based arrays, Microsoft has spent a lot of time optimizing their performance; therefore, single dimension, zero-based (SZs) arrays are "special" - and really the best implementation of an array (as opposed to multidimensional, etc.) - because SZs have specific intermediary language instructions for manipulating them.

Arrays are always passed by reference (as a memory address) - an important piece of the Array puzzle to know. While they do bounds checking (will throw an error), bounds checking can also be disabled on arrays.

Again, the biggest hindrance to arrays is that they are not re-sizable. They have a "fixed" capacity. Introducing ArrayList and List(Of T) to our history:

ArrayList - non-generic list

The ArrayList (along with List(Of T) - though there are some critical differences, here, explained later) - is perhaps best thought of as the next addition to collections (in the broad sense). ArrayList inherit from the IList (a descendant of 'ICollection') interface. ArrayLists, themselves, are bulkier - requiring more overhead - than Lists.

IList does enable the implementation to treat ArrayLists as fixed-sized lists (like Arrays); however, beyond the additional functionallity added by ArrayLists, there are no real advantages to using ArrayLists that are fixed size as ArrayLists (over Arrays) in this case are markedly slower.

From my reading, ArrayLists cannot be jagged: "Using multidimensional arrays as elements... is not supported". Again, another nail in the coffin of ArrayLists. ArrayLists are also not "typed" - meaning that, underneath everything, an ArrayList is simply a dynamic Array of Objects: Object[]. This requires a lot of boxing (implicit) and unboxing (explicit) when implementing ArrayLists, again adding to their overhead.

Unsubstantiated thought: I think I remember either reading or having heard from one of my professors that ArrayLists are sort of the bastard conceptual child of the attempt to move from Arrays to List-type Collections, i.e. while once having been a great improvement to Arrays, they are no longer the best option as further development has been done with respect to collections

List(Of T): What ArrayList became (and hoped to be)

The difference in memory usage is significant enough to where a List(Of Int32) consumed 56% less memory than an ArrayList containing the same primitive type (8 MB vs. 19 MB in the above gentleman's linked demonstration: again, linked here) - though this is a result compounded by the 64-bit machine. This difference really demonstrates two things: first (1), a boxed Int32-type "object" (ArrayList) is much bigger than a pure Int32 primitive type (List); second (2), the difference is exponential as a result of the inner-workings of a 64-bit machine.

So, what's the difference and what is a List(Of T)? MSDN defines a List(Of T) as, "... a strongly typed list of objects that can be accessed by index." The importance here is the "strongly typed" bit: a List(Of T) 'recognizes' types and stores the objects as their type. So, an Int32 is stored as an Int32 and not an Object type. This eliminates the issues caused by boxing and unboxing.

MSDN specifies this difference only comes into play when storing primitive types and not reference types. Too, the difference really occurs on a large scale: over 500 elements. What's more interesting is that the MSDN documentation reads, "It is to your advantage to use the type-specific implementation of the List(Of T) class instead of using the ArrayList class...."

Essentially, List(Of T) is ArrayList, but better. It is the "generic equivalent" of ArrayList. Like ArrayList, it is not guaranteed to be sorted until sorted (go figure). List(Of T) also has some added functionality.

Change Circle color of radio button

  1. Declare custom style in your styles.xml file.

    <style name="MyRadioButton" parent="Theme.AppCompat.Light">  
      <item name="colorControlNormal">@color/indigo</item>
      <item name="colorControlActivated">@color/pink</item>
    </style>  
    
  2. Apply this style to your RadioButton via android:theme attribute.

    <RadioButton  
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:checked="true"
        android:text="Radio Button"
        android:theme="@style/MyRadioButton"/>
    

    only if your activity extends AppCompatActivity

OpenCV NoneType object has no attribute shape

You probably get the error because your video path may be wrong in a way. Be sure your path is completely correct.

How do you do the "therefore" (?) symbol on a Mac or in Textmate?

If you are trying to insert the therefore symbol into a WORD DOCUMENT

Hold down the ALT key and type 8756

Hope the answer ur question Regards Al~Hash.

How to export MySQL database with triggers and procedures?

May be it's obvious for expert users of MYSQL but I wasted some time while trying to figure out default value would not export functions. So I thought to mention here that --routines param needs to be set to true to make it work.

mysqldump --routines=true -u <user> my_database > my_database.sql

Notepad++ Multi editing

In the position where you want to add text, do:

Shift + Alt + down arrow

and select the lines you want. Then type. The text you type is inserted on all of the lines you selected.

trigger click event from angularjs directive

Here is perhaps a different way for you to achieve this. Pass into the directive both the index and the item and let the directive setup the html in a template:

Demo: http://plnkr.co/edit/ybcNosdPA76J1IqXjcGG?p=preview

html:

<ul id="thumbnails">
    <li class="thumbnail" ng-repeat="item in items" options='#my-container' itemdata='item' index="$index">

    </li>
  </ul>

js directive:

app.directive('thumbnail', [function() {
  return {
    restrict: 'CA',
    replace: false,
    transclude: false,
    scope: {
        index: '=index',
        item: '=itemdata'
    },
    template: '<a href="#"><img src="{{item.src}}" alt="{{item.alt}}" /></a>',
    link: function(scope, elem, attrs) {
        if (parseInt(scope.index) == 0) {
            angular.element(attrs.options).css({'background-image':'url('+ scope.item.src +')'});
        }

        elem.bind('click', function() {
            var src = elem.find('img').attr('src');

            // call your SmoothZoom here
            angular.element(attrs.options).css({'background-image':'url('+ scope.item.src +')'});
        });
    }
}
}]);

You probably would be better off adding a ng-click to the image as pointed out in another answer.

Update

The link for the demo was incorrect. It has been updated to: http://plnkr.co/edit/ybcNosdPA76J1IqXjcGG?p=preview

How to download a branch with git?

We can download a specified branch by using following magical command:

git clone -b < branch name > <remote_repo url> 

How to force ViewPager to re-instantiate its items

I have found a solution. It is just a workaround to my problem but currently the only solution.

ViewPager PagerAdapter not updating the View

public int getItemPosition(Object object) {
   return POSITION_NONE;
}

Does anyone know whether this is a bug or not?

How do I change the language of moment.js?

I had to import also the language:

import moment from 'moment'
import 'moment/locale/es'  // without this line it didn't work
moment.locale('es')

Then use moment like you normally would

alert(moment(date).fromNow())

how to get bounding box for div element in jquery

using JQuery:

myelement=$("#myelement")
[myelement.offset().left, myelement.offset().top,  myelement.width(), myelement.height()]

How to specify different Debug/Release output directories in QMake .pro file

It's also useful to have a slightly different name for the output executable. You can't use something like:

release: Target = ProgramName
debug: Target = ProgramName_d

Why it doesn't work is not clear, but it does not. But:

CONFIG(debug, debug|release) {
    TARGET = ProgramName
} else {
    TARGET = ProgramName_d
}

This does work as long as the CONFIG += line precedes it.

What is the difference between a HashMap and a TreeMap?

HashMap is implemented by Hash Table while TreeMap is implemented by Red-Black tree. The main difference between HashMap and TreeMap actually reflect the main difference between a Hash and a Binary Tree , that is, when iterating, TreeMap guarantee can the key order which is determined by either element's compareTo() method or a comparator set in the TreeMap's constructor.

Take a look at following diagram.

enter image description here

Save results to csv file with Python

This is how I do it

 import csv
    file = open('???.csv', 'r')
    read = csv.reader(file)
    for column in read:
            file = open('???.csv', 'r')
            read = csv.reader(file)
            file.close()
            file = open('????.csv', 'a', newline='')
            write = csv.writer(file, delimiter = ",")
            write.writerow((, ))
            file.close()

Python Linked List

I based this additional function on Nick Stinemates

def add_node_at_end(self, data):
    new_node = Node()
    node = self.curr_node
    while node:
        if node.next == None:
            node.next = new_node
            new_node.next = None
            new_node.data = data
        node = node.next

The method he has adds the new node at the beginning while I have seen a lot of implementations which usually add a new node at the end but whatever, it is fun to do.

How to get relative path from absolute path

As Alex Brault points out, especially on Windows, the absolute path (with drive letter and all) is unambiguous and often better.

Shouldn't your OpenFileDialog use a regular tree-browser structure?

To get some nomenclature in place, the RefDir is the directory relative to which you want to specify the path; the AbsName is the absolute path name that you want to map; and the RelPath is the resulting relative path.

Take the first of these options that matches:

  • If you have different drive letters, there is no relative path from RefDir to AbsName; you must use the AbsName.
  • If the AbsName is in a sub-directory of RefDir or is a file within RefDir then simply remove the RefDir from the start of AbsName to create RelPath; optionally prepend "./" (or ".\" since you are on Windows).
  • Find the longest common prefix of RefDir and AbsName (where D:\Abc\Def and D:\Abc\Default share D:\Abc as the longest common prefix; it has to be a mapping of name components, not a simple longest common substring); call it LCP. Remove LCP from AbsName and RefDir. For each path component left in (RefDir - LCP), prepend "..\" to (AbsName - LCP) to yield RelPath.

To illustrate the last rule (which is, of course, by far the most complex), start with:

RefDir = D:\Abc\Def\Ghi
AbsName = D:\Abc\Default\Karma\Crucible

Then

LCP = D:\Abc
(RefDir - LCP) = Def\Ghi
(Absname - LCP) = Default\Karma\Crucible
RelPath = ..\..\Default\Karma\Crucible

While I was typing, DavidK produced an answer which suggests that you are not the first to need this feature and that there is a standard function to do this job. Use it. But there's no harm in being able to think your way through from first principles, either.

Except that Unix systems do not support drive letters (so everything is always located under the same root directory, and the first bullet therefore is irrelevant), the same technique could be used on Unix.

How do I get the serial key for Visual Studio Express?

I have an improvement on the answer @DewiMorgan gave for VS 2008 express. I have since confirmed it also works on VS 2005 express.
It lets you run the software without it EVER requiring registration, and also makes it so you don't have to manually delete the key every 30 days. It does this by preventing the key from ever being written.

(Deleting the correct key can also let you avoid registering VS 2015 "Community Edition," but using permissions to prevent the key being written will make the IDE crash, so I haven't found a great solution for it yet.)

The directions assume Visual C# Express 2008, but this works on all the other visual studio express apps I can find.

  1. Open regedit, head to HKEY_CURRENT_USER\Software\Microsoft\VCSExpress\9.0\Registration.
  2. Delete the value Params. picture of me deleting the value 'Params' in the registry.
  3. Right click on the key 'Registration' in the tree, and click permissions.
  4. Click Advanced...
  5. Go to the permissions tab, and uncheck the box labeled Inherit from parent the permission entries that apply to child objects. Include these with entries explicitly defined here. me unchecking the box
  6. In the dialog that opens, click copy.
    the security dialog that pops up
    Note that in Windows 7 (and 8/8.1, I think), it appears the copy button was renamed to add, as in add inherited permissions as explicit permissions.

    In Windows 10, it appears things changed again. @ravuya says that you might have to manually re-create some of the permissions, as the registry editor no longer offers this exact functionality directly. I don't use Windows very much anymore, so I'll defer to them:

    On Win10, there is a button called "Disable Inheritance" that does the same thing as the checkbox mentioned in step 5. It is necessary to create new permissions just for Registration, instead of inheriting those permissions from an upstream registry key.

  7. Hit OK in the 'Advanced' window.
  8. Back in the first permissions window, click your user, and uncheck Full Control. Me unchecking 'full control'

  9. Do the same thing for the Administrators group. Me unchecking 'full control' for the Administrators group

  10. Hit OK or Apply. Congratulations, you will never again be plagued by the registration nag, and just like WinRAR, your trial will never expire.

You may have to do the same thing for other (non-Visual C#) programs, like Visual Basic express or Visual C++ express.

It has been reported by @IronManMark20 in the comments that simply deleting the registry key works and that Visual Studio does not attempt to re-create the key. I am not sure if I believe this because when I installed VS on a clean windows installation, the key was not created until I ran VS at least once. But for what it's worth, that may be an option as well.

Repository Pattern Step by Step Explanation

As a summary, I would describe the wider impact of the repository pattern. It allows all of your code to use objects without having to know how the objects are persisted. All of the knowledge of persistence, including mapping from tables to objects, is safely contained in the repository.

Very often, you will find SQL queries scattered in the codebase and when you come to add a column to a table you have to search code files to try and find usages of a table. The impact of the change is far-reaching.

With the repository pattern, you would only need to change one object and one repository. The impact is very small.

Perhaps it would help to think about why you would use the repository pattern. Here are some reasons:

  • You have a single place to make changes to your data access

  • You have a single place responsible for a set of tables (usually)

  • It is easy to replace a repository with a fake implementation for testing - so you don't need to have a database available to your unit tests

There are other benefits too, for example, if you were using MySQL and wanted to switch to SQL Server - but I have never actually seen this in practice!

How do I kill all the processes in Mysql "show processlist"?

We can do it by MySQL Workbench. Just execute this:

kill id;

Example:

kill 13412

That will remove it.

Removing duplicate characters from a string

def remove_duplicates(value):
    var=""
    for i in value:
        if i in value:
            if i in var:
                pass
            else:
                var=var+i
    return var

print(remove_duplicates("11223445566666ababzzz@@@123#*#*"))

How can I write data attributes using Angular?

Use attribute binding syntax instead

<ol class="viewer-nav"><li *ngFor="let section of sections" 
    [attr.data-sectionvalue]="section.value">{{ section.text }}</li>  
</ol>

or

<ol class="viewer-nav"><li *ngFor="let section of sections" 
    attr.data-sectionvalue="{{section.value}}">{{ section.text }}</li>  
</ol>

See also :

How to use QTimer

mytimer.h:

    #ifndef MYTIMER_H
    #define MYTIMER_H

    #include <QTimer>

    class MyTimer : public QObject
    {
        Q_OBJECT
    public:
        MyTimer();
        QTimer *timer;

    public slots:
        void MyTimerSlot();
    };

    #endif // MYTIME

mytimer.cpp:

#include "mytimer.h"
#include <QDebug>

MyTimer::MyTimer()
{
    // create a timer
    timer = new QTimer(this);

    // setup signal and slot
    connect(timer, SIGNAL(timeout()),
          this, SLOT(MyTimerSlot()));

    // msec
    timer->start(1000);
}

void MyTimer::MyTimerSlot()
{
    qDebug() << "Timer...";
}

main.cpp:

#include <QCoreApplication>
#include "mytimer.h"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    // Create MyTimer instance
    // QTimer object will be created in the MyTimer constructor
    MyTimer timer;

    return a.exec();
}

If we run the code:

Timer...
Timer...
Timer...
Timer...
Timer...
...

resources

How to clear jQuery validation error messages?

If you want to reset numberOfInvalids() as well then add following line in resetForm function in jquery.validate.js file line number: 415.

this.invalid = {};

Is it possible in Java to access private fields via reflection

Yes, it absolutely is - assuming you've got the appropriate security permissions. Use Field.setAccessible(true) first if you're accessing it from a different class.

import java.lang.reflect.*;

class Other
{
    private String str;
    public void setStr(String value)
    {
        str = value;
    }
}

class Test
{
    public static void main(String[] args)
        // Just for the ease of a throwaway test. Don't
        // do this normally!
        throws Exception
    {
        Other t = new Other();
        t.setStr("hi");
        Field field = Other.class.getDeclaredField("str");
        field.setAccessible(true);
        Object value = field.get(t);
        System.out.println(value);
    }
}

And no, you shouldn't normally do this... it's subverting the intentions of the original author of the class. For example, there may well be validation applied in any situation where the field can normally be set, or other fields may be changed at the same time. You're effectively violating the intended level of encapsulation.

Exec : display stdout "live"

child_process.spawn returns an object with stdout and stderr streams. You can tap on the stdout stream to read data that the child process sends back to Node. stdout being a stream has the "data", "end", and other events that streams have. spawn is best used to when you want the child process to return a large amount of data to Node - image processing, reading binary data etc.

so you can solve your problem using child_process.spawn as used below.

var spawn = require('child_process').spawn,
ls = spawn('coffee -cw my_file.coffee');

ls.stdout.on('data', function (data) {
  console.log('stdout: ' + data.toString());
});

ls.stderr.on('data', function (data) {
  console.log('stderr: ' + data.toString());
});

ls.on('exit', function (code) {
  console.log('code ' + code.toString());
});

Generate random number between two numbers in JavaScript

This works for me and produces values like Python's random.randint standard library function:


function randint(min, max) {
   return Math.round((Math.random() * Math.abs(max - min)) + min);
}

console.log("Random integer: " + randint(-5, 5));

Shell - How to find directory of some command?

In the TENEX C Shell, tcsh, one can list a command's location(s), or if it is a built-in command, using the where command e.g.:

tcsh% where python
/usr/local/bin/python
/usr/bin/python

tcsh% where cd
cd is a shell built-in
/usr/bin/cd

Find Facebook user (url to profile page) by known email address

Maybe things changed, but I recall rapleaf had a service where you enter an email address and you could receive a facebook id.
https://www.rapleaf.com/

If something was not in there, one could "sign up" with the email, and it should have a chance to get the data after a while.

I came across this when using a search tool called Maltego a few years back.
The app uses many types of "transforms", and a few where related to facebook and twitter etc..

..or find some new sqli's on fb and fb apps, hehe. :)

What's the difference between OpenID and OAuth?

OpenID is (mainly) for identification/authentication, so that stackoverflow.com knows that I own chris.boyle.name (or wherever) and therefore that I am probably the same person who owned chris.boyle.name yesterday and earned some reputation points.

OAuth is designed for authorization to take actions on your behalf, so that stackoverflow.com (or wherever) can ask permission to, say, Tweet on your behalf automatically, without knowing your Twitter password.

Is there a pretty print for PHP?

Here is a version of pp that works for objects as well as arrays (I also took out the commas):

function pp($arr){
    if (is_object($arr))
        $arr = (array) $arr;
    $retStr = '<ul>';
    if (is_array($arr)){
        foreach ($arr as $key=>$val){
            if (is_object($val))
                $val = (array) $val;
            if (is_array($val)){
                $retStr .= '<li>' . $key . ' => array(' . pp($val) . ')</li>';
            }else{
                $retStr .= '<li>' . $key . ' => ' . ($val == '' ? '""' : $val) . '</li>';
            }
        }
    }
    $retStr .= '</ul>';
    return $retStr;
}

convert date string to mysql datetime field

First, convert the string into a timestamp:

$timestamp = strtotime($string);

Then do a

date("Y-m-d H:i:s", $timestamp);

Get the cartesian product of a series of lists?

I believe this works:

def cartesian_product(L):  
   if L:
       return {(a,) + b for a in L[0] 
                        for b in cartesian_product(L[1:])}
   else:
       return {()}

java, get set methods

To understand get and set, it's all related to how variables are passed between different classes.

The get method is used to obtain or retrieve a particular variable value from a class.

A set value is used to store the variables.

The whole point of the get and set is to retrieve and store the data values accordingly.

What I did in this old project was I had a User class with my get and set methods that I used in my Server class.

The User class's get set methods:

public int getuserID()
    {
        //getting the userID variable instance
        return userID;
    }
    public String getfirstName()
    {
        //getting the firstName variable instance
        return firstName;
    }
    public String getlastName()
    {
        //getting the lastName variable instance
        return lastName;
    }
    public int getage()
    {
        //getting the age variable instance
        return age;
    }

    public void setuserID(int userID)
    {
        //setting the userID variable value
        this.userID = userID;
    }
    public void setfirstName(String firstName)
    {
        //setting the firstName variable text
        this.firstName = firstName;
    }
    public void setlastName(String lastName)
    {
        //setting the lastName variable text
        this.lastName = lastName;
    }
    public void setage(int age)
    {
        //setting the age variable value
        this.age = age;
    }
}

Then this was implemented in the run() method in my Server class as follows:

//creates user object
                User use = new User(userID, firstName, lastName, age);
                //Mutator methods to set user objects
                use.setuserID(userID);
                use.setlastName(lastName);
                use.setfirstName(firstName);               
                use.setage(age); 

Understanding Spring @Autowired usage

Nothing in the example says that the "classes implementing the same interface". MovieCatalog is a type and CustomerPreferenceDao is another type. Spring can easily tell them apart.

In Spring 2.x, wiring of beans mostly happened via bean IDs or names. This is still supported by Spring 3.x but often, you will have one instance of a bean with a certain type - most services are singletons. Creating names for those is tedious. So Spring started to support "autowire by type".

What the examples show is various ways that you can use to inject beans into fields, methods and constructors.

The XML already contains all the information that Spring needs since you have to specify the fully qualified class name in each bean. You need to be a bit careful with interfaces, though:

This autowiring will fail:

 @Autowired
 public void prepare( Interface1 bean1, Interface1 bean2 ) { ... }

Since Java doesn't keep the parameter names in the byte code, Spring can't distinguish between the two beans anymore. The fix is to use @Qualifier:

 @Autowired
 public void prepare( @Qualifier("bean1") Interface1 bean1,
     @Qualifier("bean2")  Interface1 bean2 ) { ... }

React js onClick can't pass value to method

I have below 3 suggestion to this on JSX onClick Events -

  1. Actually, we don't need to use .bind() or Arrow function in our code. You can simple use in your code.

  2. You can also move onClick event from th(or ul) to tr(or li) to improve the performance. Basically you will have n number of "Event Listeners" for your n li element.

    So finally code will look like this:
    <ul onClick={this.onItemClick}>
        {this.props.items.map(item =>
               <li key={item.id} data-itemid={item.id}>
                   ...
               </li>
          )}
    </ul>
    

    // And you can access item.id in onItemClick method as shown below:

    onItemClick = (event) => {
       console.log(e.target.getAttribute("item.id"));
    }
    
  3. I agree with the approach mention above for creating separate React Component for ListItem and List. This make code looks good however if you have 1000 of li then 1000 Event Listeners will be created. Please make sure you should not have much event listener.

    import React from "react";
    import ListItem from "./ListItem";
    export default class List extends React.Component {
    
        /**
        * This List react component is generic component which take props as list of items and also provide onlick
        * callback name handleItemClick
        * @param {String} item - item object passed to caller
        */
        handleItemClick = (item) => {
            if (this.props.onItemClick) {
                this.props.onItemClick(item);
            }
        }
    
        /**
        * render method will take list of items as a props and include ListItem component
        * @returns {string} - return the list of items
        */
        render() {
            return (
                <div>
                  {this.props.items.map(item =>
                      <ListItem key={item.id} item={item} onItemClick={this.handleItemClick}/>
                  )}
                </div>
            );
        }
    
    }
    
    
    import React from "react";
    
    export default class ListItem extends React.Component {
        /**
        * This List react component is generic component which take props as item and also provide onlick
        * callback name handleItemClick
        * @param {String} item - item object passed to caller
        */
        handleItemClick = () => {
            if (this.props.item && this.props.onItemClick) {
                this.props.onItemClick(this.props.item);
            }
        }
        /**
        * render method will take item as a props and print in li
        * @returns {string} - return the list of items
        */
        render() {
            return (
                <li key={this.props.item.id} onClick={this.handleItemClick}>{this.props.item.text}</li>
            );
        }
    }
    

How to create a inset box-shadow only on one side?

The trick is a second .box-inner inside, which is larger in width than the original .box, and the box-shadow is applied to that.

Then, added more padding to the .text to make up for the added width.

This is how the logic looks:

box logic

And here's how it's done in CSS:

Use max width for .inner-box to not cause .box to get wider, and overflow to make sure the remaining is clipped:

.box {
    max-width: 100% !important;
    overflow: hidden;
}

110% is wider than the parent which is 100% in a child's context (should be the same when the parent .box has a fixed width, for example). Negative margins make up for the width and cause the element to be centered (instead of only the right part hiding):

.box-inner {
    width: 110%;
    margin-left:-5%;
    margin-right: -5%;
    -webkit-box-shadow: inset 0px 5px 10px 1px #000000;
    box-shadow: inset 0px 5px 10px 1px #000000;
}

And add some padding on the X axis to make up for the wider .inner-box:

.text {
    padding: 20px 40px;
}

Here's a working Fiddle.

If you inspect the Fiddle, you'll see:

.box .box-inner .text

Get value of c# dynamic property via string

public static object GetProperty(object target, string name)
{
    var site = System.Runtime.CompilerServices.CallSite<Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.GetMember(0, name, target.GetType(), new[]{Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(0,null)}));
    return site.Target(site, target);
}

Add reference to Microsoft.CSharp. Works also for dynamic types and private properties and fields.

Edit: While this approach works, there is almost 20× faster method from the Microsoft.VisualBasic.dll assembly:

public static object GetProperty(object target, string name)
{
    return Microsoft.VisualBasic.CompilerServices.Versioned.CallByName(target, name, CallType.Get);
}

Proper indentation for Python multiline strings

I prefer

    def method():
        string = \
"""\
line one
line two
line three\
"""

or

    def method():
        string = """\
line one
line two
line three\
"""

Is there any 'out-of-the-box' 2D/3D plotting library for C++?

Just an idea: Use Python as embeddable scripting language to plot your graphs. Python has a plethora of plotting libraries.

Displaying a vector of strings in C++

You ask two questions; your title says "Displaying a vector of strings", but you're not actually doing that, you actually build a single string composed of all the strings and output that.

Your question body asks "Why doesn't this work".

It doesn't work because your for loop is constrained by "userString.size()" which is 0, and you test your loop variable for being "userString.size() - 1". The condition of a for() loop is tested before permitting execution of the first iteration.

int n = 1;
for (int i = 1; i < n; ++i) {
    std::cout << i << endl;
}

will print exactly nothing.

So your loop executes exactly no iterations, leaving userString and sentence empty.

Lastly, your code has absolutely zero reason to use a vector. The fact that you used "decltype(userString.size())" instead of "size_t" or "auto", while claiming to be a rookie, suggests you're either reading a book from back to front or you are setting yourself up to fail a class.

So to answer your question at the end of your post: It doesn't work because you didn't step through it with a debugger and inspect the values as it went. While I say it tongue-in-cheek, I'm going to leave it out there.

Array slices in C#

You could use the arrays CopyTo() method.

Or with LINQ you can use Skip() and Take()...

byte[] arr = {1, 2, 3, 4, 5, 6, 7, 8};
var subset = arr.Skip(2).Take(2);

How to insert new row to database with AUTO_INCREMENT column without specifying column names?

Even better, use DEFAULT instead of NULL. You want to store the default value, not a NULL that might trigger a default value.

But you'd better name all columns, with a piece of SQL you can create all the INSERT, UPDATE and DELETE's you need. Just check the information_schema and construct the queries you need. There is no need to do it all by hand, SQL can help you out.

Gets last digit of a number

Without using '%'.

public int lastDigit(int no){
    int n1 = no / 10;
    n1 = no - n1 * 10;
    return n1;
}

How to get my Android device Internal Download Folder path

if a device has an SD card, you use:

Environment.getExternalStorageState() 

if you don't have an SD card, you use:

Environment.getDataDirectory()

if there is no SD card, you can create your own directory on the device locally.

    //if there is no SD card, create new directory objects to make directory on device
        if (Environment.getExternalStorageState() == null) {
                        //create new file directory object
            directory = new File(Environment.getDataDirectory()
                    + "/RobotiumTestLog/");
            photoDirectory = new File(Environment.getDataDirectory()
                    + "/Robotium-Screenshots/");
            /*
             * this checks to see if there are any previous test photo files
             * if there are any photos, they are deleted for the sake of
             * memory
             */
            if (photoDirectory.exists()) {
                File[] dirFiles = photoDirectory.listFiles();
                if (dirFiles.length != 0) {
                    for (int ii = 0; ii <= dirFiles.length; ii++) {
                        dirFiles[ii].delete();
                    }
                }
            }
            // if no directory exists, create new directory
            if (!directory.exists()) {
                directory.mkdir();
            }

            // if phone DOES have sd card
        } else if (Environment.getExternalStorageState() != null) {
            // search for directory on SD card
            directory = new File(Environment.getExternalStorageDirectory()
                    + "/RobotiumTestLog/");
            photoDirectory = new File(
                    Environment.getExternalStorageDirectory()
                            + "/Robotium-Screenshots/");
            if (photoDirectory.exists()) {
                File[] dirFiles = photoDirectory.listFiles();
                if (dirFiles.length > 0) {
                    for (int ii = 0; ii < dirFiles.length; ii++) {
                        dirFiles[ii].delete();
                    }
                    dirFiles = null;
                }
            }
            // if no directory exists, create new directory to store test
            // results
            if (!directory.exists()) {
                directory.mkdir();
            }
        }// end of SD card checking

add permissions on your manifest.xml

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Happy coding..

Using DateTime in a SqlParameter for Stored Procedure, format error

Just use:

 param.AddWithValue("@Date_Of_Birth",DOB);

That will take care of all your problems.

How to add to an existing hash in Ruby

my_hash = {:a => 5}
my_hash[:key] = "value"

pip3: command not found

After yum install python3-pip, check the name of the installed binary. e.g.

ll /usr/bin/pip*

On my CentOS 7, it is named as pip-3 instead of pip3.

What is a callback in java

Callbacks are most easily described in terms of the telephone system. A function call is analogous to calling someone on a telephone, asking her a question, getting an answer, and hanging up; adding a callback changes the analogy so that after asking her a question, you also give her your name and number so she can call you back with the answer.

Paul Jakubik, Callback Implementations in C++.

What's the best way to calculate the size of a directory in .NET?

Multi thread example to calculate directory size from Microsoft Docs, which would be faster

using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      long totalSize = 0;

      String[] args = Environment.GetCommandLineArgs();
      if (args.Length == 1) {
         Console.WriteLine("There are no command line arguments.");
         return;
      }
      if (! Directory.Exists(args[1])) {
         Console.WriteLine("The directory does not exist.");
         return;
      }

      String[] files = Directory.GetFiles(args[1]);
      Parallel.For(0, files.Length,
                   index => { FileInfo fi = new FileInfo(files[index]);
                              long size = fi.Length;
                              Interlocked.Add(ref totalSize, size);
                   } );
      Console.WriteLine("Directory '{0}':", args[1]);
      Console.WriteLine("{0:N0} files, {1:N0} bytes", files.Length, totalSize);
   }
}
// The example displaysoutput like the following:
//       Directory 'c:\windows\':
//       32 files, 6,587,222 bytes

This example only calculate the files in current folder, so if you want to calculate all the files recursively, you can change the

String[] files = Directory.GetFiles(args[1]);

to

String[] files = Directory.GetFiles(args[1], "*", SearchOption.AllDirectories);

Pointer to incomplete class type is not allowed

An "incomplete class" is one declared but not defined. E.g.

class Wielrenner;

as opposed to

class Wielrenner
{
    /* class members */
};

You need to #include "wielrenner.h" in dokter.ccp

how to delete files from amazon s3 bucket?

if you are trying to delete file using your own local host console then you can try running this python script assuming that you have have already assigned your access id and secret key in the system

import boto3

#my custom sesssion
aws_m=boto3.session.Session(profile_name="your-profile-name-on-local-host")
client=aws_m.client('s3')

#list bucket objects before deleting 
response = client.list_objects(
    Bucket='your-bucket-name'
)
for x in response.get("Contents", None):
    print(x.get("Key",None));

#delete bucket objects
response = client.delete_object(
    Bucket='your-bucket-name',
    Key='mydocs.txt'
)

#list bucket objects after deleting
response = client.list_objects(
    Bucket='your-bucket-name'
)
for x in response.get("Contents", None):
    print(x.get("Key",None));

How to read and write into file using JavaScript?

The future is here! The proposals are closer to completion, no more ActiveX or flash or java. Now we can use:

You could use the Drag/Drop to get the file into the browser, or a simple upload control. Once the user has selected a file, you can read it w/ Javascript: http://www.html5rocks.com/en/tutorials/file/dndfiles/

How do you check if a certain index exists in a table?

AdaTheDEV, I used your syntax and created the following and why.

Problem: Process runs once a quarter taking an hour due to missing index.

Correction: Alter query process or Procedure to check for index and create it if missing... Same code is placed at the end of the query and procedure to remove index since it is not needed but quarterly. Showing Only drop syntax here

-- drop the index 
begin

  IF EXISTS (SELECT *  FROM sys.indexes  WHERE name='Index_Name' 
    AND object_id = OBJECT_ID('[SchmaName].[TableName]'))
  begin
    DROP INDEX [Index_Name] ON [SchmaName].[TableName];
  end

end

What is the SQL command to return the field names of a table?

MySQL 3 and 4 (and 5):

desc tablename

which is an alias for

show fields from tablename

SQL Server (from 2000) and MySQL 5:

select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS 
where TABLE_NAME = 'tablename'

Completing the answer: like people below have said, in SQL Server you can also use the stored procedure sp_help

exec sp_help 'tablename'

Automatically add all files in a folder to a target using CMake?

So Why not use powershell to create the list of source files for you. Take a look at this script

param (
    [Parameter(Mandatory=$True)]
    [string]$root 
)

if (-not (Test-Path  -Path $root)) {    
throw "Error directory does not exist"
}

#get the full path of the root
$rootDir = get-item -Path $root
$fp=$rootDir.FullName;


$files = Get-ChildItem -Path $root -Recurse -File | 
         Where-Object { ".cpp",".cxx",".cc",".h" -contains $_.Extension} | 
         Foreach {$_.FullName.replace("${fp}\","").replace("\","/")}

$CMakeExpr = "set(SOURCES "

foreach($file in $files){

    $CMakeExpr+= """$file"" " ;
}
$CMakeExpr+=")"
return $CMakeExpr;

Suppose you have a folder with this structure

C:\Workspace\A
--a.cpp
C:\Workspace\B 
--b.cpp

Now save this file as "generateSourceList.ps1" for example, and run the script as

~>./generateSourceList.ps1 -root "C:\Workspace" > out.txt

out.txt file will contain

set(SOURCE "A/a.cpp" "B/b.cpp")

Javascript select onchange='this.form.submit()'

Bind them using jQuery and make jQuery handle it: http://jsfiddle.net/ZmxpW/.

$('select').change(function() {
    $(this).parents('form').submit();
});

Definitive way to trigger keypress events with jQuery

In case you need to take into account the current cursor and text selection...

This wasn't working for me for an AngularJS app on Chrome. As Nadia points out in the original comments, the character is never visible in the input field (at least, that was my experience). In addition, the previous solutions don't take into account the current text selection in the input field. I had to use a wonderful library jquery-selection.

I have a custom on-screen numeric keypad that fills in multiple input fields. I had to...

  1. On focus, save the lastFocus.element
  2. On blur, save the current text selection (start and stop)

    var pos = element.selection('getPos')
    lastFocus.pos = { start: pos.start, end: pos.end}
    
  3. When a button on the my keypad is pressed:

    lastFocus.element.selection( 'setPos', lastFocus.pos)
    lastFocus.element.selection( 'replace', {text: myKeyPadChar, caret: 'end'})
    

is vs typeof

Does it matter which is faster, if they don't do the same thing? Comparing the performance of statements with different meaning seems like a bad idea.

is tells you if the object implements ClassA anywhere in its type heirarchy. GetType() tells you about the most-derived type.

Not the same thing.

Fix columns in horizontal scrolling

Solved using JavaScript + jQuery! I just need similar solution to my project but current solution with HTML and CSS is not ok for me because there is issue with column height + I need more then one column to be fixed. So I create simple javascript solution using jQuery

You can try it here https://jsfiddle.net/kindrosker/ffwqvntj/

All you need is setup home many columsn will be fixed in data-count-fixed-columns parameter

<table class="table" data-count-fixed-columns="2" cellpadding="0" cellspacing="0">

and run js function

app_handle_listing_horisontal_scroll($('#table-listing'))

What is perm space?

What exists under PremGen : Class Area comes under PremGen area. Static fields are also developed at class loading time, so they also exist in PremGen. Constant Pool area having all immutable fields that are pooled like String are kept here. In addition to that, class data loaded by class loaders, Object arrays, internal objects used by jvm are also located.

SQL Server procedure declare a list

I've always found it easier to invert the test against the list in situations like this. For instance...

SELECT 
    field0, field1, field2 
FROM 
    my_table 
WHERE 
    ',' + @mysearchlist + ',' LIKE '%,' + CAST(field3 AS VARCHAR) + ',%' 

This means that there is no complicated mish-mash required for the values that you are looking for.

As an example, if our list was ('1,2,3'), then we add a comma to the start and end of our list like so: ',' + @mysearchlist + ','.

We also do the same for the field value we're looking for and add wildcards: '%,' + CAST(field3 AS VARCHAR) + ',%' (notice the % and the , characters).

Finally we test the two using the LIKE operator: ',' + @mysearchlist + ',' LIKE '%,' + CAST(field3 AS VARCHAR) + ',%'.

How to get the command line args passed to a running process on unix/linux systems?

Another variant of printing /proc/PID/cmdline with spaces in Linux is:

cat -v /proc/PID/cmdline | sed 's/\^@/\ /g' && echo

In this way cat prints NULL characters as ^@ and then you replace them with a space using sed; echo prints a newline.

How to turn a vector into a matrix in R?

A matrix is really just a vector with a dim attribute (for the dimensions). So you can add dimensions to vec using the dim() function and vec will then be a matrix:

vec <- 1:49
dim(vec) <- c(7, 7)  ## (rows, cols)
vec

> vec <- 1:49
> dim(vec) <- c(7, 7)  ## (rows, cols)
> vec
     [,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,]    1    8   15   22   29   36   43
[2,]    2    9   16   23   30   37   44
[3,]    3   10   17   24   31   38   45
[4,]    4   11   18   25   32   39   46
[5,]    5   12   19   26   33   40   47
[6,]    6   13   20   27   34   41   48
[7,]    7   14   21   28   35   42   49

Difference between mkdir() and mkdirs() in java for java.io.File

mkdir()

creates only one directory at a time, if it is parent that one only. other wise it can create the sub directory(if the specified path is existed only) and do not create any directories in between any two directories. so it can not create smultiple directories in one directory

mkdirs()

create the multiple directories(in between two directories also) at a time.

What is the best way to do a substring in a batch file?

Nicely explained above!

For all those who may suffer like me to get this working in a localized Windows (mine is XP in Slovak), you may try to replace the % with a !

So:

SET TEXT=Hello World
SET SUBSTRING=!TEXT:~3,5!
ECHO !SUBSTRING!

Run a Java Application as a Service on Linux

Referring to Spring Boot application as a Service as well, I would go for the systemd version, since it's the easiest, least verbose, and best integrated into modern distros (and even the not-so-modern ones like CentOS 7.x).

How to find when a web page was last updated

No, you cannot know when a page was last updated or last changed or uploaded to a server (which might, depending on interpretation, be three different things) just by accessing the page.

A server may, and should (according to the HTTP 1.1 protocol), send a Last-Modified header, which you can find out in several ways, e.g. using Rex Swain’s HTTP Viewer. However, according to the protocol, this is just

“the date and time at which the origin server believes the variant was last modified”.

And the protocol realistically adds:

“The exact meaning of this header field depends on the implementation of the origin server and the nature of the original resource. For files, it may be just the file system last-modified time. For entities with dynamically included parts, it may be the most recent of the set of last-modify times for its component parts. For database gateways, it may be the last-update time stamp of the record. For virtual objects, it may be the last time the internal state changed.”

In practice, web pages are very often dynamically created from a Content Management System or otherwise, and in such cases, the Last-Modified header typically shows a data stamp of creating the response, which is normally very close to the time of the request. This means that the header is practically useless in such cases.

Even in the case of a “static” page (the server simply picks up a file matching the request and sends it), the Last-Modified date stamp normally indicates just the last write access to the file on the server. This might relate to a time when the file was restored from a backup copy, or a time when the file was edited on the server without making any change to the content, or a time when it was uploaded onto the server, possibly replacing an older identical copy. In these cases, assuming that the time stamp is technically correct, it indicates a time after which the page has not been changed (but not necessarily the time of last change).

How to use a Bootstrap 3 glyphicon in an html select

If you are using the glyphicon as the first character of the string, you can use the html char (see https://glyphicons.bootstrapcheatsheets.com/) and then apply the font to the first character of the element:

    option::first-letter{
        font-family: Glyphicons Halflings;
    }

MySQl Error #1064

Sometimes when your table has a similar name to the database name you should use back tick. so instead of:

INSERT INTO books.book(field1, field2) VALUES ('value1', 'value2');

You should have this:

INSERT INTO `books`.`book`(`field1`, `field2`) VALUES ('value1', 'value2');

Difference between DOMContentLoaded and load events

  • domContentLoaded: marks the point when both the DOM is ready and there are no stylesheets that are blocking JavaScript execution - meaning we can now (potentially) construct the render tree. Many JavaScript frameworks wait for this event before they start executing their own logic. For this reason the browser captures the EventStart and EventEnd timestamps to allow us to track how long this execution took.

  • loadEvent: as a final step in every page load the browser fires an “onload” event which can trigger additional application logic.

source

How to get all selected values from <select multiple=multiple>?

The usual way:

var values = $('#select-meal-type').val();

From the docs:

In the case of <select multiple="multiple"> elements, the .val() method returns an array containing each selected option;

git am error: "patch does not apply"

I faced same error. I reverted the commit version while creating patch. it worked as earlier patch was in reverse way.

[mrdubey@SNF]$ git log 65f1d63 commit 65f1d6396315853f2b7070e0e6d99b116ba2b018 Author: Dubey Mritunjaykumar

Date: Tue Jan 22 12:10:50 2019 +0530

commit e377ab50081e3a8515a75a3f757d7c5c98a975c6 Author: Dubey Mritunjaykumar Date: Mon Jan 21 23:05:48 2019 +0530

Earlier commad used: git diff new_commit_id..prev_commit_id > 1 diff

Got error: patch failed: filename:40

working one: git diff prev_commit_id..latest_commit_id > 1.diff

Custom bullet symbol for <li> elements in <ul> that is a regular character, and not an image

My solution uses positioning to get wrapped lines automatically line up correctly. So you don't have to worry about setting padding-right on the li:before.

_x000D_
_x000D_
ul {_x000D_
  margin-left: 0;_x000D_
  padding-left: 0;_x000D_
  list-style-type: none;_x000D_
}_x000D_
_x000D_
ul li {_x000D_
  position: relative;_x000D_
  margin-left: 1em;_x000D_
}_x000D_
_x000D_
ul li:before {_x000D_
  position: absolute;_x000D_
  left: -1em;_x000D_
  content: "+";_x000D_
}
_x000D_
<ul>_x000D_
  <li>Item 1 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam</li>_x000D_
  <li>Item 2 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam</li>_x000D_
  <li>Item 3 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam</li>_x000D_
  <li>Item 4</li>_x000D_
  <li>Item 5</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

How to automatically import data from uploaded CSV or XLS file into Google Sheets

You can programmatically import data from a csv file in your Drive into an existing Google Sheet using Google Apps Script, replacing/appending data as needed.

Below is some sample code. It assumes that: a) you have a designated folder in your Drive where the CSV file is saved/uploaded to; b) the CSV file is named "report.csv" and the data in it comma-delimited; and c) the CSV data is imported into a designated spreadsheet. See comments in code for further details.

function importData() {
  var fSource = DriveApp.getFolderById(reports_folder_id); // reports_folder_id = id of folder where csv reports are saved
  var fi = fSource.getFilesByName('report.csv'); // latest report file
  var ss = SpreadsheetApp.openById(data_sheet_id); // data_sheet_id = id of spreadsheet that holds the data to be updated with new report data

  if ( fi.hasNext() ) { // proceed if "report.csv" file exists in the reports folder
    var file = fi.next();
    var csv = file.getBlob().getDataAsString();
    var csvData = CSVToArray(csv); // see below for CSVToArray function
    var newsheet = ss.insertSheet('NEWDATA'); // create a 'NEWDATA' sheet to store imported data
    // loop through csv data array and insert (append) as rows into 'NEWDATA' sheet
    for ( var i=0, lenCsv=csvData.length; i<lenCsv; i++ ) {
      newsheet.getRange(i+1, 1, 1, csvData[i].length).setValues(new Array(csvData[i]));
    }
    /*
    ** report data is now in 'NEWDATA' sheet in the spreadsheet - process it as needed,
    ** then delete 'NEWDATA' sheet using ss.deleteSheet(newsheet)
    */
    // rename the report.csv file so it is not processed on next scheduled run
    file.setName("report-"+(new Date().toString())+".csv");
  }
};


// http://www.bennadel.com/blog/1504-Ask-Ben-Parsing-CSV-Strings-With-Javascript-Exec-Regular-Expression-Command.htm
// This will parse a delimited string into an array of
// arrays. The default delimiter is the comma, but this
// can be overriden in the second argument.

function CSVToArray( strData, strDelimiter ) {
  // Check to see if the delimiter is defined. If not,
  // then default to COMMA.
  strDelimiter = (strDelimiter || ",");

  // Create a regular expression to parse the CSV values.
  var objPattern = new RegExp(
    (
      // Delimiters.
      "(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +

      // Quoted fields.
      "(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +

      // Standard fields.
      "([^\"\\" + strDelimiter + "\\r\\n]*))"
    ),
    "gi"
  );

  // Create an array to hold our data. Give the array
  // a default empty first row.
  var arrData = [[]];

  // Create an array to hold our individual pattern
  // matching groups.
  var arrMatches = null;

  // Keep looping over the regular expression matches
  // until we can no longer find a match.
  while (arrMatches = objPattern.exec( strData )){

    // Get the delimiter that was found.
    var strMatchedDelimiter = arrMatches[ 1 ];

    // Check to see if the given delimiter has a length
    // (is not the start of string) and if it matches
    // field delimiter. If id does not, then we know
    // that this delimiter is a row delimiter.
    if (
      strMatchedDelimiter.length &&
      (strMatchedDelimiter != strDelimiter)
    ){

      // Since we have reached a new row of data,
      // add an empty row to our data array.
      arrData.push( [] );

    }

    // Now that we have our delimiter out of the way,
    // let's check to see which kind of value we
    // captured (quoted or unquoted).
    if (arrMatches[ 2 ]){

      // We found a quoted value. When we capture
      // this value, unescape any double quotes.
      var strMatchedValue = arrMatches[ 2 ].replace(
        new RegExp( "\"\"", "g" ),
        "\""
      );

    } else {

      // We found a non-quoted value.
      var strMatchedValue = arrMatches[ 3 ];

    }

    // Now that we have our value string, let's add
    // it to the data array.
    arrData[ arrData.length - 1 ].push( strMatchedValue );
  }

  // Return the parsed data.
  return( arrData );
};

You can then create time-driven trigger in your script project to run importData() function on a regular basis (e.g. every night at 1AM), so all you have to do is put new report.csv file into the designated Drive folder, and it will be automatically processed on next scheduled run.

If you absolutely MUST work with Excel files instead of CSV, then you can use this code below. For it to work you must enable Drive API in Advanced Google Services in your script and in Developers Console (see How to Enable Advanced Services for details).

/**
 * Convert Excel file to Sheets
 * @param {Blob} excelFile The Excel file blob data; Required
 * @param {String} filename File name on uploading drive; Required
 * @param {Array} arrParents Array of folder ids to put converted file in; Optional, will default to Drive root folder
 * @return {Spreadsheet} Converted Google Spreadsheet instance
 **/
function convertExcel2Sheets(excelFile, filename, arrParents) {

  var parents  = arrParents || []; // check if optional arrParents argument was provided, default to empty array if not
  if ( !parents.isArray ) parents = []; // make sure parents is an array, reset to empty array if not

  // Parameters for Drive API Simple Upload request (see https://developers.google.com/drive/web/manage-uploads#simple)
  var uploadParams = {
    method:'post',
    contentType: 'application/vnd.ms-excel', // works for both .xls and .xlsx files
    contentLength: excelFile.getBytes().length,
    headers: {'Authorization': 'Bearer ' + ScriptApp.getOAuthToken()},
    payload: excelFile.getBytes()
  };

  // Upload file to Drive root folder and convert to Sheets
  var uploadResponse = UrlFetchApp.fetch('https://www.googleapis.com/upload/drive/v2/files/?uploadType=media&convert=true', uploadParams);

  // Parse upload&convert response data (need this to be able to get id of converted sheet)
  var fileDataResponse = JSON.parse(uploadResponse.getContentText());

  // Create payload (body) data for updating converted file's name and parent folder(s)
  var payloadData = {
    title: filename, 
    parents: []
  };
  if ( parents.length ) { // Add provided parent folder(s) id(s) to payloadData, if any
    for ( var i=0; i<parents.length; i++ ) {
      try {
        var folder = DriveApp.getFolderById(parents[i]); // check that this folder id exists in drive and user can write to it
        payloadData.parents.push({id: parents[i]});
      }
      catch(e){} // fail silently if no such folder id exists in Drive
    }
  }
  // Parameters for Drive API File Update request (see https://developers.google.com/drive/v2/reference/files/update)
  var updateParams = {
    method:'put',
    headers: {'Authorization': 'Bearer ' + ScriptApp.getOAuthToken()},
    contentType: 'application/json',
    payload: JSON.stringify(payloadData)
  };

  // Update metadata (filename and parent folder(s)) of converted sheet
  UrlFetchApp.fetch('https://www.googleapis.com/drive/v2/files/'+fileDataResponse.id, updateParams);

  return SpreadsheetApp.openById(fileDataResponse.id);
}

/**
 * Sample use of convertExcel2Sheets() for testing
 **/
 function testConvertExcel2Sheets() {
  var xlsId = "0B9**************OFE"; // ID of Excel file to convert
  var xlsFile = DriveApp.getFileById(xlsId); // File instance of Excel file
  var xlsBlob = xlsFile.getBlob(); // Blob source of Excel file for conversion
  var xlsFilename = xlsFile.getName(); // File name to give to converted file; defaults to same as source file
  var destFolders = []; // array of IDs of Drive folders to put converted file in; empty array = root folder
  var ss = convertExcel2Sheets(xlsBlob, xlsFilename, destFolders);
  Logger.log(ss.getId());
}

The above code is also available as a gist here.

UILabel Align Text to center

N.B.: As per the UILabel class reference, as of iOS 6 this approach is now deprecated.

Simply use the textAlignment property to see the required alignment using one of the UITextAlignment values. (UITextAlignmentLeft, UITextAlignmentCenter or UITextAlignmentRight.)

e.g.: [myUILabel setTextAlignment:UITextAlignmentCenter];

See the UILabel Class Reference for more information.

Detect if page has finished loading

Is this what you had in mind?

$("document").ready( function() {
    // do your stuff
}

Using getopts to process long and short command line options

getopts "could be used" for parsing long options as long as you don't expect them to have arguments...

Here's how to:

$ cat > longopt
while getopts 'e:-:' OPT; do
  case $OPT in
    e) echo echo: $OPTARG;;
    -) #long option
       case $OPTARG in
         long-option) echo long option;;
         *) echo long option: $OPTARG;;
       esac;;
  esac
done

$ bash longopt -e asd --long-option --long1 --long2 -e test
echo: asd
long option
long option: long1
long option: long2
echo: test

If you try to use OPTIND for getting a parameter for the long option, getopts will treat it as the first no optional positional parameter and will stop parsing any other parameters. In such a case you'll be better off handling it manually with a simple case statement.

This will "always" work:

$ cat >longopt2
while (($#)); do
    OPT=$1
    shift
    case $OPT in
        --*) case ${OPT:2} in
            long1) echo long1 option;;
            complex) echo comples with argument $1; shift;;
        esac;;

        -*) case ${OPT:1} in
            a) echo short option a;;
            b) echo short option b with parameter $1; shift;;
        esac;;
    esac
done


$ bash longopt2 --complex abc -a --long -b test
comples with argument abc
short option a
short option b with parameter test

Albeit is not as flexible as getopts and you have to do much of the error checking code yourself within the case instances...

But it is an option.

How to delete/unset the properties of a javascript object?

simply use delete, but be aware that you should read fully what the effects are of using this:

 delete object.index; //true
 object.index; //undefined

but if I was to use like so:

var x = 1; //1
delete x; //false
x; //1

but if you do wish to delete variables in the global namespace, you can use it's global object such as window, or using this in the outermost scope i.e

var a = 'b';
delete a; //false
delete window.a; //true
delete this.a; //true

http://perfectionkills.com/understanding-delete/

another fact is that using delete on an array will not remove the index but only set the value to undefined, meaning in certain control structures such as for loops, you will still iterate over that entity, when it comes to array's you should use splice which is a prototype of the array object.

Example Array:

var myCars=new Array();
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";

if I was to do:

delete myCars[1];

the resulting array would be:

["Saab", undefined, "BMW"]

but using splice like so:

myCars.splice(1,1);

would result in:

["Saab", "BMW"]

Base64 encoding and decoding in client-side Javascript

Internet Explorer 10+

// Define the string
var string = 'Hello World!';

// Encode the String
var encodedString = btoa(string);
console.log(encodedString); // Outputs: "SGVsbG8gV29ybGQh"

// Decode the String
var decodedString = atob(encodedString);
console.log(decodedString); // Outputs: "Hello World!"

Cross-Browser

Re-written and modularized UTF-8 and Base64 Javascript Encoding and Decoding Libraries / Modules for AMD, CommonJS, Nodejs and Browsers. Cross-browser compatible.


with Node.js

Here is how you encode normal text to base64 in Node.js:

//Buffer() requires a number, array or string as the first parameter, and an optional encoding type as the second parameter. 
// Default is utf8, possible encoding types are ascii, utf8, ucs2, base64, binary, and hex
var b = new Buffer('JavaScript');
// If we don't use toString(), JavaScript assumes we want to convert the object to utf8.
// We can make it convert to other formats by passing the encoding type to toString().
var s = b.toString('base64');

And here is how you decode base64 encoded strings:

var b = new Buffer('SmF2YVNjcmlwdA==', 'base64')
var s = b.toString();

with Dojo.js

To encode an array of bytes using dojox.encoding.base64:

var str = dojox.encoding.base64.encode(myByteArray);

To decode a base64-encoded string:

var bytes = dojox.encoding.base64.decode(str)

bower install angular-base64

<script src="bower_components/angular-base64/angular-base64.js"></script>

angular
    .module('myApp', ['base64'])
    .controller('myController', [

    '$base64', '$scope', 
    function($base64, $scope) {
    
        $scope.encoded = $base64.encode('a string');
        $scope.decoded = $base64.decode('YSBzdHJpbmc=');
}]);

But How?

If you would like to learn more about how base64 is encoded in general, and in JavaScript in-particular, I would recommend this article: Computer science in JavaScript: Base64 encoding

ffmpeg usage to encode a video to H264 codec format

I believe that by now the above answers are outdated (or at least unclear) so here's my little go at it. I tried compiling ffmpeg with the option --enable-encoders=libx264 and it will give no error but it won't enable anything (I can't seem to find where I found that suggestion).

Anyways step-by-step, first you must compile libx264 yourself because repository version is outdated:

  wget ftp://ftp.videolan.org/pub/x264/snapshots/last_x264.tar.bz2
  tar --bzip2 -xvf last_x264.tar.bz2
  cd x264-snapshot-XXXXXXXX-XXXX/
  ./configure
  make
  sudo make install

And then get and compile ffmpeg with libx264 enabled. I'm using the latest release which is "Happiness":

wget http://ffmpeg.org/releases/ffmpeg-0.11.2.tar.bz2
tar --bzip2 -xvf ffmpeg-0.11.2.tar.bz2
cd ffmpeg-0.11.2/
./configure --enable-libx264 --enable-gpl
make
sudo install

Now finally you have the libx264 codec to encode, to check it you may run

ffmpeg -codecs | grep h264

and you'll see the options you have were the first D means decoding and the first E means encoding

How to check if a file exists in Ansible?

I find it can be annoying and error prone to do a lot of these .stat.exists type checks. For example they require extra care to get check mode (--check) working.

Many answers here suggest

  • get and register
  • apply when register expression is true

However, sometimes this is a code smell so always look for better ways to use Ansible, specifically there are many advantages to using the correct module. e.g.

- name: install ntpdate
  package:
    name: ntpdate

or

- file:
    path: /etc/file.txt
    owner: root
    group: root
    mode: 0644

But when it is not possible use one module, also investigate if you can register and check the result of a previous task. e.g.

# jmeter_version: 4.0 
- name: Download Jmeter archive
  get_url:
    url: "http://archive.apache.org/dist/jmeter/binaries/apache-jmeter-{{ jmeter_version }}.tgz"
    dest: "/opt/jmeter/apache-jmeter-{{ jmeter_version }}.tgz"
    checksum: sha512:eee7d68bd1f7e7b269fabaf8f09821697165518b112a979a25c5f128c4de8ca6ad12d3b20cd9380a2b53ca52762b4c4979e564a8c2ff37196692fbd217f1e343
  register: download_result

- name: Extract apache-jmeter
  unarchive:
    src: "/opt/jmeter/apache-jmeter-{{ jmeter_version }}.tgz"
    dest: "/opt/jmeter/"
    remote_src: yes
    creates: "/opt/jmeter/apache-jmeter-{{ jmeter_version }}"
  when: download_result.state == 'file'

Note the when: but also the creates: so --check doesn't error out

I mention this because often these less-than-ideal practices come in pairs i.e. no apt/yum package so we have to 1) download and 2) unzip

Hope this helps

How do I push a local repo to Bitbucket using SourceTree without creating a repo on bitbucket first?

Actually there is a more simple solution (only on Mac version). Just four steps:

  1. Right click on the repository and select "Publish to remote..."

SourceTree Publish to Remote Screeshot

  1. Next window will ask you were to publish (github, bitbucket, etc), and then you are done.
  2. Link the remote repository
  3. Push

Java - Get a list of all Classes loaded in the JVM

There are multiple answers to this question, partly due to ambiguous question - the title is talking about classes loaded by the JVM, whereas the contents of the question says "may or may not be loaded by the JVM".

Assuming that OP needs classes that are loaded by the JVM by a given classloader, and only those classes - my need as well - there is a solution (elaborated here) that goes like this:

import java.net.URL;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Vector;

public class CPTest {

    private static Iterator list(ClassLoader CL)
        throws NoSuchFieldException, SecurityException,
        IllegalArgumentException, IllegalAccessException {
        Class CL_class = CL.getClass();
        while (CL_class != java.lang.ClassLoader.class) {
            CL_class = CL_class.getSuperclass();
        }
        java.lang.reflect.Field ClassLoader_classes_field = CL_class
                .getDeclaredField("classes");
        ClassLoader_classes_field.setAccessible(true);
        Vector classes = (Vector) ClassLoader_classes_field.get(CL);
        return classes.iterator();
    }

    public static void main(String args[]) throws Exception {
        ClassLoader myCL = Thread.currentThread().getContextClassLoader();
        while (myCL != null) {
            System.out.println("ClassLoader: " + myCL);
            for (Iterator iter = list(myCL); iter.hasNext();) {
                System.out.println("\t" + iter.next());
            }
            myCL = myCL.getParent();
        }
    }

}

One of the neat things about it is that you can choose an arbitrary classloader you want to check. It is however likely to break should internals of classloader class change, so it is to be used as one-off diagnostic tool.

Ubuntu, how do you remove all Python 3 but not 2

Removing Python 3 was the worst thing I did since I recently moved to the world of Linux. It removed Firefox, my launcher and, as I read while trying to fix my problem, it may also remove your desktop and terminal! Finally fixed after a long daytime nightmare. Just don't remove Python 3. Keep it there!

If that happens to you, here is the fix:

https://askubuntu.com/q/384033/402539

https://askubuntu.com/q/810854/402539

How to determine the current language of a wordpress page when using polylang?

pll_current_language

Returns the current language

Usage:

pll_current_language( $value ); 
  • $value => (optional) either name or locale or slug, defaults to slug

returns either the full name, or the WordPress locale (just as the WordPress core function ‘get_locale’ or the slug ( 2-letters code) of the current language.

updating Google play services in Emulator

I know it's late answer but I had same problem for last two days, and none of the above solutions worked for me. My app supports min sdk 16, Jelly Bean 4.1.x, so I wanted to test my app on emulator with 16 android api version and I needed Google Play Services.

In short, solution that worked for me is:

  • make new emulator Nexus 5X (with Play Store support) - Jelly Bean 4.1.x, 16 API level (WITHOUT Google APIs)
  • manually download apks of Google Play Store and Google Play Services (it is necessary that both apks have similar version, they need to start with same number, for example 17.x)
  • drag and drop those apks into new emulator
  • congratulations you have updated Google Play Services on your 4.1.x emulator

Here are the steps and errors I have encountered during the problem.

So I have made new emulator in my AVD. I picked Nexus 5X (with Play Store support). After that I picked Jelly Bean 16 api level (with Google APIs). When I opened my app dialog pop up with message You need to update your Google play services. When I clicked on Update button, nothing happened. I did update everything necessary in SDK manager, but nothing worked. I didn't have installed Google Play Store on my emulator, even tho I picked Nexus 5X which comes with preinstalled Play Store. So I couldn't find Google Play Store tab in Extended Controls (tree dots next to my emulator).

Because nothings worked, I decided to try to install Google Play Services manually, by downloading APK and dragging it into emulator. When I tried this, I encountered problem The APK failed to install. Error: INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES. I figured that this was the problem because I picked Jelly Bean 16 api level (with Google APIs). So I made new emulator

Nexus 5X (with Play Store support) - Jelly Bean 16 api level (WITHOUT Google APIs)

This allowed me to install my Google Play Service manually. But when I run my app, it still didn't want to open it. Problem was that my emulator was missing Google Play Store. So I installed it manually like Google Play Service. But when it was successfully installed, dialog started popping out every second with message Unfortunately Google Play Services has stopped. Problem was that version of my Google Play Store was 17.x and Google Play Service was 19.x. So at the end I installed Google Play Service with version 17.x, and everything worked.

How to query between two dates using Laravel and Eloquent?

If you want to check if current date exist in between two dates in db: =>here the query will get the application list if employe's application from and to date is exist in todays date.

$list=  (new LeaveApplication())
            ->whereDate('from','<=', $today)
            ->whereDate('to','>=', $today)
            ->get();

How to Calculate Execution Time of a Code Snippet in C++

#include <boost/progress.hpp>

using namespace boost;

int main (int argc, const char * argv[])
{
  progress_timer timer;

  // do stuff, preferably in a 100x loop to make it take longer.

  return 0;
}

When progress_timer goes out of scope it will print out the time elapsed since its creation.

UPDATE: Here's a version that works without Boost (tested on macOS/iOS):

#include <chrono>
#include <string>
#include <iostream>
#include <math.h>
#include <unistd.h>

class NLTimerScoped {
private:
    const std::chrono::steady_clock::time_point start;
    const std::string name;

public:
    NLTimerScoped( const std::string & name ) : name( name ), start( std::chrono::steady_clock::now() ) {
    }


    ~NLTimerScoped() {
        const auto end(std::chrono::steady_clock::now());
        const auto duration_ms = std::chrono::duration_cast<std::chrono::milliseconds>( end - start ).count();

        std::cout << name << " duration: " << duration_ms << "ms" << std::endl;
    }

};

int main(int argc, const char * argv[]) {

    {
        NLTimerScoped timer( "sin sum" );

        float a = 0.0f;

        for ( int i=0; i < 1000000; i++ ) {
            a += sin( (float) i / 100 );
        }

        std::cout << "sin sum = " << a << std::endl;
    }



    {
        NLTimerScoped timer( "sleep( 4 )" );

        sleep( 4 );
    }



    return 0;
}

How do you reverse a string in place in C or C++?

Yet another:

#include <stdio.h>
#include <strings.h>

int main(int argc, char **argv) {

  char *reverse = argv[argc-1];
  char *left = reverse;
  int length = strlen(reverse);
  char *right = reverse+length-1;
  char temp;

  while(right-left>=1){

    temp=*left;
    *left=*right;
    *right=temp;
    ++left;
    --right;

  }

  printf("%s\n", reverse);

}

Array String Declaration

As Tr?n Si Long suggested, use

String[] mStrings = new String[title.length];

And replace string concatation with proper parenthesis.

mStrings[i] = (urlbase + (title[i].replaceAll("[^a-zA-Z]", ""))).toLowerCase() + imgSel;

Try this. If it's problem due to concatation, it will be resolved with proper brackets. Hope it helps.

Failed to load resource: net::ERR_FILE_NOT_FOUND loading json.js

Remove the first / in the path. Also you don't need type="text/javascript" anymore in HTML5.

How to send a POST request in Go?

I know this is old but this answer came up in search results. For the next guy - the proposed and accepted answer works, however the code initially submitted in the question is lower-level than it needs to be. Nobody got time for that.

//one-line post request/response...
response, err := http.PostForm(APIURL, url.Values{
    "ln": {c.ln},
    "ip": {c.ip},
    "ua": {c.ua}})

//okay, moving on...
if err != nil {
  //handle postform error
}

defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)

if err != nil {
  //handle read response error
}

fmt.Printf("%s\n", string(body))

https://golang.org/pkg/net/http/#pkg-overview

What are the recommendations for html <base> tag?

To decide whether it should be used or not, you should be aware of what it does and whether it's needed. This is already partly outlined in this answer, which I also contributed to. But to make it easier to understand and follow, a second explanation here. First we need to understand:

How are links processed by the browser without <BASE> being used?

For some examples, let's assume we have these URLs:

A) http://www.example.com/index.html
B) http://www.example.com/
C) http://www.example.com/page.html
D) http://www.example.com/subdir/page.html

A+B both result in the very same file (index.html) be sent to the browser, C of course sends page.html, and D sends /subdir/page.html.

Let's further assume, both pages contain a set of links:

1) fully qualified absolute links (http://www...)
2) local absolute links (/some/dir/page.html)
3) relative links including file names (dir/page.html), and
4) relative links with "segments" only (#anchor, ?foo=bar).

The browser receives the page, and renders the HTML. If it finds some URL, it needs to know where to point it to. That's always clear for Link 1), which is taken as-is. All others depend on the URL of the rendered page:

URL     | Link | Result
--------+------+--------------------------
A,B,C,D |    2 | http://www.example.com/some/dir/page.html
A,B,C   |    3 | http://www.example.com/dir/page.html
D       |    3 | http://www.example.com/subdir/dir/page.html
A       |    4 | http://www.example.com/index.html#anchor
B       |    4 | http://www.example.com/#anchor
C       |    4 | http://www.example.com/page.html#anchor
D       |    4 | http://www.example.com/subdir/page.html#anchor

Now what changes with <BASE> being used?

<BASE> is supposed to replace the URL as it appears to the browser. So it renders all links as if the user had called up the URL specified in <BASE>. Which explains some of the confusion in several of the other answers:

  • again, nothing changes for "fully qualified absolute links" ("type 1")
  • for local absolute links, the targeted server might change (if the one specified in <BASE> differs from the one being called initially from the user)
  • relative URLs become critical here, so you've got to take special care how you set <BASE>:
    • better avoid setting it to a directory. Doing so, links of "type 3" might continue to work, but it most certainly breaks those of "type 4" (except for "case B")
    • set it to the fully qualified file name produces, in most cases, the desired results.

An example explains it best

Say you want to "prettify" some URL using mod_rewrite:

  • real file: <DOCUMENT_ROOT>/some/dir/file.php?lang=en
  • real URL: http://www.example.com/some/dir/file.php?lang=en
  • user-friendly URL: http://www.example.com/en/file

Let's assume mod_rewrite is used to transparently rewrite the user-friendly URL to the real one (no external re-direct, so the "user-friendly" one stays in the browsers address bar, while the real-one is loaded). What to do now?

  • no <BASE> specified: breaks all relative links (as they would be based on http://www.example.com/en/file now)
  • <BASE HREF='http://www.example.com/some/dir>: Absolutely wrong. dir would be considered the file part of the specified URL, so still, all relative links are broken.
  • <BASE HREF='http://www.example.com/some/dir/>: Better already. But relative links of "type 4" are still broken (except for "case B").
  • <BASE HREF='http://www.example.com/some/dir/file.php>: Exactly. Everything should be working with this one.

A last note

Keep in mind this applies to all URLs in your document:

  • <A HREF=
  • <IMG SRC=
  • <SCRIPT SRC=

Print line numbers starting at zero using awk

NR starts at 1, so use

awk '{print NR-1 "," $0}'

How to append new data onto a new line

There is also one fact that you have to consider. You should first check if your file is empty before adding anything to it. Because if your file is empty then I don't think you would like to add a blank new line in the beginning of the file. This code

  1. first checks if the file is empty
  2. If the file is empty then it will simply add your input text to the file else it will add a new line and then it will add your text to the file. You should use a try catch for os.path.getsize() to catch any exceptions.

Code:

import os

def storescores():
hs = open("hst.txt","a")
if(os.path.getsize("hst.txt") > 0):
   hs.write("\n"+name)
else:
   hs.write(name)

hs.close()

Why doesn't Python have multiline comments?

Multi-line comments are easily breakable. What if you have the following in a simple calculator program?

operation = ''
print("Pick an operation:  +-*/")
# Get user input here

Try to comment that with a multi-line comment:

/*
operation = ''
print("Pick an operation:  +-*/")
# Get user input here
*/

Oops, your string contains the end comment delimiter.

jQuery: how to get which button was clicked upon form submission?

A simple way to distinguish which <button> or <input type="button"...> is pressed, is by checking their 'id':

$("button").click(function() {
  var id = $(this).attr('id');
  ... 
});

Accessing items in an collections.OrderedDict by index

Do you have to use an OrderedDict or do you specifically want a map-like type that's ordered in some way with fast positional indexing? If the latter, then consider one of Python's many sorted dict types (which orders key-value pairs based on key sort order). Some implementations also support fast indexing. For example, the sortedcontainers project has a SortedDict type for just this purpose.

>>> from sortedcontainers import SortedDict
>>> sd = SortedDict()
>>> sd['foo'] = 'python'
>>> sd['bar'] = 'spam'
>>> print sd.iloc[0] # Note that 'bar' comes before 'foo' in sort order.
'bar'
>>> # If you want the value, then simple do a key lookup:
>>> print sd[sd.iloc[1]]
'python'

Align image to left of text on same line - Twitter Bootstrap3

Use Nesting column

To nest your content with the default grid, add a new .row and set of .col-sm-* columns within an existing .col-sm-* column. Nested rows should include a set of columns that add up to 12 or fewer (it is not required that you use all 12 available columns).

enter image description here

_x000D_
_x000D_
<div class="row">_x000D_
  <div class="col-sm-9">_x000D_
    Level 1: .col-sm-9_x000D_
    <div class="row">_x000D_
      <div class="col-xs-8 col-sm-6">_x000D_
        Level 2: .col-xs-8 .col-sm-6_x000D_
      </div>_x000D_
      <div class="col-xs-4 col-sm-6">_x000D_
        Level 2: .col-xs-4 .col-sm-6_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Convert .cer certificate to .jks

keytool comes with the JDK installation (in the bin folder):

keytool -importcert -file "your.cer" -keystore your.jks -alias "<anything>"

This will create a new keystore and add just your certificate to it.

So, you can't convert a certificate to a keystore: you add a certificate to a keystore.

Android Webview - Completely Clear the Cache

CookieSyncManager.createInstance(this);    
CookieManager cookieManager = CookieManager.getInstance(); 
cookieManager.removeAllCookie();

It can clear google account in my webview

Get distance between two points in canvas

Note that Math.hypot is part of the ES2015 standard. There's also a good polyfill on the MDN doc for this feature.

So getting the distance becomes as easy as Math.hypot(x2-x1, y2-y1).

How to get whole and decimal part of a number?

If you can count on it always having 2 decimal places, you can just use a string operation:

$decimal = 1.25;
substr($decimal,-2);  // returns "25" as a string

No idea of performance but for my simple case this was much better...

Angular2 Exception: Can't bind to 'routerLink' since it isn't a known native property

If getting this error while unit testing please write this.

import { RouterTestingModule } from '@angular/router/testing';
beforeEach(async(() => {
  TestBed.configureTestingModule({
    imports: [RouterTestingModule],
    declarations: [AppComponent],
  });
}));

Select a random sample of results from a query result

This in not a perfect answer but will get much better performance.

SELECT  *
FROM    (
    SELECT  *
    FROM    mytable sample (0.01)
    ORDER BY
            dbms_random.value
    )
WHERE rownum <= 1000

Sample will give you a percent of your actual table, if you really wanted a 1000 rows you would need to adjust that number. More often I just need an arbitrary number of rows anyway so I don't limit my results. On my database with 2 million rows I get 2 seconds vs 60 seconds.

select * from mytable sample (0.01)

Are multiple `.gitignore`s frowned on?

Pro single

  • Easy to find.

  • Hunting down exclusion rules can be quite difficult if I have multiple gitignore, at several levels in the repo.

  • With multiple files, you also typically wind up with a fair bit of duplication.

Pro multiple

  • Scopes "knowledge" to the part of the file tree where it is needed.

  • Since Git only tracks files, an empty .gitignore is the only way to commit an "empty" directory.

    (And before Git 1.8, the only way to exclude a pattern like my/**.example was to create my/.gitignore in with the pattern **.foo. This reason doesn't apply now, as you can do /my/**/*.example.)


I much prefer a single file, where I can find all the exclusions. I've never missed per-directory .svn, and I won't miss per-directory .gitignore either.

That said, multiple gitignores are quite common. If you do use them, at least be consistent in their use to make them reasonable to work with. For example, you may put them in directories only one level from the root.

Is gcc's __attribute__((packed)) / #pragma pack unsafe?

It's perfectly safe as long as you always access the values through the struct via the . (dot) or -> notation.

What's not safe is taking the pointer of unaligned data and then accessing it without taking that into account.

Also, even though each item in the struct is known to be unaligned, it's known to be unaligned in a particular way, so the struct as a whole must be aligned as the compiler expects or there'll be trouble (on some platforms, or in future if a new way is invented to optimise unaligned accesses).

Efficiently updating database using SQLAlchemy ORM

SQLAlchemy's ORM is meant to be used together with the SQL layer, not hide it. But you do have to keep one or two things in mind when using the ORM and plain SQL in the same transaction. Basically, from one side, ORM data modifications will only hit the database when you flush the changes from your session. From the other side, SQL data manipulation statements don't affect the objects that are in your session.

So if you say

for c in session.query(Stuff).all():
    c.foo = c.foo+1
session.commit()

it will do what it says, go fetch all the objects from the database, modify all the objects and then when it's time to flush the changes to the database, update the rows one by one.

Instead you should do this:

session.execute(update(stuff_table, values={stuff_table.c.foo: stuff_table.c.foo + 1}))
session.commit()

This will execute as one query as you would expect, and because at least the default session configuration expires all data in the session on commit you don't have any stale data issues.

In the almost-released 0.5 series you could also use this method for updating:

session.query(Stuff).update({Stuff.foo: Stuff.foo + 1})
session.commit()

That will basically run the same SQL statement as the previous snippet, but also select the changed rows and expire any stale data in the session. If you know you aren't using any session data after the update you could also add synchronize_session=False to the update statement and get rid of that select.

Remove files from Git commit

This is worked for me to remove the file from bit bucket repo which I pushed the file to branch initially.

git checkout origin/develop <path-to-file>
git add <path-to-file>
git commit -m "Message"
git push

How to determine whether a substring is in a different string

with in: substring in string:

>>> substring = "please help me out"
>>> string = "please help me out so that I could solve this"
>>> substring in string
True

Accessing localhost (xampp) from another computer over LAN network - how to?

First you go to Command Prompt and type

Notepad C:/windows/system32/drivers/etc/hosts

then add your ip adress below then the url of your site.

Second you go to Command Prompt and type notepad c:/xampp/bin/apache/apache2.4.18/conf/extra/httpd-vhosts.conf

then add this below

documentroot "Directory of your site"
Allow from all
Require all granted

Unable to cast object of type 'System.DBNull' to type 'System.String`

ExecuteScalar will return

  • null if there is no result set
  • otherwise the first column of the first row of the resultset, which may be DBNull.

If you know that the first column of the resultset is a string, then to cover all bases you need to check for both null and DBNull. Something like:

object accountNumber = ...ExecuteScalar(...);
return (accountNumber == null) ? String.Empty : accountNumber.ToString();

The above code relies on the fact that DBNull.ToString returns an empty string.

If accountNumber was another type (say integer), then you'd need to be more explicit:

object accountNumber = ...ExecuteScalar(...);
return (accountNumber == null || Convert.IsDBNull(accountNumber) ?     
         (int) accountNumber : 0;

If you know for sure that your resultset will always have at least one row (e.g. SELECT COUNT(*)...), then you can skip the check for null.

In your case the error message "Unable to cast object of type ‘System.DBNull’ to type ‘System.String`" indicates that the first column of your result set is a DBNUll value. This is from the cast to string on the first line:

string accountNumber = (string) ... ExecuteScalar(...);

Marc_s's comment that you don't need to check for DBNull.Value is wrong.

MySQL Error 1153 - Got a packet bigger than 'max_allowed_packet' bytes

Sometimes type setting:

max_allowed_packet = 16M

in my.ini is not working.

Try to determine the my.ini as follows:

set-variable = max_allowed_packet = 32M

or

set-variable = max_allowed_packet = 1000000000

Then restart the server:

/etc/init.d/mysql restart

Convert string to variable name in python

This is the best way, I know of to create dynamic variables in python.

my_dict = {}
x = "Buffalo"
my_dict[x] = 4

I found a similar, but not the same question here Creating dynamically named variables from user input

Execute a stored procedure in another stored procedure in SQL server

Procedure example:

Create  PROCEDURE SP_Name
     @UserName nvarchar(200),
     @Password nvarchar(200)
AS
BEGIN
    DECLARE  @loginID  int

    --Statements for this Store Proc
  --
  -- 
  --

  --execute second store procedure
  --below line calling sencond Store Procedure Exec is used for execute Store Procedure.
    **Exec SP_Name_2 @params** (if any) 


END