Programs & Examples On #Zombie process

On Unix and Unix-like computer operating systems, a zombie process or defunct process is a process that has completed execution but still has an entry in the process table. This entry is still needed to allow the process that started the (now zombie) process to read its exit status.

How to kill zombie process

Sometimes the parent ppid cannot be killed, hence kill the zombie pid

kill -9 $(ps -A -ostat,pid | awk '/[zZ]/{ print $2 }')

Error: org.testng.TestNGException: Cannot find class in classpath: EmpClass

I faced the similar issue on importing maven with testng project. This was solved by converting again into TestNg project by

right click on eclipse project > TestNG > Convert to TestNG

and replacing the existing testng.xml file with the newly created. Clean and update the maven project with mvn install

Note: take backup of your testng.xml

What is the meaning of Bus: error 10 in C

str2 is pointing to a statically allocated constant character array. You can't write to it/over it. You need to dynamically allocate space via the *alloc family of functions.

How to change permissions for a folder and its subfolders/files in one step?

You can use -R with chmod for recursive traversal of all files and subfolders.

You might need sudo as it depends on LAMP being installed by the current user or another one:

sudo chmod -R 755 /opt/lampp/htdocs

Laravel Eloquent groupBy() AND also return count of each group

This is working for me:

$user_info = DB::table('usermetas')
                 ->select('browser', DB::raw('count(*) as total'))
                 ->groupBy('browser')
                 ->get();

What is the difference between null=True and blank=True in Django?

You may have your answer however till this day it's difficult to judge whether to put null=True or blank=True or both to a field. I personally think it's pretty useless and confusing to provide so many options to developers. Let the handle the nulls or blanks however they want.

I follow this table, from Two Scoops of Django: enter image description here

Table showing when to use null or blank for each field type

PostgreSQL - max number of parameters in "IN" clause?

Just tried it. the answer is -> out-of-range integer as a 2-byte value: 32768

Why is the default value of the string type null instead of an empty string?

Since you mentioned ToUpper(), and this usage is how I found this thread, I will share this shortcut (string ?? "").ToUpper():

    private string _city;
    public string City
    {
        get
        {
            return (this._city ?? "").ToUpper();
        }
        set
        {
            this._city = value;
        }
    }

Seems better than:

        if(null != this._city)
        { this._city = this._city.ToUpper(); }

What is the difference between i = i + 1 and i += 1 in a 'for' loop?

In the first example, you are reassigning the variable a, while in the second one you are modifying the data in-place, using the += operator.

See the section about 7.2.1. Augmented assignment statements :

An augmented assignment expression like x += 1 can be rewritten as x = x + 1 to achieve a similar, but not exactly equal effect. In the augmented version, x is only evaluated once. Also, when possible, the actual operation is performed in-place, meaning that rather than creating a new object and assigning that to the target, the old object is modified instead.

+= operator calls __iadd__. This function makes the change in-place, and only after its execution, the result is set back to the object you are "applying" the += on.

__add__ on the other hand takes the parameters and returns their sum (without modifying them).

How to save a data frame as CSV to a user selected location using tcltk

You need not to use even the package "tcltk". You can simply do as shown below:

write.csv(x, file = "c:\\myname\\yourfile.csv", row.names = FALSE)

Give your path inspite of "c:\myname\yourfile.csv".

No provider for Http StaticInjectorError

In order to use Http in your app you will need to add the HttpModule to your app.module.ts:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule, ErrorHandler } from '@angular/core';
import { HttpModule } from '@angular/http';
...
  imports: [
    BrowserModule,
    HttpModule,
    IonicModule.forRoot(MyApp),
    IonicStorageModule.forRoot()
  ]

EDIT

As mentioned in the comment below, HttpModule is deprecated now, use import { HttpClientModule } from '@angular/common/http'; Make sure HttpClientModule in your imports:[] array

Tricks to manage the available memory in an R session

This is a newer answer to this excellent old question. From Hadley's Advanced R:

install.packages("pryr")

library(pryr)

object_size(1:10)
## 88 B

object_size(mean)
## 832 B

object_size(mtcars)
## 6.74 kB

(http://adv-r.had.co.nz/memory.html)

Python - Extracting and Saving Video Frames

This function extracts images from video with 1 fps, IN ADDITION it identifies the last frame and stops reading also:

import cv2
import numpy as np

def extract_image_one_fps(video_source_path):

    vidcap = cv2.VideoCapture(video_source_path)
    count = 0
    success = True
    while success:
      vidcap.set(cv2.CAP_PROP_POS_MSEC,(count*1000))      
      success,image = vidcap.read()

      ## Stop when last frame is identified
      image_last = cv2.imread("frame{}.png".format(count-1))
      if np.array_equal(image,image_last):
          break

      cv2.imwrite("frame%d.png" % count, image)     # save frame as PNG file
      print '{}.sec reading a new frame: {} '.format(count,success)
      count += 1

How to append output to the end of a text file

I would use printf instead of echo because it's more reliable and processes formatting such as new line \n properly.

This example produces an output similar to echo in previous examples:

printf "hello world"  >> read.txt   
cat read.txt
hello world

However if you were to replace printf with echo in this example, echo would treat \n as a string, thus ignoring the intent

printf "hello\nworld"  >> read.txt   
cat read.txt
hello
world

What is the cleanest way to get the progress of JQuery ajax request?

Something like this for $.ajax (HTML5 only though):

$.ajax({
    xhr: function() {
        var xhr = new window.XMLHttpRequest();
        xhr.upload.addEventListener("progress", function(evt) {
            if (evt.lengthComputable) {
                var percentComplete = evt.loaded / evt.total;
                //Do something with upload progress here
            }
       }, false);

       xhr.addEventListener("progress", function(evt) {
           if (evt.lengthComputable) {
               var percentComplete = evt.loaded / evt.total;
               //Do something with download progress
           }
       }, false);

       return xhr;
    },
    type: 'POST',
    url: "/",
    data: {},
    success: function(data){
        //Do something on success
    }
});

C++ Matrix Class

you could do it with a template, if the matrix size is known at compile-time :

template <int width, int height>
class Matrix{
    double data[height][width];
    //...member functions
};

Why does Date.parse give incorrect results?

Another solution is to build an associative array with date format and then reformat data.

This method is useful for date formatted in an unussual way.

An example:

    mydate='01.02.12 10:20:43':
    myformat='dd/mm/yy HH:MM:ss';


    dtsplit=mydate.split(/[\/ .:]/);
    dfsplit=myformat.split(/[\/ .:]/);

    // creates assoc array for date
    df = new Array();
    for(dc=0;dc<6;dc++) {
            df[dfsplit[dc]]=dtsplit[dc];
            }

    // uses assc array for standard mysql format
    dstring[r] = '20'+df['yy']+'-'+df['mm']+'-'+df['dd'];
    dstring[r] += ' '+df['HH']+':'+df['MM']+':'+df['ss'];

System.Net.Http: missing from namespace? (using .net 4.5)

Make sure it's referenced in your web.config:

Python: finding an element in a list

assuming you want to find a value in a numpy array, I guess something like this might work:

Numpy.where(arr=="value")[0]

PDOException “could not find driver”

$DB_TYPE = 'mysql'; //Type of database<br>
$DB_HOST = 'localhost'; //Host name<br>
$DB_USER = 'root'; //Host Username<br>
$DB_PASS = ''; //Host Password<br>
$DB_NAME = 'database_name'; //Database name<br><br>

$dbh = new PDO("$DB_TYPE:host=$DB_HOST; dbname=$DB_NAME;", $DB_USER, $DB_PASS); // PDO Connection

This worked for me.

Replace text inside td using jQuery having td containing other elements

How about:

function changeText() {
    $("#demoTable td").each(function () {
       $(this).html().replace("8: Tap on APN and Enter <B>www</B>", "");
    }
}

javascript, for loop defines a dynamic variable name

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

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

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

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

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

window['myVarName'] = 'namingCollisionsAreFun';  

(per comment)

HTML5 tag for horizontal line break

Simply use hr tag in HTML file and add below code in CSS file .

    hr {
       display: block;
       position: relative;
       padding: 0;
       margin: 8px auto;
       height: 0;
       width: 100%;
       max-height: 0;
       font-size: 1px;
       line-height: 0;
       clear: both;
       border: none;
       border-top: 1px solid #aaaaaa;
       border-bottom: 1px solid #ffffff;
    }

it works perfectly .

How to move an element into another element?

I just used:

$('#source').prependTo('#destination');

Which I grabbed from here.

HttpClient does not exist in .net 4.0: what can I do?

I've used HttpClient in .NET 4.0 applications on numerous occasions. If you are familiar with NuGet, you can do an Install-Package Microsoft.Net.Http to add it to your project. See the link below for further details.

http://nuget.org/packages/Microsoft.Net.Http

Writing string to a file on a new line every time

Another solution that writes from a list using fstring

lines = ['hello','world']
with open('filename.txt', "w") as fhandle:
  for line in lines:
    fhandle.write(f'{line}\n')

And as a function

def write_list(fname, lines):
    with open(fname, "w") as fhandle:
      for line in lines:
        fhandle.write(f'{line}\n')

write_list('filename.txt', ['hello','world'])

Get Android shared preferences value in activity/normal class

If you have a SharedPreferenceActivity by which you have saved your values

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String imgSett = prefs.getString(keyChannel, "");

if the value is saved in a SharedPreference in an Activity then this is the correct way to saving it.

SharedPreferences shared = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = shared.edit();
editor.putString(keyChannel, email);
editor.commit();// commit is important here.

and this is how you can retrieve the values.

SharedPreferences shared = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
String channel = (shared.getString(keyChannel, ""));

Also be aware that you can do so in a non-Activity class too but the only condition is that you need to pass the context of the Activity. use this context in to get the SharedPreferences.

mContext.getSharedPreferences(PREF_NAME, MODE_PRIVATE);

Find the min/max element of an array in JavaScript

Aside using the math function max and min, another function to use is the built in function of sort(): here we go

const nums = [12, 67, 58, 30].sort((x, y) => 
x -  y)
let min_val = nums[0]
let max_val = nums[nums.length -1]

What is the difference between $routeProvider and $stateProvider?

$route: This is used for deep-linking URLs to controllers and views (HTML partials) and watches $location.url() in order to map the path from an existing definition of route.

When we use ngRoute, the route is configured with $routeProvider and when we use ui-router, the route is configured with $stateProvider and $urlRouterProvider.

<div ng-view></div>
    $routeProvider
        .when('/contact/', {
            templateUrl: 'app/views/core/contact/contact.html',
            controller: 'ContactCtrl'
        });


<div ui-view>
    <div ui-view='abc'></div>
    <div ui-view='abc'></div>
   </div>
    $stateProvider
        .state("contact", {
            url: "/contact/",
            templateUrl: '/app/Aisel/Contact/views/contact.html',
            controller: 'ContactCtrl'
        });

Replace preg_replace() e modifier with preg_replace_callback

You shouldn't use flag e (or eval in general).

You can also use T-Regx library

pattern('(^|_)([a-z])')->replace($word)->by()->group(2)->callback('strtoupper');

Attempt by security transparent method 'WebMatrix.WebData.PreApplicationStartCode.Start()'

Reinstalling Microsoft.AspNet.WebHelpers works for me

Update-Package –reinstall Microsoft.AspNet.WebHelpers

React setState not updating state

Using async/await

async changeHandler(event) {
    await this.setState({ yourName: event.target.value });
    console.log(this.state.yourName);
}

How to get data from database in javascript based on the value passed to the function

The error is coming as your query is getting formed as

SELECT * FROM Employ where number = parseInt(val);

I dont know which DB you are using but no DB will understand parseInt.

What you can do is use a variable say temp and store the value of parseInt(val) in temp variable and make the query as

SELECT * FROM Employ where number = temp;

how to create 100% vertical line in css

I've used min-height: 100vh; with great success on some of my projects. See example.

Using Mysql WHERE IN clause in codeigniter

$data = $this->db->get_where('columnname',array('code' => 'B'));
$this->db->where_in('columnname',$data);
$this->db->where('code !=','B');
$query =  $this->db->get();
return $query->result_array();

Printing pointers in C

"s" is not a "char*", it's a "char[4]". And so, "&s" is not a "char**", but actually "a pointer to an array of 4 characater". Your compiler may treat "&s" as if you had written "&s[0]", which is roughly the same thing, but is a "char*".

When you write "char** p = &s;" you are trying to say "I want p to be set to the address of the thing which currently points to "asd". But currently there is nothing which points to "asd". There is just an array which holds "asd";

char s[] = "asd";
char *p = &s[0];  // alternately you could use the shorthand char*p = s;
char **pp = &p;

node and Error: EMFILE, too many open files

Using the graceful-fs module by Isaac Schlueter (node.js maintainer) is probably the most appropriate solution. It does incremental back-off if EMFILE is encountered. It can be used as a drop-in replacement for the built-in fs module.

Comparing arrays for equality in C++

Array is not a primitive type, and the arrays belong to different addresses in the C++ memory.

How to get date, month, year in jQuery UI datepicker?

what about that simple way)

$(document).ready ->
 $('#datepicker').datepicker( dateFormat: 'yy-mm-dd',  onSelect: (dateStr) ->
    alert dateStr # yy-mm-dd
    #OR
    alert $("#datepicker").val(); # yy-mm-dd

What is the correct way of reading from a TCP socket in C/C++?

For any non-trivial application (I.E. the application must receive and handle different kinds of messages with different lengths), the solution to your particular problem isn't necessarily just a programming solution - it's a convention, I.E. a protocol.

In order to determine how many bytes you should pass to your read call, you should establish a common prefix, or header, that your application receives. That way, when a socket first has reads available, you can make decisions about what to expect.

A binary example might look like this:

#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <arpa/inet.h>

enum MessageType {
    MESSAGE_FOO,
    MESSAGE_BAR,
};

struct MessageHeader {
    uint32_t type;
    uint32_t length;
};

/**
 * Attempts to continue reading a `socket` until `bytes` number
 * of bytes are read. Returns truthy on success, falsy on failure.
 *
 * Similar to @grieve's ReadXBytes.
 */
int readExpected(int socket, void *destination, size_t bytes)
{
    /*
    * Can't increment a void pointer, as incrementing
    * is done by the width of the pointed-to type -
    * and void doesn't have a width
    *
    * You can in GCC but it's not very portable
    */
    char *destinationBytes = destination;
    while (bytes) {
        ssize_t readBytes = read(socket, destinationBytes, bytes);
        if (readBytes < 1)
            return 0;
        destinationBytes += readBytes;
        bytes -= readBytes;
    }
    return 1;
}

int main(int argc, char **argv)
{
    int selectedFd;

    // use `select` or `poll` to wait on sockets
    // received a message on `selectedFd`, start reading

    char *fooMessage;
    struct {
        uint32_t a;
        uint32_t b;
    } barMessage;

    struct MessageHeader received;
    if (!readExpected (selectedFd, &received, sizeof(received))) {
        // handle error
    }
    // handle network/host byte order differences maybe
    received.type = ntohl(received.type);
    received.length = ntohl(received.length);

    switch (received.type) {
        case MESSAGE_FOO:
            // "foo" sends an ASCII string or something
            fooMessage = calloc(received.length + 1, 1);
            if (readExpected (selectedFd, fooMessage, received.length))
                puts(fooMessage);
            free(fooMessage);
            break;
        case MESSAGE_BAR:
            // "bar" sends a message of a fixed size
            if (readExpected (selectedFd, &barMessage, sizeof(barMessage))) {
                barMessage.a = ntohl(barMessage.a);
                barMessage.b = ntohl(barMessage.b);
                printf("a + b = %d\n", barMessage.a + barMessage.b);
            }
            break;
        default:
            puts("Malformed type received");
            // kick the client out probably
    }
}

You can likely already see one disadvantage of using a binary format - for each attribute greater than a char you read, you will have to ensure its byte order is correct using the ntohl or ntohs functions.

An alternative is to use byte-encoded messages, such as simple ASCII or UTF-8 strings, which avoid byte-order issues entirely but require extra effort to parse and validate.

There are two final considerations for network data in C.

The first is that some C types do not have fixed widths. For example, the humble int is defined as the word size of the processor, so 32 bit processors will produce 32 bit ints, while 64 bit processors will produces 64 bit ints. Good, portable code should have network data use fixed-width types, like those defined in stdint.h.

The second is struct padding. A struct with different-widthed members will add data in between some members to maintain memory alignment, making the struct faster to use in the program but sometimes producing confusing results.

#include <stdio.h>
#include <stdint.h>

int main()
{
    struct A {
        char a;
        uint32_t b;
    } A;

    printf("sizeof(A): %ld\n", sizeof(A));
}

In this example, its actual width won't be 1 char + 4 uint32_t = 5 bytes, it'll be 8:

mharrison@mharrison-KATANA:~$ gcc -o padding padding.c
mharrison@mharrison-KATANA:~$ ./padding 
sizeof(A): 8

This is because 3 bytes are added after char a to make sure uint32_t b is memory-aligned.

So if you write a struct A, then attempt to read a char and a uint32_t on the other side, you'll get char a, and a uint32_t where the first three bytes are garbage and the last byte is the first byte of the actual integer you wrote.

Either document your data format explicitly as C struct types or, better yet, document any padding bytes they might contain.

How do I get java logging output to appear on a single line?

This logging is specific to your application and not a general Java feature. What application(s) are you running?

It might be that this is coming from a specific logging library that you are using within your own code. If so, please post the details of which one you are using.

bash string equality

There's no difference, == is a synonym for = (for the C/C++ people, I assume). See here, for example.

You could double-check just to be really sure or just for your interest by looking at the bash source code, should be somewhere in the parsing code there, but I couldn't find it straightaway.

Upgrade to python 3.8 using conda

Update for 2020/07

Finally, Anaconda3-2020.07 is out and its core is Python 3.8!

You can now download Anaconda packed with Python 3.8 goodness at:

JPA Query.getResultList() - use in a generic way

Since JPA 2.0 a TypedQuery can be used:

TypedQuery<SimpleEntity> q = 
        em.createQuery("select t from SimpleEntity t", SimpleEntity.class);

List<SimpleEntity> listOfSimpleEntities = q.getResultList();
for (SimpleEntity entity : listOfSimpleEntities) {
    // do something useful with entity;
}

C# DateTime to UTC Time without changing the time

6/1/2011 4:08:40 PM Local
6/1/2011 4:08:40 PM Utc

from

DateTime dt = DateTime.Now;            
Console.WriteLine("{0} {1}", dt, dt.Kind);
DateTime ut = DateTime.SpecifyKind(dt, DateTimeKind.Utc);
Console.WriteLine("{0} {1}", ut, ut.Kind);

When to use a linked list over an array/array list?

Arrays have O(1) random access, but are really expensive to add stuff onto or remove stuff from.

Linked lists are really cheap to add or remove items anywhere and to iterate, but random access is O(n).

How do detect Android Tablets in general. Useragent?

If you use the absence of "Mobile" then its almost correct. But there are HTC Sensation 4G (4.3 inch with android 2.X) which does not send Mobile keyword.

The reason why you may want to treat it separately is due to iframes etc.

android asynctask sending callbacks to ui

You can create an interface, pass it to AsyncTask (in constructor), and then call method in onPostExecute()

For example:

Your interface:

public interface OnTaskCompleted{
    void onTaskCompleted();
}

Your Activity:

public class YourActivity implements OnTaskCompleted{
    // your Activity
}

And your AsyncTask:

public class YourTask extends AsyncTask<Object,Object,Object>{ //change Object to required type
    private OnTaskCompleted listener;

    public YourTask(OnTaskCompleted listener){
        this.listener=listener;
    }

    // required methods

    protected void onPostExecute(Object o){
        // your stuff
        listener.onTaskCompleted();
    }
}

EDIT

Since this answer got quite popular, I want to add some things.

If you're a new to Android development, AsyncTask is a fast way to make things work without blocking UI thread. It does solves some problems indeed, there is nothing wrong with how the class works itself. However, it brings some implications, such as:

  • Possibility of memory leaks. If you keep reference to your Activity, it will stay in memory even after user left the screen (or rotated the device).
  • AsyncTask is not delivering result to Activity if Activity was already destroyed. You have to add extra code to manage all this stuff or do you operations twice.
  • Convoluted code which does everything in Activity

When you feel that you matured enough to move on with Android, take a look at this article which, I think, is a better way to go for developing your Android apps with asynchronous operations.

How to use getJSON, sending data with post method?

$.getJSON() is pretty handy for sending an AJAX request and getting back JSON data as a response. Alas, the jQuery documentation lacks a sister function that should be named $.postJSON(). Why not just use $.getJSON() and be done with it? Well, perhaps you want to send a large amount of data or, in my case, IE7 just doesn’t want to work properly with a GET request.

It is true, there is currently no $.postJSON() method, but you can accomplish the same thing by specifying a fourth parameter (type) in the $.post() function:

My code looked like this:

$.post('script.php', data, function(response) {
  // Do something with the request
}, 'json');

Printing a 2D array in C

Is this any help?

#include <stdio.h>

#define MAX 10

int main()
{
    char grid[MAX][MAX];
    int i,j,row,col;

    printf("Please enter your grid size: ");
    scanf("%d %d", &row, &col);


    for (i = 0; i < row; i++) {
        for (j = 0; j < col; j++) {
            grid[i][j] = '.';
            printf("%c ", grid[i][j]);
        }
        printf("\n");
    }

    return 0;
}

pandas how to check dtype for all columns in a dataframe?

To go one step further, I assume you want to do something with these dtypes. df.dtypes.to_dict() comes in handy.

my_type = 'float64' #<---

dtypes = dataframe.dtypes.to_dict()

for col_nam, typ in dtypes.items():
    if (typ != my_type): #<---
        raise ValueError(f"Yikes - `dataframe['{col_name}'].dtype == {typ}` not {my_type}")

You'll find that Pandas did a really good job comparing NumPy classes and user-provided strings. For example: even things like 'double' == dataframe['col_name'].dtype will succeed when .dtype==np.float64.

Bootstrap modal: close current, open new

This code, close modal opened, open the new modal but inmediatly, new modal is closed.

$(nameClose).modal('hide');
$(nameOpen).modal('show');

My solution for open new modal after close other is:

function swapModals(nameClose,nameOpen) {
    $(nameClose).modal('hide');
    $(nameClose).on('hidden.bs.modal', function () {
        console.log('Fired when hide event has finished!');
        $(nameOpen).modal('show');
    });
}

Custom CSS for <audio> tag?

Besides the box-shadow, transform and border options mentioned in other answers, WebKit browsers currently also obey -webkit-text-fill-color to set the colour of the "time elapsed" numbers, but since there is no way to set their background (which might vary with platform, e.g. inverted high-contrast modes on some operating systems), you would be advised to set -webkit-text-fill-color to the value "initial" if you've used it elsewhere and the audio element is inheriting this, otherwise some users might find those numbers unreadable.

How can I convert a Word document to PDF?

You can use Cloudmersive native Java library. It is free for up to 50,000 conversions/month and is much higher fidelity in my experience than other things like iText or Apache POI-based methods. The documents actually look the same as they do in Microsoft Word which for me is the key. Incidentally it can also do XLSX, PPTX, and the legacy DOC, XLS and PPT conversion to PDF.

Here is what the code looks like, first add your imports:

import com.cloudmersive.client.invoker.ApiClient;
import com.cloudmersive.client.invoker.ApiException;
import com.cloudmersive.client.invoker.Configuration;
import com.cloudmersive.client.invoker.auth.*;
import com.cloudmersive.client.ConvertDocumentApi;

Then convert a file:

ApiClient defaultClient = Configuration.getDefaultApiClient();

// Configure API key authorization: Apikey
ApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");
Apikey.setApiKey("YOUR API KEY");

ConvertDocumentApi apiInstance = new ConvertDocumentApi();
File inputFile = new File("/path/to/input.docx"); // File to perform the operation on.
try {
  byte[] result = apiInstance.convertDocumentDocxToPdf(inputFile);
  System.out.println(result);
} catch (ApiException e) {
  System.err.println("Exception when calling ConvertDocumentApi#convertDocumentDocxToPdf");
e.printStackTrace();
}

You can get an document conversion API key for free from the portal.

Links in <select> dropdown options

... or if you want / need to keep your option 'value' as it was, just add a new attribute:

<select id="my_selection">
<option value="x" href="/link/to/somewhere">value 1</option>
<option value="y" href="/link/to/somewhere/else">value 2</option>
</select>

<script>
document.getElementById('my_selection').onchange = function() {
    window.location.href = this.children[this.selectedIndex].getAttribute('href');
}
</script>

How to reset a timer in C#?

For System.Timers.Timer, according to MSDN documentation, http://msdn.microsoft.com/en-us/library/system.timers.timer.enabled.aspx:

If the interval is set after the Timer has started, the count is reset. For example, if you set the interval to 5 seconds and then set the Enabled property to true, the count starts at the time Enabled is set. If you reset the interval to 10 seconds when count is 3 seconds, the Elapsed event is raised for the first time 13 seconds after Enabled was set to true.

So,

    const double TIMEOUT = 5000; // milliseconds

    aTimer = new System.Timers.Timer(TIMEOUT);
    aTimer.Start();     // timer start running

    :
    :

    aTimer.Interval = TIMEOUT;  // restart the timer

Listen to changes within a DIV and act accordingly

http://api.jquery.com/change/

change does only work on input form elements.

you could just trigger a function after your XML / XSL transformation or make a listener:

var html = $('#laneconfigdisplay').html()
setInterval(function(){ if($('#laneconfigdisplay').html() != html){ alert('woo'); html = $('#laneconfigdisplay').html() } }, 10000) //checks your content box all 10 seconds and triggers alert when content has changed...

Batch file for PuTTY/PSFTP file transfer automation

You need to store the psftp script (lines from open to bye) into a separate file and pass that to psftp using -b switch:

cd "C:\Program Files (x86)\PuTTY"
psftp -b "C:\path\to\script\script.txt"

Reference:
https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter6.html#psftp-option-b


EDIT: For username+password: As you cannot use psftp commands in a batch file, for the same reason, you cannot specify the username and the password as psftp commands. These are inputs to the open command. While you can specify the username with the open command (open <user>@<IP>), you cannot specify the password this way. This can be done on a psftp command line only. Then it's probably cleaner to do all on the command-line:

cd "C:\Program Files (x86)\PuTTY"
psftp -b script.txt <user>@<IP> -pw <PW>

And remove the open, <user> and <PW> lines from your script.txt.

Reference:
https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter6.html#psftp-starting
https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter3.html#using-cmdline-pw


What you are doing atm is that you run psftp without any parameter or commands. Once you exit it (like by typing bye), your batch file continues trying to run open command (and others), what Windows shell obviously does not understand.


If you really want to keep everything in one file (the batch file), you can write commands to psftp standard input, like:

(
    echo cd ...
    echo lcd ...
    echo put log.sh
) | psftp -b script.txt <user>@<IP> -pw <PW>

Error: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'

This can happen if you accidentally are not dragging the element that does have an id assigned (for example you are dragging the surrounding element). In that case the ID is empty and the function drag() is assigning an empty value which is then passed to drop() and fails there.

Try assigning the ids to all of your elements, including the tds, divs, or whatever is around your draggable element.

Converting integer to digit list

Use list on a number converted to string:

In [1]: [int(x) for x in list(str(123))]
Out[2]: [1, 2, 3]

Jenkins - How to access BUILD_NUMBER environment variable

For Groovy script in the Jenkinsfile using the $BUILD_NUMBER it works.

Get battery level and state in Android

Based on official android docs, you can use this method in a Helper or Util class to get current battery percentage:

Java version:

public static int getBatteryPercentage(Context context) {

    if (Build.VERSION.SDK_INT >= 21) {

         BatteryManager bm = (BatteryManager) context.getSystemService(BATTERY_SERVICE);
         return bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);

    } else {

         IntentFilter iFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
         Intent batteryStatus = context.registerReceiver(null, iFilter);

         int level = batteryStatus != null ? batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) : -1;
         int scale = batteryStatus != null ? batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1) : -1;

         double batteryPct = level / (double) scale;

         return (int) (batteryPct * 100);
   }
}

Kotlin version:

fun getBatteryPercentage(context: Context): Int {
    return if (Build.VERSION.SDK_INT >= 21) {
        val bm = context.getSystemService(BATTERY_SERVICE) as BatteryManager
        bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
    
    } else {
        val iFilter = IntentFilter(Intent.ACTION_BATTERY_CHANGED)
        val batteryStatus: Intent = context.registerReceiver(null, iFilter)
        val level = batteryStatus?.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
        val scale = batteryStatus?.getIntExtra(BatteryManager.EXTRA_SCALE, -1)
        val batteryPct = level / scale.toDouble()
        (batteryPct * 100).toInt()
    }
}

Combine a list of data frames into one data frame by row

There is also bind_rows(x, ...) in dplyr.

> system.time({ df.Base <- do.call("rbind", listOfDataFrames) })
   user  system elapsed 
   0.08    0.00    0.07 
> 
> system.time({ df.dplyr <- as.data.frame(bind_rows(listOfDataFrames)) })
   user  system elapsed 
   0.01    0.00    0.02 
> 
> identical(df.Base, df.dplyr)
[1] TRUE

Excel 2010 VBA - Close file No Save without prompt

If you're not wanting to save changes set savechanges to false

    Sub CloseBook2()
        ActiveWorkbook.Close savechanges:=False
    End Sub

for more examples, http://support.microsoft.com/kb/213428 and i believe in the past I've just used

    ActiveWorkbook.Close False

Case Function Equivalent in Excel

I know it a little late to answer but I think this short video will help you a lot.

http://www.xlninja.com/2012/07/25/excel-choose-function-explained/

Essentially it is using the choose function. He explains it very well in the video so I'll let do it instead of typing 20 pages.

Another video of his explains how to use data validation to populate a drop down which you can select from a limited range.

http://www.xlninja.com/2012/08/13/excel-data-validation-using-dependent-lists/

You could combine the two and use the value in the drop down as your index to the choose function. While he did not show how to combine them, I'm sure you could figure it out as his videos are good. If you have trouble, let me know and I'll update my answer to show you.

How Do I Upload Eclipse Projects to GitHub?

You need a git client to upload your project to git servers. For eclipse EGIT is a nice plugin to use GIT.

to learn the basic of git , see here // i think you should have the basic first

Jquery find nearest matching element

You could try:

$(this).closest(".column").prev().find(".inputQty").val();

How to check internet access on Android? InetAddress never times out

You can use this method to detect network availability-

public static boolean isDeviceOnline(Context context) {
        boolean isConnectionAvail = false;
        try {
            ConnectivityManager cm = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo netInfo = cm.getActiveNetworkInfo();
            return netInfo.isConnected();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isConnectionAvail;
    }

ExpressJS How to structure an application?

My question was introduced in April 2011, it's quiet old. During this time, I could improve my experience with Express.js and how to architecture an application written using this library. So, I share here my experience.

Here's my directory structure:

+-- app.js   // main entry
+-- config   // The configuration of my applications (logger, global config, ...)
+-- models   // The model data (e.g. Mongoose model)
+-- public   // The public directory (client-side code)
+-- routes   // The route definitions and implementations
+-- services // The standalone services (Database service, Email service, ...)
+-- views    // The view rendered by the server to the client (e.g. Jade, EJS, ...)

App.js

The goal of the app.js file is to bootstrap the expressjs application. It loads the configuration module, the logger module, wait for database connection, ..., and run the express server.

'use strict';
require('./config');
var database = require('./services/database');
var express = require('express');
var app = express();
module.exports = app;

function main() {
  var http = require('http');

  // Configure the application.
  app.configure(function () {
    // ... ... ...
  });
  app.configure('production', function () {
    // ... ... ...
  });
  app.configure('development', function () {
    // ... ... ...
  });

  var server = http.createServer(app);

  // Load all routes.
  require('./routes')(app);

  // Listen on http port.
  server.listen(3000);
}

database.connect(function (err) {
  if (err) { 
    // ...
  }
  main();
});

routes/

The routes directory has a index.js file. Its goal is to introduce a kind of magic to load all other files inside the routes/ directory. Here's the implementation:

/**
 * This module loads dynamically all routes modules located in the routes/
 * directory.
 */
'use strict';
var fs = require('fs');
var path = require('path');

module.exports = function (app) {
  fs.readdirSync('./routes').forEach(function (file) {
    // Avoid to read this current file.
    if (file === path.basename(__filename)) { return; }

    // Load the route file.
    require('./' + file)(app);
  });
};

With that module, creating a new route definition and implementation is really easy. For examples, hello.js:

function hello(req, res) {
  res.send('Hello world');
}

module.exports = function (app) {
  app.get('/api/hello_world', hello);
};

Each route module is standalone.

Simplest way to display current month and year like "Aug 2016" in PHP?

Here is a simple and more update format of getting the data:

   $now = new \DateTime('now');
   $month = $now->format('m');
   $year = $now->format('Y');

why $(window).load() is not working in jQuery?

<script type="text/javascript">
   $(window).ready(function () {
      alert("Window Loaded");
   });
</script>

How to convert UTC timestamp to device local time in android

The answer from @prgDevelop returns 0 on my Android Marsmallow. Must return 7200000. These changes make it work fine:

int offset = TimeZone.getTimeZone(Time.getCurrentTimezone()).getRawOffset() + TimeZone.getTimeZone(Time.getCurrentTimezone()).getDSTSavings();

Can you Run Xcode in Linux?

I think you need MonoTouch (not free!) for that plugin.

And no, there is no way to run Xcode on Linux.

Sorry for all the bad news. :)

How to execute a query in ms-access in VBA code?

Take a look at this tutorial for how to use SQL inside VBA:

http://www.ehow.com/how_7148832_access-vba-query-results.html

For a query that won't return results, use (reference here):

DoCmd.RunSQL

For one that will, use (reference here):

Dim dBase As Database
dBase.OpenRecordset

Splitting a C++ std::string using tokens, e.g. ";"

There are several libraries available solving this problem, but the simplest is probably to use Boost Tokenizer:

#include <iostream>
#include <string>
#include <boost/tokenizer.hpp>
#include <boost/foreach.hpp>

typedef boost::tokenizer<boost::char_separator<char> > tokenizer;

std::string str("denmark;sweden;india;us");
boost::char_separator<char> sep(";");
tokenizer tokens(str, sep);

BOOST_FOREACH(std::string const& token, tokens)
{
    std::cout << "<" << *tok_iter << "> " << "\n";
}

Gradle - Error Could not find method implementation() for arguments [com.android.support:appcompat-v7:26.0.0]

I moved implementation to module-level build.gradle from root-level build.gradle. It solves the issue.

How do I check for equality using Spark Dataframe without SQL Query?

There is another simple sql like option. With Spark 1.6 below also should work.

df.filter("state = 'TX'")

This is a new way of specifying sql like filters. For a full list of supported operators, check out this class.

Formatting doubles for output in C#

Though this question is meanwhile closed, I believe it is worth mentioning how this atrocity came into existence. In a way, you may blame the C# spec, which states that a double must have a precision of 15 or 16 digits (the result of IEEE-754). A bit further on (section 4.1.6) it's stated that implementations are allowed to use higher precision. Mind you: higher, not lower. They are even allowed to deviate from IEEE-754: expressions of the type x * y / z where x * y would yield +/-INF but would be in a valid range after dividing, do not have to result in an error. This feature makes it easier for compilers to use higher precision in architectures where that'd yield better performance.

But I promised a "reason". Here's a quote (you requested a resource in one of your recent comments) from the Shared Source CLI, in clr/src/vm/comnumber.cpp:

"In order to give numbers that are both friendly to display and round-trippable, we parse the number using 15 digits and then determine if it round trips to the same value. If it does, we convert that NUMBER to a string, otherwise we reparse using 17 digits and display that."

In other words: MS's CLI Development Team decided to be both round-trippable and show pretty values that aren't such a pain to read. Good or bad? I'd wish for an opt-in or opt-out.

The trick it does to find out this round-trippability of any given number? Conversion to a generic NUMBER structure (which has separate fields for the properties of a double) and back, and then compare whether the result is different. If it is different, the exact value is used (as in your middle value with 6.9 - i) if it is the same, the "pretty value" is used.

As you already remarked in a comment to Andyp, 6.90...00 is bitwise equal to 6.89...9467. And now you know why 0.0...8818 is used: it is bitwise different from 0.0.

This 15 digits barrier is hard-coded and can only be changed by recompiling the CLI, by using Mono or by calling Microsoft and convincing them to add an option to print full "precision" (it is not really precision, but by the lack of a better word). It's probably easier to just calculate the 52 bits precision yourself or use the library mentioned earlier.

EDIT: if you like to experiment yourself with IEE-754 floating points, consider this online tool, which shows you all relevant parts of a floating point.

How do I keep CSS floats in one line?

Wrap your floating <div>s in a container <div> that uses this cross-browser min-width hack:

.minwidth { min-width:100px; width: auto !important; width: 100px; }

You may also need to set "overflow" but probably not.

This works because:

  • The !important declaration, combined with min-width cause everything to stay on the same line in IE7+
  • IE6 does not implement min-width, but it has a bug such that width: 100px overrides the !important declaration, causing the container width to be 100px.

How do I bind a WPF DataGrid to a variable number of columns?

You might be able to do this with AutoGenerateColumns and a DataTemplate. I'm not positive if it would work without a lot of work, you would have to play around with it. Honestly if you have a working solution already I wouldn't make the change just yet unless there's a big reason. The DataGrid control is getting very good but it still needs some work (and I have a lot of learning left to do) to be able to do dynamic tasks like this easily.

Responsive background image in div full width

I also tried this style for ionic hybrid app background. this is also having style for background blur effect.

.bg-image {
   position: absolute;
   background: url(../img/bglogin.jpg) no-repeat;
   height: 100%;
   width: 100%;
   background-size: cover;
   bottom: 0px;
   margin: 0 auto;
   background-position: 50%;


  -webkit-filter: blur(5px);
  -moz-filter: blur(5px);
  -o-filter: blur(5px);
  -ms-filter: blur(5px);
  filter: blur(5px);

}

Credit card payment gateway in PHP?

Stripe has a PHP library to accept credit cards without needing a merchant account: https://github.com/stripe/stripe-php

Check out the documentation and FAQ, and feel free to drop by our chatroom if you have more questions.

Python: printing a file to stdout

Sure. Assuming you have a string with the file's name called fname, the following does the trick.

with open(fname, 'r') as fin:
    print(fin.read())

Kotlin Ternary Conditional Operator

You could define your own Boolean extension function that returns null when the Boolean is false to provide a structure similar to the ternary operator:

infix fun <T> Boolean.then(param: T): T? = if (this) param else null

This would make an a ? b : c expression translate to a then b ?: c, like so:

println(condition then "yes" ?: "no")

Update: But to do some more Java-like conditional switch you will need something like that

infix fun <T> Boolean.then(param: () -> T): T? = if (this) param() else null

println(condition then { "yes" } ?: "no") pay attention on the lambda. its content calculation should be postponed until we make sure condition is true

This one looks clumsy, that is why there is high demanded request exist to port Java ternary operator into Kotlin

scrollIntoView Scrolls just too far

Here's my 2 cents.

I've also had the issue of the scrollIntoView scrolling a bit past the element, so I created a script (native javascript) that prepends an element to the destination, positioned it a bit to the top with css and scrolled to that one. After scrolling, I remove the created elements again.

HTML:

//anchor tag that appears multiple times on the page
<a href="#" class="anchors__link js-anchor" data-target="schedule">
    <div class="anchors__text">
        Scroll to the schedule
    </div>
</a>

//The node we want to scroll to, somewhere on the page
<div id="schedule">
    //html
</div>

Javascript file:

(() => {
    'use strict';

    const anchors = document.querySelectorAll('.js-anchor');

    //if there are no anchors found, don't run the script
    if (!anchors || anchors.length <= 0) return;

    anchors.forEach(anchor => {
        //get the target from the data attribute
        const target = anchor.dataset.target;

        //search for the destination element to scroll to
        const destination = document.querySelector(`#${target}`);
        //if the destination element does not exist, don't run the rest of the code
        if (!destination) return;

        anchor.addEventListener('click', (e) => {
            e.preventDefault();
            //create a new element and add the `anchors__generated` class to it
            const generatedAnchor = document.createElement('div');
            generatedAnchor.classList.add('anchors__generated');

            //get the first child of the destination element, insert the generated element before it. (so the scrollIntoView function scrolls to the top of the element instead of the bottom)
            const firstChild = destination.firstChild;
            destination.insertBefore(generatedAnchor, firstChild);

            //finally fire the scrollIntoView function and make it animate "smoothly"
            generatedAnchor.scrollIntoView({
                behavior: "smooth",
                block: "start",
                inline: "start"
            });

            //remove the generated element after 1ms. We need the timeout so the scrollIntoView function has something to scroll to.
            setTimeout(() => {
                destination.removeChild(generatedAnchor);
            }, 1);
        })
    })
})();

CSS:

.anchors__generated {
    position: relative;
    top: -100px;
}

Hope this helps anyone!

Try-catch speeding up my code?

I'd have put this in as a comment as I'm really not certain that this is likely to be the case, but as I recall it doesn't a try/except statement involve a modification to the way the garbage disposal mechanism of the compiler works, in that it clears up object memory allocations in a recursive way off the stack. There may not be an object to be cleared up in this case or the for loop may constitute a closure that the garbage collection mechanism recognises sufficient to enforce a different collection method. Probably not, but I thought it worth a mention as I hadn't seen it discussed anywhere else.

count number of characters in nvarchar column

Use

SELECT length(yourfield) FROM table;

Genymotion, "Unable to load VirtualBox engine." on Mavericks. VBox is setup correctly

Update: Genymotion's 2.5.1 release (https://www.genymotion.com/#!/release-notes/251#251) seems to have fixed this issue. (thanks for the heads up @Roger!)


For those that may be stumbling upon this a bit later, I resolved this by installing VirtualBox 4.3.28 (https://www.virtualbox.org/wiki/Download_Old_Builds_4_3). The new 5.0.0 and 4.3.30 versions didn't work for me with Genymotion 2.5. None of the above solutions worked :(

It's also worth noting that at the time of writing, Genymotion's FAQ states the following:

However, for performance reasons, we recommend using version 4.3.12

Can two Java methods have same name with different return types?

If both methods have same parameter types, but different return type than it is not possible. From Java Language Specification, Java SE 8 Edition, §8.4.2. Method Signature:

Two methods or constructors, M and N, have the same signature if they have the same name, the same type parameters (if any) (§8.4.4), and, after adapting the formal parameter types of N to the the type parameters of M, the same formal parameter types.

If both methods has different parameter types (so, they have different signature), then it is possible. It is called overloading.

Python sys.argv lists and indexes

let's say on the command-line you have:

C:\> C:\Documents and Settings\fred\My Documents\Downloads\google-python-exercises
\google-python-exercises\hello.py John

to make it easier to read, let's just shorten this to:

C:\> hello.py John

argv represents all the items that come along via the command-line input, but counting starts at zero (0) not one (1): in this case, "hello.py" is element 0, "John" is element 1

in other words, sys.argv[0] == 'hello.py' and sys.argv[1] == 'John' ... but look, how many elements is this? 2, right! so even though the numbers are 0 and 1, there are 2 elements here.

len(sys.argv) >= 2 just checks whether you entered at least two elements. in this case, we entered exactly 2.

now let's translate your code into English:

define main() function:
    if there are at least 2 elements on the cmd-line:
        set 'name' to the second element located at index 1, e.g., John
    otherwise there is only 1 element... the program name, e.g., hello.py:
        set 'name' to "World" (since we did not get any useful user input)
    display 'Hello' followed by whatever i assigned to 'name'

so what does this mean? it means that if you enter:

  • "hello.py", the code outputs "Hello World" because you didn't give a name
  • "hello.py John", the code outputs "Hello John" because you did
  • "hello.py John Paul", the code still outputs "Hello John" because it does not save nor use sys.argv[2], which was "Paul" -- can you see in this case that len(sys.argv) == 3 because there are 3 elements in the sys.argv list?

Replace CRLF using powershell

You have not specified the version, I'm assuming you are using Powershell v3.

Try this:

$path = "C:\Users\abc\Desktop\File\abc.txt"
(Get-Content $path -Raw).Replace("`r`n","`n") | Set-Content $path -Force

Editor's note: As mike z points out in the comments, Set-Content appends a trailing CRLF, which is undesired. Verify with: 'hi' > t.txt; (Get-Content -Raw t.txt).Replace("`r`n","`n") | Set-Content t.txt; (Get-Content -Raw t.txt).EndsWith("`r`n"), which yields $True.

Note this loads the whole file in memory, so you might want a different solution if you want to process huge files.

UPDATE

This might work for v2 (sorry nowhere to test):

$in = "C:\Users\abc\Desktop\File\abc.txt"
$out = "C:\Users\abc\Desktop\File\abc-out.txt"
(Get-Content $in) -join "`n" > $out

Editor's note: Note that this solution (now) writes to a different file and is therefore not equivalent to the (still flawed) v3 solution. (A different file is targeted to avoid the pitfall Ansgar Wiechers points out in the comments: using > truncates the target file before execution begins). More importantly, though: this solution too appends a trailing CRLF, which may be undesired. Verify with 'hi' > t.txt; (Get-Content t.txt) -join "`n" > t.NEW.txt; [io.file]::ReadAllText((Convert-Path t.NEW.txt)).endswith("`r`n"), which yields $True.

Same reservation about being loaded to memory though.

How to use the divide function in the query?

Assuming all of these columns are int, then the first thing to sort out is converting one or more of them to a better data type - int division performs truncation, so anything less than 100% would give you a result of 0:

select (100.0 * (SPGI09_EARLY_OVER_T – SPGI09_OVER_WK_EARLY_ADJUST_T)) / (SPGI09_EARLY_OVER_T + SPGR99_LATE_CM_T  + SPGR99_ON_TIME_Q)
from 
CSPGI09_OVERSHIPMENT 

Here, I've mutiplied one of the numbers by 100.0 which will force the result of the calculation to be done with floats rather than ints. By choosing 100, I'm also getting it ready to be treated as a %.

I was also a little confused by your bracketing - I think I've got it correct - but you had brackets around single values, and then in other places you had a mix of operators (- and /) at the same level, and so were relying on the precedence rules to define which operator applied first.

The program can't start because libgcc_s_dw2-1.dll is missing

See also. It solved my problem.

By the way, is it definitely compiler flag? Maybe linker is the more suitable term here?

Leave menu bar fixed on top when scrolled

In this example, you may show your menu centered.

HTML

<div id="main-menu-container">
    <div id="main-menu">
        //your menu
    </div>
</div>

CSS

.f-nav{  /* To fix main menu container */
    z-index: 9999;
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
}
#main-menu-container {
    text-align: center; /* Assuming your main layout is centered */
}
#main-menu {
    display: inline-block;
    width: 1024px; /* Your menu's width */
}

JS

$("document").ready(function($){
    var nav = $('#main-menu-container');

    $(window).scroll(function () {
        if ($(this).scrollTop() > 125) {
            nav.addClass("f-nav");
        } else {
            nav.removeClass("f-nav");
        }
    });
});

org.hibernate.MappingException: Unknown entity

You entity is not correctly annotated, you must use the @javax.persistence.Entity annotation. You can use the Hibernate extension @org.hibernate.annotations.Entity to go beyond what JPA has to offer but the Hibernate annotation is not a replacement, it's a complement.

So change your code into:

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
public class Message { 
    ...  
}

References

usr/bin/ld: cannot find -l<nameOfTheLibrary>

Here is Ubuntu information of my laptop.

lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 18.04.2 LTS
Release:    18.04
Codename:   bionic

I use locate to find the .so files for boost_filesystem and boost_system

locate libboost_filesystem
locate libboost_system

Then link .so files to /usr/lib and rename to .so

sudo ln -s /usr/lib/x86_64-linux-gnu/libboost_filesystem.so.1.65.1 /usr/lib/libboost_filesystem.so
sudo ln -s /usr/lib/x86_64-linux-gnu/libboost_system.so.1.65.1 /usr/lib/libboost_system.so

Done! R package velocyto.R was successfully installed!

Run a vbscript from another vbscript

I saw the below code working. Simple, but I guess not documented. Anyone else used the 'Execute' command ?

   Dim body, my_script_file
   Set Fso = CreateObject("Scripting.FileSystemObject")


   Set my_script_file = fso.OpenTextFile(FILE)
   body = my_script_file.ReadAll
    my_script_file.Close

    Execute body

How can I tell if an algorithm is efficient?

Yes you can start with the Wikipedia article explaining the Big O notation, which in a nutshell is a way of describing the "efficiency" (upper bound of complexity) of different type of algorithms. Or you can look at an earlier answer where this is explained in simple english

SQL Statement using Where clause with multiple values

Select t1.SongName
From tablename t1
left join tablename t2
 on t1.SongName = t2.SongName
    and t1.PersonName <> t2.PersonName
    and t1.Status = 'Complete' -- my assumption that this is necessary
    and t2.Status = 'Complete' -- my assumption that this is necessary
    and t1.PersonName IN ('Holly', 'Ryan')
    and t2.PersonName IN ('Holly', 'Ryan')

Serializing a list to JSON

public static string JSONSerialize<T>(T obj)
        {
            string retVal = String.Empty;
            using (MemoryStream ms = new MemoryStream())
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
                serializer.WriteObject(ms, obj);
                var byteArray = ms.ToArray();
                retVal = Encoding.UTF8.GetString(byteArray, 0, byteArray.Length);
            }
            return retVal;
        }

How do I list / export private keys from a keystore?

Another less-conventional but arguably easier way of doing this is with JXplorer. Although this tool is designed to browse LDAP directories, it has an easy-to-use GUI for manipulating keystores. One such function on the GUI can export private keys from a JKS keystore.

PostgreSQL Autoincrement

Whilst it looks like sequences are the equivalent to MySQL auto_increment, there are some subtle but important differences:

1. Failed Queries Increment The Sequence/Serial

The serial column gets incremented on failed queries. This leads to fragmentation from failed queries, not just row deletions. For example, run the following queries on your PostgreSQL database:

CREATE TABLE table1 (
  uid serial NOT NULL PRIMARY KEY,
  col_b integer NOT NULL,
  CHECK (col_b>=0)
);

INSERT INTO table1 (col_b) VALUES(1);
INSERT INTO table1 (col_b) VALUES(-1);
INSERT INTO table1 (col_b) VALUES(2);

SELECT * FROM table1;

You should get the following output:

 uid | col_b 
-----+-------
   1 |     1
   3 |     2
(2 rows)

Notice how uid goes from 1 to 3 instead of 1 to 2.

This still occurs if you were to manually create your own sequence with:

CREATE SEQUENCE table1_seq;
CREATE TABLE table1 (
    col_a smallint NOT NULL DEFAULT nextval('table1_seq'),
    col_b integer NOT NULL,
    CHECK (col_b>=0)
);
ALTER SEQUENCE table1_seq OWNED BY table1.col_a;

If you wish to test how MySQL is different, run the following on a MySQL database:

CREATE TABLE table1 (
  uid int unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY,
  col_b int unsigned NOT NULL
);

INSERT INTO table1 (col_b) VALUES(1);
INSERT INTO table1 (col_b) VALUES(-1);
INSERT INTO table1 (col_b) VALUES(2);

You should get the following with no fragementation:

+-----+-------+
| uid | col_b |
+-----+-------+
|   1 |     1 |
|   2 |     2 |
+-----+-------+
2 rows in set (0.00 sec)

2. Manually Setting the Serial Column Value Can Cause Future Queries to Fail.

This was pointed out by @trev in a previous answer.

To simulate this manually set the uid to 4 which will "clash" later.

INSERT INTO table1 (uid, col_b) VALUES(5, 5);

Table data:

 uid | col_b 
-----+-------
   1 |     1
   3 |     2
   5 |     5
(3 rows)

Run another insert:

INSERT INTO table1 (col_b) VALUES(6);

Table data:

 uid | col_b 
-----+-------
   1 |     1
   3 |     2
   5 |     5
   4 |     6

Now if you run another insert:

INSERT INTO table1 (col_b) VALUES(7);

It will fail with the following error message:

ERROR: duplicate key value violates unique constraint "table1_pkey" DETAIL: Key (uid)=(5) already exists.

In contrast, MySQL will handle this gracefully as shown below:

INSERT INTO table1 (uid, col_b) VALUES(4, 4);

Now insert another row without setting uid

INSERT INTO table1 (col_b) VALUES(3);

The query doesn't fail, uid just jumps to 5:

+-----+-------+
| uid | col_b |
+-----+-------+
|   1 |     1 |
|   2 |     2 |
|   4 |     4 |
|   5 |     3 |
+-----+-------+

Testing was performed on MySQL 5.6.33, for Linux (x86_64) and PostgreSQL 9.4.9

Why does IE9 switch to compatibility mode on my website?

As an aside on more modern websites, if you are using conditional statements on your html tag as per boilerplate, this will for some reason cause ie9 to default to compatibility mode. The fix here is to move your conditional statements off the html tag and add them to the body tag, in other words out of the head section. That way you can still use those classes in your style sheet to target older browsers.

Deleting rows from parent and child tables

Here's a complete example of how it can be done. However you need flashback query privileges on the child table.

Here's the setup.

create table parent_tab
  (parent_id number primary key,
  val varchar2(20));

create table child_tab
    (child_id number primary key,
    parent_id number,
    child_val number,
     constraint child_par_fk foreign key (parent_id) references parent_tab);

insert into parent_tab values (1,'Red');
insert into parent_tab values (2,'Green');
insert into parent_tab values (3,'Blue');
insert into parent_tab values (4,'Black');
insert into parent_tab values (5,'White');

insert into child_tab values (10,1,100);
insert into child_tab values (20,3,100);
insert into child_tab values (30,3,100);
insert into child_tab values (40,4,100);
insert into child_tab values (50,5,200);

commit;

select * from parent_tab
where parent_id not in (select parent_id from child_tab);

Now delete a subset of the children (ones with parents 1,3 and 4 - but not 5).

delete from child_tab where child_val = 100;

Then get the parent_ids from the current COMMITTED state of the child_tab (ie as they were prior to your deletes) and remove those that your session has NOT deleted. That gives you the subset that have been deleted. You can then delete those out of the parent_tab

delete from parent_tab
where parent_id in
  (select parent_id from child_tab as of scn dbms_flashback.get_system_change_number
  minus
  select parent_id from child_tab);

'Green' is still there (as it didn't have an entry in the child table anyway) and 'Red' is still there (as it still has an entry in the child table)

select * from parent_tab
where parent_id not in (select parent_id from child_tab);

select * from parent_tab;

It is an exotic/unusual operation, so if i was doing it I'd probably be a bit cautious and lock both child and parent tables in exclusive mode at the start of the transaction. Also, if the child table was big it wouldn't be particularly performant so I'd opt for a PL/SQL solution like Rajesh's.

Standard Android menu icons, for example refresh

Bear in mind, this is a practice that Google explicitly advises not to do:

Warning: Because these resources can change between platform versions, you should not reference these icons using the Android platform resource IDs (i.e. menu icons under android.R.drawable).

Rather, you are adviced to make a local copy:

If you want to use any icons or other internal drawable resources, you should store a local copy of those icons or drawables in your application resources, then reference the local copy from your application code. In that way, you can maintain control over the appearance of your icons, even if the system's copy changes.

How to import a SQL Server .bak file into MySQL?

The .bak file from SQL Server is specific to that database dialect, and not compatible with MySQL.

Try using etlalchemy to migrate your SQL Server database into MySQL. It is an open-sourced tool that I created to facilitate easy migrations between different RDBMS's.

Quick installation and examples are provided here on the github page, and a more detailed explanation of the project's origins can be found here.

"Eliminate render-blocking CSS in above-the-fold content"

Few tips that may help:

  • I came across this article in CSS optimization yesterday: CSS profiling for ... optimization
    A lot of useful info on CSS and what CSS causes the most performance drains.

  • I saw the following presentation on jQueryUK on "hidden secrets" in Googe Chrome (Canary) Dev Tools: DevTools Can do that. Check out the sections on Time to First Paint, repaints and costly CSS.

  • Also, if you are using a loader like requireJS you could have a look at one of the CSS loader plugins, called require-CSS, which uses CSSO - a optimzer that also does structural optimization, eg. merging blocks with identical properties. I used it a few times and it can save quite a lot of CSS from case to case.

Off the question: I second @Enzino in creating a sprite for all the small icons you are loading. The file sizes are so small it does not really warrant a server roundtrip for each icon. Also keep in mind the total number of concurrent http requests are browser can do. So requests for a larger number of small icons are "render-blocking" as well. Although an empty page compare to yours, I like how duckduckgo loads for example.

Change the "From:" address in Unix "mail"

It's also possible to set both the From name and from address using something like:

 echo test | mail -s "test" [email protected] -- -F'Some Name<[email protected]>' -t

For some reason passing -F'Some Name' and [email protected] doesn't work, but passing in the -t to sendmail works and is "easy".

SaveFileDialog setting default path and file type?

Environment.GetSystemVariable("%SystemDrive%"); will provide the drive OS installed, and you can set filters to savedialog Obtain file path of C# save dialog box

How can I use interface as a C# generic type constraint?

Solution A: This combination of constraints should guarantee that TInterface is an interface:

class example<TInterface, TStruct>
    where TStruct : struct, TInterface
    where TInterface : class
{ }

It requires a single struct TStruct as a Witness to proof that TInterface is a struct.

You can use single struct as a witness for all your non-generic types:

struct InterfaceWitness : IA, IB, IC 
{
    public int DoA() => throw new InvalidOperationException();
    //...
}

Solution B: If you don't want to make structs as witnesses you can create an interface

interface ISInterface<T>
    where T : ISInterface<T>
{ }

and use a constraint:

class example<TInterface>
    where TInterface : ISInterface<TInterface>
{ }

Implementation for interfaces:

interface IA :ISInterface<IA>{ }

This solves some of the problems, but requires trust that noone implements ISInterface<T> for non-interface types, but that is pretty hard to do accidentally.

Automating running command on Linux from Windows using PuTTY

Code:

using System;
using System.Diagnostics;
namespace playSound
{
    class Program
    {
        public static void Main(string[] args)
        {
            Console.WriteLine(args[0]);

            Process amixerMediaProcess = new Process();
            amixerMediaProcess.StartInfo.CreateNoWindow = false;
            amixerMediaProcess.StartInfo.UseShellExecute = false;
            amixerMediaProcess.StartInfo.ErrorDialog = false;
            amixerMediaProcess.StartInfo.RedirectStandardOutput = false;
            amixerMediaProcess.StartInfo.RedirectStandardInput = false;
            amixerMediaProcess.StartInfo.RedirectStandardError = false;
            amixerMediaProcess.EnableRaisingEvents = true;

            amixerMediaProcess.StartInfo.Arguments = string.Format("{0}","-ssh username@"+args[0]+" -pw password -m commands.txt");
            amixerMediaProcess.StartInfo.FileName = "plink.exe";
            amixerMediaProcess.Start();


            Console.Write("Presskey to continue . . . ");
            Console.ReadKey(true);
    }
}

}

Sample commands.txt:

ps

Link: https://huseyincakir.wordpress.com/2015/08/27/send-commands-to-a-remote-device-over-puttyssh-putty-send-command-from-command-line/

sudo: port: command not found

You could try to source your profile file to update your environment:

$ source ~/.profile

How can I find the product GUID of an installed MSI setup?

If you have too many installers to find what you are looking for easily, here is some powershell to provide a filter and narrow it down a little by display name.

$filter = "*core*sdk*"; (Get-ChildItem HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall).Name | % { $path = "Registry::$_"; Get-ItemProperty $path } | Where-Object { $_.DisplayName -like $filter } | Select-Object -Property DisplayName, PsChildName

How can I order a List<string>?

List<string> myCollection = new List<string>()
{
    "Bob", "Bob","Alex", "Abdi", "Abdi", "Bob", "Alex", "Bob","Abdi"
};

myCollection.Sort();
foreach (var name in myCollection.Distinct())
{
    Console.WriteLine(name + " " + myCollection.Count(x=> x == name));
}

output: Abdi 3 Alex 2 Bob 4

Explicit Return Type of Lambda

You can have more than one statement when still return:

[]() -> your_type {return (
        your_statement,
        even_more_statement = just_add_comma,
        return_value);}

http://www.cplusplus.com/doc/tutorial/operators/#comma

How to split a string in Java

One way to do this is to run through the String in a for-each loop and use the required split character.

public class StringSplitTest {

    public static void main(String[] arg){
        String str = "004-034556";
        String split[] = str.split("-");
        System.out.println("The split parts of the String are");
        for(String s:split)
        System.out.println(s);
    }
}

Output:

The split parts of the String are:
004
034556

java.util.Date and getYear()

In addition to all the comments, I thought I might add some code on how to use java.util.Date, java.util.Calendar and java.util.GregorianCalendar according to the javadoc.

//Initialize your Date however you like it.
Date date = new Date();
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
int year = calendar.get(Calendar.YEAR);
//Add one to month {0 - 11}
int month = calendar.get(Calendar.MONTH) + 1;
int day = calendar.get(Calendar.DAY_OF_MONTH);

Why use argparse rather than optparse?

Why should I use it instead of optparse? Are their new features I should know about?

@Nicholas's answer covers this well, I think, but not the more "meta" question you start with:

Why has yet another command-line parsing module been created?

That's the dilemma number one when any useful module is added to the standard library: what do you do when a substantially better, but backwards-incompatible, way to provide the same kind of functionality emerges?

Either you stick with the old and admittedly surpassed way (typically when we're talking about complicated packages: asyncore vs twisted, tkinter vs wx or Qt, ...) or you end up with multiple incompatible ways to do the same thing (XML parsers, IMHO, are an even better example of this than command-line parsers -- but the email package vs the myriad old ways to deal with similar issues isn't too far away either;-).

You may make threatening grumbles in the docs about the old ways being "deprecated", but (as long as you need to keep backwards compatibility) you can't really take them away without stopping large, important applications from moving to newer Python releases.

(Dilemma number two, not directly related to your question, is summarized in the old saying "the standard library is where good packages go to die"... with releases every year and a half or so, packages that aren't very, very stable, not needing releases any more often than that, can actually suffer substantially by being "frozen" in the standard library... but, that's really a different issue).

AngularJS event on window innerWidth size change

No need for jQuery! This simple snippet works fine for me. It uses angular.element() to bind window resize event.

/**
 * Window resize event handling
 */
angular.element($window).on('resize', function () {
    console.log($window.innerWidth);
});    

Unbind event

/**
 * Window resize unbind event      
 */
angular.element($window).off('resize');

How can I get a side-by-side diff when I do "git diff"?

I personally really like icdiff !

If you're on Mac OS X with HomeBrew, just do brew install icdiff.

To get the file labels correctly, plus other cool features, I have in my ~/.gitconfig:

[pager]
    difftool = true
[diff]
    tool = icdiff
[difftool "icdiff"]
    cmd = icdiff --head=5000 --highlight --line-numbers -L \"$BASE\" -L \"$REMOTE\" \"$LOCAL\" \"$REMOTE\"

And I use it like: git difftool

How to convert Set<String> to String[]?

Use the Set#toArray(IntFunction<T[]>) method taking an IntFunction as generator.

String[] GPXFILES1 = myset.toArray(String[]::new);

If you're not on Java 11 yet, then use the Set#toArray(T[]) method taking a typed array argument of the same size.

String[] GPXFILES1 = myset.toArray(new String[myset.size()]);

While still not on Java 11, and you can't guarantee that myset is unmodifiable at the moment of conversion to array, then better specify an empty typed array.

String[] GPXFILES1 = myset.toArray(new String[0]);

CSS media queries: max-width OR max-height

There are two ways for writing a proper media queries in css. If you are writing media queries for larger device first, then the correct way of writing will be:

@media only screen 
and (min-width : 415px){
    /* Styles */
}

@media only screen 
and (min-width : 769px){
    /* Styles */
}

@media only screen 
and (min-width : 992px){
    /* Styles */
}

But if you are writing media queries for smaller device first, then it would be something like:

@media only screen 
and (max-width : 991px){
    /* Styles */
}

@media only screen 
and (max-width : 768px){
    /* Styles */
}

@media only screen 
and (max-width : 414px){
    /* Styles */
}

Return value from a VBScript function

To return a value from a VBScript function, assign the value to the name of the function, like this:

Function getNumber
    getNumber = "423"
End Function

Positioning the colorbar

The best way to get good control over the colorbar position is to give it its own axis. Like so:

# What I imagine your plotting looks like so far
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(your_data)

# Now adding the colorbar
cbaxes = fig.add_axes([0.8, 0.1, 0.03, 0.8]) 
cb = plt.colorbar(ax1, cax = cbaxes)  

The numbers in the square brackets of add_axes refer to [left, bottom, width, height], where the coordinates are just fractions that go from 0 to 1 of the plotting area.

Get the first key name of a JavaScript object

Try this:

for (var firstKey in ahash) break;

alert(firstKey);  // 'one'

MVC 4 client side validation not working

<script src="/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="/Scripts/jquery.validate.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js"></script>

This code worked for me.

FIFO based Queue implementations?

ArrayDeque is probably the fastest object-based queue in the JDK; Trove has the TIntQueue interface, but I don't know where its implementations live.

What is stability in sorting algorithms and why is it important?

If you assume what you are sorting are just numbers and only their values identify/distinguish them (e.g. elements with same value are identicle), then the stability-issue of sorting is meaningless.

However, objects with same priority in sorting may be distinct, and sometime their relative order is meaningful information. In this case, unstable sort generates problems.

For example, you have a list of data which contains the time cost [T] of all players to clean a maze with Level [L] in a game. Suppose we need to rank the players by how fast they clean the maze. However, an additional rule applies: players who clean the maze with higher-level always have a higher rank, no matter how long the time cost is.

Of course you might try to map the paired value [T,L] to a real number [R] with some algorithm which follows the rules and then rank all players with [R] value.

However, if stable sorting is feasible, then you may simply sort the entire list by [T] (Faster players first) and then by [L]. In this case, the relative order of players (by time cost) will not be changed after you grouped them by level of maze they cleaned.

PS: of course the approach to sort twice is not the best solution to the particular problem but to explain the question of poster it should be enough.

Prime numbers between 1 to 100 in C Programming Language

#include <stdio.h>

int main () {

   int i, j;

   for(i = 2; i<100; i++) {

      for(j = 2; j <= (i/j); j++) 
      if(!(i%j)) break; // if factor found, not prime
      if(j > (i/j)) printf("%d is prime", i);
   }

   return 0;
}

How can I check if a MySQL table exists with PHP?

Even faster than a bad query:

SELECT count((1)) as `ct`  FROM INFORMATION_SCHEMA.TABLES where table_schema ='yourdatabasename' and table_name='yourtablename';

This way you can just retrieve one field and one value. .016 seconds for my slower system.

Fastest way to get the first object from a queryset in django?

This could work as well:

def get_first_element(MyModel):
    my_query = MyModel.objects.all()
    return my_query[:1]

if it's empty, then returns an empty list, otherwise it returns the first element inside a list.

How can we convert an integer to string in AngularJs

.toString() is available, or just add "" to the end of the int

var x = 3,
    toString = x.toString(),
    toConcat = x + "";

Angular is simply JavaScript at the core.

Placeholder in UITextView

Simple way to use this within some line of code:

Take one label up to UITextView in .nib connecting this label to your code , After it.

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{

    if (range.location>0 || text.length!=0) {
        placeholderLabel1.hidden = YES;
    }else{
        placeholderLabel1.hidden = NO;
    }
    return YES;
}

The storage engine for the table doesn't support repair. InnoDB or MyISAM?

InnoDB works slightly different that MyISAM and they both are viable options. You should use what you think it fits the project.

Some keypoints will be:

  1. InnoDB does ACID-compliant transaction. http://en.wikipedia.org/wiki/ACID
  2. InnoDB does Referential Integrity (foreign key relations) http://www.w3resource.com/sql/joins/joining-tables-through-referential-integrity.php
  3. MyIsam does full text search, InnoDB doesn't
  4. I have been told InnoDB is faster on executing writes but slower than MyISAM doing reads (I cannot back this up and could not find any article that analyses this, I do however have the guy that told me this in high regard), feel free to ignore this point or do your own research.
  5. Default configuration does not work very well for InnoDB needs to be tweaked accordingly, run a tool like http://mysqltuner.pl/mysqltuner.pl to help you.

Notes:

  • In my opinion the second point is probably the one were InnoDB has a huge advantage over MyISAM.
  • Full text search not working with InnoDB is a bit of a pain, You can mix different storage engines but be careful when doing so.

Notes2: - I am reading this book "High performance MySQL", the author says "InnoDB loads data and creates indexes slower than MyISAM", this could also be a very important factor when deciding what to use.

Selecting the last value of a column

Similar answer to caligari's answer, but we can tidy it up by just specifying the full column range:

=INDEX(G2:G, COUNT(G2:G))

How do I assert equality on two classes without an equals method?

Can you put the comparision code you posted into some static utility method?

public static String findDifference(Type obj1, Type obj2) {
    String difference = "";
    if (obj1.getFieldA() == null && obj2.getFieldA() != null
            || !obj1.getFieldA().equals(obj2.getFieldA())) {
        difference += "Difference at field A:" + "obj1 - "
                + obj1.getFieldA() + ", obj2 - " + obj2.getFieldA();
    }
    if (obj1.getFieldB() == null && obj2.getFieldB() != null
            || !obj1.getFieldB().equals(obj2.getFieldB())) {
        difference += "Difference at field B:" + "obj1 - "
                + obj1.getFieldB() + ", obj2 - " + obj2.getFieldB();
        // (...)
    }
    return difference;
}

Than you can use this method in JUnit like this:

assertEquals("Objects aren't equal", "", findDifferences(obj1, obj));

which isn't clunky and gives you full information about differences, if they exist (through not exactly in normal form of assertEqual but you get all the info so it should be good).

Jump into interface implementation in Eclipse IDE

I always use this implementors plugin to find all the implementation of an Interface

http://eclipse-tools.sourceforge.net/updates/

it's my favorite and the best

Include headers when using SELECT INTO OUTFILE?

Since the 'include-headers' functionality doesn't seem to be build-in yet, and most "solutions" here need to type the columns names manually, and/or don't even take joins into account, I'd recommand to get around the problem.

  • The best alternative I found so far is using a decent tool (I use HeidiSQL).
    Put your request, select the grid, just right click and export to a file. It got all necessary options for a clean export, ans should handle most needs.

  • In the same idea, user3037511's approach works fine, and can be automated easily.
    Just launch your request with some command line to get your headers. You may get the data with a SELECT INTO OUTFILE... or by running your query without the limit, yours to choose.

    Note that output redirect to a file works like a charm on both Linux AND Windows.


This makes me want to highlight that 80% of the time, when I want to use SELECT FROM INFILE or SELECT INTO OUTFILE, I end-up using something else due to some limitations (here, the absence of a 'headers options', on an AWS-RDS, the missing rights, and so on.)

Hence, I don't exactly answer to the op's question... but it should answer his needs :)
EDIT : and to actually answer his question : no
As of 2017-09-07, you just can't include headers if you stick with the SELECT INTO OUTFILE command
:|

JBoss debugging in Eclipse

You need to define a Remote Java Application in the Eclipse debug configurations:

Open the debug configurations (select project, then open from menu run/debug configurations) Select Remote Java Application in the left tree and press "New" button On the right panel select your web app project and enter 8787 in the port field. Here is a link to a detailed description of this process.

When you start the remote debug configuration Eclipse will attach to the JBoss process. If successful the debug view will show the JBoss threads. There is also a disconnect icon in the toolbar/menu to stop remote debugging.

Non-numeric Argument to Binary Operator Error in R

Because your question is phrased regarding your error message and not whatever your function is trying to accomplish, I will address the error.

- is the 'binary operator' your error is referencing, and either CurrentDay or MA (or both) are non-numeric.

A binary operation is a calculation that takes two values (operands) and produces another value (see wikipedia for more). + is one such operator: "1 + 1" takes two operands (1 and 1) and produces another value (2). Note that the produced value isn't necessarily different from the operands (e.g., 1 + 0 = 1).

R only knows how to apply + (and other binary operators, such as -) to numeric arguments:

> 1 + 1
[1] 2
> 1 + 'one'
Error in 1 + "one" : non-numeric argument to binary operator

When you see that error message, it means that you are (or the function you're calling is) trying to perform a binary operation with something that isn't a number.

EDIT:

Your error lies in the use of [ instead of [[. Because Day is a list, subsetting with [ will return a list, not a numeric vector. [[, however, returns an object of the class of the item contained in the list:

> Day <- Transaction(1, 2)["b"]
> class(Day)
[1] "list"
> Day + 1
Error in Day + 1 : non-numeric argument to binary operator

> Day2 <- Transaction(1, 2)[["b"]]
> class(Day2)
[1] "numeric"
> Day2 + 1
[1] 3

Transaction, as you've defined it, returns a list of two vectors. Above, Day is a list contain one vector. Day2, however, is simply a vector.

AngularJS Folder Structure

After building a few applications, some in Symfony-PHP, some .NET MVC, some ROR, i've found that the best way for me is to use Yeoman.io with the AngularJS generator.

That's the most popular and common structure and best maintained.

And most importantly, by keeping that structure, it helps you separate your client side code and to make it agnostic to the server-side technology (all kinds of different folder structures and different server-side templating engines).

That way you can easily duplicate and reuse yours and others code.

Here it is before grunt build: (but use the yeoman generator, don't just create it!)

/app
    /scripts
            /controllers
            /directives
            /services
            /filters
            app.js
    /views
    /styles
    /img
    /bower_components
    index.html
bower.json

And after grunt build (concat, uglify, rev, etc...):

    /scripts
        scripts.min.js (all JS concatenated, minified and grunt-rev)
        vendor.min.js  (all bower components concatenated, minified and grunt-rev)
    /views
    /styles
        mergedAndMinified.css  (grunt-cssmin)
    /images
    index.html  (grunt-htmlmin)

TypeScript: correct way to do string equality?

The === is not for checking string equalit , to do so you can use the Regxp functions for example

if (x.match(y) === null) {
// x and y are not equal 
}

there is also the test function

How do I get first name and last name as whole name in a MYSQL query?

You can use a query to get the same:

SELECT CONCAT(FirstName , ' ' , MiddleName , ' ' , Lastname) AS Name FROM TableName;

Note: This query return if all columns have some value if anyone is null or empty then it will return null for all, means Name will return "NULL"

To avoid above we can use the IsNull keyword to get the same.

SELECT Concat(Ifnull(FirstName,' ') ,' ', Ifnull(MiddleName,' '),' ', Ifnull(Lastname,' ')) FROM TableName;

If anyone containing null value the ' ' (space) will add with next value.

Can you use if/else conditions in CSS?

This is a little extra info to the Boldewyn answer above.

Add some php code to do the if/else

if($x==1){
  print "<p class=\"normal\">Text</p>\n";
} else {
  print "<p class=\"active\">Text</p>\n";
}

DateTimeFormat in TypeScript

This should work...

var displayDate = new Date().toLocaleDateString();

alert(displayDate);

But I suspect you are trying it on something else, for example:

var displayDate = Date.now.toLocaleDateString(); // No!

alert(displayDate);

How to extract duration time from ffmpeg output?

I would just do this in C++ with a text file and extract the tokens. Why? I am not a linux terminal expert like the others.
To set it up I would do this in Linux..

ffmpeg -i 2>&1 | grep "" > mytext.txt

and then run some C++ app to get the data needed. Maybe extract all the important values and reformat it for further processing by using tokens. I will just have to work on my own solution and people will just make fun of me because I am a linux newbie and I do not like scripting too much.

MySQL Sum() multiple columns

SELECT student, SUM(mark1+mark2+mark3+....+markn) AS Total FROM your_table

How to export datagridview to excel using vb.net?

In design mode: Set DataGridView1 ClipboardCopyMode properties to EnableAlwaysIncludeHeaderText

or on the program code

DataGridView1.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText

In the run time select all cells content (Ctrl+A) and copy (Ctrl+C) and paste to the Excel Program. Let the Excel do the rest

Sorry for the inconvenient, I have been searching the method to print data directly from the datagridvew (create report from vb.net VB2012) and have not found the satisfaction result. Above code just my though, wondering if my applications user can rely on above simple step it will be nice and I could go ahead to next step on my program progress.

How to iterate over a TreeMap?

    //create TreeMap instance
    TreeMap treeMap = new TreeMap();

    //add key value pairs to TreeMap
    treeMap.put("1","One");
    treeMap.put("2","Two");
    treeMap.put("3","Three");

    /*
      get Collection of values contained in TreeMap using
      Collection values()        
    */
    Collection c = treeMap.values();

    //obtain an Iterator for Collection
    Iterator itr = c.iterator();

    //iterate through TreeMap values iterator
    while(itr.hasNext())
      System.out.println(itr.next());

or:

   for (Map.Entry<K,V> entry : treeMap.entrySet()) {
        V value = entry.getValue();
        K key = entry.getKey();
   }

or:

   // Use iterator to display the keys and associated values
   System.out.println("Map Values Before: ");
   Set keys = map.keySet();
   for (Iterator i = keys.iterator(); i.hasNext();) {
     Integer key = (Integer) i.next();
     String value = (String) map.get(key);
     System.out.println(key + " = " + value);
   }

How to check permissions of a specific directory?

Here is the short answer:

$ ls -ld directory

Here's what it does:

-d, --directory
    list directory entries instead of contents, and do not dereference symbolic links

You might be interested in manpages. That's where all people in here get their nice answers from.

refer to online man pages

Polygon Drawing and Getting Coordinates with Google Map API v3

to accomplish what you want, you must getPaths from the polygon. Paths will be an array of LatLng points. you get the elements of the array and split the LatLng pairs with the methods .lat and .lng in the function below, i have a redundant array corresponding to a polyline that marks the perimeter around the polygon.

saving is another story. you can then opt for many methods. you may save your list of points as a csv formatted string and export that to a file (easiest solution, by far). i highly recommend GPS TXT formats, like the ones (there are 2) readable by GPS TRACKMAKER (great free version software). if you are competent to save them to a database, that is a great solution (i do both, for redundancy).

function areaPerimeterParse(areaPerimeterPath) {
    var flag1stLoop = true;
    var areaPerimeterPathArray = areaPerimeterPath.getPath();
    var markerListParsedTXT = "Datum,WGS84,WGS84,0,0,0,0,0\r\n";

    var counter01 = 0;
    var jSpy = "";
    for (var j = 0;j<areaPerimeterPathArray.length;j++) {
        counter01++;
        jSpy += j+"  ";
        if (flag1stLoop) {
            markerListParsedTXT += 'TP,D,'+[ areaPerimeterPathArray.getAt(j).lat(), areaPerimeterPathArray.getAt(j).lng()].join(',')+',00/00/00,00:00:00,1'+'\r\n';
            flag1stLoop = false;
        } else {
            markerListParsedTXT += 'TP,D,'+[ areaPerimeterPathArray.getAt(j).lat(), areaPerimeterPathArray.getAt(j).lng()].join(',')+',00/00/00,00:00:00,0'+'\r\n';
        }

    }
    // last point repeats first point
    markerListParsedTXT += 'TP,D,'+[ areaPerimeterPathArray.getAt(0).lat(), areaPerimeterPathArray.getAt(0).lng()].join(',')+',00/00/00,00:00:00,0'+'\r\n';
    return markerListParsedTXT;
}

attention, the line that ends with ",1" (as opposed to ",0") starts a new polygon (this format allows you to save multiple polygons in the same file). i find TXT more human readable than the XML based formats GPX and KML.

The target principal name is incorrect. Cannot generate SSPI context

This is usually due to missing, incorrect or duplicated Service Principle Names (SPNs)

Steps to resolve:

  1. Confirm what AD account SQL Server is using
  2. Run the following command in Powershell or CMD in administrator mode (service account should not contain the domain)
setspn -L <ServiceAccountName> | Select-String <ServerName> | select line
  1. Make sure the returned output contains an SPN which is fully qualified, no fully qualified, with a port and without a port.

    Expected Output:

    Registered ServicePrincipalNames for CN=<ServiceAccountName>,OU=CSN Service Accounts,DC=<Domain>,DC=com: 
    MSSQLSvc/<ServerName>.<domain>.com:1433
    MSSQLSvc/<ServerName>:1433                                           
    MSSQLSvc/<ServerName>.<domain>.com
    MSSQLSvc/<ServerName>
    
  2. If you don't see all of the above, run the following command in PowerShell or CMD in admin mode (make sure to change the port if you don't use default 1433)

SETSPN -S  MSSQLSvc/<ServerName> <Domain>\<ServiceAccountName> 
SETSPN -S  MSSQLSvc/<ServerName>.<Domain> <Domain>\<ServiceAccountName> 
SETSPN -S  MSSQLSvc/<ServerName>:1433 <Domain>\<ServiceAccountName> 
SETSPN -S  MSSQLSvc/<ServerName>.<Domain>:1433 <Domain>\<ServiceAccountName>
  1. Once above is complete it normally takes a few minutes for DNS propagation

Also, if you get a message about duplicate SPNs found, you may want to delete them and recreate them

JQuery Datatables : Cannot read property 'aDataSort' of undefined

For me, the bug was in DataTables itself; The code for sorting in DataTables 1.10.9 will not check for bounds; thus if you use something like

order: [[1, 'asc']]

with an empty table, there is no row idx 1 -> this exception ensures. This happened as the data for the table was being fetched asynchronously. Initially, on page loading the dataTable gets initialized without data. It should be updated later as soon as the result data is fetched.

My solution:

// add within function _fnStringToCss( s ) in datatables.js
// directly after this line
// srcCol = nestedSort[i][0];

if(srcCol >= aoColumns.length) {
    continue;
}

// this line follows:
// aDataSort = aoColumns[ srcCol ].aDataSort;

How to perform .Max() on a property of all objects in a collection and return the object with maximum value

I believe that sorting by the column you want to get the MAX of and then grabbing the first should work. However, if there are multiple objects with the same MAX value, only one will be grabbed:

private void Test()
{
    test v1 = new test();
    v1.Id = 12;

    test v2 = new test();
    v2.Id = 12;

    test v3 = new test();
    v3.Id = 12;

    List<test> arr = new List<test>();
    arr.Add(v1);
    arr.Add(v2);
    arr.Add(v3);

    test max = arr.OrderByDescending(t => t.Id).First();
}

class test
{
    public int Id { get; set; }
}

Remove columns from dataframe where ALL values are NA

I hope this may also help. It could be made into a single command, but I found it easier for me to read by dividing it in two commands. I made a function with the following instruction and worked lightning fast.

naColsRemoval = function (DataTable) { na.cols = DataTable [ , .( which ( apply ( is.na ( .SD ) , 2 , all ) ) )] DataTable [ , unlist (na.cols) := NULL , with = F] }

.SD will allow to limit the verification to part of the table, if you wish, but it will take the whole table as

MYSQL Truncated incorrect DOUBLE value

Try replacing the AND with ,

UPDATE shop_category 
SET name = 'Secolul XVI - XVIII', name_eng = '16th to 18th centuries' 
WHERE category_id = 4768

The UPDATE Syntax shows comma should be used as the separator.

Is there a MessageBox equivalent in WPF?

In WPF it seems this code,

System.Windows.Forms.MessageBox.Show("Test");

is replaced with:

System.Windows.MessageBox.Show("Test");

MySQL JOIN with LIMIT 1 on joined table

Accepted answer by @goggin13 looks wrong. Other solutions provided to-date will work, but suffer from the n+1 problem and as such, suffer a performance hit.

n+1 problem: If there are 100 categories, then we would have to do 1 select to get the categories, then for each of the 100 categories returned, we would need to do a select to get the products in that category. So 101 SELECT queries would be performed.

My alternative solution solves the n+1 problem and consequently should be significantly more performant as only 2 selects are being performed.

SELECT
  *
FROM
    (SELECT c.id, c.title, p.id AS product_id, p.title
    FROM categories AS c
    JOIN products AS p ON c.id = p.category_id
    ORDER BY c.id ASC) AS a 
GROUP BY id;

How to check what version of jQuery is loaded?

My preference is:

console.debug("jQuery "+ (jQuery ? $().jquery : "NOT") +" loaded")

Result:

jQuery 1.8.0 loaded

How to convert list of numpy arrays into single numpy array?

In general you can concatenate a whole sequence of arrays along any axis:

numpy.concatenate( LIST, axis=0 )

but you do have to worry about the shape and dimensionality of each array in the list (for a 2-dimensional 3x5 output, you need to ensure that they are all 2-dimensional n-by-5 arrays already). If you want to concatenate 1-dimensional arrays as the rows of a 2-dimensional output, you need to expand their dimensionality.

As Jorge's answer points out, there is also the function stack, introduced in numpy 1.10:

numpy.stack( LIST, axis=0 )

This takes the complementary approach: it creates a new view of each input array and adds an extra dimension (in this case, on the left, so each n-element 1D array becomes a 1-by-n 2D array) before concatenating. It will only work if all the input arrays have the same shape—even along the axis of concatenation.

vstack (or equivalently row_stack) is often an easier-to-use solution because it will take a sequence of 1- and/or 2-dimensional arrays and expand the dimensionality automatically where necessary and only where necessary, before concatenating the whole list together. Where a new dimension is required, it is added on the left. Again, you can concatenate a whole list at once without needing to iterate:

numpy.vstack( LIST )

This flexible behavior is also exhibited by the syntactic shortcut numpy.r_[ array1, ...., arrayN ] (note the square brackets). This is good for concatenating a few explicitly-named arrays but is no good for your situation because this syntax will not accept a sequence of arrays, like your LIST.

There is also an analogous function column_stack and shortcut c_[...], for horizontal (column-wise) stacking, as well as an almost-analogous function hstack—although for some reason the latter is less flexible (it is stricter about input arrays' dimensionality, and tries to concatenate 1-D arrays end-to-end instead of treating them as columns).

Finally, in the specific case of vertical stacking of 1-D arrays, the following also works:

numpy.array( LIST )

...because arrays can be constructed out of a sequence of other arrays, adding a new dimension to the beginning.

How to make program go back to the top of the code instead of closing

write a for or while loop and put all of your code inside of it? Goto type programming is a thing of the past.

https://wiki.python.org/moin/ForLoop

How to disable/enable a button with a checkbox if checked

HTML

<input type="checkbox" id="checkme"/><input type="submit" name="sendNewSms" class="inputButton" id="sendNewSms" value=" Send " />

JS

var checker = document.getElementById('checkme');
var sendbtn = document.getElementById('sendNewSms');
checker.onchange = function() {
  sendbtn.disabled = !!this.checked;
};

DEMO

Best way to require all files from a directory in ruby?

Instead of concatenating paths like in some answers, I use File.expand_path:

Dir[File.expand_path('importers/*.rb', File.dirname(__FILE__))].each do |file|
  require file
end

Update:

Instead of using File.dirname you could do the following:

Dir[File.expand_path('../importers/*.rb', __FILE__)].each do |file|
  require file
end

Where .. strips the filename of __FILE__.

Visual Studio debugging/loading very slow

Yet another possible cause is pre-compilation of old projects that exist on the file system but have been removed or partially removed from visual studio.

I had a solution that was taking 3.5 minutes to load after a build, I had a look at the timestamps in Temporary ASP.NET Files and saw that the 3 minute delay was on a file in an old project. Had a look in VS & the project was "unavailable". Deleted it from VS, deleted from the file system, and now we're down to a sweet 8 seconds.

C# Ignore certificate errors?

This code worked for me. I had to add TLS2 because that's what the URL I am interested in was using.

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
ServicePointManager.ServerCertificateValidationCallback +=
    (sender, cert, chain, sslPolicyErrors) => { return true; };
using (var client = new HttpClient())
{
    client.BaseAddress = new Uri(UserDataUrl);
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new
      MediaTypeWithQualityHeaderValue("application/json"));
    Task<string> response = client.GetStringAsync(UserDataUrl);
    response.Wait();

    if (response.Exception != null)
    {
         return null;
    }

    return JsonConvert.DeserializeObject<UserData>(response.Result);
}

How to select ALL children (in any level) from a parent in jQuery?

I think you could do:

$('#google_translate_element').find('*').each(function(){
    $(this).unbind('click');
});

but it would cause a lot of overhead

What does Html.HiddenFor do?

And to consume the hidden ID input back on your Edit action method:

[HttpPost]
public ActionResult Edit(FormCollection collection)
{
    ViewModel.ID = Convert.ToInt32(collection["ID"]);
}

How do you underline a text in Android XML?

You can use the markup below, but note that if you set the textAllCaps to true the underline effect would be removed.

<resource>
    <string name="my_string_value">I am <u>underlined</u>.</string>
</resources>


Note

Using textAllCaps with a string (login_change_settings) that contains markup; the markup will be dropped by the caps conversion

The textAllCaps text transform will end up calling toString on the CharSequence, which has the net effect of removing any markup such as . This check looks for usages of strings containing markup that also specify textAllCaps=true.

Where should I put the CSS and Javascript code in an HTML webpage?

AS per my study in css place always inside .like:-

 <head>
  <link href="css/grid.css" rel="stylesheet" />
 </head>

and for script its depen :-

  1. If inside the script document. write present then it will be in the head tag.
  2. If script contain DEFER attribute, BECAUSE defer downloaded all in parallel

TypeScript enum to object array

Here's the simple function with correct typing I use

/**
 * Helper to produce an array of enum values.
 * @param enumeration Enumeration object.
 */
export function enumToArray<T, G extends keyof T = keyof T>(enumeration: T): T[G][] {
  // tslint:disable: comment-format

  // enum Colors {
  //   WHITE = 0,
  //   BLACK = 1,
  // }
  // Object.values(Colors) will produce ['WHITE', 'BLACK', 0, 1]

  // So, simply slice the second half
  const enumValues = Object.values(enumeration);
  return enumValues.slice(enumValues.length / 2, enumValues.length) as T[G][];
}

Usage example:

enum Colors {
  Red = 1,
  Blue = 2,
}
enumToArray(Colors)

Attempt to write a readonly database - Django w/ SELinux error

This issue is caused by SELinux. After setting file ownership just as you did, I hit this issue. The audit2why(1) tool can be used to diagnose SELinux denials from the log:

(django)[f22-4:www/django/demo] ftweedal% sudo audit2why -a
type=AVC msg=audit(1437490152.208:407): avc:  denied  { write }
      for  pid=20330 comm="httpd" name="db.sqlite3" dev="dm-1" ino=52036
      scontext=system_u:system_r:httpd_t:s0
      tcontext=unconfined_u:object_r:httpd_sys_content_t:s0
      tclass=file permissive=0
    Was caused by:
    The boolean httpd_unified was set incorrectly. 
    Description:
    Allow httpd to unified

    Allow access by executing:
    # setsebool -P httpd_unified 1

Sure enough, running sudo setsebool -P httpd_unified 1 resolved the issue.

Looking into what httpd_unified is for, I came across a fedora-selinux-list post which explains:

This Boolean is off by default, turning it on will allow all httpd executables to have full access to all content labeled with a http file context. Leaving it off makes sure that one httpd service can not interfere with another.

So turning on httpd_unified lets you circumvent the default behaviour that prevents multiple httpd instances on the same server - all running as user apache - messing with each others' stuff.

In my case, I am only running one httpd, so it was fine for me to turn on httpd_unified. If you cannot do this, I suppose some more fine-grained labelling is needed.

Get table column names in MySQL?

you can get the entire table structure using following simple command.

DESC TableName

or you can use following query.

SHOW COLUMNS FROM TableName

Creating a URL in the controller .NET MVC

If you need the full url (for instance to send by email) consider using one of the following built-in methods:

With this you create the route to use to build the url:

Url.RouteUrl("OpinionByCompany", new RouteValueDictionary(new{cid=newop.CompanyID,oid=newop.ID}), HttpContext.Request.Url.Scheme, HttpContext.Request.Url.Authority)

Here the url is built after the route engine determine the correct one:

Url.Action("Detail","Opinion",new RouteValueDictionary(new{cid=newop.CompanyID,oid=newop.ID}),HttpContext.Request.Url.Scheme, HttpContext.Request.Url.Authority)

In both methods, the last 2 parameters specifies the protocol and hostname.

Regards.

What is private bytes, virtual bytes, working set?

There is an interesting discussion here: http://social.msdn.microsoft.com/Forums/en-US/vcgeneral/thread/307d658a-f677-40f2-bdef-e6352b0bfe9e/ My understanding of this thread is that freeing small allocations are not reflected in Private Bytes or Working Set.

Long story short:

if I call

p=malloc(1000);
free(p);

then the Private Bytes reflect only the allocation, not the deallocation.

if I call

p=malloc(>512k);
free(p);

then the Private Bytes correctly reflect the allocation and the deallocation.

How to import a jar in Eclipse

  1. Right Click on the Project.
  2. Click on Build Path.
  3. Click On Configure Build Path.
  4. Under Libraries, Click on Add Jar or Add External Jar.

What's the difference between import java.util.*; and import java.util.Date; ?

Your program should work exactly the same with either import java.util.*; or import java.util.Date;. There has to be something else you did in between.

PHP: if !empty & empty

For several cases, or even just a few cases involving a lot of criteria, consider using a switch.

switch( true ){

    case ( !empty($youtube) && !empty($link) ):{
        // Nothing is empty...
        break;
    }

    case ( !empty($youtube) && empty($link) ):{
        // One is empty...
        break;
    }

    case ( empty($youtube) && !empty($link) ):{
        // The other is empty...
        break;
    }

    case ( empty($youtube) && empty($link) ):{
        // Everything is empty
        break;
    }

    default:{
        // Even if you don't expect ever to use it, it's a good idea to ALWAYS have a default.
        // That way if you change it, or miss a case, you have some default handler.
        break;
    }

}

If you have multiple cases that require the same action, you can stack them and omit the break; to flowthrough. Just maybe put a comment like /*Flowing through*/ so you're explicit about doing it on purpose.

Note that the { } around the cases aren't required, but they are nice for readability and code folding.

More about switch: http://php.net/manual/en/control-structures.switch.php

I can't access http://localhost/phpmyadmin/

Resolving same problem on Ubuntu 14.04, I use code:

    sudo ln -s /etc/phpmyadmin/apache.conf /etc/apache2/conf-enabled/phpmyadmin.conf
    sudo /etc/init.d/apache2 reload

it is because since Ubuntu 13, Apache loads configuration files from the /etc/apache2/conf-enabled directory.

Ubuntu Documentation

Oracle "Partition By" Keyword

The PARTITION BY clause sets the range of records that will be used for each "GROUP" within the OVER clause.

In your example SQL, DEPT_COUNT will return the number of employees within that department for every employee record. (It is as if you're de-nomalising the emp table; you still return every record in the emp table.)

emp_no  dept_no  DEPT_COUNT
1       10       3
2       10       3
3       10       3 <- three because there are three "dept_no = 10" records
4       20       2
5       20       2 <- two because there are two "dept_no = 20" records

If there was another column (e.g., state) then you could count how many departments in that State.

It is like getting the results of a GROUP BY (SUM, AVG, etc.) without the aggregating the result set (i.e. removing matching records).

It is useful when you use the LAST OVER or MIN OVER functions to get, for example, the lowest and highest salary in the department and then use that in a calculation against this records salary without a sub select, which is much faster.

Read the linked AskTom article for further details.

Convert JsonNode into POJO

If you're using org.codehaus.jackson, this has been possible since 1.6. You can convert a JsonNode to a POJO with ObjectMapper#readValue: http://jackson.codehaus.org/1.9.4/javadoc/org/codehaus/jackson/map/ObjectMapper.html#readValue(org.codehaus.jackson.JsonNode, java.lang.Class)


    ObjectMapper mapper = new ObjectMapper();
    JsonParser jsonParser = mapper.getJsonFactory().createJsonParser("{\"foo\":\"bar\"}");
    JsonNode tree = jsonParser.readValueAsTree();
    // Do stuff to the tree
    mapper.readValue(tree, Foo.class);

How to import csv file in PHP?

PHP > 5.3 use fgetcsv() or str_getcsv(). Couldn't be simpler.

Count number of rows per group and add result to original data frame

One simple line in base R:

df$count = table(interaction(df[, (c("name", "type"))]))[interaction(df[, (c("name", "type"))])]

Same in two lines, for clarity/efficiency:

fact = interaction(df[, (c("name", "type"))])
df$count = table(fact)[fact]

MySQL & Java - Get id of the last inserted value (JDBC)

Wouldn't you just change:

numero = stmt.executeUpdate(query);

to:

numero = stmt.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);

Take a look at the documentation for the JDBC Statement interface.

Update: Apparently there is a lot of confusion about this answer, but my guess is that the people that are confused are not reading it in the context of the question that was asked. If you take the code that the OP provided in his question and replace the single line (line 6) that I am suggesting, everything will work. The numero variable is completely irrelevant and its value is never read after it is set.

How do I return a proper success/error message for JQuery .ajax() using PHP?

Server side:

if (mysql_query($query)) {
    // ...
}
else {
    ajaxError(); 
}

Client side:

error: function() {
    alert("There was an error. Try again please!");
},
success: function(){
    alert("Thank you for subscribing!");
}

How to sync with a remote Git repository?

Assuming their updates are on master, and you are on the branch you want to merge the changes into.

git remote add origin https://github.com/<github-username>/<repo-name>.git
git pull origin master

Also note that you will then want to push the merge back to your copy of the repository:

git push origin master

Creating a new database and new connection in Oracle SQL Developer

Open Oracle SQLDeveloper

Right click on connection tab and select new connection

Enter HR_ORCL in connection name and HR for the username and password.

Specify localhost for your Hostname and enter ORCL for the SID.

Click Test.

The status of the connection Test Successfully.

The connection was not saved however click on Save button to save the connection. And then click on Connect button to connect your database.

The connection is saved and you see the connection list.

Split string into individual words Java

Use split() method

Eg:

String s = "I want to walk my dog";
String[] arr = s.split(" ");    

for ( String ss : arr) {
    System.out.println(ss);
}

Using iFrames In ASP.NET

try this

<iframe name="myIframe" id="myIframe" width="400px" height="400px" runat="server"></iframe>

Expose this iframe in the master page's codebehind:

public HtmlControl iframe
{
get
{
return this.myIframe;
}
}

Add the MasterType directive for the content page to strongly typed Master Page.

<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits=_Default" Title="Untitled Page" %>
<%@ MasterType VirtualPath="~/MasterPage.master" %>

In code behind

protected void Page_Load(object sender, EventArgs e)
{
this.Master.iframe.Attributes.Add("src", "some.aspx");
}

SQL QUERY replace NULL value in a row with a value from the previous known value

UPDATE TABLE
   SET number = (SELECT MAX(t.number)
                  FROM TABLE t
                 WHERE t.number IS NOT NULL
                   AND t.date < date)
 WHERE number IS NULL

Google Maps: How to create a custom InfoWindow?

EDIT After some hunting around, this seems to be the best option:

https://github.com/googlemaps/js-info-bubble/blob/gh-pages/examples/example.html

You can see a customised version of this InfoBubble that I used on Dive Seven, a website for online scuba dive logging. It looks like this:


There are some more examples here. They definitely don't look as nice as the example in your screenshot, however.

Regular Expression for any number greater than 0?

Another solution:

^[1-9]\d*$

\d equivalent to [0-9]

How do I run a spring boot executable jar in a Production environment?

Please note that since Spring Boot 1.3.0.M1, you are able to build fully executable jars using Maven and Gradle.

For Maven, just include the following in your pom.xml:

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <configuration>
        <executable>true</executable>
    </configuration>
</plugin>

For Gradle add the following snippet to your build.gradle:

springBoot {
    executable = true
}

The fully executable jar contains an extra script at the front of the file, which allows you to just symlink your Spring Boot jar to init.d or use a systemd script.

init.d example:

$ln -s /var/yourapp/yourapp.jar /etc/init.d/yourapp

This allows you to start, stop and restart your application like:

$/etc/init.d/yourapp start|stop|restart

Or use a systemd script:

[Unit]
Description=yourapp
After=syslog.target

[Service]
ExecStart=/var/yourapp/yourapp.jar
User=yourapp
WorkingDirectory=/var/yourapp
SuccessExitStatus=143

[Install]
WantedBy=multi-user.target

More information at the following links:

Force youtube embed to start in 720p

(This answer was updated, as the previous method using vq isn't recognized anymore.)

Specifying the height of the video will change the quality accordingly. example for html 5;

<iframe style='width:100%; height:800px;' src='https://www.youtube.com/embed/xxxxxxxx'></iframe>

If you don't want to hardcode the width and height you can add a class to the iframe for css media queries.

Tested on a working server + passes the w3.org nuhtml validator.

Passing parameters to click() & bind() event in jquery?

From where would you get these values? If they're from the button itself, you could just do

commentbtn.click(function() {
   alert(this.id);
});

If they're a variable in the binding scope, you can access them from without

var id = 1;
commentbtn.click(function() {
   alert(id);
});

If they're a variable in the binding scope, that might change before the click is called, you'll need to create a new closure

for(var i = 0; i < 5; i++) {
   $('#button'+i).click((function(id) {
      return function() {
         alert(id);
      };
   }(i)));
}

Execute the setInterval function without delay the first time

You can set a very small initial delay-time (e.g. 100) and set it to your desired delay-time within the function:

_x000D_
_x000D_
var delay = 100;_x000D_
_x000D_
function foo() {_x000D_
  console.log("Change initial delay-time to what you want.");_x000D_
  delay = 12000;_x000D_
  setTimeout(foo, delay);_x000D_
}
_x000D_
_x000D_
_x000D_

How to get < span > value?

Try this

var div = document.getElementById("test");
var spans = div.getElementsByTagName("span");

for(i=0;i<spans.length;i++)
{
  alert(spans[i].innerHTML);
}

Bulk Insert to Oracle using .NET

I'm loading 50,000 records in 15 or so seconds using Array Binding in ODP.NET

It works by repeatedly invoking a stored procedure you specify (and in which you can do updates/inserts/deletes), but it passes the multiple parameter values from .NET to the database in bulk.

Instead of specifying a single value for each parameter to the stored procedure you specify an array of values for each parameter.

Oracle passes the parameter arrays from .NET to the database in one go, and then repeatedly invokes the stored procedure you specify using the parameter values you specified.

http://www.oracle.com/technetwork/issue-archive/2009/09-sep/o59odpnet-085168.html

/Damian