Programs & Examples On #Kdevelop

Kdevelop is a IDE for C++ and Qt supporting cmake, qmake and custom makefiles. It also has plugins for PHP and Python languages.

How to retrieve raw post data from HttpServletRequest in java

We had a situation where IE forced us to post as text/plain, so we had to manually parse the parameters using getReader. The servlet was being used for long polling, so when AsyncContext::dispatch was executed after a delay, it was literally reposting the request empty handed.

So I just stored the post in the request when it first appeared by using HttpServletRequest::setAttribute. The getReader method empties the buffer, where getParameter empties the buffer too but stores the parameters automagically.

    String input = null;

    // we have to store the string, which can only be read one time, because when the
    // servlet awakens an AsyncContext, it reposts the request and returns here empty handed
    if ((input = (String) request.getAttribute("com.xp.input")) == null) {
        StringBuilder buffer = new StringBuilder();
        BufferedReader reader = request.getReader();

        String line;
        while((line = reader.readLine()) != null){
            buffer.append(line);
        }
        // reqBytes = buffer.toString().getBytes();

        input = buffer.toString();
        request.setAttribute("com.xp.input", input);
    }

    if (input == null) {
        response.setContentType("text/plain");
        PrintWriter out = response.getWriter();
        out.print("{\"act\":\"fail\",\"msg\":\"invalid\"}");
    }       

What is the best IDE for C Development / Why use Emacs over an IDE?

Emacs would be better if it had a text editor in it... :-)

Difference between @click and v-on:click Vuejs

They may look a bit different from normal HTML, but : and @ are valid chars for attribute names and all Vue.js supported browsers can parse it correctly. In addition, they do not appear in the final rendered markup. The shorthand syntax is totally optional, but you will likely appreciate it when you learn more about its usage later.

Source: official documentation.

Is it possible to declare two variables of different types in a for loop?

You can't declare multiple types in the initialization, but you can assign to multiple types E.G.

{
   int i;
   char x;
   for(i = 0, x = 'p'; ...){
      ...
   }
}

Just declare them in their own scope.

vuejs update parent data from child component

I agree with the event emitting and v-model answers for those above. However, I thought I would post what I found about components with multiple form elements that want to emit back to their parent since this seems one of the first articles returned by google.

I know the question specifies a single input, but this seemed the closest match and might save people some time with similar vue components. Also, no one has mentioned the .sync modifier yet.

As far as I know, the v-model solution is only suited to one input returning to their parent. I took a bit of time looking for it but Vue (2.3.0) documentation does show how to sync multiple props sent into the component back to the parent (via emit of course).

It is appropriately called the .sync modifier.

Here is what the documentation says:

In some cases, we may need “two-way binding” for a prop. Unfortunately, true two-way binding can create maintenance issues, because child components can mutate the parent without the source of that mutation being obvious in both the parent and the child.

That’s why instead, we recommend emitting events in the pattern of update:myPropName. For example, in a hypothetical component with a title prop, we could communicate the intent of assigning a new value with:

this.$emit('update:title', newTitle)

Then the parent can listen to that event and update a local data property, if it wants to. For example:

<text-document   
 v-bind:title="doc.title"  
 v-on:update:title="doc.title = $event"
></text-document>

For convenience, we offer a shorthand for this pattern with the .sync modifier:

<text-document v-bind:title.sync="doc.title"></text-document>

You can also sync multiple at a time by sending through an object. Check out the documentation here

COALESCE with Hive SQL

From Language DDL & UDF of Hive

NVL(value, default value) 

Returns default value if value is null else returns value

Fixed height and width for bootstrap carousel

To have a consistent flow of the images on different devices, you'd have to specify the width and height value for each carousel image item, for instance here in my example the image would take the full width but with a height of "400px" (you can specify your personal value instead)

<div class="item">
        <img src="image.jpg" style="width:100%; height: 400px;">
      </div>

How to mount the android img file under linux?

Another option would be to use the File Explorer in DDMS (Eclipse SDK), you can see the whole file system there and download/upload files to the desired place. That way you don't have to mount and deal with images. Just remember to set your device as USB debuggable (from Developer Tools)

length and length() in Java

Let me first highlight three different ways for similar purpose.

length -- arrays (int[], double[], String[]) -- to know the length of the arrays

length() -- String related Object (String, StringBuilder, etc) -- to know the length of the String

size() -- Collection Object (ArrayList, Set, etc) -- to know the size of the Collection

Now forget about length() consider just length and size().

length is not a method, so it completely makes sense that it will not work on objects. It only works on arrays.
size() its name describes it better and as it is a method, it will be used in the case of those objects who work with collection (collection frameworks) as I said up there.

Now come to length():
String is not a primitive array (so we can't use .length) and also not a Collection (so we cant use .size()) that's why we also need a different one which is length() (keep the differences and serve the purpose).

As answer to Why?
I find it useful, easy to remember and use and friendly.

Which MySQL data type to use for storing boolean values

Bit is only advantageous over the various byte options (tinyint, enum, char(1)) if you have a lot of boolean fields. One bit field still takes up a full byte. Two bit fields fit into that same byte. Three, four,five, six, seven, eight. After which they start filling up the next byte. Ultimately the savings are so small, there are thousands of other optimizations you should focus on. Unless you're dealing with an enormous amount of data, those few bytes aren't going to add up to much. If you're using bit with PHP you need to typecast the values going in and out.

C# elegant way to check if a property's property is null

I would write your own method in the type of PropertyA (or an extension method if it's not your type) using the similar pattern to the Nullable type.

class PropertyAType
{
   public PropertyBType PropertyB {get; set; }

   public PropertyBType GetPropertyBOrDefault()
   {
       return PropertyB != null ? PropertyB : defaultValue;
   }
}

Using Cygwin to Compile a C program; Execution error

Regarding the cygwin1.dll not found error, a solution I have used for at least 8 years is to add the Cygwin bin directories to the end of my %PATH% in My Computer -> Properties -> Advanced -> Environment Variables. I add them to the end of the path so in my normal work, they are searched last, minimizing the possibility of conflicts (in fact, I have had no problems with conflicts in all this time).

When you invoke the Cygwin Bash Shell, those directories get prepended to the %PATH% so everything works as intended in that environment as well.

When not running in Cygwin shell, my %PATH% is:

Path=c:\opt\perl\bin; \
     ...
     C:\opt\cygwin\bin; \
     C:\opt\cygwin\usr\bin; \
     C:\opt\cygwin\usr\local\bin;

This way, for example, ActiveState Perl's perl is found first when I am not in a Cygwin Shell, but the Cygwin perl is found when I am working in the Cygwin Shell.

String MinLength and MaxLength validation don't work (asp.net mvc)

They do now, with latest version of MVC (and jquery validate packages). mvc51-release-notes#Unobtrusive

Thanks to this answer for pointing it out!

Replace input type=file by an image

Working Code:

just hide input part and do like this.

<div class="ImageUpload">
   <label for="FileInput">
      <img src="../../img/Upload_Panel.png" style="width: 18px; margin-top: -316px; margin-left: 900px;"/>
   </label>

  <input id="FileInput" type="file" onchange="readURL(this,'Picture')" style="cursor: pointer;  display: none"/>
</div>

TypeError: coercing to Unicode: need string or buffer

For the less specific case (not just the code in the question - since this is one of the first results in Google for this generic error message. This error also occurs when running certain os command with None argument.

For example:

os.path.exists(arg)  
os.stat(arg)

Will raise this exception when arg is None.

MySQL: @variable vs. variable. What's the difference?

In MySQL, @variable indicates a user-defined variable. You can define your own.

SET @a = 'test';
SELECT @a;

Outside of stored programs, a variable, without @, is a system variable, which you cannot define yourself.

The scope of this variable is the entire session. That means that while your connection with the database exists, the variable can still be used.

This is in contrast with MSSQL, where the variable will only be available in the current batch of queries (stored procedure, script, or otherwise). It will not be available in a different batch in the same session.

How to access remote server with local phpMyAdmin client?

Follow this blog post. You can do it very easily. https://wadsashika.wordpress.com/2015/01/06/manage-remote-mysql-database-locally-using-phpmyadmin/

The file config.inc.php contains the configuration settings for your phpMyAdmin installation. It uses an array to store sets of config options for every server it can connect to and by default there is only one, your own machine, or localhost. In order to connect to another server, you would have to add another set of config options to the config array. You have to edit this configuration file.

First open config.inc.php file held in phpMyAdmin folder. In wamp server, you can find it in wamp\apps\phpmyadmin folder. Then add following part to that file.

$i++;
$cfg['Servers'][$i]['host']          = 'hostname/Ip Adress';
$cfg['Servers'][$i]['port']          = '';
$cfg['Servers'][$i]['socket']        = '';
$cfg['Servers'][$i]['connect_type']  = 'tcp';
$cfg['Servers'][$i]['extension']     = 'mysql';
$cfg['Servers'][$i]['compress']      = FALSE;
$cfg['Servers'][$i]['auth_type']     = 'config';
$cfg['Servers'][$i]['user']          = 'username';
$cfg['Servers'][$i]['password']      = 'password';

Let’s see what is the meaning of this variables.

$i++ :- Incrementing variable for each server
$cfg[‘Servers’][$i][‘host’] :- Server host name or IP adress
$cfg[‘Servers’][$i][‘port’] :- MySQL port (Leave a blank for default port. Default MySQL port is 3306)
$cfg[‘Servers’][$i][‘socket’] :- Path to the socket (Leave a blank for default socket)
$cfg[‘Servers’][$i][‘connect_type’] :- How to connect to MySQL server (‘tcp’ or ‘socket’)
$cfg[‘Servers’][$i][‘extension’] :- php MySQL extension to use (‘mysql’ or ‘msqli’)
$cfg[‘Servers’][$i][‘compress’] :- Use compressed protocol for the MySQL connection (requires PHP >= 4.3.0)
$cfg[‘Servers’][$i][‘auth_type’] :- Method of Authentication
$cfg[‘Servers’][$i][‘username’] :- Username to the MySQL database in remote server
$cfg[‘Servers’][$i][‘password’] :- Password to the MySQL database int he remote server

After adding this configuration part, restart you server and now your phpMyAdmin home page will change and it will show a field to select the server.

Now you can select you server and access your remote database by entering username and password for that database.

How does the "position: sticky;" property work?

I used a JS solution. It works in Firefox and Chrome. Any problems, let me know.

html

<body>
  <header id="header">
    <h1>Extra-Long Page Heading That Wraps</h1>
    <nav id="nav">
      <ul>
        <li><a href="" title="">Home</a></li>
        <li><a href="" title="">Page 2</a></li>
        <li><a href="" title="">Page 3</a></li>
      </ul>
    </nav>
  </header>
  <main>
    <p><!-- ridiculously long content --></p>
  </main>
  <footer>
    <p>FOOTER CONTENT</p>
  </footer>
  <script src="navbar.js" type="text/javascript"></script>
</body>

css

nav a {
    background: #aaa;
    font-size: 1.2rem;
    text-decoration: none;
    padding: 10px;
}

nav a:hover {
    background: #bbb;
}

nav li {
    background: #aaa;
    padding: 10px 0;

}

nav ul  {
    background: #aaa;
    list-style-type: none;
    margin: 0;
    padding: 0;

}

@media (min-width: 768px) {

    nav ul {
        display: flex;
    }
}

js

function applyNavbarSticky() {
    let header = document.querySelector('body > header:first-child')
    let navbar = document.querySelector('nav')
    header.style.position = 'sticky'

    function setTop() {
        let headerHeight = header.clientHeight
        let navbarHeight = navbar.clientHeight
        let styleTop = navbarHeight - headerHeight

        header.style.top = `${styleTop}px`
    }

    setTop()

    window.onresize = function () {
        setTop()
    }
}

Disable html5 video autoplay

Try adding autostart="false" to your source tag.

<video width="640" height="480" controls="controls" type="video/mp4" preload="none">
<source src="http://example.com/mytestfile.mp4" autostart="false">
Your browser does not support the video tag.
</video>

JSFiddle example

How to encode text to base64 in python

1) This works without imports in Python 2:

>>>
>>> 'Some text'.encode('base64')
'U29tZSB0ZXh0\n'
>>>
>>> 'U29tZSB0ZXh0\n'.decode('base64')
'Some text'
>>>
>>> 'U29tZSB0ZXh0'.decode('base64')
'Some text'
>>>

(although this doesn't work in Python3 )

2) In Python 3 you'd have to import base64 and do base64.b64decode('...') - will work in Python 2 too.

How can I verify a Google authentication API access token?

I need to somehow query Google and ask: Is this access token valid for [email protected]?

No. All you need is request standard login with Federated Login for Google Account Users from your API domain. And only after that you could compare "persistent user ID" with one you have from 'public interface'.

The value of realm is used on the Google Federated Login page to identify the requesting site to the user. It is also used to determine the value of the persistent user ID returned by Google.

So you need be from same domain as 'public interface'.

And do not forget that user needs to be sure that your API could be trusted ;) So Google will ask user if it allows you to check for his identity.

Get scroll position using jquery

cross browser variant

$(document).scrollTop();

How to simulate POST request?

Simple way is to use curl from command-line, for example:

DATA="foo=bar&baz=qux"
curl --data "$DATA" --request POST --header "Content-Type:application/x-www-form-urlencoded" http://example.com/api/callback | python -m json.tool

or here is example how to send raw POST request using Bash shell (JSON request):

exec 3<> /dev/tcp/example.com/80

DATA='{"email": "[email protected]"}'
LEN=$(printf "$DATA" | wc -c)

cat >&3 << EOF
POST /api/retrieveInfo HTTP/1.1
Host: example.com
User-Agent: Bash
Accept: */*
Content-Type:application/json
Content-Length: $LEN
Connection: close

$DATA
EOF

# Read response.
while read line <&3; do
   echo $line
done

How do I fetch only one branch of a remote Git repository?

git fetch <remote_name> <branch_name>

Worked for me.

Something better than .NET Reflector?

Instead of using the autoupdater, we just set the properties of the EXE file to read-only. That way it doesn’t delete the file.

how to remove the first two columns in a file using shell (awk, sed, whatever)

Thanks for posting the question. I'd also like to add the script that helped me.

awk '{ $1=""; print $0 }' file

Check line for unprintable characters while reading text file

While it's not hard to do this manually using BufferedReader and InputStreamReader, I'd use Guava:

List<String> lines = Files.readLines(file, Charsets.UTF_8);

You can then do whatever you like with those lines.

EDIT: Note that this will read the whole file into memory in one go. In most cases that's actually fine - and it's certainly simpler than reading it line by line, processing each line as you read it. If it's an enormous file, you may need to do it that way as per T.J. Crowder's answer.

Installing Pandas on Mac OSX

Write down this and try to import pandas again!

import sys
!{sys.executable} -m pip install pandas

It worked for me, hope will work for you too.

Inserting HTML into a div

I using "+" (plus) to insert div to html :

document.getElementById('idParent').innerHTML += '<div id="idChild"> content html </div>';

Hope this help.

Display current path in terminal only

If you just want to get the information of current directory, you can type:

pwd

and you don't need to use the Nautilus, or you can use a teamviewer software to remote connect to the computer, you can get everything you want.

Simple way to count character occurrences in a string

This is simple code, but of course a little bit slower.

String s = ...;
int countDollar = s.length()-s.replaceAll("\\$","").length();
int counta = s.length()-s.replaceAll("a","").length();

An even better answer is here in a duplicate question

LINQ syntax where string value is not null or empty

This won't fail on Linq2Objects, but it will fail for Linq2SQL, so I am assuming that you are talking about the SQL provider or something similar.

The reason has to do with the way that the SQL provider handles your lambda expression. It doesn't take it as a function Func<P,T>, but an expression Expression<Func<P,T>>. It takes that expression tree and translates it so an actual SQL statement, which it sends off to the server.

The translator knows how to handle basic operators, but it doesn't know how to handle methods on objects. It doesn't know that IsNullOrEmpty(x) translates to return x == null || x == string.empty. That has to be done explicitly for the translation to SQL to take place.

cannot open shared object file: No such file or directory

Copied from my answer here: https://stackoverflow.com/a/9368199/485088

Run ldconfig as root to update the cache - if that still doesn't help, you need to add the path to the file ld.so.conf (just type it in on its own line) or better yet, add the entry to a new file (easier to delete) in directory ld.so.conf.d.

How to link to specific line number on github

Don't just link to the line numbers! Be sure to use the canonical URL too. Otherwise when that file is updated, you'll have a URL that points to the wrong lines!

How to make a permanent link to the right lines:

Click on the line number you want (like line 18), and the URL in your browser will get a #L18 tacked onto the end. You literally click on the 18 at the left side, not the line of code. Looks like this:

line 18 selected

And now your browser's URL looks like this:

https://github.com/git/git/blob/master/README#L18

If you want multiple lines selected, simply hold down the shift key and click a second line number, like line 20. Looks like this:

enter image description here

And now your browser's URL looks like this:

https://github.com/git/git/blob/master/README#L18-L20

Here's the important part:

Now get the canonical url for that particular commit by pressing the y key. The URL in your browser will change to become something like this:

https://github.com/git/git/blob/5bdb7a78adf2a2656a1915e6fa656aecb45c1fc3/README#L18-L20

That link contains the actual SHA hash for that particular commit, rather than the current version of the file on master. That means that this link will work forever and not point to lines 18-20 of whatever future version of that file might contain.

Now bask in the glow of your new permanent link. ;-)

update 9/29/2017: As pointed out by @watashiSHUN, github has now made it easier to get the permanent link by providing a ... menu on the left after you select one or more lines. Please upvote @watashiSHUN's answer too.

GitHub permalink menu

update 3/25/2016: Case in point — in the example above, I referred to the "README" file in the URL. Those non-canonical urls actually worked when this answer was written. But now those urls no longer work since README was moved to README.md. But the canonical URL with SHA hash still works, just as expected.

Int division: Why is the result of 1/3 == 0?

The result is 0. Why is this, and how do I solve this problem?

TL;DR

You can solve it by doing:

double g = 1.0/3.0; 

or

double g = 1.0/3; 

or

double g = 1/3.0; 

or

double g = (double) 1 / 3;

The last of these options is required when you are using variables e.g. int a = 1, b = 3; double g = (double) a / b;.

A more completed answer

double g = 1 / 3;

This result in 0 because

  • first the dividend < divisor;
  • both variables are of type int therefore resulting in int (5.6.2. JLS) which naturally cannot represent the a floating point value such as 0.333333...
  • "Integer division rounds toward 0." 15.17.2 JLS

Why double g = 1.0/3.0; and double g = ((double) 1) / 3; work?

From Chapter 5. Conversions and Promotions one can read:

One conversion context is the operand of a numeric operator such as + or *. The conversion process for such operands is called numeric promotion. Promotion is special in that, in the case of binary operators, the conversion chosen for one operand may depend in part on the type of the other operand expression.

and 5.6.2. Binary Numeric Promotion

When an operator applies binary numeric promotion to a pair of operands, each of which must denote a value that is convertible to a numeric type, the following rules apply, in order:

If any operand is of a reference type, it is subjected to unboxing conversion (§5.1.8).

Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:

If either operand is of type double, the other is converted to double.

Otherwise, if either operand is of type float, the other is converted to float.

Otherwise, if either operand is of type long, the other is converted to long.

Otherwise, both operands are converted to type int.

Sending POST data without form

_x000D_
_x000D_
function redir(data) {_x000D_
  document.getElementById('redirect').innerHTML = '<form style="display:none;" position="absolute" method="post" action="location.php"><input id="redirbtn" type="submit" name="value" value=' + data + '></form>';_x000D_
  document.getElementById('redirbtn').click();_x000D_
}
_x000D_
<button onclick="redir('dataToBeSent');">Next Page</button>_x000D_
<div id="redirect"></div>
_x000D_
_x000D_
_x000D_

You can use this method which creates a new hidden form whose "data" is sent by "post" to "location.php" when a button[Next Page] is clicked.

use jQuery's find() on JSON object

For one dimension json you can use this:

function exist (json, modulid) {
    var ret = 0;
    $(json).each(function(index, data){
        if(data.modulId == modulid)
            ret++;
    })
    return ret > 0;
}

Dynamically Fill Jenkins Choice Parameter With Git Branches In a Specified Repo

Yes, I wrote a little groovy script which does the trick You should add a 'Dynamic Choice Parameter' to your job and customize the following groovy script to your needs :

#!/usr/bin/groovy

def gitURL = "git repo url"
def command = "git ls-remote --heads --tags ${gitURL}"

def proc = command.execute()
proc.waitFor()              

if ( proc.exitValue() != 0 ) {
   println "Error, ${proc.err.text}"
   System.exit(-1)
}

def text = proc.in.text
# put your version string match
def match = /<REGEX>/
def tags = []

text.eachMatch(match) { tags.push(it[1]) }
tags.unique()
tags.sort( { a, b ->
         def a1 = a.tokenize('._-')
         def b1 = b.tokenize('._-')
         try {
            for (i in 1..<[a1.size(), b1.size()].min()) { 
                 if (a1[i].toInteger() != b1[i].toInteger()) return a1[i].toInteger() <=> b1[i].toInteger()
            }
            return 1
         } catch (e) {
            return -1;
         }
} )
tags.reverse()

I my case the version string was in the following format X.X.X.X and could have user branches in the format X.X.X-username ,etc... So I had to write my own sort function. This was my first groovy script so if there are better ways of doing thing I would like to know.

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

You can extract a private key from a keystore with Java6 and OpenSSL. This all depends on the fact that both Java and OpenSSL support PKCS#12-formatted keystores. To do the extraction, you first use keytool to convert to the standard format. Make sure you use the same password for both files (private key password, not the keystore password) or you will get odd failures later on in the second step.

keytool -importkeystore -srckeystore keystore.jks \
    -destkeystore intermediate.p12 -deststoretype PKCS12

Next, use OpenSSL to do the extraction to PEM:

openssl pkcs12 -in intermediate.p12 -out extracted.pem -nodes

You should be able to handle that PEM file easily enough; it's plain text with an encoded unencrypted private key and certificate(s) inside it (in a pretty obvious format).

When you do this, take care to keep the files created secure. They contain secret credentials. Nothing will warn you if you fail to secure them correctly. The easiest method for securing them is to do all of this in a directory which doesn't have any access rights for anyone other than the user. And never put your password on the command line or in environment variables; it's too easy for other users to grab.

Removing MySQL 5.7 Completely

You need to remove the /var/lib/mysql folder. Also, purge when you remove the packages (I'm told this helps).

sudo apt-get remove --purge mysql-server mysql-client mysql-common

sudo rm -rf /var/lib/mysql

I was encountering similar issues. The second line got rid of my issues and allowed me to set up MySql from scratch. Hopefully it helps you too!

Struct inheritance in C++

Yes. The inheritance is public by default.

Syntax (example):

struct A { };
struct B : A { };
struct C : B { };

Multiple values in single-value context

Here's a generic helper function with assumption checking:

func assumeNoError(value interface{}, err error) interface{} {
    if err != nil {
        panic("error encountered when none assumed:" + err.Error())
    }
    return value
}

Since this returns as an interface{}, you'll generally need to cast it back to your function's return type.

For example, the OP's example called Get(1), which returns (Item, error).

item := assumeNoError(Get(1)).(Item)

The trick that makes this possible: Multi-values returned from one function call can be passed in as multi-variable arguments to another function.

As a special case, if the return values of a function or method g are equal in number and individually assignable to the parameters of another function or method f, then the call f(g(parameters_of_g)) will invoke f after binding the return values of g to the parameters of f in order.


This answer borrows heavily from existing answers, but none had provided a simple, generic solution of this form.

How do you get the Git repository's name in some Git repository?

Unfortunately, it seems that Git has no such command built in. But you can easily add it yourself with Git aliases and some shell magic.

As pointed out by this answer, you can use git rev-parse --show-toplevel to show the root of your current Git folder.

If you want to use this regularly, it's probably more convenient to define it as an alias. For this, used git config alias.root '!echo "$(git rev-parse --show-toplevel)"'. After this, you can use git root to see the root folder of the repository you're currently in.

If you want to use another subcommand name than root, simply replace the second part of alias.root in the above command with whatever you want.

For details on aliases in Git, see also the git config man page.

xls to csv converter

Maybe someone find this ready-to-use piece of code useful. It allows to create CSVs from all spreadsheets in Excel's workbook.

enter image description here

# -*- coding: utf-8 -*-
import xlrd
import csv
from os import sys

def csv_from_excel(excel_file):
    workbook = xlrd.open_workbook(excel_file)
    all_worksheets = workbook.sheet_names()
    for worksheet_name in all_worksheets:
        worksheet = workbook.sheet_by_name(worksheet_name)
        with open(u'{}.csv'.format(worksheet_name), 'wb') as your_csv_file:
            wr = csv.writer(your_csv_file, quoting=csv.QUOTE_ALL)
            for rownum in xrange(worksheet.nrows):
                wr.writerow([unicode(entry).encode("utf-8") for entry in worksheet.row_values(rownum)])

if __name__ == "__main__":
    csv_from_excel(sys.argv[1])

Bootstrap: align input with button

I tried above all and end-up with few changes which I would like to share. Here's the code which works for me (find the attached screenshot):

<div class="input-group">
    <input type="text" class="form-control" placeholder="Search text">
    <span class="input-group-btn" style="width:0;">
        <button class="btn btn-default" type="button">Go!</button>
    </span>
</div>

enter image description here

If you want to see it working, just use below code in you editor:

<html>
    <head>
        <link type='text/css' rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css' />
    </head>
    <body>
        <div class="container body-content">
            <div class="form-horizontal">
              <div class="input-group">
                  <input type="text" class="form-control" placeholder="Search text">
                  <span class="input-group-btn" style="width:0;">
                      <button class="btn btn-default" type="button">Go!</button>
                  </span>
              </div>
            </div>
        </div>
    </body>
</html>

Hope this helps.

Inserting data into a MySQL table using VB.NET

You need to open the connection first:

 SQLConnection.Open();

Remove and Replace Printed items

One way is to use ANSI escape sequences:

import sys
import time
for i in range(10):
    print("Loading" + "." * i)
    sys.stdout.write("\033[F") # Cursor up one line
    time.sleep(1)

Also sometimes useful (for example if you print something shorter than before):

sys.stdout.write("\033[K") # Clear to the end of line

using sql count in a case statement

Close... try:

select 
   Sum(case when rsp_ind = 0 then 1 Else 0 End) as 'New',
   Sum(case when rsp_ind = 1 then 1 else 0 end) as 'Accepted'
from tb_a

How to Validate Google reCaptcha on Form Submit

One issue I came up with that prevented these two files from working correctly was with my php.ini file for the website. Make sure this property is properly set, as follows:

allow_url_fopen = 

Right to Left support for Twitter Bootstrap 3

We Announce the AryaBootstrap,

The last version is based on bootstrap 4.3.1

AryaBootstrap is a bootstrap with dual layout align support and, used for LTR and RTL web design.

add "dir" to html, thats the only action you need to do.

Checkout the AryaBootstrap Website at: http://abs.aryavandidad.com/

AryaBootstrap at GitHub: https://github.com/mRizvandi/AryaBootstrap

How do I get a value of a <span> using jQuery?

$('#id span').text() is the answer!

TypeError: 'str' object cannot be interpreted as an integer

You have to convert input x and y into int like below.

x=int(x)
y=int(y)

Delete all rows in a table based on another table

Found this link useful

Copied from there

Oftentimes, one wants to delete some records from a table based on criteria in another table. How do you delete from one of those tables without removing the records in both table?

DELETE DeletingFromTable
     FROM DeletingFromTable INNER JOIN CriteriaTable
     ON DeletingFromTable.field_id = CriteriaTable.id
     WHERE CriteriaTable.criteria = "value";

The key is that you specify the name of the table to be deleted from as the SELECT. So, the JOIN and WHERE do the selection and limiting, while the DELETE does the deleting. You're not limited to just one table, though. If you have a many-to-many relationship (for instance, Magazines and Subscribers, joined by a Subscription) and you're removing a Subscriber, you need to remove any potential records from the join model as well.

 DELETE subscribers, subscriptions
     FROM subscribers INNER JOIN subscriptions 
       ON subscribers.id = subscriptions.subscriber_id
     INNER JOIN magazines 
       ON subscriptions.magazine_id = magazines.id
     WHERE subscribers.name='Wes';

Deleting records with a join could also be done with a LEFT JOIN and a WHERE to see if the joined table was NULL, so that you could remove records in one table that didn't have a match (like in preparation for adding a relationship.) Example post to come.

Converting string to tuple without splitting characters

Just in case someone comes here trying to know how to create a tuple assigning each part of the string "Quattro" and "TT" to an element of the list, it would be like this print tuple(a.split())

How can I trigger a Bootstrap modal programmatically?

If you are looking for a programmatical modal creation, you might love this:

http://nakupanda.github.io/bootstrap3-dialog/

Even though Bootstrap's modal provides a javascript way for modal creation, you still need to write modal's html markups first.

Enabling CORS in Cloud Functions for Firebase

If there are people like me out there: If you want to call the cloud function from the same project as the cloud function it self, you can init the firebase sdk and use onCall method. It will handle everything for you:

exports.newRequest = functions.https.onCall((data, context) => {
    console.log(`This is the received data: ${data}.`);
    return data;
})

Call this function like this:

// Init the firebase SDK first    
const functions = firebase.functions();
const addMessage = functions.httpsCallable(`newRequest`);

Firebase docs: https://firebase.google.com/docs/functions/callable

If you can't init the SDK here is the essence from the other suggestions:

jQuery-UI datepicker default date

Seeing that:

Set the date to highlight on first opening if the field is blank. Specify either an actual date via a Date object or as a string in the current dateFormat, or a number of days from today (e.g. +7) or a string of values and periods ('y' for years, 'm' for months, 'w' for weeks, 'd' for days, e.g. '+1m +7d'), or null for today.

If the current dateFormat is not recognized, you can still use the Date object using new Date(year, month, day)

In your example, this should work (I didn't test it) :

<script type="text/javascript">
$(function() {               
    $("#birthdate" ).datepicker({
        changeMonth: true,
        changeYear: true,
        yearRange: '1920:2010',
        dateFormat : 'dd-mm-yy',
        defaultDate: new Date(1985,01,01)
    });
});
</script>

jquery - disable click

If you're using jQuery versions 1.4.3+:

$('selector').click(false);

If not:

$('selector').click(function(){return false;});

What is setup.py?

setup.py is Python's answer to a multi-platform installer and make file.

If you’re familiar with command line installations, then make && make install translates to python setup.py build && python setup.py install.

Some packages are pure Python, and are only byte compiled. Others may contain native code, which will require a native compiler (like gcc or cl) and a Python interfacing module (like swig or pyrex).

Why doesn't os.path.join() work in this case?

Note that a similar issue can bite you if you use os.path.join() to include an extension that already includes a dot, which is what happens automatically when you use os.path.splitext(). In this example:

components = os.path.splitext(filename)
prefix = components[0]
extension = components[1]
return os.path.join("avatars", instance.username, prefix, extension)

Even though extension might be .jpg you end up with a folder named "foobar" rather than a file called "foobar.jpg". To prevent this you need to append the extension separately:

return os.path.join("avatars", instance.username, prefix) + extension

How to programmatically open the Permission Screen for a specific app on Android Marshmallow?

it is not possible to pragmatically get the permission... but ill suggest you to put that line of code in try{} catch{} which make your app unfortunately stop... and in catch body make a dialog box which will navigate the user to small tutorial to enable the draw over other apps permission... then on yes button click put this code...

 Intent callSettingIntent= new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
            startActivity(callSettingIntent);

this intent is to directly open the list of draw over other apps to manage permissions and then from here it is one click to the draw over other apps Permissions ... i know this is Not the answer you're looking for... but Im doing this in my apps...

UnicodeEncodeError: 'charmap' codec can't encode - character maps to <undefined>, print function

If you are using Windows command line to print the data, you should use

chcp 65001

This worked for me!

Linux: where are environment variables stored?

Type "set" and you will get a list of all the current variables. If you want something to persist put it in ~/.bashrc or ~/.bash_profile (if you're using bash)

Detecting a mobile browser

The best must be :

var isMobile = (/Mobile/i.test(navigator.userAgent));

But like like Yoav Barnea says...

// Seem legit
var isMobile = ('DeviceOrientationEvent' in window || 'orientation' in window);
// But with my Chrome on windows, DeviceOrientationEvent == fct()
if (/Windows NT|Macintosh|Mac OS X|Linux/i.test(navigator.userAgent)) isMobile = false;
// My android have "linux" too
if (/Mobile/i.test(navigator.userAgent)) isMobile = true;

After this 3 tests, i hope var isMobile is... ok

Maximum size of a varchar(max) variable

EDIT: After further investigation, my original assumption that this was an anomaly (bug?) of the declare @var datatype = value syntax is incorrect.

I modified your script for 2005 since that syntax is not supported, then tried the modified version on 2008. In 2005, I get the Attempting to grow LOB beyond maximum allowed size of 2147483647 bytes. error message. In 2008, the modified script is still successful.

declare @KMsg varchar(max); set @KMsg = REPLICATE('a',1024);
declare @MMsg varchar(max); set @MMsg = REPLICATE(@KMsg,1024);
declare @GMsg varchar(max); set @GMsg = REPLICATE(@MMsg,1024);
declare @GGMMsg varchar(max); set @GGMMsg = @GMsg + @GMsg + @MMsg;
select LEN(@GGMMsg)

Column/Vertical selection with Keyboard in SublimeText 3

I know notepad++ has a feature that lets you select blocks of text independent of line/column by holding control + alt + drag. So you can select just about any block of text you want.

C# Get a control's position on a form

You could walk up through the parents, noting their position within their parent, until you arrive at the Form.

Edit: Something like (untested):

public Point GetPositionInForm(Control ctrl)
{
   Point p = ctrl.Location;
   Control parent = ctrl.Parent;
   while (! (parent is Form))
   {
      p.Offset(parent.Location.X, parent.Location.Y);
      parent = parent.Parent;
   }
   return p;
}

QR Code encoding and decoding using zxing

If you really need to encode UTF-8, you can try prepending the unicode byte order mark. I have no idea how widespread the support for this method is, but ZXing at least appears to support it: http://code.google.com/p/zxing/issues/detail?id=103

I've been reading up on QR Mode recently, and I think I've seen the same practice mentioned elsewhere, but I've not the foggiest where.

How to use ng-repeat for dictionaries in AngularJs?

I would also like to mention a new functionality of AngularJS ng-repeat, namely, special repeat start and end points. That functionality was added in order to repeat a series of HTML elements instead of just a single parent HTML element.

In order to use repeater start and end points you have to define them by using ng-repeat-start and ng-repeat-end directives respectively.

The ng-repeat-start directive works very similar to ng-repeat directive. The difference is that is will repeat all the HTML elements (including the tag it's defined on) up to the ending HTML tag where ng-repeat-end is placed (including the tag with ng-repeat-end).

Sample code (from a controller):

// ...
$scope.users = {};
$scope.users["182982"] = {name:"John", age: 30};
$scope.users["198784"] = {name:"Antonio", age: 32};
$scope.users["119827"] = {name:"Stephan", age: 18};
// ...

Sample HTML template:

<div ng-repeat-start="(id, user) in users">
    ==== User details ====
</div>
<div>
    <span>{{$index+1}}. </span>
    <strong>{{id}} </strong>
    <span class="name">{{user.name}} </span>
    <span class="age">({{user.age}})</span>
</div>

<div ng-if="!$first">
   <img src="/some_image.jpg" alt="some img" title="some img" />
</div>
<div ng-repeat-end>
    ======================
</div>

Output would look similar to the following (depending on HTML styling):

==== User details ====
1.  119827 Stephan (18)
======================
==== User details ====
2.  182982 John (30)
[sample image goes here]
======================
==== User details ====
3.  198784 Antonio (32)
[sample image goes here]
======================

As you can see, ng-repeat-start repeats all HTML elements (including the element with ng-repeat-start). All ng-repeat special properties (in this case $first and $index) also work as expected.

System.Security.SecurityException when writing to Event Log

To give Network Service read permission on the EventLog/Security key (as suggested by Firenzi and royrules22) follow instructions from http://geekswithblogs.net/timh/archive/2005/10/05/56029.aspx

  1. Open the Registry Editor:
    1. Select Start then Run
    2. Enter regedt32 or regedit
  2. Navigate/expand to the following key:

    HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog\Security

  3. Right click on this entry and select Permissions

  4. Add the Network Service user

  5. Give it Read permission

UPDATE: The steps above are ok on developer machines, where you do not use deployment process to install application.
However if you deploy your application to other machine(s), consider to register event log sources during installation as suggested in SailAvid's and Nicole Calinoiu's answers.

I am using PowerShell function (calling in Octopus Deploy.ps1)

function Create-EventSources() {
    $eventSources = @("MySource1","MySource2" )
    foreach ($source in $eventSources) {
            if ([System.Diagnostics.EventLog]::SourceExists($source) -eq $false) {
                [System.Diagnostics.EventLog]::CreateEventSource($source, "Application")
            }
    }
}

How to save username and password in Git?

Attention: This method saves the credentials in plaintext on your PC's disk. Everyone on your computer can access it, e.g. malicious NPM modules.

Run

git config --global credential.helper store

then

git pull

provide a username and password and those details will then be remembered later. The credentials are stored in a file on the disk, with the disk permissions of "just user readable/writable" but still in plaintext.

If you want to change the password later

git pull

Will fail, because the password is incorrect, git then removes the offending user+password from the ~/.git-credentials file, so now re-run

git pull

to provide a new password so it works as earlier.

Placing an image to the top right corner - CSS

Position the div relatively, and position the ribbon absolutely inside it. Something like:

#content {
  position:relative;
}

.ribbon {
  position:absolute;
  top:0;
  right:0;
}

How to insert the current timestamp into MySQL database using a PHP insert query

This format is used to get current timestamp and stored in mysql

$date = date("Y-m-d H:i:s"); 

$update_query = "UPDATE db.tablename SET insert_time=".$date." WHERE username='" .$somename . "'"; 

How to set default Checked in checkbox ReactJS?

In the React rendering lifecycle, the value attribute on form elements will override the value in the DOM. With an uncontrolled component, you often want React to specify the initial value, but leave subsequent updates uncontrolled. To handle this case, you can specify a defaultValue or defaultChecked attribute instead of value.

        <input
          type="checkbox"
          defaultChecked={true}
        />

Or

React.createElement('input',{type: 'checkbox', defaultChecked: true});

Please checkout more details regarding defaultChecked for checkbox below: https://reactjs.org/docs/uncontrolled-components.html#default-values

How to get a div to resize its height to fit container?

I had the same issue, I resolved it using some javascript.

<script type="text/javascript">
 var theHeight = $("#PrimaryContent").height() + 100;
 $('#SecondaryContent').height(theHeight);
</script>

How to deal with page breaks when printing a large HTML table

I faced the same problem and search everywhere for a solution, at last, I fount something which works for me for every browsers.

html {
height: 0;
}

use this css or Instead of css you can have this javascript

$("html").height(0);

Hope this will work for you as well.

How to iterate over a TreeMap?

Just to point out the generic way to iterate over any map:

 private <K, V> void iterateOverMap(Map<K, V> map) {
    for (Map.Entry<K, V> entry : map.entrySet()) {
        System.out.println("key ->" + entry.getKey() + ", value->" + entry.getValue());
    }
    }

Trying to mock datetime.date.today(), but not working

You can mock datetime using this:

In the module sources.py:

import datetime


class ShowTime:
    def current_date():
        return datetime.date.today().strftime('%Y-%m-%d')

In your tests.py:

from unittest import TestCase, mock
import datetime


class TestShowTime(TestCase):
    def setUp(self) -> None:
        self.st = sources.ShowTime()
        super().setUp()

    @mock.patch('sources.datetime.date')
    def test_current_date(self, date_mock):
        date_mock.today.return_value = datetime.datetime(year=2019, month=10, day=1)
        current_date = self.st.current_date()
        self.assertEqual(current_date, '2019-10-01')

Get type of a generic parameter in Java with reflection

I noticed that many people lean towards the getGenericSuperclass() solution:

class RootGeneric<T> {
  public Class<T> persistentClass = (Class<T>)
    ((ParameterizedType)getClass().getGenericSuperclass())
      .getActualTypeArguments()[0];
}

However, this solution is error prone. It will not work properly if there are generics in the descendants. Consider this:

class Foo<S> extends RootGeneric<Integer> {}

class Bar extends Foo<Double> {}

Which type will Bar.persistentClass have? Class<Integer>? Nope, it will be Class<Double>. This will happen due to getClass() always returns the top most class, which is Bar in this case, and its generic super class is Foo<Double>. Hence, the argument type will be Double.

If you need a reliable solution which doesn't fail I can suggest two.

  1. Use Guava. It has a class that was made exactly for this purpose: com.google.common.reflect.TypeToken. It handles all the corner cases just fine and offers some more nice functionality. The downside is an extra dependency. Given you've used this class, your code would look simple and clear, like this:
class RootGeneric<T> {
  @SuppressWarnings("unchecked")
  public final Class<T> persistentClass = (Class<T>) (new TypeToken<T>(getClass()) {}.getType());
}
  1. Use the custom method below. It implements a significantly simplified logic similar to the Guava class, mentioned above. However, I'd not guarantee it's error prone. It does solve the problem with the generic descendants though.
abstract class RootGeneric<T> {
  @SuppressWarnings("unchecked")
  private Class<T> getTypeOfT() {
    Class<T> type = null;
    Class<?> iter = getClass();
    while (iter.getSuperclass() != null) {
      Class<?> next = iter.getSuperclass();
      if (next != null && next.isAssignableFrom(RootGeneric.class)) {
        type =
            (Class<T>)
                ((ParameterizedType) iter.getGenericSuperclass()).getActualTypeArguments()[0];
        break;
      }
      iter = next;
    }
    if (type == null) {
      throw new ClassCastException("Cannot determine type of T");
    }
    return type;
  }
}

Polymorphism vs Overriding vs Overloading

Polymorphism relates to the ability of a language to have different object treated uniformly by using a single interfaces; as such it is related to overriding, so the interface (or the base class) is polymorphic, the implementor is the object which overrides (two faces of the same medal)

anyway, the difference between the two terms is better explained using other languages, such as c++: a polymorphic object in c++ behaves as the java counterpart if the base function is virtual, but if the method is not virtual the code jump is resolved statically, and the true type not checked at runtime so, polymorphism include the ability for an object to behave differently depending on the interface used to access it; let me make an example in pseudocode:

class animal {
    public void makeRumor(){
        print("thump");
    }
}
class dog extends animal {
    public void makeRumor(){
        print("woff");
    }
}

animal a = new dog();
dog b = new dog();

a.makeRumor() -> prints thump
b.makeRumor() -> prints woff

(supposing that makeRumor is NOT virtual)

java doesn't truly offer this level of polymorphism (called also object slicing).

animal a = new dog(); dog b = new dog();

a.makeRumor() -> prints thump
b.makeRumor() -> prints woff

on both case it will only print woff.. since a and b is refering to class dog

How to compare DateTime without time via LINQ?

Try

var q = db.Games.Where(t => t.StartDate.Date >= DateTime.Now.Date).OrderBy(d => d.StartDate);

How to run DOS/CMD/Command Prompt commands from VB.NET?

I was inspired by Steve's answer but thought I'd add a bit of flare to it. I like to do the work up front of writing extension methods so later I have less work to do calling the method.

For example with the modified version of Steve's answer below, instead of making this call...

MyUtilities.RunCommandCom("DIR", "/W", true)

I can actually just type out the command and call it from my strings like this...

Directly in code.

Call "CD %APPDATA% & TREE".RunCMD()

OR

From a variable.

Dim MyCommand = "CD %APPDATA% & TREE"
MyCommand.RunCMD()

OR

From a textbox.

textbox.text.RunCMD(WaitForProcessComplete:=True)


Extension methods will need to be placed in a Public Module and carry the <Extension> attribute over the sub. You will also want to add Imports System.Runtime.CompilerServices to the top of your code file.

There's plenty of info on SO about Extension Methods if you need further help.


Extension Method

Public Module Extensions
''' <summary>
''' Extension method to run string as CMD command.
''' </summary>
''' <param name="command">[String] Command to run.</param>
''' <param name="ShowWindow">[Boolean](Default:False) Option to show CMD window.</param>
''' <param name="WaitForProcessComplete">[Boolean](Default:False) Option to wait for CMD process to complete before exiting sub.</param>
''' <param name="permanent">[Boolean](Default:False) Option to keep window visible after command has finished. Ignored if ShowWindow is False.</param>
<Extension>
Public Sub RunCMD(command As String, Optional ShowWindow As Boolean = False, Optional WaitForProcessComplete As Boolean = False, Optional permanent As Boolean = False)
    Dim p As Process = New Process()
    Dim pi As ProcessStartInfo = New ProcessStartInfo()
    pi.Arguments = " " + If(ShowWindow AndAlso permanent, "/K", "/C") + " " + command
    pi.FileName = "cmd.exe"
    pi.CreateNoWindow = Not ShowWindow
    If ShowWindow Then
        pi.WindowStyle = ProcessWindowStyle.Normal
    Else
        pi.WindowStyle = ProcessWindowStyle.Hidden
    End If
    p.StartInfo = pi
    p.Start()
    If WaitForProcessComplete Then Do Until p.HasExited : Loop
End Sub
End Module

What is the opposite of :hover (on mouse leave)?

No there is no explicit property for mouse leave in CSS.

You could use :hover on all the other elements except the item in question to achieve this effect. But Im not sure how practical that would be.

I think you have to look at a JS / jQuery solution.

When should use Readonly and Get only properties

A property that has only a getter is said to be readonly. Cause no setter is provided, to change the value of the property (from outside).

C# has has a keyword readonly, that can be used on fields (not properties). A field that is marked as "readonly", can only be set once during the construction of an object (in the constructor).

private string _name = "Foo"; // field for property Name;
private bool _enabled = false; // field for property Enabled;

public string Name{ // This is a readonly property.
  get {
    return _name;  
  }
}

public bool Enabled{ // This is a read- and writeable property.
  get{
    return _enabled;
  }
  set{
    _enabled = value;
  }
} 

MySQL VARCHAR size?

VARCHAR means that it's a variable-length character, so it's only going to take as much space as is necessary. But if you knew something about the underlying structure, it may make sense to restrict VARCHAR to some maximum amount.

For instance, if you were storing comments from the user, you may limit the comment field to only 4000 characters; if so, it doesn't really make any sense to make the sql table have a field that's larger than VARCHAR(4000).

http://dev.mysql.com/doc/refman/5.0/en/char.html

When must we use NVARCHAR/NCHAR instead of VARCHAR/CHAR in SQL Server?

You should use NVARCHAR anytime you have to store multiple languages. I believe you have to use it for the Asian languages but don't quote me on it.

Here's the problem if you take Russian for example and store it in a varchar, you will be fine so long as you define the correct code page. But let's say your using a default english sql install, then the russian characters will not be handled correctly. If you were using NVARCHAR() they would be handled properly.

Edit

Ok let me quote MSDN and maybee I was to specific but you don't want to store more then one code page in a varcar column, while you can you shouldn't

When you deal with text data that is stored in the char, varchar, varchar(max), or text data type, the most important limitation to consider is that only information from a single code page can be validated by the system. (You can store data from multiple code pages, but this is not recommended.) The exact code page used to validate and store the data depends on the collation of the column. If a column-level collation has not been defined, the collation of the database is used. To determine the code page that is used for a given column, you can use the COLLATIONPROPERTY function, as shown in the following code examples:

Here's some more:

This example illustrates the fact that many locales, such as Georgian and Hindi, do not have code pages, as they are Unicode-only collations. Those collations are not appropriate for columns that use the char, varchar, or text data type

So Georgian or Hindi really need to be stored as nvarchar. Arabic is also a problem:

Another problem you might encounter is the inability to store data when not all of the characters you wish to support are contained in the code page. In many cases, Windows considers a particular code page to be a "best fit" code page, which means there is no guarantee that you can rely on the code page to handle all text; it is merely the best one available. An example of this is the Arabic script: it supports a wide array of languages, including Baluchi, Berber, Farsi, Kashmiri, Kazakh, Kirghiz, Pashto, Sindhi, Uighur, Urdu, and more. All of these languages have additional characters beyond those in the Arabic language as defined in Windows code page 1256. If you attempt to store these extra characters in a non-Unicode column that has the Arabic collation, the characters are converted into question marks.

Something to keep in mind when you are using Unicode although you can store different languages in a single column you can only sort using a single collation. There are some languages that use latin characters but do not sort like other latin languages. Accents is a good example of this, I can't remeber the example but there was a eastern european language whose Y didn't sort like the English Y. Then there is the spanish ch which spanish users expet to be sorted after h.

All in all with all the issues you have to deal with when dealing with internalitionalization. It is my opinion that is easier to just use Unicode characters from the start, avoid the extra conversions and take the space hit. Hence my statement earlier.

Is there an equivalent of CSS max-width that works in HTML emails?

The short answer: no.

The long answer:

Fixed formats work better for HTML emails. In my experience you're best off pretending it's 1999 when it comes to HTML emails. Be explicit and use HTML attributes (width="650") where ever possible in your table definitions, not CSS (style="width:650px"). Use fixed widths, no percentages. A table width of 650 pixels wide is a safe bet. Use inline CSS to set text properties.

It's not a matter of what works in "HTML emails", but rather the plethora of email clients and their limited (and sometimes deliberately so in the case of Gmail, Hotmail etc) ability to render HTML.

Visual Studio 2010 shortcut to find classes and methods?

Left click on a method and press the F12 key to Go To Definition. Other Actions also available

DTO pattern: Best way to copy properties between two objects

I had an application that I needed to convert from a JPA entity to DTO, and I thought about it and finally came up using org.springframework.beans.BeanUtils.copyProperties for copying simple properties and also extending and using org.springframework.binding.convert.service.DefaultConversionService for converting complex properties.

In detail my service was something like this:

@Service("seedingConverterService")
public class SeedingConverterService extends DefaultConversionService implements ISeedingConverterService  {
    @PostConstruct
    public void init(){
        Converter<Feature,FeatureDTO> featureConverter = new Converter<Feature, FeatureDTO>() {

            @Override
            public FeatureDTO convert(Feature f) {
                FeatureDTO dto = new FeatureDTO();
                //BeanUtils.copyProperties(f, dto,"configurationModel");
                BeanUtils.copyProperties(f, dto);
                dto.setConfigurationModelId(f.getConfigurationModel()==null?null:f.getConfigurationModel().getId());
                return dto;
            }
        };

        Converter<ConfigurationModel,ConfigurationModelDTO> configurationModelConverter = new Converter<ConfigurationModel,ConfigurationModelDTO>() {
            @Override
            public ConfigurationModelDTO convert(ConfigurationModel c) {
                ConfigurationModelDTO dto = new ConfigurationModelDTO();
                //BeanUtils.copyProperties(c, dto, "features");
                BeanUtils.copyProperties(c, dto);
                dto.setAlgorithmId(c.getAlgorithm()==null?null:c.getAlgorithm().getId());
                List<FeatureDTO> l = c.getFeatures().stream().map(f->featureConverter.convert(f)).collect(Collectors.toList());
                dto.setFeatures(l);
                return dto;
            }
        };
        addConverter(featureConverter);
        addConverter(configurationModelConverter);
    }
}

How to get std::vector pointer to the raw data?

Take a pointer to the first element instead:

process_data (&something [0]);

How to capitalize the first letter in a String in Ruby

You can use mb_chars. This respects umlaute:

class String

  # Only capitalize first letter of a string
  def capitalize_first
    self[0] = self[0].mb_chars.upcase
    self
  end

end

Example:

"ümlaute".capitalize_first
#=> "Ümlaute"

Detect if an input has text in it using CSS -- on a page I am visiting and do not control?

You can use the :placeholder-shown pseudo class. Technically a placeholder is required, but you can use a space instead.

_x000D_
_x000D_
input:not(:placeholder-shown) {_x000D_
  border-color: green;_x000D_
}_x000D_
_x000D_
input:placeholder-shown {_x000D_
  border-color: red;_x000D_
}
_x000D_
<input placeholder="Text is required" />_x000D_
<input placeholder=" " value="This one is valid" />_x000D_
<input placeholder=" " />
_x000D_
_x000D_
_x000D_

how to draw smooth curve through N points using javascript HTML5 canvas?

I decide to add on, rather than posting my solution to another post. Below are the solution that I build, may not be perfect, but so far the output are good.

Important: it will pass through all the points!

If you have any idea, to make it better, please share to me. Thanks.

Here are the comparison of before after:

enter image description here

Save this code to HTML to test it out.

_x000D_
_x000D_
    <!DOCTYPE html>_x000D_
    <html>_x000D_
    <body>_x000D_
     <canvas id="myCanvas" width="1200" height="700" style="border:1px solid #d3d3d3;">Your browser does not support the HTML5 canvas tag.</canvas>_x000D_
     <script>_x000D_
      var cv = document.getElementById("myCanvas");_x000D_
      var ctx = cv.getContext("2d");_x000D_
    _x000D_
      function gradient(a, b) {_x000D_
       return (b.y-a.y)/(b.x-a.x);_x000D_
      }_x000D_
    _x000D_
      function bzCurve(points, f, t) {_x000D_
       //f = 0, will be straight line_x000D_
       //t suppose to be 1, but changing the value can control the smoothness too_x000D_
       if (typeof(f) == 'undefined') f = 0.3;_x000D_
       if (typeof(t) == 'undefined') t = 0.6;_x000D_
    _x000D_
       ctx.beginPath();_x000D_
       ctx.moveTo(points[0].x, points[0].y);_x000D_
    _x000D_
       var m = 0;_x000D_
       var dx1 = 0;_x000D_
       var dy1 = 0;_x000D_
    _x000D_
       var preP = points[0];_x000D_
       for (var i = 1; i < points.length; i++) {_x000D_
        var curP = points[i];_x000D_
        nexP = points[i + 1];_x000D_
        if (nexP) {_x000D_
         m = gradient(preP, nexP);_x000D_
         dx2 = (nexP.x - curP.x) * -f;_x000D_
         dy2 = dx2 * m * t;_x000D_
        } else {_x000D_
         dx2 = 0;_x000D_
         dy2 = 0;_x000D_
        }_x000D_
        ctx.bezierCurveTo(preP.x - dx1, preP.y - dy1, curP.x + dx2, curP.y + dy2, curP.x, curP.y);_x000D_
        dx1 = dx2;_x000D_
        dy1 = dy2;_x000D_
        preP = curP;_x000D_
       }_x000D_
       ctx.stroke();_x000D_
      }_x000D_
    _x000D_
      // Generate random data_x000D_
      var lines = [];_x000D_
      var X = 10;_x000D_
      var t = 40; //to control width of X_x000D_
      for (var i = 0; i < 100; i++ ) {_x000D_
       Y = Math.floor((Math.random() * 300) + 50);_x000D_
       p = { x: X, y: Y };_x000D_
       lines.push(p);_x000D_
       X = X + t;_x000D_
      }_x000D_
    _x000D_
      //draw straight line_x000D_
      ctx.beginPath();_x000D_
      ctx.setLineDash([5]);_x000D_
      ctx.lineWidth = 1;_x000D_
      bzCurve(lines, 0, 1);_x000D_
    _x000D_
      //draw smooth line_x000D_
      ctx.setLineDash([0]);_x000D_
      ctx.lineWidth = 2;_x000D_
      ctx.strokeStyle = "blue";_x000D_
      bzCurve(lines, 0.3, 1);_x000D_
     </script>_x000D_
    </body>_x000D_
    </html>
_x000D_
_x000D_
_x000D_

key_load_public: invalid format

In the case you copy your public key with clipboard and paste it, it may happen the public key string can be broken which contains new-line.

Make sure your public key string formed as one line.

Convert R vector to string vector of 1 element

Use the collapse argument to paste:

paste(a,collapse=" ")
[1] "aa bb cc"

How do you use the Immediate Window in Visual Studio?

One nice feature of the Immediate Window in Visual Studio is its ability to evaluate the return value of a method particularly if it is called by your client code but it is not part of a variable assignment. In Debug mode, as mentioned, you can interact with variables and execute expressions in memory which plays an important role in being able to do this.

For example, if you had a static method that returns the sum of two numbers such as:

private static int GetSum(int a, int b)
{
    return a + b;
}

Then in the Immediate Window you can type the following:

? GetSum(2, 4)
6

As you can seen, this works really well for static methods. However, if the method is non-static then you need to interact with a reference to the object the method belongs to.

For example, let’s say this is what your class looks like:

private class Foo
{
    public string GetMessage()
    {
        return "hello";
    }
}

If the object already exists in memory and it’s in scope, then you can call it in the Immediate Window as long as it has been instantiated before your current breakpoint (or, at least, before wherever the code is paused in debug mode):

? foo.GetMessage(); // object ‘foo’ already exists
"hello"

In addition, if you want to interact and test the method directly without relying on an existing instance in memory, then you can instantiate your own instance in the Immediate Window:

? Foo foo = new Foo(); // new instance of ‘Foo’
{temp.Program.Foo}
? foo.GetMessage()
"hello"

You can take it a step further and temporarily assign the method's results to variables if you want to do further evaluations, calculations, etc.:

? string msg = foo.GetMessage();
"hello"
? msg + " there!"
"hello there!"

Furthermore, if you don’t even want to declare a variable name for a new object and just want to run one of its methods/functions then do this:

? new Foo().GetMessage()
"hello" 

A very common way to see the value of a method is to select the method name of a class and do a ‘Add Watch’ so that you can see its current value in the Watch window. However, once again, the object needs to be instantiated and in scope for a valid value to be displayed. This is much less powerful and more restrictive than using the Immediate Window.

Along with inspecting methods, you can do simple math equations:

? 5 * 6
30

or compare values:

? 5==6
false
? 6==6
true

The question mark ('?') is unnecessary if you are in directly in the Immediate Window but it is included here for clarity (to distinguish between the typed in expressions versus the results.) However, if you are in the Command Window and need to do some quick stuff in the Immediate Window then precede your statements with '?' and off you go.

Intellisense works in the Immediate Window, but it sometimes can be a bit inconsistent. In my experience, it seems to be only available in Debug mode, but not in design, non-debug mode.

Unfortunately, another drawback of the Immediate Window is that it does not support loops.

Convert a dta file to csv without Stata software

Some mentioned SPSS, StatTransfer, they are not free. R and Python (also mentioned above) may be your choice. But personally, I would like to recommend Python, the syntax is much more intuitive than R. You can just use several command lines with Pandas in Python to read and export most of the commonly used data formats:

import pandas as pd

df = pd.read_stata('YourDataName.dta')

df.to_csv('YourDataName.csv')

Angular 2 How to redirect to 404 or other path if the path does not exist

For version v2.2.2 and newer

In version v2.2.2 and up, name property no longer exists and it shouldn't be used to define the route. path should be used instead of name and no leading slash is needed on the path. In this case use path: '404' instead of path: '/404':

 {path: '404', component: NotFoundComponent},
 {path: '**', redirectTo: '/404'}

For versions older than v2.2.2

you can use {path: '/*path', redirectTo: ['redirectPathName']}:

{path: '/home/...', name: 'Home', component: HomeComponent}
{path: '/', redirectTo: ['Home']},
{path: '/user/...', name: 'User', component: UserComponent},
{path: '/404', name: 'NotFound', component: NotFoundComponent},

{path: '/*path', redirectTo: ['NotFound']}

if no path matches then redirect to NotFound path

Rotate axis text in python matplotlib

To rotate the x-axis label to 90 degrees

for tick in ax.get_xticklabels():
    tick.set_rotation(45)

Smooth GPS data

Here's a Javascript implementation of @Stochastically's Java implementation for anyone needing it:

class GPSKalmanFilter {
  constructor (decay = 3) {
    this.decay = decay
    this.variance = -1
    this.minAccuracy = 1
  }

  process (lat, lng, accuracy, timestampInMs) {
    if (accuracy < this.minAccuracy) accuracy = this.minAccuracy

    if (this.variance < 0) {
      this.timestampInMs = timestampInMs
      this.lat = lat
      this.lng = lng
      this.variance = accuracy * accuracy
    } else {
      const timeIncMs = timestampInMs - this.timestampInMs

      if (timeIncMs > 0) {
        this.variance += (timeIncMs * this.decay * this.decay) / 1000
        this.timestampInMs = timestampInMs
      }

      const _k = this.variance / (this.variance + (accuracy * accuracy))
      this.lat += _k * (lat - this.lat)
      this.lng += _k * (lng - this.lng)

      this.variance = (1 - _k) * this.variance
    }

    return [this.lng, this.lat]
  }
}

Usage example:

   const kalmanFilter = new GPSKalmanFilter()
   const updatedCoords = []

    for (let index = 0; index < coords.length; index++) {
      const { lat, lng, accuracy, timestampInMs } = coords[index]
      updatedCoords[index] = kalmanFilter.process(lat, lng, accuracy, timestampInMs)
    }

How to import Swagger APIs into Postman?

  • Click on the orange button ("choose files")
  • Browse to the Swagger doc (swagger.yaml)
  • After selecting the file, a new collection gets created in POSTMAN. It will contain folders based on your endpoints.

You can also get some sample swagger files online to verify this(if you have errors in your swagger doc).

Change header text of columns in a GridView

You should do that in GridView's RowDataBound event which is triggered for every GridViewRow after it was databound.

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.Header)
    {
        e.Row.Cells[0].Text = "Date";
    }
}

or you can set AutogenerateColumns to false and add the columns declaratively on aspx:

<asp:gridview id="GridView1" 
  onrowdatabound="GridView1_RowDataBound"
  autogeneratecolumns="False"
  emptydatatext="No data available." 
   runat="server">
    <Columns>
         <asp:BoundField DataField="DateField" HeaderText="Date" 
            SortExpression="DateField" />
    </Columns>
</asp:gridview>

How to tell if JRE or JDK is installed

@maciej-cygan described the process well, however in order to find your java path:

$ which java

it gives you the path of java binary file which is a linked file in /usr/bin directory. next:

$ cd /usr/bin/ && ls -la | grep java

find the pointed location which is something as follows (for me):

enter image description here then cd to the pointed directory to find the real home directory for Java. next:

$ ls -la | grep java

which is as follows in this case:

enter image description here

so as it's obvious in the screenshot, my Java home directory is /usr/lib/jvm/java-11-openjdk-amd64. So accordingly I need to add JAVA_HOME to my bash profile (.bashrc, .bash_profile, etc. depending on your OS) like below:

JAVA_HOME="/usr/lib/jvm/java-11-openjdk-amd64"

Here you go!

log4net hierarchy and logging levels

Try like this, it worked for me

<root>
  <!--<level value="ALL" />-->
  <level value="ERROR" />
  <level value="INFO" />
  <level value="WARN" />     
</root>

This logs 3 types of errors - error, info, and warning

python how to "negate" value : if true return false, if false return true

Use the not boolean operator:

nyval = not myval

not returns a boolean value (True or False):

>>> not 1
False
>>> not 0
True

If you must have an integer, cast it back:

nyval = int(not myval)

However, the python bool type is a subclass of int, so this may not be needed:

>>> int(not 0)
1
>>> int(not 1)
0
>>> not 0 == 1
True
>>> not 1 == 0
True

Java: get all variable names in a class

As mentioned by few users, below code can help find all the fields in a given class.

TestClass testObject= new TestClass().getClass();
Method[] methods = testObject.getMethods();
for (Method method:methods)
{
    String name=method.getName();
    if(name.startsWith("get"))
    {
        System.out.println(name.substring(3));
    }else if(name.startsWith("is"))
    {
        System.out.println(name.substring(2));
    }
}

However a more interesting approach is below:

With the help of Jackson library, I was able to find all class properties of type String/integer/double, and respective values in a Map class. (without using reflections api!)

TestClass testObject = new TestClass();
com.fasterxml.jackson.databind.ObjectMapper m = new com.fasterxml.jackson.databind.ObjectMapper();

Map<String,Object> props = m.convertValue(testObject, Map.class);

for(Map.Entry<String, Object> entry : props.entrySet()){
    if(entry.getValue() instanceof String || entry.getValue() instanceof Integer || entry.getValue() instanceof Double){
        System.out.println(entry.getKey() + "-->" + entry.getValue());
    }
}

Where is the Postgresql config file: 'postgresql.conf' on Windows?

On my machine:

C:\Program Files (x86)\OpenERP 6.1-20121026-233219\PostgreSQL\data

If a folder does not exist, create it

As others have said, use System.IO.Directory.CreateDirectory.

But, you don't need to check if it exists first. From the documentation:

Any and all directories specified in path are created, unless they already exist or unless some part of path is invalid. If the directory already exists, this method does not create a new directory, but it returns a DirectoryInfo object for the existing directory.

Removing input background colour for Chrome autocomplete?

This will work for input, textarea and select in normal, hover, focus and active states.

input:-webkit-autofill,
input:-webkit-autofill:hover,
input:-webkit-autofill:focus,
input:-webkit-autofill:active,
textarea:-webkit-autofill,
textarea:-webkit-autofill:hover,
textarea:-webkit-autofill:focus,
textarea:-webkit-autofill:active,
select:-webkit-autofill,
select:-webkit-autofill:hover,
select:-webkit-autofill:focus,
select:-webkit-autofill:active,
{
    -webkit-box-shadow: 0 0 0px 1000px white inset !important;
}

Here is SCSS version of the above solution for those who are working with SASS/SCSS.

input:-webkit-autofill,
textarea:-webkit-autofill,
select:-webkit-autofill
{
    &, &:hover, &:focus, &:active
    {
        -webkit-box-shadow: 0 0 0px 1000px white inset !important;
    }
}

How to see local history changes in Visual Studio Code?

Basic Functionality

  • Automatically saved local edit history is available with the Local History extension.
  • Manually saved local edit history is available with the Checkpoints extension (this is the IntelliJ equivalent to adding tags to the local history).

Advanced Functionality

  • None of the extensions mentioned above support edit history when a file is moved or renamed.
  • The extensions above only support edit history. They do not support move/delete history, for example, like IntelliJ does.

Open Request

If you'd like to see this feature added natively, along with all of the advanced functionality, I'd suggest upvoting the open GitHub issue here.

Correct way of looping through C++ arrays

You can do it as follow:

#include < iostream >

using namespace std;

int main () {

   string texts[] = {"Apple", "Banana", "Orange"};

   for( unsigned int a = 0; a < sizeof(texts) / 32; a++ ) { // 32 is the size of string data type

       cout << "value of a: " << texts[a] << endl;

   }


   return 0;

}

tmux status bar configuration

I have been playing about with tmux today, trying to customised a little here and there, managed to get battery info displaying on the status right with a ruby script.

Copy the ruby script from http://natedickson.com/blog/2013/04/30/battery-status-in-tmux/ and save it as:

 battinfo.rb in ~/bin

To make it executable make sure to run:

chmod +x ~/bin/battinfo.rb

edit your ~/.tmux.config and include this line

set -g status-right "#[fg=colour155]#(pmset -g batt | ~/bin/battinfo.rb) | #[fg=colour45]%d %b %R"

PHP - SSL certificate error: unable to get local issuer certificate

Disclaimer: This code makes your server insecure.

I had the same problem in Mandrill.php file after line number 65 where it says $this->ch = curl_init();

Add following two lines:

curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, 0);

This solved my problem and also sent email using localhost but I suggest to NOT use it on live version live. On your live server the code should work without this code.

Polling the keyboard (detect a keypress) in python

I am using this for checking for key presses, can't get much simpler:

#!/usr/bin/python3
# -*- coding: UTF-8 -*-

import curses, time

def main(stdscr):
    """checking for keypress"""
    stdscr.nodelay(True)  # do not wait for input when calling getch
    return stdscr.getch()

while True:
    print("key:", curses.wrapper(main)) # prints: 'key: 97' for 'a' pressed
                                        # '-1' on no presses
    time.sleep(1)

While curses is not working on windows, there is a 'unicurses' version, supposedly working on Linux, Windows, Mac but I could not get this to work

C - reading command line parameters

There's also a C standard built-in library to get command line arguments: getopt

You can check it on Wikipedia or in Argument-parsing helpers for C/Unix.

Is it ok to scrape data from Google results?

Google will eventually block your IP when you exceed a certain amount of requests.

JavaFX Panel inside Panel auto resizing

After hours of searching and testing finally got it just after posting the question!

You can use the "AnchorPane.topAnchor, AnchorPane.bottomAnchor, AnchorPane.leftAnchor, AnchorPane.rightAnchor" fxml commands with the value "0.0" to fit/stretch/align the child elements inside a AnchorPane. So, these commands tell to child element to follow its parent while resizing.

My updated code Main.fxml

<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<AnchorPane fx:id="anchorPane" xmlns:fx="http://javafx.com/fxml" fx:controller="app.MainController">
    <!--<StackPane fx:id="stackPane" ></StackPane>--> <!-- replace with the following -->
    <StackPane fx:id="stackPane" AnchorPane.topAnchor="0.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" ></StackPane>
</AnchorPane>

Here is the result:

enter image description here

For api documentation: http://docs.oracle.com/javafx/2/api/javafx/scene/layout/AnchorPane.html

React Native TextInput that only accepts numeric characters

React Native TextInput provides keyboardType props with following possible values : default number-pad decimal-pad numeric email-address phone-pad

so for your case you can use keyboardType='number-pad' for accepting only numbers. This doesn't include '.'

so,

<TextInput 
  style={styles.textInput}
  keyboardType = 'number-pad'
  onChangeText = {(text)=> this.onChanged(text)}
  value = {this.state.myNumber}
/>

is what you have to use in your case.

for more details please refer the official doc link for TextInput : https://facebook.github.io/react-native/docs/textinput#keyboardtype

Change auto increment starting number?

You can use ALTER TABLE to change the auto_increment initial value:

ALTER TABLE tbl AUTO_INCREMENT = 5;

See the MySQL reference for more details.

How can I set the initial value of Select2 when using AJAX?

It's works for me ...

Don't use jQuery, only HTML: Create the option value you will display as selected. If ID it's in select2 data it will selected automatically.

<select id="select2" name="mySelect2">
  <option value="mySelectedValue">
        Hello, I'm here!
  </option>
</select>

Select2.org - Default Pre Selected values

Python Selenium accessing HTML source

from bs4 import BeautifulSoup
from selenium import webdriver

driver = webdriver.Chrome()
html_source_code = driver.execute_script("return document.body.innerHTML;")
html_soup: BeautifulSoup = BeautifulSoup(html_source_code, 'html.parser')

Now you can apply BeautifulSoup function to extract data...

What is the most efficient/elegant way to parse a flat table into a tree?

Now that MySQL 8.0 supports recursive queries, we can say that all popular SQL databases support recursive queries in standard syntax.

WITH RECURSIVE MyTree AS (
    SELECT * FROM MyTable WHERE ParentId IS NULL
    UNION ALL
    SELECT m.* FROM MyTABLE AS m JOIN MyTree AS t ON m.ParentId = t.Id
)
SELECT * FROM MyTree;

I tested recursive queries in MySQL 8.0 in my presentation Recursive Query Throwdown in 2017.

Below is my original answer from 2008:


There are several ways to store tree-structured data in a relational database. What you show in your example uses two methods:

  • Adjacency List (the "parent" column) and
  • Path Enumeration (the dotted-numbers in your name column).

Another solution is called Nested Sets, and it can be stored in the same table too. Read "Trees and Hierarchies in SQL for Smarties" by Joe Celko for a lot more information on these designs.

I usually prefer a design called Closure Table (aka "Adjacency Relation") for storing tree-structured data. It requires another table, but then querying trees is pretty easy.

I cover Closure Table in my presentation Models for Hierarchical Data with SQL and PHP and in my book SQL Antipatterns: Avoiding the Pitfalls of Database Programming.

CREATE TABLE ClosureTable (
  ancestor_id   INT NOT NULL REFERENCES FlatTable(id),
  descendant_id INT NOT NULL REFERENCES FlatTable(id),
  PRIMARY KEY (ancestor_id, descendant_id)
);

Store all paths in the Closure Table, where there is a direct ancestry from one node to another. Include a row for each node to reference itself. For example, using the data set you showed in your question:

INSERT INTO ClosureTable (ancestor_id, descendant_id) VALUES
  (1,1), (1,2), (1,4), (1,6),
  (2,2), (2,4),
  (3,3), (3,5),
  (4,4),
  (5,5),
  (6,6);

Now you can get a tree starting at node 1 like this:

SELECT f.* 
FROM FlatTable f 
  JOIN ClosureTable a ON (f.id = a.descendant_id)
WHERE a.ancestor_id = 1;

The output (in MySQL client) looks like the following:

+----+
| id |
+----+
|  1 | 
|  2 | 
|  4 | 
|  6 | 
+----+

In other words, nodes 3 and 5 are excluded, because they're part of a separate hierarchy, not descending from node 1.


Re: comment from e-satis about immediate children (or immediate parent). You can add a "path_length" column to the ClosureTable to make it easier to query specifically for an immediate child or parent (or any other distance).

INSERT INTO ClosureTable (ancestor_id, descendant_id, path_length) VALUES
  (1,1,0), (1,2,1), (1,4,2), (1,6,1),
  (2,2,0), (2,4,1),
  (3,3,0), (3,5,1),
  (4,4,0),
  (5,5,0),
  (6,6,0);

Then you can add a term in your search for querying the immediate children of a given node. These are descendants whose path_length is 1.

SELECT f.* 
FROM FlatTable f 
  JOIN ClosureTable a ON (f.id = a.descendant_id)
WHERE a.ancestor_id = 1
  AND path_length = 1;

+----+
| id |
+----+
|  2 | 
|  6 | 
+----+

Re comment from @ashraf: "How about sorting the whole tree [by name]?"

Here's an example query to return all nodes that are descendants of node 1, join them to the FlatTable that contains other node attributes such as name, and sort by the name.

SELECT f.name
FROM FlatTable f 
JOIN ClosureTable a ON (f.id = a.descendant_id)
WHERE a.ancestor_id = 1
ORDER BY f.name;

Re comment from @Nate:

SELECT f.name, GROUP_CONCAT(b.ancestor_id order by b.path_length desc) AS breadcrumbs
FROM FlatTable f 
JOIN ClosureTable a ON (f.id = a.descendant_id) 
JOIN ClosureTable b ON (b.descendant_id = a.descendant_id) 
WHERE a.ancestor_id = 1 
GROUP BY a.descendant_id 
ORDER BY f.name

+------------+-------------+
| name       | breadcrumbs |
+------------+-------------+
| Node 1     | 1           |
| Node 1.1   | 1,2         |
| Node 1.1.1 | 1,2,4       |
| Node 1.2   | 1,6         |
+------------+-------------+

A user suggested an edit today. SO moderators approved the edit, but I am reversing it.

The edit suggested that the ORDER BY in the last query above should be ORDER BY b.path_length, f.name, presumably to make sure the ordering matches the hierarchy. But this doesn't work, because it would order "Node 1.1.1" after "Node 1.2".

If you want the ordering to match the hierarchy in a sensible way, that is possible, but not simply by ordering by the path length. For example, see my answer to MySQL Closure Table hierarchical database - How to pull information out in the correct order.

Difference between iCalendar (.ics) and the vCalendar (.vcs)

You can try VCS to ICS file converter (Java, works with Windows, Mac, Linux etc.). It has the feature of parsing events and todos. You can convert the VCS generated by your Nokia phone, with bluetooth export or via nbuexplorer.

  • Complete support for UTF-8
  • Quoted-printable encoded strings
  • Completely open source code (GPLv3 and Apache 2.0)
  • Standard iCalendar v2.0 output
  • Encodes multiple files at once (only one event per file)
  • Compatible with Android, iOS, Mozilla Lightning/Sunbird, Google Calendar and others
  • Multiplatform

nginx - read custom header from upstream server

Use $http_MY_CUSTOM_HEADER

You can write some-thing like

set my_header $http_MY_CUSTOM_HEADER;
if($my_header != 'some-value') {
#do some thing;
}

Fill remaining vertical space - only CSS

Flexbox solution

_x000D_
_x000D_
html, body {_x000D_
  height: 100%;_x000D_
}_x000D_
_x000D_
.wrapper {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  width: 300px;_x000D_
  height: 100%;_x000D_
}_x000D_
_x000D_
.first {_x000D_
  height: 50px;_x000D_
}_x000D_
_x000D_
.second {_x000D_
  flex-grow: 1;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="first" style="background:#b2efd8">First</div>_x000D_
  <div class="second" style="background:#80c7cd">Second</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

nodejs get file name from absolute path?

In NodeJS, __filename.split(/\|//).pop() returns just the file name from the absolute file path on any OS platform. Why need to care about remembering/importing an API while this regex approach also letting us recollect our regex skills.

HTML img scaling

Adding max-width: 100%; to the img tag works for me.

Scroll / Jump to id without jQuery

on anchor tag use href and not onclick

<a href="#target1">asdf<a>

And div:

<div id="target1">some content</div>

Split array into two parts without for loop in java

You can use System.arraycopy().

int[] source = new int[1000];

int[] part1 = new int[500];
int[] part2 = new int[500];

//              (src   , src-offset  , dest , offset, count)
System.arraycopy(source, 0           , part1, 0     , part1.length);
System.arraycopy(source, part1.length, part2, 0     , part2.length);

Add a string of text into an input field when user clicks a button

Example for you to work from

HTML:

<input type="text" value="This is some text" id="text" style="width: 150px;" />
<br />
<input type="button" value="Click Me" id="button" />?

jQuery:

<script type="text/javascript">
$(function () {
    $('#button').on('click', function () {
        var text = $('#text');
        text.val(text.val() + ' after clicking');    
    });
});
<script>

Javascript

<script type="text/javascript">
document.getElementById("button").addEventListener('click', function () {
    var text = document.getElementById('text');
    text.value += ' after clicking';
});
</script>

Working jQuery example: http://jsfiddle.net/geMtZ/ ?

Lock down Microsoft Excel macro

Generate a protected application for Mac or Windows from your Excel spreadsheet using OfficeProtect with either AppProtect or QuickLicense/AddLicense. There is a demonstation video called "Protect Excel Spreedsheet" at www.excelsoftware.com/videos.

What's the difference between Cache-Control: max-age=0 and no-cache?

max-age
    When an intermediate cache is forced, by means of a max-age=0 directive, to revalidate 
its own cache entry, and the client has supplied its own validator in the request, the 
supplied validator might differ from the validator currently stored with the cache entry. 
In this case, the cache MAY use either validator in making its own request without 
affecting semantic transparency. 

    However, the choice of validator might affect performance. The best approach is for the 
intermediate cache to use its own validator when making its request. If the server replies 
with 304 (Not Modified), then the cache can return its now validated copy to the client 
with a 200 (OK) response. If the server replies with a new entity and cache validator, 
however, the intermediate cache can compare the returned validator with the one provided in 
the client's request, using the strong comparison function. If the client's validator is 
equal to the origin server's, then the intermediate cache simply returns 304 (Not 
Modified). Otherwise, it returns the new entity with a 200 (OK) response. 

    If a request includes the no-cache directive, it SHOULD NOT include min-fresh, 
max-stale, or max-age. 

courtesy: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9.4

Don't accept this as answer - I will have to read it to understand the true usage of it :)

How to format LocalDate to string?

SimpleDateFormat will not work if he is starting with LocalDate which is new in Java 8. From what I can see, you will have to use DateTimeFormatter, http://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html.

LocalDate localDate = LocalDate.now();//For reference
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd LLLL yyyy");
String formattedString = localDate.format(formatter);

That should print 05 May 1988. To get the period after the day and before the month, you might have to use "dd'.LLLL yyyy"

Convert hex string to int

The maximum value that a Java Integer can handle is 2147483657, or 2^31-1. The hexadecimal number AA0F245C is 2853119068 as a decimal number, and is far too large, so you need to use

Long.parseLong("AA0F245C", 16);

to make it work.

How to select only date from a DATETIME field in MySQL?

You can use select DATE(time) from appointment_details for date only

or

You can use select TIME(time) from appointment_details for time only

Cmake doesn't find Boost

If you are building your own boost do not forget to use the --layout=versioned otherwise the search for a particular version of library will fail

Hibernate Criteria Query to get specific columns

You can use JPQL as well as JPA Criteria API for any kind of DTO projection(Mapping only selected columns to a DTO class) . Look at below code snippets showing how to selectively select various columns instead of selecting all columns . These example also show how to select various columns from joining multiple columns . I hope this helps .

JPQL code :

String dtoProjection = "new com.katariasoft.technologies.jpaHibernate.college.data.dto.InstructorDto"
                + "(i.id, i.name, i.fatherName, i.address, id.proofNo, "
                + " v.vehicleNumber, v.vechicleType, s.name, s.fatherName, "
                + " si.name, sv.vehicleNumber , svd.name) ";

        List<InstructorDto> instructors = queryExecutor.fetchListForJpqlQuery(
                "select " + dtoProjection + " from Instructor i " + " join i.idProof id " + " join i.vehicles v "
                        + " join i.students s " + " join s.instructors si " + " join s.vehicles sv "
                        + " join sv.documents svd " + " where i.id > :id and svd.name in (:names) "
                        + " order by i.id , id.proofNo , v.vehicleNumber , si.name , sv.vehicleNumber , svd.name ",
                CollectionUtils.mapOf("id", 2, "names", Arrays.asList("1", "2")), InstructorDto.class);

        if (Objects.nonNull(instructors))
            instructors.forEach(i -> i.setName("Latest Update"));

        DataPrinters.listDataPrinter.accept(instructors);

JPA Criteria API code :

@Test
    public void fetchFullDataWithCriteria() {
        CriteriaBuilder cb = criteriaUtils.criteriaBuilder();
        CriteriaQuery<InstructorDto> cq = cb.createQuery(InstructorDto.class);

        // prepare from expressions
        Root<Instructor> root = cq.from(Instructor.class);
        Join<Instructor, IdProof> insIdProofJoin = root.join(Instructor_.idProof);
        Join<Instructor, Vehicle> insVehicleJoin = root.join(Instructor_.vehicles);
        Join<Instructor, Student> insStudentJoin = root.join(Instructor_.students);
        Join<Student, Instructor> studentInsJoin = insStudentJoin.join(Student_.instructors);
        Join<Student, Vehicle> studentVehicleJoin = insStudentJoin.join(Student_.vehicles);
        Join<Vehicle, Document> vehicleDocumentJoin = studentVehicleJoin.join(Vehicle_.documents);

        // prepare select expressions.
        CompoundSelection<InstructorDto> selection = cb.construct(InstructorDto.class, root.get(Instructor_.id),
                root.get(Instructor_.name), root.get(Instructor_.fatherName), root.get(Instructor_.address),
                insIdProofJoin.get(IdProof_.proofNo), insVehicleJoin.get(Vehicle_.vehicleNumber),
                insVehicleJoin.get(Vehicle_.vechicleType), insStudentJoin.get(Student_.name),
                insStudentJoin.get(Student_.fatherName), studentInsJoin.get(Instructor_.name),
                studentVehicleJoin.get(Vehicle_.vehicleNumber), vehicleDocumentJoin.get(Document_.name));

        // prepare where expressions.
        Predicate instructorIdGreaterThan = cb.greaterThan(root.get(Instructor_.id), 2);
        Predicate documentNameIn = cb.in(vehicleDocumentJoin.get(Document_.name)).value("1").value("2");
        Predicate where = cb.and(instructorIdGreaterThan, documentNameIn);

        // prepare orderBy expressions.
        List<Order> orderBy = Arrays.asList(cb.asc(root.get(Instructor_.id)),
                cb.asc(insIdProofJoin.get(IdProof_.proofNo)), cb.asc(insVehicleJoin.get(Vehicle_.vehicleNumber)),
                cb.asc(studentInsJoin.get(Instructor_.name)), cb.asc(studentVehicleJoin.get(Vehicle_.vehicleNumber)),
                cb.asc(vehicleDocumentJoin.get(Document_.name)));

        // prepare query
        cq.select(selection).where(where).orderBy(orderBy);
        DataPrinters.listDataPrinter.accept(queryExecutor.fetchListForCriteriaQuery(cq));

    }

ORA-28000: the account is locked error getting frequently

One of the reasons of your problem could be the password policy you are using.

And if there is no such policy of yours then check your settings for the password properties in the DEFAULT profile with the following query:

SELECT resource_name, limit
FROM dba_profiles 
WHERE profile = 'DEFAULT'
AND resource_type = 'PASSWORD';

And If required, you just need to change the PASSWORD_LIFE_TIME to unlimited with the following query:

ALTER PROFILE DEFAULT LIMIT PASSWORD_LIFE_TIME UNLIMITED;

And this Link might be helpful for your problem.

Jquery to get the id of selected value from dropdown

If you are trying to get the id, then please update your code like

  html += '<option id = "' + n.id + "' value="' + i + '">' + n.names + '</option>';

To retrieve id,

$('option:selected').attr("id")

To retrieve Value

$('option:selected').val()

in Javascript

var e = document.getElementById("jobSel");
var job = e.options[e.selectedIndex].value;

WebView and HTML5 <video>

mdelolmo's answer was incredibly helpful, but like he said, the video only plays once and then you can't open it again.

I looked into this a bit and here is what I found, in case any weary WebView travelers like myself stumble on this post in the future.

First off, I looked at the VideoView and MediaPlayer's documentation and got a better sense of how those work. I strongly recommend those.

Then, I looked at the source code to see how the Android Browser does it. Do a page find and go look at how they handle onShowCustomView(). They keep a reference to the CustomViewCallbackand to the custom view.

With all of that, and with mdelolmo's answer in mind, when you are done with the video, all you need to do is two things. First, on the VideoView that you saved a reference to, call stopPlayback() that will release the MediaPlayer to be used later elsewhere. You can see it in the VideoView source code. Second, on the CustomViewCallback you saved a reference to call CustomViewCallback.onCustomViewHidden().

After doing those two things, you can click on the same video or any other video and it will open like before. No need to restart the entire WebView.

Hope that helps.

Cannot find runtime 'node' on PATH - Visual Studio Code and Node.js

i resolved this problem after disable ESLint extention.

Remove last specific character in a string c#

The TrimEnd method takes an input character array and not a string. The code below from Dot Net Perls, shows a more efficient example of how to perform the same functionality as TrimEnd.

static string TrimTrailingChars(string value)
{
    int removeLength = 0;
    for (int i = value.Length - 1; i >= 0; i--)
    {
        char let = value[i];
        if (let == '?' || let == '!' || let == '.')
        {
            removeLength++;
        }
        else
        {
            break;
        }
    }
    if (removeLength > 0)
    {
        return value.Substring(0, value.Length - removeLength);
    }
    return value;
}

Drop primary key using script in SQL Server database

simply click

'Database'>tables>your table name>keys>copy the constraints like 'PK__TableName__30242045'

and run the below query is :

Query:alter Table 'TableName' drop constraint PK__TableName__30242045

How do I remove accents from characters in a PHP string?

If the main task is just to use the string in a URL, why not to use slugyfier?

composer require cocur/slugify

then

use Cocur\Slugify\Slugify;

$slugify = new Slugify();
echo $slugify->slugify('Fóø Bår');

It also has many bridges for popular frameworks. E.g. you can use Doctrine Extensions Sluggable behaviour to generate automatically unique slug for each entity in DB and use it in URL.

If you want just to wipe out all accents you can play around with rulesets to satisfy the requirements.

ERROR 1452: Cannot add or update a child row: a foreign key constraint fails

When you're using foreign key, your order of columns should be same for insertion.

For example, if you're adding (userid, password) in table1 from table2 then from table2 order should be same (userid, password) and not like (password,userid) where userid is foreign key in table2 of table1.

Need to make a clickable <div> button

Just use an <a> by itself, set it to display: block; and set width and height. Get rid of the <span> and <div>. This is the semantic way to do it. There is no need to wrap things in <divs> (or any element) for layout. That is what CSS is for.

Demo: http://jsfiddle.net/ThinkingStiff/89Enq/

HTML:

<a id="music" href="Music.html">Music I Like</a>

CSS:

#music {
    background-color: black;
    color: white;
    display: block;
    height: 40px;
    line-height: 40px;
    text-decoration: none;
    width: 100px;
    text-align: center;
}

Output:

enter image description here

Setting Windows PowerShell environment variables

Although the current accepted answer works in the sense that the path variable gets permanently updated from the context of PowerShell, it doesn't actually update the environment variable stored in the Windows registry.

To achieve that, you can obviously use PowerShell as well:

$oldPath=(Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH).Path

$newPath=$oldPath+’;C:\NewFolderToAddToTheList\’

Set-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH –Value $newPath

More information is in blog post Use PowerShell to Modify Your Environmental Path

If you use PowerShell community extensions, the proper command to add a path to the environment variable path is:

Add-PathVariable "C:\NewFolderToAddToTheList" -Target Machine

Deciding between HttpClient and WebClient

HttpClient is the newer of the APIs and it has the benefits of

  • has a good async programming model
  • being worked on by Henrik F Nielson who is basically one of the inventors of HTTP, and he designed the API so it is easy for you to follow the HTTP standard, e.g. generating standards-compliant headers
  • is in the .Net framework 4.5, so it has some guaranteed level of support for the forseeable future
  • also has the xcopyable/portable-framework version of the library if you want to use it on other platforms - .Net 4.0, Windows Phone etc.

If you are writing a web service which is making REST calls to other web services, you should want to be using an async programming model for all your REST calls, so that you don't hit thread starvation. You probably also want to use the newest C# compiler which has async/await support.

Note: It isn't more performant AFAIK. It's probably somewhat similarly performant if you create a fair test.

CSS word-wrapping in div

Setting just the width and float css properties would get a wrapping panel. The folowing example work just fine:

<div style="float:left; width: 250px">
Pellentesque feugiat tempor elit. Ut mollis lacinia quam. 
Sed pharetra, augue aliquam   ornare vestibulum, metus massa
laoreet tellus, eget iaculis lacus ipsum et diam. 
</div>

Maybe there are other styles in place that modify the appearance?

What does numpy.random.seed(0) do?

A random seed specifies the start point when a computer generates a random number sequence.

For example, let’s say you wanted to generate a random number in Excel (Note: Excel sets a limit of 9999 for the seed). If you enter a number into the Random Seed box during the process, you’ll be able to use the same set of random numbers again. If you typed “77” into the box, and typed “77” the next time you run the random number generator, Excel will display that same set of random numbers. If you type “99”, you’ll get an entirely different set of numbers. But if you revert back to a seed of 77, then you’ll get the same set of random numbers you started with.

For example, “take a number x, add 900 +x, then subtract 52.” In order for the process to start, you have to specify a starting number, x (the seed). Let’s take the starting number 77:

Add 900 + 77 = 977 Subtract 52 = 925 Following the same algorithm, the second “random” number would be:

900 + 925 = 1825 Subtract 52 = 1773 This simple example follows a pattern, but the algorithms behind computer number generation are much more complicated

What does it mean to have an index to scalar variable error? python

In my case, I was getting this error because I had an input named x and I was creating (without realizing it) a local variable called x. I thought I was trying to access an element of the input x (which was an array), while I was actually trying to access an element of the local variable x (which was a scalar).

How to get temporary folder for current user

try

Environment.GetEnvironmentVariable("temp");

Where are the recorded macros stored in Notepad++?

Notepad++ will forget your macros unless you map them to hotkeys via Settings - Shortcut mapper - Macros before exiting Notepad++ (as per https://superuser.com/questions/332481/how-can-i-add-a-macro-in-notepad. Tested with Notepad v6.8.3 on Windows7.)

Getting Python error "from: can't read /var/mail/Bio"

No, it's not the script, it's the fact that your script is not executed by Python at all. If your script is stored in a file named script.py, you have to execute it as python script.py, otherwise the default shell will execute it and it will bail out at the from keyword. (Incidentally, from is the name of a command line utility which prints names of those who have sent mail to the given username, so that's why it tries to access the mailboxes).

Another possibility is to add the following line to the top of the script:

#!/usr/bin/env python

This will instruct your shell to execute the script via python instead of trying to interpret it on its own.

Error - trustAnchors parameter must be non-empty

For me it got resolved just by upgrading a Jenkins plugin, "Email Extension Plugin", to the latest version (2.61).

These two plugins are responsible for email configuration in Jenkins:

  • Email Extension
  • Email Extension Template

How do I make a redirect in PHP?

Here are my thoughts:

IMHO, the best way to redirect an incoming request would be by using location headers, which goes

<?php
    header("Location: /index.php");
?>

Once this statement is executed, and output sent out, the browser will begin re-directing the user. However, ensure that there hasn't been any output (any echo / var_dump) before sending headers, else it will lead to errors.

Although this is a quick-and-dirty way to achieve what was originally asked, it would eventually turn out to be an SEO disaster, as this kind of redirect is always interpreted as a 301 / 302 redirect, hence search engines will always see your index page as a re-directed page, and not something of a landing page / main page.

Hence it will affect the SEO settings of the website.

How to make overlay control above all other controls?

<Canvas Panel.ZIndex="1" HorizontalAlignment="Left" VerticalAlignment="Top" Width="570">
  <!-- YOUR XAML CODE -->
</Canvas>

Visual Studio: ContextSwitchDeadlock

I was getting this error and switched the queries to async (await (...).ToListAsync()). All good now.

How do I run a batch file from my Java Application?

To run batch files using java if that's you're talking about...

String path="cmd /c start d:\\sample\\sample.bat";
Runtime rn=Runtime.getRuntime();
Process pr=rn.exec(path);`

This should do it.

require_once :failed to open stream: no such file or directory

set_include_path(get_include_path() . $_SERVER["DOCUMENT_ROOT"] . "/mysite/php/includes/");

Also this can help.See set_include_path()

How to change column width in DataGridView?

In my Visual Studio 2019 it worked only after I set the AutoSizeColumnsMode property to None.

Search input with an icon Bootstrap 4

Here's a fairly simple way to achieve it by enclosing both the magnifying glass icon and the input field inside a div with relative positioning.

Absolute positioning is applied to the icon, which takes it out of the normal document layout flow. The icon is then positioned inside the input. Left padding is applied to the input so that the user's input appears to the right of the icon.

Note that this example places the magnifying glass icon on the left instead of the right. This is recommended when using <input type="search"> as Chrome adds an X button in the right side of the searchbox. If we placed the icon there it would overlay the X button and look fugly.

Here is the needed Bootstrap markup.

<div class="position-relative">
    <i class="fa fa-search position-absolute"></i>
    <input class="form-control" type="search">
</div>

...and a couple CSS classes for the things which I couldn't do with Bootstrap classes:

i {
    font-size: 1rem;
    color: #333;
    top: .75rem;
    left: .75rem
}

input {
    padding-left: 2.5rem;
}

You may have to fiddle with the values for top, left, and padding-left.

How to get commit history for just one branch?

I think an option for your purposes is git log --online --decorate. This lets you know the checked commit, and the top commits for each branch that you have in your story line. By doing this, you have a nice view on the structure of your repo and the commits associated to a specific branch. I think reading this might help.

How do I get the list of keys in a Dictionary?

Marc Gravell's answer should work for you. myDictionary.Keys returns an object that implements ICollection<TKey>, IEnumerable<TKey> and their non-generic counterparts.

I just wanted to add that if you plan on accessing the value as well, you could loop through the dictionary like this (modified example):

Dictionary<string, int> data = new Dictionary<string, int>();
data.Add("abc", 123);
data.Add("def", 456);

foreach (KeyValuePair<string, int> item in data)
{
    Console.WriteLine(item.Key + ": " + item.Value);
}

How to embed fonts in CSS?

One of the best source of information on this topic is Paul Irish's Bulletproof @font-face syntax article.

Read it and you will end with something like:

/* definition */
@font-face {
  font-family: EntezareZohoor2;
  src: url('fonts/EntezareZohoor2.eot');
  src: url('fonts/EntezareZohoor2.eot?') format('?'),
       url('fonts/EntezareZohoor2.woff') format('woff'),
       url('fonts/EntezareZohoor2.ttf') format('truetype');
  font-weight: normal;
  font-style: normal;
}

/* use */
body {
    font-family: EntezareZohoor2, Tahoma, serif;
}

How do I use method overloading in Python?

You can also use pythonlangutil:

from pythonlangutil.overload import Overload, signature

class A:
    @Overload
    @signature()
    def stackoverflow(self):    
        print 'first method'

    @stackoverflow.overload
    @signature("int")
    def stackoverflow(self, i):
        print 'second method', i

How do I do an initial push to a remote repository with Git?

@Josh Lindsey already answered perfectly fine. But I want to add some information since I often use ssh.

Therefore just change:

git remote add origin [email protected]:/path/to/my_project.git

to:

git remote add origin ssh://[email protected]/path/to/my_project

Note that the colon between domain and path isn't there anymore.

No server in Eclipse; trying to install Tomcat

The Web Tools Platform provides the Java EE development tools, and is included in the IDE for Java EE Developers. Among other things, it provides the Servers view and makes it easy to launch a Tomcat server from there. You can either download the IDE for Java EE Developers, or go to the Help menu and Install New Software, looking for the Java EE features.

Pad a string with leading zeros so it's 3 characters long in SQL Server 2008

Try this with fixed length.

select right('000000'+'123',5)

select REPLICATE('0', 5 - LEN(123)) + '123'

Easy way to dismiss keyboard?

Subclass your textfields... and also textviews

In the subclass put this code..

-(void)conformsToKeyboardDismissNotification{

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dismissKeyBoard) name:KEYBOARD_DISMISS object:nil];
}

-(void)deConformsToKeyboardDismissNotification{

    [[NSNotificationCenter defaultCenter] removeObserver:self name:KEYBOARD_DISMISS object:nil];
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self resignFirstResponder];
}

In the textfield delegates (similarly for textview delegates)

-(void)textFieldDidBeginEditing:(JCPTextField *)textField{
     [textField conformsToKeyboardDismissNotification];
}


- (void)textFieldDidEndEditing:(JCPTextField *)textField{
    [textField deConformsToKeyboardDismissNotification];
}

All set.. Now just post the notification from anywhere in your code. It will resign any keyboard.

What are Makefile.am and Makefile.in?

Simple example

Shamelessly adapted from: http://www.gnu.org/software/automake/manual/html_node/Creating-amhello.html and tested on Ubuntu 14.04 Automake 1.14.1.

Makefile.am

SUBDIRS = src
dist_doc_DATA = README.md

README.md

Some doc.

configure.ac

AC_INIT([automake_hello_world], [1.0], [[email protected]])
AM_INIT_AUTOMAKE([-Wall -Werror foreign])
AC_PROG_CC
AC_CONFIG_HEADERS([config.h])
AC_CONFIG_FILES([
 Makefile
 src/Makefile
])
AC_OUTPUT

src/Makefile.am

bin_PROGRAMS = autotools_hello_world
autotools_hello_world_SOURCES = main.c

src/main.c

#include <config.h>
#include <stdio.h>

int main (void) {
  puts ("Hello world from " PACKAGE_STRING);
  return 0;
}

Usage

autoreconf --install
mkdir build
cd build
../configure
make
sudo make install
autoconf_hello_world
sudo make uninstall

This outputs:

Hello world from automake_hello_world 1.0

Notes

  • autoreconf --install generates several template files which should be tracked by Git, including Makefile.in. It only needs to be run the first time.

  • make install installs:

    • the binary to /usr/local/bin
    • README.md to /usr/local/share/doc/automake_hello_world

On GitHub for you to try it out.

Making href (anchor tag) request POST instead of GET?

Using jQuery it is very simple assuming the URL you wish to post to is on the same server or has implemented CORS

$(function() {
  $("#employeeLink").on("click",function(e) {
    e.preventDefault(); // cancel the link itself
    $.post(this.href,function(data) {
      $("#someContainer").html(data);
    });
  });
});

If you insist on using frames which I strongly discourage, have a form and submit it with the link

<form action="employee.action" method="post" target="myFrame" id="myForm"></form>

and use (in plain JS)

 window.addEventListener("load",function() {
   document.getElementById("employeeLink").addEventListener("click",function(e) {
     e.preventDefault(); // cancel the link
     document.getElementById("myForm").submit(); // but make sure nothing has name or ID="submit"
   });
 });

Without a form we need to make one

 window.addEventListener("load",function() {
   document.getElementById("employeeLink").addEventListener("click",function(e) {
     e.preventDefault(); // cancel the actual link
     var myForm = document.createElement("form");
     myForm.action=this.href;// the href of the link
     myForm.target="myFrame";
     myForm.method="POST";
     myForm.submit();
   });
 });

C# getting the path of %AppData%

The path is different if you're talking ASP.NET.

I couldn't find any of the 'SpecialFolder' values that pointed to /App_Data for ASP.NET.

Instead you need to do this:

 HttpContext.Current.ApplicationInstance.Server.MapPath("~/App_Data")  

(Note: You don't need the 'Current' property in an MVC Controller)

If theres another more 'abstract' way to get to App_Data would love to hear how.

What is the function __construct used for?

__construct() is the method name for the constructor. The constructor is called on an object after it has been created, and is a good place to put initialisation code, etc.

class Person {

    public function __construct() {
        // Code called for each new Person we create
    }

}

$person = new Person();

A constructor can accept parameters in the normal manner, which are passed when the object is created, e.g.

class Person {

    public $name = '';

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

}

$person = new Person( "Joe" );
echo $person->name;

Unlike some other languages (e.g. Java), PHP doesn't support overloading the constructor (that is, having multiple constructors which accept different parameters). You can achieve this effect using static methods.

Note: I retrieved this from the log of the (at time of this writing) accepted answer.

Configure nginx with multiple locations with different root folders on subdomain

A little more elaborate example.

Setup: You have a website at example.com and you have a web app at example.com/webapp

...
server {
  listen 443 ssl;
  server_name example.com;

  root   /usr/share/nginx/html/website_dir;
  index  index.html index.htm;
  try_files $uri $uri/ /index.html;

  location /webapp/ {
    alias  /usr/share/nginx/html/webapp_dir/;
    index  index.html index.htm;
    try_files $uri $uri/ /webapp/index.html;
  }
}
...

I've named webapp_dir and website_dir on purpose. If you have matching names and folders you can use the root directive.

This setup works and is tested with Docker.

NB!!! Be careful with the slashes. Put them exactly as in the example.

Get pixel color from canvas, on mousemove

Quick Answer

context.getImageData(x, y, 1, 1).data; returns an rgba array. e.g. [50, 50, 50, 255]


Here's a version of @lwburk's rgbToHex function that takes the rgba array as an argument.

function rgbToHex(rgb){
  return '#' + ((rgb[0] << 16) | (rgb[1] << 8) | rgb[2]).toString(16);
};

Split string based on a regular expression

Its very simple actually. Try this:

str1="a    b     c      d"
splitStr1 = str1.split()
print splitStr1

how to convert String into Date time format in JAVA?

With SimpleDateFormat. And steps are -

  1. Create your date pattern string
  2. Create SimpleDateFormat Object
  3. And parse with it.
  4. It will return Date Object.

Adding an arbitrary line to a matplotlib plot in ipython notebook

You can directly plot the lines you want by feeding the plot command with the corresponding data (boundaries of the segments):

plot([x1, x2], [y1, y2], color='k', linestyle='-', linewidth=2)

(of course you can choose the color, line width, line style, etc.)

From your example:

import numpy as np
import matplotlib.pyplot as plt

np.random.seed(5)
x = np.arange(1, 101)
y = 20 + 3 * x + np.random.normal(0, 60, 100)
plt.plot(x, y, "o")


# draw vertical line from (70,100) to (70, 250)
plt.plot([70, 70], [100, 250], 'k-', lw=2)

# draw diagonal line from (70, 90) to (90, 200)
plt.plot([70, 90], [90, 200], 'k-')

plt.show()

new chart

Send a ping to each IP on a subnet

Broadcast ping:

$ ping 192.168.1.255
PING 192.168.1.255 (192.168.1.255): 56 data bytes
64 bytes from 192.168.1.154: icmp_seq=0 ttl=64 time=0.104 ms
64 bytes from 192.168.1.51: icmp_seq=0 ttl=64 time=2.058 ms (DUP!)
64 bytes from 192.168.1.151: icmp_seq=0 ttl=64 time=2.135 ms (DUP!)
...

(Add a -b option on Linux)

In Angular, how to redirect with $location.path as $http.post success callback

Here is the changeLocation example from this article http://www.yearofmoo.com/2012/10/more-angularjs-magic-to-supercharge-your-webapp.html#apply-digest-and-phase

//be sure to inject $scope and $location
var changeLocation = function(url, forceReload) {
  $scope = $scope || angular.element(document).scope();
  if(forceReload || $scope.$$phase) {
    window.location = url;
  }
  else {
    //only use this if you want to replace the history stack
    //$location.path(url).replace();

    //this this if you want to change the URL and add it to the history stack
    $location.path(url);
    $scope.$apply();
  }
};

Filter object properties by key in ES6

Another solution using the "new" Array.reduce method:

const raw = {
  item1: { key: 'sdfd', value:'sdfd' },
  item2: { key: 'sdfd', value:'sdfd' },
  item3: { key: 'sdfd', value:'sdfd' }
};

const allowed = ['item1', 'item3'];

const filtered = allowed.reduce((obj, key) => { 
  obj[key] = raw[key]; 
  return obj 
}, {})

console.log(filtered);

Demonstration in this Fiddle...


But I like the solution in this answer here which is using Object.fromEntries Array.filter and Array.includes:

const object = Object.fromEntries(
  Object.entries(raw).filter(([key, value]) => allowed.includes(key))
);

Demonstration in this Fiddle...

Remove Unnamed columns in pandas dataframe

The approved solution doesn't work in my case, so my solution is the following one:

    ''' The column name in the example case is "Unnamed: 7"
 but it works with any other name ("Unnamed: 0" for example). '''

        df.rename({"Unnamed: 7":"a"}, axis="columns", inplace=True)

        # Then, drop the column as usual.

        df.drop(["a"], axis=1, inplace=True)

Hope it helps others.

DOM element to corresponding vue.js component

  • this.$el - points to the root element of the component
  • this.$refs.<ref name> + <div ref="<ref name>" ... - points to nested element

use $el/$refs only after mounted() step of vue lifecycle

<template>
    <div>
        root element
        <div ref="childElement">child element</div>
    </div>
</template>

<script>
    export default {
        mounted() {
            let rootElement = this.$el;
            let childElement = this.$refs.childElement;

            console.log(rootElement);
            console.log(childElement);
        }
    }
</script>

<style scoped>
</style>

enter image description here

How to list all the roles existing in Oracle database?

all_roles.sql

SELECT SUBSTR(TRIM(rtp.role),1,12)          AS ROLE
     , SUBSTR(rp.grantee,1,16)              AS GRANTEE
     , SUBSTR(TRIM(rtp.privilege),1,12)     AS PRIVILEGE
     , SUBSTR(TRIM(rtp.owner),1,12)         AS OWNER
     , SUBSTR(TRIM(rtp.table_name),1,28)    AS TABLE_NAME
     , SUBSTR(TRIM(rtp.column_name),1,20)   AS COLUMN_NAME
     , SUBSTR(rtp.common,1,4)               AS COMMON
     , SUBSTR(rtp.grantable,1,4)            AS GRANTABLE
     , SUBSTR(rp.default_role,1,16)         AS DEFAULT_ROLE
     , SUBSTR(rp.admin_option,1,4)          AS ADMIN_OPTION
  FROM role_tab_privs rtp
  LEFT JOIN dba_role_privs rp
    ON (rtp.role = rp.granted_role)
 WHERE ('&1' IS NULL OR UPPER(rtp.role) LIKE UPPER('%&1%'))
   AND ('&2' IS NULL OR UPPER(rp.grantee) LIKE UPPER('%&2%'))
   AND ('&3' IS NULL OR UPPER(rtp.table_name) LIKE UPPER('%&3%'))
   AND ('&4' IS NULL OR UPPER(rtp.owner) LIKE UPPER('%&4%'))
 ORDER BY 1
        , 2
        , 3
        , 4
;

Usage

SQLPLUS> @all_roles '' '' '' '' '' ''
SQLPLUS> @all_roles 'somerol' '' '' '' '' ''
SQLPLUS> @all_roles 'roler' 'username' '' '' '' ''
SQLPLUS> @all_roles '' '' 'part-of-database-package-name' '' '' ''
etc.

Sort collection by multiple fields in Kotlin

sortedWith + compareBy (taking a vararg of lambdas) do the trick:

val sortedList = list.sortedWith(compareBy({ it.age }, { it.name }))

You can also use the somewhat more succinct callable reference syntax:

val sortedList = list.sortedWith(compareBy(Person::age, Person::name))

What is Ruby's double-colon `::`?

What good is scope (private, protected) if you can just use :: to expose anything?

In Ruby, everything is exposed and everything can be modified from anywhere else.

If you're worried about the fact that classes can be changed from outside the "class definition", then Ruby probably isn't for you.

On the other hand, if you're frustrated by Java's classes being locked down, then Ruby is probably what you're looking for.

open link in iframe

Because the target of the link matches the name of the iframe, the link will open in the iframe. Try this:

<iframe src="http://stackoverflow.com/" name="iframe_a">
<p>Your browser does not support iframes.</p>
</iframe>

<a href="http://www.cnn.com" target="iframe_a">www.cnn.com</a>

XPath to return only elements containing the text, and not its parents

Do you want to find elements that contain "match", or that equal "match"?

This will find elements that have text nodes that equal 'match' (matches none of the elements because of leading and trailing whitespace in random2):

//*[text()='match']

This will find all elements that have text nodes that equal "match", after removing leading and trailing whitespace(matches random2):

//*[normalize-space(text())='match']

This will find all elements that contain 'match' in the text node value (matches random2 and random3):

//*[contains(text(),'match')]

This XPATH 2.0 solution uses the matches() function and a regex pattern that looks for text nodes that contain 'match' and begin at the start of the string(i.e. ^) or a word boundary (i.e. \W) and terminated by the end of the string (i.e. $) or a word boundary. The third parameter i evaluates the regex pattern case-insensitive. (matches random2)

//*[matches(text(),'(^|\W)match($|\W)','i')]

Spring-Security-Oauth2: Full authentication is required to access this resource

The client_id and client_secret, by default, should go in the Authorization header, not the form-urlencoded body.

  1. Concatenate your client_id and client_secret, with a colon between them: [email protected]:12345678.
  2. Base 64 encode the result: YWJjQGdtYWlsLmNvbToxMjM0NTY3OA==
  3. Set the Authorization header: Authorization: Basic YWJjQGdtYWlsLmNvbToxMjM0NTY3OA==

How to calculate DATE Difference in PostgreSQL?

This is how I usually do it. A simple number of days perspective of B minus A.

DATE_PART('day', MAX(joindate) - MIN(joindate)) as date_diff

How to parse a CSV file using PHP

Just discovered a handy way to get an index while parsing. My mind was blown.

$handle = fopen("test.csv", "r");
for ($i = 0; $row = fgetcsv($handle ); ++$i) {
    // Do something will $row array
}
fclose($handle);

Source: link

Spring MVC - Why not able to use @RequestBody and @RequestParam together

The @RequestBody javadoc states

Annotation indicating a method parameter should be bound to the body of the web request.

It uses registered instances of HttpMessageConverter to deserialize the request body into an object of the annotated parameter type.

And the @RequestParam javadoc states

Annotation which indicates that a method parameter should be bound to a web request parameter.

  1. Spring binds the body of the request to the parameter annotated with @RequestBody.

  2. Spring binds request parameters from the request body (url-encoded parameters) to your method parameter. Spring will use the name of the parameter, ie. name, to map the parameter.

  3. Parameters are resolved in order. The @RequestBody is processed first. Spring will consume all the HttpServletRequest InputStream. When it then tries to resolve the @RequestParam, which is by default required, there is no request parameter in the query string or what remains of the request body, ie. nothing. So it fails with 400 because the request can't be correctly handled by the handler method.

  4. The handler for @RequestParam acts first, reading what it can of the HttpServletRequest InputStream to map the request parameter, ie. the whole query string/url-encoded parameters. It does so and gets the value abc mapped to the parameter name. When the handler for @RequestBody runs, there's nothing left in the request body, so the argument used is the empty string.

  5. The handler for @RequestBody reads the body and binds it to the parameter. The handler for @RequestParam can then get the request parameter from the URL query string.

  6. The handler for @RequestParam reads from both the body and the URL query String. It would usually put them in a Map, but since the parameter is of type String, Spring will serialize the Map as comma separated values. The handler for @RequestBody then, again, has nothing left to read from the body.

How can I create a table with borders in Android?

I used this solution: in TableRow, I created for every cell LinearLayout with vertical line and actual cell in it, and after every TableRow, I added a horizontal line.

Look at the code below:

<TableLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:shrinkColumns="1">

    <TableRow            
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

            <LinearLayout 
                android:orientation="horizontal"
                android:layout_height="match_parent"
                android:layout_weight="1">

                <TextView 
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:gravity="center"/>

            </LinearLayout>

            <LinearLayout 
                android:orientation="horizontal"
                android:layout_height="match_parent"
                android:layout_weight="1">

                <View
                    android:layout_height="match_parent"
                    android:layout_width="1dp"
                    android:background="#BDCAD2"/>

                <TextView 
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:gravity="center"/>

            </LinearLayout>
      </TableRow>

      <View
        android:layout_height="1dip"
        android:background="#BDCAD2" />

      <!-- More TableRows -->
</TableLayout>

Hope it will help.

Type.GetType("namespace.a.b.ClassName") returns null

Try this method.

public static Type GetType(string typeName)
{
    var type = Type.GetType(typeName);
    if (type != null) return type;
    foreach (var a in AppDomain.CurrentDomain.GetAssemblies())
    {
        type = a.GetType(typeName);
        if (type != null)
            return type;
    }
    return null;
}

What are the differences between Visual Studio Code and Visual Studio?

Complementing the previous answers, one big difference between both is that Visual Studio Code comes in a so called "portable" version that does not require full administrative permissions to run on Windows and can be placed in a removable drive for convenience.