Programs & Examples On #Winamp

Winamp is a media player for both Windows PCs and Android devices. It's noted for graphical, sound visualization, playlist, and media library features.

Percentage width in a RelativeLayout

Just put your two textviews host and port in an independant linearlayout horizontal and use android:layout_weight to make the percentage

Custom designing EditText

enter image description here

For EditText in image above, You have to create two xml files in res-->drawable folder. First will be "bg_edittext_focused.xml" paste the lines of code in it

<?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android" >
        <solid android:color="#FFFFFF" />
        <stroke
            android:width="2dip"
            android:color="#F6F6F6" />
        <corners android:radius="2dip" />
        <padding
            android:bottom="7dip"
            android:left="7dip"
            android:right="7dip"
            android:top="7dip" />
    </shape>

Second file will be "bg_edittext_normal.xml" paste the lines of code in it

<?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android" >
        <solid android:color="#F6F6F6" />
        <stroke
            android:width="2dip"
            android:color="#F6F6F6" />
        <corners android:radius="2dip" />
        <padding
            android:bottom="7dip"
            android:left="7dip"
            android:right="7dip"
            android:top="7dip" />
    </shape>

In res-->drawable folder create another xml file with name "bg_edittext.xml" that will call above mentioned code. paste the following lines of code below in bg_edittext.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/bg_edittext_focused" android:state_focused="true"/>
    <item android:drawable="@drawable/bg_edittext_normal"/>
</selector>

Finally in res-->layout-->example.xml file in your case wherever you created your editText you'll call bg_edittext.xml as background

   <EditText
    :::::
    :::::  
    android:background="@drawable/bg_edittext"
    :::::
    :::::
    />

Node.js Best Practice Exception Handling

I wrote about this recently at http://snmaynard.com/2012/12/21/node-error-handling/. A new feature of node in version 0.8 is domains and allow you to combine all the forms of error handling into one easier manage form. You can read about them in my post.

You can also use something like Bugsnag to track your uncaught exceptions and be notified via email, chatroom or have a ticket created for an uncaught exception (I am the co-founder of Bugsnag).

Confused about Service vs Factory

live example

" hello world " example

with factory / service / provider :

var myApp = angular.module('myApp', []);
 
//service style, probably the simplest one
myApp.service('helloWorldFromService', function() {
    this.sayHello = function() {
        return "Hello, World!"
    };
});
 
//factory style, more involved but more sophisticated
myApp.factory('helloWorldFromFactory', function() {
    return {
        sayHello: function() {
            return "Hello, World!"
        }
    };
});
    
//provider style, full blown, configurable version     
myApp.provider('helloWorld', function() {
    // In the provider function, you cannot inject any
    // service or factory. This can only be done at the
    // "$get" method.
 
    this.name = 'Default';
 
    this.$get = function() {
        var name = this.name;
        return {
            sayHello: function() {
                return "Hello, " + name + "!"
            }
        }
    };
 
    this.setName = function(name) {
        this.name = name;
    };
});
 
//hey, we can configure a provider!            
myApp.config(function(helloWorldProvider){
    helloWorldProvider.setName('World');
});
        
 
function MyCtrl($scope, helloWorld, helloWorldFromFactory, helloWorldFromService) {
    
    $scope.hellos = [
        helloWorld.sayHello(),
        helloWorldFromFactory.sayHello(),
        helloWorldFromService.sayHello()];
}?

Bootstrap 3 navbar active li not changing background-color

In Bootstrap 3.3.x make sure you use the scrollspy JavaScript capability to track active elements. It's easy to include it in your HTML. Just do the following:

<body data-spy="scroll" data-target="Id or class of the element you want to track">

In most cases I usually track active elements on my navbar, so I do the following:

<body data-spy="scroll" data-target=".navbar-fixed-top" >

Now in your CSS you can target .navbar-fixed-top .active a:

.navbar-fixed-top .active a { 
    // Put in some styling 
}

This should work if you are tracking active li elements in your top fixed navigation bar.

C string append

do the following:

strcat(new_str,str1);
strcat(new_str,str2);

Splitting a list into N parts of approximately equal length

As long as you don't want anything silly like continuous chunks:

>>> def chunkify(lst,n):
...     return [lst[i::n] for i in xrange(n)]
... 
>>> chunkify(range(13), 3)
[[0, 3, 6, 9, 12], [1, 4, 7, 10], [2, 5, 8, 11]]

How can I check for Python version in a program that uses new language features?

Have a wrapper around your program that does the following.

import sys

req_version = (2,5)
cur_version = sys.version_info

if cur_version >= req_version:
   import myApp
   myApp.run()
else:
   print "Your Python interpreter is too old. Please consider upgrading."

You can also consider using sys.version(), if you plan to encounter people who are using pre-2.0 Python interpreters, but then you have some regular expressions to do.

And there might be more elegant ways to do this.

How to compile makefile using MinGW?

You have to actively choose to install MSYS to get the make.exe. So you should always have at least (the native) mingw32-make.exe if MinGW was installed properly. And if you installed MSYS you will have make.exe (in the MSYS subfolder probably).

Note that many projects require first creating a makefile (e.g. using a configure script or automake .am file) and it is this step that requires MSYS or cygwin. Makes you wonder why they bothered to distribute the native make at all.

Once you have the makefile, it is unclear if the native executable requires a different path separator than the MSYS make (forward slashes vs backward slashes). Any autogenerated makefile is likely to have unix-style paths, assuming the native make can handle those, the compiled output should be the same.

jQuery Ajax requests are getting cancelled without being sent

For Dropzone.js case. In my case it's was caused because of timeout option value was too low by default. So increase it by your needs.

{
// other dropzone options
timeout: 60000 * 10, // 10 minutes
...
}

How to handle :java.util.concurrent.TimeoutException: android.os.BinderProxy.finalize() timed out after 10 seconds errors?

We solved the problem by stopping the FinalizerWatchdogDaemon.

public static void fix() {
    try {
        Class clazz = Class.forName("java.lang.Daemons$FinalizerWatchdogDaemon");

        Method method = clazz.getSuperclass().getDeclaredMethod("stop");
        method.setAccessible(true);

        Field field = clazz.getDeclaredField("INSTANCE");
        field.setAccessible(true);

        method.invoke(field.get(null));

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

You can call the method in Application's lifecycle, like attachBaseContext(). For the same reason, you also can specific the phone's manufacture to fix the problem, it's up to you.

How to concatenate string and int in C?

Use sprintf (or snprintf if like me you can't count) with format string "pre_%d_suff".

For what it's worth, with itoa/strcat you could do:

char dst[12] = "pre_";
itoa(i, dst+4, 10);
strcat(dst, "_suff");

Make Frequency Histogram for Factor Variables

The reason you are getting the unexpected result is that hist(...) calculates the distribution from a numeric vector. In your code, table(animalFactor) behaves like a numeric vector with three elements: 1, 3, 7. So hist(...) plots the number of 1's (1), the number of 3's (1), and the number of 7's (1). @Roland's solution is the simplest.

Here's a way to do this using ggplot:

library(ggplot2)
ggp <- ggplot(data.frame(animals),aes(x=animals))
# counts
ggp + geom_histogram(fill="lightgreen")
# proportion
ggp + geom_histogram(fill="lightblue",aes(y=..count../sum(..count..)))

You would get precisely the same result using animalFactor instead of animals in the code above.

Rounding numbers to 2 digits after comma

UPDATE: Keep in mind, at the time the answer was initially written in 2010, the bellow function toFixed() worked slightly different. toFixed() seems to do some rounding now, but not in the strictly mathematical manner. So be careful with it. Do your tests... The method described bellow will do rounding well, as mathematician would expect.

  • toFixed() - method converts a number into a string, keeping a specified number of decimals. It does not actually rounds up a number, it truncates the number.
  • Math.round(n) - rounds a number to the nearest integer. Thus turning:

0.5 -> 1; 0.05 -> 0

so if you want to round, say number 0.55555, only to the second decimal place; you can do the following(this is step-by-step concept):

  • 0.55555 * 100 = 55.555
  • Math.Round(55.555) -> 56.000
  • 56.000 / 100 = 0.56000
  • (0.56000).toFixed(2) -> 0.56

and this is the code:

(Math.round(number * 100)/100).toFixed(2);

How to change font of UIButton with Swift

this work for me, thanks. I want change text size only not change font name.

var fontSizeButtonBig:Int = 30

btnMenu9.titleLabel?.font = .systemFont(ofSize: CGFloat(fontSizeButtonBig))

How do I choose grid and block dimensions for CUDA kernels?

There are two parts to that answer (I wrote it). One part is easy to quantify, the other is more empirical.

Hardware Constraints:

This is the easy to quantify part. Appendix F of the current CUDA programming guide lists a number of hard limits which limit how many threads per block a kernel launch can have. If you exceed any of these, your kernel will never run. They can be roughly summarized as:

  1. Each block cannot have more than 512/1024 threads in total (Compute Capability 1.x or 2.x and later respectively)
  2. The maximum dimensions of each block are limited to [512,512,64]/[1024,1024,64] (Compute 1.x/2.x or later)
  3. Each block cannot consume more than 8k/16k/32k/64k/32k/64k/32k/64k/32k/64k registers total (Compute 1.0,1.1/1.2,1.3/2.x-/3.0/3.2/3.5-5.2/5.3/6-6.1/6.2/7.0)
  4. Each block cannot consume more than 16kb/48kb/96kb of shared memory (Compute 1.x/2.x-6.2/7.0)

If you stay within those limits, any kernel you can successfully compile will launch without error.

Performance Tuning:

This is the empirical part. The number of threads per block you choose within the hardware constraints outlined above can and does effect the performance of code running on the hardware. How each code behaves will be different and the only real way to quantify it is by careful benchmarking and profiling. But again, very roughly summarized:

  1. The number of threads per block should be a round multiple of the warp size, which is 32 on all current hardware.
  2. Each streaming multiprocessor unit on the GPU must have enough active warps to sufficiently hide all of the different memory and instruction pipeline latency of the architecture and achieve maximum throughput. The orthodox approach here is to try achieving optimal hardware occupancy (what Roger Dahl's answer is referring to).

The second point is a huge topic which I doubt anyone is going to try and cover it in a single StackOverflow answer. There are people writing PhD theses around the quantitative analysis of aspects of the problem (see this presentation by Vasily Volkov from UC Berkley and this paper by Henry Wong from the University of Toronto for examples of how complex the question really is).

At the entry level, you should mostly be aware that the block size you choose (within the range of legal block sizes defined by the constraints above) can and does have a impact on how fast your code will run, but it depends on the hardware you have and the code you are running. By benchmarking, you will probably find that most non-trivial code has a "sweet spot" in the 128-512 threads per block range, but it will require some analysis on your part to find where that is. The good news is that because you are working in multiples of the warp size, the search space is very finite and the best configuration for a given piece of code relatively easy to find.

How to deep merge instead of shallow merge?

Does anybody know if deep merging exists in the ES6/ES7 spec?

No, it does not.

Automatic exit from Bash shell script on error

Use the set -e builtin:

#!/bin/bash
set -e
# Any subsequent(*) commands which fail will cause the shell script to exit immediately

Alternatively, you can pass -e on the command line:

bash -e my_script.sh

You can also disable this behavior with set +e.

You may also want to employ all or some of the the -e -u -x and -o pipefail options like so:

set -euxo pipefail

-e exits on error, -u errors on undefined variables, and -o (for option) pipefail exits on command pipe failures. Some gotchas and workarounds are documented well here.

(*) Note:

The shell does not exit if the command that fails is part of the command list immediately following a while or until keyword, part of the test following the if or elif reserved words, part of any command executed in a && or || list except the command following the final && or ||, any command in a pipeline but the last, or if the command's return value is being inverted with !

(from man bash)

Call a Javascript function every 5 seconds continuously

As best coding practices suggests, use setTimeout instead of setInterval.

function foo() {

    // your function code here

    setTimeout(foo, 5000);
}

foo();

Please note that this is NOT a recursive function. The function is not calling itself before it ends, it's calling a setTimeout function that will be later call the same function again.

java.io.IOException: Broken pipe

Basically, what is happening is that your user is either closing the browser tab, or is navigating away to a different page, before communication was complete. Your webserver (Jetty) generates this exception because it is unable to send the remaining bytes.

org.eclipse.jetty.io.EofException: null
! at org.eclipse.jetty.http.HttpGenerator.flushBuffer(HttpGenerator.java:914)
! at org.eclipse.jetty.http.HttpGenerator.complete(HttpGenerator.java:798)
! at org.eclipse.jetty.server.AbstractHttpConnection.completeResponse(AbstractHttpConnection.java:642)
! 

This is not an error on your application logic side. This is simply due to user behavior. There is nothing wrong in your code per se.

There are two things you may be able to do:

  1. Ignore this specific exception so that you don't log it.
  2. Make your code more efficient/packed so that it transmits less data. (Not always an option!)

List comprehension vs map

If you plan on writing any asynchronous, parallel, or distributed code, you will probably prefer map over a list comprehension -- as most asynchronous, parallel, or distributed packages provide a map function to overload python's map. Then by passing the appropriate map function to the rest of your code, you may not have to modify your original serial code to have it run in parallel (etc).

Easy way of running the same junit test over and over?

With JUnit 5 I was able to solve this using the @RepeatedTest annotation:

@RepeatedTest(10)
public void testMyCode() {
    //your test code goes here
}

Note that @Test annotation shouldn't be used along with @RepeatedTest.

How do I kill this tomcat process in Terminal?

as @Aurand to said, tomcat is not running. you can use the

ps -ef |grep java | grep tomcat command to ignore the ps programs.

worked for me in the shell scripte files.

Spring Boot: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean

The error suggests that the application you are trying to run cannot instantiate an instance of apache tomcat. Make sure you are running the application with tomcat.

if after checking all your dependencies you experience the same problem, try to add the following in your configuration class

@Bean
public EmbeddedServletContainerFactory servletContainer() {
    TomcatEmbeddedServletContainerFactory factory = 
                  new TomcatEmbeddedServletContainerFactory();
    return factory;
 }

If you are using an external instance of tomcat (especially for intellij), the problem could be that the IDE is trying to start the embedded tomcat. In this case, remove the following from your pom.xml then configure the external tomcat using the 'Edit Configurations' wizard.

<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-tomcat</artifactId>
     <scope>provided</scope>
</dependency> 

Define a global variable in a JavaScript function

To use the window object is not a good idea. As I see in comments,

'use strict';

function showMessage() {
    window.say_hello = 'hello!';
}

console.log(say_hello);

This will throw an error to use the say_hello variable we need to first call the showMessage function.

Iterate over object keys in node.js

Also remember that you can pass a second argument to the .forEach() function specifying the object to use as the this keyword.

// myOjbect is the object you want to iterate.
// Notice the second argument (secondArg) we passed to .forEach.
Object.keys(myObject).forEach(function(element, key, _array) {
  // element is the name of the key.
  // key is just a numerical value for the array
  // _array is the array of all the keys

  // this keyword = secondArg
  this.foo;
  this.bar();
}, secondArg);

Hide div element when screen size is smaller than a specific size

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

Any time the screen is less than 1026 pixels wide, anything inside the { } will apply.

Some browsers don't support media queries. You can get round this using a javascript library like Respond.JS

How set background drawable programmatically in Android

Try this:

layout.setBackground(ContextCompat.getDrawable(context, R.drawable.ready));

and for API 16<:

layout.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.ready));

Creating a thumbnail from an uploaded image

Hope this code helps for creating Thumbnail for JPG, PNG & GIF formats.

<?php

    $file = "D:/server/sites/Sourcefol/high/bucket/kath23.png";   /*Your Original Source Image */
    $pathToSave = "D:/server/sites/Sourcefol/high/bucket/New/"; /*Your Destination Folder */
    $sourceWidth =60;
    $sourceHeight = 60;
    $what = getimagesize($file);
    $file_name = basename($file);/* Name of the Image File*/
    $ext   = pathinfo($file_name, PATHINFO_EXTENSION);

    /* Adding image name _thumb for thumbnail image */
    $file_name = basename($file_name, ".$ext") . '_thumb.' . $ext;

    switch(strtolower($what['mime']))
    {
        case 'image/png':
            $img = imagecreatefrompng($file);
            $new = imagecreatetruecolor($what[0],$what[1]);
            imagecopy($new,$img,0,0,0,0,$what[0],$what[1]);
            header('Content-Type: image/png');           
        break;
        case 'image/jpeg':
            $img = imagecreatefromjpeg($file);
            $new = imagecreatetruecolor($what[0],$what[1]);
            imagecopy($new,$img,0,0,0,0,$what[0],$what[1]);
            header('Content-Type: image/jpeg');
        break;
        case 'image/gif':
            $img = imagecreatefromgif($file);
            $new = imagecreatetruecolor($what[0],$what[1]);
            imagecopy($new,$img,0,0,0,0,$what[0],$what[1]);
            header('Content-Type: image/gif');
        break;
        default: die();
    }

        imagejpeg($new,$pathToSave.$file_name);
        imagedestroy($new);

?>

Checking that a List is not empty in Hamcrest

This is fixed in Hamcrest 1.3. The below code compiles and does not generate any warnings:

// given
List<String> list = new ArrayList<String>();
// then
assertThat(list, is(not(empty())));

But if you have to use older version - instead of bugged empty() you could use:

hasSize(greaterThan(0))
(import static org.hamcrest.number.OrderingComparison.greaterThan; or
import static org.hamcrest.Matchers.greaterThan;)

Example:

// given
List<String> list = new ArrayList<String>();
// then
assertThat(list, hasSize(greaterThan(0)));

The most important thing about above solutions is that it does not generate any warnings. The second solution is even more useful if you would like to estimate minimum result size.

How to click an element in Selenium WebDriver using JavaScript

Executing a click via JavaScript has some behaviors of which you should be aware. If for example, the code bound to the onclick event of your element invokes window.alert(), you may find your Selenium code hanging, depending on the implementation of the browser driver. That said, you can use the JavascriptExecutor class to do this. My solution differs from others proposed, however, in that you can still use the WebDriver methods for locating the elements.

// Assume driver is a valid WebDriver instance that
// has been properly instantiated elsewhere.
WebElement element = driver.findElement(By.id("gbqfd"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", element);

You should also note that you might be better off using the click() method of the WebElement interface, but disabling native events before instantiating your driver. This would accomplish the same goal (with the same potential limitations), but not force you to write and maintain your own JavaScript.

How is a CSS "display: table-column" supposed to work?

The "table-column" display type means it acts like the <col> tag in HTML - i.e. an invisible element whose width* governs the width of the corresponding physical column of the enclosing table.

See the W3C standard for more information about the CSS table model.

* And a few other properties like borders, backgrounds.

How to join components of a path when you are constructing a URL in Python

Rune Kaagaard provided a great and compact solution that worked for me, I expanded on it a little:

def urljoin(*args):
    trailing_slash = '/' if args[-1].endswith('/') else ''
    return "/".join(map(lambda x: str(x).strip('/'), args)) + trailing_slash

This allows all arguments to be joined regardless of trailing and ending slashes while preserving the last slash if present.

A Simple, 2d cross-platform graphics library for c or c++?

Heavy-weight:

  • GTK
  • QT
  • WxWidgets

Lightweight:

  • FLTK
  • Fox
  • Tk
  • Lua IUP
  • Ultimate++
  • dlib

Drawing frameworks without GUI widgets:

  • SDL
  • Cairo

Setting an int to Infinity in C++

int min and max values

Int -2,147,483,648 / 2,147,483,647 Int 64 -9,223,372,036,854,775,808 / 9,223,372,036,854,775,807

i guess you could set a to equal 9,223,372,036,854,775,807 but it would need to be an int64

if you always want a to be grater that b why do you need to check it? just set it to be true always

Bootstrap - dropdown menu not working?

I had a similar problem. The version of bootstrap.js that visual studio seems to be hosed. I just pointed to this URL instead:

    <link id="active_style" rel="stylesheet" href="//netdna.bootstrapcdn.com/bootswatch/3.1.1/cosmo/bootstrap.min.css">

For completeness, here's the HTML and javascript

<ul class="nav navbar-nav navbar-right">
                    <li id="theme_selector" class="dropdown">
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown">Theme <b class="caret"></b></a>
                        <ul id="theme" class="dropdown-menu" role="menu">
                            <li><a href="#">Amelia</a></li>
                            <li><a href="#">Cerulean</a></li>
                            <li><a href="#">Cyborg</a></li>
                            <li><a href="#">Cosmo</a></li>
                            <li><a href="#">Darkly</a></li>
                            <li><a href="#">Flatly</a></li>
                            <li><a href="#">Lumen</a></li>
                            <li><a href="#">Simplex</a></li>
                            <li><a href="#">Slate</a></li>
                            <li><a href="#">Spacelab</a></li>
                            <li><a href="#">Superhero</a></li>
                            <li><a href="#">United</a></li>
                            <li><a href="#">Yeti</a></li>
                        </ul>
                    </li>
                </ul>

Javascript

$('#theme li').click(function () {
        //alert('item: ' + $(this).text());
        switch_style($(this).text());
    });

Hope it helps someone

Twitter bootstrap float div right

This does the trick, without the need to add an inline style

<div class="row-fluid">
    <div class="span6">
        <p>text left</p>
    </div>
    <div class="span6">
        <div class="pull-right">
            <p>text right</p>
        </div>
    </div>
</div>

The answer is in nesting another <div> with the "pull-right" class. Combining the two classes won't work.

Extract public/private key from PKCS12 file for later use in SSH-PK-Authentication

This is possible with a bit of format conversion.

To extract the private key in a format openssh can use:

openssl pkcs12 -in pkcs12.pfx -nocerts -nodes | openssl rsa > id_rsa

To convert the private key to a public key:

openssl rsa -in id_rsa -pubout | ssh-keygen -f /dev/stdin -i -m PKCS8

To extract the public key in a format openssh can use:

openssl pkcs12 -in pkcs12.pfx -clcerts -nokeys | openssl x509 -pubkey -noout | ssh-keygen -f /dev/stdin -i -m PKCS8

How to use terminal commands with Github?

You can't push into other people's repositories. This is because push permanently gets code into their repository, which is not cool.

What you should do, is to ask them to pull from your repository. This is done in GitHub by going to the other repository and sending a "pull request".

There is a very informative article on the GitHub's help itself: https://help.github.com/articles/using-pull-requests


To interact with your own repository, you have the following commands. I suggest you start reading on Git a bit more for these instructions (lots of materials online).

To add new files to the repository or add changed files to staged area:

$ git add <files>

To commit them:

$ git commit

To commit unstaged but changed files:

$ git commit -a

To push to a repository (say origin):

$ git push origin

To push only one of your branches (say master):

$ git push origin master

To fetch the contents of another repository (say origin):

$ git fetch origin

To fetch only one of the branches (say master):

$ git fetch origin master

To merge a branch with the current branch (say other_branch):

$ git merge other_branch

Note that origin/master is the name of the branch you fetched in the previous step from origin. Therefore, updating your master branch from origin is done by:

$ git fetch origin master
$ git merge origin/master

You can read about all of these commands in their manual pages (either on your linux or online), or follow the GitHub helps:

How to default to other directory instead of home directory

I also just changed the "Start in" setting of the shortcut icon to: %HOMEDRIVE%/xampp/htdocs/

How to change fonts in matplotlib (python)?

Say you want Comic Sans for the title and Helvetica for the x label.

csfont = {'fontname':'Comic Sans MS'}
hfont = {'fontname':'Helvetica'}

plt.title('title',**csfont)
plt.xlabel('xlabel', **hfont)
plt.show()

Javascript getElementsByName.value not working

document.getElementsByName("name") will get several elements called by same name . document.getElementsByName("name")[Number] will get one of them. document.getElementsByName("name")[Number].value will get the value of paticular element.

The key of this question is this:
The name of elements is not unique, it is usually used for several input elements in the form.
On the other hand, the id of the element is unique, which is the only definition for a particular element in a html file.

Classpath including JAR within a JAR

Winstone is pretty good http://blog.jayway.com/2008/11/28/executable-war-with-winstone-maven-plugin/. But not for complex sites. And that's a shame because all it takes is to include the plugin.

SQL Left Join first match only

Turns out I was doing it wrong, I needed to perform a nested select first of just the important columns, and do a distinct select off that to prevent trash columns of 'unique' data from corrupting my good data. The following appears to have resolved the issue... but I will try on the full dataset later.

SELECT DISTINCT P2.*
FROM (
  SELECT
      IDNo
    , FirstName
    , LastName
  FROM people P
) P2

Here is some play data as requested: http://sqlfiddle.com/#!3/050e0d/3

CREATE TABLE people
(
       [entry] int
     , [IDNo] varchar(3)
     , [FirstName] varchar(5)
     , [LastName] varchar(7)
);

INSERT INTO people
    (entry,[IDNo], [FirstName], [LastName])
VALUES
    (1,'uqx', 'bob', 'smith'),
    (2,'abc', 'john', 'willis'),
    (3,'ABC', 'john', 'willis'),
    (4,'aBc', 'john', 'willis'),
    (5,'WTF', 'jeff', 'bridges'),
    (6,'Sss', 'bill', 'doe'),
    (7,'sSs', 'bill', 'doe'),
    (8,'ssS', 'bill', 'doe'),
    (9,'ere', 'sally', 'abby'),
    (10,'wtf', 'jeff', 'bridges')
;

Prevent redirect after form is submitted

The simple answer is to shoot your call off to an external scrip via AJAX request. Then handle the response how you like.

Find closing HTML tag in Sublime Text

As said before, Control/Command + Shift + A gives you basic support for tag matching. Press it again to extend the match to the parent element. Press arrow left/right to jump to the start/end tag.

Anyway, there is no built-in highlighting of matching tags. Emmet is a popular plugin but it's overkill for this purpose and can get in the way if you don't want Emmet-like editing. Bracket Highlighter seems to be a better choice for this use case.

What are the new features in C++17?

Language features:

Templates and Generic Code

Lambda

Attributes

Syntax cleanup

Cleaner multi-return and flow control

  • Structured bindings

    • Basically, first-class std::tie with auto
    • Example:
      • const auto [it, inserted] = map.insert( {"foo", bar} );
      • Creates variables it and inserted with deduced type from the pair that map::insert returns.
    • Works with tuple/pair-likes & std::arrays and relatively flat structs
    • Actually named structured bindings in standard
  • if (init; condition) and switch (init; condition)

    • if (const auto [it, inserted] = map.insert( {"foo", bar} ); inserted)
    • Extends the if(decl) to cases where decl isn't convertible-to-bool sensibly.
  • Generalizing range-based for loops

    • Appears to be mostly support for sentinels, or end iterators that are not the same type as begin iterators, which helps with null-terminated loops and the like.
  • if constexpr

    • Much requested feature to simplify almost-generic code.

Misc

Library additions:

Data types

Invoke stuff

File System TS v1

New algorithms

  • for_each_n

  • reduce

  • transform_reduce

  • exclusive_scan

  • inclusive_scan

  • transform_exclusive_scan

  • transform_inclusive_scan

  • Added for threading purposes, exposed even if you aren't using them threaded

Threading

(parts of) Library Fundamentals TS v1 not covered above or below

Container Improvements

Smart pointer changes

Other std datatype improvements:

Misc

Traits

Deprecated

Isocpp.org has has an independent list of changes since C++14; it has been partly pillaged.

Naturally TS work continues in parallel, so there are some TS that are not-quite-ripe that will have to wait for the next iteration. The target for the next iteration is C++20 as previously planned, not C++19 as some rumors implied. C++1O has been avoided.

Initial list taken from this reddit post and this reddit post, with links added via googling or from the above isocpp.org page.

Additional entries pillaged from SD-6 feature-test list.

clang's feature list and library feature list are next to be pillaged. This doesn't seem to be reliable, as it is C++1z, not C++17.

these slides had some features missing elsewhere.

While "what was removed" was not asked, here is a short list of a few things ((mostly?) previous deprecated) that are removed in C++17 from C++:

Removed:

There were rewordings. I am unsure if these have any impact on code, or if they are just cleanups in the standard:

Papers not yet integrated into above:

  • P0505R0 (constexpr chrono)

  • P0418R2 (atomic tweaks)

  • P0512R0 (template argument deduction tweaks)

  • P0490R0 (structured binding tweaks)

  • P0513R0 (changes to std::hash)

  • P0502R0 (parallel exceptions)

  • P0509R1 (updating restrictions on exception handling)

  • P0012R1 (make exception specifications be part of the type system)

  • P0510R0 (restrictions on variants)

  • P0504R0 (tags for optional/variant/any)

  • P0497R0 (shared ptr tweaks)

  • P0508R0 (structured bindings node handles)

  • P0521R0 (shared pointer use count and unique changes?)

Spec changes:

Further reference:

Multiple models in a view

There are lots of ways...

  1. with your BigViewModel you do:

    @model BigViewModel    
    @using(Html.BeginForm()) {
        @Html.EditorFor(o => o.LoginViewModel.Email)
        ...
    }
    
  2. you can create 2 additional views

    Login.cshtml

    @model ViewModel.LoginViewModel
    @using (Html.BeginForm("Login", "Auth", FormMethod.Post))
    {
        @Html.TextBoxFor(model => model.Email)
        @Html.PasswordFor(model => model.Password)
    }
    

    and register.cshtml same thing

    after creation you have to render them in the main view and pass them the viewmodel/viewdata

    so it could be like this:

    @{Html.RenderPartial("login", ViewBag.Login);}
    @{Html.RenderPartial("register", ViewBag.Register);}
    

    or

    @{Html.RenderPartial("login", Model.LoginViewModel)}
    @{Html.RenderPartial("register", Model.RegisterViewModel)}
    
  3. using ajax parts of your web-site become more independent

  4. iframes, but probably this is not the case

Difference between -XX:+UseParallelGC and -XX:+UseParNewGC

After a lot of searching, the best explanation I've found is from Java Performance Tuning website in Question of the month: 1.4.1 Garbage collection algorithms, January 29th, 2003

Young generation garbage collection algorithms

The (original) copying collector (Enabled by default). When this collector kicks in, all application threads are stopped, and the copying collection proceeds using one thread (which means only one CPU even if on a multi-CPU machine). This is known as a stop-the-world collection, because basically the JVM pauses everything else until the collection is completed.

The parallel copying collector (Enabled using -XX:+UseParNewGC). Like the original copying collector, this is a stop-the-world collector. However this collector parallelizes the copying collection over multiple threads, which is more efficient than the original single-thread copying collector for multi-CPU machines (though not for single-CPU machines). This algorithm potentially speeds up young generation collection by a factor equal to the number of CPUs available, when compared to the original singly-threaded copying collector.

The parallel scavenge collector (Enabled using -XX:UseParallelGC). This is like the previous parallel copying collector, but the algorithm is tuned for gigabyte heaps (over 10GB) on multi-CPU machines. This collection algorithm is designed to maximize throughput while minimizing pauses. It has an optional adaptive tuning policy which will automatically resize heap spaces. If you use this collector, you can only use the the original mark-sweep collector in the old generation (i.e. the newer old generation concurrent collector cannot work with this young generation collector).

From this information, it seems the main difference (apart from CMS cooperation) is that UseParallelGC supports ergonomics while UseParNewGC doesn't.

Is there a way to make text unselectable on an HTML page?

Any JavaScript or CSS method is easily circumvented with Firebug (like Flickr's case).

You can use the ::selection pseudo-element in CSS to alter the highlight color.

If the tabs are links and the dotted rectangle in active state is of concern, you can remove that too (consider usability of course).

Class JavaLaunchHelper is implemented in two places

I am using Intellij Idea 2017 and I got into the same problem. What solved the problem for me was to simply

  1. close the project in intelliJ
  2. File -> New -> project from existing resources
  3. use Import from external model (if any)
  4. open the project again.

Checking whether a string starts with XXXX

I did a little experiment to see which of these methods

  • string.startswith('hello')
  • string.rfind('hello') == 0
  • string.rpartition('hello')[0] == ''
  • string.rindex('hello') == 0

are most efficient to return whether a certain string begins with another string.

Here is the result of one of the many test runs I've made, where each list is ordered to show the least time it took (in seconds) to parse 5 million of each of the above expressions during each iteration of the while loop I used:

['startswith: 1.37', 'rpartition: 1.38', 'rfind: 1.62', 'rindex: 1.62']
['startswith: 1.28', 'rpartition: 1.44', 'rindex: 1.67', 'rfind: 1.68']
['startswith: 1.29', 'rpartition: 1.42', 'rindex: 1.63', 'rfind: 1.64']
['startswith: 1.28', 'rpartition: 1.43', 'rindex: 1.61', 'rfind: 1.62']
['rpartition: 1.48', 'startswith: 1.48', 'rfind: 1.62', 'rindex: 1.67']
['startswith: 1.34', 'rpartition: 1.43', 'rfind: 1.64', 'rindex: 1.64']
['startswith: 1.36', 'rpartition: 1.44', 'rindex: 1.61', 'rfind: 1.63']
['startswith: 1.29', 'rpartition: 1.37', 'rindex: 1.64', 'rfind: 1.67']
['startswith: 1.34', 'rpartition: 1.44', 'rfind: 1.66', 'rindex: 1.68']
['startswith: 1.44', 'rpartition: 1.41', 'rindex: 1.61', 'rfind: 2.24']
['startswith: 1.34', 'rpartition: 1.45', 'rindex: 1.62', 'rfind: 1.67']
['startswith: 1.34', 'rpartition: 1.38', 'rindex: 1.67', 'rfind: 1.74']
['rpartition: 1.37', 'startswith: 1.38', 'rfind: 1.61', 'rindex: 1.64']
['startswith: 1.32', 'rpartition: 1.39', 'rfind: 1.64', 'rindex: 1.61']
['rpartition: 1.35', 'startswith: 1.36', 'rfind: 1.63', 'rindex: 1.67']
['startswith: 1.29', 'rpartition: 1.36', 'rfind: 1.65', 'rindex: 1.84']
['startswith: 1.41', 'rpartition: 1.44', 'rfind: 1.63', 'rindex: 1.71']
['startswith: 1.34', 'rpartition: 1.46', 'rindex: 1.66', 'rfind: 1.74']
['startswith: 1.32', 'rpartition: 1.46', 'rfind: 1.64', 'rindex: 1.74']
['startswith: 1.38', 'rpartition: 1.48', 'rfind: 1.68', 'rindex: 1.68']
['startswith: 1.35', 'rpartition: 1.42', 'rfind: 1.63', 'rindex: 1.68']
['startswith: 1.32', 'rpartition: 1.46', 'rfind: 1.65', 'rindex: 1.75']
['startswith: 1.37', 'rpartition: 1.46', 'rfind: 1.74', 'rindex: 1.75']
['startswith: 1.31', 'rpartition: 1.48', 'rfind: 1.67', 'rindex: 1.74']
['startswith: 1.44', 'rpartition: 1.46', 'rindex: 1.69', 'rfind: 1.74']
['startswith: 1.44', 'rpartition: 1.42', 'rfind: 1.65', 'rindex: 1.65']
['startswith: 1.36', 'rpartition: 1.44', 'rfind: 1.64', 'rindex: 1.74']
['startswith: 1.34', 'rpartition: 1.46', 'rfind: 1.61', 'rindex: 1.74']
['startswith: 1.35', 'rpartition: 1.56', 'rfind: 1.68', 'rindex: 1.69']
['startswith: 1.32', 'rpartition: 1.48', 'rindex: 1.64', 'rfind: 1.65']
['startswith: 1.28', 'rpartition: 1.43', 'rfind: 1.59', 'rindex: 1.66']

I believe that it is pretty obvious from the start that the startswith method would come out the most efficient, as returning whether a string begins with the specified string is its main purpose.

What surprises me is that the seemingly impractical string.rpartition('hello')[0] == '' method always finds a way to be listed first, before the string.startswith('hello') method, every now and then. The results show that using str.partition to determine if a string starts with another string is more efficient then using both rfind and rindex.

Another thing I've noticed is that string.rindex('hello') == 0 and string.rindex('hello') == 0 have a good battle going on, each rising from fourth to third place, and dropping from third to fourth place, which makes sense, as their main purposes are the same.

Here is the code:

from time import perf_counter

string = 'hello world'
places = dict()

while True:
    start = perf_counter()
    for _ in range(5000000):
        string.startswith('hello')
    end = perf_counter()
    places['startswith'] = round(end - start, 2)

    start = perf_counter()
    for _ in range(5000000):
        string.rfind('hello') == 0
    end = perf_counter()
    places['rfind'] = round(end - start, 2)

    start = perf_counter()
    for _ in range(5000000):
        string.rpartition('hello')[0] == ''
    end = perf_counter()
    places['rpartition'] = round(end - start, 2)

    start = perf_counter()
    for _ in range(5000000):
        string.rindex('hello') == 0
    end = perf_counter()
    places['rindex'] = round(end - start, 2)
    
    print([f'{b}: {str(a).ljust(4, "4")}' for a, b in sorted(i[::-1] for i in places.items())])

Passing a method parameter using Task.Factory.StartNew

class Program
{
    static void Main(string[] args)
    {
        Task.Factory.StartNew(() => MyMethod("param value"));
    }

    private static void MyMethod(string p)
    {
        Console.WriteLine(p);
    }
}

Select Top and Last rows in a table (SQL server)

You must sort your data according your needs (es. in reverse order) and use select top query

Using union and order by clause in mysql

This is because You're sorting entire result-set, You should sort, every part of union separately, or You can use ORDER BY (Something ie. subquery distance) THEN (something ie row id) clause

How to write logs in text file when using java.util.logging.Logger

Here is my logging class based on the accepted answer:

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.*;

public class ErrorLogger
{
    private Logger logger;

    public ErrorLogger()
    {
        logger = Logger.getAnonymousLogger();

        configure();
    }

    private void configure()
    {
        try
        {
            String logsDirectoryFolder = "logs";
            Files.createDirectories(Paths.get(logsDirectoryFolder));
            FileHandler fileHandler = new FileHandler(logsDirectoryFolder + File.separator + getCurrentTimeString() + ".log");
            logger.addHandler(fileHandler);
            SimpleFormatter formatter = new SimpleFormatter();
            fileHandler.setFormatter(formatter);
        } catch (IOException exception)
        {
            exception.printStackTrace();
        }

        addCloseHandlersShutdownHook();
    }

    private void addCloseHandlersShutdownHook()
    {
        Runtime.getRuntime().addShutdownHook(new Thread(() ->
        {
            // Close all handlers to get rid of empty .LCK files
            for (Handler handler : logger.getHandlers())
            {
                handler.close();
            }
        }));
    }

    private String getCurrentTimeString()
    {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
        return dateFormat.format(new Date());
    }

    public void log(Exception exception)
    {
        logger.log(Level.SEVERE, "", exception);
    }
}

IIS 500.19 with 0x80070005 The requested page cannot be accessed because the related configuration data for the page is invalid error

The same thing happened with me , Try checking this by double clicking on the Connection strings on the right pane of IIS 7 when you select a website.

It will give you an error (that there is some problem with web config file), because you have used URL rewrite rules and the respective component is not installed.

Install “Microsoft URL Rewrite Module 2.0 for IIS 7” and this should fix your problem

Multiple REPLACE function in Oracle

The accepted answer to how to replace multiple strings together in Oracle suggests using nested REPLACE statements, and I don't think there is a better way.

If you are going to make heavy use of this, you could consider writing your own function:

CREATE TYPE t_text IS TABLE OF VARCHAR2(256);

CREATE FUNCTION multiple_replace(
  in_text IN VARCHAR2, in_old IN t_text, in_new IN t_text
)
  RETURN VARCHAR2
AS
  v_result VARCHAR2(32767);
BEGIN
  IF( in_old.COUNT <> in_new.COUNT ) THEN
    RETURN in_text;
  END IF;
  v_result := in_text;
  FOR i IN 1 .. in_old.COUNT LOOP
    v_result := REPLACE( v_result, in_old(i), in_new(i) );
  END LOOP;
  RETURN v_result;
END;

and then use it like this:

SELECT multiple_replace( 'This is #VAL1# with some #VAL2# to #VAL3#',
                         NEW t_text( '#VAL1#', '#VAL2#', '#VAL3#' ),
                         NEW t_text( 'text', 'tokens', 'replace' )
                       )
FROM dual

This is text with some tokens to replace

If all of your tokens have the same format ('#VAL' || i || '#'), you could omit parameter in_old and use your loop-counter instead.

jQuery first child of "this"

you can use DOM

$(this).children().first()
// is equivalent to
$(this.firstChild)

C++ vector's insert & push_back difference

The biggest difference is their functionality. push_back always puts a new element at the end of the vector and insert allows you to select new element's position. This impacts the performance. vector elements are moved in the memory only when it's necessary to increase it's length because too little memory was allocated for it. On the other hand insert forces to move all elements after the selected position of a new element. You simply have to make a place for it. This is why insert might often be less efficient than push_back.

Select info from table where row has max date

SELECT distinct
  group, 
  max_date = MAX(date) OVER (PARTITION BY group), checks
FROM table

Should work.

Last executed queries for a specific database

This works for me to find queries on any database in the instance. I'm sysadmin on the instance (check your privileges):

SELECT deqs.last_execution_time AS [Time], dest.text AS [Query], dest.*
FROM sys.dm_exec_query_stats AS deqs
CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
WHERE dest.dbid = DB_ID('msdb')
ORDER BY deqs.last_execution_time DESC

This is the same answer that Aaron Bertrand provided but it wasn't placed in an answer.

fork() child and parent processes

We control fork() process call by if, else statement. See my code below:

int main()
{
   int forkresult, parent_ID;

   forkresult=fork();
   if(forkresult !=0 )
   {
        printf(" I am the parent my ID is = %d" , getpid());
        printf(" and my child ID is = %d\n" , forkresult);
   }
   parent_ID = getpid();

   if(forkresult ==0)
      printf(" I am the  child ID is = %d",getpid());
   else
      printf(" and my parent ID is = %d", parent_ID);
}

How can I initialize a C# List in the same line I declare it. (IEnumerable string Collection Example)

Posting this answer for folks wanting to initialize list with POCOs and also coz this is the first thing that pops up in search but all answers only for list of type string.

You can do this two ways one is directly setting the property by setter assignment or much cleaner by creating a constructor that takes in params and sets the properties.

class MObject {        
        public int Code { get; set; }
        public string Org { get; set; }
    }

List<MObject> theList = new List<MObject> { new MObject{ PASCode = 111, Org="Oracle" }, new MObject{ PASCode = 444, Org="MS"} };

OR by parameterized constructor

class MObject {
        public MObject(int code, string org)
        {
            Code = code;
            Org = org;
        }

        public int Code { get; set; }
        public string Org { get; set; }
    }

List<MObject> theList = new List<MObject> {new MObject( 111, "Oracle" ), new MObject(222,"SAP")};


        

Spring REST Service: how to configure to remove null objects in json response

I've found a solution through configuring the Spring container, but it's still not exactly what I wanted.

I rolled back to Spring 3.0.5, removed and in it's place I changed my config file to:

    <bean
    class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <list>
            <bean
                class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
                <property name="objectMapper" ref="jacksonObjectMapper" />
            </bean>
        </list>
    </property>
</bean>


<bean id="jacksonObjectMapper" class="org.codehaus.jackson.map.ObjectMapper" />
<bean id="jacksonSerializationConfig" class="org.codehaus.jackson.map.SerializationConfig"
    factory-bean="jacksonObjectMapper" factory-method="getSerializationConfig" />
<bean
    class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    <property name="targetObject" ref="jacksonSerializationConfig" />
    <property name="targetMethod" value="setSerializationInclusion" />
    <property name="arguments">
        <list>
            <value type="org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion">NON_NULL</value>
        </list>
    </property>
</bean>

This is of course similar to responses given in other questions e.g.

configuring the jacksonObjectMapper not working in spring mvc 3

The important thing to note is that mvc:annotation-driven and AnnotationMethodHandlerAdapter cannot be used in the same context.

I'm still unable to get it working with Spring 3.1 and mvc:annotation-driven though. A solution that uses mvc:annotation-driven and all the benefits that accompany it would be far better I think. If anyone could show me how to do this, that would be great.

Fit image into ImageView, keep aspect ratio and then resize ImageView to image dimensions?

May not be answer for this specific question, but if someone is, like me, searching for answer how to fit image in ImageView with bounded size (for example, maxWidth) while preserving Aspect Ratio and then get rid of excessive space occupied by ImageView, then the simplest solution is to use the following properties in XML:

    android:scaleType="centerInside"
    android:adjustViewBounds="true"

$(document).ready(function(){ Uncaught ReferenceError: $ is not defined

No need to use jQuery.noConflict and all

Try this instead:

// Replace line no. 87 (guessing from your chrome console) to the following

jQuery(document).ready(function($){

// All your code using $

});

If you still get error at line 87, like Uncaught reference error: jQuery is not defined, then you need to include jQuery file before using it, for which you can check the above answers

Blocks and yields in Ruby

It's quite possible that someone will provide a truly detailed answer here, but I've always found this post from Robert Sosinski to be a great explanation of the subtleties between blocks, procs & lambdas.

I should add that I believe the post I'm linking to is specific to ruby 1.8. Some things have changed in ruby 1.9, such as block variables being local to the block. In 1.8, you'd get something like the following:

>> a = "Hello"
=> "Hello"
>> 1.times { |a| a = "Goodbye" }
=> 1
>> a
=> "Goodbye"

Whereas 1.9 would give you:

>> a = "Hello"
=> "Hello"
>> 1.times { |a| a = "Goodbye" }
=> 1
>> a
=> "Hello"

I don't have 1.9 on this machine so the above might have an error in it.

Android ADB commands to get the device properties

From Linux Terminal:

adb shell getprop | grep "model\|version.sdk\|manufacturer\|hardware\|platform\|revision\|serialno\|product.name\|brand"

From Windows PowerShell:

adb shell 
getprop | grep -e 'model' -e 'version.sdk' -e 'manufacturer' -e 'hardware' -e 'platform' -e 'revision' -e 'serialno' -e 'product.name' -e 'brand'

Sample output for Samsung:

[gsm.version.baseband]: [G900VVRU2BOE1]
[gsm.version.ril-impl]: [Samsung RIL v3.0]
[net.knoxscep.version]: [2.0.1]
[net.knoxsso.version]: [2.1.1]
[net.knoxvpn.version]: [2.2.0]
[persist.service.bdroid.version]: [4.1]
[ro.board.platform]: [msm8974]
[ro.boot.hardware]: [qcom]
[ro.boot.serialno]: [xxxxxx]
[ro.build.version.all_codenames]: [REL]
[ro.build.version.codename]: [REL]
[ro.build.version.incremental]: [G900VVRU2BOE1]
[ro.build.version.release]: [5.0]
[ro.build.version.sdk]: [21]
[ro.build.version.sdl]: [2101]
[ro.com.google.gmsversion]: [5.0_r2]
[ro.config.timaversion]: [3.0]
[ro.hardware]: [qcom]
[ro.opengles.version]: [196108]
[ro.product.brand]: [Verizon]
[ro.product.manufacturer]: [samsung]
[ro.product.model]: [SM-G900V]
[ro.product.name]: [kltevzw]
[ro.revision]: [14]
[ro.serialno]: [e5ce97c7]

HTML email in outlook table width issue - content is wider than the specified table width

I guess problem is in width attributes in table and td remove 'px' for example

<table border="0" cellpadding="0" cellspacing="0" width="580px" style="background-color: #0290ba;">

Should be

<table border="0" cellpadding="0" cellspacing="0" width="580" style="background-color: #0290ba;">

How do I clone a Django model instance object and save it to the database?

How to do this was added to the official Django docs in Django1.4

https://docs.djangoproject.com/en/1.10/topics/db/queries/#copying-model-instances

The official answer is similar to miah's answer, but the docs point out some difficulties with inheritance and related objects, so you should probably make sure you read the docs.

How to fix height of TR?

Putting div inside a td made it work for me.

<table width="100%">
    <tr><td><div style="font-size:2px; height:2px; vertical-align:middle;">&nbsp;</div></td></tr>

removing bold styling from part of a header

You could wrap the not-bold text into a span and give the span the following properties:

.notbold{
    font-weight:normal
}?

and

<h1>**This text should be bold**, <span class='notbold'>but this text should not</span></h1>

See: http://jsfiddle.net/MRcpa/1/

Use <span> when you want to change the style of elements without placing them in a new block-level element in the document.

Java List.contains(Object with field value equal to x)

This is how to do it using Java 8+ :

boolean isJohnAlive = list.stream().anyMatch(o -> o.getName().equals("John"));

Error in plot.new() : figure margins too large in R

This sometimes happen in RStudio. In order to solve it you can attempt to plot to an external window (Windows-only):

windows() ## create window to plot your file
## ... your plotting code here ...
dev.off() 

Replace one substring for another string in shell script

This can be done entirely with bash string manipulation:

first="I love Suzy and Mary"
second="Sara"
first=${first/Suzy/$second}

That will replace only the first occurrence; to replace them all, double the first slash:

first="Suzy, Suzy, Suzy"
second="Sara"
first=${first//Suzy/$second}
# first is now "Sara, Sara, Sara"

Hash string in c#

I don't really understand the full scope of your question, but if all you need is a hash of the string, then it's very easy to get that.

Just use the GetHashCode method.

Like this:

string hash = username.GetHashCode();

How can I easily switch between PHP versions on Mac OSX?

If you have both versions of PHP installed, you can switch between versions using the link and unlink brew commands.

For example, to switch between PHP 7.4 and PHP 7.3

brew unlink [email protected]
brew link [email protected]

PS: both versions of PHP have be installed for these commands to work.

How to add directory to classpath in an application run profile in IntelliJ IDEA?

In Intellij 13, it looks it's slightly different again. Here are the instructions for Intellij 13:

  1. click on the Project view or unhide it by clicking on the "1: Project" button on the left border of the window or by pressing Alt + 1
  2. find your project or sub-module and click on it to highlight it, then press F4, or right click and choose "Open Module Settings" (on IntelliJ 14 it became F12)
  3. click on the dependencies tab
  4. Click the "+" button on the right and select "Jars or directories..."
  5. Find your path and click OK
  6. In the dialog with "Choose Categories of Selected File", choose Classes (even if it's properties), press OK and OK again
  7. You can now run your application and it will have the selected path in the class path

Printing a char with printf

This is supposed to print the ASCII value of the character, as %d is the escape sequence for an integer. So the value given as argument of printf is taken as integer when printed.

char ch = 'a';
printf("%d", ch);

Same holds for printf("%d", '\0');, where the NULL character is interpreted as the 0 integer.

Finally, sizeof('\n') is 4 because in C, this notation for characters stands for the corresponding ASCII integer. So '\n' is the same as 10 as an integer.

It all depends on the interpretation you give to the bytes.

javascript pushing element at the beginning of an array

Use unshift, which modifies the existing array by adding the arguments to the beginning:

TheArray.unshift(TheNewObject);

How to process SIGTERM signal gracefully?

I think you are near to a possible solution.

Execute mainloop in a separate thread and extend it with the property shutdown_flag. The signal can be caught with signal.signal(signal.SIGTERM, handler) in the main thread (not in a separate thread). The signal handler should set shutdown_flag to True and wait for the thread to end with thread.join()

How does Google reCAPTCHA v2 work behind the scenes?

My Bots are running well against ReCaptcha.

Here my Solution.

Let your Bot do this Steps:

First write a Human Mouse Move Function to move your Mouse like a B-Spline (Ask me for Source Code). This is the most important Point.

Also use for better results a VPN like https://www.purevpn.com

For every Recpatcha do these Steps:

  1. If you use VPN switch IP first

  2. Clear all Browser Cookies

  3. Clear all Browser Cache

  4. Set one of these Useragents by Random:

    a. Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)

    b. Mozilla/5.0 (Windows NT 6.1; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0

5 Move your Mouse with the Human Mouse Move Funktion from a RandomPoint into the I am not a Robot Image every time with different 10x10 Randomrange

  1. Then Click ever with random delay between

    WM_LBUTTONDOWN

    and

    WM_LBUTTONUP

  2. Take Screenshot from Image Captcha

  3. Send Screenshot to

    http://www.deathbycaptcha.com

    or

    https://2captcha.com

and let they solve.

  1. After receiving click cooridinates from captcha solver use your Human Mouse move Funktion to move and Click Recaptcha Images

  2. Use your Human Mouse Move Funktion to move and Click to the Recaptcha Verify Button

In 75% all trys Recaptcha will solved

Chears Google

Tom

How to set socket timeout in C when making multiple connections?

You can use the SO_RCVTIMEO and SO_SNDTIMEO socket options to set timeouts for any socket operations, like so:

    struct timeval timeout;      
    timeout.tv_sec = 10;
    timeout.tv_usec = 0;

    if (setsockopt (sockfd, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout,
                sizeof(timeout)) < 0)
        error("setsockopt failed\n");

    if (setsockopt (sockfd, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout,
                sizeof(timeout)) < 0)
        error("setsockopt failed\n");

Edit: from the setsockopt man page:

SO_SNDTIMEO is an option to set a timeout value for output operations. It accepts a struct timeval parameter with the number of seconds and microseconds used to limit waits for output operations to complete. If a send operation has blocked for this much time, it returns with a partial count or with the error EWOULDBLOCK if no data were sent. In the current implementation, this timer is restarted each time additional data are delivered to the protocol, implying that the limit applies to output portions ranging in size from the low-water mark to the high-water mark for output.

SO_RCVTIMEO is an option to set a timeout value for input operations. It accepts a struct timeval parameter with the number of seconds and microseconds used to limit waits for input operations to complete. In the current implementation, this timer is restarted each time additional data are received by the protocol, and thus the limit is in effect an inactivity timer. If a receive operation has been blocked for this much time without receiving additional data, it returns with a short count or with the error EWOULDBLOCK if no data were received. The struct timeval parameter must represent a positive time interval; otherwise, setsockopt() returns with the error EDOM.

Differences between unique_ptr and shared_ptr

unique_ptr
is a smart pointer which owns an object exclusively.

shared_ptr
is a smart pointer for shared ownership. It is both copyable and movable. Multiple smart pointer instances can own the same resource. As soon as the last smart pointer owning the resource goes out of scope, the resource will be freed.

Converting a list to a set changes element order

In mathematics, there are sets and ordered sets (osets).

  • set: an unordered container of unique elements (Implemented)
  • oset: an ordered container of unique elements (NotImplemented)

In Python, only sets are directly implemented. We can emulate osets with regular dict keys (3.7+).

Given

a = [1, 2, 20, 6, 210, 2, 1]
b = {2, 6}

Code

oset = dict.fromkeys(a).keys()
# dict_keys([1, 2, 20, 6, 210])

Demo

Replicates are removed, insertion-order is preserved.

list(oset)
# [1, 2, 20, 6, 210]

Set-like operations on dict keys.

oset - b
# {1, 20, 210}

oset | b
# {1, 2, 5, 6, 20, 210}

oset & b
# {2, 6}

oset ^ b
# {1, 5, 20, 210}

Details

Note: an unordered structure does not preclude ordered elements. Rather, maintained order is not guaranteed. Example:

assert {1, 2, 3} == {2, 3, 1}                    # sets (order is ignored)

assert [1, 2, 3] != [2, 3, 1]                    # lists (order is guaranteed)

One may be pleased to discover that a list and multiset (mset) are two more fascinating, mathematical data structures:

  • list: an ordered container of elements that permits replicates (Implemented)
  • mset: an unordered container of elements that permits replicates (NotImplemented)*

Summary

Container | Ordered | Unique | Implemented
----------|---------|--------|------------
set       |    n    |    y   |     y
oset      |    y    |    y   |     n
list      |    y    |    n   |     y
mset      |    n    |    n   |     n*  

*A multiset can be indirectly emulated with collections.Counter(), a dict-like mapping of multiplicities (counts).

How to open a file / browse dialog using javascript?

Here is a non-jQuery solution. Note you can't just use .click() as some browsers do not support it.

<script type="text/javascript">
function performClick(elemId) {
   var elem = document.getElementById(elemId);
   if(elem && document.createEvent) {
      var evt = document.createEvent("MouseEvents");
      evt.initEvent("click", true, false);
      elem.dispatchEvent(evt);
   }
}
</script>
<a href="#" onclick="performClick('theFile');">Open file dialog</a>
<input type="file" id="theFile" />

Python 3: UnboundLocalError: local variable referenced before assignment

You can fix this by passing parameters rather than relying on Globals

def function(Var1, Var2): 
    if Var2 == 0 and Var1 > 0:
        print("Result One")
    elif Var2 == 1 and Var1 > 0:
        print("Result Two")
    elif Var1 < 1:
        print("Result Three")
    return Var1 - 1
function(1, 1)

Python "TypeError: unhashable type: 'slice'" for encoding categorical data

I was getting same error (TypeError: unhashable type: 'slice') with below code:

included_cols = [2,4,10]
dataset = dataset[:,included_cols]  #Columns 2,4 and 10 are included.

Resolved with below code by putting iloc after dataset:

included_cols = [2,4,10]
dataset = dataset.iloc[:,included_cols]  #Columns 2,4 and 10 are included.

Count number of tables in Oracle

REM setting current_schema is required as the 2nd query depends on the current user referred in the session

ALTER SESSION SET CURRENT_SCHEMA=TABLE_OWNER;

SELECT table_name,
         TO_NUMBER (
            EXTRACTVALUE (
               xmltype (
                  DBMS_XMLGEN.getxml ('select count(*) c from ' || table_name)),
               '/ROWSET/ROW/C'))
            COUNT
    FROM dba_tables
   WHERE owner = 'TABLE_OWNER'
ORDER BY COUNT DESC;

Reading large text files with streams in C#

If you read the performance and benchmark stats on this website, you'll see that the fastest way to read (because reading, writing, and processing are all different) a text file is the following snippet of code:

using (StreamReader sr = File.OpenText(fileName))
{
    string s = String.Empty;
    while ((s = sr.ReadLine()) != null)
    {
        //do your stuff here
    }
}

All up about 9 different methods were bench marked, but that one seem to come out ahead the majority of the time, even out performing the buffered reader as other readers have mentioned.

Google access token expiration time

Have a look at: https://developers.google.com/accounts/docs/OAuth2UserAgent#handlingtheresponse

It says:

Other parameters included in the response include expires_in and token_type. These parameters describe the lifetime of the token in seconds...

IllegalArgumentException or NullPointerException for a null parameter?

I was all in favour of throwing IllegalArgumentException for null parameters, until today, when I noticed the java.util.Objects.requireNonNull method in Java 7. With that method, instead of doing:

if (param == null) {
    throw new IllegalArgumentException("param cannot be null.");
}

you can do:

Objects.requireNonNull(param);

and it will throw a NullPointerException if the parameter you pass it is null.

Given that that method is right bang in the middle of java.util I take its existence to be a pretty strong indication that throwing NullPointerException is "the Java way of doing things".

I think I'm decided at any rate.

Note that the arguments about hard debugging are bogus because you can of course provide a message to NullPointerException saying what was null and why it shouldn't be null. Just like with IllegalArgumentException.

One added advantage of NullPointerException is that, in highly performance critical code, you could dispense with an explicit check for null (and a NullPointerException with a friendly error message), and just rely on the NullPointerException you'll get automatically when you call a method on the null parameter. Provided you call a method quickly (i.e. fail fast), then you have essentially the same effect, just not quite as user friendly for the developer. Most times it's probably better to check explicitly and throw with a useful message to indicate which parameter was null, but it's nice to have the option of changing that if performance dictates without breaking the published contract of the method/constructor.

What's is the difference between train, validation and test set, in neural networks?

Would appreciate any thoughts on the situation with 3 data sets. Say a logistic regression model is fitted yielding the following accuracy (Gini): Train: 70%; Test 58% and Out-of-time validation: 66%.

Actually all the possible combinations of predictors bring the same results with quite a huge drop between train and test data sets. The sample size is around 8k divided into train and test 70/30. OOT sample contains a few thousands of cases. Regularization, ensembles didn't help in solving this.

I doubt whether this is something I should concern if OOT performance is acceptable and close to train sample performance?

Why is Spring's ApplicationContext.getBean considered bad?

The motivation is to write code that doesn't depend explicitly on Spring. That way, if you choose to switch containers, you don't have to rewrite any code.

Think of the container as something is invisible to your code, magically providing for its needs, without being asked.

Dependency injection is a counterpoint to the "service locator" pattern. If you are going to lookup dependencies by name, you might as well get rid of the DI container and use something like JNDI.

symfony 2 No route found for "GET /"

Prefix is the prefix for url routing. If it's equals to '/' it means it will have no prefix. Then you defined a route with pattern "it should start with /hello".

To create a route for '/' you need to add these lines in your src/Shop/MyShopBundle/Resources/config/routing.yml :

ShopMyShopBundle_homepage:
    pattern:  /
    defaults: { _controller: ShopMyShopBundle:Main:index }

Why call git branch --unset-upstream to fixup?

This might solve your problem.

after doing changes you can commit it and then

git remote add origin https://(address of your repo) it can be https or ssh
then
git push -u origin master

hope it works for you.

thanks

'' is not recognized as an internal or external command, operable program or batch file

When you want to run an executable file from the Command prompt, (cmd.exe), or a batch file, it will:

  • Search the current working directory for the executable file.
  • Search all locations specified in the %PATH% environment variable for the executable file.

If the file isn't found in either of those options you will need to either:

  1. Specify the location of your executable.
  2. Change the working directory to that which holds the executable.
  3. Add the location to %PATH% by apending it, (recommended only with extreme caution).

You can see which locations are specified in %PATH% from the Command prompt, Echo %Path%.

Because of your reported error we can assume that Mobile.exe is not in the current directory or in a location specified within the %Path% variable, so you need to use 1., 2. or 3..

Examples for 1.

C:\directory_path_without_spaces\My-App\Mobile.exe

or:

"C:\directory path with spaces\My-App\Mobile.exe"

Alternatively you may try:

Start C:\directory_path_without_spaces\My-App\Mobile.exe

or

Start "" "C:\directory path with spaces\My-App\Mobile.exe"

Where "" is an empty title, (you can optionally add a string between those doublequotes).

Examples for 2.

CD /D C:\directory_path_without_spaces\My-App
Mobile.exe

or

CD /D "C:\directory path with spaces\My-App"
Mobile.exe

You could also use the /D option with Start to change the working directory for the executable to be run by the start command

Start /D C:\directory_path_without_spaces\My-App Mobile.exe

or

Start "" /D "C:\directory path with spaces\My-App" Mobile.exe

Correct modification of state arrays in React.js

This worked for me to add an array within an array

this.setState(prevState => ({
    component: prevState.component.concat(new Array(['new', 'new']))
}));

WordPress is giving me 404 page not found for all pages except the homepage

IF all this dont work, your .htaccess is correct, and permalinks trick didnt work, you may have not enabled your apache2 rewite mod.

I ran this and my issue was solved:

 sudo a2enmod rewrite 

How to set the timeout for a TcpClient?

If using async & await and desire to use a time out without blocking, then an alternative and simpler approach from the answer provide by mcandal is to execute the connect on a background thread and await the result. For example:

Task<bool> t = Task.Run(() => client.ConnectAsync(ipAddr, port).Wait(1000));
await t;
if (!t.Result)
{
   Console.WriteLine("Connect timed out");
   return; // Set/return an error code or throw here.
}
// Successful Connection - if we get to here.

See the Task.Wait MSDN article for more info and other examples.

Easy way to print Perl array? (with a little formatting)

Also, you may want to try Data::Dumper. Example:

use Data::Dumper;

# simple procedural interface
print Dumper($foo, $bar);

@font-face src: local - How to use the local font if the user already has it?

If you want to check for local files first do:

@font-face {
font-family: 'Green Sans Web';
src:
    local('Green Web'),
    local('GreenWeb-Regular'),
    url('GreenWeb.ttf');
}

There is a more elaborate description of what to do here.

What does "to stub" mean in programming?

A stub is a controllable replacement for an Existing Dependency (or collaborator) in the system. By using a stub, you can test your code without dealing with the dependency directly.

External Dependency - Existing Dependency:
It is an object in your system that your code under test interacts with and over which you have no control. (Common examples are filesystems, threads, memory, time, and so on.)

Forexample in below code:

public void Analyze(string filename)
    {
        if(filename.Length<8)
        {
            try
            {
                errorService.LogError("long file entered named:" + filename);
            }
            catch (Exception e)
            {
                mailService.SendEMail("[email protected]", "ErrorOnWebService", "someerror");
            }
        }
    }

You want to test mailService.SendEMail() method, but to do that you need to simulate an Exception in your test method, so you just need to create a Fake Stub errorService object to simulate the result you want, then your test code will be able to test mailService.SendEMail() method. As you see you need to simulate a result which is from an another Dependency which is ErrorService class object (Existing Dependency object).

How do I clear my Jenkins/Hudson build history?

Go to "Manage Jenkins" > "Script Console"

Run below:

def jobName = "build_name"  
def job = Jenkins.instance.getItem(jobName)  
job.getBuilds().each { it.delete() }  
job.save()

Python - Count elements in list

just do len(MyList)

This also works for strings, tuples, dict objects.

/usr/bin/codesign failed with exit code 1

Open the project path in terminal and enter the below commands in terminal

1) find . | xargs -0 xattr -c

2) xattr -rc .

This works for me.

How to force composer to reinstall a library?

First execute composer clearcache

Then clear your vendors folder

rm -rf vendor/*

or better yet just remove the specific module which makes problems to avoid having to download all over again.

Maven:Non-resolvable parent POM and 'parent.relativePath' points at wrong local POM

The normal layout for a maven multi module project is:

parent
+-- pom.xml
+-- module
    +-- pom.xml

Check that you use this layout.

Additionally:

  1. the relativePath looks strange. Instead of '..'

    <relativePath>..</relativePath>
    

    try '../' instead:

    <relativePath>../</relativePath>
    

    You can also remove relativePath if you use the standard layout. This is what I always do, and on the command line I can build as well the parent (and all modules) or only a single module.

  2. The module path may be wrong. In the parent you define the module as:

    <module>junitcategorizer.cutdetection</module>
    

    You must specify the name of the folder of the child module, not an artifact identifier. If junitcategorizer.cutdetection is not the name of the folder than change it accordingly.

Hope that helps..

EDIT have a look at the other post, I answered there.

How to send a "multipart/form-data" with requests in python?

Here is the python snippet you need to upload one large single file as multipart formdata. With NodeJs Multer middleware running on the server side.

import requests
latest_file = 'path/to/file'
url = "http://httpbin.org/apiToUpload"
files = {'fieldName': open(latest_file, 'rb')}
r = requests.put(url, files=files)

For the server side please check the multer documentation at: https://github.com/expressjs/multer here the field single('fieldName') is used to accept one single file, as in:

var upload = multer().single('fieldName');

How do I prevent people from doing XSS in Spring MVC?

In Spring you can escape the html from JSP pages generated by <form> tags. This closes off a lot avenues for XSS attacks, and can be done automatically in three ways:

For the entire application in the web.xml file:

<context-param>
    <param-name>defaultHtmlEscape</param-name>
    <param-value>true</param-value>
</context-param>

For all forms on a given page in the file itself:

<spring:htmlEscape defaultHtmlEscape="true" /> 

For each form:

<form:input path="someFormField" htmlEscape="true" /> 

How do you programmatically update query params in react-router?

It can also be written this way

this.props.history.push(`${window.location.pathname}&page=${pageNumber}`)

VBA to copy a file from one directory to another

This method is even easier if you're ok with fewer options:

FileCopy source, destination

How to write a basic swap function in Java

Here is one trick:

public static int getItself(int itself, int dummy)
{
    return itself;
}

public static void main(String[] args)
{
    int a = 10;
    int b = 20;

    a = getItself(b, b = a);
}

What's the best way to get the last element of an array without deleting it?

One more possible solution...

$last_element = array_reverse( $array )[0];

How do I insert datetime value into a SQLite database?

This may not be the most popular or efficient method, but I tend to forgo strong datatypes in SQLite since they are all essentially dumped in as strings anyway.

I've written a thin C# wrapper around the SQLite library before (when using SQLite with C#, of course) to handle insertions and extractions to and from SQLite as if I were dealing with DateTime objects.

How to make Git "forget" about a file that was tracked but is now in .gitignore?

move it out, commit, then move it back in. This has worked for me in the past. There is probably a 'gittier' way to accomplish this.

Creating and Update Laravel Eloquent

Save function:

$shopOwner->save()

already do what you want...

Laravel code:

    // If the model already exists in the database we can just update our record
    // that is already in this database using the current IDs in this "where"
    // clause to only update this model. Otherwise, we'll just insert them.
    if ($this->exists)
    {
        $saved = $this->performUpdate($query);
    }

    // If the model is brand new, we'll insert it into our database and set the
    // ID attribute on the model to the value of the newly inserted row's ID
    // which is typically an auto-increment value managed by the database.
    else
    {
        $saved = $this->performInsert($query);
    }

javascript setTimeout() not working

Please change your code as follows:

<script>
    var button = document.getElementById("reactionTester");
    var start = document.getElementById("start");
    function init() {
        var startInterval/*in milliseconds*/ = Math.floor(Math.random()*30)*1000;
        setTimeout(startTimer,startInterval); 
    }
    function startTimer(){
        document.write("hey");
    }
</script>

See if that helps. Basically, the difference is references the 'startTimer' function instead of executing it.

How do I create batch file to rename large number of files in a folder?

dir /b *.jpg >file.bat

This will give you lines such as:

Vacation2010 001.jpg
Vacation2010 002.jpg
Vacation2010 003.jpg

Edit file.bat in your favorite Windows text-editor, doing the equivalent of:

s/Vacation2010(.+)/rename "&" "December \1"/

That's a regex; many editors support them, but none that come default with Windows (as far as I know). You can also get a command line tool such as sed or perl which can take the exact syntax I have above, after escaping for the command line.

The resulting lines will look like:

rename "Vacation2010 001.jpg" "December 001.jpg"
rename "Vacation2010 002.jpg" "December 002.jpg"
rename "Vacation2010 003.jpg" "December 003.jpg"

You may recognize these lines as rename commands, one per file from the original listing. ;) Run that batch file in cmd.exe.

How do I correct the character encoding of a file?

There are programs that try to detect the encoding of an file like chardet. Then you could convert it to a different encoding using iconv. But that requires that the original text is still intact and no information is lost (for example by removing accents or whole accented letters).

Android: combining text & image on a Button or ImageButton

    <ImageView
        android:id="@+id/iv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop"
        android:src="@drawable/temp"
        />

PDF to image using Java

In Ghost4J library (http://ghost4j.sourceforge.net), since version 0.4.0 you can use a SimpleRenderer to do the job with few lines of code:

  1. Load PDF or PS file (use PSDocument class for that):

        PDFDocument document = new PDFDocument();
        document.load(new File("input.pdf"));
    
  2. Create the renderer

        SimpleRenderer renderer = new SimpleRenderer();
    
        // set resolution (in DPI)
        renderer.setResolution(300);
    
  3. Render

        List<Image> images = renderer.render(document);
    

Then you can do what you want with your image objects, for example, you can write them as PNG like this:

            for (int i = 0; i < images.size(); i++) {
                ImageIO.write((RenderedImage) images.get(i), "png", new File((i + 1) + ".png"));
            }

Note: Ghost4J uses the native Ghostscript C API so you need to have a Ghostscript installed on your box.

I hope it will help you :)

How to connect html pages to mysql database?

HTML are markup languages, basically they are set of tags like <html>, <body>, which is used to present a website using , and as a whole. All these, happen in the clients system or the user you will be browsing the website.

Now, Connecting to a database, happens on whole another level. It happens on server, which is where the website is hosted.

So, in order to connect to the database and perform various data related actions, you have to use server-side scripts, like , , etc.

Now, lets see a snippet of connection using MYSQLi Extension of PHP

$db = mysqli_connect('hostname','username','password','databasename');

This single line code, is enough to get you started, you can mix such code, combined with HTML tags to create a HTML page, which is show data based pages. For example:

<?php
    $db = mysqli_connect('hostname','username','password','databasename');
?>
<html>
    <body>
          <?php
                $query = "SELECT * FROM `mytable`;";
                $result = mysqli_query($db, $query);
                while($row = mysqli_fetch_assoc($result)) {
                      // Display your datas on the page
                }
          ?>
    </body>
</html>

In order to insert new data into the database, you can use phpMyAdmin or write a INSERT query and execute them.

Understanding Matlab FFT example

There are some misconceptions here.

Frequencies above 500 can be represented in an FFT result of length 1000. Unfortunately these frequencies are all folded together and mixed into the first 500 FFT result bins. So normally you don't want to feed an FFT a signal containing any frequencies at or above half the sampling rate, as the FFT won't care and will just mix the high frequencies together with the low ones (aliasing) making the result pretty much useless. That's why data should be low-pass filtered before being sampled and fed to an FFT.

The FFT returns amplitudes without frequencies because the frequencies depend, not just on the length of the FFT, but also on the sample rate of the data, which isn't part of the FFT itself or it's input. You can feed the same length FFT data at any sample rate, as thus get any range of frequencies out of it.

The reason the result plots ends at 500 is that, for any real data input, the frequencies above half the length of the FFT are just mirrored repeats (complex conjugated) of the data in the first half. Since they are duplicates, most people just ignore them. Why plot duplicates? The FFT calculates the other half of the result for people who feed the FFT complex data (with both real and imaginary components), which does create two different halves.

How to stop process from .BAT file?

To terminate a process you know the name of, try:

taskkill /IM notepad.exe

This will ask it to close, but it may refuse, offer to "save changes", etc. If you want to forcibly kill it, try:

taskkill /F /IM notepad.exe

jQuery .get error response function?

If you want a generic error you can setup all $.ajax() (which $.get() uses underneath) requests jQuery makes to display an error using $.ajaxSetup(), for example:

$.ajaxSetup({
  error: function(xhr, status, error) {
    alert("An AJAX error occured: " + status + "\nError: " + error);
  }
});

Just run this once before making any AJAX calls (no changes to your current code, just stick this before somewhere). This sets the error option to default to the handler/function above, if you made a full $.ajax() call and specified the error handler then what you had would override the above.

Round number to nearest integer

For this purpose I would suggest just do the following thing -

int(round(x))

This will give you nearest integer.

Hope this helps!!

wp_nav_menu change sub-menu class name?

Like it always is, after having looked for a long time before writing something to the site, just a minute after I posted here I found my solution.

It thought I'd share it here so someone else can find it.

//Add "parent" class to pages with subpages, change submenu class name, add depth class

    class Prio_Walker extends Walker_Nav_Menu {
    function display_element( $element, &$children_elements, $max_depth, $depth=0, $args, &$output ){
        $GLOBALS['dd_children'] = ( isset($children_elements[$element->ID]) )? 1:0;
        $GLOBALS['dd_depth'] = (int) $depth;
        parent::display_element( $element, $children_elements, $max_depth, $depth, $args, $output );
    }

     function start_lvl(&$output, $depth) {
    $indent = str_repeat("\t", $depth);
    $output .= "\n$indent<ul class=\"children level-".$depth."\">\n";
  }
}

add_filter('nav_menu_css_class','add_parent_css',10,2);
function  add_parent_css($classes, $item){
     global  $dd_depth, $dd_children;
     $classes[] = 'depth'.$dd_depth;
     if($dd_children)
         $classes[] = 'parent';
    return $classes;
}

//Add class to parent pages to show they have subpages (only for automatic wp_nav_menu)

function add_parent_class( $css_class, $page, $depth, $args )
{
   if ( ! empty( $args['has_children'] ) )
       $css_class[] = 'parent';
   return $css_class;
}
add_filter( 'page_css_class', 'add_parent_class', 10, 4 );

This is where I found the solution: Solution in WordPress support forum

correct PHP headers for pdf file download

Example 2 on w3schools shows what you are trying to achieve.

<?php
header("Content-type:application/pdf");

// It will be called downloaded.pdf
header("Content-Disposition:attachment;filename='downloaded.pdf'");

// The PDF source is in original.pdf
readfile("original.pdf");
?>

Also remember that,

It is important to notice that header() must be called before any actual output is sent (In PHP 4 and later, you can use output buffering to solve this problem)

How do I detect if I am in release or debug mode?

The simplest, and best long-term solution, is to use BuildConfig.DEBUG. This is a boolean value that will be true for a debug build, false otherwise:

if (BuildConfig.DEBUG) {
  // do something for a debug build
}

There have been reports that this value is not 100% reliable from Eclipse-based builds, though I personally have not encountered a problem, so I cannot say how much of an issue it really is.

If you are using Android Studio, or if you are using Gradle from the command line, you can add your own stuff to BuildConfig or otherwise tweak the debug and release build types to help distinguish these situations at runtime.

The solution from Illegal Argument is based on the value of the android:debuggable flag in the manifest. If that is how you wish to distinguish a "debug" build from a "release" build, then by definition, that's the best solution. However, bear in mind that going forward, the debuggable flag is really an independent concept from what Gradle/Android Studio consider a "debug" build to be. Any build type can elect to set the debuggable flag to whatever value that makes sense for that developer and for that build type.

How can I import a large (14 GB) MySQL dump file into a new MySQL database?

Simple solution is to run this query: mysql -h yourhostname -u username -p databasename < yoursqlfile.sql

And if you want to import with progress bar, try this: pv yoursqlfile.sql | mysql -uxxx -pxxxx databasename

How to force JS to do math instead of putting two strings together

You have the line

dots = document.getElementById("txt").value;

in your file, this will set dots to be a string because the contents of txt is not restricted to a number.

to convert it to an int change the line to:

dots = parseInt(document.getElementById("txt").value, 10);

Note: The 10 here specifies decimal (base-10). Without this some browsers may not interpret the string correctly. See MDN: parseInt.

What is the origin of foo and bar?

tl;dr

  • "Foo" and "bar" as metasyntactic variables were popularised by MIT and DEC, the first references are in work on LISP and PDP-1 and Project MAC from 1964 onwards.

  • Many of these people were in MIT's Tech Model Railroad Club, where we find the first documented use of "foo" in tech circles in 1959 (and a variant in 1958).

  • Both "foo" and "bar" (and even "baz") were well known in popular culture, especially from Smokey Stover and Pogo comics, which will have been read by many TMRC members.

  • Also, it seems likely the military FUBAR contributed to their popularity.


The use of lone "foo" as a nonsense word is pretty well documented in popular culture in the early 20th century, as is the military FUBAR. (Some background reading: FOLDOC FOLDOC Jargon File Jargon File Wikipedia RFC3092)


OK, so let's find some references.

STOP PRESS! After posting this answer, I discovered this perfect article about "foo" in the Friday 14th January 1938 edition of The Tech ("MIT's oldest and largest newspaper & the first newspaper published on the web"), Volume LVII. No. 57, Price Three Cents:

On Foo-ism

The Lounger thinks that this business of Foo-ism has been carried too far by its misguided proponents, and does hereby and forthwith take his stand against its abuse. It may be that there's no foo like an old foo, and we're it, but anyway, a foo and his money are some party. (Voice from the bleachers- "Don't be foo-lish!")

As an expletive, of course, "foo!" has a definite and probably irreplaceable position in our language, although we fear that the excessive use to which it is currently subjected may well result in its falling into an early (and, alas, a dark) oblivion. We say alas because proper use of the word may result in such happy incidents as the following.

It was an 8.50 Thermodynamics lecture by Professor Slater in Room 6-120. The professor, having covered the front side of the blackboard, set the handle that operates the lift mechanism, turning meanwhile to the class to continue his discussion. The front board slowly, majestically, lifted itself, revealing the board behind it, and on that board, writ large, the symbols that spelled "FOO"!

The Tech newspaper, a year earlier, the Letter to the Editor, September 1937:

By the time the train has reached the station the neophytes are so filled with the stories of the glory of Phi Omicron Omicron, usually referred to as Foo, that they are easy prey.

...

It is not that I mind having lost my first four sons to the Grand and Universal Brotherhood of Phi Omicron Omicron, but I do wish that my fifth son, my baby, should at least be warned in advance.

Hopefully yours,

Indignant Mother of Five.

And The Tech in December 1938:

General trend of thought might be best interpreted from the remarks made at the end of the ballots. One vote said, '"I don't think what I do is any of Pulver's business," while another merely added a curt "Foo."


The first documented "foo" in tech circles is probably 1959's Dictionary of the TMRC Language:

FOO: the sacred syllable (FOO MANI PADME HUM); to be spoken only when under inspiration to commune with the Deity. Our first obligation is to keep the Foo Counters turning.

These are explained at FOLDOC. The dictionary's compiler Pete Samson said in 2005:

Use of this word at TMRC antedates my coming there. A foo counter could simply have randomly flashing lights, or could be a real counter with an obscure input.

And from 1996's Jargon File 4.0.0:

Earlier versions of this lexicon derived 'baz' as a Stanford corruption of bar. However, Pete Samson (compiler of the TMRC lexicon) reports it was already current when he joined TMRC in 1958. He says "It came from "Pogo". Albert the Alligator, when vexed or outraged, would shout 'Bazz Fazz!' or 'Rowrbazzle!' The club layout was said to model the (mythical) New England counties of Rowrfolk and Bassex (Rowrbazzle mingled with (Norfolk/Suffolk/Middlesex/Essex)."

A year before the TMRC dictionary, 1958's MIT Voo Doo Gazette ("Humor suplement of the MIT Deans' office") (PDF) mentions Foocom, in "The Laws of Murphy and Finagle" by John Banzhaf (an electrical engineering student):

Further research under a joint Foocom and Anarcom grant expanded the law to be all embracing and universally applicable: If anything can go wrong, it will!

Also 1964's MIT Voo Doo (PDF) references the TMRC usage:

Yes! I want to be an instant success and snow customers. Send me a degree in: ...

  • Foo Counters

  • Foo Jung


Let's find "foo", "bar" and "foobar" published in code examples.

So, Jargon File 4.4.7 says of "foobar":

Probably originally propagated through DECsystem manuals by Digital Equipment Corporation (DEC) in 1960s and early 1970s; confirmed sightings there go back to 1972.

The first published reference I can find is from February 1964, but written in June 1963, The Programming Language LISP: its Operation and Applications by Information International, Inc., with many authors, but including Timothy P. Hart and Michael Levin:

Thus, since "FOO" is a name for itself, "COMITRIN" will treat both "FOO" and "(FOO)" in exactly the same way.

Also includes other metasyntactic variables such as: FOO CROCK GLITCH / POOT TOOR / ON YOU / SNAP CRACKLE POP / X Y Z

I expect this is much the same as this next reference of "foo" from MIT's Project MAC in January 1964's AIM-064, or LISP Exercises by Timothy P. Hart and Michael Levin:

car[((FOO . CROCK) . GLITCH)]

It shares many other metasyntactic variables like: CHI / BOSTON NEW YORK / SPINACH BUTTER STEAK / FOO CROCK GLITCH / POOT TOOP / TOOT TOOT / ISTHISATRIVIALEXCERCISE / PLOOP FLOT TOP / SNAP CRACKLE POP / ONE TWO THREE / PLANE SUB THRESHER

For both "foo" and "bar" together, the earliest reference I could find is from MIT's Project MAC in June 1966's AIM-098, or PDP-6 LISP by none other than Peter Samson:

EXPLODE, like PRIN1, inserts slashes, so (EXPLODE (QUOTE FOO/ BAR)) PRIN1's as (F O O // / B A R) or PRINC's as (F O O / B A R).


Some more recallations.

@Walter Mitty recalled on this site in 2008:

I second the jargon file regarding Foo Bar. I can trace it back at least to 1963, and PDP-1 serial number 2, which was on the second floor of Building 26 at MIT. Foo and Foo Bar were used there, and after 1964 at the PDP-6 room at project MAC.

John V. Everett recalls in 1996:

When I joined DEC in 1966, foobar was already being commonly used as a throw-away file name. I believe fubar became foobar because the PDP-6 supported six character names, although I always assumed the term migrated to DEC from MIT. There were many MIT types at DEC in those days, some of whom had worked with the 7090/7094 CTSS. Since the 709x was also a 36 bit machine, foobar may have been used as a common file name there.

Foo and bar were also commonly used as file extensions. Since the text editors of the day operated on an input file and produced an output file, it was common to edit from a .foo file to a .bar file, and back again.

It was also common to use foo to fill a buffer when editing with TECO. The text string to exactly fill one disk block was IFOO$HXA127GA$$. Almost all of the PDP-6/10 programmers I worked with used this same command string.

Daniel P. B. Smith in 1998:

Dick Gruen had a device in his dorm room, the usual assemblage of B-battery, resistors, capacitors, and NE-2 neon tubes, which he called a "foo counter." This would have been circa 1964 or so.

Robert Schuldenfrei in 1996:

The use of FOO and BAR as example variable names goes back at least to 1964 and the IBM 7070. This too may be older, but that is where I first saw it. This was in Assembler. What would be the FORTRAN integer equivalent? IFOO and IBAR?

Paul M. Wexelblat in 1992:

The earliest PDP-1 Assembler used two characters for symbols (18 bit machine) programmers always left a few words as patch space to fix problems. (Jump to patch space, do new code, jump back) That space conventionally was named FU: which stood for Fxxx Up, the place where you fixed Fxxx Ups. When spoken, it was known as FU space. Later Assemblers ( e.g. MIDAS allowed three char tags so FU became FOO, and as ALL PDP-1 programmers will tell you that was FOO space.

Bruce B. Reynolds in 1996:

On the IBM side of FOO(FU)BAR is the use of the BAR side as Base Address Register; in the middle 1970's CICS programmers had to worry out the various xxxBARs...I think one of those was FRACTBAR...

Here's a straight IBM "BAR" from 1955.


Other early references:


I haven't been able to find any references to foo bar as "inverted foo signal" as suggested in RFC3092 and elsewhere.

Here are a some of even earlier F00s but I think they're coincidences/false positives:

Simulating ENTER keypress in bash script

echo -ne '\n' | <yourfinecommandhere>

or taking advantage of the implicit newline that echo generates (thanks Marcin)

echo | <yourfinecommandhere>

Now we can simply use the --sk option:

--sk, --skip-keypress Don't wait for a keypress after each test

i.e. sudo rkhunter --sk --checkall

How does the SQL injection from the "Bobby Tables" XKCD comic work?

The '); ends the query, it doesn't start a comment. Then it drops the students table and comments the rest of the query that was supposed to be executed.

Width of input type=text element

The visible width of an element is width + padding + border + outline, so it seems that you are forgetting about the border on the input element. That is, to say, that the default border width for an input element on most (some?) browsers is actually calculated as 2px, not one. Hence your input is appearing as 2px wider. Try explicitly setting the border-width on the input, or making your div wider.

Adding a legend to PyPlot in Matplotlib in the simplest manner possible

You can access the Axes instance (ax) with plt.gca(). In this case, you can use

plt.gca().legend()

You can do this either by using the label= keyword in each of your plt.plot() calls or by assigning your labels as a tuple or list within legend, as in this working example:

import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-0.75,1,100)
y0 = np.exp(2 + 3*x - 7*x**3)
y1 = 7-4*np.sin(4*x)
plt.plot(x,y0,x,y1)
plt.gca().legend(('y0','y1'))
plt.show()

pltGcaLegend

However, if you need to access the Axes instance more that once, I do recommend saving it to the variable ax with

ax = plt.gca()

and then calling ax instead of plt.gca().

Creating a JSON dynamically with each input value using jquery

May be this will help, I'd prefer pure JS wherever possible, it improves the performance drastically as you won't have lots of JQuery function calls.

var obj = [];
var elems = $("input[class=email]");

for (i = 0; i < elems.length; i += 1) {
    var id = this.getAttribute('title');
    var email = this.value;
    tmp = {
        'title': id,
        'email': email
    };

    obj.push(tmp);
}

Use CSS3 transitions with gradient backgrounds

One work-around is to transition the background position to give the effect that the gradient is changing: http://sapphion.com/2011/10/css3-gradient-transition-with-background-position/

CSS3 gradient transition with background-position

Although you can’t directly animate gradients using the CSS transition property, it is possible to animate the background-position property to achieve a simple gradient animation:

The code for this is dead simple:

_x000D_
_x000D_
#DemoGradient{  _x000D_
    background: -webkit-linear-gradient(#C7D3DC,#5B798E);  _x000D_
    background: -moz-linear-gradient(#C7D3DC,#5B798E);  _x000D_
    background: -o-linear-gradient(#C7D3DC,#5B798E);  _x000D_
    background: linear-gradient(#C7D3DC,#5B798E);  _x000D_
  _x000D_
    -webkit-transition: background 1s ease-out;  _x000D_
    -moz-transition: background 1s ease-out;  _x000D_
    -o-transition: background 1s ease-out;  _x000D_
    transition: background 1s ease-out;  _x000D_
  _x000D_
    background-size:1px 200px;  _x000D_
    border-radius: 10px;  _x000D_
    border: 1px solid #839DB0;  _x000D_
    cursor:pointer;  _x000D_
    width: 150px;  _x000D_
    height: 100px;  _x000D_
}  _x000D_
#DemoGradient:Hover{  _x000D_
    background-position:100px;  _x000D_
}  
_x000D_
<div id="DemoGradient"></div>  
_x000D_
_x000D_
_x000D_

How can I iterate over an enum?

The typical way is as follows:

enum Foo {
  One,
  Two,
  Three,
  Last
};

for ( int fooInt = One; fooInt != Last; fooInt++ )
{
   Foo foo = static_cast<Foo>(fooInt);
   // ...
}

Please note, the enum Last is meant to be skipped by the iteration. Utilizing this "fake" Last enum, you don't have to update your terminating condition in the for loop to the last "real" enum each time you want to add a new enum. If you want to add more enums later, just add them before Last. The loop in this example will still work.

Of course, this breaks down if the enum values are specified:

enum Foo {
  One = 1,
  Two = 9,
  Three = 4,
  Last
};

This illustrates that an enum is not really meant to iterate through. The typical way to deal with an enum is to use it in a switch statement.

switch ( foo )
{
    case One:
        // ..
        break;
    case Two:  // intentional fall-through
    case Three:
        // ..
        break;
    case Four:
        // ..
        break;
     default:
        assert( ! "Invalid Foo enum value" );
        break;
}

If you really want to enumerate, stuff the enum values in a vector and iterate over that. This will properly deal with the specified enum values as well.

Laravel Mail::send() sending to multiple to or bcc addresses

I am using Laravel 5.6 and the Notifications Facade.

If I set a variable with comma separating the e-mails and try to send it, I get the error: "Address in mail given does not comply with RFC 2822, 3.6.2"

So, to solve the problem, I got the solution idea from @Toskan, coding the following.

        // Get data from Database
        $contacts = Contacts::select('email')
            ->get();

        // Create an array element
        $contactList = [];
        $i=0;

        // Fill the array element
        foreach($contacts as $contact){
            $contactList[$i] = $contact->email;
            $i++;
        }

        .
        .
        .

        \Mail::send('emails.template', ['templateTitle'=>$templateTitle, 'templateMessage'=>$templateMessage, 'templateSalutation'=>$templateSalutation, 'templateCopyright'=>$templateCopyright], function($message) use($emailReply, $nameReply, $contactList) {
                $message->from('[email protected]', 'Some Company Name')
                        ->replyTo($emailReply, $nameReply)
                        ->bcc($contactList, 'Contact List')
                        ->subject("Subject title");
            });

It worked for me to send to one or many recipients.

JQuery How to extract value from href tag?

Use this jQuery extension by James Padoley

getResourceAsStream() is always returning null

I think this way you can get the file from "anywhere" (including server locations) and you do not need to care about where to put it.

It's usually a bad practice having to care about such things.

Thread.currentThread().getContextClassLoader().getResourceAsStream("abc.properties");

How to remove Left property when position: absolute?

left: initial

This will also set left back to the browser default.

But important to know property: initial is not supported in IE.

Is it possible to write to the console in colour in .NET?

Above comments are both solid responses, however note that they aren't thread safe. If you are writing to the console with multiple threads, changing colors will add a race condition that can create some strange looking output. It is simple to fix though:

public class ConsoleWriter
{
    private static object _MessageLock= new object();

    public void WriteMessage(string message)
    {
        lock (_MessageLock)
        {
            Console.BackgroundColor = ConsoleColor.Red;
            Console.WriteLine(message);
            Console.ResetColor();
        }
    }
}

How do I remove  from the beginning of a file?

BOM is just a sequence of characters ($EF $BB $BF for UTF-8), so just remove them using scripts or configure the editor so it's not added.

From Removing BOM from UTF-8:

#!/usr/bin/perl
@file=<>;
$file[0] =~ s/^\xEF\xBB\xBF//;
print(@file);

I am sure it translates to PHP easily.

How to center a button within a div?

Updated Answer

Updating because I noticed it's an active answer, however Flexbox would be the correct approach now.

Live Demo

Vertical and horizontal alignment.

#wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
}

Just horizontal (as long as the main flex axis is horizontal which is default)

#wrapper {
  display: flex;
  justify-content: center;
}

Original Answer using a fixed width and no flexbox

If the original poster wants vertical and center alignment its quite easy for fixed width and height of the button, try the following

Live Demo

CSS

button{
    height:20px; 
    width:100px; 
    margin: -20px -50px; 
    position:relative;
    top:50%; 
    left:50%;
}

for just horizontal alignment use either

button{
    margin: 0 auto;
}

or

div{
    text-align:center;
}

Blurry text after using CSS transform: scale(); in Chrome

After trying everything else here with no luck, what finally fixed this issue for me was removing the will-change: transform; property. For some reason it caused horribly blurry looking scaling in Chrome, but not Firefox.

"break;" out of "if" statement?

I think the question is a little bit fuzzy - for example, it can be interpreted as a question about best practices in programming loops with if inside. So, I'll try to answer this question with this particular interpretation.

If you have if inside a loop, then in most cases you'd like to know how the loop has ended - was it "broken" by the if or was it ended "naturally"? So, your sample code can be modified in this way:

bool intMaxFound = false;
for (size = 0; size < HAY_MAX; size++)
{
  // wait for hay until EOF
  printf("\nhaystack[%d] = ", size);
  int straw = GetInt();
  if (straw == INT_MAX)
     {intMaxFound = true; break;}

  // add hay to stack
  haystack[size] = straw;
}
if (intMaxFound)
{
  // ... broken
}
else
{
  // ... ended naturally
}

The problem with this code is that the if statement is buried inside the loop body, and it takes some effort to locate it and understand what it does. A more clear (even without the break statement) variant will be:

bool intMaxFound = false;
for (size = 0; size < HAY_MAX && !intMaxFound; size++)
{
  // wait for hay until EOF
  printf("\nhaystack[%d] = ", size);
  int straw = GetInt();
  if (straw == INT_MAX)
     {intMaxFound = true; continue;}

  // add hay to stack
  haystack[size] = straw;
}
if (intMaxFound)
{
  // ... broken
}
else
{
  // ... ended naturally
}

In this case you can clearly see (just looking at the loop "header") that this loop can end prematurely. If the loop body is a multi-page text, written by somebody else, then you'd thank its author for saving your time.

UPDATE:

Thanks to SO - it has just suggested the already answered question about crash of the AT&T phone network in 1990. It's about a risky decision of C creators to use a single reserved word break to exit from both loops and switch.

Anyway this interpretation doesn't follow from the sample code in the original question, so I'm leaving my answer as it is.

Calculate time difference in Windows batch file

@echo off

rem Get start time:
for /F "tokens=1-4 delims=:.," %%a in ("%time%") do (
   set /A "start=(((%%a*60)+1%%b %% 100)*60+1%%c %% 100)*100+1%%d %% 100"
)

rem Any process here...

rem Get end time:
for /F "tokens=1-4 delims=:.," %%a in ("%time%") do (
   set /A "end=(((%%a*60)+1%%b %% 100)*60+1%%c %% 100)*100+1%%d %% 100"
)

rem Get elapsed time:
set /A elapsed=end-start

rem Show elapsed time:
set /A hh=elapsed/(60*60*100), rest=elapsed%%(60*60*100), mm=rest/(60*100), rest%%=60*100, ss=rest/100, cc=rest%%100
if %mm% lss 10 set mm=0%mm%
if %ss% lss 10 set ss=0%ss%
if %cc% lss 10 set cc=0%cc%
echo %hh%:%mm%:%ss%,%cc%

EDIT 2017-05-09: Shorter method added

I developed a shorter method to get the same result, so I couldn't resist to post it here. The two for commands used to separate time parts and the three if commands used to insert leading zeros in the result are replaced by two long arithmetic expressions, that could even be combined into a single longer line.

The method consists in directly convert a variable with a time in "HH:MM:SS.CC" format into the formula needed to convert the time to centiseconds, accordingly to the mapping scheme given below:

       HH        :      MM        :      SS        .       CC

(((10  HH  %%100)*60+1  MM  %%100)*60+1  SS  %%100)*100+1  CC  %%100

That is, insert (((10 at beginning, replace the colons by %%100)*60+1, replace the point by %%100)*100+1 and insert %%100 at end; finally, evaluate the resulting string as an arithmetic expression. In the time variable there are two different substrings that needs to be replaced, so the conversion must be completed in two lines. To get an elapsed time, use (endTime)-(startTime) expression and replace both time strings in the same line.

EDIT 2017/06/14: Locale independent adjustment added

EDIT 2020/06/05: Pass-over-midnight adjustment added

@echo off
setlocal EnableDelayedExpansion

set "startTime=%time: =0%"

set /P "=Any process here..."

set "endTime=%time: =0%"



rem Get elapsed time:
set "end=!endTime:%time:~8,1%=%%100)*100+1!"  &  set "start=!startTime:%time:~8,1%=%%100)*100+1!"
set /A "elap=((((10!end:%time:~2,1%=%%100)*60+1!%%100)-((((10!start:%time:~2,1%=%%100)*60+1!%%100), elap-=(elap>>31)*24*60*60*100"

rem Convert elapsed time to HH:MM:SS:CC format:
set /A "cc=elap%%100+100,elap/=100,ss=elap%%60+100,elap/=60,mm=elap%%60+100,hh=elap/60+100"

echo Start:    %startTime%
echo End:      %endTime%
echo Elapsed:  %hh:~1%%time:~2,1%%mm:~1%%time:~2,1%%ss:~1%%time:~8,1%%cc:~1%

You may review a detailed explanation of this method at this answer.

Inserting HTML elements with JavaScript

You want this

document.body.insertAdjacentHTML( 'afterbegin', '<div id="myID">...</div>' );

How can I select an element with multiple classes in jQuery?

Group Selector

body {font-size: 12px; }
body {font-family: arial, helvetica, sans-serif;}
th {font-size: 12px; font-family: arial, helvetica, sans-serif;}
td {font-size: 12px; font-family: arial, helvetica, sans-serif;}

Becomes this:

body, th, td {font-size: 12px; font-family: arial, helvetica, sans-serif;}

So in your case you have tried the group selector whereas its an intersection

$(".a, .b") 

instead use this

$(".a.b") 

Is it possible to have placeholders in strings.xml for runtime values?

Yes! you can do so without writing any Java/Kotlin code, only XML by using this small library I created, which does so at buildtime, so your app won't be affected by it: https://github.com/LikeTheSalad/android-string-reference

Usage

Your strings:

<resources>
    <string name="app_name">My App Name</string>
    <string name="template_welcome_message">Welcome to ${app_name}</string>
</resources>

The generated string after building:

<!--resolved.xml-->
<resources>
    <string name="welcome_message">Welcome to My App Name</string>
</resources>

Drop shadow on a div container?

.shadow {
    -moz-box-shadow:    3px 3px 5px 6px #ccc;
    -webkit-box-shadow: 3px 3px 5px 6px #ccc;
    box-shadow:         3px 3px 5px 6px #ccc;
}

"The import org.springframework cannot be resolved."

if you're sure that your pom.xml is pretty good, then you have just to update the poject. right click on the project - Maven - update project. or simply alt+F5.

Can there exist two main methods in a Java program?

The below code in file "Locomotive.java" will compile and run successfully, with the execution results showing

2<SPACE>

As mentioned in above post, the overload rules still work for the main method. However, the entry point is the famous psvm (public static void main(String[] args))

public class Locomotive {
    Locomotive() { main("hi");}

    public static void main(String[] args) {
        System.out.print("2 ");
    }

    public static void main(String args) {
        System.out.print("3 " + args);
    }
}

How may I reference the script tag that loaded the currently-executing script?

Since scripts are executed sequentially, the currently executed script tag is always the last script tag on the page until then. So, to get the script tag, you can do:

var scripts = document.getElementsByTagName( 'script' );
var thisScriptTag = scripts[ scripts.length - 1 ];

SQL Server returns error "Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'." in Windows application

Try setting "Integrated Security=False" in the connection string.

<add name="YourContext" connectionString="Data Source=<IPAddressOfDBServer>;Initial Catalog=<DBName>;USER ID=<youruserid>;Password=<yourpassword>;Integrated Security=False;MultipleActiveResultSets=True" providerName="System.Data.SqlClient"/>

How do I iterate through each element in an n-dimensional matrix in MATLAB?

As pointed out in a few other answers, you can iterate over all elements in a matrix A (of any dimension) using a linear index from 1 to numel(A) in a single for loop. There are also a couple of functions you can use: arrayfun and cellfun.

Let's first assume you have a function that you want to apply to each element of A (called my_func). You first create a function handle to this function:

fcn = @my_func;

If A is a matrix (of type double, single, etc.) of arbitrary dimension, you can use arrayfun to apply my_func to each element:

outArgs = arrayfun(fcn, A);

If A is a cell array of arbitrary dimension, you can use cellfun to apply my_func to each cell:

outArgs = cellfun(fcn, A);

The function my_func has to accept A as an input. If there are any outputs from my_func, these are placed in outArgs, which will be the same size/dimension as A.

One caveat on outputs... if my_func returns outputs of different sizes and types when it operates on different elements of A, then outArgs will have to be made into a cell array. This is done by calling either arrayfun or cellfun with an additional parameter/value pair:

outArgs = arrayfun(fcn, A, 'UniformOutput', false);
outArgs = cellfun(fcn, A, 'UniformOutput', false);

#1055 - Expression of SELECT list is not in GROUP BY clause and contains nonaggregated column this is incompatible with sql_mode=only_full_group_by

So let's fully understand, Let's say you have a query which works in localhost but does not in production mode, This is because in MySQL 5.7 and above they decided to activate the sql_mode=only_full_group_by by default, basically it is a strict mode which prevents you to select non aggregated fields.

Here's the query (works in local but not in production mode) :

SELECT post.*, YEAR(created_at) as year
FROM post
GROUP BY year

SELECT post.id, YEAR(created_at) as year  // This will generate an error since there are many ids
FROM post
GROUP BY year

To verify if the sql_mode=only_full_group_by is activated for, you should execute the following query :

SELECT @@sql_mode;   //localhost

Output : IGNORE_SPACE, STRICT_TRANS, ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION (If you don't see it, it means it is deactivated)

But if try in production mode, or somewhere where it gives you the error it should be activated:

SELECT @@sql_mode;   //production

Output: ONLY_FULL_GROUP_BY, STRICT_TRANS_TABLES, NO_ZERO_IN_DATE, NO_ZERO... And it's ONLY_FULL_GROUP_BY we're looking for here.

Otherwise, if you are using phpMyAdmin then go to -> Variables and search for sql_mode

Let's take our previous example and adapt it to it :

SELECT MIN(post.id), YEAR(created_at) as year  //Here we are solving the problem with MIN()
FROM post
GROUP BY year

And the same for MAX()

And if we want all the IDs, we're going to need:

SELECT GROUP_CONCAT(post.id SEPARATOR ','), YEAR(created_at) as year
FROM post
GROUP BY year

or another newly added function:

SELECT ANY_VALUE(post.id), YEAR(created_at) as year 
FROM post
GROUP BY year

?? ANY_VALUE does not exist for MariaDB

And If you want all the fields, then you could use the same:

SELECT ANY_VALUE(post.id), ANY_VALUE(post.slug), ANY_VALUE(post.content) YEAR(created_at) as year 
FROM post
GROUP BY year

? To deactivate the sql_mode=only_full_group_by then you'll need to execute this query:

SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode, 'ONLY_FULL_GROUP_BY', ''));

Sorry for the novel, hope it helps.

Passing a URL with brackets to curl

I was getting this error though there were no (obvious) brackets in my URL, and in my situation the --globoff command will not solve the issue.

For example (doing this on on mac in iTerm2):

for endpoint in $(grep some_string output.txt); do curl "http://1.2.3.4/api/v1/${endpoint}" ; done

I have grep aliased to "grep --color=always". As a result, the above command will result in this error, with some_string highlighted in whatever colour you have grep set to:

curl: (3) bad range in URL position 31:
http://1.2.3.4/api/v1/lalalasome_stringlalala

The terminal was transparently translating the [colour\codes]some_string[colour\codes] into the expected no-special-characters URL when viewed in terminal, but behind the scenes the colour codes were being sent in the URL passed to curl, resulting in brackets in your URL.

Solution is to not use match highlighting.

How should I copy Strings in Java?

Strings are immutable objects so you can copy them just coping the reference to them, because the object referenced can't change ...

So you can copy as in your first example without any problem :

String s = "hello";
String backup_of_s = s;
s = "bye";

offsetting an html anchor to adjust for fixed header

@AlexanderSavin's solution works great in WebKit browsers for me.

I additionally had to use :target pseudo-class which applies style to the selected anchor to adjust padding in FF, Opera & IE9:

a:target {
  padding-top: 40px
}

Note that this style is not for Chrome / Safari so you'll probably have to use css-hacks, conditional comments etc.

Also I'd like to notice that Alexander's solution works due to the fact that targeted element is inline. If you don't want link you could simply change display property:

<div id="myanchor" style="display: inline">
   <h1 style="padding-top: 40px; margin-top: -40px;">My anchor</h1>
</div>

Virtual Serial Port for Linux

You may want to look at Tibbo VSPDL for creating a linux virtual serial port using a Kernel driver -- it seems pretty new, and is available for download right now (beta version). Not sure about the license at this point, or whether they want to make it available commercially only in the future.

There are other commercial alternatives, such as http://www.ttyredirector.com/.

In Open Source, Remserial (GPL) may also do what you want, using Unix PTY's. It transmits the serial data in "raw form" to a network socket; STTY-like setup of terminal parameters must be done when creating the port, changing them later like described in RFC 2217 does not seem to be supported. You should be able to run two remserial instances to create a virtual nullmodem like com0com, except that you'll need to set up port speed etc in advance.

Socat (also GPL) is like an extended variant of Remserial with many many more options, including a "PTY" method for redirecting the PTY to something else, which can be another instance of Socat. For Unit tets, socat is likely nicer than remserial because you can directly cat files into the PTY. See the PTY example on the manpage. A patch exists under "contrib" to provide RFC2217 support for negotiating serial line settings.

Simple linked list in C++

This is the most simple example I can think of in this case and is not tested. Please consider that this uses some bad practices and does not go the way you normally would go with C++ (initialize lists, separation of declaration and definition, and so on). But that are topics I can't cover here.

#include <iostream>
using namespace std;

class LinkedList{
    // Struct inside the class LinkedList
    // This is one node which is not needed by the caller. It is just
    // for internal work.
    struct Node {
        int x;
        Node *next;
    };

// public member
public:
    // constructor
    LinkedList(){
        head = NULL; // set head to NULL
    }

    // destructor
    ~LinkedList(){
        Node *next = head;
        
        while(next) {              // iterate over all elements
            Node *deleteMe = next;
            next = next->next;     // save pointer to the next element
            delete deleteMe;       // delete the current entry
        }
    }
    
    // This prepends a new value at the beginning of the list
    void addValue(int val){
        Node *n = new Node();   // create new Node
        n->x = val;             // set value
        n->next = head;         // make the node point to the next node.
                                //  If the list is empty, this is NULL, so the end of the list --> OK
        head = n;               // last but not least, make the head point at the new node.
    }

    // returns the first element in the list and deletes the Node.
    // caution, no error-checking here!
    int popValue(){
        Node *n = head;
        int ret = n->x;

        head = head->next;
        delete n;
        return ret;
    }

// private member
private:
    Node *head; // this is the private member variable. It is just a pointer to the first Node
};

int main() {
    LinkedList list;

    list.addValue(5);
    list.addValue(10);
    list.addValue(20);

    cout << list.popValue() << endl;
    cout << list.popValue() << endl;
    cout << list.popValue() << endl;
    // because there is no error checking in popValue(), the following
    // is undefined behavior. Probably the program will crash, because
    // there are no more values in the list.
    // cout << list.popValue() << endl;
    return 0;
}

I would strongly suggest you to read a little bit about C++ and Object oriented programming. A good starting point could be this: http://www.galileocomputing.de/1278?GPP=opoo

EDIT: added a pop function and some output. As you can see the program pushes 3 values 5, 10, 20 and afterwards pops them. The order is reversed afterwards because this list works in stack mode (LIFO, Last in First out)

EditText request focus

Yes, I got the answer.. just simply edit the manifest file as:

        <activity android:name=".MainActivity"
        android:label="@string/app_name"
        android:windowSoftInputMode="stateAlwaysVisible" />

and set EditText.requestFocus() in onCreate()..

Thanks..

MySQL Trigger: Delete From Table AFTER DELETE

I think there is an error in the trigger code. As you want to delete all rows with the deleted patron ID, you have to use old.id (Otherwise it would delete other IDs)

Try this as the new trigger:

CREATE TRIGGER log_patron_delete AFTER DELETE on patrons
FOR EACH ROW
BEGIN
DELETE FROM patron_info
    WHERE patron_info.pid = old.id;
END

Dont forget the ";" on the delete query. Also if you are entering the TRIGGER code in the console window, make use of the delimiters also.

Change background colour for Visual Studio

This is the only one right answer on this whole page as people answered about "Visual Studio", not "Visual Studio Code":

To change color theme in "Visual Studio Code", use:

File -> Preferences -> Color Theme -> select any color theme you like

You can also download other custom themes as extensions. To do that, open extensions tab on sidebar and type "theme" into the search field to filter extensions only to themes related ones. Click any you like, click "download" and then "install". After installation and restarting VSC, you can find newly installed themes next to default themes in the same place:

File -> Preferences -> Color Theme -> select newly downloaded color theme

PS - Microsoft made bad naming decision by calling this new editor Visual Studio Code, it's terrible how many wrong links we have in google and stackoverflow. They should rename it to VSCode or something.

How can I get the value of a registry key from within a batch script?

Thanks, i just need to use:

SETLOCAL EnableExtensions

And put a:

2^>nul

Into the REG QUERY called in the FOR command. Thanks a lot again! :)

Problems with jQuery getJSON using local files in Chrome

This is a known issue with Chrome.

Here's the link in the bug tracker:

Issue 40787: Local files doesn't load with Ajax

Tokenizing strings in C

Here's an example of strtok usage, keep in mind that strtok is destructive of its input string (and therefore can't ever be used on a string constant

char *p = strtok(str, " ");
while(p != NULL) {
    printf("%s\n", p);
    p = strtok(NULL, " ");
}

Basically the thing to note is that passing a NULL as the first parameter to strtok tells it to get the next token from the string it was previously tokenizing.

Drop Down Menu/Text Field in one

Option 1

Include the script from dhtmlgoodies and initialize like this:

<input type="text" name="myText" value="Norway"
       selectBoxOptions="Canada;Denmark;Finland;Germany;Mexico"> 
createEditableSelect(document.forms[0].myText);

Option 2

Here's a custom solution which combines a <select> element and <input> element, styles them, and toggles back and forth via JavaScript

<div style="position:relative;width:200px;height:25px;border:0;padding:0;margin:0;">
  <select style="position:absolute;top:0px;left:0px;width:200px; height:25px;line-height:20px;margin:0;padding:0;"
          onchange="document.getElementById('displayValue').value=this.options[this.selectedIndex].text; document.getElementById('idValue').value=this.options[this.selectedIndex].value;">
    <option></option>
    <option value="one">one</option>
    <option value="two">two</option>
    <option value="three">three</option>
  </select>
  <input type="text" name="displayValue" id="displayValue" 
         placeholder="add/select a value" onfocus="this.select()"
         style="position:absolute;top:0px;left:0px;width:183px;width:180px\9;#width:180px;height:23px; height:21px\9;#height:18px;border:1px solid #556;"  >
  <input name="idValue" id="idValue" type="hidden">
</div>

post ajax data to PHP and return data

So what does count_votes look like? Is it a script? Anything that you want to get back from an ajax call can be retrieved using a simple echo (of course you could use JSON or xml, but for this simple example you would just need to output something in count_votes.php like:

$id = $_POST['id'];

function getVotes($id){
    // call your database here
    $query = ("SELECT votes FROM poll WHERE ID = $id");
    $result = @mysql_query($query);
    $row = mysql_fetch_row($result);

    return $row->votes;
}
$votes = getVotes($id);
echo $votes;

This is just pseudocode, but should give you the idea. What ever you echo from count_votes will be what is returned to "data" in your ajax call.

How to send a header using a HTTP request through a curl call?

GET (multiple parameters):

curl -X  GET "http://localhost:3000/action?result1=gh&result2=ghk"

or

curl --request  GET "http://localhost:3000/action?result1=gh&result2=ghk"

or

curl  "http://localhost:3000/action?result1=gh&result2=ghk"

or

curl -i -H "Application/json" -H "Content-type: application/json"  "http://localhost:3000/action?result1=gh&result2=ghk"

What is the advantage of using heredoc in PHP?

Some IDEs highlight the code in heredoc strings automatically - which makes using heredoc for XML or HTML visually appealing.

I personally like it for longer parts of i.e. XML since I don't have to care about quoting quote characters and can simply paste the XML.

Detecting the character encoding of an HTTP POST request

The Charset used in the POST will match that of the Charset specified in the HTML hosting the form. Hence if your form is sent using UTF-8 encoding that is the encoding used for the posted content. The URL encoding is applied after the values are converted to the set of octets for the character encoding.

addEventListener for keydown on Canvas

Sometimes just setting canvas's tabindex to '1' (or '0') works. But sometimes - it doesn't, for some strange reason.

In my case (ReactJS app, dynamic canvas el creation and mount) I need to call canvasEl.focus() to fix it. Maybe this is somehow related to React (my old app based on KnockoutJS works without '..focus()' )

Custom method names in ASP.NET Web API

Web APi 2 and later versions support a new type of routing, called attribute routing. As the name implies, attribute routing uses attributes to define routes. Attribute routing gives you more control over the URIs in your web API. For example, you can easily create URIs that describe hierarchies of resources.

For example:

[Route("customers/{customerId}/orders")]
public IEnumerable<Order> GetOrdersByCustomer(int customerId) { ... }

Will perfect and you don't need any extra code for example in WebApiConfig.cs. Just you have to be sure web api routing is enabled or not in WebApiConfig.cs , if not you can activate like below:

        // Web API routes
        config.MapHttpAttributeRoutes();

You don't have to do something more or change something in WebApiConfig.cs. For more details you can have a look this article.

How can you determine a point is between two other points on a line segment?

You can do it by solving the line equation for that line segment with the point coordinates you will know whether that point is on the line and then checking the bounds of the segment to know whether it is inside or outside of it. You can apply some threshold because well it is somewhere in space mostl likely defined by a floating point value and you must not hit the exact one. Example in php

function getLineDefinition($p1=array(0,0), $p2=array(0,0)){
    
    $k = ($p1[1]-$p2[1])/($p1[0]-$p2[0]);
    $q = $p1[1]-$k*$p1[0];
    
    return array($k, $q);
    
}

function isPointOnLineSegment($line=array(array(0,0),array(0,0)), $pt=array(0,0)){
    
    // GET THE LINE DEFINITION y = k.x + q AS array(k, q) 
    $def = getLineDefinition($line[0], $line[1]);
    
    // use the line definition to find y for the x of your point
    $y = $def[0]*$pt[0]+$def[1];

    $yMin = min($line[0][1], $line[1][1]);
    $yMax = max($line[0][1], $line[1][1]);

    // exclude y values that are outside this segments bounds
    if($y>$yMax || $y<$yMin) return false;
    
    // calculate the difference of your points y value from the reference value calculated from lines definition 
    // in ideal cases this would equal 0 but we are dealing with floating point values so we need some threshold value not to lose results
    // this is up to you to fine tune
    $diff = abs($pt[1]-$y);
    
    $thr = 0.000001;
    
    return $diff<=$thr;
    
}

How to save picture to iPhone photo library?

Swift 4

func writeImage(image: UIImage) {
    UIImageWriteToSavedPhotosAlbum(image, self, #selector(self.finishWriteImage), nil)
}

@objc private func finishWriteImage(_ image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: UnsafeRawPointer) {
    if (error != nil) {
        // Something wrong happened.
        print("error occurred: \(String(describing: error))")
    } else {
        // Everything is alright.
        print("saved success!")
    }
}

How do I make JavaScript beep?

Note:put this code in your javascript at the point you want the beep to occur. and remember to specify the directory or folder where the beep sound is stored(source).

<script>
//Appending HTML5 Audio Tag in HTML Body
$('<audio id="chatAudio"><source src="sound/notify.ogg" type="audio/ogg"><source src="sound/notify.mp3" type="audio/mpeg"><source src="sound/notify.wav" type="audio/wav"></audio>').appendTo('body');

$('#chatAudio')[0].play();
</script>

Reference:http://www.9lessons.info/2013/04/play-notification-sound-using-jquery.html.

I implemented this in a social media i am developing and it works find, a notification like that of facebook when chatting, notifying you that you have a new chat message

Maven:Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:2.7:resources

I had this issue too because I was filtering /src/main/resources and forgot I had added a keystore (*.jks) binary to this directory.

Add a "resource" block with exclusions for binary files and your problem may be resolved.

<build>
  <finalName>somename</finalName>
  <testResources>
    <testResource>
      <directory>src/test/resources</directory>
      <filtering>false</filtering>
    </testResource>
  </testResources>
  <resources>
    <resource>
      <directory>src/main/resources</directory>
      <filtering>true</filtering>
      <excludes>
        <exclude>*.jks</exclude>
        <exclude>*.png</exclude>
      </excludes>        
    </resource>
  </resources>
...

AngularJs ReferenceError: angular is not defined

Always make sure that js file (angular.min.js) is referenced first in the HTML file. For example:

----------------- This reference will THROW error -------------------------

< script src="otherXYZ.js"></script>
< script src="angular.min.js"></script>

----------------- This reference will WORK as expected -------------------

< script src="angular.min.js"></script>
< script src="otherXYZ.js"></script>

How to define optional methods in Swift protocol?

Slightly off topic from the original question, but it builds off Antoine’s idea and I thought it might help someone.

You can also make computed properties optional for structs with protocol extensions.

You can make a property on the protocol optional

protocol SomeProtocol {
    var required: String { get }
    var optional: String? { get }
}

Implement the dummy computed property in the protocol extension

extension SomeProtocol {
    var optional: String? { return nil }
}

And now you can use structs that do or don’t have the optional property implemented

struct ConformsWithoutOptional {
    let required: String
}

struct ConformsWithOptional {
    let required: String
    let optional: String?
}

I’ve also written up how to do optional properties in Swift protocols on my blog, which I’ll keep updated in case things change through the Swift 2 releases.

How to enable MySQL Query Log?

First, Remember that this logfile can grow very large on a busy server.

For mysql < 5.1.29:

To enable the query log, put this in /etc/my.cnf in the [mysqld] section

log   = /path/to/query.log  #works for mysql < 5.1.29

Also, to enable it from MySQL console

SET general_log = 1;

See http://dev.mysql.com/doc/refman/5.1/en/query-log.html

For mysql 5.1.29+

With mysql 5.1.29+ , the log option is deprecated. To specify the logfile and enable logging, use this in my.cnf in the [mysqld] section:

general_log_file = /path/to/query.log
general_log      = 1

Alternately, to turn on logging from MySQL console (must also specify log file location somehow, or find the default location):

SET global general_log = 1;

Also note that there are additional options to log only slow queries, or those which do not use indexes.

Implementing autocomplete

I think you can use typeahead.js. There are typescript definitions for it. so it'll be easy to use it i guess if you are using typescript for development.

Adding default parameter value with type hint in Python

Your second way is correct.

def foo(opts: dict = {}):
    pass

print(foo.__annotations__)

this outputs

{'opts': <class 'dict'>}

It's true that's it's not listed in PEP 484, but type hints are an application of function annotations, which are documented in PEP 3107. The syntax section makes it clear that keyword arguments works with function annotations in this way.

I strongly advise against using mutable keyword arguments. More information here.

jQuery .attr("disabled", "disabled") not working in Chrome

if you are removing all disabled attributes from input, then why not just do:

$("input").removeAttr('disabled');

Then after ajax success:

$("input[type='text']").attr('disabled', true);

Make sure you use remove the disabled attribute before submit, or it won't submit that data. If you need to submit it before changing, you need to use readonly instead.

How to show the "Are you sure you want to navigate away from this page?" when changes committed?

Based on all the answers on this thread, I wrote the following code and it worked for me.

If you have only some input/textarea tags which requires an onunload event to be checked, you can assign HTML5 data-attributes as data-onunload="true"

for eg.

<input type="text" data-onunload="true" />
<textarea data-onunload="true"></textarea>

and the Javascript (jQuery) can look like this :

$(document).ready(function(){
    window.onbeforeunload = function(e) {
        var returnFlag = false;
        $('textarea, input').each(function(){
            if($(this).attr('data-onunload') == 'true' && $(this).val() != '')
                returnFlag = true;
        });

        if(returnFlag)
            return "Sure you want to leave?";   
    };
});

how to fix EXE4J_JAVA_HOME, No JVM could be found on your system error?

Leave you stuff there and Try the following as well:

Start > Right-click on My computer > Properties > Advanced system settings > Environment Variables > look for variable name called "Path" in the lower box

set path value value as: (you can just add it to the starting of line, don't forgot semi column in between )

c:\Program Files\java\jre7\bin

WebDriver - wait for element using Java

We're having a lot of race conditions with elementToBeClickable. See https://github.com/angular/protractor/issues/2313. Something along these lines worked reasonably well even if a little brute force

Awaitility.await()
        .atMost(timeout)
        .ignoreException(NoSuchElementException.class)
        .ignoreExceptionsMatching(
            Matchers.allOf(
                Matchers.instanceOf(WebDriverException.class),
                Matchers.hasProperty(
                    "message",
                    Matchers.containsString("is not clickable at point")
                )
            )
        ).until(
            () -> {
                this.driver.findElement(locator).click();
                return true;
            },
            Matchers.is(true)
        );

IN-clause in HQL or Java Persistence Query Language

Using pure JPA with Hibernate 5.0.2.Final as the actual provider the following seems to work with positional parameters as well:

Entity.java:

@Entity
@NamedQueries({
    @NamedQuery(name = "byAttributes", query = "select e from Entity e where e.attribute in (?1)") })
public class Entity {
    @Column(name = "attribute")
    private String attribute;
}

Dao.java:

public class Dao {
    public List<Entity> findByAttributes(Set<String> attributes) {
        Query query = em.createNamedQuery("byAttributes");
        query.setParameter(1, attributes);

        List<Entity> entities = query.getResultList();
        return entities;
    }
}

jquery, selector for class within id

Also $( "#container" ).find( "div.robotarm" );
is equal to: $( "div.robotarm", "#container" )