Programs & Examples On #Oscilloscope

Laboratory instrument to observe changes of electric signals on the screen.

Reading serial data in realtime in Python

You need to set the timeout to "None" when you open the serial port:

ser = serial.Serial(**bco_port**, timeout=None, baudrate=115000, xonxoff=False, rtscts=False, dsrdtr=False) 

This is a blocking command, so you are waiting until you receive data that has newline (\n or \r\n) at the end: line = ser.readline()

Once you have the data, it will return ASAP.

error: resource android:attr/fontVariationSettings not found

@All the issue is because of the latest major breaking changes in the google play service and firebase June 17, 2019 release.

If you are on Ionic or Cordova project. Please go through all the plugins where it has dependency google play service and firebase service with + mark

Example:

In my firebase cordova integration I had com.google.firebase:firebase-core:+ com.google.firebase:firebase-messaging:+ So the plus always downloading the latest release which was causing error. Change + with version number as per the March 15, 2019 release https://developers.google.com/android/guides/releases

Make sure to replace + symbols with actual version in build.gradle file of cordova library

I just discovered why all ASP.Net websites are slow, and I am trying to work out what to do about it

I started using the AngiesList.Redis.RedisSessionStateModule, which aside from using the (very fast) Redis server for storage (I'm using the windows port -- though there is also an MSOpenTech port), it does absolutely no locking on the session.

In my opinion, if your application is structured in a reasonable way, this is not a problem. If you actually need locked, consistent data as part of the session, you should specifically implement a lock/concurrency check on your own.

MS deciding that every ASP.NET session should be locked by default just to handle poor application design is a bad decision, in my opinion. Especially because it seems like most developers didn't/don't even realize sessions were locked, let alone that apps apparently need to be structured so you can do read-only session state as much as possible (opt-out, where possible).

How to use <md-icon> in Angular Material?

As the other answers didn't address my concern I decided to write my own answer.

The path given in the icon attribute of the md-icon directive is the URL of a .png or .svg file lying somewhere in your static file directory. So you have to put the right path of that file in the icon attribute. p.s put the file in the right directory so that your server could serve it.

Remember md-icon is not like bootstrap icons. Currently they are merely a directive that shows a .svg file.

Update

Angular material design has changed a lot since this question was posted.

Now there are several ways to use md-icon

The first way is to use SVG icons.

<md-icon md-svg-src = '<url_of_an_image_file>'></md-icon>

Example:

<md-icon md-svg-src = '/static/img/android.svg'></md-icon>

or

<md-icon md-svg-src = '{{ getMyIcon() }}'></md-icon>

:where getMyIcon is a method defined in $scope.

or <md-icon md-svg-icon="social:android"></md-icon>

to use this you have to the $mdIconProvider service to configure your application with svg iconsets.

angular.module('appSvgIconSets', ['ngMaterial'])  
  .controller('DemoCtrl', function($scope) {})  
  .config(function($mdIconProvider) {
    $mdIconProvider
      .iconSet('social', 'img/icons/sets/social-icons.svg', 24)
      .defaultIconSet('img/icons/sets/core-icons.svg', 24);    
  });

The second way is to use font icons.

<md-icon md-font-icon="android" alt="android"></md-icon>

<md-icon md-font-icon="fa-magic" class="fa" alt="magic wand"></md-icon>

prior to doing this you have to load the font library like this..

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

or use font icons with ligatures

<md-icon md-font-library="material-icons">face</md-icon>

<md-icon md-font-library="material-icons">#xE87C;</md-icon>

<md-icon md-font-library="material-icons" class="md-light md-48">face</md-icon>

For further details check our

Angular Material mdIcon Directive documentation

$mdIcon Service Documentation

$mdIconProvider Service Documentation

running php script (php function) in linux bash

php test.php

should do it, or

php -f test.php

to be explicit.

Get the IP Address of local computer

Winsock specific:

// Init WinSock
WSADATA wsa_Data;
int wsa_ReturnCode = WSAStartup(0x101,&wsa_Data);

// Get the local hostname
char szHostName[255];
gethostname(szHostName, 255);
struct hostent *host_entry;
host_entry=gethostbyname(szHostName);
char * szLocalIP;
szLocalIP = inet_ntoa (*(struct in_addr *)*host_entry->h_addr_list);
WSACleanup();

How do I add space between items in an ASP.NET RadioButtonList

<asp:RadioButtonList ID="rbn" runat="server" RepeatLayout="Table" RepeatColumns="2"
                        Width="100%" >
                        <asp:ListItem Text="1"></asp:ListItem>
                        <asp:ListItem Text="2"></asp:ListItem>
                        <asp:ListItem Text="3"></asp:ListItem>
                        <asp:ListItem Text="4"></asp:ListItem>
                    </asp:RadioButtonList>

Cannot import scipy.misc.imread

If you have Pillow installed with scipy and it is still giving you error then check your scipy version because it has been removed from scipy since 1.3.0rc1.

rather install scipy 1.1.0 by :

pip install scipy==1.1.0

check https://github.com/scipy/scipy/issues/6212


The method imread in scipy.misc requires the forked package of PIL named Pillow. If you are having problem installing the right version of PIL try using imread in other packages:

from matplotlib.pyplot import imread
im = imread(image.png)

To read jpg images without PIL use:

import cv2 as cv
im = cv.imread(image.jpg)

You can try from scipy.misc.pilutil import imread instead of from scipy.misc import imread

Please check the GitHub page : https://github.com/amueller/mglearn/issues/2 for more details.

querySelector, wildcard element match?

I was messing/musing on one-liners involving querySelector() & ended up here, & have a possible answer to the OP question using tag names & querySelector(), with credits to @JaredMcAteer for answering MY question, aka have RegEx-like matches with querySelector() in vanilla Javascript

Hoping the following will be useful & fit the OP's needs or everyone else's:

// basically, of before:
var youtubeDiv = document.querySelector('iframe[src="http://www.youtube.com/embed/Jk5lTqQzoKA"]')

// after     
var youtubeDiv = document.querySelector('iframe[src^="http://www.youtube.com"]');
// or even, for my needs
var youtubeDiv = document.querySelector('iframe[src*="youtube"]');

Then, we can, for example, get the src stuff, etc ...

console.log(youtubeDiv.src);
//> "http://www.youtube.com/embed/Jk5lTqQzoKA"
console.debug(youtubeDiv);
//> (...)

Secure Web Services: REST over HTTPS vs SOAP + WS-Security. Which is better?

If your RESTFul call sends XML Messages back and forth embedded in the Html Body of the HTTP request, you should be able to have all the benefits of WS-Security such as XML encryption, Cerificates, etc in your XML messages while using whatever security features are available from http such as SSL/TLS encryption.

I get exception when using Thread.sleep(x) or wait()

Put your Thread.sleep in a try catch block

try {
    //thread to sleep for the specified number of milliseconds
    Thread.sleep(100);
} catch ( java.lang.InterruptedException ie) {
    System.out.println(ie);
}

How to rename a pane in tmux?

For those who want to easily rename their panes, this is what I have in my .tmux.conf

set -g default-command '                      \
function renamePane () {                      \
  read -p "Enter Pane Name: " pane_name;      \
  printf "\033]2;%s\033\\r:r" "${pane_name}"; \
};                                            \
export -f renamePane;                         \
bash -i'
set -g pane-border-status top
set -g pane-border-format "#{pane_index} #T #{pane_current_command}"
bind-key -T prefix R send-keys "renamePane" C-m

Panes are automatically named with their index, machine name and current command. To change the machine name you can run <C-b>R which will prompt you to enter a new name.

*Pane renaming only works when you are in a shell.

What is a CSRF token? What is its importance and how does it work?

The root of it all is to make sure that the requests are coming from the actual users of the site. A csrf token is generated for the forms and Must be tied to the user's sessions. It is used to send requests to the server, in which the token validates them. This is one way of protecting against csrf, another would be checking the referrer header.

What's the use of ob_start() in php?

You have it backwards. ob_start does not buffer the headers, it buffers the content. Using ob_start allows you to keep the content in a server-side buffer until you are ready to display it.

This is commonly used to so that pages can send headers 'after' they've 'sent' some content already (ie, deciding to redirect half way through rendering a page).

Call another rest api from my server in Spring-Boot

Does Retrofit have any method to achieve this? If not, how I can do that?

YES

Retrofit is type-safe REST client for Android and Java. Retrofit turns your HTTP API into a Java interface.

For more information refer the following link

https://howtodoinjava.com/retrofit2/retrofit2-beginner-tutorial

php foreach with multidimensional array

Holla/Hello, I got it! You can easily get the file name,tmp_name,file_size etc.So I will show you how to get file name with a line of code.

for ($i = 0 ; $i < count($files['name']); $i++) {
    echo $files['name'][$i].'<br/>';
}

It is tested on my PC.

how to add picasso library in android studio

Add this to your dependencies in build.gradle:

enter image description here

dependencies {
 implementation 'com.squareup.picasso:picasso:2.71828'
  ...

The latest version can be found here

Make sure you are connected to the Internet. When you sync Gradle, all related files will be added to your project

Take a look at your libraries folder, the library you just added should be in there.

enter image description here

Using union and order by clause in mysql

I tried adding the order by to each of the queries prior to unioning like

(select * from table where distance=0 order by add_date) 
union 
(select * from table where distance>0 and distance<=5 order by add_date)

but it didn't seem to work. It didn't actually do the ordering within the rows from each select.

I think you will need to keep the order by on the outside and add the columns in the where clause to the order by, something like

(select * from table where distance=0) 
union 
(select * from table where distance>0 and distance<=5) 
order by distance, add_date

This may be a little tricky, since you want to group by ranges, but I think it should be doable.

Print all key/value pairs in a Java ConcurrentHashMap

The HashMap has forEach as part of its structure. You can use that with a lambda expression to print out the contents in a one liner such as:

map.forEach((k,v)-> System.out.println(k+", "+v));

or

map.forEach((k,v)-> System.out.println("key: "+k+", value: "+v));

HTTP Error 404.3-Not Found in IIS 7.5

I was having trouble accessing wcf service hosted locally in IIS. Running aspnet_regiis.exe -i wasn't working.

However, I fortunately came across the following:

Rahul's blog

which informs that servicemodelreg also needs to be run:

Run Visual Studio 2008 Command Prompt as “Administrator”. Navigate to C:\Windows\Microsoft.NET\Framework\v3.0\Windows Communication Foundation. Run this command servicemodelreg –i.

Adding elements to object

For anyone still looking for a solution, I think that the objects should have been stored in an array like...

var element = {}, cart = [];
element.id = id;
element.quantity = quantity;
cart.push(element);

Then when you want to use an element as an object you can do this...

var element = cart.find(function (el) { return el.id === "id_that_we_want";});

Put a variable at "id_that_we_want" and give it the id of the element that we want from our array. An "elemnt" object is returned. Of course we dont have to us id to find the object. We could use any other property to do the find.

How to set default value for column of new created table from select statement in 11g

The reason is that CTAS (Create table as select) does not copy any metadata from the source to the target table, namely

  • no primary key
  • no foreign keys
  • no grants
  • no indexes
  • ...

To achieve what you want, I'd either

  • use dbms_metadata.get_ddl to get the complete table structure, replace the table name with the new name, execute this statement, and do an INSERT afterward to copy the data
  • or keep using CTAS, extract the not null constraints for the source table from user_constraints and add them to the target table afterwards

How can I make all images of different height and width the same via CSS?

.article-img img{ 
    height: 100%;
    width: 100%;
    position: relative;
    vertical-align: middle;
    border-style: none;
 }

You will make images size same as div and you can use bootstrap grid to manipulate div size accordingly

Meaning of *& and **& in C++

An int* is a pointer to an int, so int*& must be a reference to a pointer to an int. Similarly, int** is a pointer to a pointer to an int, so int**& must be a reference to a pointer to a pointer to an int.

Find all zero-byte files in directory and subdirectories

To print the names of all files in and below $dir of size 0:

find "$dir" -size 0

Note that not all implementations of find will produce output by default, so you may need to do:

find "$dir" -size 0 -print

Two comments on the final loop in the question:

Rather than iterating over every other word in a string and seeing if the alternate values are zero, you can partially eliminate the issue you're having with whitespace by iterating over lines. eg:

printf '1 f1\n0 f 2\n10 f3\n' | while read size path; do
    test "$size" -eq 0 && echo "$path"; done

Note that this will fail in your case if any of the paths output by ls contain newlines, and this reinforces 2 points: don't parse ls, and have a sane naming policy that doesn't allow whitespace in paths.

Secondly, to output the data from the loop, there is no need to store the output in a variable just to echo it. If you simply let the loop write its output to stdout, you accomplish the same thing but avoid storing it.

What is the standard naming convention for html/css ids and classes?

There is no agreed upon naming convention for HTML and CSS. But you could structure your nomenclature around object design. More specifically what I call Ownership and Relationship.

Ownership

Keywords that describe the object, could be separated by hyphens.

car-new-turned-right

Keywords that describe the object can also fall into four categories (which should be ordered from left to right): Object, Object-Descriptor, Action, and Action-Descriptor.

car - a noun, and an object
new - an adjective, and an object-descriptor that describes the object in more detail
turned - a verb, and an action that belongs to the object
right - an adjective, and an action-descriptor that describes the action in more detail

Note: verbs (actions) should be in past-tense (turned, did, ran, etc).

Relationship

Objects can also have relationships like parent and child. The Action and Action-Descriptor belongs to the parent object, they don't belong to the child object. For relationships between objects you could use an underscore.

car-new-turned-right_wheel-left-turned-left

  • car-new-turned-right (follows the ownership rule)
  • wheel-left-turned-left (follows the ownership rule)
  • car-new-turned-right_wheel-left-turned-left (follows the relationship rule)

Final notes:

  • Because CSS is case-insensitive, it's better to write all names in lower-case (or upper-case); avoid camel-case or pascal-case as they can lead to ambiguous names.
  • Know when to use a class and when to use an id. It's not just about an id being used once on the web page. Most of the time, you want to use a class and not an id. Web components like (buttons, forms, panels, ...etc) should always use a class. Id's can easily lead to naming conflicts, and should be used sparingly for namespacing your markup. The above concepts of ownership and relationship apply to naming both classes and ids, and will help you avoid naming conflicts.
  • If you don't like my CSS naming convention, there are several others as well: Structural naming convention, Presentational naming convention, Semantic naming convention, BEM naming convention, OCSS naming convention, etc.

Fixing Segmentation faults in C++

Before the problem arises, try to avoid it as much as possible:

  • Compile and run your code as often as you can. It will be easier to locate the faulty part.
  • Try to encapsulate low-level / error prone routines so that you rarely have to work directly with memory (pay attention to the modelization of your program)
  • Maintain a test-suite. Having an overview of what is currently working, what is no more working etc, will help you to figure out where the problem is (Boost test is a possible solution, I don't use it myself but the documentation can help to understand what kind of information must be displayed).

Use appropriate tools for debugging. On Unix:

  • GDB can tell you where you program crash and will let you see in what context.
  • Valgrind will help you to detect many memory-related errors.
  • With GCC you can also use mudflap With GCC, Clang and since October experimentally MSVC you can use Address/Memory Sanitizer. It can detect some errors that Valgrind doesn't and the performance loss is lighter. It is used by compiling with the-fsanitize=address flag.

Finally I would recommend the usual things. The more your program is readable, maintainable, clear and neat, the easiest it will be to debug.

Cannot create JDBC driver of class ' ' for connect URL 'null' : I do not understand this exception

Did you try to specify resource only in context.xml

<Resource name="jdbc/PollDatasource" auth="Container" type="javax.sql.DataSource"
driverClassName="org.apache.derby.jdbc.EmbeddedDriver"
url="jdbc:derby://localhost:1527/poll_database;create=true"
username="suhail" password="suhail"
maxActive="20" maxIdle="10" maxWait="-1" />

and remove <resource-ref> section from web.xml?

In one project I've seen configuration without <resource-ref> section in web.xml and it worked.

It's an educated guess, but I think <resource-ref> declaration of JNDI resource named jdbc/PollDatasource in web.xml may override declaration of resource with same name in context.xml and the declaration in web.xml is missing both driverClassName and url hence the NPEs for that properties.

get all keys set in memcached

If you have PHP & PHP-memcached installed, you can run

$ php -r '$c = new Memcached(); $c->addServer("localhost", 11211); var_dump( $c->getAllKeys() );'

Uncaught Error: SECURITY_ERR: DOM Exception 18 when I try to set a cookie

Faced with the same situation playing with Javascript . Unfortunately Chrome doesn't allow to access javascript workers stored in a local file.

One kind of workaround below using a local storage is to running Chrome with --allow-file-access-from-files (with s at the end), but only one instance of Chrome is allowed, which is not too convenient for me. For this reason i'm using Chrome Canary, with file access allowed.

BTW in Firefox there is no such an issue.

When to use DataContract and DataMember attributes?

DataMember attribute is not mandatory to add to serialize data. When DataMember attribute is not added, old XMLSerializer serializes the data. Adding a DataMember provides useful properties like order, name, isrequired which cannot be used otherwise.

Syntax behind sorted(key=lambda: ...)

I think all of the answers here cover the core of what the lambda function does in the context of sorted() quite nicely, however I still feel like a description that leads to an intuitive understanding is lacking, so here is my two cents.

For the sake of completeness, I'll state the obvious up front: sorted() returns a list of sorted elements and if we want to sort in a particular way or if we want to sort a complex list of elements (e.g. nested lists or a list of tuples) we can invoke the key argument.

For me, the intuitive understanding of the key argument, why it has to be callable, and the use of lambda as the (anonymous) callable function to accomplish this comes in two parts.

  1. Using lamba ultimately means you don't have to write (define) an entire function, like the one sblom provided an example of. Lambda functions are created, used, and immediately destroyed - so they don't funk up your code with more code that will only ever be used once. This, as I understand it, is the core utility of the lambda function and its applications for such roles are broad. Its syntax is purely by convention, which is in essence the nature of programmatic syntax in general. Learn the syntax and be done with it.

Lambda syntax is as follows:

lambda input_variable(s): tasty one liner

e.g.

In [1]: f00 = lambda x: x/2

In [2]: f00(10)
Out[2]: 5.0

In [3]: (lambda x: x/2)(10)
Out[3]: 5.0

In [4]: (lambda x, y: x / y)(10, 2)
Out[4]: 5.0

In [5]: (lambda: 'amazing lambda')() # func with no args!
Out[5]: 'amazing lambda'
  1. The idea behind the key argument is that it should take in a set of instructions that will essentially point the 'sorted()' function at those list elements which should used to sort by. When it says key=, what it really means is: As I iterate through the list one element at a time (i.e. for e in list), I'm going to pass the current element to the function I provide in the key argument and use that to create a transformed list which will inform me on the order of final sorted list.

Check it out:

mylist = [3,6,3,2,4,8,23]
sorted(mylist, key=WhatToSortBy)

Base example:

sorted(mylist)

[2, 3, 3, 4, 6, 8, 23] # all numbers are in order from small to large.

Example 1:

mylist = [3,6,3,2,4,8,23]
sorted(mylist, key=lambda x: x%2==0)

[3, 3, 23, 6, 2, 4, 8] # Does this sorted result make intuitive sense to you?

Notice that my lambda function told sorted to check if (e) was even or odd before sorting.

BUT WAIT! You may (or perhaps should) be wondering two things - first, why are my odds coming before my evens (since my key value seems to be telling my sorted function to prioritize evens by using the mod operator in x%2==0). Second, why are my evens out of order? 2 comes before 6 right? By analyzing this result, we'll learn something deeper about how the sorted() 'key' argument works, especially in conjunction with the anonymous lambda function.

Firstly, you'll notice that while the odds come before the evens, the evens themselves are not sorted. Why is this?? Lets read the docs:

Key Functions Starting with Python 2.4, both list.sort() and sorted() added a key parameter to specify a function to be called on each list element prior to making comparisons.

We have to do a little bit of reading between the lines here, but what this tells us is that the sort function is only called once, and if we specify the key argument, then we sort by the value that key function points us to.

So what does the example using a modulo return? A boolean value: True == 1, False == 0. So how does sorted deal with this key? It basically transforms the original list to a sequence of 1s and 0s.

[3,6,3,2,4,8,23] becomes [0,1,0,1,1,1,0]

Now we're getting somewhere. What do you get when you sort the transformed list?

[0,0,0,1,1,1,1]

Okay, so now we know why the odds come before the evens. But the next question is: Why does the 6 still come before the 2 in my final list? Well that's easy - its because sorting only happens once! i.e. Those 1s still represent the original list values, which are in their original positions relative to each other. Since sorting only happens once, and we don't call any kind of sort function to order the original even values from low to high, those values remain in their original order relative to one another.

The final question is then this: How do I think conceptually about how the order of my boolean values get transformed back in to the original values when I print out the final sorted list?

Sorted() is a built-in method that (fun fact) uses a hybrid sorting algorithm called Timsort that combines aspects of merge sort and insertion sort. It seems clear to me that when you call it, there is a mechanic that holds these values in memory and bundles them with their boolean identity (mask) determined by (...!) the lambda function. The order is determined by their boolean identity calculated from the lambda function, but keep in mind that these sublists (of one's and zeros) are not themselves sorted by their original values. Hence, the final list, while organized by Odds and Evens, is not sorted by sublist (the evens in this case are out of order). The fact that the odds are ordered is because they were already in order by coincidence in the original list. The takeaway from all this is that when lambda does that transformation, the original order of the sublists are retained.

So how does this all relate back to the original question, and more importantly, our intuition on how we should implement sorted() with its key argument and lambda?

That lambda function can be thought of as a pointer that points to the values we need to sort by, whether its a pointer mapping a value to its boolean transformed by the lambda function, or if its a particular element in a nested list, tuple, dict, etc., again determined by the lambda function.

Lets try and predict what happens when I run the following code.

mylist = [(3, 5, 8), (6, 2, 8), ( 2, 9, 4), (6, 8, 5)]
sorted(mylist, key=lambda x: x[1])

My sorted call obviously says, "Please sort this list". The key argument makes that a little more specific by saying, for each element (x) in mylist, return index 1 of that element, then sort all of the elements of the original list 'mylist' by the sorted order of the list calculated by the lambda function. Since we have a list of tuples, we can return an indexed element from that tuple. So we get:

[(6, 2, 8), (3, 5, 8), (6, 8, 5), (2, 9, 4)]

Run that code, and you'll find that this is the order. Try indexing a list of integers and you'll find that the code breaks.

This was a long winded explanation, but I hope this helps to 'sort' your intuition on the use of lambda functions as the key argument in sorted() and beyond.

Access multiple viewchildren using @viewchild

Use the @ViewChildren decorator combined with QueryList. Both of these are from "@angular/core"

@ViewChildren(CustomComponent) customComponentChildren: QueryList<CustomComponent>;

Doing something with each child looks like: this.customComponentChildren.forEach((child) => { child.stuff = 'y' })

There is further documentation to be had at angular.io, specifically: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#sts=Parent%20calls%20a%20ViewChild

Can I have multiple background images using CSS?

Yes, it is possible, and has been implemented by popular usability testing website Silverback. If you look through the source code you can see that the background is made up of several images, placed on top of each other.

Here is the article demonstrating how to do the effect can be found on Vitamin. A similar concept for wrapping these 'onion skin' layers can be found on A List Apart.

Is it possible to read the value of a annotation in java?

Elaborating to the answer of @Cephalopod, if you wanted all column names in a list you could use this oneliner:

List<String> columns = 
        Arrays.asList(MyClass.class.getFields())
              .stream()
              .filter(f -> f.getAnnotation(Column.class)!=null)
              .map(f -> f.getAnnotation(Column.class).columnName())
              .collect(Collectors.toList());

Including a groovy script in another groovy

For late-comers, it appears that groovy now support the :load file-path command which simply redirects input from the given file, so it is now trivial to include library scripts.

It works as input to the groovysh & as a line in a loaded file:
groovy:000> :load file1.groovy

file1.groovy can contain:
:load path/to/another/file invoke_fn_from_file();

How do I create a timeline chart which shows multiple events? Eg. Metallica Band members timeline on wiki

As mentioned in the earlier comment, stacked bar chart does the trick, though the data needs to be setup differently.(See image below)

Duration column = End - Start

  1. Once done, plot your stacked bar chart using the entire data.
  2. Mark start and end range to no fill.
  3. Right click on the X Axis and change Axis options manually. (This did cause me some issues, till I realized I couldn't manipulate them to enter dates, :) yeah I am newbie, excel masters! :))

enter image description here

find files by extension, *.html under a folder in nodejs

You can use OS help for this. Here is a cross-platform solution:

1. The bellow function uses ls and dir and does not search recursively but it has relative paths

var exec = require('child_process').exec;
function findFiles(folder,extension,cb){
    var command = "";
    if(/^win/.test(process.platform)){
        command = "dir /B "+folder+"\\*."+extension;
    }else{
        command = "ls -1 "+folder+"/*."+extension;
    }
    exec(command,function(err,stdout,stderr){
        if(err)
            return cb(err,null);
        //get rid of \r from windows
        stdout = stdout.replace(/\r/g,"");
        var files = stdout.split("\n");
        //remove last entry because it is empty
        files.splice(-1,1);
        cb(err,files);
    });
}

findFiles("folderName","html",function(err,files){
    console.log("files:",files);
})

2. The bellow function uses find and dir, searches recursively but on windows it has absolute paths

var exec = require('child_process').exec;
function findFiles(folder,extension,cb){
    var command = "";
    if(/^win/.test(process.platform)){
        command = "dir /B /s "+folder+"\\*."+extension;
    }else{
        command = 'find '+folder+' -name "*.'+extension+'"'
    }
    exec(command,function(err,stdout,stderr){
        if(err)
            return cb(err,null);
        //get rid of \r from windows
        stdout = stdout.replace(/\r/g,"");
        var files = stdout.split("\n");
        //remove last entry because it is empty
        files.splice(-1,1);
        cb(err,files);
    });
}

findFiles("folder","html",function(err,files){
    console.log("files:",files);
})

How to define object in array in Mongoose schema correctly with 2d geo index

Thanks for the replies.

I tried the first approach, but nothing changed. Then, I tried to log the results. I just drilled down level by level, until I finally got to where the data was being displayed.

After a while I found the problem: When I was sending the response, I was converting it to a string via .toString().

I fixed that and now it works brilliantly. Sorry for the false alarm.

How to set a Timer in Java?

So the first part of the answer is how to do what the subject asks as this was how I initially interpreted it and a few people seemed to find helpful. The question was since clarified and I've extended the answer to address that.

Setting a timer

First you need to create a Timer (I'm using the java.util version here):

import java.util.Timer;

..

Timer timer = new Timer();

To run the task once you would do:

timer.schedule(new TimerTask() {
  @Override
  public void run() {
    // Your database code here
  }
}, 2*60*1000);
// Since Java-8
timer.schedule(() -> /* your database code here */, 2*60*1000);

To have the task repeat after the duration you would do:

timer.scheduleAtFixedRate(new TimerTask() {
  @Override
  public void run() {
    // Your database code here
  }
}, 2*60*1000, 2*60*1000);

// Since Java-8
timer.scheduleAtFixedRate(() -> /* your database code here */, 2*60*1000, 2*60*1000);

Making a task timeout

To specifically do what the clarified question asks, that is attempting to perform a task for a given period of time, you could do the following:

ExecutorService service = Executors.newSingleThreadExecutor();

try {
    Runnable r = new Runnable() {
        @Override
        public void run() {
            // Database task
        }
    };

    Future<?> f = service.submit(r);

    f.get(2, TimeUnit.MINUTES);     // attempt the task for two minutes
}
catch (final InterruptedException e) {
    // The thread was interrupted during sleep, wait or join
}
catch (final TimeoutException e) {
    // Took too long!
}
catch (final ExecutionException e) {
    // An exception from within the Runnable task
}
finally {
    service.shutdown();
}

This will execute normally with exceptions if the task completes within 2 minutes. If it runs longer than that, the TimeoutException will be throw.

One issue is that although you'll get a TimeoutException after the two minutes, the task will actually continue to run, although presumably a database or network connection will eventually time out and throw an exception in the thread. But be aware it could consume resources until that happens.

Disable mouse scroll wheel zoom on embedded Google Maps

The simplest one:

<div id="myIframe" style="width:640px; height:480px;">
   <div style="background:transparent; position:absolute; z-index:1; width:100%; height:100%; cursor:pointer;" onClick="style.pointerEvents='none'"></div>
   <iframe src="https://www.google.com/maps/d/embed?mid=XXXXXXXXXXXXXX" style="width:640px; height:480px;"></iframe>
</div>

how to install multiple versions of IE on the same system?

I would use VMs. Create an XP (or whatever) VM using VMware Workstation or similar product, and snapshot it. That is your oldest version. Then perform the upgrades one at a time, and snapshot each time. Then you can switch to any snapshot you need later, or clone independent VMs based on all the snapshots so you can run them all at once. You probably want to test on different operating systems as well as different versions, so VMs generalize that solution as well rather than some one-off solution of hacking multiple IEs to coexist on a single instance of Windows.

How do I capture the output into a variable from an external process in PowerShell?

Note: The command in the question uses Start-Process, which prevents direct capturing of the target program's output. Generally, do not use Start-Process to execute console applications synchronously - just invoke them directly, as in any shell. Doing so keeps the application connected to the calling console's standard streams, allowing its output to be captured by simple assignment $output = netdom ..., as detailed below.

Fundamentally, capturing output from external programs works the same as with PowerShell-native commands (you may want a refresher on how to execute external programs; <command> is a placeholder for any valid command below):

$cmdOutput = <command>   # captures the command's success stream / stdout output

Note that $cmdOutput receives an array of objects if <command> produces more than 1 output object, which in the case of an external program means a string[1] array containing the program's output lines.

If you want to make sure that the result is always an array - even if only one object is output, type-constrain the variable as an array, or wrap the command in @(), the array-subexpression operator):

[array] $cmdOutput = <command> # or: $cmdOutput = @(<command>)

By contrast, if you want $cmdOutput to always receive a single - potentially multi-line - string, use Out-String, though note that a trailing newline is invariably added:

# Note: Adds a trailing newline.
$cmdOutput = <command> | Out-String

With calls to external programs - which by definition only ever return strings in PowerShell[1] - you can avoid that by using the -join operator instead:

# NO trailing newline.
$cmdOutput = (<command>) -join "`n"

Note: For simplicity, the above uses "`n" to create Unix-style LF-only newlines, which PowerShell happily accepts on all platforms; if you need platform-appropriate newlines (CRLF on Windows, LF on Unix), use [Environment]::NewLine instead.


To capture output in a variable and print to the screen:

<command> | Tee-Object -Variable cmdOutput # Note how the var name is NOT $-prefixed

Or, if <command> is a cmdlet or advanced function, you can use common parameter
-OutVariable / -ov
:

<command> -OutVariable cmdOutput   # cmdlets and advanced functions only

Note that with -OutVariable, unlike in the other scenarios, $cmdOutput is always a collection, even if only one object is output. Specifically, an instance of the array-like [System.Collections.ArrayList] type is returned.
See this GitHub issue for a discussion of this discrepancy.


To capture the output from multiple commands, use either a subexpression ($(...)) or call a script block ({ ... }) with & or .:

$cmdOutput = $(<command>; ...)  # subexpression

$cmdOutput = & {<command>; ...} # script block with & - creates child scope for vars.

$cmdOutput = . {<command>; ...} # script block with . - no child scope

Note that the general need to prefix with & (the call operator) an individual command whose name/path is quoted - e.g., $cmdOutput = & 'netdom.exe' ... - is not related to external programs per se (it equally applies to PowerShell scripts), but is a syntax requirement: PowerShell parses a statement that starts with a quoted string in expression mode by default, whereas argument mode is needed to invoke commands (cmdlets, external programs, functions, aliases), which is what & ensures.

The key difference between $(...) and & { ... } / . { ... } is that the former collects all input in memory before returning it as a whole, whereas the latter stream the output, suitable for one-by-one pipeline processing.


Redirections also work the same, fundamentally (but see caveats below):

$cmdOutput = <command> 2>&1 # redirect error stream (2) to success stream (1)

However, for external commands the following is more likely to work as expected:

$cmdOutput = cmd /c <command> '2>&1' # Let cmd.exe handle redirection - see below.

Considerations specific to external programs:

  • External programs, because they operate outside PowerShell's type system, only ever return strings via their success stream (stdout); similarly, PowerShell only ever sends strings to external programs via the pipeline.[1]

    • Character-encoding issues can therefore come into play:
      • On sending data via the pipeline to external programs, PowerShell uses the encoding stored in the $OutVariable preference variable; which in Windows PowerShell defaults to ASCII(!) and in PowerShell [Core] to UTF-8.

      • On receiving data from an external program, PowerShell uses the encoding stored in [Console]::OutputEncoding to decode the data, which in both PowerShell editions defaults to the system's active OEM code page.

      • See this answer for more information; this answer discusses the still-in-beta (as of this writing) Windows 10 feature that allows you to set UTF-8 as both the ANSI and the OEM code page system-wide.

  • If the output contains more than 1 line, PowerShell by default splits it into an array of strings. More accurately, the output lines are stored in an array of type [System.Object[]] whose elements are strings ([System.String]).

  • If you want the output to be a single, potentially multi-line string, use the -join operator (you can alternatively pipe to Out-String, but that invariably adds a trailing newline):
    $cmdOutput = (<command>) -join [Environment]::NewLine

  • Merging stderr into stdout with 2>&1, so as to also capture it as part of the success stream, comes with caveats:

    • To do this at the source, let cmd.exe handle the redirection, using the following idioms (works analogously with sh on Unix-like platforms):
      $cmdOutput = cmd /c <command> '2>&1' # *array* of strings (typically)
      $cmdOutput = (cmd /c <command> '2>&1') -join "`r`n" # single string

      • cmd /c invokes cmd.exe with command <command> and exits after <command> has finished.

      • Note the single quotes around 2>&1, which ensures that the redirection is passed to cmd.exe rather than being interpreted by PowerShell.

      • Note that involving cmd.exe means that its rules for escaping characters and expanding environment variables come into play, by default in addition to PowerShell's own requirements; in PS v3+ you can use special parameter --% (the so-called stop-parsing symbol) to turn off interpretation of the remaining parameters by PowerShell, except for cmd.exe-style environment-variable references such as %PATH%.

      • Note that since you're merging stdout and stderr at the source with this approach, you won't be able to distinguish between stdout-originated and stderr-originated lines in PowerShell; if you do need this distinction, use PowerShell's own 2>&1 redirection - see below.

    • Use PowerShell's 2>&1 redirection to know which lines came from what stream:

      • Stderr output is captured as error records ([System.Management.Automation.ErrorRecord]), not strings, so the output array may contain a mix of strings (each string representing a stdout line) and error records (each record representing a stderr line). Note that, as requested by 2>&1, both the strings and the error records are received through PowerShell's success output stream).

      • Note: The following only applies to Windows PowerShell - these problems have been corrected in PowerShell [Core] v6+, though the filtering technique by object type shown below ($_ -is [System.Management.Automation.ErrorRecord]) can also be useful there.

      • In the console, the error records print in red, and the 1st one by default produces multi-line display, in the same format that a cmdlet's non-terminating error would display; subsequent error records print in red as well, but only print their error message, on a single line.

      • When outputting to the console, the strings typically come first in the output array, followed by the error records (at least among a batch of stdout/stderr lines output "at the same time"), but, fortunately, when you capture the output, it is properly interleaved, using the same output order you would get without 2>&1; in other words: when outputting to the console, the captured output does NOT reflect the order in which stdout and stderr lines were generated by the external command.

      • If you capture the entire output in a single string with Out-String, PowerShell will add extra lines, because the string representation of an error record contains extra information such as location (At line:...) and category (+ CategoryInfo ...); curiously, this only applies to the first error record.

        • To work around this problem, apply the .ToString() method to each output object instead of piping to Out-String:
          $cmdOutput = <command> 2>&1 | % { $_.ToString() };
          in PS v3+ you can simplify to:
          $cmdOutput = <command> 2>&1 | % ToString
          (As a bonus, if the output isn't captured, this produces properly interleaved output even when printing to the console.)

        • Alternatively, filter the error records out and send them to PowerShell's error stream with Write-Error (as a bonus, if the output isn't captured, this produces properly interleaved output even when printing to the console):

$cmdOutput = <command> 2>&1 | ForEach-Object {
  if ($_ -is [System.Management.Automation.ErrorRecord]) {
    Write-Error $_
  } else {
    $_
  }
}

[1] As of PowerShell 7.1, PowerShell knows only strings when communicating with external programs. There is generally no concept of raw byte data in a PowerShell pipeline. If you want raw byte data returned from an external program, you must shell out to cmd.exe /c (Windows) or sh -c (Unix), save to a file there, then read that file in PowerShell. See this answer for more information.

Select a Column in SQL not in Group By

Thing I like to do is to wrap addition columns in aggregate function, like max(). It works very good when you don't expect duplicate values.

Select MAX(cpe.createdon) As MaxDate, cpe.fmgcms_cpeclaimid, MAX(cpe.fmgcms_claimid) As fmgcms_claimid 
from Filteredfmgcms_claimpaymentestimate cpe
where cpe.createdon < 'reportstartdate'
group by cpe.fmgcms_cpeclaimid

What is newline character -- '\n'

I think this post by Jeff Attwood addresses your question perfectly. It takes you through the differences between newlines on Dos, Mac and Unix, and then explains the history of CR (Carriage return) and LF (Line feed).

Using CMake to generate Visual Studio C++ project files

Lots of great answers here but they might be superseded by this CMake support in Visual Studio (Oct 5 2016)

Django - Reverse for '' not found. '' is not a valid view function or pattern name

In my case, this error occurred due to a mismatched url name. e.g,

<form action="{% url 'test-view' %}" method="POST">

urls.py

path("test/", views.test, name='test-view'),

Get table column names in MySQL?

How about this:

SELECT @cCommand := GROUP_CONCAT( COLUMN_NAME ORDER BY column_name SEPARATOR ',\n')
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_SCHEMA = 'my_database' AND TABLE_NAME = 'my_table';

SET @cCommand = CONCAT( 'SELECT ', @cCommand, ' from my_database.my_table;');
PREPARE xCommand from @cCommand;
EXECUTE xCommand;

Automated way to convert XML files to SQL database?

For Mysql please see the LOAD XML SyntaxDocs.

It should work without any additional XML transformation for the XML you've provided, just specify the format and define the table inside the database firsthand with matching column names:

LOAD XML LOCAL INFILE 'table1.xml'
    INTO TABLE table1
    ROWS IDENTIFIED BY '<table1>';

There is also a related question:

For Postgresql I do not know.

Change status bar color with AppCompat ActionBarActivity

Thanks for above answers, with the help of those, after certain R&D for xamarin.android MVVMCross application, below worked

Flag specified for activity in method OnCreate

protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);
        this.Window.AddFlags(WindowManagerFlags.DrawsSystemBarBackgrounds);
    }

For each MvxActivity, Theme is mentioned as below

 [Activity(
    LaunchMode = LaunchMode.SingleTop,
    ScreenOrientation = ScreenOrientation.Portrait,
    Theme = "@style/Theme.Splash",
    Name = "MyView"
    )]

My SplashStyle.xml looks like as below

<?xml version="1.0" encoding="utf-8"?>
<resources> 
    <style name="Theme.Splash" parent="Theme.AppCompat.Light.NoActionBar">
          <item name="android:statusBarColor">@color/app_red</item>
          <item name="android:colorPrimaryDark">@color/app_red</item>
    </style>
 </resources>

And I have V7 appcompact referred.

Find and replace - Add carriage return OR Newline

You can also try \x0d\x0a in the "Replace with" box with "Use regular Expression" box checked to get carriage return + line feed using Visual Studio Find/Replace. Using \n (line feed) is the same as \x0a

Is there a way to get a collection of all the Models in your Rails app?

This seems to work for me:

  Dir.glob(RAILS_ROOT + '/app/models/*.rb').each { |file| require file }
  @models = Object.subclasses_of(ActiveRecord::Base)

Rails only loads models when they are used, so the Dir.glob line "requires" all the files in the models directory.

Once you have the models in an array, you can do what you were thinking (e.g. in view code):

<% @models.each do |v| %>
  <li><%= h v.to_s %></li>
<% end %>

What are the differences between "=" and "<-" assignment operators in R?

The operators <- and = assign into the environment in which they are evaluated. The operator <- can be used anywhere, whereas the operator = is only allowed at the top level (e.g., in the complete expression typed at the command prompt) or as one of the subexpressions in a braced list of expressions.

javascript, for loop defines a dynamic variable name

You cannot create different "variable names" but you can create different object properties. There are many ways to do whatever it is you're actually trying to accomplish. In your case I would just do

for (var i = myArray.length - 1; i >= 0; i--) {    console.log(eval(myArray[i])); }; 

More generally you can create object properties dynamically, which is the type of flexibility you're thinking of.

var result = {}; for (var i = myArray.length - 1; i >= 0; i--) {     result[myArray[i]] = eval(myArray[i]);   }; 

I'm being a little handwavey since I don't actually understand language theory, but in pure Javascript (including Node) references (i.e. variable names) are happening at a higher level than at runtime. More like at the call stack; you certainly can't manufacture them in your code like you produce objects or arrays. Browsers do actually let you do this anyway though it's terrible practice, via

window['myVarName'] = 'namingCollisionsAreFun';  

(per comment)

Entity Framework Migrations renaming tables and columns

If you don't like writing/changing the required code in the Migration class manually, you can follow a two-step approach which automatically make the RenameColumn code which is required:

Step One Use the ColumnAttribute to introduce the new column name and then add-migration (e.g. Add-Migration ColumnChanged)

public class ReportPages
{
    [Column("Section_Id")]                 //Section_Id
    public int Group_Id{get;set}
}

Step-Two change the property name and again apply to same migration (e.g. Add-Migration ColumnChanged -force) in the Package Manager Console

public class ReportPages
{
    [Column("Section_Id")]                 //Section_Id
    public int Section_Id{get;set}
}

If you look at the Migration class you can see the automatically code generated is RenameColumn.

How to secure RESTful web services?

There's another, very secure method. It's client certificates. Know how servers present an SSL Cert when you contact them on https? Well servers can request a cert from a client so they know the client is who they say they are. Clients generate certs and give them to you over a secure channel (like coming into your office with a USB key - preferably a non-trojaned USB key).

You load the public key of the cert client certificates (and their signer's certificate(s), if necessary) into your web server, and the web server won't accept connections from anyone except the people who have the corresponding private keys for the certs it knows about. It runs on the HTTPS layer, so you may even be able to completely skip application-level authentication like OAuth (depending on your requirements). You can abstract a layer away and create a local Certificate Authority and sign Cert Requests from clients, allowing you to skip the 'make them come into the office' and 'load certs onto the server' steps.

Pain the neck? Absolutely. Good for everything? Nope. Very secure? Yup.

It does rely on clients keeping their certificates safe however (they can't post their private keys online), and it's usually used when you sell a service to clients rather then letting anyone register and connect.

Anyway, it may not be the solution you're looking for (it probably isn't to be honest), but it's another option.

Create a list from two object lists with linq

There are a few pieces to doing this, assuming each list does not contain duplicates, Name is a unique identifier, and neither list is ordered.

First create an append extension method to get a single list:

static class Ext {
  public static IEnumerable<T> Append(this IEnumerable<T> source,
                                      IEnumerable<T> second) {
    foreach (T t in source) { yield return t; }
    foreach (T t in second) { yield return t; }
  }
}

Thus can get a single list:

var oneList = list1.Append(list2);

Then group on name

var grouped = oneList.Group(p => p.Name);

Then can process each group with a helper to process one group at a time

public Person MergePersonGroup(IGrouping<string, Person> pGroup) {
  var l = pGroup.ToList(); // Avoid multiple enumeration.
  var first = l.First();
  var result = new Person {
    Name = first.Name,
    Value = first.Value
  };
  if (l.Count() == 1) {
    return result;
  } else if (l.Count() == 2) {
    result.Change = first.Value - l.Last().Value;
    return result;
  } else {
    throw new ApplicationException("Too many " + result.Name);
  }
}

Which can be applied to each element of grouped:

var finalResult = grouped.Select(g => MergePersonGroup(g));

(Warning: untested.)

JavaScript: How to pass object by value?

Actually, Javascript is always pass by value. But because object references are values, objects will behave like they are passed by reference.

So in order to walk around this, stringify the object and parse it back, both using JSON. See example of code below:

var person = { Name: 'John', Age: '21', Gender: 'Male' };

var holder = JSON.stringify(person);
// value of holder is "{"Name":"John","Age":"21","Gender":"Male"}"
// note that holder is a new string object

var person_copy = JSON.parse(holder);
// value of person_copy is { Name: 'John', Age: '21', Gender: 'Male' };
// person and person_copy now have the same properties and data
// but are referencing two different objects

How can I get file extensions with JavaScript?

There is a standard library function for this in the path module:

import path from 'path';

console.log(path.extname('abc.txt'));

Output:

.txt

So, if you only want the format:

path.extname('abc.txt').slice(1) // 'txt'

If there is no extension, then the function will return an empty string:

path.extname('abc') // ''

If you are using Node, then path is built-in. If you are targetting the browser, then Webpack will bundle a path implementation for you. If you are targetting the browser without Webpack, then you can include path-browserify manually.

There is no reason to do string splitting or regex.

Delete all the queues from RabbitMQ?

Here is a way to do it with PowerShell. the URL may need to be updated

$cred = Get-Credential
 iwr -ContentType 'application/json' -Method Get -Credential $cred   'http://localhost:15672/api/queues' | % { 
    ConvertFrom-Json  $_.Content } | % { $_ } | ? { $_.messages -gt 0} | % {
    iwr  -method DELETE -Credential $cred  -uri  $("http://localhost:15672/api/queues/{0}/{1}" -f  [System.Web.HttpUtility]::UrlEncode($_.vhost),  $_.name)
 }

Java Multiple Inheritance

In Java 8, which is still in the development phase as of February 2014, you could use default methods to achieve a sort of C++-like multiple inheritance. You could also have a look at this tutorial which shows a few examples that should be easier to start working with than the official documentation.

add maven repository to build.gradle

After

apply plugin: 'com.android.application'

You should add this:

  repositories {
        mavenCentral()
        maven {
            url "https://repository-achartengine.forge.cloudbees.com/snapshot/"
        }
    }

@Benjamin explained the reason.

If you have a maven with authentication you can use:

repositories {
            mavenCentral()
            maven {
               credentials {
                   username xxx
                   password xxx
               }
               url    'http://mymaven/xxxx/repositories/releases/'
            }
}

It is important the order.

Unit Tests not discovered in Visual Studio 2017

Check if the NUnit 3 Test Adapter is enabled. In my case, I already installed it a long time ago, but suddenly it got disabled somehow. Took me quite a while before I decided to check that part...

NUnit 3 Test Adapter Disabled

batch file to list folders within a folder to one level

I tried this command to display the list of files in the directory.

dir /s /b > List.txt

In the file it displays the list below.

C:\Program Files (x86)\Cisco Systems\Cisco Jabber\XmppMgr.dll

C:\Program Files (x86)\Cisco Systems\Cisco Jabber\XmppSDK.dll

C:\Program Files (x86)\Cisco Systems\Cisco Jabber\accessories\Plantronics

C:\Program Files (x86)\Cisco Systems\Cisco Jabber\accessories\SennheiserJabberPlugin.dll

C:\Program Files (x86)\Cisco Systems\Cisco Jabber\accessories\Logitech\LogiUCPluginForCisco

C:\Program Files (x86)\Cisco Systems\Cisco Jabber\accessories\Logitech\LogiUCPluginForCisco\lucpcisco.dll

What is want to do is only to display sub-directory not the full directory path.

Just like this:

Cisco Jabber\XmppMgr.dll Cisco Jabber\XmppSDK.dll

Cisco Jabber\accessories\JabraJabberPlugin.dll

Cisco Jabber\accessories\Logitech

Cisco Jabber\accessories\Plantronics

Cisco Jabber\accessories\SennheiserJabberPlugin.dll

SQL query: Delete all records from the table except latest N?

DELETE FROM table WHERE ID NOT IN
(SELECT MAX(ID) ID FROM table)

How to reset (clear) form through JavaScript?

You could use the following:

$('[element]').trigger('reset')

Linking to an external URL in Javadoc?

Taken from the javadoc spec

@see <a href="URL#value">label</a> : Adds a link as defined by URL#value. The URL#value is a relative or absolute URL. The Javadoc tool distinguishes this from other cases by looking for a less-than symbol (<) as the first character.

For example : @see <a href="http://www.google.com">Google</a>

WPF Databinding: How do I access the "parent" data context?

You could try something like this:

...Binding="{Binding RelativeSource={RelativeSource FindAncestor, 
AncestorType={x:Type Window}}, Path=DataContext.AllowItemCommand}" ...

How can I send and receive WebSocket messages on the server side?

In addition to the PHP frame encoding function, here follows a decode function:

function Decode($M){
    $M = array_map("ord", str_split($M));
    $L = $M[1] AND 127;

    if ($L == 126)
        $iFM = 4;
    else if ($L == 127)
        $iFM = 10;
    else
        $iFM = 2;

    $Masks = array_slice($M, $iFM, 4);

    $Out = "";
    for ($i = $iFM + 4, $j = 0; $i < count($M); $i++, $j++ ) {
        $Out .= chr($M[$i] ^ $Masks[$j % 4]);
    }
    return $Out;
}

I've implemented this and also other functions in an easy-to-use WebSocket PHP class here.

JSON.parse vs. eval()

You are more vulnerable to attacks if using eval: JSON is a subset of Javascript and json.parse just parses JSON whereas eval would leave the door open to all JS expressions.

Check if a string is null or empty in XSLT

In some cases, you might want to know when the value is specifically null, which is particularly necessary when using XML which has been serialized from .NET objects. While the accepted answer works for this, it also returns the same result when the string is blank or empty, i.e. '', so you can't differentiate.

<group>
    <item>
        <id>item 1</id>
        <CategoryName xsi:nil="true" />
    </item>
</group>

So you can simply test the attribute.

<xsl:if test="CategoryName/@xsi:nil='true'">
   Hello World.
</xsl:if>

Sometimes it's necessary to know the exact state and you can't simply check if CategoryName is instantiated, because unlike say Javascript

<xsl:if test="CategoryName">
   Hello World.
</xsl:if>

Will return true for a null element.

Python: How to check a string for substrings from a list?

Try this test:

any(substring in string for substring in substring_list)

It will return True if any of the substrings in substring_list is contained in string.

Note that there is a Python analogue of Marc Gravell's answer in the linked question:

from itertools import imap
any(imap(string.__contains__, substring_list)) 

In Python 3, you can use map directly instead:

any(map(string.__contains__, substring_list))

Probably the above version using a generator expression is more clear though.

Difference between / and /* in servlet mapping url pattern

The essential difference between /* and / is that a servlet with mapping /* will be selected before any servlet with an extension mapping (like *.html), while a servlet with mapping / will be selected only after extension mappings are considered (and will be used for any request which doesn't match anything else---it is the "default servlet").

In particular, a /* mapping will always be selected before a / mapping. Having either prevents any requests from reaching the container's own default servlet.

Either will be selected only after servlet mappings which are exact matches (like /foo/bar) and those which are path mappings longer than /* (like /foo/*). Note that the empty string mapping is an exact match for the context root (http://host:port/context/).

See Chapter 12 of the Java Servlet Specification, available in version 3.1 at http://download.oracle.com/otndocs/jcp/servlet-3_1-fr-eval-spec/index.html.

Python, compute list difference

The above examples trivialized the problem of calculating differences. Assuming sorting or de-duplication definitely make it easier to compute the difference, but if your comparison cannot afford those assumptions then you'll need a non-trivial implementation of a diff algorithm. See difflib in the python standard library.

#! /usr/bin/python2
from difflib import SequenceMatcher

A = [1,2,3,4]
B = [2,5]

squeeze=SequenceMatcher( None, A, B )

print "A - B = [%s]"%( reduce( lambda p,q: p+q,
                               map( lambda t: squeeze.a[t[1]:t[2]],
                                    filter(lambda x:x[0]!='equal',
                                           squeeze.get_opcodes() ) ) ) )

Or Python3...

#! /usr/bin/python3
from difflib import SequenceMatcher
from functools import reduce

A = [1,2,3,4]
B = [2,5]

squeeze=SequenceMatcher( None, A, B )

print( "A - B = [%s]"%( reduce( lambda p,q: p+q,
                               map( lambda t: squeeze.a[t[1]:t[2]],
                                    filter(lambda x:x[0]!='equal',
                                           squeeze.get_opcodes() ) ) ) ) )

Output:

A - B = [[1, 3, 4]]

How do ACID and database transactions work?

[Gray] introduced the ACD properties for a transaction in 1981. In 1983 [Haerder] added the Isolation property. In my opinion, the ACD properties would be have a more useful set of properties to discuss. One interpretation of Atomicity (that the transaction should be atomic as seen from any client any time) would actually imply the isolation property. The "isolation" property is useful when the transaction is not isolated; when the isolation property is relaxed. In ANSI SQL speak: if the isolation level is weaker then SERIALIZABLE. But when the isolation level is SERIALIZABLE, the isolation property is not really of interest.

I have written more about this in a blog post: "ACID Does Not Make Sense".

http://blog.franslundberg.com/2013/12/acid-does-not-make-sense.html

[Gray] The Transaction Concept, Jim Gray, 1981. http://research.microsoft.com/en-us/um/people/gray/papers/theTransactionConcept.pdf

[Haerder] Principles of Transaction-Oriented Database Recovery, Haerder and Reuter, 1983. http://www.stanford.edu/class/cs340v/papers/recovery.pdf

Ansible: create a user with sudo privileges

Sometimes it's knowing what to ask. I didn't know as I am a developer who has taken on some DevOps work.

Apparently 'passwordless' or NOPASSWD login is a thing which you need to put in the /etc/sudoers file.

The answer to my question is at Ansible: best practice for maintaining list of sudoers.

The Ansible playbook code fragment looks like this from my problem:

- name: Make sure we have a 'wheel' group
  group:
    name: wheel
    state: present

- name: Allow 'wheel' group to have passwordless sudo
  lineinfile:
    dest: /etc/sudoers
    state: present
    regexp: '^%wheel'
    line: '%wheel ALL=(ALL) NOPASSWD: ALL'
    validate: 'visudo -cf %s'

- name: Add sudoers users to wheel group
  user:
    name=deployer
    groups=wheel
    append=yes
    state=present
    createhome=yes

- name: Set up authorized keys for the deployer user
  authorized_key: user=deployer key="{{item}}"
  with_file:
    - /home/railsdev/.ssh/id_rsa.pub

And the best part is that the solution is idempotent. It doesn't add the line

%wheel ALL=(ALL) NOPASSWD: ALL

to /etc/sudoers when the playbook is run a subsequent time. And yes...I was able to ssh into the server as "deployer" and run sudo commands without having to give a password.

Best C# API to create PDF

Update:

I'm not sure when or if the license changed for the iText# library, but it is licensed under AGPL which means it must be licensed if included with a closed-source product. The question does not (currently) require free or open-source libraries. One should always investigate the license type of any library used in a project.


I have used iText# with success in .NET C# 3.5; it is a port of the open source Java library for PDF generation and it's free.

There is a NuGet package available for iTextSharp version 5 and the official developer documentation, as well as C# examples, can be found at itextpdf.com

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

neither try any above ways nor sudo apt autoremove python3 because it will remove all gnome based applications from your system including gnome-terminal. In case if you have done that mistake and left with kernal only than trysudo apt install gnome on kernal.

try to change your default python version instead removing it. you can do this through bashrc file or export path command.

MVC4 DataType.Date EditorFor won't display date value in Chrome, fine in Internet Explorer

As an addition to Darin Dimitrov's answer:

If you only want this particular line to use a certain (different from standard) format, you can use in MVC5:

@Html.EditorFor(model => model.Property, new {htmlAttributes = new {@Value = @Model.Property.ToString("yyyy-MM-dd"), @class = "customclass" } })

PHP date() format when inserting into datetime in MySQL

I use the following PHP code to create a variable that I insert into a MySQL DATETIME column.

$datetime = date_create()->format('Y-m-d H:i:s');

This will hold the server's current Date and Time.

How to change active class while click to another link in bootstrap use jquery?

You are binding you click on the wrong element, you should bind it to the a.

You are prevent default event to occur on the li, but li have no default behavior, a does.

Try this:

$(document).ready(function () {
    $('.nav li a').click(function(e) {

        $('.nav li.active').removeClass('active');

        var $parent = $(this).parent();
        $parent.addClass('active');
        e.preventDefault();
    });
});

How do you pass view parameters when navigating from an action in JSF2?

The unintuitive thing about passing parameters in JSF is that you do not decide what to send (in the action), but rather what you wish to receive (in the target page).

When you do an action that ends with a redirect, the target page metadata is loaded and all required parameters are read and appended to the url as params.

Note that this is exactly the same mechanism as with any other JSF binding: you cannot read inputText's value from one place and have it write somewhere else. The value expression defined in viewParam is used both for reading (before the redirect) and for writing (after the redirect).

With your bean you just do:

@ManagedBean
@RequestScoped
public class MyBean {

private int id;

public String submit() {
    //Does stuff
    id = setID();
    return "success?faces-redirect=true&includeViewParams=true";
}

// setter and getter for id

If the receiving side has:

    <f:metadata>
        <f:viewParam name="id" value="#{myBean.id}" />
    </f:metadata>

It will do exactly what you want.

What is the best way to prevent session hijacking?

The SSL only helps with sniffing attacks. If an attacker has access to your machine I will assume they can copy your secure cookie too.

At the very least, make sure old cookies lose their value after a while. Even a successful hijaking attack will be thwarted when the cookie stops working. If the user has a cookie from a session that logged in more than a month ago, make them reenter their password. Make sure that whenever a user clicks on your site's "log out" link, that the old session UUID can never be used again.

I'm not sure if this idea will work but here goes: Add a serial number into your session cookie, maybe a string like this:

SessionUUID, Serial Num, Current Date/Time

Encrypt this string and use it as your session cookie. Regularly change the serial num - maybe when the cookie is 5 minutes old and then reissue the cookie. You could even reissue it on every page view if you wanted to. On the server side, keep a record of the last serial num you've issued for that session. If someone ever sends a cookie with the wrong serial number it means that an attacker may be using a cookie they intercepted earlier so invalidate the session UUID and ask the user to reenter their password and then reissue a new cookie.

Remember that your user may have more than one computer so they may have more than one active session. Don't do something that forces them to log in again every time they switch between computers.

How to Truncate a string in PHP to the word closest to a certain number of characters?

While this is a rather old question, I figured I would provide an alternative, as it was not mentioned and valid for PHP 4.3+.

You can use the sprintf family of functions to truncate text, by using the %.Ns precision modifier.

A period . followed by an integer who's meaning depends on the specifier:

  • For e, E, f and F specifiers: this is the number of digits to be printed after the decimal point (by default, this is 6).
  • For g and G specifiers: this is the maximum number of significant digits to be printed.
  • For s specifier: it acts as a cutoff point, setting a maximum character limit to the string

Simple Truncation https://3v4l.org/QJDJU

$string = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var_dump(sprintf('%.10s', $string));

Result

string(10) "0123456789"

Expanded Truncation https://3v4l.org/FCD21

Since sprintf functions similarly to substr and will partially cut off words. The below approach will ensure words are not cutoff by using strpos(wordwrap(..., '[break]'), '[break]') with a special delimiter. This allows us to retrieve the position and ensure we do not match on standard sentence structures.

Returning a string without partially cutting off words and that does not exceed the specified width, while preserving line-breaks if desired.

function truncate($string, $width, $on = '[break]') {
    if (strlen($string) > $width && false !== ($p = strpos(wordwrap($string, $width, $on), $on))) {
        $string = sprintf('%.'. $p . 's', $string);
    }
    return $string;
}
var_dump(truncate('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ', 20));

var_dump(truncate("Lorem Ipsum is simply dummy text of the printing and typesetting industry.", 20));

var_dump(truncate("Lorem Ipsum\nis simply dummy text of the printing and typesetting industry.", 20));

Result

/* 
string(36) "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"  
string(14) "Lorem Ipsum is" 
string(14) "Lorem Ipsum
is" 
*/

Results using wordwrap($string, $width) or strtok(wordwrap($string, $width), "\n")

/*
string(14) "Lorem Ipsum is"
string(11) "Lorem Ipsum"
*/

Including JavaScript class definition from another file in Node.js

You can simply do this:

user.js

class User {
    //...
}

module.exports = User

server.js

const User = require('./user.js')

// Instantiate User:
let user = new User()

This is called CommonJS module.

Export multiple values

Sometimes it could be useful to export more than one value. For example it could be classes, functions or constants. This is an alternative version of the same functionality:

user.js

class User {}

exports.User = User //  Spot the difference

server.js

const {User} = require('./user.js') //  Destructure on import

// Instantiate User:
let user = new User()

ES Modules

Since Node.js version 14 it's possible to use ES Modules with CommonJS. Read more about it in the ESM documentation.

?? Don't use globals, it creates potential conflicts with the future code.

How to delete the last row of data of a pandas dataframe

DF[:-n]

where n is the last number of rows to drop.

To drop the last row :

DF = DF[:-1]

How to get second-highest salary employees in a table

Try This one

    select * from
   (
    select name,salary,ROW_NUMBER() over( order by Salary desc) as
    rownum from    employee
   ) as t where t.rownum=2

http://askme.indianyouth.info/details/write-a-sql-query-to-find-the-10th-highest-employee-salary-from-an-employee-table-explain-your-answer-111

LaTeX Optional Arguments

Example from the guide:

\newcommand{\example}[2][YYY]{Mandatory arg: #2;
                                 Optional arg: #1.}

This defines \example to be a command with two arguments, 
referred to as #1 and #2 in the {<definition>}--nothing new so far. 
But by adding a second optional argument to this \newcommand 
(the [YYY]) the first argument (#1) of the newly defined 
command \example is made optional with its default value being YYY.

Thus the usage of \example is either:

   \example{BBB}
which prints:
Mandatory arg: BBB; Optional arg: YYY.
or:
   \example[XXX]{AAA}
which prints:
Mandatory arg: AAA; Optional arg: XXX.

'setInterval' vs 'setTimeout'

setInterval fires again and again in intervals, while setTimeout only fires once.

See reference at MDN.

Replace console output in Python

An easy solution is just writing "\r" before the string and not adding a newline; if the string never gets shorter this is sufficient...

sys.stdout.write("\rDoing thing %i" % i)
sys.stdout.flush()

Slightly more sophisticated is a progress bar... this is something I am using:

def startProgress(title):
    global progress_x
    sys.stdout.write(title + ": [" + "-"*40 + "]" + chr(8)*41)
    sys.stdout.flush()
    progress_x = 0

def progress(x):
    global progress_x
    x = int(x * 40 // 100)
    sys.stdout.write("#" * (x - progress_x))
    sys.stdout.flush()
    progress_x = x

def endProgress():
    sys.stdout.write("#" * (40 - progress_x) + "]\n")
    sys.stdout.flush()

You call startProgress passing the description of the operation, then progress(x) where x is the percentage and finally endProgress()

Cannot delete or update a parent row: a foreign key constraint fails

I tried the solution mentioned by @Alino Manzi but it didn't work for me on the WordPress related tables using wpdb.

then I modified the code as below and it worked

SET FOREIGN_KEY_CHECKS=OFF; //disabling foreign key

//run the queries which are giving foreign key errors

SET FOREIGN_KEY_CHECKS=ON; // enabling foreign key

Catch multiple exceptions in one line (except block)

From Python documentation -> 8.3 Handling Exceptions:

A try statement may have more than one except clause, to specify handlers for different exceptions. At most one handler will be executed. Handlers only handle exceptions that occur in the corresponding try clause, not in other handlers of the same try statement. An except clause may name multiple exceptions as a parenthesized tuple, for example:

except (RuntimeError, TypeError, NameError):
    pass

Note that the parentheses around this tuple are required, because except ValueError, e: was the syntax used for what is normally written as except ValueError as e: in modern Python (described below). The old syntax is still supported for backwards compatibility. This means except RuntimeError, TypeError is not equivalent to except (RuntimeError, TypeError): but to except RuntimeError as TypeError: which is not what you want.

Django Cookies, how can I set them?

You could manually set the cookie, but depending on your use case (and if you might want to add more types of persistent/session data in future) it might make more sense to use Django's sessions feature. This will let you get and set variables tied internally to the user's session cookie. Cool thing about this is that if you want to store a lot of data tied to a user's session, storing it all in cookies will add a lot of weight to HTTP requests and responses. With sessions the session cookie is all that is sent back and forth (though there is the overhead on Django's end of storing the session data to keep in mind).

The way to check a HDFS directory's size?

Extending to Matt D and others answers, the command can be till Apache Hadoop 3.0.0

hadoop fs -du [-s] [-h] [-v] [-x] URI [URI ...]

It displays sizes of files and directories contained in the given directory or the length of a file in case it's just a file.

Options:

  • The -s option will result in an aggregate summary of file lengths being displayed, rather than the individual files. Without the -s option, the calculation is done by going 1-level deep from the given path.
  • The -h option will format file sizes in a human-readable fashion (e.g 64.0m instead of 67108864)
  • The -v option will display the names of columns as a header line.
  • The -x option will exclude snapshots from the result calculation. Without the -x option (default), the result is always calculated from all INodes, including all snapshots under the given path.

du returns three columns with the following format:

 +-------------------------------------------------------------------+ 
 | size  |  disk_space_consumed_with_all_replicas  |  full_path_name | 
 +-------------------------------------------------------------------+ 

##Example command:

hadoop fs -du /user/hadoop/dir1 \
    /user/hadoop/file1 \
    hdfs://nn.example.com/user/hadoop/dir1 

Exit Code: Returns 0 on success and -1 on error.

source: Apache doc

LINQ Group By into a Dictionary Object

I cannot comment on @Michael Blackburn, but I guess you got the downvote because the GroupBy is not necessary in this case.

Use it like:

var lookupOfCustomObjects = listOfCustomObjects.ToLookup(o=>o.PropertyName);
var listWithAllCustomObjectsWithPropertyName = lookupOfCustomObjects[propertyName]

Additionally, I've seen this perform way better than when using GroupBy().ToDictionary().

How to abort makefile if variable not set?

Use the shell error handling for unset variables (note the double $):

$ cat Makefile
foo:
        echo "something is set to $${something:?}"

$ make foo
echo "something is set to ${something:?}"
/bin/sh: something: parameter null or not set
make: *** [foo] Error 127


$ make foo something=x
echo "something is set to ${something:?}"
something is set to x

If you need a custom error message, add it after the ?:

$ cat Makefile
hello:
        echo "hello $${name:?please tell me who you are via \$$name}"

$ make hello
echo "hello ${name:?please tell me who you are via \$name}"
/bin/sh: name: please tell me who you are via $name
make: *** [hello] Error 127

$ make hello name=jesus
echo "hello ${name:?please tell me who you are via \$name}"
hello jesus

What is the difference between iterator and iterable and how to use them?

In addition to ColinD and Seeker answers.

In simple terms, Iterable and Iterator are both interfaces provided in Java's Collection Framework.

Iterable

A class has to implement the Iterable interface if it wants to have a for-each loop to iterate over its collection. However, the for-each loop can only be used to cycle through the collection in the forward direction and you won't be able to modify the elements in this collection. But, if all you want is to read the elements data, then it's very simple and thanks to Java lambda expression it's often one liner. For example:

iterableElements.forEach (x -> System.out.println(x) );

Iterator

This interface enables you to iterate over a collection, obtaining and removing its elements. Each of the collection classes provides a iterator() method that returns an iterator to the start of the collection. The advantage of this interface over iterable is that with this interface you can add, modify or remove elements in a collection. But, accessing elements needs a little more code than iterable. For example:

for (Iterator i = c.iterator(); i.hasNext(); ) {
       Element e = i.next();    //Get the element
       System.out.println(e);    //access or modify the element
}

Sources:

  1. Java Doc Iterable
  2. Java Doc Iterator

How to set opacity in parent div and not affect in child div?

I had the same problem and I fixed by setting transparent png image as background for the parent tag.

This is the 1px x 1px PNG Image that I have created with 60% Opacity of black background !

RGB to hex and hex to RGB

function hex2rgb(hex) {
  return ['0x' + hex[1] + hex[2] | 0, '0x' + hex[3] + hex[4] | 0, '0x' + hex[5] + hex[6] | 0];
}

Add JVM options in Tomcat

As Bhavik Shah says, you can do it in JAVA_OPTS, but the recommended way (as per catalina.sh) is to use CATALINA_OPTS:

#   CATALINA_OPTS   (Optional) Java runtime options used when the "start",
#                   "run" or "debug" command is executed.
#                   Include here and not in JAVA_OPTS all options, that should
#                   only be used by Tomcat itself, not by the stop process,
#                   the version command etc.
#                   Examples are heap size, GC logging, JMX ports etc.

#   JAVA_OPTS       (Optional) Java runtime options used when any command
#                   is executed.
#                   Include here and not in CATALINA_OPTS all options, that
#                   should be used by Tomcat and also by the stop process,
#                   the version command etc.
#                   Most options should go into CATALINA_OPTS.

Changing the selected option of an HTML Select element

Test this Demo

  1. Selecting Option based on its value

    var vals = [2,'c'];
    
    $('option').each(function(){
       var $t = $(this);
    
       for (var n=vals.length; n--; )
          if ($t.val() == vals[n]){
             $t.prop('selected', true);
             return;
          }
    });
    
  2. Selecting Option based on its text

    var vals = ['Two','CCC'];                   // what we're looking for is different
    
    $('option').each(function(){
       var $t = $(this);
    
       for (var n=vals.length; n--; )
          if ($t.text() == vals[n]){            // method used is different
             $t.prop('selected', true);
             return;
          }
    });
    

Supporting HTML

<select>
   <option value=""></option>
   <option value="1">One</option>
   <option value="2">Two</option>
   <option value="3">Three</option>
</select>

<select>
   <option value=""></option>
   <option value="a">AAA</option>
   <option value="b">BBB</option>
   <option value="c">CCC</option>
</select>

How to have jQuery restrict file types on upload?

For the front-end it is pretty convenient to put 'accept' attribute if you are using a file field.

Example:

<input id="file" type="file" name="file" size="30" 
       accept="image/jpg,image/png,image/jpeg,image/gif" 
/>

A couple of important notes:

How can I keep a container running on Kubernetes?

I did a hack by putting it in background:

[root@localhost ~]# kubectl run hello -it --image ubuntu -- bash &
[2] 128461

Exec on pod hello

[root@localhost ~]# kubectl exec -it hello -- whoami
root
[root@localhost ~]# kubectl exec -it hello -- hostname
hello

Getting a shell

[root@localhost ~]# kubectl exec -it hello -- bash
root@hello:/# ls
bin  boot  dev  etc  home  lib  lib32  lib64  libx32  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var

What is the best IDE for PHP?

All are good, but only Delphi for PHP (RadPHP 3.0) has a designer, drag and drop controls, GUI editeor, huge set of components including Zend Framework, Facebook, database, etc. components. It is the best in town.

RadPHP is the best of all; It has all the features the others have. Its designer is the best of all. You can design your page just like Dreamweaver (more than Dreamweaver).

If you use RadPHP you will feel like using ASP.NET with Visual Studio (but the language is PHP).

It's too bad only a few know about this.

How to Lock the data in a cell in excel using vba

Try using the Worksheet.Protect method, like so:

Sub ProtectActiveSheet()
    Dim ws As Worksheet
    Set ws = ActiveSheet
    ws.Protect DrawingObjects:=True, Contents:=True, _
        Scenarios:=True, Password="SamplePassword"
End Sub

You should, however, be concerned about including the password in your VBA code. You don't necessarily need a password if you're only trying to put up a simple barrier that keeps a user from making small mistakes like deleting formulas, etc.

Also, if you want to see how to do certain things in VBA in Excel, try recording a Macro and looking at the code it generates. That's a good way to get started in VBA.

How to convert a DataFrame back to normal RDD in pyspark?

@dapangmao's answer works, but it doesn't give the regular spark RDD, it returns a Row object. If you want to have the regular RDD format.

Try this:

rdd = df.rdd.map(tuple)

or

rdd = df.rdd.map(list)

How do I change selected value of select2 dropdown with JqGrid?

This should be even easier.

$("#e1").select2("val", ["View" ,"Modify"]);

But make sure the values which you pass are already present in the HTMl

jQuery - select the associated label element of a input field

You shouldn't rely on the order of elements by using prev or next. Just use the for attribute of the label, as it should correspond to the ID of the element you're currently manipulating:

var label = $("label[for='" + $(this).attr('id') + "']");

However, there are some cases where the label will not have for set, in which case the label will be the parent of its associated control. To find it in both cases, you can use a variation of the following:

var label = $('label[for="' + $(this).attr('id') + '"]');

if(label.length <= 0) {
    var parentElem = $(this).parent(),
        parentTagName = parentElem.get(0).tagName.toLowerCase();

    if(parentTagName == "label") {
        label = parentElem;
    }
}

I hope this helps!

Android studio logcat nothing to show

Logcat has a little icon to the right of logcat. You can use the icon to turn logcat on and off. I can usually make logcat active by clicking the icon (maybe several times).

How to catch exception correctly from http.request()?

Perhaps you can try adding this in your imports:

import 'rxjs/add/operator/catch';

You can also do:

return this.http.request(request)
  .map(res => res.json())
  .subscribe(
    data => console.log(data),
    err => console.log(err),
    () => console.log('yay')
  );

Per comments:

EXCEPTION: TypeError: Observable_1.Observable.throw is not a function

Similarly, for that, you can use:

import 'rxjs/add/observable/throw';

Setting PATH environment variable in OSX permanently

I've found that there are some files that may affect the $PATH variable in macOS (works for me, 10.11 El Capitan), listed below:

  1. As the top voted answer said, vi /etc/paths, which is recommended from my point of view.

  2. Also don't forget the /etc/paths.d directory, which contains files may affect the $PATH variable, set the git and mono-command path in my case. You can ls -l /etc/paths.d to list items and rm /etc/paths.d/path_you_dislike to remove items.

  3. If you're using a "bash" environment (the default Terminal.app, for example), you should check out ~/.bash_profile or ~/.bashrc. There may be not that file yet, but these two files have effects on the $PATH.

  4. If you're using a "zsh" environment (Oh-My-Zsh, for example), you should check out ~./zshrc instead of ~/.bash* thing.

And don't forget to restart all the terminal windows, then echo $PATH. The $PATH string will be PATH_SET_IN_3&4:PATH_SET_IN_1:PATH_SET_IN_2.

Noticed that the first two ways (/etc/paths and /etc/path.d) is in / directory which will affect all the accounts in your computer while the last two ways (~/.bash* or ~/.zsh*) is in ~/ directory (aka, /Users/yourusername/) which will only affect your account settings.

Read more: Mac OS X: Set / Change $PATH Variable - nixCraft

How can I check if my python object is a number?

Use Number from the numbers module to test isinstance(n, Number) (available since 2.6).

isinstance(n, numbers.Number)

Here it is in action with various kinds of numbers and one non-number:

>>> from numbers import Number
... from decimal import Decimal
... from fractions import Fraction
... for n in [2, 2.0, Decimal('2.0'), complex(2,0), Fraction(2,1), '2']:
...     print '%15s %s' % (n.__repr__(), isinstance(n, Number))
              2 True
            2.0 True
 Decimal('2.0') True
         (2+0j) True
 Fraction(2, 1) True
            '2' False

This is, of course, contrary to duck typing. If you are more concerned about how an object acts rather than what it is, perform your operations as if you have a number and use exceptions to tell you otherwise.

Difference between static STATIC_URL and STATIC_ROOT on Django

STATICFILES_DIRS: You can keep the static files for your project here e.g. the ones used by your templates.

STATIC_ROOT: leave this empty, when you do manage.py collectstatic, it will search for all the static files on your system and move them here. Your static file server is supposed to be mapped to this folder wherever it is located. Check it after running collectstatic and you'll find the directory structure django has built.

--------Edit----------------

As pointed out by @DarkCygnus, STATIC_ROOT should point at a directory on your filesystem, the folder should be empty since it will be populated by Django.

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

or

STATIC_ROOT = '/opt/web/project/static_files'

--------End Edit -----------------

STATIC_URL: '/static/' is usually fine, it's just a prefix for static files.

Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile (default-compile)

I renamed the .m2 directory, this didn't help yet, so I installed the newest sdk/jdk and restarted eclipse. This worked.

It seems an SDK was needed and I only had installed a JRE.

Which is weird, because eclipse worked on the same machine for a different older project.

I imported a second maven project, and Run/maven install did only complete after restarting eclipse. So maybe just a restart of eclipse was necessary.

Importing yet another project, and had to do maven install twice before it worked even though I had restarted eclipse.

How to bind Close command to a button

For .NET 4.5 SystemCommands class will do the trick (.NET 4.0 users can use WPF Shell Extension google - Microsoft.Windows.Shell or Nicholas Solution).

    <Window.CommandBindings>
        <CommandBinding Command="{x:Static SystemCommands.CloseWindowCommand}" 
                        CanExecute="CloseWindow_CanExec" 
                        Executed="CloseWindow_Exec" />
    </Window.CommandBindings>
    <!-- Binding Close Command to the button control -->
    <Button ToolTip="Close Window" Content="Close" Command="{x:Static SystemCommands.CloseWindowCommand}"/>

In the Code Behind you can implement the handlers like this:

    private void CloseWindow_CanExec(object sender, CanExecuteRoutedEventArgs e)
    {
        e.CanExecute = true;
    }

    private void CloseWindow_Exec(object sender, ExecutedRoutedEventArgs e)
    {
        SystemCommands.CloseWindow(this);
    }

How can I get current date in Android?

try with this link of code this is absolute correct answer for all cases all over date and time. or customize date and time as per need and requirement of app.

try with this link .try with this link

git clone error: RPC failed; curl 56 OpenSSL SSL_read: SSL_ERROR_SYSCALL, errno 10054

It's mentioned as SSL_ERROR_SYSCALL, errno 10054.

To resolve this SSL issue I went to .gitconfig file (which is located in c drive in my desktop) I changed sslverify to false and added my username and email id.

sslVerify = `false` //make sslVerify as false    
[user]
    name = `***<Enter your name>**`
    email = `**<Email Id>**`

How to redirect from one URL to another URL?

Since you tagged the question with javascript and html...

For a purely HTML solution, you can use a meta tag in the header to "refresh" the page, specifying a different URL:

<meta HTTP-EQUIV="REFRESH" content="0; url=http://www.yourdomain.com/somepage.html">

If you can/want to use JavaScript, you can set the location.href of the window:

<script type="text/javascript">
    window.location.href = "http://www.yourdomain.com/somepage.html";
</script>

How can I enable "URL Rewrite" Module in IIS 8.5 in Server 2012?

First, install the URL Rewrite from a download or from the Web Platform Installer. Second, restart IIS. And, finally, close IIS and open again. The last step worked for me.

Laravel: PDOException: could not find driver

You need to enable these extensions in the php.ini file

Before:

;extension=pdo_mysql
;extension=mysqli
;extension=pdo_sqlite
;extension=sqlite3

After:

extension=pdo_mysql
extension=mysqli
extension=pdo_sqlite
extension=sqlite3

It is advisable that you also activate the fileinfo extension, many packages require this.

How to convert a boolean array to an int array

Using numpy, you can do:

y = x.astype(int)

If you were using a non-numpy array, you could use a list comprehension:

y = [int(val) for val in x]

Verify ImageMagick installation

In Bash you can check if Imagick is an installed module:

$ php -m | grep imagick

If the response is blank it is not installed.

Adding a css class to select using @Html.DropDownList()

Looking at the controller, and learing a bit more about how MVC actually works, I was able to make sense of this.

My view was one of the auto-generated ones, and contained this line of code:

@Html.DropDownList("PriorityID", string.Empty)

To add html attributes, I needed to do something like this:

@Html.DropDownList("PriorityID", (IEnumerable<SelectListItem>)ViewBag.PriorityID, new { @class="dropdown" })

Thanks again to @Laurent for your help, I realise the question wasn't as clear as it could have been...

UPDATE:

A better way of doing this would be to use DropDownListFor where possible, that way you don't rely on a magic string for the name attribute

@Html.DropDownListFor(x => x.PriorityID, (IEnumerable<SelectListItem>)ViewBag.PriorityID, new { @class = "dropdown" })

NSAttributedString add text alignment

I was searching for the same issue and was able to center align the text in a NSAttributedString this way:

NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init] ;
[paragraphStyle setAlignment:NSTextAlignmentCenter];

NSMutableAttributedString *attribString = [[NSMutableAttributedString alloc]initWithString:string];
[attribString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [string length])];

How do I paste multi-line bash codes into terminal and run it all at once?

Add parenthesis around the lines. Example:

$ (
sudo apt-get update
dokku apps
dokku ps:stop APP # repeat to shut down each running app
sudo apt-get install -qq -y dokku herokuish sshcommand plugn
dokku ps:rebuildall # rebuilds all applications
)

ERROR 1115 (42000): Unknown character set: 'utf8mb4'

Open your mysql file any edit tool

find

/*!40101 SET NAMES utf8mb4 */;

change

/*!40101 SET NAMES utf8 */;

Save and upload ur mysql.

How to iterate over a string in C?

  • sizeof(source) is returning to you the size of a char*, not the length of the string. You should be using strlen(source), and you should move that out of the loop, or else you'll be recalculating the size of the string every loop.
  • By printing with the %s format modifier, printf is looking for a char*, but you're actually passing a char. You should use the %c modifier.

What is the right way to check for a null string in Objective-C?

You just check for nil

if(data[@"Bonds"]==nil){
  NSLog(@"it is nil");
}

or

if ([data[@"Bonds"] isKindOfClass:[NSNull class]]) {
    NSLog(@"it is null");
}

What causes the error "undefined reference to (some function)"?

It's a linker error. ld is the linker, so if you get an error message ending with "ld returned 1 exit status", that tells you that it's a linker error.

The error message tells you that none of the object files you're linking against contains a definition for avergecolumns. The reason for that is that the function you've defined is called averagecolumns (in other words: you misspelled the function name when calling the function (and presumably in the header file as well - otherwise you'd have gotten a different error at compile time)).

Proper use of the IDisposable interface

In the example you posted, it still doesn't "free the memory now". All memory is garbage collected, but it may allow the memory to be collected in an earlier generation. You'd have to run some tests to be sure.


The Framework Design Guidelines are guidelines, and not rules. They tell you what the interface is primarily for, when to use it, how to use it, and when not to use it.

I once read code that was a simple RollBack() on failure utilizing IDisposable. The MiniTx class below would check a flag on Dispose() and if the Commit call never happened it would then call Rollback on itself. It added a layer of indirection making the calling code a lot easier to understand and maintain. The result looked something like:

using( MiniTx tx = new MiniTx() )
{
    // code that might not work.

    tx.Commit();
} 

I've also seen timing / logging code do the same thing. In this case the Dispose() method stopped the timer and logged that the block had exited.

using( LogTimer log = new LogTimer("MyCategory", "Some message") )
{
    // code to time...
}

So here are a couple of concrete examples that don't do any unmanaged resource cleanup, but do successfully used IDisposable to create cleaner code.

Forcing label to flow inline with input that they label

<style>
.nowrap {
    white-space: nowrap;
}
</style>

...

<label for="id1" class="nowrap">label1:
    <input type="text" id="id1"/>
</label>

Wrap your inputs within the label tag

How do I iterate through children elements of a div using jQuery?

It is also possible to iterate through all elements within a specific context, no mattter how deeply nested they are:

$('input', $('#mydiv')).each(function () {
    console.log($(this)); //log every element found to console output
});

The second parameter $('#mydiv') which is passed to the jQuery 'input' Selector is the context. In this case the each() clause will iterate through all input elements within the #mydiv container, even if they are not direct children of #mydiv.

How to use glOrtho() in OpenGL?

Have a look at this picture: Graphical Projections enter image description here

The glOrtho command produces an "Oblique" projection that you see in the bottom row. No matter how far away vertexes are in the z direction, they will not recede into the distance.

I use glOrtho every time I need to do 2D graphics in OpenGL (such as health bars, menus etc) using the following code every time the window is resized:

glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0f, windowWidth, windowHeight, 0.0f, 0.0f, 1.0f);

This will remap the OpenGL coordinates into the equivalent pixel values (X going from 0 to windowWidth and Y going from 0 to windowHeight). Note that I've flipped the Y values because OpenGL coordinates start from the bottom left corner of the window. So by flipping, I get a more conventional (0,0) starting at the top left corner of the window rather.

Note that the Z values are clipped from 0 to 1. So be careful when you specify a Z value for your vertex's position, it will be clipped if it falls outside that range. Otherwise if it's inside that range, it will appear to have no effect on the position except for Z tests.

Static Vs. Dynamic Binding in Java

With the static method in the parent and child class: Static Binding

public class test1 {   
    public static void main(String args[]) {
        parent pc = new child(); 
        pc.start(); 
    }
}

class parent {
    static public void start() {
        System.out.println("Inside start method of parent");
    }
}

class child extends parent {

    static public void start() {
        System.out.println("Inside start method of child");
    }
}

// Output => Inside start method of parent

Dynamic Binding :

public class test1 {   
    public static void main(String args[]) {
        parent pc = new child();
        pc.start(); 
    }
}

class parent {
   public void start() {
        System.out.println("Inside start method of parent");
    }
}

class child extends parent {

   public void start() {
        System.out.println("Inside start method of child");
    }
}

// Output => Inside start method of child

Filtering Pandas DataFrames on dates

Previous answer is not correct in my experience, you can't pass it a simple string, needs to be a datetime object. So:

import datetime 
df.loc[datetime.date(year=2014,month=1,day=1):datetime.date(year=2014,month=2,day=1)]

Shell Scripting: Using a variable to define a path

To add to the above correct answer :- For my case in shell, this code worked (working on sqoop)

ROOT_PATH="path/to/the/folder"
--options-file  $ROOT_PATH/query.txt

How to get the file-path of the currently executing javascript code

Within the script:

var scripts = document.getElementsByTagName("script"),
    src = scripts[scripts.length-1].src;

This works because the browser loads and executes scripts in order, so while your script is executing, the document it was included in is sure to have your script element as the last one on the page. This code of course must be 'global' to the script, so save src somewhere where you can use it later. Avoid leaking global variables by wrapping it in:

(function() { ... })();

how to programmatically fake a touch event to a UIButton?

It turns out that

[buttonObj sendActionsForControlEvents:UIControlEventTouchUpInside];

got me exactly what I needed, in this case.

EDIT: Don't forget to do this in the main thread, to get results similar to a user-press.


For Swift 3:

buttonObj.sendActions(for: .touchUpInside)

Border length smaller than div width?

You can use a linear gradient:

_x000D_
_x000D_
div {_x000D_
    width:100px;_x000D_
    height:50px;_x000D_
    display:block;_x000D_
    background-image: linear-gradient(to right, #000 1px, rgba(255,255,255,0) 1px), linear-gradient(to left, #000 0.1rem, rgba(255,255,255,0) 1px);_x000D_
 background-position: bottom;_x000D_
 background-size: 100% 25px;_x000D_
 background-repeat: no-repeat;_x000D_
    border-bottom: 1px solid #000;_x000D_
    border-top: 1px solid red;_x000D_
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

How to reload / refresh model data from the server programmatically?

Before I show you how to reload / refresh model data from the server programmatically? I have to explain for you the concept of Data Binding. This is an extremely powerful concept that will truly revolutionize the way you develop. So may be you have to read about this concept from this link or this seconde link in order to unterstand how AngularjS work.

now I'll show you a sample example that exaplain how can you update your model from server.

HTML Code:

<div ng-controller="PersonListCtrl">
    <ul>
        <li ng-repeat="person in persons">
            Name: {{person.name}}, Age {{person.age}}
        </li>
    </ul>
   <button ng-click="updateData()">Refresh Data</button>
</div>

So our controller named: PersonListCtrl and our Model named: persons. go to your Controller js in order to develop the function named: updateData() that will be invoked when we are need to update and refresh our Model persons.

Javascript Code:

app.controller('adsController', function($log,$scope,...){

.....

$scope.updateData = function(){
$http.get('/persons').success(function(data) {
       $scope.persons = data;// Update Model-- Line X
     });
}

});

Now I explain for you how it work: when user click on button Refresh Data, the server will call to function updateData() and inside this function we will invoke our web service by the function $http.get() and when we have the result from our ws we will affect it to our model (Line X).Dice that affects the results for our model, our View of this list will be changed with new Data.

jquery ajax get responsetext from http url

Actually, you can make cross domain requests with i.e. Firefox, se this for a overview: http://ajaxian.com/archives/cross-site-xmlhttprequest-in-firefox-3

Webkit and IE8 supports it as well in some fashion.

Hiding elements in responsive layout?

Additional CSS Remove Sidebar from all pages in Mobile view:

@media only screen and (max-width:767px)
{
#secondary {
display: none;
}
}

Closing Excel Application using VBA

You can try out

ThisWorkbook.Save
ThisWorkbook.Saved = True
Application.Quit

How to run Conda?

The main point is that as of December 2018 it's Scripts not bin.


Updating $PATH in "git bash for windows"

Use one of these:
export PATH=$USERPROFILE/AppData/Local/Continuum/anaconda2/Scripts/:$PATH
export PATH=$USERPROFILE/AppData/Local/Continuum/anaconda3/Scripts/:$PATH


Updating $PATH in the windows default command line

Use one of these:
SET PATH=%USERPROFILE%\AppData\Local\Continuum\anaconda2\Scripts\;%PATH%
SET PATH=%USERPROFILE%\AppData\Local\Continuum\anaconda3\Scripts\;%PATH%


Updating $PATH in Linux

Change /app to your installation location. If you installed anaconda change Miniconda to Anaconda. Also, check for Script vs. bin,.

export PATH="/app/Miniconda/bin:$PATH"

You may need to run set -a before setting the path, I think this is important if you're setting the path in a script. For example if you have your export command in a file called set_my_path.sh, I think you'd need to do set -a; source("set_my_path.sh").

The set -a will make your changes to the path persist for your session, but they are still not permanent.

For a more permanent solution add the command to ~/.bashrc. The installers may offer to add something like this to your ~/.bashrc file, but you can do it too (or comment it out to undo it).


General Observations:

Background: I installed the 64 bit versions of Anaconda 2 and 3 recently on my Windows 10 machine following the recommended installation steps in December of 2018.

  • Adding conda also enables ipython, which works much better in the native Windows command line
  • Following the strongly recommended installation does not add conda or ipython to the path
  • Anaconda 3 doesn't seem to install a command prompt application, but Anaconda 2 did have a command prompt application
  • The /bin folder seems to have been replaced with Scripts
  • Poking around in the Scripts folder is interesting, maybe the Anaconda command prompt application is in there somewhere.

How to replace all special character into a string using C#

Assume you want to replace symbols which are not digits or letters (and _ character as @Guffa correctly pointed):

string input = "Hello@Hello&Hello(Hello)";
string result = Regex.Replace(input, @"[^\w\d]", ",");
// Hello,Hello,Hello,Hello,

You can add another symbols which should not be replaced. E.g. if you want white space symbols to stay, then just add \s to pattern: \[^\w\d\s]

In SQL Server, what does "SET ANSI_NULLS ON" mean?

It means that no rows will be returned if @region is NULL, when used in your first example, even if there are rows in the table where Region is NULL.

When ANSI_NULLS is on (which you should always set on anyway, since the option to not have it on is going to be removed in the future), any comparison operation where (at least) one of the operands is NULL produces the third logic value - UNKNOWN (as opposed to TRUE and FALSE).

UNKNOWN values propagate through any combining boolean operators if they're not already decided (e.g. AND with a FALSE operand or OR with a TRUE operand) or negations (NOT).

The WHERE clause is used to filter the result set produced by the FROM clause, such that the overall value of the WHERE clause must be TRUE for the row to not be filtered out. So, if an UNKNOWN is produced by any comparison, it will cause the row to be filtered out.


@user1227804's answer includes this quote:

If both sides of the comparison are columns or compound expressions, the setting does not affect the comparison.

from SET ANSI_NULLS*

However, I'm not sure what point it's trying to make, since if two NULL columns are compared (e.g. in a JOIN), the comparison still fails:

create table #T1 (
    ID int not null,
    Val1 varchar(10) null
)
insert into #T1(ID,Val1) select 1,null

create table #T2 (
    ID int not null,
    Val1 varchar(10) null
)
insert into #T2(ID,Val1) select 1,null

select * from #T1 t1 inner join #T2 t2 on t1.ID = t2.ID and t1.Val1 = t2.Val1

The above query returns 0 rows, whereas:

select * from #T1 t1 inner join #T2 t2 on t1.ID = t2.ID and (t1.Val1 = t2.Val1 or t1.Val1 is null and t2.Val1 is null)

Returns one row. So even when both operands are columns, NULL does not equal NULL. And the documentation for = doesn't have anything to say about the operands:

When you compare two NULL expressions, the result depends on the ANSI_NULLS setting:

If ANSI_NULLS is set to ON, the result is NULL1, following the ANSI convention that a NULL (or unknown) value is not equal to another NULL or unknown value.

If ANSI_NULLS is set to OFF, the result of NULL compared to NULL is TRUE.

Comparing NULL to a non-NULL value always results in FALSE2.

However, both 1 and 2 are incorrect - the result of both comparisons is UNKNOWN.


*The cryptic meaning of this text was finally discovered years later. What it actually means is that, for those comparisons, the setting has no effect and it always acts as if the setting were ON. Would have been clearer if it had stated that SET ANSI_NULLS OFF was the setting that had no affect.

How do I write a batch script that copies one directory to another, replaces old files?

Have you considered using the "xcopy" command?

The xcopy command will do all that for you.

127 Return code from $?

A shell convention is that a successful executable should exit with the value 0. Anything else can be interpreted as a failure of some sort, on part of bash or the executable you that just ran. See also $PIPESTATUS and the EXIT STATUS section of the bash man page:

   For  the shell’s purposes, a command which exits with a zero exit status has succeeded.  An exit status
   of zero indicates success.  A non-zero exit status indicates failure.  When a command terminates  on  a
   fatal signal N, bash uses the value of 128+N as the exit status.
   If  a command is not found, the child process created to execute it returns a status of 127.  If a com-
   mand is found but is not executable, the return status is 126.

   If a command fails because of an error during expansion or redirection, the exit status is greater than
   zero.

   Shell  builtin  commands  return  a  status of 0 (true) if successful, and non-zero (false) if an error
   occurs while they execute.  All builtins return an exit status of 2 to indicate incorrect usage.

   Bash itself returns the exit status of the last command executed, unless  a  syntax  error  occurs,  in
   which case it exits with a non-zero value.  See also the exit builtin command below.

Change background of LinearLayout in Android

Use this code, where li is the LinearLayout: li.setBackgroundColor(Color.parseColor("#ffff00"));

Java string to date conversion

Simple two formatters we have used:

  1. Which format date do we want?
  2. Which format date is actually present?

We parse the full date to time format:

date="2016-05-06 16:40:32";

public static String setDateParsing(String date) throws ParseException {

    // This is the format date we want
    DateFormat mSDF = new SimpleDateFormat("hh:mm a");

    // This format date is actually present
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-mm-dd hh:mm");
    return mSDF.format(formatter.parse(date));
}

Entity Framework .Remove() vs. .DeleteObject()

It's not generally correct that you can "remove an item from a database" with both methods. To be precise it is like so:

  • ObjectContext.DeleteObject(entity) marks the entity as Deleted in the context. (It's EntityState is Deleted after that.) If you call SaveChanges afterwards EF sends a SQL DELETE statement to the database. If no referential constraints in the database are violated the entity will be deleted, otherwise an exception is thrown.

  • EntityCollection.Remove(childEntity) marks the relationship between parent and childEntity as Deleted. If the childEntity itself is deleted from the database and what exactly happens when you call SaveChanges depends on the kind of relationship between the two:

    • If the relationship is optional, i.e. the foreign key that refers from the child to the parent in the database allows NULL values, this foreign will be set to null and if you call SaveChanges this NULL value for the childEntity will be written to the database (i.e. the relationship between the two is removed). This happens with a SQL UPDATE statement. No DELETE statement occurs.

    • If the relationship is required (the FK doesn't allow NULL values) and the relationship is not identifying (which means that the foreign key is not part of the child's (composite) primary key) you have to either add the child to another parent or you have to explicitly delete the child (with DeleteObject then). If you don't do any of these a referential constraint is violated and EF will throw an exception when you call SaveChanges - the infamous "The relationship could not be changed because one or more of the foreign-key properties is non-nullable" exception or similar.

    • If the relationship is identifying (it's necessarily required then because any part of the primary key cannot be NULL) EF will mark the childEntity as Deleted as well. If you call SaveChanges a SQL DELETE statement will be sent to the database. If no other referential constraints in the database are violated the entity will be deleted, otherwise an exception is thrown.

I am actually a bit confused about the Remarks section on the MSDN page you have linked because it says: "If the relationship has a referential integrity constraint, calling the Remove method on a dependent object marks both the relationship and the dependent object for deletion.". This seems unprecise or even wrong to me because all three cases above have a "referential integrity constraint" but only in the last case the child is in fact deleted. (Unless they mean with "dependent object" an object that participates in an identifying relationship which would be an unusual terminology though.)

Checking if a string is empty or null in Java

This way you check if the string is not null and not empty, also considering the empty spaces:

boolean isEmpty = str == null || str.trim().length() == 0;
if (isEmpty) {
    // handle the validation
}

How do I create a new Git branch from an old commit?

git checkout -b NEW_BRANCH_NAME COMMIT_ID

This will create a new branch called 'NEW_BRANCH_NAME' and check it out.

("check out" means "to switch to the branch")

git branch NEW_BRANCH_NAME COMMIT_ID

This just creates the new branch without checking it out.


in the comments many people seem to prefer doing this in two steps. here's how to do so in two steps:

git checkout COMMIT_ID
# you are now in the "detached head" state
git checkout -b NEW_BRANCH_NAME

How to avoid "cannot load such file -- utils/popen" from homebrew on OSX

To restore your Homebrew setup try this:

cd /usr/local/Homebrew/Library && git stash && git clean -d -f && git reset --hard && git pull

How to set a CMake option() at command line

Delete the CMakeCache.txt file and try this:

cmake -G %1 -DBUILD_SHARED_LIBS=ON -DBUILD_STATIC_LIBS=ON -DBUILD_TESTS=ON ..

You have to enter all your command-line definitions before including the path.

Reading HTML content from a UIWebView

I use a swift extension like this:

extension UIWebView {
    var htmlContent:String? {
        return self.stringByEvaluatingJavaScript(from: "document.documentElement.outerHTML")
    }

}

What does it mean when a PostgreSQL process is "idle in transaction"?

The PostgreSQL manual indicates that this means the transaction is open (inside BEGIN) and idle. It's most likely a user connected using the monitor who is thinking or typing. I have plenty of those on my system, too.

If you're using Slony for replication, however, the Slony-I FAQ suggests idle in transaction may mean that the network connection was terminated abruptly. Check out the discussion in that FAQ for more details.

NoClassDefFoundError while trying to run my jar with java.exe -jar...what's wrong?

i had the same problem with my jar the solution

  1. Create the MANIFEST.MF file:

Manifest-Version: 1.0

Sealed: true

Class-Path: . lib/jarX1.jar lib/jarX2.jar lib/jarX3.jar

Main-Class: com.MainClass

  1. Right click on project, Select Export.

select export all outpout folders for checked project

  1. select using existing manifest from workspace and select the MANIFEST.MF file

This worked for me :)

Port 443 in use by "Unable to open process" with PID 4

I had the same problem when I installed xampp on Windows 7. I installed Windows server and Web Deployment Agent Service (MsDepSvc.exe) which uses port 80. So I had an error PID 4 listening to port 80 when I ran apache.

Solution

Open task manager: (Ctrl+Shift+Esc) then find "MsDepSvc.exe" and disable it. Finally restart xampp

ref: http://www.honk.com.au/index.php/2010/10/20/windows-7-pid-4-listening-port-80-apache-cannot-star/

Add Whatsapp function to website, like sms, tel

Rahul's answer gives me an error: You seem to be trying to send a WhatsApp message to a phone number that is not registered with WhatsApp..., even though I'm sending it to a registered WhatsApp number.

This, however works:

<li><a href="intent:0123456789#Intent;scheme=smsto;package=com.whatsapp;action=android.intent.action.SENDTO;end"><i class="fa fa-whatsapp"></i>+237 655 421 621</li>

How do I get the last character of a string?

public char LastChar(String a){
    return a.charAt(a.length() - 1);
}

How to send JSON instead of a query string with $.ajax?

If you are sending this back to asp.net and need the data in request.form[] then you'll need to set the content type to "application/x-www-form-urlencoded; charset=utf-8"

Original post here

Secondly get rid of the Datatype, if your not expecting a return the POST will wait for about 4 minutes before failing. See here

How can I add spaces between two <input> lines using CSS?

You can also wrap your text in label fields, so your form will be more self-explainable semantically.

Just remember to float labels and inputs to the left and to add a specific width to them, and the containing form. Then you can add margins to both of them, to adjust the spacing between the lines (you understand, of course, that this is a pretty minimal markup that expects content to be as big as to some limit).

That way you wont have to add any more elements, just the label-input pairs, all of them wrapped in a form element.

For example:

<form>
<label for="txtName">Name</label>
<input id"txtName" type="text">
<label for="txtEmail">Email</label>
<input id"txtEmail" type="text">
<label for="txtAddress">Address</label>
<input id"txtAddress" type="text">
...
<input type="submit" value="Submit The Form">
</form>

And the css will be:

form{
float:left; /*to clear the floats of inner elements,usefull if you wanna add a border or background image*/
width:300px;
}
label{
float:left;
width:150px;
margin-bottom:10px; /*or whatever you want the spacing to be*/
}
input{
float:left;
width:150px;
margin-bottom:10px; /*or whatever you want the spacing to be*/
}

How to pass props to {this.props.children}

You no longer need {this.props.children}. Now you can wrap your child component using render in Route and pass your props as usual:

<BrowserRouter>
  <div>
    <ul>
      <li><Link to="/">Home</Link></li>
      <li><Link to="/posts">Posts</Link></li>
      <li><Link to="/about">About</Link></li>
    </ul>

    <hr/>

    <Route path="/" exact component={Home} />
    <Route path="/posts" render={() => (
      <Posts
        value1={1}
        value2={2}
        data={this.state.data}
      />
    )} />
    <Route path="/about" component={About} />
  </div>
</BrowserRouter>

JSON parse error: Can not construct instance of java.time.LocalDate: no String-argument constructor/factory method to deserialize from String value

I have just wrestled with this for 3 hours. I credit the answer from Dherik (Bonus material about AMQP) for bringing me within striking distance of MY answer, YMMV.

I registered the JavaTimeModule in my object mapper in my SpringBootApplication like this:

@Bean
@Primary
public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
    ObjectMapper objectMapper = builder.build();
    objectMapper.registerModule(new JavaTimeModule());
    return objectMapper;
}

However my Instants that were coming over the STOMP connection were still not deserialising. Then I realised I had inadvertantly created a MappingJackson2MessageConverter which creates a second ObjectMapper. So I guess the moral of the story is: Are you sure you have adjusted all your ObjectMappers? In my case I replaced the MappingJackson2MessageConverter.objectMapper with the outer version that has the JavaTimeModule registered, and all is well:

@Autowired
ObjectMapper objectMapper;

@Bean
public WebSocketStompClient webSocketStompClient(WebSocketClient webSocketClient,
        StompSessionHandler stompSessionHandler) {
    WebSocketStompClient webSocketStompClient = new WebSocketStompClient(webSocketClient);
    MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
    converter.setObjectMapper(objectMapper);
    webSocketStompClient.setMessageConverter(converter);
    webSocketStompClient.connect("http://localhost:8080/myapp", stompSessionHandler);
    return webSocketStompClient;
}

Oracle SQL Developer: Failure - Test failed: The Network Adapter could not establish the connection?

You can locate a file named listener.ora under the installation folder oraclexe\app\oracle\product\11.2.0\server\network\ADMIN It contains the following entries

SID_LIST_LISTENER =
  (SID_LIST =
    (SID_DESC =
      (SID_NAME = PLSExtProc)
      (ORACLE_HOME = C:\oraclexe\app\oracle\product\11.2.0\server)
      (PROGRAM = extproc)
    )
    (SID_DESC =
      (SID_NAME = CLRExtProc)
      (ORACLE_HOME = C:\oraclexe\app\oracle\product\11.2.0\server)
      (PROGRAM = extproc)
    )
  )

LISTENER =
  (DESCRIPTION_LIST =
    (DESCRIPTION =
      (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1))
      (ADDRESS = (PROTOCOL = TCP)(HOST = Codemaker-PC)(PORT = 1521))
    )
  )

DEFAULT_SERVICE_LISTENER = (XE)

You should verify the HOST (Here it is Codemaker-PC) should be the computer name. If it's not correct the change it as computer name.

then try the following command on the command prompt run as administrator,

lsnrctl start

How to uninstall Ruby from /usr/local?

It's not a good idea to uninstall 1.8.6 if it's in /usr/bin. That is owned by the OS and is expected to be there.

If you put /usr/local/bin in your PATH before /usr/bin then things you have installed in /usr/local/bin will be found before any with the same name in /usr/bin, effectively overwriting or updating them, without actually doing so. You can still reach them by explicitly using /usr/bin in your #! interpreter invocation line at the top of your code.

@Anurag recommended using RVM, which I'll second. I use it to manage 1.8.7 and 1.9.1 in addition to the OS's 1.8.6.

In a simple to understand explanation, what is Runnable in Java?

A Runnable is basically a type of class (Runnable is an Interface) that can be put into a thread, describing what the thread is supposed to do.

The Runnable Interface requires of the class to implement the method run() like so:

public class MyRunnableTask implements Runnable {
     public void run() {
         // do stuff here
     }
}

And then use it like this:

Thread t = new Thread(new MyRunnableTask());
t.start();

If you did not have the Runnable interface, the Thread class, which is responsible to execute your stuff in the other thread, would not have the promise to find a run() method in your class, so you could get errors. That is why you need to implement the interface.

Advanced: Anonymous Type

Note that you do not need to define a class as usual, you can do all of that inline:

Thread t = new Thread(new Runnable() {
    public void run() {
        // stuff here
    }
});
t.start();

This is similar to the above, only you don't create another named class.

T-SQL string replace in Update

If anyone cares, for NTEXT, use the following format:

SELECT CAST(REPLACE(CAST([ColumnValue] AS NVARCHAR(MAX)),'find','replace') AS NTEXT) 
    FROM [DataTable]

SSIS Connection Manager Not Storing SQL Password

There is easy way of doing this. I don't know why people are giving complicated answers.

Double click SSIS package. Then go to connection manager, select DestinationConnectionOLDB and then add password next to login field.

Example: Data Source=SysproDB1;User ID=test;password=test;Initial Catalog=ASBuiltDW;Provider=SQLNCLI11;Auto Translate=false;

Do same for SourceConnectionOLDB.

Error: Could not find gradle wrapper within Android SDK. Might need to update your Android SDK - Android

  1. If you have android studio installed within your system, then copy the templates folder from C:\Program Files\Android\Android Studio\plugins\android\lib\templates
  2. Paste it in the folder C:\Users\<user-name>\AppData\Local\Android\sdk\tools
  3. Run the command: ionic build android

All necessary jar files will be downloaded and apk file for the application will be generated.

Note: Set environment variables to C:\Users\<user-name>\AppData\Local\Android\sdk\tools. Also set user-name to your current username.

New warnings in iOS 9: "all bitcode will be dropped"

Method canOpenUrl is in iOS 9 (due to privacy) changed and is not free to use any more. Your banner provider checks for installed apps so that they do not show banners for an app that is already installed.

That gives all the log statements like

-canOpenURL: failed for URL: "kindle://home" - error: "This app is not allowed to query for scheme kindle"

The providers should update their logic for this.

If you need to query for installed apps/available schemes you need to add them to your info.plist file.

Add the key 'LSApplicationQueriesSchemes' to your plist as an array. Then add strings in that array like 'kindle'.

Of course this is not really an option for the banner ads (since those are dynamic), but you can still query that way for your own apps or specific other apps like Twitter and Facebook.

Documentation of the canOpenUrl: method canOpenUrl:

Documentation about the LSApplicationQueriesSchemes key

Laravel migration default value

You can simple put the default value using default(). See the example

 $table->enum('is_approved', array('0','1'))->default('0');

I have used enum here and the default value is 0.

Can I position an element fixed relative to parent?

With multiple divs I managed to get a fixed-y and absolute-x divs. In my case I needed a div on left and right sides, aligned to a centered 1180px width div.

    <div class="parentdiv" style="
        background: transparent;
        margin: auto;
        width: 100%;
        max-width: 1220px;
        height: 10px;
        text-align: center;">
        <div style="
            position: fixed;
            width: 100%;
            max-width: 1220px;">
            <div style="
                position: absolute;
                background: black;
                height: 20px;
                width: 20px;
                left: 0;">
            </div>
            <div style="
                width: 20px;
                height: 20px;
                background: blue;
                position: absolute;                                           
                right: 0;">
            </div>
        </div>
    </div>

How to insert a new key value pair in array in php?

Try this:

foreach($array as $k => $obj) { 
    $obj->{'newKey'} = "value"; 
}

How to set env variable in Jupyter notebook

You can setup environment variables in your code as follows:

import sys,os,os.path
sys.path.append(os.path.expanduser('~/code/eol_hsrl_python'))
os.environ['HSRL_INSTRUMENT']='gvhsrl'
os.environ['HSRL_CONFIG']=os.path.expanduser('~/hsrl_config')

This if of course a temporary fix, to get a permanent one, you probably need to export the variables into your ~.profile, more information can be found here

JPA: unidirectional many-to-one and cascading delete

Use this way to delete only one side

    @ManyToOne(cascade=CascadeType.PERSIST, fetch = FetchType.LAZY)
//  @JoinColumn(name = "qid")
    @JoinColumn(name = "qid", referencedColumnName = "qid", foreignKey = @ForeignKey(name = "qid"), nullable = false)
    // @JsonIgnore
    @JsonBackReference
    private QueueGroup queueGroup;

C#: HttpClient with POST parameters

A cleaner alternative would be to use a Dictionary to handle parameters. They are key-value pairs after all.

private static readonly HttpClient httpclient;

static MyClassName()
{
    // HttpClient is intended to be instantiated once and re-used throughout the life of an application. 
    // Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads. 
    // This will result in SocketException errors.
    // https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=netframework-4.7.1
    httpclient = new HttpClient();    
} 

var url = "http://myserver/method";
var parameters = new Dictionary<string, string> { { "param1", "1" }, { "param2", "2" } };
var encodedContent = new FormUrlEncodedContent (parameters);

var response = await httpclient.PostAsync (url, encodedContent).ConfigureAwait (false);
if (response.StatusCode == HttpStatusCode.OK) {
    // Do something with response. Example get content:
    // var responseContent = await response.Content.ReadAsStringAsync ().ConfigureAwait (false);
}

Also dont forget to Dispose() httpclient, if you dont use the keyword using

As stated in the Remarks section of the HttpClient class in the Microsoft docs, HttpClient should be instantiated once and re-used.

Edit:

You may want to look into response.EnsureSuccessStatusCode(); instead of if (response.StatusCode == HttpStatusCode.OK).

You may want to keep your httpclient and dont Dispose() it. See: Do HttpClient and HttpClientHandler have to be disposed?

Edit:

Do not worry about using .ConfigureAwait(false) in .NET Core. For more details look at https://blog.stephencleary.com/2017/03/aspnetcore-synchronization-context.html

How do I get the last character of a string using an Excel function?

No need to apologize for asking a question! Try using the RIGHT function. It returns the last n characters of a string.

=RIGHT(A1, 1)

What is tempuri.org?

Note that namespaces that are in the format of a valid Web URL don't necessarily need to be dereferenced i.e. you don't need to serve actual content at that URL. All that matters is that the namespace is globally unique.

Get everything after the dash in a string in JavaScript

myString.split('-').splice(1).join('-')

Assign static IP to Docker container

This works for me.

Create a network with docker network create --subnet=172.17.0.0/16 selnet

Run docker image docker run --net selnet --ip 172.18.0.2 hub

At first, I got

docker: Error response from daemon: Invalid address 172.17.0.2: It does not belong to any of this network's subnets.
ERRO[0000] error waiting for container: context canceled

Solution: Increased the 2nd quadruple of the IP [.18. instead of .17.]

How to create a new img tag with JQuery, with the src and id from a JavaScript object?

You save some bytes by avoiding the .attr altogether by passing the properties to the jQuery constructor:

var img = $('<img />',
             { id: 'Myid',
               src: 'MySrc.gif', 
               width: 300
             })
              .appendTo($('#YourDiv'));

Make absolute positioned div expand parent div height

Try this, it was worked for me

.child {
    width: 100%;
    position: absolute;
    top: 0px;
    bottom: 0px;
    z-index: 1;
}

It will set child height to parent height

Read line with Scanner

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication1;

import java.io.File;
import java.util.Scanner;

/**
 *
 * @author zsagga
 */
class openFile {
        private Scanner x ; 
        int count = 0 ; 
        String path = "C:\\Users\\zsagga\\Documents\\NetBeansProjects\\JavaApplication1\\src\\javaapplication1\\Readthis.txt"; 


    public void openFile() {
//                System.out.println("I'm Here");
        try {
            x = new Scanner(new File(path)); 

        } 
        catch (Exception e) {
            System.out.println("Could not find a file");
        }
    }

    public void readFile() {

        while (x.hasNextLine()){
            count ++ ;
            x.nextLine();     
        }
        System.out.println(count);
    }

    public void closeFile() {
        x.close();
    }
}

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication1;

/**
 *
 * @author zsagga
 */
public class JavaApplication1 {

    public static void main(String[] args) {
        // TODO code application logic here
        openFile r =  new openFile(); 
        r.openFile(); 
        r.readFile();
        r.closeFile(); 

    }
}

Android: Background Image Size (in Pixel) which Support All Devices

Check this. This image will show for all icon size for different screen sizes

Size

Go To Definition: "Cannot navigate to the symbol under the caret."

Ran into this problem when using F12 to try and go to a method definition.

All of the mentioned items (except the /resetuserdata - which I didn't try because it would be a pain to recover from) didn't work.

What did work for me:

  • Exit Visual Studio
  • From a Command Prompt, go to the folder for your solution and run the following code (this deletes ALL bin and obj folders in your solution):

    FOR /F "tokens=*" %%G IN ('DIR /B /AD /S bin') DO RMDIR /S /Q "%%G"
    FOR /F "tokens=*" %%G IN ('DIR /B /AD /S obj') DO RMDIR /S /Q "%%G"
    
  • Restart Visual Studio. Opening the solution should take a bit longer as it now rebuilds the obj folders.

After doing this F12 worked!

As a side note, I normally place this in a batch file in my solution's folder, along side the .sln file. This makes it easy to run later!

Git merge with force overwrite

Not really related to this answer, but I'd ditch git pull, which just runs git fetch followed by git merge. You are doing three merges, which is going to make your Git run three fetch operations, when one fetch is all you will need. Hence:

git fetch origin   # update all our origin/* remote-tracking branches

git checkout demo         # if needed -- your example assumes you're on it
git merge origin/demo     # if needed -- see below

git checkout master
git merge origin/master

git merge -X theirs demo   # but see below

git push origin master     # again, see below

Controlling the trickiest merge

The most interesting part here is git merge -X theirs. As root545 noted, the -X options are passed on to the merge strategy, and both the default recursive strategy and the alternative resolve strategy take -X ours or -X theirs (one or the other, but not both). To understand what they do, though, you need to know how Git finds, and treats, merge conflicts.

A merge conflict can occur within some file1 when the base version differs from both the current (also called local, HEAD, or --ours) version and the other (also called remote or --theirs) version of that same file. That is, the merge has identified three revisions (three commits): base, ours, and theirs. The "base" version is from the merge base between our commit and their commit, as found in the commit graph (for much more on this, see other StackOverflow postings). Git has then found two sets of changes: "what we did" and "what they did". These changes are (in general) found on a line-by-line, purely textual basis. Git has no real understanding of file contents; it is merely comparing each line of text.

These changes are what you see in git diff output, and as always, they have context as well. It's possible that things we changed are on different lines from things they changed, so that the changes seem like they would not collide, but the context has also changed (e.g., due to our change being close to the top or bottom of the file, so that the file runs out in our version, but in theirs, they have also added more text at the top or bottom).

If the changes happen on different lines—for instance, we change color to colour on line 17 and they change fred to barney on line 71—then there is no conflict: Git simply takes both changes. If the changes happen on the same lines, but are identical changes, Git takes one copy of the change. Only if the changes are on the same lines, but are different changes, or that special case of interfering context, do you get a modify/modify conflict.

The -X ours and -X theirs options tell Git how to resolve this conflict, by picking just one of the two changes: ours, or theirs. Since you said you are merging demo (theirs) into master (ours) and want the changes from demo, you would want -X theirs.

Blindly applying -X, however, is dangerous. Just because our changes did not conflict on a line-by-line basis does not mean our changes do not actually conflict! One classic example occurs in languages with variable declarations. The base version might declare an unused variable:

int i;

In our version, we delete the unused variable to make a compiler warning go away—and in their version, they add a loop some lines later, using i as the loop counter. If we combine the two changes, the resulting code no longer compiles. The -X option is no help here since the changes are on different lines.

If you have an automated test suite, the most important thing to do is to run the tests after merging. You can do this after committing, and fix things up later if needed; or you can do it before committing, by adding --no-commit to the git merge command. We'll leave the details for all of this to other postings.


1You can also get conflicts with respect to "file-wide" operations, e.g., perhaps we fix the spelling of a word in a file (so that we have a change), and they delete the entire file (so that they have a delete). Git will not resolve these conflicts on its own, regardless of -X arguments.


Doing fewer merges and/or smarter merges and/or using rebase

There are three merges in both of our command sequences. The first is to bring origin/demo into the local demo (yours uses git pull which, if your Git is very old, will fail to update origin/demo but will produce the same end result). The second is to bring origin/master into master.

It's not clear to me who is updating demo and/or master. If you write your own code on your own demo branch, and others are writing code and pushing it to the demo branch on origin, then this first-step merge can have conflicts, or produce a real merge. More often than not, it's better to use rebase, rather than merge, to combine work (admittedly, this is a matter of taste and opinion). If so, you might want to use git rebase instead. On the other hand, if you never do any of your own commits on demo, you don't even need a demo branch. Alternatively, if you want to automate a lot of this, but be able to check carefully when there are commits that both you and others, made, you might want to use git merge --ff-only origin/demo: this will fast-forward your demo to match the updated origin/demo if possible, and simply outright fail if not (at which point you can inspect the two sets of changes, and choose a real merge or a rebase as appropriate).

This same logic applies to master, although you are doing the merge on master, so you definitely do need a master. It is, however, even likelier that you would want the merge to fail if it cannot be done as a fast-forward non-merge, so this probably also should be git merge --ff-only origin/master.

Let's say that you never do your own commits on demo. In this case we can ditch the name demo entirely:

git fetch origin   # update origin/*

git checkout master
git merge --ff-only origin/master || die "cannot fast-forward our master"

git merge -X theirs origin/demo || die "complex merge conflict"

git push origin master

If you are doing your own demo branch commits, this is not helpful; you might as well keep the existing merge (but maybe add --ff-only depending on what behavior you want), or switch it to doing a rebase. Note that all three methods may fail: merge may fail with a conflict, merge with --ff-only may not be able to fast-forward, and rebase may fail with a conflict (rebase works by, in essence, cherry-picking commits, which uses the merge machinery and hence can get a merge conflict).

Java foreach loop: for (Integer i : list) { ... }

The API does not support that directly. You can use the for(int i..) loop and count the elements or use subLists(0, size - 1) and handle the last element explicitly:

  if(x.isEmpty()) return;
  int last = x.size() - 1;
  for(Integer i : x.subList(0, last)) out.println(i);
  out.println("last " + x.get(last));

This is only useful if it does not introduce redundancy. It performs better than the counting version (after the subList overhead is amortized). (Just in case you cared after the boxing anyway).

Converting an int or String to a char array on Arduino

You can convert it to char* if you don't need a modifiable string by using:

(char*) yourString.c_str();

This would be very useful when you want to publish a String variable via MQTT in arduino.

What does it mean to "call" a function in Python?

To "call" means to make a reference in your code to a function that is written elsewhere. This function "call" can be made to the standard Python library (stuff that comes installed with Python), third-party libraries (stuff other people wrote that you want to use), or your own code (stuff you wrote). For example:

#!/usr/env python

import os

def foo():
    return "hello world"

print os.getlogin()
print foo()

I created a function called "foo" and called it later on with that print statement. I imported the standard "os" Python library then I called the "getlogin" function within that library.

How to remove button shadow (android)

Instead of a Button, you can use a TextView and add a click listener in the java code.

I.e.

in the activity layout xml:

<TextView
    android:id="@+id/btn_text_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/colorPrimaryDark"
    android:text="@string/btn_text"
    android:gravity="center"
    android:textColor="@color/colorAccent"
    android:fontFamily="sans-serif-medium"
    android:textAllCaps="true" />

in the activity java file:

TextView btnTextView = (TextView) findViewById(R.id.btn_text_view);
btnTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // handler code
            }
        });

Difference between HashMap, LinkedHashMap and TreeMap

These are different implementations of the same interface. Each implementation has some advantages and some disadvantages (fast insert, slow search) or vice versa.

For details look at the javadoc of TreeMap, HashMap, LinkedHashMap.

JavaScript getElementByID() not working

At the point you are calling your function, the rest of the page has not rendered and so the element is not in existence at that point. Try calling your function on window.onload maybe. Something like this:

<html>
<head>
    <title></title>
    <script type="text/javascript">
        window.onload = function(){
           var refButton = document.getElementById("btnButton");

            refButton.onclick = function() {
                alert('I am clicked!');
            }
        };
    </script>
</head>
<body>
    <form id="form1">
    <div>
        <input id="btnButton" type="button" value="Click me"/>
    </div>
    </form>
</body>
</html>

How can I add C++11 support to Code::Blocks compiler?

Use g++ -std=c++11 -o <output_file_name> <file_to_be_compiled>

What is a database transaction?

A transaction is a way of representing a state change. Transactions ideally have four properties, commonly known as ACID:

  • Atomic (if the change is committed, it happens in one fell swoop; you can never see "half a change")
  • Consistent (the change can only happen if the new state of the system will be valid; any attempt to commit an invalid change will fail, leaving the system in its previous valid state)
  • Isolated (no-one else sees any part of the transaction until it's committed)
  • Durable (once the change has happened - if the system says the transaction has been committed, the client doesn't need to worry about "flushing" the system to make the change "stick")

See the Wikipedia ACID entry for more details.

Although this is typically applied to databases, it doesn't have to be. (In particular, see Software Transactional Memory.)

What does $(function() {} ); do?

This is a shortcut for $(document).ready(), which is executed when the browser has finished loading the page (meaning here, "when the DOM is available"). See http://www.learningjquery.com/2006/09/introducing-document-ready. If you are trying to call example() before the browser has finished loading the page, it may not work.

Hibernate Criteria Join with 3 Tables

The fetch mode only says that the association must be fetched. If you want to add restrictions on an associated entity, you must create an alias, or a subcriteria. I generally prefer using aliases, but YMMV:

Criteria c = session.createCriteria(Dokument.class, "dokument");
c.createAlias("dokument.role", "role"); // inner join by default
c.createAlias("role.contact", "contact");
c.add(Restrictions.eq("contact.lastName", "Test"));
return c.list();

This is of course well explained in the Hibernate reference manual, and the javadoc for Criteria even has examples. Read the documentation: it has plenty of useful information.