Programs & Examples On #Trusted application

How to automatically generate unique id in SQL like UID12345678?

Table Creating

create table emp(eno int identity(100001,1),ename varchar(50))

Values inserting

insert into emp(ename)values('narendra'),('ajay'),('anil'),('raju')

Select Table

select * from emp

Output

eno     ename
100001  narendra
100002  rama
100003  ajay
100004  anil
100005  raju

git commit error: pathspec 'commit' did not match any file(s) known to git

Please take note that in windows, it is very important that the git commit -m "initial commit" has the initial commit texts in double quotes. Single quotes will throw a path spec error.

What are database constraints?

There are basically 4 types of main constraints in SQL:

  • Domain Constraint: if one of the attribute values provided for a new tuple is not of the specified attribute domain

  • Key Constraint: if the value of a key attribute in a new tuple already exists in another tuple in the relation

  • Referential Integrity: if a foreign key value in a new tuple references a primary key value that does not exist in the referenced relation

  • Entity Integrity: if the primary key value is null in a new tuple

Convert number to month name in PHP

strtotime expects a standard date format, and passes back a timestamp.

You seem to be passing strtotime a single digit to output a date format from.

You should be using mktime which takes the date elements as parameters.

Your full code:

$monthNum = sprintf("%02s", $result["month"]);
$monthName = date("F", mktime(null, null, null, $monthNum));

echo $monthName;

However, the mktime function does not require a leading zero to the month number, so the first line is completely unnecessary, and $result["month"] can be passed straight into the function.

This can then all be combined into a single line, echoing the date inline.

Your refactored code:

echo date("F", mktime(null, null, null, $result["month"], 1));

...

How to redirect to a route in laravel 5 by using href tag if I'm not using blade or any template?

In addition to @chanafdo answer, you can use route name

when working with laravel blade

<a href="{{route('login')}}">login here</a> with parameter in route name

when go to url like URI: profile/{id} <a href="{{route('profile', ['id' => 1])}}">login here</a>

without blade

<a href="<?php echo route('login')?>">login here</a>

with parameter in route name

when go to url like URI: profile/{id} <a href="<?php echo route('profile', ['id' => 1])?>">login here</a>

As of laravel 5.2 you can use @php @endphp to create as <?php ?> in laravel blade. Using blade your personal opinion but I suggest to use it. Learn it. It has many wonderful features as template inheritance, Components & Slots,subviews etc...

How can I check if a string represents an int, without using try/except?

str.isdigit() should do the trick.

Examples:

str.isdigit("23") ## True
str.isdigit("abc") ## False
str.isdigit("23.4") ## False

EDIT: As @BuzzMoschetti pointed out, this way will fail for minus number (e.g, "-23"). In case your input_num can be less than 0, use re.sub(regex_search,regex_replace,contents) before applying str.isdigit(). For example:

import re
input_num = "-23"
input_num = re.sub("^-", "", input_num) ## "^" indicates to remove the first "-" only
str.isdigit(input_num) ## True

JQuery, setTimeout not working

setInterval(function() {
    $('#board').append('.');
}, 1000);

You can use clearInterval if you wanted to stop it at one point.

JSON: why are forward slashes escaped?

I asked the same question some time ago and had to answer it myself. Here's what I came up with:

It seems, my first thought [that it comes from its JavaScript roots] was correct.

'\/' === '/' in JavaScript, and JSON is valid JavaScript. However, why are the other ignored escapes (like \z) not allowed in JSON?

The key for this was reading http://www.cs.tut.fi/~jkorpela/www/revsol.html, followed by http://www.w3.org/TR/html4/appendix/notes.html#h-B.3.2. The feature of the slash escape allows JSON to be embedded in HTML (as SGML) and XML.

Convert js Array() to JSon object for use with JQuery .ajax

You can iterate the key/value pairs of the saveData object to build an array of the pairs, then use join("&") on the resulting array:

var a = [];
for (key in saveData) {
    a.push(key+"="+saveData[key]);
}
var serialized = a.join("&") // a=2&c=1

How to apply CSS page-break to print a table with lots of rows?

I have looked around for a fix for this. I have a jquery mobile site that has a final print page and it combines dozens of pages. I tried all the fixes above but the only thing I could get to work is this:

<div style="clear:both!important;"/></div>
<div style="page-break-after:always"></div> 
<div style="clear:both!important;"/> </div>

Java - removing first character of a string

Another solution, you can solve your problem using replaceAll with some regex ^.{1} (regex demo) for example :

String str = "Jamaica";
int nbr = 1;
str = str.replaceAll("^.{" + nbr + "}", "");//Output = amaica

How to pass parameter to function using in addEventListener?

No need to pass anything in. The function used for addEventListener will automatically have this bound to the current element. Simply use this in your function:

productLineSelect.addEventListener('change', getSelection, false);

function getSelection() {
    var value = this.options[this.selectedIndex].value;
    alert(value);
}

Here's the fiddle: http://jsfiddle.net/dJ4Wm/


If you want to pass arbitrary data to the function, wrap it in your own anonymous function call:

productLineSelect.addEventListener('change', function() {
    foo('bar');
}, false);

function foo(message) {
    alert(message);
}

Here's the fiddle: http://jsfiddle.net/t4Gun/


If you want to set the value of this manually, you can use the call method to call the function:

var self = this;
productLineSelect.addEventListener('change', function() {
    getSelection.call(self);
    // This'll set the `this` value inside of `getSelection` to `self`
}, false);

function getSelection() {
    var value = this.options[this.selectedIndex].value;
    alert(value);
}

How to get row from R data.frame

Try:

> d <- data.frame(a=1:3, b=4:6, c=7:9)

> d
  a b c
1 1 4 7
2 2 5 8
3 3 6 9

> d[1, ]
  a b c
1 1 4 7

> d[1, ]['a']
  a
1 1

How can I modify a saved Microsoft Access 2007 or 2010 Import Specification?

Another great option is the free V-Tools addin for Microsoft Access. Among other helpful tools it has a form to edit and save the Import/Export specifications.

enter image description here

enter image description here

Note: As of version 1.83, there is a bug in enumerating the code pages on Windows 10. (Apparently due to a missing/changed API function in Windows 10) The tools still works great, you just need to comment out a few lines of code or step past it in the debug window.

This has been a real life-saver for me in editing a complex import spec for our online orders.

IEnumerable<object> a = new IEnumerable<object>(); Can I do this?

I wanted to create a new enumerable object or list and be able to add to it.

This comment changes everything. You can't add to a generic IEnumerable<T>. If you want to stay with the interfaces in System.Collections.Generic, you need to use a class that implements ICollection<T> like List<T>.

Increase JVM max heap size for Eclipse

You can use this configuration:

-startup
plugins/org.eclipse.equinox.launcher_1.3.0.v20120522-1813.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.1.200.v20120913-144807
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile
-vmargs
-Xms512m
-Xmx1024m
-XX:+UseParallelGC
-XX:PermSize=256M
-XX:MaxPermSize=512M

Excel 2013 horizontal secondary axis

You should follow the guidelines on Add a secondary horizontal axis:

Add a secondary horizontal axis

To complete this procedure, you must have a chart that displays a secondary vertical axis. To add a secondary vertical axis, see Add a secondary vertical axis.

  1. Click a chart that displays a secondary vertical axis. This displays the Chart Tools, adding the Design, Layout, and Format tabs.

  2. On the Layout tab, in the Axes group, click Axes.

    enter image description here

  3. Click Secondary Horizontal Axis, and then click the display option that you want.

enter image description here


Add a secondary vertical axis

You can plot data on a secondary vertical axis one data series at a time. To plot more than one data series on the secondary vertical axis, repeat this procedure for each data series that you want to display on the secondary vertical axis.

  1. In a chart, click the data series that you want to plot on a secondary vertical axis, or do the following to select the data series from a list of chart elements:

    • Click the chart.

      This displays the Chart Tools, adding the Design, Layout, and Format tabs.

    • On the Format tab, in the Current Selection group, click the arrow in the Chart Elements box, and then click the data series that you want to plot along a secondary vertical axis.

      enter image description here

  2. On the Format tab, in the Current Selection group, click Format Selection. The Format Data Series dialog box is displayed.

    Note: If a different dialog box is displayed, repeat step 1 and make sure that you select a data series in the chart.

  3. On the Series Options tab, under Plot Series On, click Secondary Axis and then click Close.

    A secondary vertical axis is displayed in the chart.

  4. To change the display of the secondary vertical axis, do the following:

    • On the Layout tab, in the Axes group, click Axes.

    • Click Secondary Vertical Axis, and then click the display option that you want.

  5. To change the axis options of the secondary vertical axis, do the following:

    • Right-click the secondary vertical axis, and then click Format Axis.

    • Under Axis Options, select the options that you want to use.

Converting UTF-8 to ISO-8859-1 in Java - how to keep it as single byte

Starting with a set of bytes which encode a string using UTF-8, creates a string from that data, then get some bytes encoding the string in a different encoding:

    byte[] utf8bytes = { (byte)0xc3, (byte)0xa2, 0x61, 0x62, 0x63, 0x64 };
    Charset utf8charset = Charset.forName("UTF-8");
    Charset iso88591charset = Charset.forName("ISO-8859-1");

    String string = new String ( utf8bytes, utf8charset );

    System.out.println(string);

    // "When I do a getbytes(encoding) and "
    byte[] iso88591bytes = string.getBytes(iso88591charset);

    for ( byte b : iso88591bytes )
        System.out.printf("%02x ", b);

    System.out.println();

    // "then create a new string with the bytes in ISO-8859-1 encoding"
    String string2 = new String ( iso88591bytes, iso88591charset );

    // "I get a two different chars"
    System.out.println(string2);

this outputs strings and the iso88591 bytes correctly:

âabcd 
e2 61 62 63 64 
âabcd

So your byte array wasn't paired with the correct encoding:

    String failString = new String ( utf8bytes, iso88591charset );

    System.out.println(failString);

Outputs

âabcd

(either that, or you just wrote the utf8 bytes to a file and read them elsewhere as iso88591)

Command line: search and replace in all filenames matched by grep

The answer already given of using find and sed

find -name '*.html' -print -exec sed -i.bak 's/foo/bar/g' {} \;

is probably the standard answer. Or you could use perl -pi -e s/foo/bar/g' instead of the sed command.

For most quick uses, you may find the command rpl is easier to remember. Here is replacement (foo -> bar), recursively on all files in the current directory:

rpl -R foo bar .

It's not available by default on most Linux distros but is quick to install (apt-get install rpl or similar).

However, for tougher jobs that involve regular expressions and back substitution, or file renames as well as search-and-replace, the most general and powerful tool I'm aware of is repren, a small Python script I wrote a while back for some thornier renaming and refactoring tasks. The reasons you might prefer it are:

  • Support renaming of files as well as search-and-replace on file contents (including moving files between directories and creating new parent directories).
  • See changes before you commit to performing the search and replace.
  • Support regular expressions with back substitution, whole words, case insensitive, and case preserving (replace foo -> bar, Foo -> Bar, FOO -> BAR) modes.
  • Works with multiple replacements, including swaps (foo -> bar and bar -> foo) or sets of non-unique replacements (foo -> bar, f -> x).

Check the README for examples.

Copy Files from Windows to the Ubuntu Subsystem

You should be able to access your windows system under the /mnt directory. For example inside of bash, use this to get to your pictures directory:

cd /mnt/c/Users/<ubuntu.username>/Pictures

Hope this helps!

Where do I find the Instagram media ID of a image

Here is python solution to do this without api call.

def media_id_to_code(media_id):
    alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'
    short_code = ''
    while media_id > 0:
        remainder = media_id % 64
        media_id = (media_id-remainder)/64
        short_code = alphabet[remainder] + short_code
    return short_code


def code_to_media_id(short_code):
    alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'
    media_id = 0;
    for letter in short_code:
        media_id = (media_id*64) + alphabet.index(letter)

    return media_id

How can I call a WordPress shortcode within a template?

Make sure to enable the use of shortcodes in text widgets.

// To enable the use, add this in your *functions.php* file:
add_filter( 'widget_text', 'do_shortcode' );

// and then you can use it in any PHP file:  
<?php echo do_shortcode('[YOUR-SHORTCODE-NAME/TAG]'); ?>

Check the documentation for more.

Add items to comboBox in WPF

Its better to build ObservableCollection and take advantage of it

public ObservableCollection<string> list = new ObservableCollection<string>();
list.Add("a");
list.Add("b");
list.Add("c");
this.cbx.ItemsSource = list;

cbx is comobobox name

Also Read : Difference between List, ObservableCollection and INotifyPropertyChanged

replace all occurrences in a string

Use the global flag.

str.replace(/\n/g, '<br />');

Matrix multiplication in OpenCV

You say that the matrices are the same dimensions, and yet you are trying to perform matrix multiplication on them. Multiplication of matrices with the same dimension is only possible if they are square. In your case, you get an assertion error, because the dimensions are not square. You have to be careful when multiplying matrices, as there are two possible meanings of multiply.

Matrix multiplication is where two matrices are multiplied directly. This operation multiplies matrix A of size [a x b] with matrix B of size [b x c] to produce matrix C of size [a x c]. In OpenCV it is achieved using the simple * operator:

C = A * B

Element-wise multiplication is where each pixel in the output matrix is formed by multiplying that pixel in matrix A by its corresponding entry in matrix B. The input matrices should be the same size, and the output will be the same size as well. This is achieved using the mul() function:

output = A.mul(B);

How do you clone a Git repository into a specific folder?

When you move the files to where you want them, are you also moving the .git directory? Depending on your OS and configuration, this directory may be hidden.

It contains the repo and the supporting files, while the project files that are in your /public directory are only the versions in the currently check-out commit (master branch by default).

Multithreading in Bash

Sure, just add & after the command:

read_cfg cfgA &
read_cfg cfgB &
read_cfg cfgC &
wait

all those jobs will then run in the background simultaneously. The optional wait command will then wait for all the jobs to finish.

Each command will run in a separate process, so it's technically not "multithreading", but I believe it solves your problem.

css display table cell requires percentage width

Note also that vertical-align:top; is often necessary for correct table cell appearance.

css table-cell, contents have unnecessary top margin

adb command not found in linux environment

updating the $PATH did not work for me, therefore I added a symbolic link to adb to make it work, as follows:

ln -s <android-sdk-folder>/platform-tools/adb <android-sdk-folder>/tools/adb

How do you specify a different port number in SQL Management Studio?

127.0.0.1,6283

Add a comma between the ip and port

How to use passive FTP mode in Windows command prompt?

FileZilla Works well. I Use FileZilla FTP Client "Manual Transfer" which supports Passive mode.

Example: Open FileZilla and Select "Transfer" >> "Manual Transfer" then within the Manual Transfer Window, perform the following:

  1. Confirm proper Download / Upload option is selected
  2. For Remote: Enter name of directory where the file to download is located
  3. For Remote: Enter the name of the file to be downloaded
  4. For Local: Browse to desired directory you want to download file to
  5. For Local: Enter a file name to save downloaded file As (use same file name as file to be downloaded unless you want to change it)
  6. Check-Box "Start transfer immediately" and Click "OK"
  7. Download should start momentarily
  8. Note: If you forgot to Check-Box "Start transfer immediately"... No Problem: just Right-Click on the file to be downloaded (within the Process Queue (file transfer queue) at the bottom of the FileZilla window pane and Select "Process Queue"
  9. Download process should begin momentarily
  10. Done

Handling JSON Post Request in Go

I like to define custom structs locally. So:

// my handler func
func addImage(w http.ResponseWriter, r *http.Request) {

    // define custom type
    type Input struct {
        Url        string  `json:"url"`
        Name       string  `json:"name"`
        Priority   int8    `json:"priority"`
    }

    // define a var 
    var input Input

    // decode input or return error
    err := json.NewDecoder(r.Body).Decode(&input)
    if err != nil {
        w.WriteHeader(400)
        fmt.Fprintf(w, "Decode error! please check your JSON formating.")
        return
    }

    // print user inputs
    fmt.Fprintf(w, "Inputed name: %s", input.Name)

}

Delete all nodes and relationships in neo4j 1.8

you are probably doing it correct, only the dashboard shows just the higher ID taken, and thus the number of "active" nodes, relationships, although there are none. it is just informative.

to be sure you have an empty graph, run this command:

START n=node(*) return count(n);
START r=rel(*) return count(r);

if both give you 0, your deletion was succesfull.

What function is to replace a substring from a string in C?

There you go....this is the function to replace every occurance of char x with char y within character string str

char *zStrrep(char *str, char x, char y){
    char *tmp=str;
    while(*tmp)
        if(*tmp == x)
            *tmp++ = y; /* assign first, then incement */
        else
            *tmp++;

    *tmp='\0';
    return str;
}

An example usage could be

  Exmaple Usage
        char s[]="this is a trial string to test the function.";
        char x=' ', y='_';
        printf("%s\n",zStrrep(s,x,y));

  Example Output
        this_is_a_trial_string_to_test_the_function.

The function is from a string library I maintain on Github, you are more than welcome to have a look at other available functions or even contribute to the code :)

https://github.com/fnoyanisi/zString

EDIT: @siride is right, the function above replaces chars only. Just wrote this one, which replaces character strings.

#include <stdio.h>
#include <stdlib.h>

/* replace every occurance of string x with string y */
char *zstring_replace_str(char *str, const char *x, const char *y){
    char *tmp_str = str, *tmp_x = x, *dummy_ptr = tmp_x, *tmp_y = y;
    int len_str=0, len_y=0, len_x=0;

    /* string length */
    for(; *tmp_y; ++len_y, ++tmp_y)
        ;

    for(; *tmp_str; ++len_str, ++tmp_str)
        ;

    for(; *tmp_x; ++len_x, ++tmp_x)
        ;

    /* Bounds check */
    if (len_y >= len_str)
        return str;

    /* reset tmp pointers */
    tmp_y = y;
    tmp_x = x;

    for (tmp_str = str ; *tmp_str; ++tmp_str)
        if(*tmp_str == *tmp_x) {
            /* save tmp_str */
            for (dummy_ptr=tmp_str; *dummy_ptr == *tmp_x; ++tmp_x, ++dummy_ptr)
                if (*(tmp_x+1) == '\0' && ((dummy_ptr-str+len_y) < len_str)){
                /* Reached end of x, we got something to replace then!
                * Copy y only if there is enough room for it
                */
                    for(tmp_y=y; *tmp_y; ++tmp_y, ++tmp_str)
                        *tmp_str = *tmp_y;
            }
        /* reset tmp_x */
        tmp_x = x;
        }

    return str;
}

int main()
{
    char s[]="Free software is a matter of liberty, not price.\n"
             "To understand the concept, you should think of 'free' \n"
             "as in 'free speech', not as in 'free beer'";

    printf("%s\n\n",s);
    printf("%s\n",zstring_replace_str(s,"ree","XYZ"));
    return 0;
}

And below is the output

Free software is a matter of liberty, not price.
To understand the concept, you should think of 'free' 
as in 'free speech', not as in 'free beer'

FXYZ software is a matter of liberty, not price.
To understand the concept, you should think of 'fXYZ' 
as in 'fXYZ speech', not as in 'fXYZ beer'

What is an application binary interface (ABI)?

Summary

There are various interpretation and strong opinions of the exact layer that define an ABI (application binary interface).

In my view an ABI is a subjective convention of what is considered a given/platform for a specific API. The ABI is the "rest" of conventions that "will not change" for a specific API or that will be addressed by the runtime environment: executors, tools, linkers, compilers, jvm, and OS.

Defining an Interface: ABI, API

If you want to use a library like joda-time you must declare a dependency on joda-time-<major>.<minor>.<patch>.jar. The library follows best practices and use Semantic Versioning. This defines the API compatibility at three levels:

  1. Patch - You don't need to change at all your code. The library just fixes some bugs.
  2. Minor - You don't need to change your code since the additions
  3. Major - The interface (API) is changed and you might need to change your code.

In order for you to use a new major release of the same library a lot of other conventions are still to be respected:

  • The binary language used for the libraries (in Java cases the JVM target version that defines the Java bytecode)
  • Calling conventions
  • JVM conventions
  • Linking conventions
  • Runtime conventions All these are defined and managed by the tools we use.

Examples

Java case study

For example, Java standardized all these conventions, not in a tool, but in a formal JVM specification. The specification allowed other vendors to provide a different set of tools that can output compatible libraries.

Java provides two other interesting case studies for ABI: Scala versions and Dalvik virtual machine.

Dalvik virtual machine broke the ABI

The Dalvik VM needs a different type of bytecode than the Java bytecode. The Dalvik libraries are obtained by converting the Java bytecode (with same API) for Dalvik. In this way you can get two versions of the same API: defined by the original joda-time-1.7.2.jar. We could call it joda-time-1.7.2.jar and joda-time-1.7.2-dalvik.jar. They use a different ABI one is for the stack-oriented standard Java vms: Oracle's one, IBM's one, open Java or any other; and the second ABI is the one around Dalvik.

Scala successive releases are incompatible

Scala doesn't have binary compatibility between minor Scala versions: 2.X . For this reason the same API "io.reactivex" %% "rxscala" % "0.26.5" has three versions (in the future more): for Scala 2.10, 2.11 and 2.12. What is changed? I don't know for now, but the binaries are not compatible. Probably the latest versions adds things that make the libraries unusable on the old virtual machines, probably things related to linking/naming/parameter conventions.

Java successive releases are incompatible

Java has problems with the major releases of the JVM too: 4,5,6,7,8,9. They offer only backward compatibility. Jvm9 knows how to run code compiled/targeted (javac's -target option) for all other versions, while JVM 4 doesn't know how to run code targeted for JVM 5. All these while you have one joda-library. This incompatibility flies bellow the radar thanks to different solutions:

  1. Semantic versioning: when libraries target higher JVM they usually change the major version.
  2. Use JVM 4 as the ABI, and you're safe.
  3. Java 9 adds a specification on how you can include bytecode for specific targeted JVM in the same library.

Why did I start with the API definition?

API and ABI are just conventions on how you define compatibility. The lower layers are generic in respect of a plethora of high level semantics. That's why it's easy to make some conventions. The first kind of conventions are about memory alignment, byte encoding, calling conventions, big and little endian encodings, etc. On top of them you get the executable conventions like others described, linking conventions, intermediate byte code like the one used by Java or LLVM IR used by GCC. Third you get conventions on how to find libraries, how to load them (see Java classloaders). As you go higher and higher in concepts you have new conventions that you consider as a given. That's why they didn't made it to the semantic versioning. They are implicit or collapsed in the major version. We could amend semantic versioning with <major>-<minor>-<patch>-<platform/ABI>. This is what is actually happening already: platform is already a rpm, dll, jar (JVM bytecode), war(jvm+web server), apk, 2.11 (specific Scala version) and so on. When you say APK you already talk about a specific ABI part of your API.

API can be ported to different ABI

The top level of an abstraction (the sources written against the highest API can be recompiled/ported to any other lower level abstraction.

Let's say I have some sources for rxscala. If the Scala tools are changed I can recompile them to that. If the JVM changes I could have automatic conversions from the old machine to the new one without bothering with the high level concepts. While porting might be difficult will help any other client. If a new operating system is created using a totally different assembler code a translator can be created.

APIs ported across languages

There are APIs that are ported in multiple languages like reactive streams. In general they define mappings to specific languages/platforms. I would argue that the API is the master specification formally defined in human language or even a specific programming language. All the other "mappings" are ABI in a sense, else more API than the usual ABI. The same is happening with the REST interfaces.

Color text in terminal applications in UNIX

This is a little C program that illustrates how you could use color codes:

#include <stdio.h>

#define KNRM  "\x1B[0m"
#define KRED  "\x1B[31m"
#define KGRN  "\x1B[32m"
#define KYEL  "\x1B[33m"
#define KBLU  "\x1B[34m"
#define KMAG  "\x1B[35m"
#define KCYN  "\x1B[36m"
#define KWHT  "\x1B[37m"

int main()
{
    printf("%sred\n", KRED);
    printf("%sgreen\n", KGRN);
    printf("%syellow\n", KYEL);
    printf("%sblue\n", KBLU);
    printf("%smagenta\n", KMAG);
    printf("%scyan\n", KCYN);
    printf("%swhite\n", KWHT);
    printf("%snormal\n", KNRM);

    return 0;
}

django no such table:

One way to sync your database to your django models is to delete your database file and run makemigrations and migrate commands again. This will reflect your django models structure to your database from scratch. Although, make sure to backup your database file before deleting in case you need your records.

This solution worked for me since I wasn't much bothered about the data and just wanted my db and models structure to sync up.

How to see data from .RData file?

It sounds like the only varaible stored in the .RData file was one named isfar.

Are you really sure that you saved the table? The command should have been:

save(the_table, file = "isfar.RData")

There are many ways to examine a variable.

Type it's name at the command prompt to see it printed. Then look at str, ls.str, summary, View and unclass.

How to check if a column exists in a datatable

DataColumnCollection col = datatable.Columns;        
if (!columns.Contains("ColumnName1"))
{
   //Column1 Not Exists
}

if (columns.Contains("ColumnName2"))
{
   //Column2 Exists
}

SQL SELECT from multiple tables

SELECT `product`.*, `customer1`.`name1`, `customer2`.`name2`
FROM `product`
LEFT JOIN `customer1` ON `product`.`cid` = `customer1`.`cid`
LEFT JOIN `customer2` ON `product`.`cid` = `customer2`.`cid`

JQuery show/hide when hover

I hope my script help you.

<i class="mostrar-producto">mostrar...</i>
<div class="producto" style="display:none;position: absolute;">Producto</div>

My script

<script>
$(".mostrar-producto").mouseover(function(){
     $(".producto").fadeIn();
 });

 $(".mostrar-producto").mouseleave(function(){
      $(".producto").fadeOut();
  });
</script>

this in equals method

this is the current Object instance. Whenever you have a non-static method, it can only be called on an instance of your object.

How do I get an OAuth 2.0 authentication token in C#

This example get token thouth HttpWebRequest

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(pathapi);
        request.Method = "POST";
        string postData = "grant_type=password";
        ASCIIEncoding encoding = new ASCIIEncoding();
        byte[] byte1 = encoding.GetBytes(postData);

        request.ContentType = "application/x-www-form-urlencoded";

        request.ContentLength = byte1.Length;
        Stream newStream = request.GetRequestStream();
        newStream.Write(byte1, 0, byte1.Length);

        HttpWebResponse response = request.GetResponse() as HttpWebResponse;            
        using (Stream responseStream = response.GetResponseStream())
        {
            StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
            getreaderjson = reader.ReadToEnd();
        }

AngularJS: How to run additional code after AngularJS has rendered a template?

Finally i found the solution, i was using a REST service to update my collection. In order to convert datatable jquery is the follow code:

$scope.$watchCollection( 'conferences', function( old, nuew ) {
        if( old === nuew ) return;
        $( '#dataTablex' ).dataTable().fnDestroy();
        $timeout(function () {
                $( '#dataTablex' ).dataTable();
        });
    });

How to copy the first few lines of a giant file, and add a line of text at the end of it using some Linux commands?

I am assuming what you are trying to achieve is to insert a line after the first few lines of of a textfile.

head -n10 file.txt >> newfile.txt
echo "your line >> newfile.txt
tail -n +10 file.txt >> newfile.txt

If you don't want to rest of the lines from the file, just skip the tail part.

Removing empty rows of a data file in R

I assume you want to remove rows that are all NAs. Then, you can do the following :

data <- rbind(c(1,2,3), c(1, NA, 4), c(4,6,7), c(NA, NA, NA), c(4, 8, NA)) # sample data
data
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    1   NA    4
[3,]    4    6    7
[4,]   NA   NA   NA
[5,]    4    8   NA

data[rowSums(is.na(data)) != ncol(data),]
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    1   NA    4
[3,]    4    6    7
[4,]    4    8   NA

If you want to remove rows that have at least one NA, just change the condition :

data[rowSums(is.na(data)) == 0,]
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    6    7

Bootstrap 3 dropdown select

I found a better library which transform the normal <select> <option> to bootsrap button dropdown format.

https://developer.snapappointments.com/bootstrap-select/

Parsing JSON Array within JSON Object

mainJSON.getJSONArray("source") returns a JSONArray, hence you can remove the new JSONArray.

The JSONArray contructor with an object parameter expects it to be a Collection or Array (not JSONArray)

Try this:

JSONArray jsonMainArr = mainJSON.getJSONArray("source"); 

Python functions call by reference

Python is neither pass-by-value nor pass-by-reference. It's more of "object references are passed by value" as described here:

  1. Here's why it's not pass-by-value. Because

    def append(list):
        list.append(1)
    
    list = [0]
    reassign(list)
    append(list)
    

returns [0,1] showing that some kind of reference was clearly passed as pass-by-value does not allow a function to alter the parent scope at all.

Looks like pass-by-reference then, hu? Nope.

  1. Here's why it's not pass-by-reference. Because

    def reassign(list):
      list = [0, 1]
    
    list = [0]
    reassign(list)
    print list
    

returns [0] showing that the original reference was destroyed when list was reassigned. pass-by-reference would have returned [0,1].

For more information look here:

If you want your function to not manipulate outside scope, you need to make a copy of the input parameters that creates a new object.

from copy import copy

def append(list):
  list2 = copy(list)
  list2.append(1)
  print list2

list = [0]
append(list)
print list

Why do I get a SyntaxError for a Unicode escape in my file path?

f = open('C:\\Users\\Pooja\\Desktop\\trolldata.csv')

Use '\\' for python program in Python version 3 and above.. Error will be resolved..

Create table in SQLite only if it doesn't exist already

From http://www.sqlite.org/lang_createtable.html:

CREATE TABLE IF NOT EXISTS some_table (id INTEGER PRIMARY KEY AUTOINCREMENT, ...);

Android : How to set onClick event for Button in List item of ListView

This has been discussed in many posts but still I could not figure out a solution with:

android:focusable="false"
android:focusableInTouchMode="false"
android:focusableInTouchMode="false"

Below solution will work with any of the ui components : Button, ImageButtons, ImageView, Textview. LinearLayout, RelativeLayout clicks inside a listview cell and also will respond to onItemClick:

Adapter class - getview():

    @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = convertView;
            if (view == null) {
                view = lInflater.inflate(R.layout.my_ref_row, parent, false);
            }
            final Organization currentOrg = organizationlist.get(position).getOrganization();

            TextView name = (TextView) view.findViewById(R.id.name);
            Button btn = (Button) view.findViewById(R.id.btn_check);
            btn.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    context.doSelection(currentOrg);

                }
            });

       if(currentOrg.isSelected()){
            btn.setBackgroundResource(R.drawable.sub_search_tick);
        }else{
            btn.setBackgroundResource(R.drawable.sub_search_tick_box);
        }

    }

In this was you can get the button clicked object to the activity. (Specially when you want the button to act as a check box with selected and non-selected states):

    public void doSelection(Organization currentOrg) {
        Log.e("Btn clicked ", currentOrg.getOrgName());
        if (currentOrg.isSelected() == false) {
            currentOrg.setSelected(true);
        } else {
            currentOrg.setSelected(false);
        }
        adapter.notifyDataSetChanged();

    }

GIT: Checkout to a specific folder

For a single file:

git show HEAD:abspath/to/file > file.copy

How to execute a Python script from the Django shell?

Something I just found to be interesting is Django Scripts, which allows you to write scripts to be run with python manage.py runscript foobar. More detailed information on implementation and scructure can be found here, http://django-extensions.readthedocs.org/en/latest/index.html

How to compare two columns in Excel (from different sheets) and copy values from a corresponding column if the first two columns match?

As kmcamara discovered, this is exactly the kind of problem that VLOOKUP is intended to solve, and using vlookup is arguably the simplest of the alternative ways to get the job done.

In addition to the three parameters for lookup_value, table_range to be searched, and the column_index for return values, VLOOKUP takes an optional fourth argument that the Excel documentation calls the "range_lookup".

Expanding on deathApril's explanation, if this argument is set to TRUE (or 1) or omitted, the table range must be sorted in ascending order of the values in the first column of the range for the function to return what would typically be understood to be the "correct" value. Under this default behavior, the function will return a value based upon an exact match, if one is found, or an approximate match if an exact match is not found.

If the match is approximate, the value that is returned by the function will be based on the next largest value that is less than the lookup_value. For example, if "12AT8003" were missing from the table in Sheet 1, the lookup formulas for that value in Sheet 2 would return '2', since "12AT8002" is the largest value in the lookup column of the table range that is less than "12AT8003". (VLOOKUP's default behavior makes perfect sense if, for example, the goal is to look up rates in a tax table.)

However, if the fourth argument is set to FALSE (or 0), VLOOKUP returns a looked-up value only if there is an exact match, and an error value of #N/A if there is not. It is now the usual practice to wrap an exact VLOOKUP in an IFERROR function in order to catch the no-match gracefully. Prior to the introduction of IFERROR, no matches were checked with an IF function using the VLOOKUP formula once to check whether there was a match, and once to return the actual match value.

Though initially harder to master, deusxmach1na's proposed solution is a variation on a powerful set of alternatives to VLOOKUP that can be used to return values for a column or list to the left of the lookup column, expanded to handle cases where an exact match on more than one criterion is needed, or modified to incorporate OR as well as AND match conditions among multiple criteria.

Repeating kcamara's chosen solution, the VLOOKUP formula for this problem would be:

   =VLOOKUP(A1,Sheet1!A$1:B$600,2,FALSE)

Callback when DOM is loaded in react.js

A combination of componentDidMount and componentDidUpdate will get the job done in a code with class components. But if you're writing code in total functional components the Effect Hook would do a great job it's the same as componentDidMount and componentDidUpdate.

import React, { useState, useEffect } from 'react';

function Example() {
  const [count, setCount] = useState(0);

  // Similar to componentDidMount and componentDidUpdate:
  useEffect(() => {
    // Update the document title using the browser API
    document.title = `You clicked ${count} times`;
  });

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

https://reactjs.org/docs/hooks-effect.html

How should I deal with "package 'xxx' is not available (for R version x.y.z)" warning?

Another minor addition, while trying to test for an old R version using the docker image rocker/r-ver:3.1.0

  1. The default repos setting is MRAN and this fails to get many packages.
  2. That version of R doesn't have https, so, for example: install.packages("knitr", repos = "https://cran.rstudio.com") seems to work.

Difference between string and text in rails?

As explained above not just the db datatype it will also affect the view that will be generated if you are scaffolding. string will generate a text_field text will generate a text_area

Customizing the template within a Directive

The above answers unfortunately don't quite work. In particular, the compile stage does not have access to scope, so you can't customize the field based on dynamic attributes. Using the linking stage seems to offer the most flexibility (in terms of asynchronously creating dom, etc.) The below approach addresses that:

<!-- Usage: -->
<form>
  <form-field ng-model="formModel[field.attr]" field="field" ng-repeat="field in fields">
</form>
// directive
angular.module('app')
.directive('formField', function($compile, $parse) {
  return { 
    restrict: 'E', 
    compile: function(element, attrs) {
      var fieldGetter = $parse(attrs.field);

      return function (scope, element, attrs) {
        var template, field, id;
        field = fieldGetter(scope);
        template = '..your dom structure here...'
        element.replaceWith($compile(template)(scope));
      }
    }
  }
})

I've created a gist with more complete code and a writeup of the approach.

Java, How to get number of messages in a topic in apache kafka

You may use kafkatool. Please check this link -> http://www.kafkatool.com/download.html

Kafka Tool is a GUI application for managing and using Apache Kafka clusters. It provides an intuitive UI that allows one to quickly view objects within a Kafka cluster as well as the messages stored in the topics of the cluster. enter image description here

Can (a== 1 && a ==2 && a==3) ever evaluate to true?

Okay, another hack with generators:

_x000D_
_x000D_
const value = function* () {_x000D_
  let i = 0;_x000D_
  while(true) yield ++i;_x000D_
}();_x000D_
_x000D_
Object.defineProperty(this, 'a', {_x000D_
  get() {_x000D_
    return value.next().value;_x000D_
  }_x000D_
});_x000D_
_x000D_
if (a === 1 && a === 2 && a === 3) {_x000D_
  console.log('yo!');_x000D_
}
_x000D_
_x000D_
_x000D_

Add vertical whitespace using Twitter Bootstrap?

In v2, there isn't anything built-in for that much vertical space, so you'll want to stick with a custom class. For smaller heights, I usually just throw a <div class="control-group"> around a button.

How can I check if some text exist or not in the page using Selenium?

  boolean Error = driver.getPageSource().contains("Your username or password was incorrect.");
    if (Error == true)
    {
     System.out.print("Login unsuccessful");
    }
    else
    {
     System.out.print("Login successful");
    }

Android Studio-No Module

Go to Project setting enter image description here

CHECK if the project setting is like this,if the module that you want is show in here enter image description here

IF the module that you want or "Module SDK" is not show or not correct.

then go to the module's build.gradle file to check if the CompileSdkVersion has installed in your computer.

or modifier the CompileSdkVersion to the version that has been installed in your computer.

In my case:I just installed sdk version 29 in my computer but in the module build.gradle file ,I'm setting the CompilerSdkVersion 28

Both are not matched.

Modifier the build.gradle file CompilerSdkVersion 29 which I installed in my computer

It's working!!!

enter image description here enter image description here

How to paste text to end of every line? Sublime 2

Yeah Regex is cool, but there are other alternative.

  • Select all the lines you want to prefix or suffix
  • Goto menu Selection -> Split into Lines (Cmd/Ctrl + Shift + L)

This allows you to edit multiple lines at once. Now you can add *Quotes (") or anything * at start and end of each lines.

Get month name from number

Calendar API

From that you can see that calendar.month_name[3] would return March, and the array index of 0 is the empty string, so there's no need to worry about zero-indexing either.

How can I reference a commit in an issue comment on GitHub?

If you are trying to reference a commit in another repo than the issue is in, you can prefix the commit short hash with reponame@.

Suppose your commit is in the repo named dev, and the GitLab issue is in the repo named test. You can leave a comment on the issue and reference the commit by dev@e9c11f0a (where e9c11f0a is the first 8 letters of the sha hash of the commit you want to link to) if that makes sense.

Display List in a View MVC

Your action method considers model type asList<string>. But, in your view you are waiting for IEnumerable<Standings.Models.Teams>. You can solve this problem with changing the model in your view to List<string>.

But, the best approach would be to return IEnumerable<Standings.Models.Teams> as a model from your action method. Then you haven't to change model type in your view.

But, in my opinion your models are not correctly implemented. I suggest you to change it as:

public class Team
{
    public int Position { get; set; }
    public string HomeGround {get; set;}
    public string NickName {get; set;}
    public int Founded { get; set; }
    public string Name { get; set; }
}

Then you must change your action method as:

public ActionResult Index()
{
    var model = new List<Team>();

    model.Add(new Team { Name = "MU"});
    model.Add(new Team { Name = "Chelsea"});
    ...

    return View(model);
}

And, your view:

@model IEnumerable<Standings.Models.Team>

@{
     ViewBag.Title = "Standings";
}

@foreach (var item in Model)
{
    <div>
        @item.Name
        <hr />
    </div>
}

Django: Redirect to previous page after login

Django's built-in authentication works the way you want.

Their login pages include a next query string which is the page to return to after login.

Look at http://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.decorators.login_required

MongoError: connect ECONNREFUSED 127.0.0.1:27017

because you didn't start mongod process before you try starting mongo shell.

Start mongod server

mongod

Open another terminal window

Start mongo shell

mongo

What is a unix command for deleting the first N characters of a line?

tail -f logfile | grep org.springframework | cut -c 900-

would remove the first 900 characters

cut uses 900- to show the 900th character to the end of the line

however when I pipe all of this through grep I don't get anything

How do I use Access-Control-Allow-Origin? Does it just go in between the html head tags?

<?php header("Access-Control-Allow-Origin: http://example.com"); ?>

This command disables only first console warning info

console

Result: console result

How can I completely uninstall nodejs, npm and node in Ubuntu

Try the following commands:

$ sudo apt-get install nodejs
$ sudo apt-get install aptitude
$ sudo aptitude install npm

Using Gradle to build a jar with dependencies

Simple sulution

jar {
    manifest {
        attributes 'Main-Class': 'cova2.Main'
    } 
    doFirst {
        from { configurations.runtime.collect { it.isDirectory() ? it : zipTree(it) } }
    }
}

change <audio> src with javascript

with jQuery:

 $("#playerSource").attr("src", "new_src");

    var audio = $("#player");      

    audio[0].pause();
    audio[0].load();//suspends and restores all audio element

    if (isAutoplay) 
        audio[0].play();

HTML CSS How to stop a table cell from expanding

To post Chris Dutrow's comment here as answer:

style="table-layout:fixed;" 

in the style of the table itself is what worked for me. Thanks Chris!

Full example:

<table width="55" height="55" border="0" cellspacing="0" cellpadding="0" style="border-radius:50%; border:0px solid #000000;table-layout:fixed" align="center" bgcolor="#152b47">
  <tbody>
    <td style="color:#ffffff;font-family:TW-Averta-Regular,Averta,Helvetica,Arial;font-size:11px;overflow:hidden;width:55px;text-align:center;valign:top;whitespace:nowrap;">

     Your table content here

    </td>
  </tbody>
</table>

How do you find the first key in a dictionary?

For Python 3 below eliminates overhead of list conversion:

first = next(iter(prices.values()))

JavaScript code to stop form submission

All your answers gave something to work with.

FINALLY, this worked for me: (if you dont choose at least one checkbox item, it warns and stays in the same page)

<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <form name="helloForm" action="HelloWorld" method="GET"  onsubmit="valthisform();">
            <br>
            <br><b> MY LIKES </b>
            <br>
            First Name: <input type="text" name="first_name" required>
            <br />
            Last Name: <input type="text" name="last_name"  required />
            <br>
            <input type="radio" name="modifyValues" value="uppercase" required="required">Convert to uppercase <br>
            <input type="radio" name="modifyValues" value="lowercase" required="required">Convert to lowercase <br>
            <input type="radio" name="modifyValues" value="asis"      required="required" checked="checked">Do not convert <br>
            <br>
            <input type="checkbox" name="c1" value="maths"     /> Maths
            <input type="checkbox" name="c1" value="physics"   /> Physics
            <input type="checkbox" name="c1" value="chemistry" /> Chemistry
            <br>

            <button onclick="submit">Submit</button>

            <!-- input type="submit" value="submit" / -->
            <script>
                <!---
                function valthisform() {
                    var checkboxs=document.getElementsByName("c1");
                    var okay=false;
                    for(var i=0,l=checkboxs.length;i<l;i++) {
                        if(checkboxs[i].checked) {
                            okay=true;
                            break;
                        }
                    }
                    if (!okay) { 
                        alert("Please check a checkbox");
                        event.preventDefault();
                    } else {
                    }
                }
                -->
            </script>
        </form>
    </body>
</html>

Linux command to print directory structure in the form of a tree

This command works to display both folders and files.

find . | sed -e "s/[^-][^\/]*\// |/g" -e "s/|\([^ ]\)/|-\1/"

Example output:

.
 |-trace.pcap
 |-parent
 | |-chdir1
 | | |-file1.txt
 | |-chdir2
 | | |-file2.txt
 | | |-file3.sh
 |-tmp
 | |-json-c-0.11-4.el7_0.x86_64.rpm

Source: Comment from @javasheriff here. Its submerged as a comment and posting it as answer helps users spot it easily.

Android/Eclipse: how can I add an image in the res/drawable folder?

Just copy the image and paste into Eclipse in the res/drawable directory. Note that the image name should be in lowercase, otherwise it will end up with an error.

Counting the number of files in a directory using Java

Unfortunately, as mmyers said, File.list() is about as fast as you are going to get using Java. If speed is as important as you say, you may want to consider doing this particular operation using JNI. You can then tailor your code to your particular situation and filesystem.

How to avoid 'cannot read property of undefined' errors?

In str's answer, value 'undefined' will be returned instead of the set default value if the property is undefined. This sometimes can cause bugs. The following will make sure the defaultVal will always be returned when either the property or the object is undefined.

const temp = {};
console.log(getSafe(()=>temp.prop, '0'));

function getSafe(fn, defaultVal) {
    try {
        if (fn() === undefined) {
            return defaultVal
        } else {
            return fn();
        }

    } catch (e) {
        return defaultVal;
    }
}

TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

What the error is telling, is that you can't convert an entire list into an integer. You could get an index from the list and convert that into an integer:

x = ["0", "1", "2"] 
y = int(x[0]) #accessing the zeroth element

If you're trying to convert a whole list into an integer, you are going to have to convert the list into a string first:

x = ["0", "1", "2"]
y = ''.join(x) # converting list into string
z = int(y)

If your list elements are not strings, you'll have to convert them to strings before using str.join:

x = [0, 1, 2]
y = ''.join(map(str, x))
z = int(y)

Also, as stated above, make sure that you're not returning a nested list.

CREATE DATABASE permission denied in database 'master' (EF code-first)

If you're running the site under IIS, you may need to set the Application Pool's Identity to an administrator.

Event detect when css property changed using Jquery

You can use jQuery's css function to test the CSS properties, eg. if ($('node').css('display') == 'block').

Colin is right, that there is no explicit event that gets fired when a specific CSS property gets changed. But you may be able to flip it around, and trigger an event that sets the display, and whatever else.

Also consider using adding CSS classes to get the behavior you want. Often you can add a class to a containing element, and use CSS to affect all elements. I often slap a class onto the body element to indicate that an AJAX response is pending. Then I can use CSS selectors to get the display I want.

Not sure if this is what you're looking for.

Python Pandas : pivot table with aggfunc = count unique distinct

For best performance I recommend doing DataFrame.drop_duplicates followed up aggfunc='count'.

Others are correct that aggfunc=pd.Series.nunique will work. This can be slow, however, if the number of index groups you have is large (>1000).

So instead of (to quote @Javier)

df2.pivot_table('X', 'Y', 'Z', aggfunc=pd.Series.nunique)

I suggest

df2.drop_duplicates(['X', 'Y', 'Z']).pivot_table('X', 'Y', 'Z', aggfunc='count')

This works because it guarantees that every subgroup (each combination of ('Y', 'Z')) will have unique (non-duplicate) values of 'X'.

Passing std::string by Value or Reference

Check this answer for C++11. Basically, if you pass an lvalue the rvalue reference

From this article:

void f1(String s) {
    vector<String> v;
    v.push_back(std::move(s));
}
void f2(const String &s) {
    vector<String> v;
    v.push_back(s);
}

"For lvalue argument, ‘f1’ has one extra copy to pass the argument because it is by-value, while ‘f2’ has one extra copy to call push_back. So no difference; for rvalue argument, the compiler has to create a temporary ‘String(L“”)’ and pass the temporary to ‘f1’ or ‘f2’ anyway. Because ‘f2’ can take advantage of move ctor when the argument is a temporary (which is an rvalue), the costs to pass the argument are the same now for ‘f1’ and ‘f2’."

Continuing: " This means in C++11 we can get better performance by using pass-by-value approach when:

  1. The parameter type supports move semantics - All standard library components do in C++11
  2. The cost of move constructor is much cheaper than the copy constructor (both the time and stack usage).
  3. Inside the function, the parameter type will be passed to another function or operation which supports both copy and move.
  4. It is common to pass a temporary as the argument - You can organize you code to do this more.

"

OTOH, for C++98 it is best to pass by reference - less data gets copied around. Passing const or non const depend of whether you need to change the argument or not.

How to debug a referenced dll (having pdb)

Step 1: Go to Tools-->Option-->Debugging

Step 2: Uncheck Enable Just My Code

Step 3: Uncheck Require source file exactly match with original Version

Step 4: Uncheck Step over Properties and Operators

Step 5: Go to Project properties-->Debug

Step 6: Check Enable native code debugging

Chaining Observables in RxJS

About promise composition vs. Rxjs, as this is a frequently asked question, you can refer to a number of previously asked questions on SO, among which :

Basically, flatMap is the equivalent of Promise.then.

For your second question, do you want to replay values already emitted, or do you want to process new values as they arrive? In the first case, check the publishReplay operator. In the second case, standard subscription is enough. However you might need to be aware of the cold. vs. hot dichotomy depending on your source (cf. Hot and Cold observables : are there 'hot' and 'cold' operators? for an illustrated explanation of the concept)

Official reasons for "Software caused connection abort: socket write error"

For anyone using simple Client Server programms and getting this error, it is a problem of unclosed (or closed to early) Input or Output Streams.

MongoDB relationships: embed or reference?

I know this is quite old but if you are looking for the answer to the OP's question on how to return only specified comment, you can use the $ (query) operator like this:

db.question.update({'comments.content': 'xxx'}, {'comments.$': true})

How do I add the contents of an iterable to a set?

For the benefit of anyone who might believe e.g. that doing aset.add() in a loop would have performance competitive with doing aset.update(), here's an example of how you can test your beliefs quickly before going public:

>\python27\python -mtimeit -s"it=xrange(10000);a=set(xrange(100))" "a.update(it)"
1000 loops, best of 3: 294 usec per loop

>\python27\python -mtimeit -s"it=xrange(10000);a=set(xrange(100))" "for i in it:a.add(i)"
1000 loops, best of 3: 950 usec per loop

>\python27\python -mtimeit -s"it=xrange(10000);a=set(xrange(100))" "a |= set(it)"
1000 loops, best of 3: 458 usec per loop

>\python27\python -mtimeit -s"it=xrange(20000);a=set(xrange(100))" "a.update(it)"
1000 loops, best of 3: 598 usec per loop

>\python27\python -mtimeit -s"it=xrange(20000);a=set(xrange(100))" "for i in it:a.add(i)"
1000 loops, best of 3: 1.89 msec per loop

>\python27\python -mtimeit -s"it=xrange(20000);a=set(xrange(100))" "a |= set(it)"
1000 loops, best of 3: 891 usec per loop

Looks like the cost per item of the loop approach is over THREE times that of the update approach.

Using |= set() costs about 1.5x what update does but half of what adding each individual item in a loop does.

get specific row from spark dataframe

When you want to fetch max value of a date column from dataframe, just the value without object type or Row object information, you can refer to below code.

table = "mytable"

max_date = df.select(max('date_col')).first()[0]

2020-06-26
instead of Row(max(reference_week)=datetime.date(2020, 6, 26))

SQL Server: Filter output of sp_who2

I am writing here for future use of my own. It uses sp_who2 and insert into table variable instead of temp table because Temp table cannot be used twice if you do not drop it. And shows blocked and blocker at the same line.

--blocked: waiting becaused blocked by blocker
--blocker: caused blocking
declare @sp_who2 table(
    SPID int,
    Status varchar(max),
    Login varchar(max),
    HostName varchar(max),
    BlkBy varchar(max),
    DBName varchar(max),
    Command varchar(max),
    CPUTime int,
    DiskIO int,
    LastBatch varchar(max),
    ProgramName varchar(max),
    SPID_2 int,
    REQUESTID int
)
insert into @sp_who2 exec sp_who2
select  w.SPID blocked_spid, w.BlkBy blocker_spid, tblocked.text blocked_text, tblocker.text blocker_text
from    @sp_who2 w
        inner join sys.sysprocesses pblocked on w.SPID = pblocked.spid
        cross apply sys.dm_exec_sql_text(pblocked.sql_handle) tblocked
        inner join sys.sysprocesses pblocker on case when w.BlkBy = '  .' then 0 else cast(w.BlkBy as int) end = pblocker.spid
        cross apply sys.dm_exec_sql_text(pblocker.sql_handle) tblocker
where   pblocked.Status = 'SUSPENDED'

Open Source Alternatives to Reflector?

Another replacement would be dotPeek. JetBrains announced it as a free tool. It will probably have more features when used with their Resharper but even when used alone it works very well.

User experience is more like MSVS than a standalone disassembler. I like code reading more than in Reflector. Ctrl+T navigation suits me better too. Just synchronizing the tree with the code pane could be better.

All in all, it is still in development but very well usable already.

Free Rest API to retrieve current datetime as string (timezone irrelevant)

If you're using Rails, you can just make an empty file in the public folder and use ajax to get that. Then parse the headers for the Date header. Files in the Public folder bypass the Rails stack, and so have lower latency.

How to replace multiple substrings of a string?

You can use the pandas library and the replace function which supports both exact matches as well as regex replacements. For example:

df = pd.DataFrame({'text': ['Billy is going to visit Rome in November', 'I was born in 10/10/2010', 'I will be there at 20:00']})

to_replace=['Billy','Rome','January|February|March|April|May|June|July|August|September|October|November|December', '\d{2}:\d{2}', '\d{2}/\d{2}/\d{4}']
replace_with=['name','city','month','time', 'date']

print(df.text.replace(to_replace, replace_with, regex=True))

And the modified text is:

0    name is going to visit city in month
1                      I was born in date
2                 I will be there at time

You can find an example here. Notice that the replacements on the text are done with the order they appear in the lists

How to set a header in an HTTP response?

Header fields are not copied to subsequent requests. You should use either cookie for this (addCookie method) or store "REMOTE_USER" in session (which you can obtain with getSession method).

I want to exception handle 'list index out of range.'

For anyone interested in a shorter way:

gotdata = len(dlist)>1 and dlist[1] or 'null'

But for best performance, I suggest using False instead of 'null', then a one line test will suffice:

gotdata = len(dlist)>1 and dlist[1]

Pretty printing XML in Python

I solved this with some lines of code, opening the file, going trough it and adding indentation, then saving it again. I was working with small xml files, and did not want to add dependencies, or more libraries to install for the user. Anyway, here is what I ended up with:

    f = open(file_name,'r')
    xml = f.read()
    f.close()

    #Removing old indendations
    raw_xml = ''        
    for line in xml:
        raw_xml += line

    xml = raw_xml

    new_xml = ''
    indent = '    '
    deepness = 0

    for i in range((len(xml))):

        new_xml += xml[i]   
        if(i<len(xml)-3):

            simpleSplit = xml[i:(i+2)] == '><'
            advancSplit = xml[i:(i+3)] == '></'        
            end = xml[i:(i+2)] == '/>'    
            start = xml[i] == '<'

            if(advancSplit):
                deepness += -1
                new_xml += '\n' + indent*deepness
                simpleSplit = False
                deepness += -1
            if(simpleSplit):
                new_xml += '\n' + indent*deepness
            if(start):
                deepness += 1
            if(end):
                deepness += -1

    f = open(file_name,'w')
    f.write(new_xml)
    f.close()

It works for me, perhaps someone will have some use of it :)

Copy and Paste a set range in the next empty row

You could also try this

Private Sub CommandButton1_Click()

Sheets("Sheet1").Range("A3:E3").Copy

Dim lastrow As Long
lastrow = Range("A65536").End(xlUp).Row

Sheets("Summary Info").Activate
Cells(lastrow + 1, 1).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False

End Sub

Importing large sql file to MySql via command line

Guys regarding time taken for importing huge files most importantly it takes more time is because default setting of mysql is "autocommit = true", you must set that off before importing your file and then check how import works like a gem...

First open MySQL:

mysql -u root -p

Then, You just need to do following :

mysql>use your_db

mysql>SET autocommit=0 ; source the_sql_file.sql ; COMMIT ;

"multiple target patterns" Makefile error

I met with the same error. After struggling, I found that it was due to "Space" in the folder name.

For example :

Earlier My folder name was : "Qt Projects"

Later I changed it to : "QtProjects"

and my issue was resolved.

Its very simple but sometimes a major issue.

How to add header data in XMLHttpRequest when using formdata?

Use: xmlhttp.setRequestHeader(key, value);

UTF-8 text is garbled when form is posted as multipart/form-data

The filter thing and setting up Tomcat to support UTF-8 URIs is only important if you're passing the via the URL's query string, as you would with a HTTP GET. If you're using a POST, with a query string in the HTTP message's body, what's important is going to be the content-type of the request and this will be up to the browser to set the content-type to UTF-8 and send the content with that encoding.

The only way to really do this is by telling the browser that you can only accept UTF-8 by setting the Accept-Charset header on every response to "UTF-8;q=1,ISO-8859-1;q=0.6". This will put UTF-8 as the best quality and the default charset, ISO-8859-1, as acceptable, but a lower quality.

When you say the file name is garbled, is it garbled in the HttpServletRequest.getParameter's return value?

Do I need to close() both FileReader and BufferedReader?

The source code for BufferedReader shows that the underlying is closed when you close the BufferedReader.

Using sudo with Python script

Please try module pexpect. Here is my code:

import pexpect
remove = pexpect.spawn('sudo dpkg --purge mytool.deb')
remove.logfile = open('log/expect-uninstall-deb.log', 'w')
remove.logfile.write('try to dpkg --purge mytool\n')
if remove.expect(['(?i)password.*']) == 0:
    # print "successfull"
    remove.sendline('mypassword')
    time.sleep(2)
    remove.expect(pexpect.EOF,5)
else:
    raise AssertionError("Fail to Uninstall deb package !")

Why doesn't Dijkstra's algorithm work for negative weight edges?

Try Dijkstra's algorithm on the following graph, assuming A is the source node and D is the destination, to see what is happening:

Graph

Note that you have to follow strictly the algorithm definition and you should not follow your intuition (which tells you the upper path is shorter).

The main insight here is that the algorithm only looks at all directly connected edges and it takes the smallest of these edge. The algorithm does not look ahead. You can modify this behavior , but then it is not the Dijkstra algorithm anymore.

How do I create an abstract base class in JavaScript?

We can use Factory design pattern in this case. Javascript use prototype to inherit the parent's members.

Define the parent class constructor.

var Animal = function() {
  this.type = 'animal';
  return this;
}
Animal.prototype.tired = function() {
  console.log('sleeping: zzzZZZ ~');
}

And then create children class.

// These are the child classes
Animal.cat = function() {
  this.type = 'cat';
  this.says = function() {
    console.log('says: meow');
  }
}

Then define the children class constructor.

// Define the child class constructor -- Factory Design Pattern.
Animal.born = function(type) {
  // Inherit all members and methods from parent class,
  // and also keep its own members.
  Animal[type].prototype = new Animal();
  // Square bracket notation can deal with variable object.
  creature = new Animal[type]();
  return creature;
}

Test it.

var timmy = Animal.born('cat');
console.log(timmy.type) // cat
timmy.says(); // meow
timmy.tired(); // zzzZZZ~

Here's the Codepen link for the full example coding.

setting system property

System.setProperty("gate.home", "/some/directory"); 

After that you can retrieve its value later by calling

String value =  System.getProperty("gate.home");

What does set -e mean in a bash script?

As per bash - The Set Builtin manual, if -e/errexit is set, the shell exits immediately if a pipeline consisting of a single simple command, a list or a compound command returns a non-zero status.

By default, the exit status of a pipeline is the exit status of the last command in the pipeline, unless the pipefail option is enabled (it's disabled by default).

If so, the pipeline's return status of the last (rightmost) command to exit with a non-zero status, or zero if all commands exit successfully.

If you'd like to execute something on exit, try defining trap, for example:

trap onexit EXIT

where onexit is your function to do something on exit, like below which is printing the simple stack trace:

onexit(){ while caller $((n++)); do :; done; }

There is similar option -E/errtrace which would trap on ERR instead, e.g.:

trap onerr ERR

Examples

Zero status example:

$ true; echo $?
0

Non-zero status example:

$ false; echo $?
1

Negating status examples:

$ ! false; echo $?
0
$ false || true; echo $?
0

Test with pipefail being disabled:

$ bash -c 'set +o pipefail -e; true | true | true; echo success'; echo $?
success
0
$ bash -c 'set +o pipefail -e; false | false | true; echo success'; echo $?
success
0
$ bash -c 'set +o pipefail -e; true | true | false; echo success'; echo $?
1

Test with pipefail being enabled:

$ bash -c 'set -o pipefail -e; true | false | true; echo success'; echo $?
1

How can I sort generic list DESC and ASC?

without linq, use Sort() and then Reverse() it.

Unable to find a @SpringBootConfiguration when doing a JpaTest

Make sure the test class is in a sub-package of your main spring boot class

Why do we always prefer using parameters in SQL statements?

Two years after my first go, I'm recidivating...

Why do we prefer parameters? SQL injection is obviously a big reason, but could it be that we're secretly longing to get back to SQL as a language. SQL in string literals is already a weird cultural practice, but at least you can copy and paste your request into management studio. SQL dynamically constructed with host language conditionals and control structures, when SQL has conditionals and control structures, is just level 0 barbarism. You have to run your app in debug, or with a trace, to see what SQL it generates.

Don't stop with just parameters. Go all the way and use QueryFirst (disclaimer: which I wrote). Your SQL lives in a .sql file. You edit it in the fabulous TSQL editor window, with syntax validation and Intellisense for your tables and columns. You can assign test data in the special comments section and click "play" to run your query right there in the window. Creating a parameter is as easy as putting "@myParam" in your SQL. Then, each time you save, QueryFirst generates the C# wrapper for your query. Your parameters pop up, strongly typed, as arguments to the Execute() methods. Your results are returned in an IEnumerable or List of strongly typed POCOs, the types generated from the actual schema returned by your query. If your query doesn't run, your app won't compile. If your db schema changes and your query runs but some columns disappear, the compile error points to the line in your code that tries to access the missing data. And there are numerous other advantages. Why would you want to access data any other way?

How can I convert an integer to a hexadecimal string in C?

To convert an integer to a string also involves char array or memory management.

To handle that part for such short arrays, code could use a compound literal, since C99, to create array space, on the fly. The string is valid until the end of the block.

#define UNS_HEX_STR_SIZE ((sizeof (unsigned)*CHAR_BIT + 3)/4 + 1)
//                         compound literal v--------------------------v
#define U2HS(x) unsigned_to_hex_string((x), (char[UNS_HEX_STR_SIZE]) {0}, UNS_HEX_STR_SIZE)

char *unsigned_to_hex_string(unsigned x, char *dest, size_t size) {
  snprintf(dest, size, "%X", x);
  return dest;
}

int main(void) {
  // 3 array are formed v               v        v
  printf("%s %s %s\n", U2HS(UINT_MAX), U2HS(0), U2HS(0x12345678));
  char *hs = U2HS(rand());
  puts(hs);
  // `hs` is valid until the end of the block
}

Output

FFFFFFFF 0 12345678
5851F42D

What is pluginManagement in Maven's pom.xml?

You use pluginManagement in a parent pom to configure it in case any child pom wants to use it, but not every child plugin wants to use it. An example can be that your super pom defines some options for the maven Javadoc plugin.

Not each child pom might want to use Javadoc, so you define those defaults in a pluginManagement section. The child pom that wants to use the Javadoc plugin, just defines a plugin section and will inherit the configuration from the pluginManagement definition in the parent pom.

Routing for custom ASP.NET MVC 404 Error page

Source

NotFoundMVC - Provides a user-friendly 404 page whenever a controller, action or route is not found in your ASP.NET MVC3 application. A view called NotFound is rendered instead of the default ASP.NET error page.

You can add this plugin via nuget using: Install-Package NotFoundMvc

NotFoundMvc automatically installs itself during web application start-up. It handles all the different ways a 404 HttpException is usually thrown by ASP.NET MVC. This includes a missing controller, action and route.

Step by Step Installation Guide :

1 - Right click on your Project and Select Manage Nuget Packages...

2 - Search for NotFoundMvc and install it. enter image description here

3 - Once the installation has be completed, two files will be added to your project. As shown in the screenshots below.

enter image description here

4 - Open the newly added NotFound.cshtml present at Views/Shared and modify it at your will. Now run the application and type in an incorrect url, and you will be greeted with a User friendly 404 page.

enter image description here

No more, will users get errors message like Server Error in '/' Application. The resource cannot be found.

Hope this helps :)

P.S : Kudos to Andrew Davey for making such an awesome plugin.

Replace negative values in an numpy array

You are halfway there. Try:

In [4]: a[a < 0] = 0

In [5]: a
Out[5]: array([1, 2, 3, 0, 5])

Spaces in URLs?

The information there is I think partially correct:

That's not true. An URL can use spaces. Nothing defines that a space is replaced with a + sign.

As you noted, an URL can NOT use spaces. The HTTP request would get screwed over. I'm not sure where the + is defined, though %20 is standard.

How to picture "for" loop in block representation of algorithm

The Algorithm for given flow chart :

enter image description here

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

Step :01

  • Start

Step :02 [Variable initialization]

  • Set counter: i<----K [Where K:Positive Number]

Step :03[Condition Check]

  • If condition True then Do your task, set i=i+N and go to Step :03 [Where N:Positive Number]
  • If condition False then go to Step :04

Step:04

  • Stop

How to speed up insertion performance in PostgreSQL

In addition to excellent Craig Ringer's post and depesz's blog post, if you would like to speed up your inserts through ODBC (psqlodbc) interface by using prepared-statement inserts inside a transaction, there are a few extra things you need to do to make it work fast:

  1. Set the level-of-rollback-on-errors to "Transaction" by specifying Protocol=-1 in the connection string. By default psqlodbc uses "Statement" level, which creates a SAVEPOINT for each statement rather than an entire transaction, making inserts slower.
  2. Use server-side prepared statements by specifying UseServerSidePrepare=1 in the connection string. Without this option the client sends the entire insert statement along with each row being inserted.
  3. Disable auto-commit on each statement using SQLSetConnectAttr(conn, SQL_ATTR_AUTOCOMMIT, reinterpret_cast<SQLPOINTER>(SQL_AUTOCOMMIT_OFF), 0);
  4. Once all rows have been inserted, commit the transaction using SQLEndTran(SQL_HANDLE_DBC, conn, SQL_COMMIT);. There is no need to explicitly open a transaction.

Unfortunately, psqlodbc "implements" SQLBulkOperations by issuing a series of unprepared insert statements, so that to achieve the fastest insert one needs to code up the above steps manually.

Random row selection in Pandas dataframe

Below line will randomly select n number of rows out of the total existing row numbers from the dataframe df without replacement.

df=df.take(np.random.permutation(len(df))[:n])

Ruby: How to iterate over a range, but in set increments?

See http://ruby-doc.org/core/classes/Range.html#M000695 for the full API.

Basically you use the step() method. For example:

(10..100).step(10) do |n|
    # n = 10
    # n = 20
    # n = 30
    # ...
end

PANIC: Cannot find AVD system path. Please define ANDROID_SDK_ROOT (in windows 10)

Open Android Studio and under the Tools you will find the AVD manager. Click on it and ensure that you have a valid virtual device with the SDK downloaded (click "download" in the Actions column if shown). Then ensure that the correct virtual device is selected on the toolbar.

How to select last two characters of a string

You can pass a negative index to .slice(). That will indicate an offset from the end of the set.

var member = "my name is Mate";

var last2 = member.slice(-2);

alert(last2); // "te"

How to hide image broken Icon using only CSS/HTML?

Since 2005, Mozilla browsers such as Firefox have supported the non-standard :-moz-broken CSS pseudo-class that can accomplish exactly this request:

_x000D_
_x000D_
td {_x000D_
  min-width:64px; /* for display purposes so you can see the empty cell */_x000D_
}_x000D_
_x000D_
img[alt]:-moz-broken {_x000D_
  display:none;_x000D_
}
_x000D_
<table border="1"><tr><td>_x000D_
  <img src="error">_x000D_
</td><td>_x000D_
  <img src="broken" alt="A broken image">_x000D_
</td><td>_x000D_
  <img src="https://images-na.ssl-images-amazon.com/images/I/218eLEn0fuL.png"_x000D_
       alt="A bird" style="width: 120px">_x000D_
</td></tr></table>
_x000D_
_x000D_
_x000D_

img[alt]::before also works in Firefox 64 (though once upon a time it was img[alt]::after so this is not reliable). I can't get either of those to work in Chrome 71.

Does an HTTP Status code of 0 have any meaning?

Know it's an old post. But these issues still exist.

Here are some of my findings on the subject, grossly explained.

"Status" 0 means one of 3 things, as per the XMLHttpRequest spec:

  • dns name resolution failed (that's for instance when network plug is pulled out)

  • server did not answer (a.k.a. unreachable or unresponding)

  • request was aborted because of a CORS issue (abortion is performed by the user-agent and follows a failing OPTIONS pre-flight).

If you want to go further, dive deep into the inners of XMLHttpRequest. I suggest reading the ready-state update sequence ([0,1,2,3,4] is the normal sequence, [0,1,4] corresponds to status 0, [0,1,2,4] means no content sent which may be an error or not). You may also want to attach listeners to the xhr (onreadystatechange, onabort, onerror, ontimeout) to figure out details.

From the spec (XHR Living spec):

const unsigned short UNSENT = 0;
const unsigned short OPENED = 1;
const unsigned short HEADERS_RECEIVED = 2;
const unsigned short LOADING = 3;
const unsigned short DONE = 4;

ASP.NET MVC: No parameterless constructor defined for this object

I had same problem but later found adding any new interface and corresponding class requires it to be registered under Initializable Module for dependency injection. In my case it was inside code as follows:

[InitializableModule]
[ModuleDependency(typeof(EPiServer.Web.InitializationModule))]
public class DependencyResolverInitialization : IConfigurableModule
{

    public void ConfigureContainer(ServiceConfigurationContext context)
    {
        context.Container.Configure(ConfigureContainer);
        var structureMapDependencyResolver = new StructureMapDependencyResolver(context.Container);
        DependencyResolver.SetResolver(structureMapDependencyResolver);
        GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpControllerActivator), structureMapDependencyResolver);
    }

    private void ConfigureContainer(ConfigurationExpression container)
    {
        container.For<IAppSettingService>().Use<AppSettingService>();
        container.For<ISiteSettingService>().Use<SiteSettingService>();
        container.For<IBreadcrumbBuilder>().Use<BreadcrumbBuilder>();
        container.For<IFilterContentService>().Use<FilterContentService>().Singleton();
        container.For<IDependecyFactoryResolver>().Use<DependecyFactoryResolver>();
        container.For<IUserService>().Use<UserService>();
        container.For<IGalleryVmFactory>().Use<GalleryVmFactory>();
        container.For<ILanguageService>().Use<LanguageService>();
        container.For<ILanguageBranchRepository>().Use<LanguageBranchRepository>();
        container.For<ICacheService>().Use<CacheService>(); 
        container.For<ISearchService>().Use<SearchService>();
        container.For<IReflectionService>().Use<ReflectionService>();
        container.For<ILocalizationService>().Use<LocalizationService>();
        container.For<IBookingFormService>().Use<BookingFormService>();
        container.For<IGeoService>().Use<GeoService>();
        container.For<ILocationService>().Use<LocationService>();
        RegisterEnterpriseAPIClient(container);
    }

   public void Initialize(InitializationEngine context)
    {
    }

    public void Uninitialize(InitializationEngine context)
    {
    }

    public void Preload(string[] parameters)
    {
    }
}

}

Plugin is too old, please update to a more recent version, or set ANDROID_DAILY_OVERRIDE environment variable to

the output is from NonFinalPluginExpiry.java

example 2.4.0-alpha7

https://github.com/c3ph3us/android-gradle-plugin-source-codes/blob/master/gradle-2.4.0-alpha7-sources/com/android/build/gradle/internal/NonFinalPluginExpiry.java

if someone want to use plugin and dont want to do a daily google shi..

either need to:

  1. recompile plugin
  2. replace "Plugin-Version" in manifest
  3. make a automation script to generate env var and set it daily

         MessageDigest crypt = MessageDigest.getInstance("SHA-1");
         crypt.reset();
         crypt.update(String.format(
                         "%1$s:%2$s:%3$s",
                            now.getYear(),
                            now.getMonthValue() -1,
                            now.getDayOfMonth())
                            .getBytes("utf8"));
        String overrideValue = new BigInteger(1, crypt.digest()).toString(16);
    

EXAMPLE APP IN JAVA (sources + JAR):

  1. FOR GENERATE ADO - for ALL OS'es WITH JVM
  2. SET ENV for LINUX

https://github.com/c3ph3us/ado

https://github.com/c3ph3us/ado/releases

example bash function to export env and start idea / or studio:

// eval export & start idea :) 
function sti() {
    export `java -jar AndroidDailyOverride.jar p`
    idea.sh
}

How to add leading zeros for for-loop in shell?

Use the following syntax:

$ for i in {01..05}; do echo "$i"; done
01
02
03
04
05

Disclaimer: Leading zeros only work in >=bash-4.

If you want to use printf, nothing prevents you from putting its result in a variable for further use:

$ foo=$(printf "%02d" 5)
$ echo "${foo}"
05

How can I check whether a option already exist in select by JQuery

This evaluates to true if it already exists:

$("#yourSelect option[value='yourValue']").length > 0;

Maven: How do I activate a profile from command line?

Activation by system properties can be done as follows

<activation>
    <property>
        <name>foo</name>
        <value>bar</value>
    </property>
</activation>

And run the mvn build with -D to set system property

mvn clean install -Dfoo=bar

This method also helps select profiles in transitive dependency of project artifacts.

Create hive table using "as select" or "like" and also specify delimiter

Let's say we have an external table called employee

hive> SHOW CREATE TABLE employee;
OK
CREATE EXTERNAL TABLE employee(
  id string,
  fname string,
  lname string, 
  salary double)
ROW FORMAT SERDE
  'org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe'
WITH SERDEPROPERTIES (
  'colelction.delim'=':',
  'field.delim'=',',
  'line.delim'='\n',
  'serialization.format'=',')
STORED AS INPUTFORMAT
  'org.apache.hadoop.mapred.TextInputFormat'
OUTPUTFORMAT
  'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'
LOCATION
  'maprfs:/user/hadoop/data/employee'
TBLPROPERTIES (
  'COLUMN_STATS_ACCURATE'='false',
  'numFiles'='0',
  'numRows'='-1',
  'rawDataSize'='-1',
  'totalSize'='0',
  'transient_lastDdlTime'='1487884795')
  1. To create a person table like employee

    CREATE TABLE person LIKE employee;

  2. To create a person external table like employee

    CREATE TABLE person LIKE employee LOCATION 'maprfs:/user/hadoop/data/person';

  3. then use DESC person; to see the newly created table schema.

Simple logical operators in Bash

A very portable version (even to legacy bourne shell):

if [ "$varA" = 1 -a \( "$varB" = "t1" -o "$varB" = "t2" \) ]
then    do-something
fi

This has the additional quality of running only one subprocess at most (which is the process [), whatever the shell flavor.

Replace = with -eq if variables contain numeric values, e.g.

  • 3 -eq 03 is true, but
  • 3 = 03 is false. (string comparison)

lists and arrays in VBA

You will have to change some of your data types but the basics of what you just posted could be converted to something similar to this given the data types I used may not be accurate.

Dim DateToday As String: DateToday = Format(Date, "yyyy/MM/dd")
Dim Computers As New Collection
Dim disabledList As New Collection
Dim compArray(1 To 1) As String

'Assign data to first item in array
compArray(1) = "asdf"

'Format = Item, Key
Computers.Add "ErrorState", "Computer Name"

'Prints "ErrorState"
Debug.Print Computers("Computer Name")

Collections cannot be sorted so if you need to sort data you will probably want to use an array.

Here is a link to the outlook developer reference. http://msdn.microsoft.com/en-us/library/office/ff866465%28v=office.14%29.aspx

Another great site to help you get started is http://www.cpearson.com/Excel/Topic.aspx

Moving everything over to VBA from VB.Net is not going to be simple since not all the data types are the same and you do not have the .Net framework. If you get stuck just post the code you're stuck converting and you will surely get some help!

Edit:

Sub ArrayExample()
    Dim subject As String
    Dim TestArray() As String
    Dim counter As Long

    subject = "Example"
    counter = Len(subject)

    ReDim TestArray(1 To counter) As String

    For counter = 1 To Len(subject)
        TestArray(counter) = Right(Left(subject, counter), 1)
    Next
End Sub

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

I think you are not asking the right question--

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

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

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

Reference — What does this symbol mean in PHP?

Question:

What does "&" mean here in PHP?

PHP "&" operator

Makes life more easier once we get used to it..(check example below carefully)

& usually checks bits that are set in both $a and $b are set.

have you even noticed how these calls works?

   error_reporting(E_ERROR | E_WARNING | E_PARSE);
    error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
    error_reporting(E_ALL & ~E_NOTICE);
    error_reporting(E_ALL);

So behind all above is game of bitwise operator and bits.

One usefull case of these is easy configurations like give below, so a single integer field can store thousands of combos for you.

Most people have already read the docs but didn't reliase the real world use case of these bitwise operators.

Example That you 'll love

<?php

class Config {

    // our constants must be 1,2,4,8,16,32,64 ....so on
    const TYPE_CAT=1;
    const TYPE_DOG=2;
    const TYPE_LION=4;
    const TYPE_RAT=8;
    const TYPE_BIRD=16;
    const TYPE_ALL=31;

    private $config;

    public function __construct($config){
        $this->config=$config;

        if($this->is(Config::TYPE_CAT)){
            echo 'cat ';
        }
        if($this->is(Config::TYPE_DOG)){
            echo 'dog ';
        }
        if($this->is(Config::TYPE_RAT)){
            echo 'rat ';
        }
        if($this->is(Config::TYPE_LION)){
            echo 'lion ';
        }
        if($this->is(Config::TYPE_BIRD)){
            echo 'bird ';
        }
        echo "\n";
    }

    private function is($value){
        return $this->config & $value;
    }
}

new Config(Config::TYPE_ALL);
// cat dog rat lion bird
new Config(Config::TYPE_BIRD);
//bird
new Config(Config::TYPE_BIRD | Config::TYPE_DOG);
//dog bird
new Config(Config::TYPE_ALL & ~Config::TYPE_DOG & ~Config::TYPE_CAT);
//rat lion bird

Push commits to another branch

you can do this easily

git status
git add .
git commit -m "any commit"
git pull origin (branch name, master in my case)
git push origin current branch(master):branch 2(development)(in which you want to push changes)

Can not deserialize instance of java.lang.String out of START_ARRAY token

The error is:

Can not deserialize instance of java.lang.String out of START_ARRAY token at [Source: line: 1, column: 1095] (through reference chain: JsonGen["platforms"])

In JSON, platforms look like this:

"platforms": [
    {
        "platform": "iphone"
    },
    {
        "platform": "ipad"
    },
    {
        "platform": "android_phone"
    },
    {
        "platform": "android_tablet"
    }
]

So try change your pojo to something like this:

private List platforms;

public List getPlatforms(){
    return this.platforms;
}

public void setPlatforms(List platforms){
    this.platforms = platforms;
}

EDIT: you will need change mobile_networks too. Will look like this:

private List mobile_networks;

public List getMobile_networks() {
    return mobile_networks;
}

public void setMobile_networks(List mobile_networks) {
    this.mobile_networks = mobile_networks;
}

What does #defining WIN32_LEAN_AND_MEAN exclude exactly?

Complementing the above answers and also "Parroting" from the Windows Dev Center documentation,

The Winsock2.h header file internally includes core elements from the Windows.h header file, so there is not usually an #include line for the Windows.h header file in Winsock applications. If an #include line is needed for the Windows.h header file, this should be preceded with the #define WIN32_LEAN_AND_MEAN macro. For historical reasons, the Windows.h header defaults to including the Winsock.h header file for Windows Sockets 1.1. The declarations in the Winsock.h header file will conflict with the declarations in the Winsock2.h header file required by Windows Sockets 2.0. The WIN32_LEAN_AND_MEAN macro prevents the Winsock.h from being included by the Windows.h header ..

How to insert spaces/tabs in text using HTML/CSS

If you're asking for tabs to align stuff in some lines, you can use <table>.

Putting each line in <tr> ... </tr>. And each element inside that line in <td> ... </td>. And of course you can always control the padding of each table cell to adjust the space between them.

This will make them aligned and they will look pretty nice :)

How do I get a string format of the current date time, in python?

If you don't care about formatting and you just need some quick date, you can use this:

import time
print(time.ctime())

How to get size of mysql database?

To get a result in MB:

SELECT
SUM(ROUND(((DATA_LENGTH + INDEX_LENGTH) / 1024 / 1024), 2)) AS "SIZE IN MB"
FROM INFORMATION_SCHEMA.TABLES
WHERE
TABLE_SCHEMA = "SCHEMA-NAME";

To get a result in GB:

SELECT
SUM(ROUND(((DATA_LENGTH + INDEX_LENGTH) / 1024 / 1024 / 1024), 2)) AS "SIZE IN GB"
FROM INFORMATION_SCHEMA.TABLES
WHERE
TABLE_SCHEMA = "SCHEMA-NAME";

Threading pool similar to the multiprocessing Pool?

If you don't mind executing other's code, here's mine:

Note: There is lot of extra code you may want to remove [added for better clarificaiton and demonstration how it works]

Note: Python naming conventions were used for method names and variable names instead of camelCase.

Working procedure:

  1. MultiThread class will initiate with no of instances of threads by sharing lock, work queue, exit flag and results.
  2. SingleThread will be started by MultiThread once it creates all instances.
  3. We can add works using MultiThread (It will take care of locking).
  4. SingleThreads will process work queue using a lock in middle.
  5. Once your work is done, you can destroy all threads with shared boolean value.
  6. Here, work can be anything. It can automatically import (uncomment import line) and process module using given arguments.
  7. Results will be added to results and we can get using get_results

Code:

import threading
import queue


class SingleThread(threading.Thread):
    def __init__(self, name, work_queue, lock, exit_flag, results):
        threading.Thread.__init__(self)
        self.name = name
        self.work_queue = work_queue
        self.lock = lock
        self.exit_flag = exit_flag
        self.results = results

    def run(self):
        # print("Coming %s with parameters %s", self.name, self.exit_flag)
        while not self.exit_flag:
            # print(self.exit_flag)
            self.lock.acquire()
            if not self.work_queue.empty():
                work = self.work_queue.get()
                module, operation, args, kwargs = work.module, work.operation, work.args, work.kwargs
                self.lock.release()
                print("Processing : " + operation + " with parameters " + str(args) + " and " + str(kwargs) + " by " + self.name + "\n")
                # module = __import__(module_name)
                result = str(getattr(module, operation)(*args, **kwargs))
                print("Result : " + result + " for operation " + operation + " and input " + str(args) + " " + str(kwargs))
                self.results.append(result)
            else:
                self.lock.release()
        # process_work_queue(self.work_queue)

class MultiThread:
    def __init__(self, no_of_threads):
        self.exit_flag = bool_instance()
        self.queue_lock = threading.Lock()
        self.threads = []
        self.work_queue = queue.Queue()
        self.results = []
        for index in range(0, no_of_threads):
            thread = SingleThread("Thread" + str(index+1), self.work_queue, self.queue_lock, self.exit_flag, self.results)
            thread.start()
            self.threads.append(thread)

    def add_work(self, work):
        self.queue_lock.acquire()
        self.work_queue._put(work)
        self.queue_lock.release()

    def destroy(self):
        self.exit_flag.value = True
        for thread in self.threads:
            thread.join()

    def get_results(self):
        return self.results


class Work:
    def __init__(self, module, operation, args, kwargs={}):
        self.module = module
        self.operation = operation
        self.args = args
        self.kwargs = kwargs


class SimpleOperations:
    def sum(self, *args):
        return sum([int(arg) for arg in args])

    @staticmethod
    def mul(a, b, c=0):
        return int(a) * int(b) + int(c)


class bool_instance:
    def __init__(self, value=False):
        self.value = value

    def __setattr__(self, key, value):
        if key != "value":
            raise AttributeError("Only value can be set!")
        if not isinstance(value, bool):
            raise AttributeError("Only True/False can be set!")
        self.__dict__[key] = value
        # super.__setattr__(key, bool(value))

    def __bool__(self):
        return self.value

if __name__ == "__main__":
    multi_thread = MultiThread(5)
    multi_thread.add_work(Work(SimpleOperations(), "mul", [2, 3], {"c":4}))
    while True:
        data_input = input()
        if data_input == "":
            pass
        elif data_input == "break":
            break
        else:
            work = data_input.split()
            multi_thread.add_work(Work(SimpleOperations(), work[0], work[1:], {}))
    multi_thread.destroy()
    print(multi_thread.get_results())

Disable validation of HTML5 form elements

I just wanted to add that using the novalidate attribute in your form will only prevent the browser from sending the form. The browser still evaluates the data and adds the :valid and :invalid pseudo classes.

I found this out because the valid and invalid pseudo classes are part of the HTML5 boilerplate stylesheet which I have been using. I just removed the entries in the CSS file that related to the pseudo classes. If anyone finds another solution please let me know.

How do I resolve the "java.net.BindException: Address already in use: JVM_Bind" error?

You can close every Java Process and start again your app:

taskkill /F /IM java.exe

start your app again...

How to include a PHP variable inside a MySQL statement

The rules of adding a PHP variable inside of any MySQL statement are plain and simple:

  1. Any variable that represents an SQL data literal, (or, to put it simply - an SQL string, or a number) MUST be added through a prepared statement. No exceptions.
  2. Any other query part, such as an SQL keyword, a table or a field name, or an operator - must be filtered through a white list.

So as your example only involves data literals, then all variables must be added through placeholders (also called parameters). To do so:

  • In your SQL statement, replace all variables with placeholders
  • prepare the resulting query
  • bind variables to placeholders
  • execute the query

And here is how to do it with all popular PHP database drivers:

Adding data literals using mysql ext

Such a driver doesn't exist.

Adding data literals using mysqli

$type = 'testing';
$reporter = "John O'Hara";
$query = "INSERT INTO contents (type, reporter, description) 
             VALUES(?, ?, 'whatever')";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("ss", $type, $reporter);
$stmt->execute();

The code is a bit complicated but the detailed explanation of all these operators can be found in my article, How to run an INSERT query using Mysqli, as well as a solution that eases the process dramatically.

For a SELECT query you will need to add just a call to get_result() method to get a familiar mysqli_result from which you can fetch the data the usual way:

$reporter = "John O'Hara";
$stmt = $mysqli->prepare("SELECT * FROM users WHERE name=?");
$stmt->bind_param("s", $reporter);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc(); // or while (...)

Adding data literals using PDO

$type = 'testing';
$reporter = "John O'Hara";
$query = "INSERT INTO contents (type, reporter, description) 
             VALUES(?, ?, 'whatever')";
$stmt = $pdo->prepare($query);
$stmt->execute([$type, $reporter]);

In PDO, we can have the bind and execute parts combined, which is very convenient. PDO also supports named placeholders which some find extremely convenient.

Adding keywords or identifiers

Sometimes we have to add a variable that represents another part of a query, such as a keyword or an identifier (a database, table or a field name). It's a rare case but it's better to be prepared.

In this case, your variable must be checked against a list of values explicitly written in your script. This is explained in my other article, Adding a field name in the ORDER BY clause based on the user's choice:

Unfortunately, PDO has no placeholder for identifiers (table and field names), therefore a developer must filter them out manually. Such a filter is often called a "white list" (where we only list allowed values) as opposed to a "black-list" where we list disallowed values.

So we have to explicitly list all possible variants in the PHP code and then choose from them.

Here is an example:

$orderby = $_GET['orderby'] ?: "name"; // set the default value
$allowed = ["name","price","qty"]; // the white list of allowed field names
$key = array_search($orderby, $allowed, true); // see if we have such a name
if ($key === false) { 
    throw new InvalidArgumentException("Invalid field name"); 
}

Exactly the same approach should be used for the direction,

$direction = $_GET['direction'] ?: "ASC";
$allowed = ["ASC","DESC"];
$key = array_search($direction, $allowed, true);
if ($key === false) { 
    throw new InvalidArgumentException("Invalid ORDER BY direction"); 
}

After such a code, both $direction and $orderby variables can be safely put in the SQL query, as they are either equal to one of the allowed variants or there will be an error thrown.

The last thing to mention about identifiers, they must be also formatted according to the particular database syntax. For MySQL it should be backtick characters around the identifier. So the final query string for our order by example would be

$query = "SELECT * FROM `table` ORDER BY `$orderby` $direction";

How to convert a Drawable to a Bitmap?

A Drawable can be drawn onto a Canvas, and a Canvas can be backed by a Bitmap:

(Updated to handle a quick conversion for BitmapDrawables and to ensure that the Bitmap created has a valid size)

public static Bitmap drawableToBitmap (Drawable drawable) {
    if (drawable instanceof BitmapDrawable) {
        return ((BitmapDrawable)drawable).getBitmap();
    }

    int width = drawable.getIntrinsicWidth();
    width = width > 0 ? width : 1;
    int height = drawable.getIntrinsicHeight();
    height = height > 0 ? height : 1;

    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap); 
    drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    drawable.draw(canvas);

    return bitmap;
}

How to read file using NPOI

Simple read example below:

using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;

//.....

private void button1_Click(object sender, EventArgs e)
{
    HSSFWorkbook hssfwb;
    using (FileStream file = new FileStream(@"c:\test.xls", FileMode.Open, FileAccess.Read))
    {
        hssfwb= new HSSFWorkbook(file);
    }

    ISheet sheet = hssfwb.GetSheet("Arkusz1");
    for (int row = 0; row <= sheet.LastRowNum; row++)
    {
        if (sheet.GetRow(row) != null) //null is when the row only contains empty cells 
        {
            MessageBox.Show(string.Format("Row {0} = {1}", row, sheet.GetRow(row).GetCell(0).StringCellValue));
        }
    }
}  

By the way: on NPOI website here in Download section there is example package - a pack of C# examples. Try it, if you haven't yet. :)

How to check if a String contains any letter from a to z?

Replace your for loop by this :

errorCounter = Regex.Matches(yourstring,@"[a-zA-Z]").Count;

Remember to use Regex class, you have to using System.Text.RegularExpressions; in your import

HTML form input tag name element array with JavaScript

To answer your questions in order:
1) There is no specific name for this. It's simply multiple elements with the same name (and in this case type as well). Name isn't unique, which is why id was invented (it's supposed to be unique).
2)

function getElementsByTagAndName(tag, name) {
    //you could pass in the starting element which would make this faster
    var elem = document.getElementsByTagName(tag);  
    var arr = new Array();
    var i = 0;
    var iarr = 0;
    var att;
    for(; i < elem.length; i++) {
        att = elem[i].getAttribute("name");
        if(att == name) {
            arr[iarr] = elem[i];
            iarr++;
        }
    }
    return arr;
}

Cannot find mysql.sock

I couldn't find mysql socket at all so reinstalled mysql server(all tables and phpmyadmin settings were preserved). Here are the commands:

1) Install

sudo apt-get install mysql-server

2) Follow terminal configuration steps

sudo mysql_secure_installation

3) Check status: (Should return "Active: active (running)")

systemctl status mysql.service

Where can I get Google developer key

It's the API key as listed under 'API Access', the 'Simple API Access' box.

flow 2 columns of text automatically with CSS

Automatically floating two columns next to eachother is not currently possible only with CSS/HTML. Two ways to achieve this:

Method 1: When there's no continous text, just lots of non-related paragraphs:

Float all paragraphs to the left, give them half the width of the containing element and if possible set a fixed height.

<div id="container">
  <p>This is paragraph 1. Lorem ipsum ... </p>
  <p>This is paragraph 2. Lorem ipsum ... </p>
  <p>This is paragraph 3. Lorem ipsum ... </p>
  <p>This is paragraph 4. Lorem ipsum ... </p>
  <p>This is paragraph 5. Lorem ipsum ... </p>
  <p>This is paragraph 6. Lorem ipsum ... </p>
</div>

#container { width: 600px; }
#container p { float: left; width: 300px; /* possibly also height: 300px; */ }

You can also insert clearer-divs between paragraphs to avoid having to use a fixed height. If you want two columns, add a clearer-div between two-and-two paragraphs. This will align the top of the two next paragraphs, making it look more tidy. Example:

<div id="container">
  <p>This is paragraph 1. Lorem ipsum ... </p>
  <p>This is paragraph 2. Lorem ipsum ... </p>
  <div class="clear"></div>
  <p>This is paragraph 3. Lorem ipsum ... </p>
  <p>This is paragraph 4. Lorem ipsum ... </p>
  <div class="clear"></div>
  <p>This is paragraph 5. Lorem ipsum ... </p>
  <p>This is paragraph 6. Lorem ipsum ... </p>
</div>

/* in addition to the above CSS */
.clear { clear: both; height: 0; }

Method 2: When the text is continous

More advanced, but it can be done.

<div id="container">
  <div class="contentColumn">
    <p>This is paragraph 1. Lorem ipsum ... </p>
    <p>This is paragraph 2. Lorem ipsum ... </p>
    <p>This is paragraph 3. Lorem ipsum ... </p>
  </div>
  <div class="contentColumn">
    <p>This is paragraph 4. Lorem ipsum ... </p>
    <p>This is paragraph 5. Lorem ipsum ... </p>
    <p>This is paragraph 6. Lorem ipsum ... </p>
  </div>
</div>

.contentColumn { width: 300px; float: left; }
#container { width: 600px; }

When it comes to the ease of use: none of these are really easy for a non-technical client. You might attempt to explain to him/her how to do this properly, and tell him/her why. Learning very basic HTML is not a bad idea anyways, if the client is going to be updating the web pages via a WYSIWYG-editor in the future.

Or you could try to implement some Javascript-solution that counts the total number of paragraphs, splits them in two and creates columns. This will also degrade gracefully for those who have JavaScript disabled. A third option is to have all this splitting-into-columns-action happen serverside if this is an option.

(Method 3: CSS3 Multi-column Layout Module)

You might read about the CSS3 way of doing it, but it's not really practical for a production website. Not yet, at least.

Why I cannot cout a string?

Use c_str() to convert the std::string to const char *.

cout << "String is  : " << text.c_str() << endl ;

How to get line count of a large file cheaply in Python?

the result of opening a file is an iterator, which can be converted to a sequence, which has a length:

with open(filename) as f:
   return len(list(f))

this is more concise than your explicit loop, and avoids the enumerate.

Calling virtual functions inside constructors

Calling a polymorphic function from a constructor is a recipe for disaster in most OO languages. Different languages will perform differently when this situation is encountered.

The basic problem is that in all languages the Base type(s) must be constructed previous to the Derived type. Now, the problem is what does it mean to call a polymorphic method from the constructor. What do you expect it to behave like? There are two approaches: call the method at the Base level (C++ style) or call the polymorphic method on an unconstructed object at the bottom of the hierarchy (Java way).

In C++ the Base class will build its version of the virtual method table prior to entering its own construction. At this point a call to the virtual method will end up calling the Base version of the method or producing a pure virtual method called in case it has no implementation at that level of the hierarchy. After the Base has been fully constructed, the compiler will start building the Derived class, and it will override the method pointers to point to the implementations in the next level of the hierarchy.

class Base {
public:
   Base() { f(); }
   virtual void f() { std::cout << "Base" << std::endl; } 
};
class Derived : public Base
{
public:
   Derived() : Base() {}
   virtual void f() { std::cout << "Derived" << std::endl; }
};
int main() {
   Derived d;
}
// outputs: "Base" as the vtable still points to Base::f() when Base::Base() is run

In Java, the compiler will build the virtual table equivalent at the very first step of construction, prior to entering the Base constructor or Derived constructor. The implications are different (and to my likings more dangerous). If the base class constructor calls a method that is overriden in the derived class the call will actually be handled at the derived level calling a method on an unconstructed object, yielding unexpected results. All attributes of the derived class that are initialized inside the constructor block are yet uninitialized, including 'final' attributes. Elements that have a default value defined at the class level will have that value.

public class Base {
   public Base() { polymorphic(); }
   public void polymorphic() { 
      System.out.println( "Base" );
   }
}
public class Derived extends Base
{
   final int x;
   public Derived( int value ) {
      x = value;
      polymorphic();
   }
   public void polymorphic() {
      System.out.println( "Derived: " + x ); 
   }
   public static void main( String args[] ) {
      Derived d = new Derived( 5 );
   }
}
// outputs: Derived 0
//          Derived 5
// ... so much for final attributes never changing :P

As you see, calling a polymorphic (virtual in C++ terminology) methods is a common source of errors. In C++, at least you have the guarantee that it will never call a method on a yet unconstructed object...

How can I prevent the TypeError: list indices must be integers, not tuple when copying a python list to a numpy array?

You probably do not need to be making lists and appending them to make your array. You can likely just do it all at once, which is faster since you can use numpy to do your loops instead of doing them yourself in pure python.

To answer your question, as others have said, you cannot access a nested list with two indices like you did. You can if you convert mean_data to an array before not after you try to slice it:

R = np.array(mean_data)[:,0]

instead of

R = np.array(mean_data[:,0])

But, assuming mean_data has a shape nx3, instead of

R = np.array(mean_data)[:,0]
P = np.array(mean_data)[:,1]
Z = np.array(mean_data)[:,2]

You can simply do

A = np.array(mean_data).mean(axis=0)

which averages over the 0th axis and returns a length-n array

But to my original point, I will make up some data to try to illustrate how you can do this without building any lists one item at a time:

java.lang.NoClassDefFoundError: org/hamcrest/SelfDescribing

A few steps you have to follow:

  • Right click on the project.
  • Choose Build Path & then from its menu choose Add Libraries.
  • Choose JUnit then click Next.
  • Choose JUnit4 then Finish.

This works for me...

how to open a page in new tab on button click in asp.net?

Take care to reset target, otherwise all other calls like Response.Redirect will open in a new tab, which might be not what you want.

<asp:LinkButton OnClientClick="openInNewTab();" .../>

In javaScript:

<script type="text/javascript">
    function openInNewTab() {
        window.document.forms[0].target = '_blank'; 
        setTimeout(function () { window.document.forms[0].target = ''; }, 0);
    }
</script>

How to lowercase a pandas dataframe string column if it has missing values?

copy your Dataframe column and simply apply

df=data['x']
newdf=df.str.lower()

Bound method error

There's no error here. You're printing a function, and that's what functions look like.

To actually call the function, you have to put parens after that. You're already doing that above. If you want to print the result of calling the function, just have the function return the value, and put the print there. For example:

print test.sort_word_list()

On the other hand, if you want the function to mutate the object's state, and then print the state some other way, that's fine too.

Now, your code seems to work in some places, but not others; let's look at why:

  • parser sets a variable called word_list, and you later print test.word_list, so that works.
  • sort_word_list sets a variable called sorted_word_list, and you later print test.sort_word_list—that is, the function, not the variable. So, you see the bound method. (Also, as Jon Clements points out, even if you fix this, you're going to print None, because that's what sort returns.)
  • num_words sets a variable called num_words, and you again print the function—but in this case, the variable has the same name as the function, meaning that you're actually replacing the function with its output, so it works. This is probably not what you want to do, however.

(There are cases where, at first glance, that seems like it might be a good idea—you only want to compute something once, and then access it over and over again without constantly recomputing that. But this isn't the way to do it. Either use a @property, or use a memoization decorator.)

How to solve maven 2.6 resource plugin dependency?

This issue is happening due to change of protocol from http to https for central repository. please refer following link for more details. https://support.sonatype.com/hc/en-us/articles/360041287334-Central-501-HTTPS-Required 

In order to fix the problem, copy following into your pom.ml file. This will set the repository url to use https.

<repositories>
        <repository>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
            <id>central</id>
            <name>Central Repository</name>
            <url>https://repo.maven.apache.org/maven2</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <releases>
                <updatePolicy>never</updatePolicy>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
            <id>central</id>
            <name>Central Repository</name>
            <url>https://repo.maven.apache.org/maven2</url>
        </pluginRepository>
    </pluginRepositories>

NumPy ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

The error message explains it pretty well:

ValueError: The truth value of an array with more than one element is ambiguous. 
Use a.any() or a.all()

What should bool(np.array([False, False, True])) return? You can make several plausible arguments:

(1) True, because bool(np.array(x)) should return the same as bool(list(x)), and non-empty lists are truelike;

(2) True, because at least one element is True;

(3) False, because not all elements are True;

and that's not even considering the complexity of the N-d case.

So, since "the truth value of an array with more than one element is ambiguous", you should use .any() or .all(), for example:

>>> v = np.array([1,2,3]) == np.array([1,2,4])
>>> v
array([ True,  True, False], dtype=bool)
>>> v.any()
True
>>> v.all()
False

and you might want to consider np.allclose if you're comparing arrays of floats:

>>> np.allclose(np.array([1,2,3+1e-8]), np.array([1,2,3]))
True

Copy entire directory contents to another directory?

This is my piece of Groovy code for that. Tested.

private static void copyLargeDir(File dirFrom, File dirTo){
    // creation the target dir
    if (!dirTo.exists()){
        dirTo.mkdir();
    }
    // copying the daughter files
    dirFrom.eachFile(FILES){File source ->
        File target = new File(dirTo,source.getName());
        target.bytes = source.bytes;
    }
    // copying the daughter dirs - recursion
    dirFrom.eachFile(DIRECTORIES){File source ->
        File target = new File(dirTo,source.getName());
        copyLargeDir(source, target)
    }
}

How do I fit an image (img) inside a div and keep the aspect ratio?

Unfortunately max-width + max-height do not fully cover my task... So I have found another solution:

To save the Image ratio while scaling you also can use object-fit CSS3 propperty.

Useful article: Control image aspect ratios with CSS3

img {
    width: 100%; /* or any custom size */
    height: 100%; 
    object-fit: contain;
}

Bad news: IE not supported (Can I Use)

pandas: best way to select all columns whose names start with X

In my case I needed a list of prefixes

colsToScale=["production", "test", "development"]
dc[dc.columns[dc.columns.str.startswith(tuple(colsToScale))]]

How do I modify the URL without reloading the page?

Any changes of the loction (either window.location or document.location) will cause a request on that new URL, if you’re not just changing the URL fragment. If you change the URL, you change the URL.

Use server-side URL rewrite techniques like Apache’s mod_rewrite if you don’t like the URLs you are currently using.

mongodb group values by multiple fields

TLDR Summary

In modern MongoDB releases you can brute force this with $slice just off the basic aggregation result. For "large" results, run parallel queries instead for each grouping ( a demonstration listing is at the end of the answer ), or wait for SERVER-9377 to resolve, which would allow a "limit" to the number of items to $push to an array.

db.books.aggregate([
    { "$group": {
        "_id": {
            "addr": "$addr",
            "book": "$book"
        },
        "bookCount": { "$sum": 1 }
    }},
    { "$group": {
        "_id": "$_id.addr",
        "books": { 
            "$push": { 
                "book": "$_id.book",
                "count": "$bookCount"
            },
        },
        "count": { "$sum": "$bookCount" }
    }},
    { "$sort": { "count": -1 } },
    { "$limit": 2 },
    { "$project": {
        "books": { "$slice": [ "$books", 2 ] },
        "count": 1
    }}
])

MongoDB 3.6 Preview

Still not resolving SERVER-9377, but in this release $lookup allows a new "non-correlated" option which takes an "pipeline" expression as an argument instead of the "localFields" and "foreignFields" options. This then allows a "self-join" with another pipeline expression, in which we can apply $limit in order to return the "top-n" results.

db.books.aggregate([
  { "$group": {
    "_id": "$addr",
    "count": { "$sum": 1 }
  }},
  { "$sort": { "count": -1 } },
  { "$limit": 2 },
  { "$lookup": {
    "from": "books",
    "let": {
      "addr": "$_id"
    },
    "pipeline": [
      { "$match": { 
        "$expr": { "$eq": [ "$addr", "$$addr"] }
      }},
      { "$group": {
        "_id": "$book",
        "count": { "$sum": 1 }
      }},
      { "$sort": { "count": -1  } },
      { "$limit": 2 }
    ],
    "as": "books"
  }}
])

The other addition here is of course the ability to interpolate the variable through $expr using $match to select the matching items in the "join", but the general premise is a "pipeline within a pipeline" where the inner content can be filtered by matches from the parent. Since they are both "pipelines" themselves we can $limit each result separately.

This would be the next best option to running parallel queries, and actually would be better if the $match were allowed and able to use an index in the "sub-pipeline" processing. So which is does not use the "limit to $push" as the referenced issue asks, it actually delivers something that should work better.


Original Content

You seem have stumbled upon the top "N" problem. In a way your problem is fairly easy to solve though not with the exact limiting that you ask for:

db.books.aggregate([
    { "$group": {
        "_id": {
            "addr": "$addr",
            "book": "$book"
        },
        "bookCount": { "$sum": 1 }
    }},
    { "$group": {
        "_id": "$_id.addr",
        "books": { 
            "$push": { 
                "book": "$_id.book",
                "count": "$bookCount"
            },
        },
        "count": { "$sum": "$bookCount" }
    }},
    { "$sort": { "count": -1 } },
    { "$limit": 2 }
])

Now that will give you a result like this:

{
    "result" : [
            {
                    "_id" : "address1",
                    "books" : [
                            {
                                    "book" : "book4",
                                    "count" : 1
                            },
                            {
                                    "book" : "book5",
                                    "count" : 1
                            },
                            {
                                    "book" : "book1",
                                    "count" : 3
                            }
                    ],
                    "count" : 5
            },
            {
                    "_id" : "address2",
                    "books" : [
                            {
                                    "book" : "book5",
                                    "count" : 1
                            },
                            {
                                    "book" : "book1",
                                    "count" : 2
                            }
                    ],
                    "count" : 3
            }
    ],
    "ok" : 1
}

So this differs from what you are asking in that, while we do get the top results for the address values the underlying "books" selection is not limited to only a required amount of results.

This turns out to be very difficult to do, but it can be done though the complexity just increases with the number of items you need to match. To keep it simple we can keep this at 2 matches at most:

db.books.aggregate([
    { "$group": {
        "_id": {
            "addr": "$addr",
            "book": "$book"
        },
        "bookCount": { "$sum": 1 }
    }},
    { "$group": {
        "_id": "$_id.addr",
        "books": { 
            "$push": { 
                "book": "$_id.book",
                "count": "$bookCount"
            },
        },
        "count": { "$sum": "$bookCount" }
    }},
    { "$sort": { "count": -1 } },
    { "$limit": 2 },
    { "$unwind": "$books" },
    { "$sort": { "count": 1, "books.count": -1 } },
    { "$group": {
        "_id": "$_id",
        "books": { "$push": "$books" },
        "count": { "$first": "$count" }
    }},
    { "$project": {
        "_id": {
            "_id": "$_id",
            "books": "$books",
            "count": "$count"
        },
        "newBooks": "$books"
    }},
    { "$unwind": "$newBooks" },
    { "$group": {
      "_id": "$_id",
      "num1": { "$first": "$newBooks" }
    }},
    { "$project": {
        "_id": "$_id",
        "newBooks": "$_id.books",
        "num1": 1
    }},
    { "$unwind": "$newBooks" },
    { "$project": {
        "_id": "$_id",
        "num1": 1,
        "newBooks": 1,
        "seen": { "$eq": [
            "$num1",
            "$newBooks"
        ]}
    }},
    { "$match": { "seen": false } },
    { "$group":{
        "_id": "$_id._id",
        "num1": { "$first": "$num1" },
        "num2": { "$first": "$newBooks" },
        "count": { "$first": "$_id.count" }
    }},
    { "$project": {
        "num1": 1,
        "num2": 1,
        "count": 1,
        "type": { "$cond": [ 1, [true,false],0 ] }
    }},
    { "$unwind": "$type" },
    { "$project": {
        "books": { "$cond": [
            "$type",
            "$num1",
            "$num2"
        ]},
        "count": 1
    }},
    { "$group": {
        "_id": "$_id",
        "count": { "$first": "$count" },
        "books": { "$push": "$books" }
    }},
    { "$sort": { "count": -1 } }
])

So that will actually give you the top 2 "books" from the top two "address" entries.

But for my money, stay with the first form and then simply "slice" the elements of the array that are returned to take the first "N" elements.


Demonstration Code

The demonstration code is appropriate for usage with current LTS versions of NodeJS from v8.x and v10.x releases. That's mostly for the async/await syntax, but there is nothing really within the general flow that has any such restriction, and adapts with little alteration to plain promises or even back to plain callback implementation.

index.js

const { MongoClient } = require('mongodb');
const fs = require('mz/fs');

const uri = 'mongodb://localhost:27017';

const log = data => console.log(JSON.stringify(data, undefined, 2));

(async function() {

  try {
    const client = await MongoClient.connect(uri);

    const db = client.db('bookDemo');
    const books = db.collection('books');

    let { version } = await db.command({ buildInfo: 1 });
    version = parseFloat(version.match(new RegExp(/(?:(?!-).)*/))[0]);

    // Clear and load books
    await books.deleteMany({});

    await books.insertMany(
      (await fs.readFile('books.json'))
        .toString()
        .replace(/\n$/,"")
        .split("\n")
        .map(JSON.parse)
    );

    if ( version >= 3.6 ) {

    // Non-correlated pipeline with limits
      let result = await books.aggregate([
        { "$group": {
          "_id": "$addr",
          "count": { "$sum": 1 }
        }},
        { "$sort": { "count": -1 } },
        { "$limit": 2 },
        { "$lookup": {
          "from": "books",
          "as": "books",
          "let": { "addr": "$_id" },
          "pipeline": [
            { "$match": {
              "$expr": { "$eq": [ "$addr", "$$addr" ] }
            }},
            { "$group": {
              "_id": "$book",
              "count": { "$sum": 1 },
            }},
            { "$sort": { "count": -1 } },
            { "$limit": 2 }
          ]
        }}
      ]).toArray();

      log({ result });
    }

    // Serial result procesing with parallel fetch

    // First get top addr items
    let topaddr = await books.aggregate([
      { "$group": {
        "_id": "$addr",
        "count": { "$sum": 1 }
      }},
      { "$sort": { "count": -1 } },
      { "$limit": 2 }
    ]).toArray();

    // Run parallel top books for each addr
    let topbooks = await Promise.all(
      topaddr.map(({ _id: addr }) =>
        books.aggregate([
          { "$match": { addr } },
          { "$group": {
            "_id": "$book",
            "count": { "$sum": 1 }
          }},
          { "$sort": { "count": -1 } },
          { "$limit": 2 }
        ]).toArray()
      )
    );

    // Merge output
    topaddr = topaddr.map((d,i) => ({ ...d, books: topbooks[i] }));
    log({ topaddr });

    client.close();

  } catch(e) {
    console.error(e)
  } finally {
    process.exit()
  }

})()

books.json

{ "addr": "address1",  "book": "book1"  }
{ "addr": "address2",  "book": "book1"  }
{ "addr": "address1",  "book": "book5"  }
{ "addr": "address3",  "book": "book9"  }
{ "addr": "address2",  "book": "book5"  }
{ "addr": "address2",  "book": "book1"  }
{ "addr": "address1",  "book": "book1"  }
{ "addr": "address15", "book": "book1"  }
{ "addr": "address9",  "book": "book99" }
{ "addr": "address90", "book": "book33" }
{ "addr": "address4",  "book": "book3"  }
{ "addr": "address5",  "book": "book1"  }
{ "addr": "address77", "book": "book11" }
{ "addr": "address1",  "book": "book1"  }

Please add a @Pipe/@Directive/@Component annotation. Error

I faced the same error when I used another class instead of component down the component decorator.

Component class must come just after the component decorator

  @Component({
 selector: 'app-smsgtrecon',
 templateUrl: './smsgtrecon.component.html',
 styleUrls: ['./smsgtrecon.component.css'],
 providers: [ChecklistDatabase]
 })


// THIS CAUSE ISSUE MOVE THIS UP TO COMPONENT DECORATOR
/**
* Node for to-do item
*/
 export class TodoItemNode {
 children: TodoItemNode[];
 item: string;
}


 export class SmsgtreconComponent implements OnInit {

After moving TodoItemNode to the top of component decorator it worked

Solution

// THIS CAUSE ISSUE MOVE THIS UP TO COMPONENT DECORATOR
/**
* Node for to-do item
*/
 export class TodoItemNode {
 children: TodoItemNode[];
 item: string;
}


@Component({
 selector: 'app-smsgtrecon',
 templateUrl: './smsgtrecon.component.html',
 styleUrls: ['./smsgtrecon.component.css'],
 providers: [ChecklistDatabase]
 })


 export class SmsgtreconComponent implements OnInit {

With block equivalent in C#?

About 3/4 down the page in the "Using Objects" section:

VB:

With hero 
  .Name = "SpamMan" 
  .PowerLevel = 3 
End With 

C#:

//No "With" construct
hero.Name = "SpamMan"; 
hero.PowerLevel = 3; 

How to cut first n and last n columns?

The first part of your question is easy. As already pointed out, cut accepts omission of either the starting or the ending index of a column range, interpreting this as meaning either “from the start to column n (inclusive)” or “from column n (inclusive) to the end,” respectively:

$ printf 'this:is:a:test' | cut -d: -f-2
this:is
$ printf 'this:is:a:test' | cut -d: -f3-
a:test

It also supports combining ranges. If you want, e.g., the first 3 and the last 2 columns in a row of 7 columns:

$ printf 'foo:bar:baz:qux:quz:quux:quuz' | cut -d: -f-3,6-
foo:bar:baz:quux:quuz

However, the second part of your question can be a bit trickier depending on what kind of input you’re expecting. If by “last n columns” you mean “last n columns (regardless of their indices in the overall row)” (i.e. because you don’t necessarily know how many columns you’re going to find in advance) then sadly this is not possible to accomplish using cut alone. In order to effectively use cut to pull out “the last n columns” in each line, the total number of columns present in each line must be known beforehand, and each line must be consistent in the number of columns it contains.

If you do not know how many “columns” may be present in each line (e.g. because you’re working with input that is not strictly tabular), then you’ll have to use something like awk instead. E.g., to use awk to pull out the last 2 “columns” (awk calls them fields, the number of which can vary per line) from each line of input:

$ printf '/a\n/a/b\n/a/b/c\n/a/b/c/d\n' | awk -F/ '{print $(NF-1) FS $(NF)}'
/a
a/b
b/c
c/d

Initializing data.frames()

I always just convert a matrix:

x <- as.data.frame(matrix(nrow = 100, ncol = 10))

HTML table with fixed headers and a fixed column?

Working example of link posted by pranav:

http://jsbin.com/nolanole/1/edit?html,js,output

FYI: Tested in IE 6, 7, & 8 (compatibility mode on or off), FF 3 & 3.5, Chrome 2. Not screen-reader-friendly (headers aren't part of content table).

EDIT 5/5/14: moved example to jsBin. This is old, but amazingly still works in current Chrome, IE, and Firefox (though IE and Firefox might require some adjustments to row heights).

Get elements by attribute when querySelectorAll is not available without using libraries?

Try this - I slightly changed the above answers:

var getAttributes = function(attribute) {
    var allElements = document.getElementsByTagName('*'),
        allElementsLen = allElements.length,
        curElement,
        i,
        results = [];

    for(i = 0; i < allElementsLen; i += 1) {
        curElement = allElements[i];

        if(curElement.getAttribute(attribute)) {
            results.push(curElement);
        }
    }

    return results;
};

Then,

getAttributes('data-foo');

Maven parent pom vs modules pom

In my opinion, to answer this question, you need to think in terms of project life cycle and version control. In other words, does the parent pom have its own life cycle i.e. can it be released separately of the other modules or not?

If the answer is yes (and this is the case of most projects that have been mentioned in the question or in comments), then the parent pom needs his own module from a VCS and from a Maven point of view and you'll end up with something like this at the VCS level:

root
|-- parent-pom
|   |-- branches
|   |-- tags
|   `-- trunk
|       `-- pom.xml
`-- projectA
    |-- branches
    |-- tags
    `-- trunk
        |-- module1
        |   `-- pom.xml
        |-- moduleN
        |   `-- pom.xml
        `-- pom.xml

This makes the checkout a bit painful and a common way to deal with that is to use svn:externals. For example, add a trunks directory:

root
|-- parent-pom
|   |-- branches
|   |-- tags
|   `-- trunk
|       `-- pom.xml
|-- projectA
|   |-- branches
|   |-- tags
|   `-- trunk
|       |-- module1
|       |   `-- pom.xml
|       |-- moduleN
|       |   `-- pom.xml
|       `-- pom.xml
`-- trunks

With the following externals definition:

parent-pom http://host/svn/parent-pom/trunk
projectA http://host/svn/projectA/trunk

A checkout of trunks would then result in the following local structure (pattern #2):

root/
  parent-pom/
    pom.xml
  projectA/

Optionally, you can even add a pom.xml in the trunks directory:

root
|-- parent-pom
|   |-- branches
|   |-- tags
|   `-- trunk
|       `-- pom.xml
|-- projectA
|   |-- branches
|   |-- tags
|   `-- trunk
|       |-- module1
|       |   `-- pom.xml
|       |-- moduleN
|       |   `-- pom.xml
|       `-- pom.xml
`-- trunks
    `-- pom.xml

This pom.xml is a kind of "fake" pom: it is never released, it doesn't contain a real version since this file is never released, it only contains a list of modules. With this file, a checkout would result in this structure (pattern #3):

root/
  parent-pom/
    pom.xml
  projectA/
  pom.xml

This "hack" allows to launch of a reactor build from the root after a checkout and make things even more handy. Actually, this is how I like to setup maven projects and a VCS repository for large builds: it just works, it scales well, it gives all the flexibility you may need.

If the answer is no (back to the initial question), then I think you can live with pattern #1 (do the simplest thing that could possibly work).

Now, about the bonus questions:

  • Where is the best place to define the various shared configuration as in source control, deployment directories, common plugins etc. (I'm assuming the parent but I've often been bitten by this and they've ended up in each project rather than a common one).

Honestly, I don't know how to not give a general answer here (like "use the level at which you think it makes sense to mutualize things"). And anyway, child poms can always override inherited settings.

  • How do the maven-release plugin, hudson and nexus deal with how you set up your multi-projects (possibly a giant question, it's more if anyone has been caught out when by how a multi-project build has been set up)?

The setup I use works well, nothing particular to mention.

Actually, I wonder how the maven-release-plugin deals with pattern #1 (especially with the <parent> section since you can't have SNAPSHOT dependencies at release time). This sounds like a chicken or egg problem but I just can't remember if it works and was too lazy to test it.

MySQL JOIN with LIMIT 1 on joined table

I like more another approach described in a similar question: https://stackoverflow.com/a/11885521/2215679

This approach is better especially in case if you need to show more than one field in SELECT. To avoid Error Code: 1241. Operand should contain 1 column(s) or double sub-select for each column.

For your situation the Query should looks like:

SELECT
 c.id,
 c.title,
 p.id AS product_id,
 p.title AS product_title
FROM categories AS c
JOIN products AS p ON
 p.id = (                                 --- the PRIMARY KEY
  SELECT p1.id FROM products AS p1
  WHERE c.id=p1.category_id
  ORDER BY p1.id LIMIT 1
 )

Pandas percentage of total with groupby

One-line solution:

df.join(
    df.groupby('state').agg(state_total=('sales', 'sum')),
    on='state'
).eval('sales / state_total')

This returns a Series of per-office ratios -- can be used on it's own or assigned to the original Dataframe.

DataTables warning: Requested unknown parameter '0' from the data source for row '0'

In my weird scenario, I had a different column that didn't always return a value in the 'render' function. return null solved my issue.

Vertically align text within input field of fixed-height without display: table or padding?

In my opinion, the answer on this page with the most votes is the best answer, but his math was wrong and I couldn't comment on it.

I needed a text input box to be exactly 40 pixels high including a 1 pixel border all the way around. Of course I wanted the text vertically aligned in the center in all browsers.

1 pixel border top
1 pixel border bottom
8 pixel top padding
8 pixel bottom padding
22 pixel font size

1 + 1 + 8 + 8 + 22 = 40 pixels exactly.

One thing to remember is that you must remove your css height property or those pixels will get added to your total above.

<input type="text" style="padding-top:8px; padding-bottom:8px; margin: 0; border: solid 1px #000000; font-size:22px;" />

This is working in Firefox, Chrome, IE 8, and Safari. I can only assume that if something simple like this is working in IE8, it should work similarly in 6, 7, and 9 but I have not tested it. Please let me know and I'll edit this post accordingly.

How can I remove punctuation from input text in Java?

You may try this:-

Scanner scan = new Scanner(System.in);
System.out.println("Type a sentence and press enter.");
String input = scan.nextLine();
String strippedInput = input.replaceAll("\\W", "");
System.out.println("Your string: " + strippedInput);

[^\w] matches a non-word character, so the above regular expression will match and remove all non-word characters.

Conditional WHERE clause with CASE statement in Oracle

You can write the where clause as:

where (case when (:stateCode = '') then (1)
            when (:stateCode != '') and (vw.state_cd in (:stateCode)) then 1
            else 0)
       end) = 1;

Alternatively, remove the case entirely:

where (:stateCode = '') or
      ((:stateCode != '') and vw.state_cd in (:stateCode));

Or, even better:

where (:stateCode = '') or vw.state_cd in (:stateCode)

split string in two on given index and return both parts

If code elegance ranks higher than the performance hit of regex, then

'1234567'.match(/^(.*)(.{3})/).slice(1).join(',')
=> "1234,567"

There's a lot of room to further modify the regex to be more precise.

If join() doesn't work then you might need to use map with a closure, at which point the other answers here may be less bytes and line noise.

Show div when radio button selected

I would handle it like so:

$(document).ready(function() {
   $('input[type="radio"]').click(function() {
       if($(this).attr('id') == 'watch-me') {
            $('#show-me').show();           
       }

       else {
            $('#show-me').hide();   
       }
   });
});

How to programmatically set the Image source

Try to assign the image that way instead:

imgFavorito.Source = new BitmapImage(new Uri(base.BaseUri, @"/Assets/favorited.png"));

Checking if a variable is defined?

Also, you can check if it's defined while in a string via interpolation, if you code:

puts "Is array1 defined and what type is it? #{defined?(@array1)}"

The system will tell you the type if it is defined. If it is not defined it will just return a warning saying the variable is not initialized.

Hope this helps! :)

Reactjs setState() with a dynamic key name?

In loop with .map work like this:

{
    dataForm.map(({ id, placeholder, type }) => {
        return <Input
            value={this.state.type}
            onChangeText={(text) => this.setState({ [type]: text })}
            placeholder={placeholder}
            key={id} />
    })
}

Note the [] in type parameter. Hope this helps :)

datetime dtypes in pandas read_csv

Why it does not work

There is no datetime dtype to be set for read_csv as csv files can only contain strings, integers and floats.

Setting a dtype to datetime will make pandas interpret the datetime as an object, meaning you will end up with a string.

Pandas way of solving this

The pandas.read_csv() function has a keyword argument called parse_dates

Using this you can on the fly convert strings, floats or integers into datetimes using the default date_parser (dateutil.parser.parser)

headers = ['col1', 'col2', 'col3', 'col4']
dtypes = {'col1': 'str', 'col2': 'str', 'col3': 'str', 'col4': 'float'}
parse_dates = ['col1', 'col2']
pd.read_csv(file, sep='\t', header=None, names=headers, dtype=dtypes, parse_dates=parse_dates)

This will cause pandas to read col1 and col2 as strings, which they most likely are ("2016-05-05" etc.) and after having read the string, the date_parser for each column will act upon that string and give back whatever that function returns.

Defining your own date parsing function:

The pandas.read_csv() function also has a keyword argument called date_parser

Setting this to a lambda function will make that particular function be used for the parsing of the dates.

GOTCHA WARNING

You have to give it the function, not the execution of the function, thus this is Correct

date_parser = pd.datetools.to_datetime

This is incorrect:

date_parser = pd.datetools.to_datetime()

Pandas 0.22 Update

pd.datetools.to_datetime has been relocated to date_parser = pd.to_datetime

Thanks @stackoverYC

How do I disable the resizable property of a textarea?

<textarea style="resize:none" rows="10" placeholder="Enter Text" ></textarea>

Circular (or cyclic) imports in Python

Module a.py :

import b
print("This is from module a")

Module b.py

import a
print("This is from module b")

Running "Module a" will output:

>>> 
'This is from module a'
'This is from module b'
'This is from module a'
>>> 

It output this 3 lines while it was supposed to output infinitival because of circular importing. What happens line by line while running"Module a" is listed here:

  1. The first line is import b. so it will visit module b
  2. The first line at module b is import a. so it will visit module a
  3. The first line at module a is import b but note that this line won't be executed again anymore, because every file in python execute an import line just for once, it does not matter where or when it is executed. so it will pass to the next line and print "This is from module a".
  4. After finish visiting whole module a from module b, we are still at module b. so the next line will print "This is from module b"
  5. Module b lines are executed completely. so we will go back to module a where we started module b.
  6. import b line have been executed already and won't be executed again. the next line will print "This is from module a" and program will be finished.

Display DateTime value in dd/mm/yyyy format in Asp.NET MVC

All you have to do is apply the format you want in the html helper call, ie.

@Html.TextBoxFor(m => m.RegistrationDate, "{0:dd/MM/yyyy}")

You don't need to provide the date format in the model class.

How to add a vertical Separator?

This is not exactly what author asked, but still, it is very simple and works exactly as expected.

Rectangle does the job:

<StackPanel Grid.Column="2" Orientation="Horizontal">
    <Button >Next</Button>
    <Button >Prev</Button>
    <Rectangle VerticalAlignment="Stretch" Width="1" Margin="2" Stroke="Black" />
    <Button>Filter all</Button>
</StackPanel>

In java how to get substring from a string till a character c?

How about using regex?

String firstWord = filename.replaceAll("\\..*","")

This replaces everything from the first dot to the end with "" (ie it clears it, leaving you with what you want)

Here's a test:

System.out.println("abc.def.hij".replaceAll("\\..*", "");

Output:

abc

Jquery array.push() not working

Your HTML should include quotes for attributes : http://jsfiddle.net/dKWnb/4/

Not required when using a HTML5 doctype - thanks @bazmegakapa

You create the array each time and add a value to it ... its working as expected ?

Moving the array outside of the live() function works fine :

var myarray = []; // more efficient than new Array()
$("#test").live("click",function() {
        myarray.push($("#drop").val());
        alert(myarray);
});

http://jsfiddle.net/dKWnb/5/

Also note that in later versions of jQuery v1.7 -> the live() method is deprecated and replaced by the on() method.

How to clone ArrayList and also clone its contents?

A nasty way is to do it with reflection. Something like this worked for me.

public static <T extends Cloneable> List<T> deepCloneList(List<T> original) {
    if (original == null || original.size() < 1) {
        return new ArrayList<>();
    }

    try {
        int originalSize = original.size();
        Method cloneMethod = original.get(0).getClass().getDeclaredMethod("clone");
        List<T> clonedList = new ArrayList<>();

        // noinspection ForLoopReplaceableByForEach
        for (int i = 0; i < originalSize; i++) {
            // noinspection unchecked
            clonedList.add((T) cloneMethod.invoke(original.get(i)));
        }
        return clonedList;
    } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
        System.err.println("Couldn't clone list due to " + e.getMessage());
        return new ArrayList<>();
    }
}

Finding element's position relative to the document

http://www.quirksmode.org/js/findpos.html Explains the best way to do it, all in all, you are on the right track you have to find the offsets and traverse up the tree of parents.

Coerce multiple columns to factors at once

If you have another objective of getting in values from the table then using them to be converted, you can try the following way

### pre processing
ind <- bigm.train[,lapply(.SD,is.character)]
ind <- names(ind[,.SD[T]])
### Convert multiple columns to factor
bigm.train[,(ind):=lapply(.SD,factor),.SDcols=ind]

This selects columns which are specifically character based and then converts them to factor.

Conversion failed when converting from a character string to uniqueidentifier

this fails:

 DECLARE @vPortalUID NVARCHAR(32)
 SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
 DECLARE @nPortalUID AS UNIQUEIDENTIFIER
 SET @nPortalUID = CAST(@vPortalUID AS uniqueidentifier)
 PRINT @nPortalUID

this works

 DECLARE @vPortalUID NVARCHAR(36)
 SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
 DECLARE @nPortalUID AS UNIQUEIDENTIFIER
 SET @nPortalUID = CAST(@vPortalUID AS UNIQUEIDENTIFIER)
 PRINT @nPortalUID

the difference is NVARCHAR(36), your input parameter is too small!