Programs & Examples On #Dynamic allocation

How do I declare a 2d array in C++ using new?

Start by defining the array using pointers (Line 1):

int** a = new int* [x];     //x is the number of rows
for(int i = 0; i < x; i++)
    a[i] = new int[y];     //y is the number of columns

For files in directory, only echo filename (no path)

You can either use what SiegeX said above or if you aren't interested in learning/using parameter expansion, you can use:

for filename in $(ls /home/user/);
do
    echo $filename
done;

Send Message in C#

Building on Mark Byers's answer.

The 3rd project could be a WCF project, hosted as a Windows Service. If all programs listened to that service, one application could call the service. The service passes the message on to all listening clients and they can perform an action if suitable.

Good WCF videos here - http://msdn.microsoft.com/en-us/netframework/dd728059

How to detect pressing Enter on keyboard using jQuery?

I wrote a small plugin to make it easier to bind the "on enter key pressed" a event:

$.fn.enterKey = function (fnc) {
    return this.each(function () {
        $(this).keypress(function (ev) {
            var keycode = (ev.keyCode ? ev.keyCode : ev.which);
            if (keycode == '13') {
                fnc.call(this, ev);
            }
        })
    })
}

Usage:

$("#input").enterKey(function () {
    alert('Enter!');
})

How to equalize the scales of x-axis and y-axis in Python matplotlib?

You need to dig a bit deeper into the api to do this:

from matplotlib import pyplot as plt
plt.plot(range(5))
plt.xlim(-3, 3)
plt.ylim(-3, 3)
plt.gca().set_aspect('equal', adjustable='box')
plt.draw()

doc for set_aspect

Make xargs execute the command once for each line of input

You can limit the number of lines, or arguments (if there are spaces between each argument) using the --max-lines or --max-args flags, respectively.

  -L max-lines
         Use at most max-lines nonblank input lines per command line.  Trailing blanks cause an input line to be logically continued on the next  input
         line.  Implies -x.

  --max-lines[=max-lines], -l[max-lines]
         Synonym  for  the -L option.  Unlike -L, the max-lines argument is optional.  If max-args is not specified, it defaults to one.  The -l option
         is deprecated since the POSIX standard specifies -L instead.

  --max-args=max-args, -n max-args
         Use at most max-args arguments per command line.  Fewer than max-args arguments will be used if the size (see  the  -s  option)  is  exceeded,
         unless the -x option is given, in which case xargs will exit.

What does the "undefined reference to varName" in C mean?

An initial reaction to this would be to ask and ensure that the two object files are being linked together. This is done at the compile stage by compiling both files at the same time:

gcc -o programName a.c b.c

Or if you want to compile separately, it would be:

gcc -c a.c
gcc -c b.c
gcc -o programName a.o b.o

Best way to convert text files between character sets?

to write properties file (Java) normally I use this in linux (mint and ubuntu distributions):

$ native2ascii filename.properties

For example:

$ cat test.properties 
first=Execução número um
second=Execução número dois

$ native2ascii test.properties 
first=Execu\u00e7\u00e3o n\u00famero um
second=Execu\u00e7\u00e3o n\u00famero dois

PS: I writed Execution number one/two in portugues to force special characters.

In my case, in first execution I received this message:

$ native2ascii teste.txt 
The program 'native2ascii' can be found in the following packages:
 * gcj-5-jdk
 * openjdk-8-jdk-headless
 * gcj-4.8-jdk
 * gcj-4.9-jdk
Try: sudo apt install <selected package>

When I installed the first option (gcj-5-jdk) the problem was finished.

I hope this help someone.

Install shows error in console: INSTALL FAILED CONFLICTING PROVIDER

The Authority + Provider name that you have declared in the manifest probably

How to place Text and an Image next to each other in HTML?

You want to use css float for this, you can put it directly in your code.

<body>
<img src="website_art.png" height= "75" width="235" style="float:left;"/>
<h3 style="float:right;">The Art of Gaming</h3>
</body>

But I would really suggest learning the basics of css and splitting all your styling out to a separate style sheet, and use classes. It will help you in the future. A good place to start is w3schools or, perhaps later down the path, Mozzila Dev. Network (MDN).

HTML:

<body>
  <img src="website_art.png" class="myImage"/>
  <h3 class="heading">The Art of Gaming</h3>
</body>

CSS:

.myImage {
  float: left;
  height: 75px;
  width: 235px;
  font-family: Veranda;
}
.heading {
  float:right;
}

How to mkdir only if a directory does not already exist?

Defining complex directory trees with one command

mkdir -p project/{lib/ext,bin,src,doc/{html,info,pdf},demo/stat/a}

Error when checking model input: expected convolution2d_input_1 to have 4 dimensions, but got array with shape (32, 32, 3)

You should simply apply the following transformation to your input data array.

input_data = input_data.reshape((-1, image_side1, image_side2, channels))

Importing CommonCrypto in a Swift framework

I know this is an old question. But I figure out an alternative way to use the library in Swift project, which might be helpful for those who don't want to import framework introduced in these answers.

In Swift project, create a Objective-C bridging header, create NSData category (or custom class that to use the library) in Objective-C. The only drawback would be that you have to write all implementation code in Objective-C. For example:

#import "NSData+NSDataEncryptionExtension.h"
#import <CommonCrypto/CommonCryptor.h>

@implementation NSData (NSDataEncryptionExtension)
- (NSData *)AES256EncryptWithKey:(NSString *)key {
    //do something
}

- (NSData *)AES256DecryptWithKey:(NSString *)key {
//do something
}

And then in your objective-c bridging header, add this

#import "NSData+NSDataEncryptionExtension.h"

And then in Swift class do similar thing:

public extension String {
func encryp(withKey key:String) -> String? {
    if let data = self.data(using: .utf8), let encrypedData = NSData(data: data).aes256Encrypt(withKey: key) {
        return encrypedData.base64EncodedString()
    }
    return nil
}
func decryp(withKey key:String) -> String? {
    if let data = NSData(base64Encoded: self, options: []), let decrypedData = data.aes256Decrypt(withKey: key) {
        return decrypedData.UTF8String
    }
    return nil
}
}

It works as expected.

Calling Oracle stored procedure from C#?

It's basically the same mechanism as for a non query command with:

  • command.CommandText = the name of the stored procedure
  • command.CommandType = CommandType.StoredProcedure
  • As many calls to command.Parameters.Add as the number of parameters the sp requires
  • command.ExecuteNonQuery

There are plenty of examples out there, the first one returned by Google is this one

There's also a little trap you might fall into, if your SP is a function, your return value parameter must be first in the parameters collection

Why I am Getting Error 'Channel is unrecoverably broken and will be disposed!'

It's obvious this creeps up due to many issues. For me, I was posting several OneTimeWorkRequest, each accessing a single room database, and inserting into a single table.

Making the DAO functions suspended, and calling them within the coroutine scope of the worker fixed this for me.

How to terminate script execution when debugging in Google Chrome?

Open the source tab in 'Developer Tools', click on a line number in a script that is running, this will create a breakpoint and the debugger will break there.

Do I use <img>, <object>, or <embed> for SVG files?

Found one solution with pure CSS and without double image downloading. It is not beautiful as I want, but it works.

<!DOCTYPE html>
<html>
  <head>
    <title>HTML5 SVG demo</title>
    <style type="text/css">
     .nicolas_cage {
         background: url('nicolas_cage.jpg');
         width: 20px;
         height: 15px;
     }
     .fallback {
     }
    </style>
  </head>
<body>
<svg xmlns="http://www.w3.org/2000/svg" width="0" height="0">
    <style>
    <![CDATA[ 
        .fallback { background: none; background-image: none; display: none; }
    ]]>
    </style>
</svg>

<!-- inline svg -->
<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40">
  <switch>
     <circle cx="20" cy="20" r="18" stroke="grey" stroke-width="2" fill="#99FF66" />
     <foreignObject>
         <div class="nicolas_cage fallback"></div>
     </foreignObject>
  </switch>
</svg>
<hr/>
<!-- external svg -->
    <object type="image/svg+xml" data="circle_orange.svg">
        <div class="nicolas_cage fallback"></div>
    </object>
</body>
</html>

The idea is to insert special SVG with fallback style.

More details and testing process you can find in my blog.

Pass row number as variable in excel sheet

An alternative is to use OFFSET:

Assuming the column value is stored in B1, you can use the following

C1 = OFFSET(A1, 0, B1 - 1)

This works by:

a) taking a base cell (A1)
b) adding 0 to the row (keeping it as A)
c) adding (A5 - 1) to the column

You can also use another value instead of 0 if you want to change the row value too.

Eliminating NAs from a ggplot

Try remove_missing instead with vars = the_variable. It is very important that you set the vars argument, otherwise remove_missing will remove all rows that contain an NA in any column!! Setting na.rm = TRUE will suppress the warning message.

ggplot(data = remove_missing(MyData, na.rm = TRUE, vars = the_variable),aes(x= the_variable, fill=the_variable, na.rm = TRUE)) + 
       geom_bar(stat="bin") 

Javascript Regular Expression Remove Spaces

Remove all spaces in string

// Remove only spaces
`
Text with spaces 1 1     1     1 
and some
breaklines

`.replace(/ /g,'');
"
Textwithspaces1111
andsome
breaklines

"

// Remove spaces and breaklines
`
Text with spaces 1 1     1     1
and some
breaklines

`.replace(/\s/g,'');
"Textwithspaces1111andsomebreaklines"

Using port number in Windows host file

This doesn't give the requested result exactly, however, for what I was doing, I was not fussed with adding the port into the URL within a browser.

I added the domain name to the hosts file

127.0.0.1      example.com

Ran my HTTP server from the domain name on port 8080

php -S example.com:8080

Then accessed the website through port 8080

http://example.com:8080

Just wanted to share in case anyone else is in a similar situation.

Xcode variables

Here's a list of the environment variables. I think you might want CURRENT_VARIANT. See also BUILD_VARIANTS.

Java 8 Streams FlatMap method example

Am I the only one who finds unwinding lists boring? ;-)

Let's try with objects. Real world example by the way.

Given: Object representing repetitive task. About important task fields: reminders are starting to ring at start and repeat every repeatPeriod repeatUnit(e.g. 5 HOURS) and there will be repeatCount reminders in total(including starting one).

Goal: achieve a list of task copies, one for each task reminder invocation.

List<Task> tasks =
            Arrays.asList(
                    new Task(
                            false,//completed sign
                            "My important task",//task name (text)
                            LocalDateTime.now().plus(2, ChronoUnit.DAYS),//first reminder(start)
                            true,//is task repetitive?
                            1,//reminder interval
                            ChronoUnit.DAYS,//interval unit
                            5//total number of reminders
                    )
            );

tasks.stream().flatMap(
        x -> LongStream.iterate(
                x.getStart().toEpochSecond(ZoneOffset.UTC),
                p -> (p + x.getRepeatPeriod()*x.getRepeatUnit().getDuration().getSeconds())
        ).limit(x.getRepeatCount()).boxed()
        .map( y -> new Task(x,LocalDateTime.ofEpochSecond(y,0,ZoneOffset.UTC)))
).forEach(System.out::println);

Output:

Task{completed=false, text='My important task', start=2014-10-01T21:35:24, repeat=false, repeatCount=0, repeatPeriod=0, repeatUnit=null}
Task{completed=false, text='My important task', start=2014-10-02T21:35:24, repeat=false, repeatCount=0, repeatPeriod=0, repeatUnit=null}
Task{completed=false, text='My important task', start=2014-10-03T21:35:24, repeat=false, repeatCount=0, repeatPeriod=0, repeatUnit=null}
Task{completed=false, text='My important task', start=2014-10-04T21:35:24, repeat=false, repeatCount=0, repeatPeriod=0, repeatUnit=null}
Task{completed=false, text='My important task', start=2014-10-05T21:35:24, repeat=false, repeatCount=0, repeatPeriod=0, repeatUnit=null}

P.S.: I would appreciate if someone suggested a simpler solution, I'm not a pro after all.

UPDATE: @RBz asked for detailed explanation so here it is. Basically flatMap puts all elements from streams inside another stream into output stream. A lot of streams here :). So, for each Task in initial stream lambda expression x -> LongStream.iterate... creates a stream of long values that represent task start moments. This stream is limited to x.getRepeatCount() instances. It's values start from x.getStart().toEpochSecond(ZoneOffset.UTC) and each next value is calculated using lambda p -> (p + x.getRepeatPeriod()*x.getRepeatUnit().getDuration().getSeconds(). boxed() returns the stream with each long value as a Long wrapper instance. Then each Long in that stream is mapped to new Task instance that is not repetitive anymore and contains exact execution time. This sample contains only one Task in input list. But imagine that you have a thousand. You will have then a stream of 1000 streams of Task objects. And what flatMap does here is putting all Tasks from all streams onto the same output stream. That's all as I understand it. Thank you for your question!

Return generated pdf using spring MVC

You were on the right track with response.getOutputStream(), but you're not using its output anywhere in your code. Essentially what you need to do is to stream the PDF file's bytes directly to the output stream and flush the response. In Spring you can do it like this:

@RequestMapping(value="/getpdf", method=RequestMethod.POST)
public ResponseEntity<byte[]> getPDF(@RequestBody String json) {
    // convert JSON to Employee 
    Employee emp = convertSomehow(json);

    // generate the file
    PdfUtil.showHelp(emp);

    // retrieve contents of "C:/tmp/report.pdf" that were written in showHelp
    byte[] contents = (...);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_PDF);
    // Here you have to set the actual filename of your pdf
    String filename = "output.pdf";
    headers.setContentDispositionFormData(filename, filename);
    headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
    ResponseEntity<byte[]> response = new ResponseEntity<>(contents, headers, HttpStatus.OK);
    return response;
}

Notes:

  • use meaningful names for your methods: naming a method that writes a PDF document showHelp is not a good idea
  • reading a file into a byte[]: example here
  • I'd suggest adding a random string to the temporary PDF file name inside showHelp() to avoid overwriting the file if two users send a request at the same time

add Shadow on UIView using swift 3

Please try this, it's working for me.

extension UIView {


func dropShadow() {

    layer.shadowColor = UIColor.black.cgColor
    layer.shadowOffset = CGSize(width: 2, height: 3)
    layer.masksToBounds = false

    layer.shadowOpacity = 0.3
    layer.shadowRadius = 3
    //layer.shadowPath = UIBezierPath(rect: bounds).cgPath
    layer.rasterizationScale = UIScreen.main.scale
    layer.shouldRasterize = true
}}

Python - Module Not Found

you need a file named __init__.py (two underscores on each side) in every folder in the hierarchy, so one in src/ and one in model/. This is what python looks for to know that it should access a particular folder. The files are meant to contain initialization instructions but even if you create them empty this will solve it.

cmake error 'the source does not appear to contain CMakeLists.txt'

You should do mkdir build and cd build while inside opencv folder, not the opencv-contrib folder. The CMakeLists.txt is there.

Facebook database design?

You're looking for foreign keys. Basically you can't have an array in a database unless it has it's own table.


Example schema:

    Users Table
        userID PK
        other data
    Friends Table
        userID   -- FK to users's table representing the user that has a friend.
        friendID -- FK to Users' table representing the user id of the friend

How get the base URL via context path in JSF?

JSTL 1.2 variation leveraged from BalusC answer

<c:set var="baseURL" value="${pageContext.request.requestURL.substring(0, pageContext.request.requestURL.length() - pageContext.request.requestURI.length())}${pageContext.request.contextPath}/" />

<head>
  <base href="${baseURL}" />

Linq to SQL how to do "where [column] in (list of values)"

Here is how I do it by using HashSet

        HashSet<String> hs = new HashSet<string>(new String[] { "Pluto", "Earth", "Neptune" });
        String[] arr =
        {
            "Pluto",
            "Earth",
            "Neptune",
            "Jupiter",
            "Saturn",
            "Mercury",
            "Pluto",
            "Earth",
            "Neptune",
            "Jupiter",
            "Saturn",
            "Mercury",
            // etc.
        };
        ICollection<String> coll = arr;

        String[] arrStrFiltered = coll.Where(str => hs.Contains(str)).ToArray();

HashSet is basically almost to O(1) so your complexity remains O(n).

How can I show line numbers in Eclipse?

Window ? Preferences ? General ? Editors ? Text Editors ? Show line numbers.


Edit: I wrote this long ago but as @ArtOfWarfar and @voidstate mentioned you can now simply:

Right click the gutter and select "Show Line Numbers":

What is the difference between Dim, Global, Public, and Private as Modular Field Access Modifiers?

Dim and Private work the same, though the common convention is to use Private at the module level, and Dim at the Sub/Function level. Public and Global are nearly identical in their function, however Global can only be used in standard modules, whereas Public can be used in all contexts (modules, classes, controls, forms etc.) Global comes from older versions of VB and was likely kept for backwards compatibility, but has been wholly superseded by Public.

Unable to locate an executable at "/usr/bin/java/bin/java" (-1)

Most certainly, export JAVA_HOME=/usr/bin/java is the culprit. This env var should point to the JDK or JRE installation directory. Googling shows that the best option for MacOS X seems to be export JAVA_HOME=/Library/Java/Home.

What regular expression will match valid international phone numbers?

This will work for international numbers;

C#:

@"^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$"

JS:

/^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/

How can I delete derived data in Xcode 8?

Select Xcode and Follow 4 steps that highlighted in photo and remove derived data then restart your project.enter image description here

How can I restart a Java application?

Similar to Yoda's 'improved' answer, but with further improvements (both functional, readability, and testability). It's now safe to run, and restarts for as as many times as the amount of program arguments given.

  • No accumulation of JAVA_TOOL_OPTIONS options.
  • Automatically finds main class.
  • Inherits current stdout/stderr.

public static void main(String[] args) throws Exception {
    if (args.length == 0)
        return;
    else
        args = Arrays.copyOf(args, args.length - 1);

    List<String> command = new ArrayList<>(32);
    appendJavaExecutable(command);
    appendVMArgs(command);
    appendClassPath(command);
    appendEntryPoint(command);
    appendArgs(command, args);

    System.out.println(command);
    try {
        new ProcessBuilder(command).inheritIO().start();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

private static void appendJavaExecutable(List<String> cmd) {
    cmd.add(System.getProperty("java.home") + File.separator + "bin" + File.separator + "java");
}

private static void appendVMArgs(Collection<String> cmd) {
    Collection<String> vmArguments = ManagementFactory.getRuntimeMXBean().getInputArguments();

    String javaToolOptions = System.getenv("JAVA_TOOL_OPTIONS");
    if (javaToolOptions != null) {
        Collection<String> javaToolOptionsList = Arrays.asList(javaToolOptions.split(" "));
        vmArguments = new ArrayList<>(vmArguments);
        vmArguments.removeAll(javaToolOptionsList);
    }

    cmd.addAll(vmArguments);
}

private static void appendClassPath(List<String> cmd) {
    cmd.add("-cp");
    cmd.add(ManagementFactory.getRuntimeMXBean().getClassPath());
}

    private static void appendEntryPoint(List<String> cmd) {
    StackTraceElement[] stackTrace          = new Throwable().getStackTrace();
    StackTraceElement   stackTraceElement   = stackTrace[stackTrace.length - 1];
    String              fullyQualifiedClass = stackTraceElement.getClassName();
    String              entryMethod         = stackTraceElement.getMethodName();
    if (!entryMethod.equals("main"))
        throw new AssertionError("Entry point is not a 'main()': " + fullyQualifiedClass + '.' + entryMethod);

    cmd.add(fullyQualifiedClass);
}

private static void appendArgs(List<String> cmd, String[] args) {
    cmd.addAll(Arrays.asList(args));
}

V1.1 Bugfix: null pointer if JAVA_TOOL_OPTIONS is not set


Example:

$ java -cp Temp.jar Temp a b c d e
[/usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java, -cp, Temp.jar, Temp, a, b, c, d]
[/usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java, -cp, Temp.jar, Temp, a, b, c]
[/usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java, -cp, Temp.jar, Temp, a, b]
[/usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java, -cp, Temp.jar, Temp, a]
[/usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java, -cp, Temp.jar, Temp]
$

How can I get list of values from dict?

Follow the below example --

songs = [
{"title": "happy birthday", "playcount": 4},
{"title": "AC/DC", "playcount": 2},
{"title": "Billie Jean", "playcount": 6},
{"title": "Human Touch", "playcount": 3}
]

print("====================")
print(f'Songs --> {songs} \n')
title = list(map(lambda x : x['title'], songs))
print(f'Print Title --> {title}')

playcount = list(map(lambda x : x['playcount'], songs))
print(f'Print Playcount --> {playcount}')
print (f'Print Sorted playcount --> {sorted(playcount)}')

# Aliter -
print(sorted(list(map(lambda x: x['playcount'],songs))))

Where can I find System.Web.Helpers, System.Web.WebPages, and System.Web.Razor?

I had to install RazorGenerator.Templating to get it all to work. From the NuGet console, type:

Install-Package RazorGenerator.Templating

Is there a way to word-wrap long words in a div?

Aaron Bennet's solution is working perfectly for me, but i had to remove this line from his code --> white-space: -pre-wrap; beacause it was giving an error, so the final working code is the following:

.wordwrap { 
   white-space: pre-wrap;      /* CSS3 */   
   white-space: -moz-pre-wrap; /* Firefox */   
   white-space: -o-pre-wrap;   /* Opera 7 */    
   word-wrap: break-word;      /* IE */
}

thank you very much

How to find all occurrences of an element in a list

A solution using list.index:

def indices(lst, element):
    result = []
    offset = -1
    while True:
        try:
            offset = lst.index(element, offset+1)
        except ValueError:
            return result
        result.append(offset)

It's much faster than the list comprehension with enumerate, for large lists. It is also much slower than the numpy solution if you already have the array, otherwise the cost of converting outweighs the speed gain (tested on integer lists with 100, 1000 and 10000 elements).

NOTE: A note of caution based on Chris_Rands' comment: this solution is faster than the list comprehension if the results are sufficiently sparse, but if the list has many instances of the element that is being searched (more than ~15% of the list, on a test with a list of 1000 integers), the list comprehension is faster.

How to get english language word database?

There's no such thing as a "complete" list. Different people have different ways of measuring -- for example, they might include slang, neologisms, multi-word phrases, offensive terms, foreign words, verb conjugations, and so on. Some people have even counted a million words! So you'll have to decide what you want in a word list.

How do I convert two lists into a dictionary?

If you are working with more than 1 set of values and wish to have a list of dicts you can use this:

def as_dict_list(data: list, columns: list):
    return [dict((zip(columns, row))) for row in data]

Real-life example would be a list of tuples from a db query paired to a tuple of columns from the same query. Other answers only provided for 1 to 1.

How to get distinct values for non-key column fields in Laravel?

**

Tested for Laravel 5.8

**

Since you wanna get all columns from the table, you can collect all of the data and then filter it using Collections function called Unique

// Get all users with unique name
User::all()->unique('name')

or

// Get all & latest users with unique name 
User::latest()->get()->unique('name')

For more information you can check Laravel Collection Documentations

EDIT: You might have issue with perfomance, by using Unique() you'll get all data first from User table, and then Laravel will filter it. This way isn't good if you have lots of Users data. You can use query builder and call each fields that you wanna use, example:

User::select('username','email','name')->distinct('name')->get();

Regex lookahead, lookbehind and atomic groups

Grokking lookaround rapidly.
How to distinguish lookahead and lookbehind? Take 2 minutes tour with me:

(?=) - positive lookahead
(?<=) - positive lookbehind

Suppose

    A  B  C #in a line

Now, we ask B, Where are you?
B has two solutions to declare it location:

One, B has A ahead and has C bebind
Two, B is ahead(lookahead) of C and behind (lookhehind) A.

As we can see, the behind and ahead are opposite in the two solutions.
Regex is solution Two.

How to reset Jenkins security settings from the command line?

To disable Jenkins security in simple steps in Linux, run these commands:

sudo ex +g/useSecurity/d +g/authorizationStrategy/d -scwq /var/lib/jenkins/config.xml
sudo /etc/init.d/jenkins restart

It will remove useSecurity and authorizationStrategy lines from your config.xml root config file and restart your Jenkins.

See also: Disable security at Jenkins website


After gaining the access to Jenkins, you can re-enable security in your Configure Global Security page by choosing the Access Control/Security Realm. After than don't forget to create the admin user.

Change primary key column in SQL Server

Assuming that your current primary key constraint is called pk_history, you can replace the following lines:

ALTER TABLE history ADD PRIMARY KEY (id)

ALTER TABLE history
DROP CONSTRAINT userId
DROP CONSTRAINT name

with these:

ALTER TABLE history DROP CONSTRAINT pk_history

ALTER TABLE history ADD CONSTRAINT pk_history PRIMARY KEY (id)

If you don't know what the name of the PK is, you can find it with the following query:

SELECT * 
  FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
 WHERE TABLE_NAME = 'history'

Read .mat files in Python

First save the .mat file as:

save('test.mat', '-v7')

After that, in Python, use the usual loadmat function:

import scipy.io as sio
test = sio.loadmat('test.mat')

Change Tomcat Server's timeout in Eclipse

I also had the issue of the Eclipse Tomcat Server timing out and tried every suggestion including:

  • increasing timeout seconds
  • deleting various .metadata files in workspace directory
  • deleting the server instance in Eclipse along with the Run Config

Nothing worked until I read Rohitdev's comment and realized that I had, in fact added a breakpoint in an interceptor class after a big code change and had forgotten to toggle it off. I removed it and all other breakpoints and Tomcat started right up.

How to convert NSData to byte array in iPhone?

That's because the return type for [data bytes] is a void* c-style array, not a Uint8 (which is what Byte is a typedef for).

The error is because you are trying to set an allocated array when the return is a pointer type, what you are looking for is the getBytes:length: call which would look like:

[data getBytes:&byteData length:len];

Which fills the array you have allocated with data from the NSData object.

How to remove an element slowly with jQuery?

You mean like

$target.hide('slow')

?

Input Type image submit form value?

I've found that image-buttons DO return a response, but you should NOT use a value-option. What I see returned are two version of the name="MYNAME" with .X and .Y endings.

For example:

<input type="image" src="/path-to/stop.png" name="STOP" width="25" height="25" align="top" alt="Stop sign">

This is within your <form> to </form>. If you click the image, what's returned are STOP.X and STOP.Y with numeric values. The existence of either indicates the STOP image-button was clicked. You don't need any special code. Just treat it as another kind of "submit" button that returns a pair of augmented NAMEs.

I've tried this on Safari, Firefox and Chrome. The image wasn't displayed with Safari, but where it was supposed to be located, my cursor turned into a finger-icon, and I could click it.

Git vs Team Foundation Server

Original: @Rob, TFS has something called "Shelving" that addresses your concern about commiting work-in-progress without it affecting the official build. I realize you see central version control as a hindrance, but with respect to TFS, checking your code into the shelf can be viewed as a strength b/c then the central server has a copy of your work-in-progress in the rare event your local machine crashes or is lost/stolen or you need to switch gears quickly. My point is that TFS should be given proper praise in this area. Also, branching and merging in TFS2010 has been improved from prior versions, and it isn't clear what version you are referring to when you say "... from experience that branching and merging in TFS is not good." Disclaimer: I'm a moderate user of TFS2010.

Edit Dec-5-2011: To the OP, one thing that bothers me about TFS is that it insists on setting all your local files to "read-only" when you're not working on them. If you want to make a change, the flow is that you must "check-out" the file, which just clears the readonly attribute on the file so that TFS knows to keep an eye on it. That's an inconvenient workflow. The way I would prefer it to work is that is just automatically detects if I've made a change and doesn't worry/bother with the file attributes at all. That way, I can modify the file either in Visual Studio, or Notepad, or with whatever tool I please. The version control system should be as transparent as possible in this regard. There is a Windows Explorer Extension (TFS PowerTools) that allows you to work with your files in Windows Explorer, but that doesn't simplify the workflow very much.

Rendering HTML in a WebView with custom CSS

Is it possible to have all the content rendered in-page, in a given div? You could then reset the css based on the id, and work on from there.

Say you give your div id="ocon"

In your css, have a definition like:

#ocon *{background:none;padding:0;etc,etc,}

and you can set values to clear all css from applying to the content. After that, you can just use

#ocon ul{}

or whatever, further down the stylesheet, to apply new styles to the content.

Replace all particular values in a data frame

Since PikkuKatja and glallen asked for a more general solution and I cannot comment yet, I'll write an answer. You can combine statements as in:

> df[df=="" | df==12] <- NA
> df
     A    B
1  <NA> <NA>
2  xyz  <NA>
3  jkl  100

For factors, zxzak's code already yields factors:

> df <- data.frame(list(A=c("","xyz","jkl"), B=c(12,"",100)))
> str(df)
'data.frame':   3 obs. of  2 variables:
 $ A: Factor w/ 3 levels "","jkl","xyz": 1 3 2
 $ B: Factor w/ 3 levels "","100","12": 3 1 2

If in trouble, I'd suggest to temporarily drop the factors.

df[] <- lapply(df, as.character)

How to format a number 0..9 to display with 2 digits (it's NOT a date)

If you need to print the number you can use printf

System.out.printf("%02d", num);

You can use

String.format("%02d", num);

or

(num < 10 ? "0" : "") + num;

or

(""+(100+num)).substring(1);

Remove all elements contained in another array

Use the Array.filter() method:

myArray = myArray.filter( function( el ) {
  return toRemove.indexOf( el ) < 0;
} );

Small improvement, as browser support for Array.includes() has increased:

myArray = myArray.filter( function( el ) {
  return !toRemove.includes( el );
} );

Next adaptation using arrow functions:

myArray = myArray.filter( ( el ) => !toRemove.includes( el ) );

Getting time elapsed in Objective-C

For anybody coming here looking for a getTickCount() implementation for iOS, here is mine after putting various sources together.

Previously I had a bug in this code (I divided by 1000000 first) which was causing some quantisation of the output on my iPhone 6 (perhaps this was not an issue on iPhone 4/etc or I just never noticed it). Note that by not performing that division first, there is some risk of overflow if the numerator of the timebase is quite large. If anybody is curious, there is a link with much more information here: https://stackoverflow.com/a/23378064/588476

In light of that information, maybe it is safer to use Apple's function CACurrentMediaTime!

I also benchmarked the mach_timebase_info call and it takes approximately 19ns on my iPhone 6, so I removed the (not threadsafe) code which was caching the output of that call.

#include <mach/mach.h>
#include <mach/mach_time.h>

uint64_t getTickCount(void)
{
    mach_timebase_info_data_t sTimebaseInfo;
    uint64_t machTime = mach_absolute_time();

    // Convert to milliseconds
    mach_timebase_info(&sTimebaseInfo);
    machTime *= sTimebaseInfo.numer;
    machTime /= sTimebaseInfo.denom;
    machTime /= 1000000; // convert from nanoseconds to milliseconds

    return machTime;
}

Do be aware of the potential risk of overflow depending on the output of the timebase call. I suspect (but do not know) that it might be a constant for each model of iPhone. on my iPhone 6 it was 125/3.

The solution using CACurrentMediaTime() is quite trivial:

uint64_t getTickCount(void)
{
    double ret = CACurrentMediaTime();
    return ret * 1000;
}

Reading/parsing Excel (xls) files with Python

You might also consider running the (non-python) program xls2csv. Feed it an xls file, and you should get back a csv.

How to select clear table contents without destroying the table?

How about:

ACell.ListObject.DataBodyRange.Rows.Delete

That will keep your table structure and headings, but clear all the data and rows.

EDIT: I'm going to just modify a section of my answer from your previous post, as it does mostly what you want. This leaves just one row:

With loSource
   .Range.AutoFilter
   .DataBodyRange.Offset(1).Resize(.DataBodyRange.Rows.Count - 1, .DataBodyRange.Columns.Count).Rows.Delete
   .DataBodyRange.Rows(1).Specialcells(xlCellTypeConstants).ClearContents
End With

If you want to leave all the rows intact with their formulas and whatnot, just do:

With loSource
   .Range.AutoFilter
   .DataBodyRange.Specialcells(xlCellTypeConstants).ClearContents
End With

Which is close to what @Readify suggested, except it won't clear formulas.

python pandas extract year from datetime: df['year'] = df['date'].year is not working

When to use dt accessor

A common source of confusion revolves around when to use .year and when to use .dt.year.

The former is an attribute for pd.DatetimeIndex objects; the latter for pd.Series objects. Consider this dataframe:

df = pd.DataFrame({'Dates': pd.to_datetime(['2018-01-01', '2018-10-20', '2018-12-25'])},
                  index=pd.to_datetime(['2000-01-01', '2000-01-02', '2000-01-03']))

The definition of the series and index look similar, but the pd.DataFrame constructor converts them to different types:

type(df.index)     # pandas.tseries.index.DatetimeIndex
type(df['Dates'])  # pandas.core.series.Series

The DatetimeIndex object has a direct year attribute, while the Series object must use the dt accessor. Similarly for month:

df.index.month               # array([1, 1, 1])
df['Dates'].dt.month.values  # array([ 1, 10, 12], dtype=int64)

A subtle but important difference worth noting is that df.index.month gives a NumPy array, while df['Dates'].dt.month gives a Pandas series. Above, we use pd.Series.values to extract the NumPy array representation.

Remove local git tags that are no longer on the remote repository

The same answer as @Richard W but for Windows (PowerShell)

git tag | foreach-object -process { git tag -d $_ }
git fetch -t

Fatal error: Call to undefined function socket_create()

I got this error when my .env file was not set up properly. Make sure you have a .env file with valid database login credentials.

align 3 images in same row with equal spaces?

HTML:

<div class="container">
    <span>
        <img ... >
    </span>
    <span>
        <img ... >
    </span>
    <span>
        <img ... >
    </span>
</div>

CSS:

.container{ width:50%; margin:0 auto; text-align:center}
.container span{ width:30%; margin:0 1%;  }

I haven't tested this, but hope this will work.

You can add 'display:inline-block' to .container span to make the span to have fixed 30% width

Multiple values in single-value context

In case of a multi-value return function you can't refer to fields or methods of a specific value of the result when calling the function.

And if one of them is an error, it's there for a reason (which is the function might fail) and you should not bypass it because if you do, your subsequent code might also fail miserably (e.g. resulting in runtime panic).

However there might be situations where you know the code will not fail in any circumstances. In these cases you can provide a helper function (or method) which will discard the error (or raise a runtime panic if it still occurs).
This can be the case if you provide the input values for a function from code, and you know they work.
Great examples of this are the template and regexp packages: if you provide a valid template or regexp at compile time, you can be sure they can always be parsed without errors at runtime. For this reason the template package provides the Must(t *Template, err error) *Template function and the regexp package provides the MustCompile(str string) *Regexp function: they don't return errors because their intended use is where the input is guaranteed to be valid.

Examples:

// "text" is a valid template, parsing it will not fail
var t = template.Must(template.New("name").Parse("text"))

// `^[a-z]+\[[0-9]+\]$` is a valid regexp, always compiles
var validID = regexp.MustCompile(`^[a-z]+\[[0-9]+\]$`)

Back to your case

IF you can be certain Get() will not produce error for certain input values, you can create a helper Must() function which would not return the error but raise a runtime panic if it still occurs:

func Must(i Item, err error) Item {
    if err != nil {
        panic(err)
    }
    return i
}

But you should not use this in all cases, just when you're sure it succeeds. Usage:

val := Must(Get(1)).Value

Alternative / Simplification

You can even simplify it further if you incorporate the Get() call into your helper function, let's call it MustGet:

func MustGet(value int) Item {
    i, err := Get(value)
    if err != nil {
        panic(err)
    }
    return i
}

Usage:

val := MustGet(1).Value

See some interesting / related questions:

how to parse multiple returns in golang

Return map like 'ok' in Golang on normal functions

How to remove specific value from array using jQuery

Remove Item in Array

var arr = ["jQuery", "JavaScript", "HTML", "Ajax", "Css"];
var itemtoRemove = "HTML";
arr.splice($.inArray(itemtoRemove, arr), 1);

Text-decoration: none not working

a:link{
  text-decoration: none!important;
}

=> Working with me :) , good luck

SqlBulkCopy - The given value of type String from the data source cannot be converted to type money of the specified target column

@Corey - It just simply strips out all invalid characters. However, your comment made me think of the answer.

The problem was that many of the fields in my database are nullable. When using SqlBulkCopy, an empty string is not inserted as a null value. So in the case of my fields that are not varchar (bit, int, decimal, datetime, etc) it was trying to insert an empty string, which obviously is not valid for that data type.

The solution was to modify my loop where I validate the values to this (repeated for each datatype that is not string)

//--- convert decimal values
foreach (DataColumn DecCol in DecimalColumns)
{
     if(string.IsNullOrEmpty(dr[DecCol].ToString()))
          dr[DecCol] = null; //--- this had to be set to null, not empty
     else
          dr[DecCol] = Helpers.CleanDecimal(dr[DecCol].ToString());
}

After making the adjustments above, everything inserts without issues.

Codesign wants to access key "access" in your keychain, I put in my login password but keeps asking me

The same dialog asking for the KeyChain password has 3 buttons. Most likely the wanted password is that for logging in to your Mac. If you press "Allow" it only works for some tiny aspect and will ask again, which is very puzzling. You need to press "Always Allow". The verification team at Apple is very weak, they need some 'normal' developers in the design team for the chain of events to get an app in the app store. Normal developers have very sketchy ideas about KeyChains and Certificates and Profiles.

Writing a dictionary to a text file?

You can do as follow :

import json
exDict = {1:1, 2:2, 3:3}
file.write(json.dumps(exDict))

https://developer.rhino3d.com/guides/rhinopython/python-xml-json/

What is an AssertionError? In which case should I throw it from my own code?

AssertionError is an Unchecked Exception which rises explicitly by programmer or by API Developer to indicate that assert statement fails.

assert(x>10);

Output:

AssertionError

If x is not greater than 10 then you will get runtime exception saying AssertionError.

How to fix the "508 Resource Limit is reached" error in WordPress?

I've already encountered this error and this is the best solution I've found:

In your root folder (probably called public_html)please add this code to your .htaccess file...

REPLACE the 00.00.00.000 with YOUR IP address. If you don't know your IP address buzz over to What Is My IP - The IP Address Experts Since 1999

#By Marky WP Root Directory to deny entry for WP-Login & xmlrpc
<Files wp-login.php>
        order deny,allow
        deny from all
        allow from 00.00.00.000
    </Files>
<Files xmlrpc.php>
        order deny,allow
        deny from all
        allow from 00.00.00.000
    </Files>

In your wp-admin folder please add this code to your .htaccess file...

#By Marky WP Admin Folder to deny entry for entire admin folder
order deny,allow
deny from all
allow from 00.00.00.000
<Files index.php>
        order deny,allow
        deny from all
        allow from 00.00.00.000
    </Files>

From: https://www.quora.com/I-am-using-shared-hosting-and-my-I-O-usage-is-full-after-every-minute-What-is-this-I-O-usage-in-cPanel-How-can-I-reduce-it

How to split one string into multiple strings separated by at least one space in bash shell?

Just use the shells "set" built-in. For example,

set $text

After that, individual words in $text will be in $1, $2, $3, etc. For robustness, one usually does

set -- junk $text
shift

to handle the case where $text is empty or start with a dash. For example:

text="This is          a              test"
set -- junk $text
shift
for word; do
  echo "[$word]"
done

This prints

[This]
[is]
[a]
[test]

How to install a previous exact version of a NPM package?

you can update your npm package by using this command:

npm install <package_name>@<version_number>

example: npm install [email protected]

How do I overload the [] operator in C#

I believe this is what you are looking for:

Indexers (C# Programming Guide)

class SampleCollection<T>
{
    private T[] arr = new T[100];
    public T this[int i]
    {
        get => arr[i];
        set => arr[i] = value;
    }
}

// This class shows how client code uses the indexer
class Program
{
    static void Main(string[] args)
    {
        SampleCollection<string> stringCollection = 
            new SampleCollection<string>();
        stringCollection[0] = "Hello, World";
        System.Console.WriteLine(stringCollection[0]);
    }
}

A component is changing an uncontrolled input of type text to be controlled error in ReactJS

In my case it was pretty much what Mayank Shukla's top answer says. The only detail was that my state was lacking completely the property I was defining.

For example, if you have this state:

state = {
    "a" : "A",
    "b" : "B",
}

If you're expanding your code, you might want to add a new prop so, someplace else in your code you might create a new property c whose value is not only undefined on the component's state but the property itself is undefined.

To solve this just make sure to add c into your state and give it a proper initial value.

e.g.,

state = {
    "a" : "A",
    "b" : "B",
    "c" : "C", // added and initialized property!
}

Hope I was able to explain my edge case.

How to undo a successful "git cherry-pick"?

git reflog can come to your rescue.

Type it in your console and you will get a list of your git history along with SHA-1 representing them.

Simply checkout any SHA-1 that you wish to revert to


Before answering let's add some background, explaining what is this HEAD.

First of all what is HEAD?

HEAD is simply a reference to the current commit (latest) on the current branch.
There can only be a single HEAD at any given time. (excluding git worktree)

The content of HEAD is stored inside .git/HEAD and it contains the 40 bytes SHA-1 of the current commit.


detached HEAD

If you are not on the latest commit - meaning that HEAD is pointing to a prior commit in history its called detached HEAD.

enter image description here

On the command line, it will look like this- SHA-1 instead of the branch name since the HEAD is not pointing to the tip of the current branch

enter image description here

enter image description here

A few options on how to recover from a detached HEAD:


git checkout

git checkout <commit_id>
git checkout -b <new branch> <commit_id>
git checkout HEAD~X // x is the number of commits t go back

This will checkout new branch pointing to the desired commit.
This command will checkout to a given commit.
At this point, you can create a branch and start to work from this point on.

# Checkout a given commit. 
# Doing so will result in a `detached HEAD` which mean that the `HEAD`
# is not pointing to the latest so you will need to checkout branch
# in order to be able to update the code.
git checkout <commit-id>

# create a new branch forked to the given commit
git checkout -b <branch name>

git reflog

You can always use the reflog as well.
git reflog will display any change which updated the HEAD and checking out the desired reflog entry will set the HEAD back to this commit.

Every time the HEAD is modified there will be a new entry in the reflog

git reflog
git checkout HEAD@{...}

This will get you back to your desired commit

enter image description here


git reset --hard <commit_id>

"Move" your HEAD back to the desired commit.

# This will destroy any local modifications.
# Don't do it if you have uncommitted work you want to keep.
git reset --hard 0d1d7fc32

# Alternatively, if there's work to keep:
git stash
git reset --hard 0d1d7fc32
git stash pop
# This saves the modifications, then reapplies that patch after resetting.
# You could get merge conflicts if you've modified things which were
# changed since the commit you reset to.
  • Note: (Since Git 2.7)
    you can also use the git rebase --no-autostash as well.

git revert <sha-1>

"Undo" the given commit or commit range.
The reset command will "undo" any changes made in the given commit.
A new commit with the undo patch will be committed while the original commit will remain in the history as well.

# add new commit with the undo of the original one.
# the <sha-1> can be any commit(s) or commit range
git revert <sha-1>

This schema illustrates which command does what.
As you can see there reset && checkout modify the HEAD.

enter image description here

Iterate through Nested JavaScript Objects

You can get through every object in the list and get which value you want. Just pass an object as first parameter in the function call and object property which you want as second parameter. Change object with your object.

_x000D_
_x000D_
const treeData = [{_x000D_
        "jssType": "fieldset",_x000D_
        "jssSelectLabel": "Fieldset (with legend)",_x000D_
        "jssSelectGroup": "jssItem",_x000D_
        "jsName": "fieldset-715",_x000D_
        "jssLabel": "Legend",_x000D_
        "jssIcon": "typcn typcn-folder",_x000D_
        "expanded": true,_x000D_
        "children": [{_x000D_
                "jssType": "list-ol",_x000D_
                "jssSelectLabel": "List - ol",_x000D_
                "jssSelectGroup": "jssItem",_x000D_
                "jsName": "list-ol-147",_x000D_
                "jssLabel": "",_x000D_
                "jssIcon": "dashicons dashicons-editor-ol",_x000D_
                "noChildren": false,_x000D_
                "expanded": true,_x000D_
                "children": [{_x000D_
                        "jssType": "list-li",_x000D_
                        "jssSelectLabel": "List Item - li",_x000D_
                        "jssSelectGroup": "jssItem",_x000D_
                        "jsName": "list-li-752",_x000D_
                        "jssLabel": "",_x000D_
                        "jssIcon": "dashicons dashicons-editor-ul",_x000D_
                        "noChildren": false,_x000D_
                        "expanded": true,_x000D_
                        "children": [{_x000D_
                            "jssType": "text",_x000D_
                            "jssSelectLabel": "Text (short text)",_x000D_
                            "jssSelectGroup": "jsTag",_x000D_
                            "jsName": "text-422",_x000D_
                            "jssLabel": "Your Name (required)",_x000D_
                            "jsRequired": true,_x000D_
                            "jsTagOptions": [{_x000D_
                                    "jsOption": "",_x000D_
                                    "optionLabel": "Default value",_x000D_
                                    "optionType": "input"_x000D_
                                },_x000D_
                                {_x000D_
                                    "jsOption": "placeholder",_x000D_
                                    "isChecked": false,_x000D_
                                    "optionLabel": "Use this text as the placeholder of the field",_x000D_
                                    "optionType": "checkbox"_x000D_
                                },_x000D_
                                {_x000D_
                                    "jsOption": "akismet_author_email",_x000D_
                                    "isChecked": false,_x000D_
                                    "optionLabel": "Akismet - this field requires author's email address",_x000D_
                                    "optionType": "checkbox"_x000D_
                                }_x000D_
                            ],_x000D_
                            "jsValues": "",_x000D_
                            "jsPlaceholder": false,_x000D_
                            "jsAkismetAuthor": false,_x000D_
                            "jsIdAttribute": "",_x000D_
                            "jsClassAttribute": "",_x000D_
                            "jssIcon": "typcn typcn-sort-alphabetically",_x000D_
                            "noChildren": true_x000D_
                        }]_x000D_
                    },_x000D_
                    {_x000D_
                        "jssType": "list-li",_x000D_
                        "jssSelectLabel": "List Item - li",_x000D_
                        "jssSelectGroup": "jssItem",_x000D_
                        "jsName": "list-li-538",_x000D_
                        "jssLabel": "",_x000D_
                        "jssIcon": "dashicons dashicons-editor-ul",_x000D_
                        "noChildren": false,_x000D_
                        "expanded": true,_x000D_
                        "children": [{_x000D_
                            "jssType": "email",_x000D_
                            "jssSelectLabel": "Email",_x000D_
                            "jssSelectGroup": "jsTag",_x000D_
                            "jsName": "email-842",_x000D_
                            "jssLabel": "Email Address (required)",_x000D_
                            "jsRequired": true,_x000D_
                            "jsTagOptions": [{_x000D_
                                    "jsOption": "",_x000D_
                                    "optionLabel": "Default value",_x000D_
                                    "optionType": "input"_x000D_
                                },_x000D_
                                {_x000D_
                                    "jsOption": "placeholder",_x000D_
                                    "isChecked": false,_x000D_
                                    "optionLabel": "Use this text as the placeholder of the field",_x000D_
                                    "optionType": "checkbox"_x000D_
                                },_x000D_
                                {_x000D_
                                    "jsOption": "akismet_author_email",_x000D_
                                    "isChecked": false,_x000D_
                                    "optionLabel": "Akismet - this field requires author's email address",_x000D_
                                    "optionType": "checkbox"_x000D_
                                }_x000D_
                            ],_x000D_
                            "jsValues": "",_x000D_
                            "jsPlaceholder": false,_x000D_
                            "jsAkismetAuthorEmail": false,_x000D_
                            "jsIdAttribute": "",_x000D_
                            "jsClassAttribute": "",_x000D_
                            "jssIcon": "typcn typcn-mail",_x000D_
                            "noChildren": true_x000D_
                        }]_x000D_
                    },_x000D_
                    {_x000D_
                        "jssType": "list-li",_x000D_
                        "jssSelectLabel": "List Item - li",_x000D_
                        "jssSelectGroup": "jssItem",_x000D_
                        "jsName": "list-li-855",_x000D_
                        "jssLabel": "",_x000D_
                        "jssIcon": "dashicons dashicons-editor-ul",_x000D_
                        "noChildren": false,_x000D_
                        "expanded": true,_x000D_
                        "children": [{_x000D_
                            "jssType": "textarea",_x000D_
                            "jssSelectLabel": "Textarea (long text)",_x000D_
                            "jssSelectGroup": "jsTag",_x000D_
                            "jsName": "textarea-217",_x000D_
                            "jssLabel": "Your Message",_x000D_
                            "jsRequired": false,_x000D_
                            "jsTagOptions": [{_x000D_
                                    "jsOption": "",_x000D_
                                    "optionLabel": "Default value",_x000D_
                                    "optionType": "input"_x000D_
                                },_x000D_
                                {_x000D_
                                    "jsOption": "placeholder",_x000D_
                                    "isChecked": false,_x000D_
                                    "optionLabel": "Use this text as the placeholder of the field",_x000D_
                                    "optionType": "checkbox"_x000D_
                                }_x000D_
                            ],_x000D_
                            "jsValues": "",_x000D_
                            "jsPlaceholder": false,_x000D_
                            "jsIdAttribute": "",_x000D_
                            "jsClassAttribute": "",_x000D_
                            "jssIcon": "typcn typcn-document-text",_x000D_
                            "noChildren": true_x000D_
                        }]_x000D_
                    }_x000D_
                ]_x000D_
            },_x000D_
            {_x000D_
                "jssType": "paragraph",_x000D_
                "jssSelectLabel": "Paragraph - p",_x000D_
                "jssSelectGroup": "jssItem",_x000D_
                "jsName": "paragraph-993",_x000D_
                "jssContent": "* Required",_x000D_
                "jssIcon": "dashicons dashicons-editor-paragraph",_x000D_
                "noChildren": true_x000D_
            }_x000D_
        ]_x000D_
        _x000D_
    },_x000D_
    {_x000D_
        "jssType": "submit",_x000D_
        "jssSelectLabel": "Submit",_x000D_
        "jssSelectGroup": "jsTag",_x000D_
        "jsName": "submit-704",_x000D_
        "jssLabel": "Send",_x000D_
        "jsValues": "",_x000D_
        "jsRequired": false,_x000D_
        "jsIdAttribute": "",_x000D_
        "jsClassAttribute": "",_x000D_
        "jssIcon": "typcn typcn-mail",_x000D_
        "noChildren": true_x000D_
    },_x000D_
    _x000D_
];_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
 function findObjectByLabel(obj, label) {_x000D_
       for(var elements in obj){_x000D_
           if (elements === label){_x000D_
                console.log(obj[elements]);_x000D_
           }_x000D_
            if(typeof obj[elements] === 'object'){_x000D_
            findObjectByLabel(obj[elements], 'jssType');_x000D_
           }_x000D_
          _x000D_
       }_x000D_
};_x000D_
_x000D_
 findObjectByLabel(treeData, 'jssType');
_x000D_
_x000D_
_x000D_

How to set the value for Radio Buttons When edit?

    Gender :<br>
    <input type="radio" name="g" value="male"  <?php echo ($g=='Male')?'checked':'' ?>>male <br>
    <input type="radio" name="g" value="female"<?php echo ($g=='female')?'checked':'' ?>>female
            <?php echo $errors['g'];?>

How to remove whitespace from a string in typescript?

Problem

The trim() method removes whitespace from both sides of a string.

Source

Solution

You can use a Javascript replace method to remove white space like

"hello world".replace(/\s/g, "");

Example

_x000D_
_x000D_
var out = "hello world".replace(/\s/g, "");_x000D_
console.log(out);
_x000D_
_x000D_
_x000D_

How to display my location on Google Maps for Android API v2

Before enabling the My Location layer, you must request location permission from the user. This sample does not include a request for location permission.

To simplify, in terms of lines of code, the request for the location permit can be made using the library EasyPermissions.

Then following the example of the official documentation of The My Location Layer my code works as follows for all versions of Android that contain Google services.

  1. Create an activity that contains a map and implements the interfaces OnMyLocationClickListener y OnMyLocationButtonClickListener.
  2. Define in app/build.gradle implementation 'pub.devrel:easypermissions:2.0.1'
  3. Forward results to EasyPermissions within method onRequestPermissionsResult()

    EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);

  4. Request permission and operate according to the user's response with requestLocationPermission()

  5. Call requestLocationPermission() and set the listeners to onMapReady().

MapsActivity.java

public class MapsActivity extends FragmentActivity implements 
    OnMapReadyCallback,
    GoogleMap.OnMyLocationClickListener,
    GoogleMap.OnMyLocationButtonClickListener {

    private final int REQUEST_LOCATION_PERMISSION = 1;

    private GoogleMap mMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        requestLocationPermission();
        mMap.setOnMyLocationButtonClickListener(this);
        mMap.setOnMyLocationClickListener(this);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @SuppressLint("MissingPermission")
    @AfterPermissionGranted(REQUEST_LOCATION_PERMISSION)
    public void requestLocationPermission() {
        String[] perms = {Manifest.permission.ACCESS_FINE_LOCATION};
        if(EasyPermissions.hasPermissions(this, perms)) {
            mMap.setMyLocationEnabled(true);
            Toast.makeText(this, "Permission already granted", Toast.LENGTH_SHORT).show();
        }
        else {
            EasyPermissions.requestPermissions(this, "Please grant the location permission", REQUEST_LOCATION_PERMISSION, perms);
        }
    }

    @Override
    public boolean onMyLocationButtonClick() {
        Toast.makeText(this, "MyLocation button clicked", Toast.LENGTH_SHORT).show();
        return false;
    }

    @Override
    public void onMyLocationClick(@NonNull Location location) {
        Toast.makeText(this, "Current location:\n" + location, Toast.LENGTH_LONG).show();
    }
}

Source

How to show full height background image?

CSS can do that with background-size: cover;

But to be more detailed and support more browsers...

Use aspect ratio like this:

 aspectRatio      = $bg.width() / $bg.height();

FIDDLE

Free easy way to draw graphs and charts in C++?

I've used this "portable plotter". It's very small, multiplatform, easy to use and you can plug it into different graphical libraries. pplot

(Only for the plots part)

If you use or plan to use Qt, another multiplatform solution is Qwt and Qchart

How to correctly assign a new string value?

The first example doesn't work because you can't assign values to arrays - arrays work (sort of) like const pointers in this respect. What you can do though is copy a new value into the array:

strcpy(p.name, "Jane");

Char arrays are fine to use if you know the maximum size of the string in advance, e.g. in the first example you are 100% sure that the name will fit into 19 characters (not 20 because one character is always needed to store the terminating zero value).

Conversely, pointers are better if you don't know the possible maximum size of your string, and/or you want to optimize your memory usage, e.g. avoid reserving 512 characters for the name "John". However, with pointers you need to dynamically allocate the buffer they point to, and free it when not needed anymore, to avoid memory leaks.

Update: example of dynamically allocated buffers (using the struct definition in your 2nd example):

char* firstName = "Johnnie";
char* surname = "B. Goode";
person p;

p.name = malloc(strlen(firstName) + 1);
p.surname = malloc(strlen(surname) + 1);

p.age = 25;
strcpy(p.name, firstName);
strcpy(p.surname, surname);

printf("Name: %s; Age: %d\n",p.name,p.age);

free(p.surname);
free(p.name);

Batch: Remove file extension

In case the file your variable holds doesn't actually exist the FOR approach won't work. One trick you could use, if you know the length of the extension, is taking a substring:

%var:~0,-4%

the -4 means that the last 4 digits (presumably .ext) will be truncated.

Generating a unique machine id

There is a library available for getting hardware specific informations: Hardware serial number extractor (CPU, RAM, HDD, BIOS)

Your project contains error(s), please fix it before running it

Delete the .android folder from your Documents&settings\User\ on XP and \User\ on Win7. Recreate the AVD again and create a new project.

Excel: How to check if a cell is empty with VBA?

IsEmpty() would be the quickest way to check for that.

IsNull() would seem like a similar solution, but keep in mind Null has to be assigned to the cell; it's not inherently created in the cell.

Also, you can check the cell by:

count()

counta()

Len(range("BCell").Value) = 0

Android Studio don't generate R.java for my import project

Just use the 'Rebuild Project' from the 'Build' menu from the top menu bar.

How to make a great R reproducible example

I wonder if an http://old.r-fiddle.org/ link could be a very neat way of sharing a problem. It receives a unique ID like and one could even think about embedding it in SO.

Perform a Shapiro-Wilk Normality Test

What does shapiro.test do?

shapiro.test tests the Null hypothesis that "the samples come from a Normal distribution" against the alternative hypothesis "the samples do not come from a Normal distribution".

How to perform shapiro.test in R?

The R help page for ?shapiro.test gives,

x - a numeric vector of data values. Missing values are allowed, 
    but the number of non-missing values must be between 3 and 5000.

That is, shapiro.test expects a numeric vector as input, that corresponds to the sample you would like to test and it is the only input required. Since you've a data.frame, you'll have to pass the desired column as input to the function as follows:

> shapiro.test(heisenberg$HWWIchg)
#   Shapiro-Wilk normality test

# data:  heisenberg$HWWIchg 
# W = 0.9001, p-value = 0.2528

Interpreting results from shapiro.test:

First, I strongly suggest you read this excellent answer from Ian Fellows on testing for normality.

As shown above, the shapiro.test tests the NULL hypothesis that the samples came from a Normal distribution. This means that if your p-value <= 0.05, then you would reject the NULL hypothesis that the samples came from a Normal distribution. As Ian Fellows nicely put it, you are testing against the assumption of Normality". In other words (correct me if I am wrong), it would be much better if one tests the NULL hypothesis that the samples do not come from a Normal distribution. Why? Because, rejecting a NULL hypothesis is not the same as accepting the alternative hypothesis.

In case of the null hypothesis of shapiro.test, a p-value <= 0.05 would reject the null hypothesis that the samples come from normal distribution. To put it loosely, there is a rare chance that the samples came from a normal distribution. The side-effect of this hypothesis testing is that this rare chance happens very rarely. To illustrate, take for example:

set.seed(450)
x <- runif(50, min=2, max=4)
shapiro.test(x)
#   Shapiro-Wilk normality test
# data:  runif(50, min = 2, max = 4) 
# W = 0.9601, p-value = 0.08995

So, this (particular) sample runif(50, min=2, max=4) comes from a normal distribution according to this test. What I am trying to say is that, there are many many cases under which the "extreme" requirements (p < 0.05) are not satisfied which leads to acceptance of "NULL hypothesis" most of the times, which might be misleading.

Another issue I'd like to quote here from @PaulHiemstra from under comments about the effects on large sample size:

An additional issue with the Shapiro-Wilk's test is that when you feed it more data, the chances of the null hypothesis being rejected becomes larger. So what happens is that for large amounts of data even very small deviations from normality can be detected, leading to rejection of the null hypothesis event though for practical purposes the data is more than normal enough.

Although he also points out that R's data size limit protects this a bit:

Luckily shapiro.test protects the user from the above described effect by limiting the data size to 5000.

If the NULL hypothesis were the opposite, meaning, the samples do not come from a normal distribution, and you get a p-value < 0.05, then you conclude that it is very rare that these samples do not come from a normal distribution (reject the NULL hypothesis). That loosely translates to: It is highly likely that the samples are normally distributed (although some statisticians may not like this way of interpreting). I believe this is what Ian Fellows also tried to explain in his post. Please correct me if I've gotten something wrong!

@PaulHiemstra also comments about practical situations (example regression) when one comes across this problem of testing for normality:

In practice, if an analysis assumes normality, e.g. lm, I would not do this Shapiro-Wilk's test, but do the analysis and look at diagnostic plots of the outcome of the analysis to judge whether any assumptions of the analysis where violated too much. For linear regression using lm this is done by looking at some of the diagnostic plots you get using plot(lm()). Statistics is not a series of steps that cough up a few numbers (hey p < 0.05!) but requires a lot of experience and skill in judging how to analysis your data correctly.

Here, I find the reply from Ian Fellows to Ben Bolker's comment under the same question already linked above equally (if not more) informative:

For linear regression,

  1. Don't worry much about normality. The CLT takes over quickly and if you have all but the smallest sample sizes and an even remotely reasonable looking histogram you are fine.

  2. Worry about unequal variances (heteroskedasticity). I worry about this to the point of (almost) using HCCM tests by default. A scale location plot will give some idea of whether this is broken, but not always. Also, there is no a priori reason to assume equal variances in most cases.

  3. Outliers. A cooks distance of > 1 is reasonable cause for concern.

Those are my thoughts (FWIW).

Hope this clears things up a bit.

Pythonic way to combine FOR loop and IF statement

You can use generators too, if generator expressions become too involved or complex:

def gen():
    for x in xyz:
        if x in a:
            yield x

for x in gen():
    print x

Difference between Static methods and Instance methods

The basic paradigm in Java is that you write classes, and that those classes are instantiated. Instantiated objects (an instance of a class) have attributes associated with them (member variables) that affect their behavior; when the instance has its method executed it will refer to these variables.

However, all objects of a particular type might have behavior that is not dependent at all on member variables; these methods are best made static. By being static, no instance of the class is required to run the method.

You can do this to execute a static method:

MyClass.staticMethod();  // Simply refers to the class's static code

But to execute a non-static method, you must do this:

MyClass obj = new MyClass();//Create an instance
obj.nonstaticMethod();  // Refer to the instance's class's code

On a deeper level the compiler, when it puts a class together, collects pointers to methods and attaches them to the class. When those methods are executed it follows the pointers and executes the code at the far end. If a class is instantiated, the created object contains a pointer to the "virtual method table", which points to the methods to be called for that particular class in the inheritance hierarchy. However, if the method is static, no "virtual method table" is needed: all calls to that method go to the exact same place in memory to execute the exact same code. For that reason, in high-performance systems it's better to use a static method if you are not reliant on instance variables.

what is the differences between sql server authentication and windows authentication..?

Ideally, Windows authentication must be used when working in an Intranet type of an environment.

Whereas, SQL Server authentication can be used in all the other type of cases.

Here is a link which might help.

Windows Authentication vs. SQL Server Authentication

Rails Object to hash

Old question, but heavily referenced ... I think most people use other methods, but there is infact a to_hash method, it has to be setup right. Generally, pluck is a better answer after rails 4 ... answering this mainly because I had to search a bunch to find this thread or anything useful & assuming others are hitting the same problem...

Note: not recommending this for everyone, but edge cases!


From the ruby on rails api ... http://api.rubyonrails.org/classes/ActiveRecord/Result.html ...

This class encapsulates a result returned from calling #exec_query on any database connection adapter. For example:

result = ActiveRecord::Base.connection.exec_query('SELECT id, title, body FROM posts')
result # => #<ActiveRecord::Result:0xdeadbeef>

...

# Get an array of hashes representing the result (column => value):
result.to_hash
# => [{"id" => 1, "title" => "title_1", "body" => "body_1"},
      {"id" => 2, "title" => "title_2", "body" => "body_2"},
      ...
     ] ...

How to display table data more clearly in oracle sqlplus

I usually start with something like:

set lines 256
set trimout on
set tab off

Have a look at help set if you have the help information installed. And then select name,address rather than select * if you really only want those two columns.

Converting unix time into date-time via excel

=A1/(24*60*60) + DATE(1970;1;1) should work with seconds.

=(A1/86400/1000)+25569 if your time is in milliseconds, so dividing by 1000 gives use the correct date

Don't forget to set the type to Date on your output cell. I tried it with this date: 1504865618099 which is equal to 8-09-17 10:13.

What is "X-Content-Type-Options=nosniff"?

A really simple explanation that I found useful: the nosniff response header is a way to keep a website more secure.

From Security Researcher, Scott Helme, here:

It prevents Google Chrome and Internet Explorer from trying to mime-sniff the content-type of a response away from the one being declared by the server.

What does "./" (dot slash) refer to in terms of an HTML file path location?

In reference to the quick reference list, specifically you can use the following :

\.\ Root Directory + Current directory (Drive Letter)

How can I refresh c# dataGridView after update ?

You just need to redefine the DataSource. So if you have for example DataGridView's DataSource that contains a, b, i c:

DataGridView.DataSource = a, b, c

And suddenly you update the DataSource so you have just a and b, you would need to redefine your DataSource:

DataGridView.DataSource = a, b

I hope you find this useful.

Thank you.

Test if registry value exists

The best way to test if a registry value exists is to do just that - test for its existence. This is a one-liner, even if it's a little hard to read.

PS C:> (Get-ItemProperty $regkey).PSObject.Properties.Name -contains $name

If you actually look up its data, then you run into the complication of how Powershell interprets 0.

Server http:/localhost:8080 requires a user name and a password. The server says: XDB

you can find the username and password details in your {tomcat installation directory}/conf/tomcat-users.xml

PHP - syntax error, unexpected T_CONSTANT_ENCAPSED_STRING

$out.='<option value="'.$key.'">'.$value["name"];

me funciono con esta

"<a  href='javascript:void(0)' onclick='cargar_datos_cliente(\"$row->DSC_EST\")' class='button micro asignar margin-none'>Editar</a>";

How do I find the data directory for a SQL Server instance?

Various components of SQL Server (Data, Logs, SSAS, SSIS, etc) have a default directory. The setting for this can be found in the registry. Read more here:

http://technet.microsoft.com/en-us/library/ms143547%28SQL.90%29.aspx

So if you created a database using just CREATE DATABASE MyDatabaseName it would be created at the path specified in one of the settings above.

Now, if the admin / installer changed the default path, then the default path for the instance is stored in the registry at

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\[INSTANCENAME]\Setup

If you know the name of the instance then you can query the registry. This example is SQL 2008 specific - let me know if you need the SQL2005 path as well.

DECLARE @regvalue varchar(100)

EXEC master.dbo.xp_regread @rootkey='HKEY_LOCAL_MACHINE',
        @key='SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10.MSSQLServer\Setup',
        @value_name='SQLDataRoot',
        @value=@regvalue OUTPUT,
        @output = 'no_output'

SELECT @regvalue as DataAndLogFilePath

Each database can be created overriding the server setting in a it's own location when you issue the CREATE DATABASE DBName statement with the appropriate parameters. You can find that out by executing sp_helpdb

exec sp_helpdb 'DBName'

android - How to get view from context?

Starting with a context, the root view of the associated activity can be had by

View rootView = ((Activity)_context).Window.DecorView.FindViewById(Android.Resource.Id.Content);

In Raw Android it'd look something like:

View rootView = ((Activity)mContext).getWindow().getDecorView().findViewById(android.R.id.content)

Then simply call the findViewById on this

View v = rootView.findViewById(R.id.your_view_id);

Jenkins CI: How to trigger builds on SVN commit

You can use a post-commit hook.

Put the post-commit hook script in the hooks folder, create a wget_folder in your C:\ drive, and put the wget.exe file in this folder. Add the following code in the file called post-commit.bat

SET REPOS=%1   
SET REV=%2

FOR /f "tokens=*" %%a IN (  
'svnlook uuid %REPOS%'  
) DO (  
SET UUID=%%a  
)  

FOR /f "tokens=*" %%b IN (  
'svnlook changed --revision %REV% %REPOS%'  
) DO (  
SET POST=%%b   
)

echo %REPOS% ----- 1>&2

echo %REV% -- 1>&2

echo %UUID% --1>&2

echo %POST% --1>&2

C:\wget_folder\wget ^   
    --header="Content-Type:text/plain" ^   
    --post-data="%POST%" ^   
    --output-document="-" ^   
    --timeout=2 ^     
    http://localhost:9090/job/Test/build/%UUID%/notifyCommit?rev=%REV%    

where Test = name of the job

echo is used to see the value and you can also add exit 2 at the end to know about the issue and whether the post-commit hook script is running or not.

LINQ to read XML

Or, if you want a more general approach - i.e. for nesting up to "levelN":

void Main()
{
    XElement rootElement = XElement.Load(@"c:\events\test.xml");

    Console.WriteLine(GetOutline(0, rootElement));  
}

private string GetOutline(int indentLevel, XElement element)
{
    StringBuilder result = new StringBuilder();

    if (element.Attribute("name") != null)
    {
        result = result.AppendLine(new string(' ', indentLevel * 2) + element.Attribute("name").Value);
    }

    foreach (XElement childElement in element.Elements())
    {
        result.Append(GetOutline(indentLevel + 1, childElement));
    }

    return result.ToString();
}

HTML code for an apostrophe

&#39; in decimal.

%27 in hex.

How should I import data from CSV into a Postgres table using pgAdmin 3?

You may have a table called 'test'

COPY test(gid, "name", the_geom)
FROM '/home/data/sample.csv'
WITH DELIMITER ','
CSV HEADER

jQuery select box validation

Since you cannot set value="" within your first option, you'll need to create your own rule using the built-in addMethod() method.

jQuery:

$(document).ready(function () {

    $('#myform').validate({ // initialize the plugin
        rules: {
            year: {
                selectcheck: true
            }
        }
    });

    jQuery.validator.addMethod('selectcheck', function (value) {
        return (value != '0');
    }, "year required");

});

HTML:

<select name="year">
    <option value="0">Year</option>
    <option value="1">1955</option>
    <option value="2">1956</option>
</select>

Working Demo: http://jsfiddle.net/tPRNd/


Original Answer: (Only if you can set value="" within the first option)

To properly validate a select element with the jQuery Validate plugin simply requires that the first option contains value="". So remove the 0 from value="0" and it's fixed.

jQuery:

$(document).ready(function () {

    $('#myform').validate({ // initialize the plugin
        rules: {
            year: {
                required: true,
            }
        }
    });

});

HTML:

<select name="year">
    <option value="">Year</option>
    <option value="1">1955</option>
    <option value="2">1956</option>
</select>

Demo: http://jsfiddle.net/XGtEr/

Android emulator doesn't take keyboard input - SDK tools rev 20

In your home folder /.android/avd//config.ini add the line hw.keyboard=yes

How to write to a file without overwriting current contents?

Instead of "w" use "a" (append) mode with open function:

with open("games.txt", "a") as text_file:

How do I know which version of Javascript I'm using?

Click on this link to see which version your BROWSER is using: http://jsfiddle.net/Ac6CT/

You should be able filter by using script tags to each JS version.

<script type="text/javascript">
  var jsver = 1.0;
</script>
<script language="Javascript1.1">
  jsver = 1.1;
</script>
<script language="Javascript1.2">
  jsver = 1.2;
</script>
<script language="Javascript1.3">
  jsver = 1.3;
</script>
<script language="Javascript1.4">
  jsver = 1.4;
</script>
<script language="Javascript1.5">
  jsver = 1.5;
</script>
<script language="Javascript1.6">
  jsver = 1.6;
</script>
<script language="Javascript1.7">
  jsver = 1.7;
</script>
<script language="Javascript1.8">
  jsver = 1.8;
</script>
<script language="Javascript1.9">
  jsver = 1.9;
</script>

<script type="text/javascript">
  alert(jsver);
</script>

My Chrome reports 1.7

Blatantly stolen from: http://javascript.about.com/library/bljver.htm

How can you get the active users connected to a postgreSQL database via SQL?

OP asked for users connected to a particular database:

-- Who's currently connected to my_great_database?
SELECT * FROM pg_stat_activity 
  WHERE datname = 'my_great_database';

This gets you all sorts of juicy info (as others have mentioned) such as

  • userid (column usesysid)
  • username (usename)
  • client application name (appname), if it bothers to set that variable -- psql does :-)
  • IP address (client_addr)
  • what state it's in (a couple columns related to state and wait status)
  • and everybody's favorite, the current SQL command being run (query)

Swift double to string

In addition to @Zaph answer, you can create extension:

extension Double {
    func toString() -> String {
        return String(format: "%.1f",self)
    }
}

Usage:

var a:Double = 1.5
println("output: \(a.toString())")  // output: 1.5

Java Delegates?

Depending precisely what you mean, you can achieve a similar effect (passing around a method) using the Strategy Pattern.

Instead of a line like this declaring a named method signature:

// C#
public delegate void SomeFunction();

declare an interface:

// Java
public interface ISomeBehaviour {
   void SomeFunction();
}

For concrete implementations of the method, define a class that implements the behaviour:

// Java
public class TypeABehaviour implements ISomeBehaviour {
   public void SomeFunction() {
      // TypeA behaviour
   }
}

public class TypeBBehaviour implements ISomeBehaviour {
   public void SomeFunction() {
      // TypeB behaviour
   }
}

Then wherever you would have had a SomeFunction delegate in C#, use an ISomeBehaviour reference instead:

// C#
SomeFunction doSomething = SomeMethod;
doSomething();
doSomething = SomeOtherMethod;
doSomething();

// Java
ISomeBehaviour someBehaviour = new TypeABehaviour();
someBehaviour.SomeFunction();
someBehaviour = new TypeBBehaviour();
someBehaviour.SomeFunction();

With anonymous inner classes, you can even avoid declaring separate named classes and almost treat them like real delegate functions.

// Java
public void SomeMethod(ISomeBehaviour pSomeBehaviour) {
   ...
}

...

SomeMethod(new ISomeBehaviour() { 
   @Override
   public void SomeFunction() {
      // your implementation
   }
});

This should probably only be used when the implementation is very specific to the current context and wouldn't benefit from being reused.

And then of course in Java 8, these do become basically lambda expressions:

// Java 8
SomeMethod(() -> { /* your implementation */ });

Turning multiple lines into one comma separated line

xargs -a your_file | sed 's/ /,/g'

This is a shorter way.

list.clear() vs list = new ArrayList<Integer>();

I think that the answer is that it depends on a whole range of factors such as:

  • whether the list size can be predicted beforehand (i.e. can you set the capacity accurately),
  • whether the list size is variable (i.e. each time it is filled),
  • how long the lifetime of the list will be in both versions, and
  • your heap / GC parameters and CPU.

These make it hard to predict which will be better. But my intuition is that the difference will not be that great.

Two bits of advice on optimization:

  • Don't waste time trying to optimize this ... unless the application is objectively too slow AND measurement using a profiler tells you that this is a performance hotspot. (The chances are that one of those preconditions won't be true.)

  • If you do decide to optimize this, do it scientifically. Try both (all) of the alternatives and decide which is best by measuring the performance in your actual application on a realistic problem / workload / input set. (An artificial benchmark is liable to give you answers that do not predict real-world behavior, because of factors like those I listed previously.)

How do you use String.substringWithRange? (or, how do Ranges work in Swift?)

Swift 2

Simple

let str = "My String"
let subStr = str[str.startIndex.advancedBy(3)...str.startIndex.advancedBy(7)]
//"Strin"

Swift 3

let startIndex = str.index(str.startIndex, offsetBy: 3)
let endIndex = str.index(str.startIndex, offsetBy: 7)

str[startIndex...endIndex]       // "Strin"
str.substring(to: startIndex)    // "My "
str.substring(from: startIndex)  // "String"

Swift 4

substring(to:) and substring(from:) are deprecated in Swift 4.

String(str[..<startIndex])    // "My "
String(str[startIndex...])    // "String"
String(str[startIndex...endIndex])    // "Strin"

How to increment a JavaScript variable using a button press event

Yes:

<script type="text/javascript">
var counter = 0;
</script>

and

<button onclick="counter++">Increment</button>

How to make Bootstrap carousel slider use mobile left/right swipe

Same functionality I prefer than using much heavy jQuery mobile is Carousel Swipe. I suggest directly jump in to source code on github, and copy file carousel-swipe.js in to your project directory.

Use swiper events as bellow:

$('#carousel-example-generic').carousel({
      interval: false 
  });

How to use range-based for() loop with std::map?

In C++17 this is called structured bindings, which allows for the following:

std::map< foo, bar > testing = { /*...blah...*/ };
for ( const auto& [ k, v ] : testing )
{
  std::cout << k << "=" << v << "\n";
}

Run Java Code Online

I found this online java compiler and runner. It work also with threads and showing results immediately. http://www.browxy.com

no operator "<<" matches these operands

If you want to use std::string reliably, you must #include <string>.

How to know Laravel version and where is it defined?

If you want to know the specific version then you need to check composer.lock file and search For

"name": "laravel/framework",

you will find your version in next line

"version": "v5.7.9",

How to import csv file in PHP?

$row = 1;
    $arrResult  = array();
    if (($handle = fopen("ifsc_code.csv", "r")) !== FALSE) {
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
            $num = count($data);
            DB::table('banks')->insert(
                array('bank_name' => $data[1], 'ifsc' => $data[2], 'micr' => $data[3], 'branch_name' => $data[4],'address' => $data[5], 'contact' => $data[6], 'city' => $data[7],'district' => $data[8],'state' => $data[9])
            );
        }
        fclose($handle);
    }

CSS white space at bottom of page despite having both min-height and height tag

I find it quite remarkable that out of 6 answers, none of them have mentioned the real source of the problem.

Collapsing margins on the last p inside #fw-footer is where that extra space is originating from.

A sensible fix would be to add overflow: hidden to #fw-footer (or simply add margin: 0 on the last p).

You could also just move the script inside that last p outside of the p, and then remove the p entirely; there's no need to wrap a script in a p. The first p (#fw-foottext) has margin: 0 applied, so the problem won't happen with that one.


As an aside, you've broken the fix I gave you in this question:

CSS3 gradient background with unwanted white space at bottom

You need html { height: 100% } and body { min-height: 100% }.

At the moment, you have html { height: auto } being applied, which does not work:

(This happens with a window taller than the content on the page)

Synchronizing a local Git repository with a remote one

The permanent fix if one wants to create a new branch on the remote to mirror and track your local branch(or, vice-versa) is:

git config --global push.default current

I always configure my local git with this command after I do git clone. Although it can be applied anytime when the local-remote branch "Git fatal: The current branch has no upstream branch" error occurs.

Hope this helps. Much peace. :)

Hbase quickly count number of rows

You could try hbase api methods!

org.apache.hadoop.hbase.client.coprocessor.AggregationClient

How to change MySQL data directory?

  1. Stop MySQL using the following command:

    sudo /etc/init.d/mysql stop
    
  2. Copy the existing data directory (default located in /var/lib/mysql) using the following command:

    sudo cp -R -p /var/lib/mysql /newpath
    
  3. edit the MySQL configuration file with the following command:

    sudo gedit /etc/mysql/my.cnf   # or perhaps /etc/mysql/mysql.conf.d/mysqld.cnf
    
  4. Look for the entry for datadir, and change the path (which should be /var/lib/mysql) to the new data directory.

  5. In the terminal, enter the command:

    sudo gedit /etc/apparmor.d/usr.sbin.mysqld
    
  6. Look for lines beginning with /var/lib/mysql. Change /var/lib/mysql in the lines with the new path.

  7. Save and close the file.

  8. Restart the AppArmor profiles with the command:

    sudo /etc/init.d/apparmor reload
    
  9. Restart MySQL with the command:

    sudo /etc/init.d/mysql restart
    
  10. Now login to MySQL and you can access the same databases you had before.

Sorting HTML table with JavaScript

In case your table does not have ths but only tds (with headers included) you can try the following which is based on Nick Grealy's answer above:

_x000D_
_x000D_
const getCellValue = (tr, idx) => tr.children[idx].innerText || tr.children[idx].textContent;_x000D_
_x000D_
const comparer = (idx, asc) => (a, b) => ((v1, v2) => _x000D_
    v1 !== '' && v2 !== '' && !isNaN(v1) && !isNaN(v2) ? v1 - v2 : v1.toString().localeCompare(v2)_x000D_
    )(getCellValue(asc ? a : b, idx), getCellValue(asc ? b : a, idx));_x000D_
_x000D_
// do the work..._x000D_
document.querySelectorAll('tr:first-child td').forEach(td => td.addEventListener('click', (() => {_x000D_
    const table = td.closest('table');_x000D_
    Array.from(table.querySelectorAll('tr:nth-child(n+2)'))_x000D_
        .sort(comparer(Array.from(td.parentNode.children).indexOf(td), this.asc = !this.asc))_x000D_
        .forEach(tr => table.appendChild(tr) );_x000D_
})));
_x000D_
@charset "UTF-8";_x000D_
@import url('https://fonts.googleapis.com/css?family=Roboto');_x000D_
_x000D_
*{_x000D_
  font-family: 'Roboto', sans-serif;_x000D_
  text-transform:capitalize;_x000D_
  overflow:hidden;_x000D_
  margin: 0 auto;_x000D_
  text-align:left;_x000D_
}_x000D_
_x000D_
table {_x000D_
 color:#666;_x000D_
 font-size:12px;_x000D_
 background:#124;_x000D_
 border:#ccc 1px solid;_x000D_
 -moz-border-radius:3px;_x000D_
 -webkit-border-radius:3px;_x000D_
 border-radius:3px;_x000D_
  border-collapse: collapse;_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
table td {_x000D_
 padding:10px;_x000D_
 border-top: 1px solid #ffffff;_x000D_
 border-bottom:1px solid #e0e0e0;_x000D_
 border-left: 1px solid #e0e0e0;_x000D_
 background: #fafafa;_x000D_
 background: -webkit-gradient(linear, left top, left bottom, from(#fbfbfb), to(#fafafa));_x000D_
 background: -moz-linear-gradient(top,  #fbfbfb,  #fafafa);_x000D_
  width: 6.9in;_x000D_
}_x000D_
_x000D_
table tbody tr:first-child td_x000D_
{_x000D_
 background: #124!important;_x000D_
  color:#fff;_x000D_
}_x000D_
_x000D_
table tbody tr th_x000D_
{_x000D_
  padding:10px;_x000D_
  border-left: 1px solid #e0e0e0;_x000D_
 background: #124!important;_x000D_
  color:#fff;_x000D_
}
_x000D_
<table>_x000D_
        <tr><td>Country</td><td>Date</td><td>Size</td></tr>_x000D_
        <tr><td>France</td><td>2001-01-01</td><td><i>25</i></td></tr>_x000D_
        <tr><td>spain</td><td>2005-05-05</td><td></td></tr>_x000D_
        <tr><td>Lebanon</td><td>2002-02-02</td><td><b>-17</b></td></tr>_x000D_
        <tr><td>Argentina</td><td>2005-04-04</td><td>100</td></tr>_x000D_
        <tr><td>USA</td><td></td><td>-6</td></tr>_x000D_
    </table>
_x000D_
_x000D_
_x000D_

How to copy and paste worksheets between Excel workbooks?

Not tested, but something like:

Dim sourceSheet As Worksheet
Dim destSheet As Worksheet

'' copy from the source
Workbooks.Open Filename:="c:\source.xls"
Set sourceSheet = Worksheets("source")
sourceSheet.Activate
sourceSheet.Cells.Select
Selection.Copy

'' paste to the destination
Workbooks.Open Filename:="c:\destination.xls"
Set destSheet = Worksheets("dest")
destSheet.Activate
destSheet.Cells.Select
destSheet.Paste

'' save & close
ActiveWorkbook.Save
ActiveWorkbook.Close

Note that this assumes the destination sheet already exists. It's pretty easy to create one if it doesn't.

400 BAD request HTTP error code meaning?

Selecting a HTTP response code is quite an easy task and can be described by simple rules. The only tricky part which is often forgotten is paragraph 6.5 from RFC 7231:

Except when responding to a HEAD request, the server SHOULD send a representation containing an explanation of the error situation, and whether it is a temporary or permanent condition.

Rules are as following:

  1. If request was successful, then return 2xx code (3xx for redirect). If there was an internal logic error on a server, then return 5xx. If there is anything wrong in client request, then return 4xx code.
  2. Look through available response code from selected category. If one of them has a name which matches well to your situation, you can use it. Otherwise just fallback to x00 code (200, 400, 500). If you doubt, fallback to x00 code.
  3. Return error description in response body. For 4xx codes it must contain enough information for client developer to understand the reason and fix the client. For 5xx because of security reasons no details must be revealed.
  4. If client needs to distinguish different errors and have different reaction depending on it, define a machine readable and extendible error format and use it everywhere in your API. It is good practice to make that from very beginning.
  5. Keep in mind that client developer may do strange things and try to parse strings which you return as human readable description. And by changing the strings you will break such badly written clients. So always provide machine readable description and try to avoid reporting additional information in text.

So in your case I'd returned 400 error and something like this if "Roman" is obtained from user input and client must have specific reaction:

{
    "error_type" : "unsupported_resource",
    "error_description" : "\"Roman\" is not supported"
}

or a more generic error, if such situation is a bad logic error in a client and is not expected, unless developer made something wrong:

{
    "error_type" : "malformed_json",
    "error_description" : "\"Roman\" is not supported for \"requestedResource\" field"
}

Detect encoding and make everything UTF-8

A really nice way to implement an isUTF8-function can be found on php.net:

function isUTF8($string) {
    return (utf8_encode(utf8_decode($string)) == $string);
}

Parsing Query String in node.js

There's also the QueryString module's parse() method:

var http = require('http'),
    queryString = require('querystring');

http.createServer(function (oRequest, oResponse) {

    var oQueryParams;

    // get query params as object
    if (oRequest.url.indexOf('?') >= 0) {
        oQueryParams = queryString.parse(oRequest.url.replace(/^.*\?/, ''));

        // do stuff
        console.log(oQueryParams);
    }

    oResponse.writeHead(200, {'Content-Type': 'text/plain'});
    oResponse.end('Hello world.');

}).listen(1337, '127.0.0.1');

Center text in div?

Add to the selector containing the text

margin:auto;

How to create a Restful web service with input parameters?

You can try this... put parameters as :
http://localhost:8080/WebApplication11/webresources/generic/getText?arg1=hello in your browser...

package newpackage;

import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;


import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PUT;
import javax.ws.rs.QueryParam;

@Path("generic")
public class GenericResource {

    @Context
    private UriInfo context;

    /**
     * Creates a new instance of GenericResource
     */
    public GenericResource() {
    }

    /**
     * Retrieves representation of an instance of newpackage.GenericResource

     * @return an instance of java.lang.String
     */
    @GET
    @Produces("text/plain")
    @Consumes("text/plain")
    @Path("getText/")
    public String getText(@QueryParam("arg1")
            @DefaultValue("") String arg1) {

       return  arg1 ;  }

    @PUT
    @Consumes("text/plain")
    public void putText(String content) {





    }
}

How do I declare and assign a variable on a single line in SQL

on sql 2008 this is valid

DECLARE @myVariable nvarchar(Max) = 'John said to Emily "Hey there Emily"'
select @myVariable

on sql server 2005, you need to do this

DECLARE @myVariable nvarchar(Max) 
select @myVariable = 'John said to Emily "Hey there Emily"'
select @myVariable

java.lang.ClassNotFoundException: org.eclipse.core.runtime.adaptor.EclipseStarter

I just went through this. If you want to manually move your Eclipse installation you need to find and edit relative references in the following files.

Relative to Eclipse install dir:

  • configuration/org.eclipse.equinox.source/source.info
  • configuration/org.eclipse.equinox.simpleconfigurator/bundles.info
  • configuration/config.ini
  • eclipse.ini

For me in all these files there was a ../ reference to a .p2 folder in my home directory. Found them all using a simple grep:

grep '../../../../' * -R

Then just hit it with sed or manually go change it. In my case I moved it up one folder so easy fix:

grep -rl '../../../../' * -R | xargs sed -i 's/..\/..\/..\/..\//..\/..\/..\//g'

Now Eclipse runs fine again.

How to use passive FTP mode in Windows command prompt?

The quote PASV command is not a command to the ftp.exe program, it is a command to the FTP server requesting a high order port for data transfer. A passive transfer is one in which the FTP data over these high order ports while control is maintained in the lower ports.

The windows ftp.exe program can be used to send the FTP server commands to make a passive data transfer between two FTP servers. A standard windows installation will not, and probably should not, have FTP server service running as an endpoint for passive transfers. So if passive transfers are needed with a standard windows box, a solution other than ftp.exe is necessary as FTPing to localhost as one of the connections won't work in most windows environments.

You can effect a passive FTP transfer between two different hosts (but not two connections on the same host) as follows:

Open up two prompts, use one to ftp.exe connect to your source FTP server and one to ftp.exe connect to your destination FTP server.

Now establish a passive connection between the servers using the raw commands PASV and PORT. The quote PASV command will respond with an IP/port in ellipsis. Use that data for the quote PORT <data> command. Your passive link is now established assuming that firewalls haven't blocked one or more of the four ports (2 for FTP control, 2 for FTP data)

Next start receive of data with the quote STOR <filename> command to the receiving FTP server then send the control command quote RETR <filename> to the source FTP server.

so for me:

client 1
> ftp.exe server1
ftp> quote PASV
227 Entering Passive Mode (10,0,3,1,54,161)

client 2 
> ftp.exe server2
ftp> quote PORT 10,0,3,1,54,54,161
ftp> quote STOR myFile

client 1
ftp> quote RETR myFile

Cavet: I'm connecting to some old FTP servers YMMV

MySQL query String contains

In addition to the answer from @WoLpH.

When using the LIKE keyword you also have the ability to limit which direction the string matches. For example:

If you were looking for a string that starts with your $needle:

... WHERE column LIKE '{$needle}%'

If you were looking for a string that ends with the $needle:

... WHERE column LIKE '%{$needle}'

Find oldest/youngest datetime object in a list

The datetime module has its own versions of min and max as available methods. https://docs.python.org/2/library/datetime.html

Django return redirect() with parameters

urls.py:

#...    
url(r'element/update/(?P<pk>\d+)/$', 'element.views.element_update', name='element_update'),

views.py:

from django.shortcuts import redirect
from .models import Element


def element_info(request):
    # ...
    element = Element.object.get(pk=1)
    return redirect('element_update', pk=element.id)

def element_update(request, pk)
    # ...

$(form).ajaxSubmit is not a function

Try ajaxsubmit library. It does ajax submition as well as validation via ajax.

Also configuration is very flexible to support any kind of UI.

Live demo available with js, css and html examples.

jQuery trigger event when click outside the element

$(document).click((e) => {
  if ($.contains($(".the-one-you-can-click-and-should-still-open").get(0), e.target)) {
  } else {
    this.onClose();
  }
}); 

How do I call Objective-C code from Swift?

Quote from the documentation:

Any Objective-C framework (or C library) that’s accessible as a module can be imported directly into Swift. This includes all of the Objective-C system frameworks—such as Foundation, UIKit, and SpriteKit—as well as common C libraries supplied with the system. For example, to import Foundation, simply add this import statement to the top of the Swift file you’re working in:

import Foundation

This import makes all of the Foundation APIs—including NSDate, NSURL, NSMutableData, and all of their methods, properties, and categories—directly available in Swift.

Delete multiple rows by selecting checkboxes using PHP

Something that sometimes crops up you may/maynot be aware of

Won't always be picked up by by $_POST['delete'] when using IE. Firefox and chrome should work fine though. I use a seperate isntead which solves the problem for IE

As for your not deleting in your code above you appear to be echoing out 2x sets of check boxes both pulling the same data? Is this just a copy + paste mistake or is this actually how your code is?

If its how your code is that'll be the problem as the user could be ticking one checkbox array item but the other one will be unchecked so the php code for delete is getting confused. Either rename the 2nd check box or delete that block of html surely you don't need to display the same list twice ?

Interview Question: Merge two sorted singly linked lists without creating new nodes

public static Node merge(Node h1, Node h2) {

    Node h3 = new Node(0);
    Node current = h3;

    boolean isH1Left = false;
    boolean isH2Left = false;

    while (h1 != null || h2 != null) {
        if (h1.data <= h2.data) {
            current.next = h1;
            h1 = h1.next;
        } else {
            current.next = h2;
            h2 = h2.next;
        }
        current = current.next;

        if (h2 == null && h1 != null) {
            isH1Left = true;
            break;
        }

        if (h1 == null && h2 != null) {
            isH2Left = true;
            break;
        }
    }

    if (isH1Left) {
        while (h1 != null) {
            current.next = h1;
            current = current.next;
            h1 = h1.next;
        }
    } 

    if (isH2Left) {
        while (h2 != null) {
            current.next = h2;
            current = current.next;
            h2 = h2.next;
        }
    }

    h3 = h3.next;

    return h3;
}

How to get Django and ReactJS to work together?

I feel your pain as I, too, am starting out to get Django and React.js working together. Did a couple of Django projects, and I think, React.js is a great match for Django. However, it can be intimidating to get started. We are standing on the shoulders of giants here ;)

Here's how I think, it all works together (big picture, please someone correct me if I'm wrong).

  • Django and its database (I prefer Postgres) on one side (backend)
  • Django Rest-framework providing the interface to the outside world (i.e. Mobile Apps and React and such)
  • Reactjs, Nodejs, Webpack, Redux (or maybe MobX?) on the other side (frontend)

Communication between Django and 'the frontend' is done via the Rest framework. Make sure you get your authorization and permissions for the Rest framework in place.

I found a good boiler template for exactly this scenario and it works out of the box. Just follow the readme https://github.com/scottwoodall/django-react-template and once you are done, you have a pretty nice Django Reactjs project running. By no means this is meant for production, but rather as a way for you to dig in and see how things are connected and working!

One tiny change I'd like to suggest is this: Follow the setup instructions BUT before you get to the 2nd step to setup the backend (Django here https://github.com/scottwoodall/django-react-template/blob/master/backend/README.md), change the requirements file for the setup.

You'll find the file in your project at /backend/requirements/common.pip Replace its content with this

appdirs==1.4.0
Django==1.10.5
django-autofixture==0.12.0
django-extensions==1.6.1
django-filter==1.0.1
djangorestframework==3.5.3
psycopg2==2.6.1

this gets you the latest stable version for Django and its Rest framework.

I hope that helps.

<script> tag vs <script type = 'text/javascript'> tag

<!-- HTML4 and (x)HTML -->
<script type="text/javascript"></script>


<!-- HTML5 -->
<script></script>

type attribute identifies the scripting language of code embedded within a script element or referenced via the element’s src attribute. This is specified as a MIME type; examples of supported MIME types include text/javascript, text/ecmascript, application/javascript, and application/ecmascript. If this attribute is absent, the script is treated as JavaScript.

Ref: https://developer.mozilla.org/en/docs/Web/HTML/Element/script

In python, how do I cast a class object to a dict

There is no magic method that will do what you want. The answer is simply name it appropriately. asdict is a reasonable choice for a plain conversion to dict, inspired primarily by namedtuple. However, your method will obviously contain special logic that might not be immediately obvious from that name; you are returning only a subset of the class' state. If you can come up with with a slightly more verbose name that communicates the concepts clearly, all the better.

Other answers suggest using __iter__, but unless your object is truly iterable (represents a series of elements), this really makes little sense and constitutes an awkward abuse of the method. The fact that you want to filter out some of the class' state makes this approach even more dubious.

How to make a GridLayout fit screen size

Starting in API 21 the notion of weight was added to GridLayout.

To support older android devices, you can use the GridLayout from the v7 support library.

compile 'com.android.support:gridlayout-v7:22.2.1'

The following XML gives an example of how you can use weights to fill the screen width.

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.GridLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:grid="http://schemas.android.com/apk/res-auto"

    android:id="@+id/choice_grid"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:padding="4dp"

    grid:alignmentMode="alignBounds"
    grid:columnCount="2"
    grid:rowOrderPreserved="false"
    grid:useDefaultMargins="true">

    <TextView
        android:layout_width="0dp"
        android:layout_height="100dp"
        grid:layout_columnWeight="1"
        grid:layout_gravity="fill_horizontal"
        android:gravity="center"
        android:background="#FF33B5E5"
        android:text="Tile1" />

    <TextView
        android:layout_width="0dp"
        android:layout_height="100dp"
        grid:layout_columnWeight="1"
        grid:layout_gravity="fill_horizontal"
        android:gravity="center"
        android:background="#FF33B5E5"
        android:text="Tile2" />

    <TextView
        android:layout_width="0dp"
        android:layout_height="100dp"
        grid:layout_columnWeight="1"
        grid:layout_gravity="fill_horizontal"
        android:gravity="center"
        android:background="#FF33B5E5"
        android:text="Tile3" />

    <TextView
        android:layout_width="0dp"
        android:layout_height="100dp"
        grid:layout_columnWeight="1"
        grid:layout_gravity="fill_horizontal"
        android:gravity="center"
        android:background="#FF33B5E5"
        android:text="Tile4" />

</android.support.v7.widget.GridLayout>

How can I call PHP functions by JavaScript?

Try This

<script>
  var phpadd= <?php echo add(1,2);?> //call the php add function
  var phpmult= <?php echo mult(1,2);?> //call the php mult function
  var phpdivide= <?php echo divide(1,2);?> //call the php divide function
</script>

Get index of array element faster than O(n)

Is there a good reason not to use a hash? Lookups are O(1) vs. O(n) for the array.

What is Robocopy's "restartable" option?

Restartable mode (/Z) has to do with a partially-copied file. With this option, should the copy be interrupted while any particular file is partially copied, the next execution of robocopy can pick up where it left off rather than re-copying the entire file.

That option could be useful when copying very large files over a potentially unstable connection.

Backup mode (/B) has to do with how robocopy reads files from the source system. It allows the copying of files on which you might otherwise get an access denied error on either the file itself or while trying to copy the file's attributes/permissions. You do need to be running in an Administrator context or otherwise have backup rights to use this flag.

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

ValidateForm returns boolean,not a string.
When you do this if(ValidateForm() == 'false'), is the same of if(false == 'false'), which is not true.

function post(url, formId) {
    if(!ValidateForm()) {
        // False
    } else {
        // True
    }
}

How to turn on/off MySQL strict mode in localhost (xampp)?

To change it permanently in Windows (10), edit the my.ini file. To find the my.ini file, look at the path in the Windows server. E.g. for my MySQL 5.7 instance, the service is MYSQL57, and in this service's properties the Path to executable is:

"C:\Program Files\MySQL\MySQL Server 5.7\bin\mysqld.exe" --defaults-file="C:\ProgramData\MySQL\MySQL Server 5.7\my.ini" MySQL57

I.e. edit the my.ini file in C:\ProgramData\MySQL\MySQL Server 5.7\. Note that C:\ProgramData\ is a hidden folder in Windows (10). My file has the following lines of interest:

# Set the SQL mode to strict
sql-mode="STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"

Remove STRICT_TRANS_TABLES, from this sql-mode line, save the file and restart the MYSQL57 service. Verify the result by executing SHOW VARIABLES LIKE 'sql_mode'; in a (new) MySQL Command Line Client window.

(I found the other answers and documents on the web useful, but none of them seem to tell you where to find the my.ini file in Windows.)

How do I hide the PHP explode delimiter from submitted form results?

<select name="FakeName" id="Fake-ID" aria-required="true" required>  <?php $options=nl2br(file_get_contents("employees.txt")); $options=explode("<br />",$options);  foreach ($options as $item_array) { echo "<option value='".$item_array"'>".$item_array"</option>";  } ?> </select> 

Python if not == vs if !=

In the first one Python has to execute one more operations than necessary(instead of just checking not equal to it has to check if it is not true that it is equal, thus one more operation). It would be impossible to tell the difference from one execution, but if run many times, the second would be more efficient. Overall I would use the second one, but mathematically they are the same

Warning: Failed propType: Invalid prop `component` supplied to `Route`

This question is a bit old, but for those still arriving here now and using react-router 4.3 it's a bug and got fixed in the beta version 4.4.0. Just upgrade your react-router to version +4.4.0. Be aware that it's a beta version at this moment.

yarn add react-router@next

or

npm install -s [email protected]

What is the total amount of public IPv4 addresses?

Public IP Addresses

https://github.com/stephenlb/geo-ip will generate a list of Valid IP Public Addresses including Localities.

'1.0.0.0/8' to '191.0.0.0/8' are the valid public IP Address range exclusive of the reserved Private IP Addresses as follows:

import iptools
## Private IP Addresses
private_ips = iptools.IpRangeList(
    '0.0.0.0/8',      '10.0.0.0/8',     '100.64.0.0/10', '127.0.0.0/8',
    '169.254.0.0/16', '172.16.0.0/12',  '192.0.0.0/24',  '192.0.2.0/24',
    '192.88.99.0/24', '192.168.0.0/16', '198.18.0.0/15', '198.51.100.0/24',
    '203.0.113.0/24', '224.0.0.0/4',    '240.0.0.0/4',   '255.255.255.255/32'
)

IP Generator

Generates a JSON dump of IP Addresses and associated Geo information. Note that the valid public IP Address range is from '1.0.0.0/8' to '191.0.0.0/8' excluding the reserved Private IP Address ranges shown lower down in this readme.

docker build -t geo-ip .
docker run -e IPRANGE='54.0.0.0/30' geo-ip               ## a few IPs
docker run -e IPRANGE='54.0.0.0/26' geo-ip               ## a few more IPs
docker run -e IPRANGE='54.0.0.0/16' geo-ip               ## a lot more IPs
docker run -e IPRANGE='0.0.0.0/0'   geo-ip               ## ALL IPs ( slooooowwwwww )
docker run -e IPRANGE='0.0.0.0/0'   geo-ip > geo-ip.json ## ALL IPs saved to JSON File
docker run geo-ip 

A little faster option for scanning all valid public addresses:

for i in $(seq 1 191); do \
    docker run -e IPRANGE="$i.0.0.0/8" geo-ip; \
    sleep 1; \ 
done

This prints less than 4,228,250,625 JSON lines to STDOUT. Here is an example of one of the lines:

{"city": "Palo Alto", "ip": "0.0.0.0", "longitude": -122.1274,
 "continent": "North America", "continent_code": "NA",
 "state": "California", "country": "United States", "latitude": 37.418,
 "iso_code": "US", "state_code": "CA", "aso": "PubNub",
 "asn": "11404", "zip_code": "94107"}

Private and Reserved IP Range

The dockerfile in the repo above will exclude non-usable IP addresses following the guide from the wikipedia article: https://en.wikipedia.org/wiki/Reserved_IP_addresses

MaxMind Geo IP

The dockerfile imports a free public Database provided by https://www.maxmind.com/en/home

How to make return key on iPhone make keyboard disappear?

If you want to disappear keyboard when writing on alert box textfileds

[[alertController.textFields objectAtIndex:1] resignFirstResponder];

mysql_fetch_array() expects parameter 1 to be resource problem

The most likely cause is an error in mysql_query(). Have you checked to make sure it worked? Output the value of $result and mysql_error(). You may have misspelled something, selected the wrong database, have a permissions issue, etc. So:

$id = (int)$_GET['id']; // this also sanitizes it
$sql = "SELECT * FROM student WHERE idno = $id";
$result = mysql_query($sql);
if (!$result) {
  die("Error running $sql: " . mysql_error());
}

Sanitizing $_GET['id'] is really important. You can use mysql_real_escape_string() but casting it to an int is sufficient for integers. Basically you want to avoid SQL injection.

How to convert seconds to time format?

Sorry this is too late but maybe useful

function mediaTimeDeFormater($seconds)
{
    if (!is_numeric($seconds))
        throw new Exception("Invalid Parameter Type!");


    $ret = "";

    $hours = (string )floor($seconds / 3600);
    $secs = (string )$seconds % 60;
    $mins = (string )floor(($seconds - ($hours * 3600)) / 60);

    if (strlen($hours) == 1)
        $hours = "0" . $hours;
    if (strlen($secs) == 1)
        $secs = "0" . $secs;
    if (strlen($mins) == 1)
        $mins = "0" . $mins;

    if ($hours == 0)
        $ret = "$mins:$secs";
    else
        $ret = "$hours:$mins:$secs";

    return $ret;
}

echo mediaTimeDeFormater(216.064000);//3:36

Can the Android drawable directory contain subdirectories?

One way to partially get around the problem is to use the API Level suffix. I use res/layout-v1, res/layout-v2 etc to hold multiple sub projects in the same apk. This mechanism can be used for all resource types.

Obviously, this can only be used if you are targeting API levels above the res/layout-v? you are using.

Also, watch out for the bug in Android 1.5 and 1.6. See Andoroid documentation about the API Level suffix.

Datatable to html Table

From this link

using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Text;
using System.Xml;

namespace ClientUtil
{
public class DataTableUtil
{

public static string DataTableToXmlString(DataTable dtData)
{
if (dtData == null || dtData.Columns.Count == 0)
return (string) null;
DataColumn[] primaryKey = dtData.PrimaryKey;
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append(“<TABLE>”);
stringBuilder.Append(“<TR>”);
foreach (DataColumn dataColumn in (InternalDataCollectionBase) dtData.Columns)
{
if (DataTableUtil.IsPrimaryKey(dataColumn.ColumnName, primaryKey))
stringBuilder.Append(“<TH IsPK=’true’ ColType='”).Append(Convert.ToString(dataColumn.DataType == typeof (object) ? (object) typeof (string) : (object) dataColumn.DataType)).Append(“‘>”).Append(dataColumn.ColumnName.Replace(“&”, “”)).Append(“</TH>”);
else
stringBuilder.Append(“<TH IsPK=’false’ ColType='”).Append(Convert.ToString(dataColumn.DataType == typeof (object) ? (object) typeof (string) : (object) dataColumn.DataType)).Append(“‘>”).Append(dataColumn.ColumnName.Replace(“&”, “”)).Append(“</TH>”);
}
stringBuilder.Append(“</TR>”);
int num1 = 0;
foreach (DataRow dataRow in (InternalDataCollectionBase) dtData.Rows)
{
stringBuilder.Append(“<TR>”);
int num2 = 0;
foreach (DataColumn dataColumn in (InternalDataCollectionBase) dtData.Columns)
{
string str = Convert.IsDBNull(dataRow[dataColumn.ColumnName]) ? (string) null : Convert.ToString(dataRow[dataColumn.ColumnName]).Replace(“<“, “&lt;”).Replace(“>”, “&gt;”).Replace(“\””, “&quot;”).Replace(“‘”, “&apos;”).Replace(“&”, “&amp;”);
if (!string.IsNullOrEmpty(str))
stringBuilder.Append(“<TD>”).Append(str).Append(“</TD>”);
else
stringBuilder.Append(“<TD>”).Append(“</TD>”);
++num2;
}
stringBuilder.Append(“</TR>”);
++num1;
}
stringBuilder.Append(“</TABLE>”);
return ((object) stringBuilder).ToString();
}

protected static bool IsPrimaryKey(string ColumnName, DataColumn[] PKs)
{
if (PKs == null || string.IsNullOrEmpty(ColumnName))
return false;
foreach (DataColumn dataColumn in PKs)
{
if (dataColumn.ColumnName.ToLower().Trim() == ColumnName.ToLower().Trim())
return true;
}
return false;
}

public static DataTable XmlStringToDataTable(string XmlData)
{
DataTable dataTable = (DataTable) null;
IList<DataColumn> list = (IList<DataColumn>) new List<DataColumn>();
if (string.IsNullOrEmpty(XmlData))
return (DataTable) null;
XmlDocument xmlDocument1 = new XmlDocument();
xmlDocument1.PreserveWhitespace = true;
XmlDocument xmlDocument2 = xmlDocument1;
xmlDocument2.LoadXml(XmlData);
XmlNode xmlNode1 = xmlDocument2.SelectSingleNode(“/TABLE”);
if (xmlNode1 != null)
{
dataTable = new DataTable();
int num = 0;
foreach (XmlNode xmlNode2 in xmlNode1.SelectNodes(“TR”))
{
if (num == 0)
{
foreach (XmlNode xmlNode3 in xmlNode2.SelectNodes(“TH”))
{
bool result = false;
string str = xmlNode3.Attributes[“IsPK”].Value;
if (!string.IsNullOrEmpty(str))
{
if (!bool.TryParse(str, out result))
result = false;
}
else
result = false;
Type type = Type.GetType(xmlNode3.Attributes[“ColType”].Value);
DataColumn column = new DataColumn(xmlNode3.InnerText, type);
if (result)
list.Add(column);
if (!dataTable.Columns.Contains(column.ColumnName))
dataTable.Columns.Add(column);
}
if (list.Count > 0)
{
DataColumn[] dataColumnArray = new DataColumn[list.Count];
for (int index = 0; index < list.Count; ++index)
dataColumnArray[index] = list[index];
dataTable.PrimaryKey = dataColumnArray;
}
}
else
{
DataRow row = dataTable.NewRow();
int index = 0;
foreach (XmlNode xmlNode3 in xmlNode2.SelectNodes(“TD”))
{
Type dataType = dataTable.Columns[index].DataType;
string s = xmlNode3.InnerText;
if (!string.IsNullOrEmpty(s))
{
try
{
s = s.Replace(“&lt;”, “<“);
s = s.Replace(“&gt;”, “>”);
s = s.Replace(“&quot;”, “\””);
s = s.Replace(“&apos;”, “‘”);
s = s.Replace(“&amp;”, “&”);
row[index] = Convert.ChangeType((object) s, dataType);
}
catch
{
if (dataType == typeof (DateTime))
row[index] = (object) DateTime.ParseExact(s, “yyyyMMdd”, (IFormatProvider) CultureInfo.InvariantCulture);
}
}
else
row[index] = Convert.DBNull;
++index;
}
dataTable.Rows.Add(row);
}
++num;
}
}
return dataTable;
}
}
}

Declaring and using MySQL varchar variables

Looks like you forgot the @ in variable declaration. Also I remember having problems with SET in MySql a long time ago.

Try

DECLARE @FOO varchar(7);
DECLARE @oldFOO varchar(7);
SELECT @FOO = '138';
SELECT @oldFOO = CONCAT('0', @FOO);

update mypermits 
   set person = @FOO 
 where person = @oldFOO;

What are the complexity guarantees of the standard containers?

I'm not aware of anything like a single table that lets you compare all of them in at one glance (I'm not sure such a table would even be feasible).

Of course the ISO standard document enumerates the complexity requirements in detail, sometimes in various rather readable tables, other times in less readable bullet points for each specific method.

Also the STL library reference at http://www.cplusplus.com/reference/stl/ provides the complexity requirements where appropriate.

Android: How to rotate a bitmap on a center point

Edited: optimized code.

public static Bitmap RotateBitmap(Bitmap source, float angle)
{
      Matrix matrix = new Matrix();
      matrix.postRotate(angle);
      return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
}

To get Bitmap from resources:

Bitmap source = BitmapFactory.decodeResource(this.getResources(), R.drawable.your_img);

Get a substring of a char*

Assuming you know the position and the length of the substring:

char *buff = "this is a test string";
printf("%.*s", 4, buff + 10);

You could achieve the same thing by copying the substring to another memory destination, but it's not reasonable since you already have it in memory.

This is a good example of avoiding unnecessary copying by using pointers.

How to test if a string is JSON or not?

var parsedData;

try {
    parsedData = JSON.parse(data)
} catch (e) {
    // is not a valid JSON string
}

However, I will suggest to you that your http call / service should return always a data in the same format. So if you have an error, than you should have a JSON object that wrap this error:

{"error" : { "code" : 123, "message" : "Foo not supported" } } 

And maybe use as well as HTTP status a 5xx code.

how to check if a form is valid programmatically using jQuery Validation Plugin

iContribute: It's never too late for a right answer.

var form = $("form#myForm");
if($('form#myForm > :input[required]:visible').val() != ""){
  form.submit();
}else{
  console.log("Required field missing.");
}

This way the basic HTML5 validation for 'required' fields takes place without interfering with the standard submit using the form's 'name' values.

Android Completely transparent Status Bar?

You can use this below code.

getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN); 
getWindow().setStatusBarColor(Color.TRANSPARENT);

Include this layout in your main layout.

toolbar.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/toolbarNav"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/transparent"
        app:contentInsetEnd="0dp"
        app:contentInsetLeft="0dp"
        app:contentInsetRight="0dp"
        app:contentInsetStart="0dp">

        <RelativeLayout
            android:id="@+id/rlBackImageLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/main_background2">  //add your color here

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="@dimen/_40sdp"
                android:layout_marginTop="@dimen/_16sdp"
                android:orientation="horizontal">

                <ImageView
                    android:id="@+id/toolbarIcon"
                    android:layout_width="@dimen/_30sdp"
                    android:layout_height="@dimen/_30sdp"
                    android:layout_gravity="center"
                    android:layout_marginStart="@dimen/_10sdp"
                    android:padding="@dimen/_5sdp"
                    android:src="@drawable/nav_icon" />

                <TextView
                    android:id="@+id/txtTitle"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_gravity="center"
                    android:layout_marginEnd="@dimen/_30sdp"
                    android:fontFamily="@font/muli_semibold"
                    android:gravity="center"
                    android:textColor="#fff"
                    android:textSize="@dimen/_14ssp"
                    android:textStyle="bold"
                    tools:text="test Data" />

            </LinearLayout>

        </RelativeLayout>

    </androidx.appcompat.widget.Toolbar>

Note: You can replace SDP and SSP with dp and sp respectively.

WPF: ItemsControl with scrollbar (ScrollViewer)

Put your ScrollViewer in a DockPanel and set the DockPanel MaxHeight property

[...]
<DockPanel MaxHeight="700">
  <ScrollViewer VerticalScrollBarVisibility="Auto">
   <ItemsControl ItemSource ="{Binding ...}">
     [...]
   </ItemsControl>
  </ScrollViewer>
</DockPanel>
[...]

Which encoding opens CSV files correctly with Excel on both Mac and Windows?

instead of csv, trying outputting html with an XLS extension and "application/excel" mime-type. I know this will work in Windows, but can't speak for MacOS

How to pass a JSON array as a parameter in URL

You can pass your json Input as a POST request along with authorization header in this way

public static JSONObject getHttpConn(String json){
        JSONObject jsonObject=null;
        try {
            HttpPost httpPost=new HttpPost("http://google.com/");
            org.apache.http.client.HttpClient client = HttpClientBuilder.create().build();
            StringEntity stringEntity=new StringEntity("d="+json);

            httpPost.addHeader("content-type", "application/x-www-form-urlencoded");
            String authorization="test:test@123";
            String encodedAuth = "Basic " + Base64.encode(authorization.getBytes());        
            httpPost.addHeader("Authorization", security.get("Authorization"));
            httpPost.setEntity(stringEntity);
            HttpResponse reponse=client.execute(httpPost);
            InputStream inputStream=reponse.getEntity().getContent();
            String jsonResponse=IOUtils.toString(inputStream);
            jsonObject=JSONObject.fromObject(jsonResponse);
            } catch (UnsupportedEncodingException e) {

            e.printStackTrace();
        } catch (ClientProtocolException e) {

            e.printStackTrace();
        } catch (IOException e) {

            e.printStackTrace();
        }
        return jsonObject;


    }

This Method will return a json response.In same way you can use GET method

Checking version of angular-cli that's installed?

angular cli can report its version when you run it with the version flag

ng --version

how get yesterday and tomorrow datetime in c#

Beware of adding an unwanted timezone to your results, especially if the date is going to be sent out via a Web API. Use UtcNow instead, to make it timezone-less.

How can I export a GridView.DataSource to a datatable or dataset?

Ambu,

I was having the same issue as you, and this is the code I used to figure it out. Although, I don't use the footer row section for my purposes, I did include it in this code.

    DataTable dt = new DataTable();

    // add the columns to the datatable            
    if (GridView1.HeaderRow != null)
    {

        for (int i = 0; i < GridView1.HeaderRow.Cells.Count; i++)
        {
            dt.Columns.Add(GridView1.HeaderRow.Cells[i].Text);
        }
    }

    //  add each of the data rows to the table
    foreach (GridViewRow row in GridView1.Rows)
    {
        DataRow dr;
        dr = dt.NewRow();

        for (int i = 0; i < row.Cells.Count; i++)
        {
            dr[i] = row.Cells[i].Text.Replace("&nbsp;","");
        }
        dt.Rows.Add(dr);
    }

    //  add the footer row to the table
    if (GridView1.FooterRow != null)
    {
        DataRow dr;
        dr = dt.NewRow();

        for (int i = 0; i < GridView1.FooterRow.Cells.Count; i++)
        {
            dr[i] = GridView1.FooterRow.Cells[i].Text.Replace("&nbsp;","");
        }
        dt.Rows.Add(dr);
    }

How add "or" in switch statements?

case 2:
case 5:
do something
break;

css to make bootstrap navbar transparent

Further to Jochem Stoel's answer... I added 'navbar-fixed-top' to the DIV tag's class and it worked.

NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference

You should initialize yours recordings. You are passing to adapter null

ArrayList<String> recordings = null; //You are passing this null

How do I exit a while loop in Java?

Use break:

while (true) {
    ....
    if (obj == null) {
        break;
    }
    ....
}

However, if your code looks exactly like you have specified you can use a normal while loop and change the condition to obj != null:

while (obj != null) {
    ....
}

Validate that end date is greater than start date with jQuery

I like what Franz said, because is what I'm using :P

var date_ini = new Date($('#id_date_ini').val()).getTime();
var date_end = new Date($('#id_date_end').val()).getTime();
if (isNaN(date_ini)) {
// error date_ini;
}
if (isNaN(date_end)) {
// error date_end;
}
if (date_ini > date_end) {
// do something;
}

How to change time in DateTime?

If you already have the time stored in another DateTime object you can use the Add method.

DateTime dateToUse = DateTime.Now();
DateTime timeToUse = new DateTime(2012, 2, 4, 10, 15, 30); //10:15:30 AM

DateTime dateWithRightTime = dateToUse.Date.Add(timeToUse.TimeOfDay);

The TimeOfDay property is a TimeSpan object and can be passed to the Add method. And since we use the Date property of the dateToUse variable we get just the date and add the time span.

Codeigniter $this->db->order_by(' ','desc') result is not complete

Put from before where, and order_by on last:

$this->db->select('*');
$this->db->from('courses');
$this->db->where('tennant_id',$tennant_id);
$this->db->order_by("UPPER(course_name)","desc");

Or try BINARY:

ORDER BY BINARY course_name DESC;

You should add manually on codeigniter for binary sorting.

And set "course_name" character column.

If sorting is used on a character type column, normally the sort is conducted in a case-insensitive fashion.

What type of structure data in courses table?

If you frustrated you can put into array and return using PHP:

Use natcasesort for order in "natural order": (Reference: http://php.net/manual/en/function.natcasesort.php)

Your array from database as example: $array_db = $result_from_db:

$final_result = natcasesort($array_db);

print_r($final_result);

Avoid Adding duplicate elements to a List C#

Your this check:

if (!lines2.Contains(lines3.ToString()))

is invalid. You are checking if your lines2 contains System.String[] since lines3.ToString() will give you that. You need to check if item from lines3 exists in lines2 or not.

You can iterate each item in lines3 check if it exists in the lines2 and then add it. Something like.

foreach (string str in lines3)
{
    if (!lines2.Contains(str))
        lines2.Add(str);
}

Or if your lines2 is any empty list, then you can simply add the lines3 distinct values to the list like:

lines2.AddRange(lines3.Distinct());

then your lines2 will contain distinct values.

jQuery to serialize only elements within a div

Try also this:

$('#divId').find('input').serialize()

Best approach to real time http streaming to HTML5 video client

EDIT 3: As of IOS 10, HLS will support fragmented mp4 files. The answer now, is to create fragmented mp4 assets, with a DASH and HLS manifest. > Pretend flash, iOS9 and below and IE 10 and below don't exist.

Everything below this line is out of date. Keeping it here for posterity.


EDIT 2: As people in the comments are pointing out, things change. Almost all browsers will support AVC/AAC codecs. iOS still requires HLS. But via adaptors like hls.js you can play HLS in MSE. The new answer is HLS+hls.js if you need iOS. or just Fragmented MP4 (i.e. DASH) if you don't

There are many reasons why video and, specifically, live video is very difficult. (Please note that the original question specified that HTML5 video is a requirement, but the asker stated Flash is possible in the comments. So immediately, this question is misleading)

First I will restate: THERE IS NO OFFICIAL SUPPORT FOR LIVE STREAMING OVER HTML5. There are hacks, but your mileage may vary.

EDIT: since I wrote this answer Media Source Extensions have matured, and are now very close to becoming a viable option. They are supported on most major browsers. IOS continues to be a hold out.

Next, you need to understand that Video on demand (VOD) and live video are very different. Yes, they are both video, but the problems are different, hence the formats are different. For example, if the clock in your computer runs 1% faster than it should, you will not notice on a VOD. With live video, you will be trying to play video before it happens. If you want to join a a live video stream in progress, you need the data necessary to initialize the decoder, so it must be repeated in the stream, or sent out of band. With VOD, you can read the beginning of the file them seek to whatever point you wish.

Now let's dig in a bit.

Platforms:

  • iOS
  • PC
  • Mac
  • Android

Codecs:

  • vp8/9
  • h.264
  • thora (vp3)

Common Delivery methods for live video in browsers:

  • DASH (HTTP)
  • HLS (HTTP)
  • flash (RTMP)
  • flash (HDS)

Common Delivery methods for VOD in browsers:

  • DASH (HTTP Streaming)
  • HLS (HTTP Streaming)
  • flash (RTMP)
  • flash (HTTP Streaming)
  • MP4 (HTTP pseudo streaming)
  • I'm not going to talk about MKV and OOG because I do not know them very well.

html5 video tag:

  • MP4
  • webm
  • ogg

Lets look at which browsers support what formats

Safari:

  • HLS (iOS and mac only)
  • h.264
  • MP4

Firefox

  • DASH (via MSE but no h.264)
  • h.264 via Flash only!
  • VP9
  • MP4
  • OGG
  • Webm

IE

  • Flash
  • DASH (via MSE IE 11+ only)
  • h.264
  • MP4

Chrome

  • Flash
  • DASH (via MSE)
  • h.264
  • VP9
  • MP4
  • webm
  • ogg

MP4 cannot be used for live video (NOTE: DASH is a superset of MP4, so don't get confused with that). MP4 is broken into two pieces: moov and mdat. mdat contains the raw audio video data. But it is not indexed, so without the moov, it is useless. The moov contains an index of all data in the mdat. But due to its format, it can not be 'flattened' until the timestamps and size of EVERY frame is known. It may be possible to construct an moov that 'fibs' the frame sizes, but is is very wasteful bandwidth wise.

So if you want to deliver everywhere, we need to find the least common denominator. You will see there is no LCD here without resorting to flash example:

  • iOS only supports h.264 video. and it only supports HLS for live.
  • Firefox does not support h.264 at all, unless you use flash
  • Flash does not work in iOS

The closest thing to an LCD is using HLS to get your iOS users, and flash for everyone else. My personal favorite is to encode HLS, then use flash to play HLS for everyone else. You can play HLS in flash via JW player 6, (or write your own HLS to FLV in AS3 like I did)

Soon, the most common way to do this will be HLS on iOS/Mac and DASH via MSE everywhere else (This is what Netflix will be doing soon). But we are still waiting for everyone to upgrade their browsers. You will also likely need a separate DASH/VP9 for Firefox (I know about open264; it sucks. It can't do video in main or high profile. So it is currently useless).

How to trigger a file download when clicking an HTML button or JavaScript

For the button you can do

<form method="get" action="file.doc">
   <button type="submit">Download!</button>
</form>

How can I change my Cygwin home folder after installation?

I'd like to add a correction/update to the bit about $HOME taking precedence. The home directory in /etc/passwd takes precedence over everything.

I'm a long time Cygwin user and I just did a clean install of Windows 7 x64 and Cygwin V1.126. I was going nuts trying to figure out why every time I ran ssh I kept getting:

e:\>ssh foo.bar.com
Could not create directory '/home/dhaynes/.ssh'.
The authenticity of host 'foo.bar.com (10.66.19.19)' can't be established.
...

I add the HOME=c:\users\dhaynes definition in the Windows environment but still it kept trying to create '/home/dhaynes'. I tried every combo I could including setting HOME to /cygdrive/c/users/dhaynes. Googled for the error message, could not find anything, couldn't find anything on the cygwin site. I use cygwin from cmd.exe, not bash.exe but the problem was present in both.

I finally realized that the home directory in /etc/passwd was taking precedence over the $HOME environment variable. I simple re-ran 'mkpasswd -l >/etc/passwd' and that updated the home directory, now all is well with ssh.

That may be obvious to linux types with sysadmin experience but for those of us who primarily use Windows it's a bit obscure.

Hibernate Criteria for Dates

Why do you use Restrictions.like(...)?

You should use Restrictions.eq(...).

Note you can also use .le, .lt, .ge, .gt on date objects as comparison operators. LIKE operator is not appropriate for this case since LIKE is useful when you want to match results according to partial content of a column. Please see http://www.sql-tutorial.net/SQL-LIKE.asp for the reference.

For example if you have a name column with some people's full name, you can do where name like 'robert %' so that you will return all entries with name starting with 'robert ' (% can replace any character).

In your case you know the full content of the date you're trying to match so you shouldn't use LIKE but equality. I guess Hibernate doesn't give you any exception in this case, but anyway you will probably have the same problem with the Restrictions.eq(...).

Your date object you got with the code:

SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-YYYY");
String myDate = "17-04-2011";
Date date = formatter.parse(myDate);

This date object is equals to the 17-04-2011 at 0h, 0 minutes, 0 seconds and 0 nanoseconds.

This means that your entries in database must have exactly that date. What i mean is that if your database entry has a date "17-April-2011 19:20:23.707000000", then it won't be retrieved because you just ask for that date: "17-April-2011 00:00:00.0000000000".

If you want to retrieve all entries of your database from a given day, you will have to use the following code:

    SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-YYYY");
    String myDate = "17-04-2011";
    // Create date 17-04-2011 - 00h00
    Date minDate = formatter.parse(myDate);
    // Create date 18-04-2011 - 00h00 
    // -> We take the 1st date and add it 1 day in millisecond thanks to a useful and not so known class
    Date maxDate = new Date(minDate.getTime() + TimeUnit.DAYS.toMillis(1));
    Conjunction and = Restrictions.conjunction();
    // The order date must be >= 17-04-2011 - 00h00
    and.add( Restrictions.ge("orderDate", minDate) );
    // And the order date must be < 18-04-2011 - 00h00
    and.add( Restrictions.lt("orderDate", maxDate) ); 

How to redirect the output of an application in background to /dev/null

These will also redirect both:

yourcommand  &> /dev/null

yourcommand  >& /dev/null

though the bash manual says the first is preferred.

How do I convert an array object to a string in PowerShell?

1> $a = "This", "Is", "a", "cat"

2> [system.String]::Join(" ", $a)

Line two performs the operation and outputs to host, but does not modify $a:

3> $a = [system.String]::Join(" ", $a)

4> $a

This Is a cat

5> $a.Count

1

Do you have to put Task.Run in a method to make it async?

First, let's clear up some terminology: "asynchronous" (async) means that it may yield control back to the calling thread before it starts. In an async method, those "yield" points are await expressions.

This is very different than the term "asynchronous", as (mis)used by the MSDN documentation for years to mean "executes on a background thread".

To futher confuse the issue, async is very different than "awaitable"; there are some async methods whose return types are not awaitable, and many methods returning awaitable types that are not async.

Enough about what they aren't; here's what they are:

  • The async keyword allows an asynchronous method (that is, it allows await expressions). async methods may return Task, Task<T>, or (if you must) void.
  • Any type that follows a certain pattern can be awaitable. The most common awaitable types are Task and Task<T>.

So, if we reformulate your question to "how can I run an operation on a background thread in a way that it's awaitable", the answer is to use Task.Run:

private Task<int> DoWorkAsync() // No async because the method does not need await
{
  return Task.Run(() =>
  {
    return 1 + 2;
  });
}

(But this pattern is a poor approach; see below).

But if your question is "how do I create an async method that can yield back to its caller instead of blocking", the answer is to declare the method async and use await for its "yielding" points:

private async Task<int> GetWebPageHtmlSizeAsync()
{
  var client = new HttpClient();
  var html = await client.GetAsync("http://www.example.com/");
  return html.Length;
}

So, the basic pattern of things is to have async code depend on "awaitables" in its await expressions. These "awaitables" can be other async methods or just regular methods returning awaitables. Regular methods returning Task/Task<T> can use Task.Run to execute code on a background thread, or (more commonly) they can use TaskCompletionSource<T> or one of its shortcuts (TaskFactory.FromAsync, Task.FromResult, etc). I don't recommend wrapping an entire method in Task.Run; synchronous methods should have synchronous signatures, and it should be left up to the consumer whether it should be wrapped in a Task.Run:

private int DoWork()
{
  return 1 + 2;
}

private void MoreSynchronousProcessing()
{
  // Execute it directly (synchronously), since we are also a synchronous method.
  var result = DoWork();
  ...
}

private async Task DoVariousThingsFromTheUIThreadAsync()
{
  // I have a bunch of async work to do, and I am executed on the UI thread.
  var result = await Task.Run(() => DoWork());
  ...
}

I have an async/await intro on my blog; at the end are some good followup resources. The MSDN docs for async are unusually good, too.