Programs & Examples On #Mousewheel

A mouse wheel (or scroll wheel) is a hard plastic or rubbery disc (the "wheel") on a computer mouse that is perpendicular to the mouse surface. It is used for scrolling.

How to prevent page scrolling when scrolling a DIV element?

In the solution above there is a little mistake regarding Firefox. In Firefox "DOMMouseScroll" event has no e.detail property,to get this property you should write the following 'e.originalEvent.detail'.

Here is a working solution for Firefox:

$.fn.isolatedScroll = function() {
    this.on('mousewheel DOMMouseScroll', function (e) {
        var delta = e.wheelDelta || (e.originalEvent && e.originalEvent.wheelDelta) || -e.originalEvent.detail,
            bottomOverflow = (this.scrollTop + $(this).outerHeight() - this.scrollHeight) >= 0,
            topOverflow = this.scrollTop <= 0;

        if ((delta < 0 && bottomOverflow) || (delta > 0 && topOverflow)) {
            e.preventDefault();
        }
    });
    return this;
};

Get mouse wheel events in jQuery?

There's a plugin that detects up/down mouse wheel and velocity over a region.

Export MySQL database using PHP only

Here is my code, This will backup MySQL database and store it in the specified path.

<?php
function backup_mysql_database($options){
$mtables = array(); $contents = "-- Database: `".$options['db_to_backup']."` --\n";

$mysqli = new mysqli($options['db_host'], $options['db_uname'], $options['db_password'], $options['db_to_backup']);
if ($mysqli->connect_error) {
    die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}

$results = $mysqli->query("SHOW TABLES");

while($row = $results->fetch_array()){
    if (!in_array($row[0], $options['db_exclude_tables'])){
        $mtables[] = $row[0];
    }
}

foreach($mtables as $table){
    $contents .= "-- Table `".$table."` --\n";

    $results = $mysqli->query("SHOW CREATE TABLE ".$table);
    while($row = $results->fetch_array()){
        $contents .= $row[1].";\n\n";
    }

    $results = $mysqli->query("SELECT * FROM ".$table);
    $row_count = $results->num_rows;
    $fields = $results->fetch_fields();
    $fields_count = count($fields);

    $insert_head = "INSERT INTO `".$table."` (";
    for($i=0; $i < $fields_count; $i++){
        $insert_head  .= "`".$fields[$i]->name."`";
            if($i < $fields_count-1){
                    $insert_head  .= ', ';
                }
    }
    $insert_head .=  ")";
    $insert_head .= " VALUES\n";        

    if($row_count>0){
        $r = 0;
        while($row = $results->fetch_array()){
            if(($r % 400)  == 0){
                $contents .= $insert_head;
            }
            $contents .= "(";
            for($i=0; $i < $fields_count; $i++){
                $row_content =  str_replace("\n","\\n",$mysqli->real_escape_string($row[$i]));

                switch($fields[$i]->type){
                    case 8: case 3:
                        $contents .=  $row_content;
                        break;
                    default:
                        $contents .= "'". $row_content ."'";
                }
                if($i < $fields_count-1){
                        $contents  .= ', ';
                    }
            }
            if(($r+1) == $row_count || ($r % 400) == 399){
                $contents .= ");\n\n";
            }else{
                $contents .= "),\n";
            }
            $r++;
        }
    }
}

if (!is_dir ( $options['db_backup_path'] )) {
        mkdir ( $options['db_backup_path'], 0777, true );
 }

$backup_file_name = $options['db_to_backup'] . " sql-backup- " . date( "d-m-Y--h-i-s").".sql";

$fp = fopen($options['db_backup_path'] . '/' . $backup_file_name ,'w+');
if (($result = fwrite($fp, $contents))) {
    echo "Backup file created '--$backup_file_name' ($result)"; 
}
fclose($fp);
return $backup_file_name;
}

$options = array(
    'db_host'=> 'localhost',  //mysql host
    'db_uname' => 'root',  //user
    'db_password' => '', //pass
    'db_to_backup' => 'attendance', //database name
    'db_backup_path' => '/htdocs', //where to backup
    'db_exclude_tables' => array() //tables to exclude
);
$backup_file_name=backup_mysql_database($options);

How to add an image to a JPanel?

You can subclass JPanel - here is an extract from my ImagePanel, which puts an image in any one of 5 locations, top/left, top/right, middle/middle, bottom/left or bottom/right:

protected void paintComponent(Graphics gc) {
    super.paintComponent(gc);

    Dimension                           cs=getSize();                           // component size

    gc=gc.create();
    gc.clipRect(insets.left,insets.top,(cs.width-insets.left-insets.right),(cs.height-insets.top-insets.bottom));
    if(mmImage!=null) { gc.drawImage(mmImage,(((cs.width-mmSize.width)/2)       +mmHrzShift),(((cs.height-mmSize.height)/2)        +mmVrtShift),null); }
    if(tlImage!=null) { gc.drawImage(tlImage,(insets.left                       +tlHrzShift),(insets.top                           +tlVrtShift),null); }
    if(trImage!=null) { gc.drawImage(trImage,(cs.width-insets.right-trSize.width+trHrzShift),(insets.top                           +trVrtShift),null); }
    if(blImage!=null) { gc.drawImage(blImage,(insets.left                       +blHrzShift),(cs.height-insets.bottom-blSize.height+blVrtShift),null); }
    if(brImage!=null) { gc.drawImage(brImage,(cs.width-insets.right-brSize.width+brHrzShift),(cs.height-insets.bottom-brSize.height+brVrtShift),null); }
    }

Hiding the address bar of a browser (popup)

You might no be able to HIDE it, but if you are looking for the extra space, what I did and seems to work is a very simple thing, the address bar has 60px height, so this is my solution.

@media only screen and (max-width: 1024px){ // only from ipads down
  body{
    padding-bottom: 60px; // push your whole site same height upwards. ;)
  }
}

mcrypt is deprecated, what is the alternative?

You should use OpenSSL over mcrypt as it's actively developed and maintained. It provides better security, maintainability and portability. Secondly it performs AES encryption/decryption much faster. It uses PKCS7 padding by default, but you can specify OPENSSL_ZERO_PADDING if you need it. To use with a 32-byte binary key, you can specify aes-256-cbc which is much obvious than MCRYPT_RIJNDAEL_128.

Here is the code example using Mcrypt:

Unauthenticated AES-256-CBC encryption library written in Mcrypt with PKCS7 padding.

/**
 * This library is unsafe because it does not MAC after encrypting
 */
class UnsafeMcryptAES
{
    const CIPHER = MCRYPT_RIJNDAEL_128;

    public static function encrypt($message, $key)
    {
        if (mb_strlen($key, '8bit') !== 32) {
            throw new Exception("Needs a 256-bit key!");
        }
        $ivsize = mcrypt_get_iv_size(self::CIPHER);
        $iv = mcrypt_create_iv($ivsize, MCRYPT_DEV_URANDOM);

        // Add PKCS7 Padding
        $block = mcrypt_get_block_size(self::CIPHER);
        $pad = $block - (mb_strlen($message, '8bit') % $block, '8bit');
        $message .= str_repeat(chr($pad), $pad);

        $ciphertext = mcrypt_encrypt(
            MCRYPT_RIJNDAEL_128,
            $key,
            $message,
            MCRYPT_MODE_CBC,
            $iv
        );

        return $iv . $ciphertext;
    }

    public static function decrypt($message, $key)
    {
        if (mb_strlen($key, '8bit') !== 32) {
            throw new Exception("Needs a 256-bit key!");
        }
        $ivsize = mcrypt_get_iv_size(self::CIPHER);
        $iv = mb_substr($message, 0, $ivsize, '8bit');
        $ciphertext = mb_substr($message, $ivsize, null, '8bit');

        $plaintext = mcrypt_decrypt(
            MCRYPT_RIJNDAEL_128,
            $key,
            $ciphertext,
            MCRYPT_MODE_CBC,
            $iv
        );

        $len = mb_strlen($plaintext, '8bit');
        $pad = ord($plaintext[$len - 1]);
        if ($pad <= 0 || $pad > $block) {
            // Padding error!
            return false;
        }
        return mb_substr($plaintext, 0, $len - $pad, '8bit');
    }
}

And here is the version written using OpenSSL:

/**
 * This library is unsafe because it does not MAC after encrypting
 */
class UnsafeOpensslAES
{
    const METHOD = 'aes-256-cbc';

    public static function encrypt($message, $key)
    {
        if (mb_strlen($key, '8bit') !== 32) {
            throw new Exception("Needs a 256-bit key!");
        }
        $ivsize = openssl_cipher_iv_length(self::METHOD);
        $iv = openssl_random_pseudo_bytes($ivsize);

        $ciphertext = openssl_encrypt(
            $message,
            self::METHOD,
            $key,
            OPENSSL_RAW_DATA,
            $iv
        );

        return $iv . $ciphertext;
    }

    public static function decrypt($message, $key)
    {
        if (mb_strlen($key, '8bit') !== 32) {
            throw new Exception("Needs a 256-bit key!");
        }
        $ivsize = openssl_cipher_iv_length(self::METHOD);
        $iv = mb_substr($message, 0, $ivsize, '8bit');
        $ciphertext = mb_substr($message, $ivsize, null, '8bit');

        return openssl_decrypt(
            $ciphertext,
            self::METHOD,
            $key,
            OPENSSL_RAW_DATA,
            $iv
        );
    }
}

Source: If You're Typing the Word MCRYPT Into Your PHP Code, You're Doing It Wrong.

How to use onResume()?

Most of the previous answers do a good job explaining how, why, and when to use onResume() but I would like to add something about re-creating your Activity.

I want to know if I want to restart the activity at the end of exectuion of an other what method is executed onCreate() or onResume()

The answer is onCreate() However, when deciding to actually re-create it, you should ask yourself how much of the Activity needs to be re-created. If it is data in an adapter, say for a list, then you can call notifyDataChanged() on the adapter to repopulate the adapter and not have to redraw everything.

Also, if you just need to update certain views but not all then it may be more efficient to call invalidate() on the view(s) that need updated. This will only redraw those views and possibly allow your application to run more smoothly. I hope this can help you.

OOP vs Functional Programming vs Procedural

All of them are good in their own ways - They're simply different approaches to the same problems.

In a purely procedural style, data tends to be highly decoupled from the functions that operate on it.

In an object oriented style, data tends to carry with it a collection of functions.

In a functional style, data and functions tend toward having more in common with each other (as in Lisp and Scheme) while offering more flexibility in terms of how functions are actually used. Algorithms tend also to be defined in terms of recursion and composition rather than loops and iteration.

Of course, the language itself only influences which style is preferred. Even in a pure-functional language like Haskell, you can write in a procedural style (though that is highly discouraged), and even in a procedural language like C, you can program in an object-oriented style (such as in the GTK+ and EFL APIs).

To be clear, the "advantage" of each paradigm is simply in the modeling of your algorithms and data structures. If, for example, your algorithm involves lists and trees, a functional algorithm may be the most sensible. Or, if, for example, your data is highly structured, it may make more sense to compose it as objects if that is the native paradigm of your language - or, it could just as easily be written as a functional abstraction of monads, which is the native paradigm of languages like Haskell or ML.

The choice of which you use is simply what makes more sense for your project and the abstractions your language supports.

JS Client-Side Exif Orientation: Rotate and Mirror JPEG Images

If

width = img.width;
height = img.height;
var ctx = canvas.getContext('2d');

Then you can use these transformations to turn the image to orientation 1

From orientation:

  1. ctx.transform(1, 0, 0, 1, 0, 0);
  2. ctx.transform(-1, 0, 0, 1, width, 0);
  3. ctx.transform(-1, 0, 0, -1, width, height);
  4. ctx.transform(1, 0, 0, -1, 0, height);
  5. ctx.transform(0, 1, 1, 0, 0, 0);
  6. ctx.transform(0, 1, -1, 0, height, 0);
  7. ctx.transform(0, -1, -1, 0, height, width);
  8. ctx.transform(0, -1, 1, 0, 0, width);

Before drawing the image on ctx

How to hide collapsible Bootstrap 4 navbar on click

With trying out above solutions, I was missing a solution for Dropdown toggles, so here you go! Also opens submenu items.

Maybe you have to tweak it a bit if your toggle class is different.

$('.navbar-nav li a').on('click', function(){
    if(!$( this ).hasClass('dropdown-toggle')){
        $('.navbar-collapse').collapse('hide');
    }
});

Video format or MIME type is not supported

Firefox does not support the MPEG H.264 (mp4) format at this time, due to a philosophical disagreement with the closed-source nature of the format.

To play videos in all browsers without using plugins, you will need to host multiple copies of each video, in different formats. You will also need to use an alternate form of the video tag, as seen in the JSFiddle from @TimHayes above, reproduced below. Mozilla claims that only mp4 and WebM are necessary to ensure complete coverage of all major browsers, but you may wish to consult the Video Formats and Browser Support heading on W3C's HTML5 Video page to see which browser supports what formats.

Additionally, it's worth checking out the HTML5 Video page on Wikipedia for a basic comparison of the major file formats.

Below is the appropriate video tag (you will need to re-encode your video in WebM or OGG formats as well as your existing mp4):

<video id="video" controls='controls'>
  <source src="videos/clip.mp4" type="video/mp4"/>
  <source src="videos/clip.webm" type="video/webm"/>
  <source src="videos/clip.ogv" type="video/ogg"/>
  Your browser doesn't seem to support the video tag.
</video>

Updated Nov. 8, 2013

Network infrastructure giant Cisco has announced plans to open-source an implementation of the H.264 codec, removing the licensing fees that have so far proved a barrier to use by Mozilla. Without getting too deep into the politics of it (see following link for that) this will allow Firefox to support H.264 starting in "early 2014". However, as noted in that link, this still comes with a caveat. The H.264 codec is merely for video, and in the MPEG-4 container it is most commonly paired with the closed-source AAC audio codec. Because of this, playback of H.264 video will work, but audio will depend on whether the end-user has the AAC codec already present on their machine.

The long and short of this is that progress is being made, but you still can't avoid using multiple encodings without using a plugin.

how can I check if a file exists?

an existing folder will FAIL with FileExists

Function FileExists(strFileName)
' Check if a file exists - returns True or False

use instead or in addition:

Function FolderExists(strFolderPath)
' Check if a path exists

Using setDate in PreparedStatement

Not sure, but what I think you're looking for is to create a java.util.Date from a String, then convert that java.util.Date to a java.sql.Date.

try this:

private static java.sql.Date getCurrentDate(String date) {

    java.util.Date today;
    java.sql.Date rv = null;
    try {

        SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
        today = format.parse(date);
        rv = new java.sql.Date(today.getTime());
        System.out.println(rv.getTime());

    } catch (Exception e) {
        System.out.println("Exception: " + e.getMessage());
    } finally {
        return rv;
    }

}    

Will return a java.sql.Date object for setDate();

The function above will print out a long value:

1375934400000

Can I set an opacity only to the background image of a div?

So here is an other way:

background-image: linear-gradient(rgba(255,255,255,0.5), rgba(255,255,255,0.5)), url("your_image.png");

Remove Object from Array using JavaScript

Use splice function on arrays. Specify the position of the start element and the length of the subsequence you want to remove.

someArray.splice(pos, 1);

iOS 10 - Changes in asking permissions of Camera, microphone and Photo Library causing application to crash

You have to add this permission in Info.plist for iOS 10.

Photo :

Key       :  Privacy - Photo Library Usage Description    
Value   :  $(PRODUCT_NAME) photo use

Microphone :

Key        :  Privacy - Microphone Usage Description    
Value    :  $(PRODUCT_NAME) microphone use

Camera :

Key       :  Privacy - Camera Usage Description   
Value   :  $(PRODUCT_NAME) camera use

Convert string to title case with JavaScript

This solution takes punctuation into account for new sentences, handles quotations, converts minor words to lowercase and ignores acronyms or all-caps words.

var stopWordsArray = new Array("a", "all", "am", "an", "and", "any", "are", "as", "at", "be", "but", "by", "can", "can't", "did", "didn't", "do", "does", "doesn't", "don't", "else", "for", "get", "gets", "go", "got", "had", "has", "he", "he's", "her", "here", "hers", "hi", "him", "his", "how", "i'd", "i'll", "i'm", "i've", "if", "in", "is", "isn't", "it", "it's", "its", "let", "let's", "may", "me", "my", "no", "of", "off", "on", "our", "ours", "she", "so", "than", "that", "that's", "thats", "the", "their", "theirs", "them", "then", "there", "there's", "these", "they", "they'd", "they'll", "they're", "they've", "this", "those", "to", "too", "try", "until", "us", "want", "wants", "was", "wasn't", "we", "we'd", "we'll", "we're", "we've", "well", "went", "were", "weren't", "what", "what's", "when", "where", "which", "who", "who's", "whose", "why", "will", "with", "won't", "would", "yes", "yet", "you", "you'd", "you'll", "you're", "you've", "your");

// Only significant words are transformed. Handles acronyms and punctuation
String.prototype.toTitleCase = function() {
    var newSentence = true;
    return this.split(/\s+/).map(function(word) {
        if (word == "") { return; }
        var canCapitalise = true;
        // Get the pos of the first alpha char (word might start with " or ')
        var firstAlphaCharPos = word.search(/\w/);
        // Check for uppercase char that is not the first char (might be acronym or all caps)
        if (word.search(/[A-Z]/) > 0) {
            canCapitalise = false;
        } else if (stopWordsArray.indexOf(word) != -1) {
            // Is a stop word and not a new sentence
            word.toLowerCase();
            if (!newSentence) {
                canCapitalise = false;
            }
        }
        // Is this the last word in a sentence?
        newSentence = (word.search(/[\.!\?:]['"]?$/) > 0)? true : false;
        return (canCapitalise)? word.replace(word[firstAlphaCharPos], word[firstAlphaCharPos].toUpperCase()) : word;
    }).join(' ');
}

// Pass a string using dot notation:
alert("A critical examination of Plato's view of the human nature".toTitleCase());
var str = "Ten years on: a study into the effectiveness of NCEA in New Zealand schools";
str.toTitleCase());
str = "\"Where to from here?\" the effectivness of eLearning in childhood education";
alert(str.toTitleCase());

/* Result:
A Critical Examination of Plato's View of the Human Nature.
Ten Years On: A Study Into the Effectiveness of NCEA in New Zealand Schools.
"Where to From Here?" The Effectivness of eLearning in Childhood Education. */

How to present a modal atop the current view in Swift

First, remove all explicit setting of modal presentation style in code and do the following:

  1. In the storyboard set the ModalViewController's modalPresentation style to Over Current context

img1

  1. Check the checkboxes in the Root/Presenting ViewController - Provide Context and Define Context. They seem to be working even unchecked.

How can I detect if this dictionary key exists in C#?

Here is a little something I cooked up today. Seems to work for me. Basically you override the Add method in your base namespace to do a check and then call the base's Add method in order to actually add it. Hope this works for you

using System;
using System.Collections.Generic;
using System.Collections;

namespace Main
{
    internal partial class Dictionary<TKey, TValue> : System.Collections.Generic.Dictionary<TKey, TValue>
    {
        internal new virtual void Add(TKey key, TValue value)
        {   
            if (!base.ContainsKey(key))
            {
                base.Add(key, value);
            }
        }
    }

    internal partial class List<T> : System.Collections.Generic.List<T>
    {
        internal new virtual void Add(T item)
        {
            if (!base.Contains(item))
            {
                base.Add(item);
            }
        }
    }

    public class Program
    {
        public static void Main()
        {
            Dictionary<int, string> dic = new Dictionary<int, string>();
            dic.Add(1,"b");
            dic.Add(1,"a");
            dic.Add(2,"c");
            dic.Add(1, "b");
            dic.Add(1, "a");
            dic.Add(2, "c");

            string val = "";
            dic.TryGetValue(1, out val);

            Console.WriteLine(val);
            Console.WriteLine(dic.Count.ToString());


            List<string> lst = new List<string>();
            lst.Add("b");
            lst.Add("a");
            lst.Add("c");
            lst.Add("b");
            lst.Add("a");
            lst.Add("c");

            Console.WriteLine(lst[2]);
            Console.WriteLine(lst.Count.ToString());
        }
    }
}

Javascript use variable as object name

I think Shaz's answer for local variables is hard to understand, though it works for non-recursive functions. Here's another way that I think it's clearer (but it's still his idea, exact same behavior). It's also not accessing the local variables dynamically, just the property of the local variable.

Essentially, it's using a global variable (attached to the function object)

// Here's  a version of it that is more straight forward.
function doIt() {
    doIt.objname = {};
    var someObject = "objname";
    doIt[someObject].value = "value";    
    console.log(doIt.objname);
})();

Which is essentially the same thing as creating a global to store the variable, so you can access it as a property. Creating a global to do this is such a hack.

Here's a cleaner hack that doesn't create global variables, it uses a local variable instead.

function doIt() {
  var scope = {
     MyProp: "Hello"
  };
  var name = "MyProp";
  console.log(scope[name]);
}

See Javascript: interpret string as object reference?

simple Jquery hover enlarge

If you have more than 1 image on the page that you like to enlarge, name the id's for instance "content1", "content2", "content3", etc. Then extend the script with this, like so:

$(document).ready(function() {
    $("[id^=content]").hover(function() {
        $(this).addClass('transition');
    }, function() {
        $(this).removeClass('transition');
    });
});

Edit: Change the "#content" CSS to: img[id^=content] to remain having the transition effects.

Position: absolute and parent height?

This is another late answer but i figured out a fairly simple way of placing the "bar" text in between the four squares. Here are the changes i made; In the bar section i wrapped the "bar" text within a center and div tags.

<header><center><div class="bar">bar</div></center></header>

And in the CSS section i created a "bar" class which is used in the div tag above. After adding this the bar text was centered between the four colored blocks.

.bar{
    position: relative;
}

How can I symlink a file in Linux?

Links are basically of two types:

Symbolic links (soft): link to a symbolic path indicating the abstract location of another file

Hard links: link to the specific location of physical data.

Example 1:

ln /root/file1 /root/file2

The above is an example of a hard link where you can have a copy of your physical data.

Example 2:

ln -s /path/to/file1.txt /path/to/file2.txt

The above command will create a symbolic link to file1.txt.

If you delete a source file then you won't have anything to the destination in soft.

When you do:

ls -lai

You'll see that there is a different inode number for the symlinks.

For more details, you can read the man page of ln on your Linux OS.

How to display Toast in Android?

Inside Fragments (onCreateView)

Toast.makeText(getActivity(), "your message" , Toast.LENGTH_LONG).show();

Inside Classes (onCreate)

Toast.makeText(myClassName.this, "your message" , Toast.LENGTH_LONG).show();

How do I get monitor resolution in Python?

A cross platform and easy way to do this is by using TKinter that comes with nearly all the python versions so you don't have to install anything:

import tkinter
root = tkinter.Tk()
root.withdraw()
WIDTH, HEIGHT = root.winfo_screenwidth(), root.winfo_screenheight()

How to set shape's opacity?

Use this one, I've written this to my app,

<?xml version="1.0" encoding="utf-8"?>
<!--  res/drawable/rounded_edittext.xml -->
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" android:padding="10dp">
    <solid android:color="#882C383E"/>
    <corners
        android:bottomRightRadius="5dp"
        android:bottomLeftRadius="5dp"
        android:topLeftRadius="5dp"
        android:topRightRadius="5dp"/>
</shape>

jQuery, checkboxes and .is(":checked")

$( "#checkbox" ).change(function() {
    if($(this).is(":checked")){
        alert('hi');
    }

});

In HTML5, should the main navigation be inside or outside the <header> element?

To expand on what @JoshuaMaddox said, in the MDN Learning Area, under the "Introduction to HTML" section, the Document and website structure sub-section says (bold/emphasis is by me):

Header

Usually a big strip across the top with a big heading and/or logo. This is where the main common information about a website usually stays from one webpage to another.

Navigation bar

Links to the site's main sections; usually represented by menu buttons, links, or tabs. Like the header, this content usually remains consistent from one webpage to another — having an inconsistent navigation on your website will just lead to confused, frustrated users. Many web designers consider the navigation bar to be part of the header rather than a individual component, but that's not a requirement; in fact some also argue that having the two separate is better for accessibility, as screen readers can read the two features better if they are separate.

How do I get the current username in Windows PowerShell?

$username=( ( Get-WMIObject -class Win32_ComputerSystem | Select-Object -ExpandProperty username ) -split '\\' )[1]

$username

The second username is for display only purposes only if you copy and paste it.

How do you create a read-only user in PostgreSQL?

I read trough all the possible solutions, which are all fine, if you remember to connect to the database before you grant the things ;) Thanks anyway to all other solutions!!!

user@server:~$ sudo su - postgres

create psql user:

postgres@server:~$ createuser --interactive 
Enter name of role to add: readonly
Shall the new role be a superuser? (y/n) n
Shall the new role be allowed to create databases? (y/n) n
Shall the new role be allowed to create more new roles? (y/n) n

start psql cli and set a password for the created user:

postgres@server:~$ psql
psql (10.6 (Ubuntu 10.6-0ubuntu0.18.04.1), server 9.5.14)
Type "help" for help.

postgres=# alter user readonly with password 'readonly';
ALTER ROLE

connect to the target database:

postgres=# \c target_database 
psql (10.6 (Ubuntu 10.6-0ubuntu0.18.04.1), server 9.5.14)
You are now connected to database "target_database" as user "postgres".

grant all the needed privileges:

target_database=# GRANT CONNECT ON DATABASE target_database TO readonly;
GRANT

target_database=# GRANT USAGE ON SCHEMA public TO readonly ;
GRANT

target_database=# GRANT SELECT ON ALL TABLES IN SCHEMA public TO readonly ;
GRANT

alter default privileges for targets db public shema:

target_database=# ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO readonly;
ALTER DEFAULT PRIVILEGES

Django: List field in model?

I think it will help you.

from django.db import models
import ast

class ListField(models.TextField):
    __metaclass__ = models.SubfieldBase
    description = "Stores a python list"

    def __init__(self, *args, **kwargs):
        super(ListField, self).__init__(*args, **kwargs)

    def to_python(self, value):
        if not value:
            value = []

        if isinstance(value, list):
            return value

        return ast.literal_eval(value)

    def get_prep_value(self, value):
        if value is None:
            return value

        return unicode(value)

    def value_to_string(self, obj):
        value = self._get_val_from_obj(obj)
        return self.get_db_prep_value(value)

class ListModel(models.Model):
    test_list = ListField()

Example :

>>> ListModel.objects.create(test_list= [[1,2,3], [2,3,4,4]])

>>> ListModel.objects.get(id=1)

>>> o = ListModel.objects.get(id=1)
>>> o.id
1L
>>> o.test_list
[[1, 2, 3], [2, 3, 4, 4]]
>>> 

Constraint Layout Vertical Align Center

May be i did not fully understand the problem, but, centering all view inside a ConstraintLayout seems very simple. This is what I used:

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center">

enter image description here

Last two lines did the trick!

SQL How to Select the most recent date item

Not sure of exact syntax (you use varchar2 type which means not SQL Server hence TOP) but you can use the LIMIT keyword for MySQL:

Select * FROM test_table WHERE user_id = value
     ORDER BY DATE_ADDED DESC LIMIT 1

Or rownum in Oracle

 SELECT * FROM
     (Select rownum as rnum, * FROM test_table WHERE user_id = value ORDER BY DATE_ADDED DESC)
 WHERE rnum = 1

If DB2, I'm not sure whether it's TOP, LIMIT or rownum...

How to construct a REST API that takes an array of id's for the resources

I find another way of doing the same thing by using @PathParam. Here is the code sample.

@GET
@Path("data/xml/{Ids}")
@Produces("application/xml")
public Object getData(@PathParam("zrssIds") String Ids)
{
  System.out.println("zrssIds = " + Ids);
  //Here you need to use String tokenizer to make the array from the string.
}

Call the service by using following url.

http://localhost:8080/MyServices/resources/cm/data/xml/12,13,56,76

where

http://localhost:8080/[War File Name]/[Servlet Mapping]/[Class Path]/data/xml/12,13,56,76

Class Not Found Exception when running JUnit test

Earlier, in this case, I always did mvn eclipse:eclipse and restarted my Eclipse and it worked. After migrating to GIT, it stopped working for me which is somewhat weird.

Basic problem here is Mr Eclipse does not find the compiled class. Then, I set the output folder as Project/target/test-classes which is by default generated by mvn clean install without skipping the test and proceeded with following workaround:

Option 1: Set classpath for each test case

Eclipse ->Run ->Run Configurations ->under JUnit->select mytest -> under classpath tab->Select User Entries->Advanced->Add Folder -> Select ->Apply->Run

Option 2: Create classpath variable and include it in classpath for all the test cases

Eclipse ->Windows ->Classpath Variables ->New->[Name : Junit_test_cases_cp | path : ]->ok Then go to Eclipse->Run ->Run Configurations ->JUnit->select mytest ->under classpath tab ->Select User Entries->Advanced->Add classpath variables->Select Junit_test_cases_cp->ok->Apply->Run

This is the only thing currently working for me after trying all the suggestions online.

Divide a number by 3 without using *, /, +, -, % operators

#include <stdio.h>

typedef struct { char a,b,c; } Triple;

unsigned long div3(Triple *v, char *r) {
  if ((long)v <= 2)  
    return (unsigned long)r;
  return div3(&v[-1], &r[1]);
}

int main() {
  unsigned long v = 21; 
  int r = div3((Triple*)v, 0); 
  printf("%ld / 3 = %d\n", v, r); 
  return 0;
}

matching query does not exist Error in Django

As mentioned in Django docs, when get method finds no entry or finds multiple entries, it raises an exception, this is the expected behavior:

get() raises MultipleObjectsReturned if more than one object was found. The MultipleObjectsReturned exception is an attribute of the model class.

get() raises a DoesNotExist exception if an object wasn’t found for the given parameters. This exception is an attribute of the model class.

Using exceptions is a way to handle this problem, but I actually don't like the ugly try-except block. An alternative solution, and cleaner to me, is to use the combination of filter + first.

user = UniversityDetails.objects.filter(email=email).first()

When you do .first() to an empty queryset it returns None. This way you can have the same effect in a single line.

The only difference between catching the exception and using this method occurs when you have multiple entries, the former will raise an exception while the latter will set the first element, but as you are using get I may assume we won't fall on this situation.

Note that first method was added on Django 1.6.

SessionTimeout: web.xml vs session.maxInactiveInterval()

Now, i'm being told that this will terminate the session (or is it all sessions?) in the 15th minute of use, regardless their activity.

No, that's not true. The session-timeout configures a per session timeout in case of inactivity.

Are these methods equivalent? Should I favour the web.xml config?

The setting in the web.xml is global, it applies to all sessions of a given context. Programatically, you can change this for a particular session.

How to check if input date is equal to today's date?

A simple date comparison in pure JS should be sufficient:

// Create date from input value
var inputDate = new Date("11/21/2011");

// Get today's date
var todaysDate = new Date();

// call setHours to take the time out of the comparison
if(inputDate.setHours(0,0,0,0) == todaysDate.setHours(0,0,0,0)) {
    // Date equals today's date
}

Here's a working JSFiddle.

Why can't I reference System.ComponentModel.DataAnnotations?

To Reference System.ComponentModel.DataAnnotations

In a code file to have Using System.ComponentModel.DataAnnotations; at the top of the file such as:

using System.ComponentModel.DataAnnotations;

Add a .NET reference to your project by right clicking the project in solution explorer:

enter image description here

Hope this helps! This question helped me.

How to get "GET" request parameters in JavaScript?

You can use the URL to acquire the GET variables. In particular, window.location.search gives everything after (and including) the '?'. You can read more about window.location here.

SSH SCP Local file to Remote in Terminal Mac Os X

Watch that your file name doesn't have : in them either. I found that I had to mv blah-07-08-17-02:69.txt no_colons.txt and then scp no-colons.txt server: then don't forget to mv back on the server. Just in case this was an issue.

Get current user id in ASP.NET Identity 2.0

GetUserId() is an extension method on IIdentity and it is in Microsoft.AspNet.Identity.IdentityExtensions. Make sure you have added the namespace with using Microsoft.AspNet.Identity;.

Shortest way to check for null and assign another value if not

To extend @Dave's answer...if planRec.approved_by is already a string

this.approved_by = planRec.approved_by ?? "";

Best radio-button implementation for IOS

I know its very late to answer this but hope this may help anyone.

you can create button like radio button using IBOutletCollection. create one IBOutletCollection property in our .h file.

@property (nonatomic, strong) IBOutletCollection(UIButton) NSArray *ButtonArray;

connect all button with this IBOutletCollection and make one IBAction method for all three button.

- (IBAction)btnTapped:(id)sender {
       for ( int i=0; i < [self.ButtonArray count]; i++) {
           [[self.ButtonArray objectAtIndex:i] setImage:[UIImage                         
            imageNamed:@"radio-off.png"]                 
            forState:UIControlStateNormal];
       }
     [sender setImage:[UIImage imageNamed:@"radio-on.png"]
      forState:UIControlStateNormal];
}

Aggregate / summarize multiple variables per group (e.g. sum, mean)

Yes, in your formula, you can cbind the numeric variables to be aggregated:

aggregate(cbind(x1, x2) ~ year + month, data = df1, sum, na.rm = TRUE)
   year month         x1          x2
1  2000     1   7.862002   -7.469298
2  2001     1 276.758209  474.384252
3  2000     2  13.122369 -128.122613
...
23 2000    12  63.436507  449.794454
24 2001    12 999.472226  922.726589

See ?aggregate, the formula argument and the examples.

Automating running command on Linux from Windows using PuTTY

Code:

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

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

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


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

}

Sample commands.txt:

ps

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

What do *args and **kwargs mean?

Notice the cool thing in S.Lott's comment - you can also call functions with *mylist and **mydict to unpack positional and keyword arguments:

def foo(a, b, c, d):
  print a, b, c, d

l = [0, 1]
d = {"d":3, "c":2}

foo(*l, **d)

Will print: 0 1 2 3

Error 1920 service failed to start. Verify that you have sufficient privileges to start system services

In my case I had to delete the services in my installshield project and start from square one. My original service components were added manually and I couldn't get them working, the only error I was getting was the same "Error 1920 service failed to start. Verify that you have sufficient privileges to start system services." that you were getting. After deleting my components, I re-added them using the component wizard.
enter image description here

Component Wizard looks like this

I actually had to create two new components. One was of type "Install Service".

Service Component type shown here

enter image description here

The other component I had to add was of "Control Service" type.

enter image description here

I had to choose the service that I had setup when I added the Install Service component.enter image description here

After that it worked, even though nothing looked differently from the components I had added manually. Installshield must do something behind the scenes when it wires up the service components with the component wizard.

All of this was with Install Shield 2016.

Are PostgreSQL column names case-sensitive?

Identifiers (including column names) that are not double-quoted are folded to lower case in PostgreSQL. Column names that were created with double-quotes and thereby retained upper-case letters (and/or other syntax violations) have to be double-quoted for the rest of their life:

"first_Name"

Values (string literals / constants) are enclosed in single quotes:

'xyz'

So, yes, PostgreSQL column names are case-sensitive (when double-quoted):

SELECT * FROM persons WHERE "first_Name" = 'xyz';

Read the manual on identifiers here.

My standing advice is to use legal, lower-case names exclusively so double-quoting is not needed.

SQL Server 2008 R2 can't connect to local database in Management Studio

I have the same error but with different case. Let me quote the solution from here:

Luckly I also have the same set up on my desktop. I have installed first default instance and then Sql Express. Everything is fine for me for several days. Then I tried connecting the way you trying, i.e with MachineName\MsSqlServer to default instance and I got exctaly the same error.

So the solution is when you trying to connect to default instance you don't need to provide instance name.(well this is something puzzled me, why it is failing when we are giving instance name when it is a default instance? Is it some bug, don't know)

Just try with - PC-NAME and everything will be fine. PC-NAME is the MSSQLServer instance.

Edit : Well after reading your question again I realized that you are not aware of the fact that MSSQLSERVER is the default instance of Sql Server. And for connecting to default instance (MSSQLSERVER) you don't need to provide the instance name in connection string. The "MachineName" is itself means "MachineName\MSSQLSERVER".

Sending an Intent to browser to open specific URL

Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(browserIntent);

PHP: How to check if image file exists?

file_exists($filepath) will return a true result for a directory and full filepath, so is not always a solution when a filename is not passed.

is_file($filepath) will only return true for fully filepaths

Warning: DOMDocument::loadHTML(): htmlParseEntityRef: expecting ';' in Entity,

To evaporate the warning, you can use libxml_use_internal_errors(true)

// create new DOMDocument
$document = new \DOMDocument('1.0', 'UTF-8');

// set error level
$internalErrors = libxml_use_internal_errors(true);

// load HTML
$document->loadHTML($html);

// Restore error level
libxml_use_internal_errors($internalErrors);

How to grep for two words existing on the same line?

You cat try with below command

cat log|grep -e word1 -e word2

How to auto-remove trailing whitespace in Eclipse?

You don't need any plugin to do so. For instance, if you code JAVA, you can erase trailing whitespaces configuring save actions:

Eclipse 3.6

Preferences -> Java -> Editors -> Save Actions -> Check Perform the selected actions on save -> Check Additional actions -> Click the Configure.. button.

In the Code organizing tab, check Remove trailing whitespace

CSS technique for a horizontal line with words in the middle

Solution for IE8 and newer...

Issues worth noting:

Using background-color to mask a border might not be the best solution. If you have a complex (or unknown) background color (or image), masking will ultimately fail. Also, if you resize the text, you'll notice that white background color (or whatever you set) will start covering up the text on the line above (or below).

You also don't want to "guesstimate" how wide the the sections are either, because it makes the styles very inflexible and almost impossible to implement on a responsive site where the width of the content is changing.

Solution:

(View JSFiddle)

Instead of "masking" a border with a background-color, use your display property.

HTML

<div class="group">
    <div class="item line"></div>
    <div class="item text">This is a test</div>
    <div class="item line"></div>
</div>

CSS

.group { display: table; width: 100%; }
.item { display: table-cell; }
.text { white-space: nowrap; width: 1%; padding: 0 10px; }
.line { border-bottom: 1px solid #000; position: relative; top: -.5em; }

Resize your text by placing your font-size property on the .group element.

Limitations:

  • No multi-line text. Single lines only.
  • HTML markup isn't as elegant
  • top property on .line element needs to be half of line-height. So, if you have a line-height of 1.5em, then the top should be -.75em. This is a limitation because it's not automated, and if you are applying these styles on elements with different line-heights, then you might need to reapply your line-height style.

For me, these limitations outweigh the "issues" I noted at the beginning of my answer for most implementations.

How can I read the contents of an URL with Python?

#!/usr/bin/python
# -*- coding: utf-8 -*-
# Works on python 3 and python 2.
# when server knows where the request is coming from.

import sys

if sys.version_info[0] == 3:
    from urllib.request import urlopen
else:
    from urllib import urlopen
with urlopen('https://www.facebook.com/') as \
    url:
    data = url.read()

print data

# When the server does not know where the request is coming from.
# Works on python 3.

import urllib.request

user_agent = \
    'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'

url = 'https://www.facebook.com/'
headers = {'User-Agent': user_agent}

request = urllib.request.Request(url, None, headers)
response = urllib.request.urlopen(request)
data = response.read()
print data

Align DIV's to bottom or baseline

You would probably would have to set the child div to have position: absolute.

Update your child style to

#parentDiv .childDiv
{
  height:100px;
  width:30px;
  background-color:#999;
  position:absolute;
  top:207px;
}

Read a local text file using Javascript

You can use a FileReader object to read text file here is example code:

  <div id="page-wrapper">

        <h1>Text File Reader</h1>
        <div>
            Select a text file: 
            <input type="file" id="fileInput">
        </div>
        <pre id="fileDisplayArea"><pre>

    </div>
<script>
window.onload = function() {
        var fileInput = document.getElementById('fileInput');
        var fileDisplayArea = document.getElementById('fileDisplayArea');

        fileInput.addEventListener('change', function(e) {
            var file = fileInput.files[0];
            var textType = /text.*/;

            if (file.type.match(textType)) {
                var reader = new FileReader();

                reader.onload = function(e) {
                    fileDisplayArea.innerText = reader.result;
                }

                reader.readAsText(file);    
            } else {
                fileDisplayArea.innerText = "File not supported!"
            }
        });
}

</script>

Here is the codepen demo

If you have a fixed file to read every time your application load then you can use this code :

<script>
var fileDisplayArea = document.getElementById('fileDisplayArea');
function readTextFile(file)
{
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, false);
    rawFile.onreadystatechange = function ()
    {
        if(rawFile.readyState === 4)
        {
            if(rawFile.status === 200 || rawFile.status == 0)
            {
                var allText = rawFile.responseText;
                fileDisplayArea.innerText = allText 
            }
        }
    }
    rawFile.send(null);
}

readTextFile("file:///C:/your/path/to/file.txt");
</script>

How to use paginator from material angular?

based on Wesley Coetzee's answer i wrote this. Hope it can help anyone googling this issue. I had bugs with swapping the paginator size in the middle of the list that's why i submit my answer:

Paginator html and list

<mat-paginator [length]="localNewspapers.length" pageSize=20
               (page)="getPaginatorData($event)" [pageSizeOptions]="[10, 20, 30]"
               showFirstLastButtons="false">
</mat-paginator>
<mat-list>
   <app-newspaper-pagi-item *ngFor="let paper of (localNewspapers | 
                         slice: lowValue : highValue)"
                         [newspaper]="paper"> 
  </app-newspaper-pagi-item>

Component logic

import {Component, Input, OnInit} from "@angular/core";
import {PageEvent} from "@angular/material";

@Component({
  selector: 'app-uniques-newspaper-list',
  templateUrl: './newspaper-uniques-list.component.html',
})
export class NewspaperUniquesListComponent implements OnInit {
  lowValue: number = 0;
  highValue: number = 20;

  // used to build an array of papers relevant at any given time
  public getPaginatorData(event: PageEvent): PageEvent {
    this.lowValue = event.pageIndex * event.pageSize;
    this.highValue = this.lowValue + event.pageSize;
    return event;
  }

}

Python dictionary: Get list of values for list of keys

A little speed comparison:

Python 2.7.11 |Anaconda 2.4.1 (64-bit)| (default, Dec  7 2015, 14:10:42) [MSC v.1500 64 bit (AMD64)] on win32
In[1]: l = [0,1,2,3,2,3,1,2,0]
In[2]: m = {0:10, 1:11, 2:12, 3:13}
In[3]: %timeit [m[_] for _ in l]  # list comprehension
1000000 loops, best of 3: 762 ns per loop
In[4]: %timeit map(lambda _: m[_], l)  # using 'map'
1000000 loops, best of 3: 1.66 µs per loop
In[5]: %timeit list(m[_] for _ in l)  # a generator expression passed to a list constructor.
1000000 loops, best of 3: 1.65 µs per loop
In[6]: %timeit map(m.__getitem__, l)
The slowest run took 4.01 times longer than the fastest. This could mean that an intermediate result is being cached 
1000000 loops, best of 3: 853 ns per loop
In[7]: %timeit map(m.get, l)
1000000 loops, best of 3: 908 ns per loop
In[33]: from operator import itemgetter
In[34]: %timeit list(itemgetter(*l)(m))
The slowest run took 9.26 times longer than the fastest. This could mean that an intermediate result is being cached 
1000000 loops, best of 3: 739 ns per loop

So list comprehension and itemgetter are the fastest ways to do this.

UPDATE: For large random lists and maps I had a bit different results:

Python 2.7.11 |Anaconda 2.4.1 (64-bit)| (default, Dec  7 2015, 14:10:42) [MSC v.1500 64 bit (AMD64)] on win32
In[2]: import numpy.random as nprnd
l = nprnd.randint(1000, size=10000)
m = dict([(_, nprnd.rand()) for _ in range(1000)])
from operator import itemgetter
import operator
f = operator.itemgetter(*l)
%timeit f(m)
%timeit list(itemgetter(*l)(m))
%timeit [m[_] for _ in l]  # list comprehension
%timeit map(m.__getitem__, l)
%timeit list(m[_] for _ in l)  # a generator expression passed to a list constructor.
%timeit map(m.get, l)
%timeit map(lambda _: m[_], l)
1000 loops, best of 3: 1.14 ms per loop
1000 loops, best of 3: 1.68 ms per loop
100 loops, best of 3: 2 ms per loop
100 loops, best of 3: 2.05 ms per loop
100 loops, best of 3: 2.19 ms per loop
100 loops, best of 3: 2.53 ms per loop
100 loops, best of 3: 2.9 ms per loop

So in this case the clear winner is f = operator.itemgetter(*l); f(m), and clear outsider: map(lambda _: m[_], l).

UPDATE for Python 3.6.4:

import numpy.random as nprnd
l = nprnd.randint(1000, size=10000)
m = dict([(_, nprnd.rand()) for _ in range(1000)])
from operator import itemgetter
import operator
f = operator.itemgetter(*l)
%timeit f(m)
%timeit list(itemgetter(*l)(m))
%timeit [m[_] for _ in l]  # list comprehension
%timeit list(map(m.__getitem__, l))
%timeit list(m[_] for _ in l)  # a generator expression passed to a list constructor.
%timeit list(map(m.get, l))
%timeit list(map(lambda _: m[_], l)
1.66 ms ± 74.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
2.1 ms ± 93.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
2.58 ms ± 88.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
2.36 ms ± 60.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
2.98 ms ± 142 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
2.7 ms ± 284 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
3.14 ms ± 62.6 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

So, results for Python 3.6.4 is almost the same.

Javascript foreach loop on associative array object

If the node.js or browser supported Object.entries(), it can be used as an alternative to using Object.keys() (https://stackoverflow.com/a/18804596/225291).

_x000D_
_x000D_
const h = {_x000D_
  a: 1,_x000D_
  b: 2_x000D_
};_x000D_
_x000D_
Object.entries(h).forEach(([key, value]) => console.log(value));_x000D_
// logs 1, 2
_x000D_
_x000D_
_x000D_

in this example, forEach uses Destructuring assignment of an array.

ExecuteReader: Connection property has not been initialized

You can also write this:

SqlCommand cmd=new SqlCommand ("insert into time(project,iteration) values (@project, @iteration)", conn);
cmd.Parameters.AddWithValue("@project",name1.SelectedValue);
cmd.Parameters.AddWithValue("@iteration",iteration.SelectedValue);

Reset textbox value in javascript

To set value

 $('#searchField').val('your_value');

to retrieve value

$('#searchField').val();

Tomcat 7 "SEVERE: A child container failed during start"

This same issue occurred for me and stack trace

SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost].StandardContext[/XXXXSearch]]
    at java.util.concurrent.FutureTask.report(FutureTask.java:122)
    at java.util.concurrent.FutureTask.get(FutureTask.java:192)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1123)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:800)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost].StandardContext[/XXXXSearch]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    ... 6 more
Caused by: java.lang.IllegalStateException: Unable to complete the scan for annotations for web application [/XXXXSearch]. Possible root causes include a too low setting for -Xss and illegal cyclic inheritance dependencies
    at org.apache.catalina.startup.ContextConfig.processAnnotationsStream(ContextConfig.java:2109)
    at org.apache.catalina.startup.ContextConfig.processAnnotationsJar(ContextConfig.java:1981)
    at org.apache.catalina.startup.ContextConfig.processAnnotationsUrl(ContextConfig.java:1947)
    at org.apache.catalina.startup.ContextConfig.processAnnotations(ContextConfig.java:1932)
    at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1326)
    at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:878)
    at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:369)
    at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
    at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5179)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 6 more
Caused by: java.lang.StackOverflowError
    at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269)
    at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269)
    at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269)
    at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269)
    at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269)
    at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269)
    at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269
    at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269)
    at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269)
    at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269)
    at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269)
    at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269)

In my analysis what i found was, this issue is occurred when illegal cyclic inheritance dependencies caused for Tomcat startup annotation processing.

But my project had lot of dependency JARs, and couldn't found which one is responsible for this.

After trying so many unhappy approaches What i did was , I have updated my tomcat plugin to following and ran the same scenario,

<plugin>
    <groupId>org.apache.tomcat.maven</groupId>
    <artifactId>tomcat8-maven-plugin</artifactId>
    <version>3.0-r1756463</version>
<\plugin>

Then i was able to find which JAR is caused to this issue ,

Aug 23, 2017 2:32:12 PM org.apache.catalina.startup.ContextConfig processAnnotationsJar
SEVERE: Unable to process Jar entry [cryptix/test/TestLOKI91.class] from Jar [jar:file:/C:/Users/Tharinda/.m2/repository/cryptix/cryptix/1.2.2/cryptix-1.2.2.jar!/] for annotations
java.io.EOFException
    at org.apache.tomcat.util.bcel.classfile.FastDataInputStream.readUnsignedShort(FastDataInputStream.java:120)
    at org.apache.tomcat.util.bcel.classfile.ClassParser.readAttributes(ClassParser.java:110)
    at org.apache.tomcat.util.bcel.classfile.ClassParser.parse(ClassParser.java:94)
    at org.apache.catalina.startup.ContextConfig.processAnnotationsStream(ContextConfig.java:1994)
    at org.apache.catalina.startup.ContextConfig.processAnnotationsJar(ContextConfig.java:1944)
    at org.apache.catalina.startup.ContextConfig.processAnnotationsUrl(ContextConfig.java:1919)
    at org.apache.catalina.startup.ContextConfig.processAnnotations(ContextConfig.java:1880)
    at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1149)
    at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:771)
    at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:305)
    at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117)
    at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5120)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

Then just solving the issue with cryptix-1.2.2.jar solved this problem.

I strongly recommend to move tomcat8-maven-plugin which seems stable and less buggy at the moment.

batch script - run command on each file in directory

Actually this is pretty easy since Windows Vista. Microsoft added the command FORFILES

in your case

forfiles /p c:\directory /m *.xls /c "cmd /c ssconvert @file @fname.xlsx"

the only weird thing with this command is that forfiles automatically adds double quotes around @file and @fname. but it should work anyway

Where can I find WcfTestClient.exe (part of Visual Studio)

C:\Program Files (x86)\Microsoft Visual Studio (Your Version Here)\Common7\IDE

Append an int to a std::string

You cannot cast an int to a char* to get a string. Try this:

std::ostringstream sstream;
sstream << "select logged from login where id = " << ClientID;
std::string query = sstream.str();

stringstream reference

How can I open multiple files using "with open" in Python?

Late answer (8 yrs), but for someone looking to join multiple files into one, the following function may be of help:

def multi_open(_list):
    out=""
    for x in _list:
        try:
            with open(x) as f:
                out+=f.read()
        except:
            pass
            # print(f"Cannot open file {x}")
    return(out)

fl = ["C:/bdlog.txt", "C:/Jts/tws.vmoptions", "C:/not.exist"]
print(multi_open(fl))

2018-10-23 19:18:11.361 PROFILE  [Stop Drivers] [1ms]
2018-10-23 19:18:11.361 PROFILE  [Parental uninit] [0ms]
...
# This file contains VM parameters for Trader Workstation.
# Each parameter should be defined in a separate line and the
...

How do I set cell value to Date and apply default Excel date format?

http://poi.apache.org/spreadsheet/quick-guide.html#CreateDateCells

CellStyle cellStyle = wb.createCellStyle();
CreationHelper createHelper = wb.getCreationHelper();
cellStyle.setDataFormat(
    createHelper.createDataFormat().getFormat("m/d/yy h:mm"));
cell = row.createCell(1);
cell.setCellValue(new Date());
cell.setCellStyle(cellStyle);

Unable to set default python version to python3 in ubuntu

To change Python 3.6.8 as the default in Ubuntu 18.04 to Python 3.7.

Install Python 3.7

Steps to install Python3.7 and configure it as the default interpreter.

  1. Install the python3.7 package using apt-get

    sudo apt-get install python3.7

  2. Add Python3.6 & Python 3.7 to update-alternatives

sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.6 1
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.7 2
  1. Update Python 3 to point to Python 3.7

    sudo update-alternatives --config python3 Enter 2 for Python 3.7

  2. Test the version of python

python3 --version
Python 3.7.1 

Find Active Tab using jQuery and Twitter Bootstrap

First of all you need to remove the data-toggle attribute. We will use some JQuery, so make sure you include it.

  <ul class='nav nav-tabs'>
    <li class='active'><a href='#home'>Home</a></li>
    <li><a href='#menu1'>Menu 1</a></li>
    <li><a href='#menu2'>Menu 2</a></li>
    <li><a href='#menu3'>Menu 3</a></li>
  </ul>

  <div class='tab-content'>
    <div id='home' class='tab-pane fade in active'>
      <h3>HOME</h3>
    <div id='menu1' class='tab-pane fade'>
      <h3>Menu 1</h3>
    </div>
    <div id='menu2' class='tab-pane fade'>
      <h3>Menu 2</h3>
    </div>
    <div id='menu3' class='tab-pane fade'>
      <h3>Menu 3</h3>
    </div>
  </div>
</div>

<script>
$(document).ready(function(){
// Handling data-toggle manually
    $('.nav-tabs a').click(function(){
        $(this).tab('show');
    });
// The on tab shown event
    $('.nav-tabs a').on('shown.bs.tab', function (e) {
        alert('Hello from the other siiiiiide!');
        var current_tab = e.target;
        var previous_tab = e.relatedTarget;
    });
});
</script>

Detecting attribute change of value of an attribute I made

There is this extensions that adds an event listener to attribute changes.

Usage:

<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript"
  src="https://cdn.rawgit.com/meetselva/attrchange/master/js/attrchange.js"></script>

Bind attrchange handler function to selected elements

$(selector).attrchange({
    trackValues: true, /* Default to false, if set to true the event object is 
                updated with old and new value.*/
    callback: function (event) { 
        //event               - event object
        //event.attributeName - Name of the attribute modified
        //event.oldValue      - Previous value of the modified attribute
        //event.newValue      - New value of the modified attribute
        //Triggered when the selected elements attribute is added/updated/removed
    }        
});

How to coerce a list object to type 'double'

In this case a loop will also do the job (and is usually sufficiently fast).

a <- array(0, dim=dim(X))
for (i in 1:ncol(X)) {a[,i] <- X[,i]}

MongoDB relationships: embed or reference?

I came across this small presentation while researching this question on my own. I was surprised at how well it was laid out, both the info and the presentation of it.

http://openmymind.net/Multiple-Collections-Versus-Embedded-Documents

It summarized:

As a general rule, if you have a lot of [child documents] or if they are large, a separate collection might be best.

Smaller and/or fewer documents tend to be a natural fit for embedding.

Does mobile Google Chrome support browser extensions?

Just use a different browser. Follow the steps given below to install Chrome extensions on your Android device.

Step 1: Open Google Play Store and download Yandex Browser. Install the browser on your phone.

Step 2: In the URL box of your new browser, open 'chrome.google.com/webstore’ by entering the same in the URL address.

Step 3: Look for the Chrome extension that you want and once you have it, tap on 'Add to Chrome.’

The added Chrome extension will now be automatically added to the Yandex browser.

Time calculation in php (add 10 hours)?

You can simply make use of the DateTime class , OOP Style.

<?php
$date = new DateTime('1:00:00');
$date->add(new DateInterval('PT10H'));
echo $date->format('H:i:s a'); //"prints" 11:00:00 a.m

JPanel Padding in Java

Set an EmptyBorder around your JPanel.
Example:

JPanel p =new JPanel();
p.setBorder(new EmptyBorder(10, 10, 10, 10));

How to pass List from Controller to View in MVC 3

  1. Create a model which contains your list and other things you need for the view.

    For example:

    public class MyModel
    {
        public List<string> _MyList { get; set; }
    }
    
  2. From the action method put your desired list to the Model, _MyList property, like:

    public ActionResult ArticleList(MyModel model)
    {
        model._MyList = new List<string>{"item1","item2","item3"};
        return PartialView(@"~/Views/Home/MyView.cshtml", model);
    }
    
  3. In your view access the model as follows

    @model MyModel
    foreach (var item in Model)
    {
       <div>@item</div>
    }
    

I think it will help for start.

What does the SQL Server Error "String Data, Right Truncation" mean and how do I fix it?

I got around the issue by using a convert on the "?", so my code looks like convert(char(50),?) and that got rid of the truncation error.

A simple jQuery form validation script

You can simply use the jQuery Validate plugin as follows.

jQuery:

$(document).ready(function () {

    $('#myform').validate({ // initialize the plugin
        rules: {
            field1: {
                required: true,
                email: true
            },
            field2: {
                required: true,
                minlength: 5
            }
        }
    });

});

HTML:

<form id="myform">
    <input type="text" name="field1" />
    <input type="text" name="field2" />
    <input type="submit" />
</form>

DEMO: http://jsfiddle.net/xs5vrrso/

Options: http://jqueryvalidation.org/validate

Methods: http://jqueryvalidation.org/category/plugin/

Standard Rules: http://jqueryvalidation.org/category/methods/

Optional Rules available with the additional-methods.js file:

maxWords
minWords
rangeWords
letterswithbasicpunc
alphanumeric
lettersonly
nowhitespace
ziprange
zipcodeUS
integer
vinUS
dateITA
dateNL
time
time12h
phoneUS
phoneUK
mobileUK
phonesUK
postcodeUK
strippedminlength
email2 (optional TLD)
url2 (optional TLD)
creditcardtypes
ipv4
ipv6
pattern
require_from_group
skip_or_fill_minimum
accept
extension

CRON job to run on the last day of the month

You can just connect all answers in one cron line and use only date command.

Just check the difference between day of the month which is today and will be tomorrow:

0 23 * * * root [ $(expr $(date +\%d -d '1 days') - $(date +\%d)  ) -le 0 ]  && echo true

If these difference is below 0 it means that we change the month and there is last day of the month.

Pandas: ValueError: cannot convert float NaN to integer

Also, even at the lastest versions of pandas if the column is object type you would have to convert into float first, something like:

df['column_name'].astype(np.float).astype("Int32")

NB: You have to go through numpy float first and then to nullable Int32, for some reason.

The size of the int if it's 32 or 64 depends on your variable, be aware you may loose some precision if your numbers are to big for the format.

Find which rows have different values for a given column in Teradata SQL

You can do this using a group by:

select id, addressCode
from t
group by id, addressCode
having min(address) <> max(address)

Another way of writing this may seem clearer, but does not perform as well:

select id, addressCode
from t
group by id, addressCode
having count(distinct address) > 1

Failed to find 'ANDROID_HOME' environment variable

I would like to share an answer that also demonstrates approach using the Android SDK provided by the Ubuntu repository:

Install Android SDK

sudo apt-get install android-sdk

Export environmental variables

export ANDROID_HOME="/usr/lib/android-sdk/"
export PATH="${PATH}:${ANDROID_HOME}tools/:${ANDROID_HOME}platform-tools/"

Converting NumPy array into Python List structure?

Use tolist():

import numpy as np
>>> np.array([[1,2,3],[4,5,6]]).tolist()
[[1, 2, 3], [4, 5, 6]]

Note that this converts the values from whatever numpy type they may have (e.g. np.int32 or np.float32) to the "nearest compatible Python type" (in a list). If you want to preserve the numpy data types, you could call list() on your array instead, and you'll end up with a list of numpy scalars. (Thanks to Mr_and_Mrs_D for pointing that out in a comment.)

Best way to repeat a character in C#

Without a doubt the accepted answer is the best and fastest way to repeat a single character.

Binoj Anthony's answer is a simple and quite efficient way to repeat a string.

However, if you don't mind a little more code, you can use my array fill technique to efficiently create these strings even faster. In my comparison tests, the code below executed in about 35% of the time of the StringBuilder.Insert code.

public static string Repeat(this string value, int count)
{
    var values = new char[count * value.Length];
    values.Fill(value.ToCharArray());
    return new string(values);
}

public static void Fill<T>(this T[] destinationArray, params T[] value)
{
    if (destinationArray == null)
    {
        throw new ArgumentNullException("destinationArray");
    }

    if (value.Length > destinationArray.Length)
    {
        throw new ArgumentException("Length of value array must not be more than length of destination");
    }

    // set the initial array value
    Array.Copy(value, destinationArray, value.Length);

    int copyLength, nextCopyLength;

    for (copyLength = value.Length; (nextCopyLength = copyLength << 1) < destinationArray.Length; copyLength = nextCopyLength)
    {
        Array.Copy(destinationArray, 0, destinationArray, copyLength, copyLength);
    }

    Array.Copy(destinationArray, 0, destinationArray, copyLength, destinationArray.Length - copyLength);
}

For more about this array fill technique, see Fastest way to fill an array with a single value

JQuery .hasClass for multiple values in an if statement

Try this:

if ($('html').hasClass('class1 class2')) {

// do stuff 

}

R solve:system is exactly singular

Lapack is a Linear Algebra package which is used by R (actually it's used everywhere) underneath solve(), dgesv spits this kind of error when the matrix you passed as a parameter is singular.

As an addendum: dgesv performs LU decomposition, which, when using your matrix, forces a division by 0, since this is ill-defined, it throws this error. This only happens when matrix is singular or when it's singular on your machine (due to approximation you can have a really small number be considered 0)

I'd suggest you check its determinant if the matrix you're using contains mostly integers and is not big. If it's big, then take a look at this link.

ArrayList insertion and retrieval order

Yes. ArrayList is a sequential list. So, insertion and retrieval order is the same.

If you add elements during retrieval, the order will not remain the same.

Getting an odd error, SQL Server query using `WITH` clause

It should be legal to put a semicolon directly before the WITH keyword.

Python Save to file

file = open('Failed.py', 'w')
file.write('whatever')
file.close()

Here is a more pythonic version, which automatically closes the file, even if there was an exception in the wrapped block:

with open('Failed.py', 'w') as file:
    file.write('whatever')

How to load data from a text file in a PostgreSQL database?

The slightly modified version of COPY below worked better for me, where I specify the CSV format. This format treats backslash characters in text without any fuss. The default format is the somewhat quirky TEXT.

COPY myTable FROM '/path/to/file/on/server' ( FORMAT CSV, DELIMITER('|') );

Recursion or Iteration?

You have to keep in mind that utilizing too deep recursion you will run into Stack Overflow, depending on allowed stack size. To prevent this make sure to provide some base case which ends you recursion.

How to create range in Swift?

If anyone want to create NSRange object can create as:

let range: NSRange = NSRange.init(location: 0, length: 5)

this will create range with position 0 and length 5

How to solve "Unresolved inclusion: <iostream>" in a C++ file in Eclipse CDT?

I use Eclipse for cross compiling and I have to add the explicit directories for some of the standard C++ libraries. Right click your project and select Properties. You'll get the dialog shown in the image. Follow the image and use the + icon to explicitly add the paths to your C++ libraries. enter image description here

how to check the version of jar file?

Thought I would give a more recent answer as this question still comes up pretty high on searches.

Checking CLi JAR Version:

Run the following on the CLi jar file:

unzip -p jenkins-cli.jar META-INF/MANIFEST.MF

Example Output:

Manifest-Version: 1.0
Built-By: kohsuke
Jenkins-CLI-Version: 2.210  <--- Jenkins CLI Version
Created-By: Apache Maven 3.6.1
Build-Jdk: 1.8.0_144
Main-Class: hudson.cli.CLI

The CLi version is listed above.

To get the Server Version, run the following:

java -jar ./jenkins-cli.jar -s https://<Server_URL> -auth <email>@<domain>.com:<API Token> version

(the above will vary based on your implementation of authentication, please change accordingly)

Example Output:

Dec 23, 2019 4:42:55 PM org.apache.sshd.common.util.security.AbstractSecurityProviderRegistrar getOrCreateProvider
INFO: getOrCreateProvider(EdDSA) created instance of net.i2p.crypto.eddsa.EdDSASecurityProvider
2.210  <-- Jenkins Server Version

JavaScript: How do I print a message to the error console?

console.error(message); //gives you the red errormessage
console.log(message); //gives the default message
console.warn(message); //gives the warn message with the exclamation mark in front of it
console.info(message); //gives an info message with an 'i' in front of the message

You also can add CSS to your logging messages:

console.log('%c My message here', "background: blue; color: white; padding-left:10px;");

Java enum with multiple value types

First, the enum methods shouldn't be in all caps. They are methods just like other methods, with the same naming convention.

Second, what you are doing is not the best possible way to set up your enum. Instead of using an array of values for the values, you should use separate variables for each value. You can then implement the constructor like you would any other class.

Here's how you should do it with all the suggestions above:

public enum States {
    ...
    MASSACHUSETTS("Massachusetts",  "MA",   true),
    MICHIGAN     ("Michigan",       "MI",   false),
    ...; // all 50 of those

    private final String full;
    private final String abbr;
    private final boolean originalColony;

    private States(String full, String abbr, boolean originalColony) {
        this.full = full;
        this.abbr = abbr;
        this.originalColony = originalColony;
    }

    public String getFullName() {
        return full;
    }

    public String getAbbreviatedName() {
        return abbr;
    }

    public boolean isOriginalColony(){
        return originalColony;
    }
}

Handling file renames in git

Let's think about your files from git perspective.

Keep in mind git doesn't track any metadata about your files

Your repository has (among others)

$ cd repo
$ ls
...
iphone.css
...

and it is under git control:

$ git ls-files --error-unmatch iphone.css &>/dev/null && echo file is tracked
file is tracked

Test this with:

$ touch newfile
$ git ls-files --error-unmatch newfile &>/dev/null && echo file is tracked
(no output, it is not tracked)
$ rm newfile

When you do

$ mv iphone.css mobile.css

From git perspective,

  • there is no iphone.css (it is deleted -git warns about that-).
  • there is a new file mobile.css.
  • Those files are totally unrelated.

So, git advises about files it already knows (iphone.css) and new files it detects (mobile.css) but only when files are in index or HEAD git starts to check their contents.

At this moment, neither "iphone.css deletion" nor mobile.css are on index.

Add iphone.css deletion to index

$ git rm iphone.css

git tells you exactly what has happened: (iphone.css is deleted. Nothing more happened)

then add new file mobile.css

$ git add mobile.css

This time both deletion and new file are on index. Now git detects context are the same and expose it as a rename. In fact if files are 50% similar it will detect that as a rename, that let you change mobile.css a bit while keeping the operation as a rename.

See this is reproducible on git diff. Now that your files are on index you must use --cached. Edit mobile.css a bit, add that to index and see the difference between:

$ git diff --cached 

and

$ git diff --cached -M

-M is the "detect renames" option for git diff. -M stands for -M50% (50% or more similarity will make git express it as a rename) but you can reduce this to -M20% (20%) if you edit mobile.css a lot.

Measure the time it takes to execute a t-sql query

Click on Statistics icon to display and then run the query to get the timings and to know how efficient your query is

Stratified Train/Test-split in scikit-learn

#train_size is 1 - tst_size - vld_size
tst_size=0.15
vld_size=0.15

X_train_test, X_valid, y_train_test, y_valid = train_test_split(df.drop(y, axis=1), df.y, test_size = vld_size, random_state=13903) 

X_train_test_V=pd.DataFrame(X_train_test)
X_valid=pd.DataFrame(X_valid)

X_train, X_test, y_train, y_test = train_test_split(X_train_test, y_train_test, test_size=tst_size, random_state=13903)

How to show math equations in general github's markdown(not github's blog)

A "quick and dirty" solution is to maintain a standard .md file using standard TeX equations, e.g. _README.md. When you are satisfied, pass the entire file through Pandoc to convert from standard Markdown to Markdown (Github flavour), and copy the output to README.md.

You can do this online for a quick turnaround, or install/configure Pandoc locally.

Regular expression to match URLs in Java

I'll try a standard "Why are you doing it this way?" answer... Do you know about java.net.URL?

URL url = new URL(stringURL);

The above will throw a MalformedURLException if it can't parse the URL.

onclick open window and specific size

Anyone looking for a quick Vue file component, here you go:

// WindowUrl.vue

<template>
    <a :href="url" :class="classes" @click="open">
        <slot></slot>
    </a>
</template>

<script>
    export default {
        props: {
            url: String,
            width: String,
            height: String,
            classes: String,
        },
        methods: {
            open(e) {
                // Prevent the link from opening on the parent page.
                e.preventDefault();

                window.open(
                    this.url,
                    'targetWindow',
                    `toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=yes,width=${this.width},height=${this.height}`
                );
            }
        }
    }
</script>

Usage:

<window-url url="/print/shipping" class="btn btn-primary" height="250" width="250">
    Print Shipping Label
</window-url>

Detect whether Office is 32bit or 64bit via the registry

Another way to detect the bitness of Office is to find out the typelib.

For example, to detect Outlook's bitness, write a .JS file as following:

function detectVersion()
    var outlooktlib = "TypeLib\\{00062FFF-0000-0000-C000-000000000046}";
    var HKCR = 0x80000000;

    var loc = new ActiveXObject("WbemScripting.SWbemLocator");
    var svc = loc.ConnectServer(null,"root\\default");
    var reg = svc.Get("StdRegProv");

    var method = reg.Methods_.Item("EnumKey");
    var inparam = method.InParameters.SpawnInstance_();
    inparam.hDefKey = HKCR;
    inparam.sSubKeyName = outlooktlib;
    var outparam = reg.ExecMethod_(method.Name,inparam);
    tlibver = outparam.sNames.toArray()[0];

    method = reg.Methods_.Item("GetStringValue");
    inparam = method.InParameters.SpawnInstance_();
    inparam.hDefKey = HKCR;
    inparam.sSubKeyName = outlooktlib + "\\" + tlibver + "\\0\\win32";
    inparam.sValueName = "";
    outparam = reg.ExecMethod_(method.Name,inparam);
    if(outparam.sValue) return "32 bit";

    method = reg.Methods_.Item("GetStringValue");
    inparam = method.InParameters.SpawnInstance_();
    inparam.hDefKey = HKCR;
    inparam.sSubKeyName = outlooktlib + "\\" + tlibver + "\\0\\win64";
    inparam.sValueName = "";
    outparam = reg.ExecMethod_(method.Name,inparam);
    if(outparam.sValue) return "64 bit";

    return "Not installed or unrecognizable";
}

You could find out other Office component's typelib id, and replace the first line of the function for it. Here is a brief list of interesting IDs:

{4AFFC9A0-5F99-101B-AF4E-00AA003F0F07} - Access
{00020905-0000-0000-C000-000000000046} - Word
{00020813-0000-0000-C000-000000000046} - Excel
{91493440-5A91-11CF-8700-00AA0060263B} - Powerpoint
{0002123C-0000-0000-C000-000000000046} - Publisher
{0EA692EE-BB50-4E3C-AEF0-356D91732725} - OneNote 2010+
{F2A7EE29-8BF6-4A6D-83F1-098E366C709C} - OneNote 2007

All above lib id were found through the Windows SDK tool OLE-COM Object Viewer, you could find out more lib id's by using it.

The benefit of this approach is that it works for all versions of office, and provides control on every single component in you interest. Furthermore, those keys are in the HKEY_CLASSES_ROOT and deeply integrated into the system, so it is highly unlikely they were not accessible even in a sandbox environment.

How to vertically align elements in a div?

As per today, I have found a new workaround to vertically align multiple text-lines in a div using CSS3 (and I am also using bootstrap v3 grid system to beautify the UI), which is as below:

.immediate-parent-of-text-containing-div{
    height: 50px;         /* or any fixed height that suits you.*/
}

.text-containing-div {
    display: inline-grid;
    align-items: center;
    text-align: center;
    height: 100%;
}

As per my understanding, immediate parent of text containing element must have some height. I hope it will help you too. Thanks!

How do I fix 'Invalid character value for cast specification' on a date column in flat file?

I was ultimately able to resolve the solution by setting the column type in the flat file connection to be of type "database date [DT_DBDATE]"

Apparently the differences between these date formats are as follow:

DT_DATE A date structure that consists of year, month, day, and hour.

DT_DBDATE A date structure that consists of year, month, and day.

DT_DBTIMESTAMP A timestamp structure that consists of year, month, hour, minute, second, and fraction

By changing the column type to DT_DBDATE the issue was resolved - I attached a Data Viewer and the CYCLE_DATE value was now simply "12/20/2010" without a time component, which apparently resolved the issue.

Check if a string is null or empty in XSLT

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

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

So you can simply test the attribute.

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

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

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

Will return true for a null element.

CORS Access-Control-Allow-Headers wildcard being ignored?

here's the incantation for nginx, inside a

location / {
    # Simple requests
    if ($request_method ~* "(GET|POST)") {
      add_header "Access-Control-Allow-Origin"  *;
    }

    # Preflighted requests
    if ($request_method = OPTIONS ) {
      add_header "Access-Control-Allow-Origin"  *;
      add_header "Access-Control-Allow-Methods" "GET, POST, OPTIONS, HEAD";
      add_header "Access-Control-Allow-Headers" "Authorization, Origin, X-Requested-With, Content-Type, Accept";
    }

}

Is there possibility of sum of ArrayList without looping

The only alternative to using a loop is to use recursion.

You can define a method like

public static int sum(List<Integer> ints) {
   return ints.isEmpty() ? 0 : ints.get(0) + ints.subList(1, ints.length());
}

This is very inefficient compared to using a plain loop and can blow up if you have many elements in the list.

An alternative which avoid a stack overflow is to use.

public static int sum(List<Integer> ints) {
    int len = ints.size();
    if (len == 0) return 0;
    if (len == 1) return ints.get(0);
    return sum(ints.subList(0, len/2)) + sum(ints.subList(len/2, len));
}

This is just as inefficient, but will avoid a stack overflow.


The shortest way to write the same thing is

int sum = 0, a[] = {2, 4, 6, 8};

for(int i: a) {
    sum += i;
}

System.out.println("sum(a) = " + sum);

prints

sum(a) = 20

How to download python from command-line?

apt-get install python2.7 will work on debian-like linuxes. The python website describes a whole bunch of other ways to get Python.

What is CDATA in HTML?

CDATA is Obsolete.

Note that CDATA sections should not be used within HTML; they only work in XML.

So do not use it in HTML 5.

https://developer.mozilla.org/en-US/docs/Web/API/CDATASection#Specifications

Screenshot from MDN

adding comment in .properties files

According to the documentation of the PropertyFile task, you can append the generated properties to an existing file. You could have a properties file with just the comment line, and have the Ant task append the generated properties.

c# .net change label text

When I had this problem I could see only a part of my text and this is the solution for that:

Be sure to set the AutoSize property to true.

output.AutoSize = true;

How to parse a date?

How about getSelectedDate? Anyway, specifically on your code question, the problem is with this line:

new SimpleDateFormat("yyyy-MM-dd");

The string that goes in the constructor has to match the format of the date. The documentation for how to do that is here. Looks like you need something close to "EEE MMM d HH:mm:ss zzz yyyy"

What does "Could not find or load main class" mean?

By default, Java uses ., the current working directory, as the default CLASSPATH. What this means is that when you type a command at the prompt e.g. java MyClass, the command is interpreted as if you had type java -cp . MyClass. Did you see that dot between -cp and MyClass? (cp is short for the longer classpath option)

This is sufficient for most cases and things seems to work just fine until at some time you try to add a directory to your CLASSPATH. In most cases when programmers need to do this, they just run a command like set CLASSPATH=path\to\some\dir. This command creates a new environment variable called CLASSPATH having the value path\to\some\dir or replaces its value with path\to\some\dir if CLASSPATH was already set before.

When this is done, you now have a CLASSPATH environment variable and Java no longer uses its default classpath (.) but the one you've set. So the next day you open your editor, write some java program, cd to the directory where you saved it, compile it, and try to run it with the command java MyClass, and you are greeted with a nice output: Could not find or load main class ... (If your commands were working well before and you are now getting this output, then this might be the case for you).

What happens is that when you run the command java MyClass, Java searches for the class file named MyClass in the directory or directories that you have set in your CLASSPATH and not your current working directory so it doesn't find your class file there and hence complains.

What you need to do is add . to your class path again which can be done with the command set CLASSPATH=%CLASSPATH%;. (notice the dot after the semicolon). In plain english this command says "Pick what was initially the value of CLASSPATH (%CLASSPATH%), add . to it (;.) and assign the result back to CLASSPATH".

And voila, you are once again able to use your command java MyClass as usual.

How to get the SHA-1 fingerprint certificate in Android Studio for debug mode?

I did this way:

Step 1: Go to this folder

On Mac: /Users/<username>/.android/

On Windows: C:\Documents and Settings\<username>\.android\

On Linux: ~/.android/

Step 2: Run this command line:

keytool -list -v -keystore debug.keystore -storepass android

You will see the SHA-1 key.

'list' object has no attribute 'shape'

Use numpy.array to use shape attribute.

>>> import numpy as np
>>> X = np.array([
...     [[-9.035250067710876], [7.453250169754028], [33.34074878692627]],
...     [[-6.63700008392334], [5.132999956607819], [31.66075038909912]],
...     [[-5.1272499561309814], [8.251499891281128], [30.925999641418457]]
... ])
>>> X.shape
(3L, 3L, 1L)

NOTE X.shape returns 3-items tuple for the given array; [n, T] = X.shape raises ValueError.

SQL Server 2012 column identity increment jumping from 6 to 1000+ on 7th entry

Got the same problem, found the following bug report in SQL Server 2012 If still relevant see conditions that cause the issue - there are some workarounds there as well (didn't try though). Failover or Restart Results in Reseed of Identity

How do I run a Python program?

In IDLE press F5

You can open your .py file with IDLE and press F5 to run it.

You can open that same file with other editor ( like Komodo as you said ) save it and press F5 again; F5 works with IDLE ( even when the editing is done with another tool ).

If you want to run it directly from Komodo according to this article: Executing Python Code Within Komodo Edit you have to:

  1. go to Toolbox -> Add -> New Command...
  2. in the top field enter the name 'Run Python file'
  3. in the 'Command' field enter this text:

    %(python) %F 3.a optionall click on the 'Key Binding' tab and assign a key command to this command

  4. click Ok.

Using BETWEEN in CASE SQL statement

Take out the MONTHS from your case, and remove the brackets... like this:

CASE 
    WHEN RATE_DATE BETWEEN '2010-01-01' AND '2010-01-31' THEN 'JANUARY'
    ELSE 'NOTHING'
END AS 'MONTHS'

You can think of this as being equivalent to:

CASE TRUE
    WHEN RATE_DATE BETWEEN '2010-01-01' AND '2010-01-31' THEN 'JANUARY'
    ELSE 'NOTHING'
END AS 'MONTHS'

Display filename before matching line

This is a slight modification from a previous solution. My example looks for stderr redirection in bash scripts: grep '2>' $(find . -name "*.bash")

Parsing JSON in Spring MVC using Jackson JSON

I'm using json lib from http://json-lib.sourceforge.net/
json-lib-2.1-jdk15.jar

import net.sf.json.JSONObject;
...

public void send()
{
    //put attributes
    Map m = New HashMap();
    m.put("send_to","[email protected]");
    m.put("email_subject","this is a test email");
    m.put("email_content","test email content");

    //generate JSON Object
    JSONObject json = JSONObject.fromObject(content);
    String message = json.toString();
    ...
}

public void receive(String jsonMessage)
{
    //parse attributes
    JSONObject json = JSONObject.fromObject(jsonMessage);
    String to = (String) json.get("send_to");
    String title = (String) json.get("email_subject");
    String content = (String) json.get("email_content");
    ...
}

More samples here http://json-lib.sourceforge.net/usage.html

Can you run GUI applications in a Docker container?

I managed to run a video stream from an USB camera using opencv in docker by following these steps:

  1. Let docker access the X server

    xhost +local:docker
    
  2. Create the X11 Unix socket and the X authentication file

    XSOCK=/tmp/.X11-unix
    XAUTH=/tmp/.docker.xauth
    
  3. Add proper permissions

    xauth nlist $DISPLAY | sed -e 's/^..../ffff/' | xauth -f $XAUTH nmerge -
    
  4. Set the Qt rendering speed to "native", so it doesn't bypass the X11 rendering engine

    export QT_GRAPHICSSYSTEM=native
    
  5. Tell Qt to not use MIT-SHM (shared memory) - that way it should be also safer security-wise

    export QT_X11_NO_MITSHM=1
    
  6. Update the docker run command

    docker run -it \
               -e DISPLAY=$DISPLAY \
               -e XAUTHORITY=$XAUTH \
               -v $XSOCK:$XSOCK \
               -v $XAUTH:$XAUTH \
               --runtime=nvidia \
               --device=/dev/video0:/dev/video0 \
               nvcr.io/nvidia/pytorch:19.10-py3
    

Note: When you finish the the project, return the access controls at their default value - xhost -local:docker

More details: Using GUI's with Docker

Credit: Real-time and video processing object detection using Tensorflow, OpenCV and Docker

Why do I get PLS-00302: component must be declared when it exists?

You can get that error if you have an object with the same name as the schema. For example:

create sequence s2;

begin
  s2.a;
end;
/

ORA-06550: line 2, column 6:
PLS-00302: component 'A' must be declared
ORA-06550: line 2, column 3:
PL/SQL: Statement ignored

When you refer to S2.MY_FUNC2 the object name is being resolved so it doesn't try to evaluate S2 as a schema name. When you just call it as MY_FUNC2 there is no confusion, so it works.

The documentation explains name resolution. The first piece of the qualified object name - S2 here - is evaluated as an object on the current schema before it is evaluated as a different schema.

It might not be a sequence; other objects can cause the same error. You can check for the existence of objects with the same name by querying the data dictionary.

select owner, object_type, object_name
from all_objects
where object_name = 'S2';

Android - set TextView TextStyle programmatically?

Search for setTextAppearance or also setTextTypeface. There is similar question on stackoverflow: How to change a TextView's style at runtime

Disable/enable an input with jQuery?

There are many ways using them you can enable/disable any element :

Approach 1

$("#txtName").attr("disabled", true);

Approach 2

$("#txtName").attr("disabled", "disabled");

If you are using jQuery 1.7 or higher version then use prop(), instead of attr().

$("#txtName").prop("disabled", "disabled");

If you wish to enable any element then you just have to do opposite of what you did to make it disable. However jQuery provides another way to remove any attribute.

Approach 1

$("#txtName").attr("disabled", false);

Approach 2

$("#txtName").attr("disabled", "");

Approach 3

$("#txtName").removeAttr("disabled");

Again, if you are using jQuery 1.7 or higher version then use prop(), instead of attr(). That's is. This is how you enable or disable any element using jQuery.

Progress Bar with HTML and CSS

http://jsfiddle.net/cwZSW/1406/

_x000D_
_x000D_
#progress {_x000D_
    background: #333;_x000D_
    border-radius: 13px;_x000D_
    height: 20px;_x000D_
    width: 300px;_x000D_
    padding: 3px;_x000D_
}_x000D_
_x000D_
#progress:after {_x000D_
    content: '';_x000D_
    display: block;_x000D_
    background: orange;_x000D_
    width: 50%;_x000D_
    height: 100%;_x000D_
    border-radius: 9px;_x000D_
}
_x000D_
<div id="progress"></div>
_x000D_
_x000D_
_x000D_

What is the difference between window, screen, and document in Javascript?

the window contains everything, so you can call window.screen and window.document to get those elements. Check out this fiddle, pretty-printing the contents of each object: http://jsfiddle.net/JKirchartz/82rZu/

You can also see the contents of the object in firebug/dev tools like this:

console.dir(window);
console.dir(document);
console.dir(screen);

window is the root of everything, screen just has screen dimensions, and document is top DOM object. so you can think of it as window being like a super-document...

getDate with Jquery Datepicker

This line looks questionable:

page_output.innerHTML = str_output;

You can use .innerHTML within jQuery, or you can use it without, but you have to address the selector semantically one way or the other:

$('#page_output').innerHTML /* for jQuery */
document.getElementByID('page_output').innerHTML /* for standard JS */

or better yet

$('#page_output').html(str_output);

how to convert a string to an array in php

With explode function of php

$array=explode(" ",$str); 

This is a quick example for you http://codepad.org/Pbg4n76i

Excel: last character/string match in a string

How about creating a custom function and using that in your formula? VBA has a built-in function, InStrRev, that does exactly what you're looking for.

Put this in a new module:

Function RSearch(str As String, find As String)
    RSearch = InStrRev(str, find)
End Function

And your function will look like this (assuming the original string is in B1):

=LEFT(B1,RSearch(B1,"\"))

Configuring Log4j Loggers Programmatically

If someone comes looking for configuring log4j2 programmatically in Java, then this link could help: (https://www.studytonight.com/post/log4j2-programmatic-configuration-in-java-class)

Here is the basic code for configuring a Console Appender:

ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();

builder.setStatusLevel(Level.DEBUG);
// naming the logger configuration
builder.setConfigurationName("DefaultLogger");

// create a console appender
AppenderComponentBuilder appenderBuilder = builder.newAppender("Console", "CONSOLE")
                .addAttribute("target", ConsoleAppender.Target.SYSTEM_OUT);
// add a layout like pattern, json etc
appenderBuilder.add(builder.newLayout("PatternLayout")
                .addAttribute("pattern", "%d %p %c [%t] %m%n"));
RootLoggerComponentBuilder rootLogger = builder.newRootLogger(Level.DEBUG);
rootLogger.add(builder.newAppenderRef("Console"));

builder.add(appenderBuilder);
builder.add(rootLogger);
Configurator.reconfigure(builder.build());

This will reconfigure the default rootLogger and will also create a new appender.

Decoding UTF-8 strings in Python

You need to properly decode the source text. Most likely the source text is in UTF-8 format, not ASCII.

Because you do not provide any context or code for your question it is not possible to give a direct answer.

I suggest you study how unicode and character encoding is done in Python:

http://docs.python.org/2/howto/unicode.html

How to scroll to an element?

I used this inside a onclick function to scroll smoothly to a div where its id is "step2Div".

let offset = 100;
window.scrollTo({
    behavior: "smooth",
    top:
    document.getElementById("step2Div").getBoundingClientRect().top -
    document.body.getBoundingClientRect().top -
    offset
});

subsampling every nth entry in a numpy array

You can use numpy's slicing, simply start:stop:step.

>>> xs
array([1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4])
>>> xs[1::4]
array([2, 2, 2])

This creates a view of the the original data, so it's constant time. It'll also reflect changes to the original array and keep the whole original array in memory:

>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2]         # O(1), constant time
>>> b[:] = 0           # modifying the view changes original array
>>> a                  # original array is modified
array([0, 2, 0, 4, 0])

so if either of the above things are a problem, you can make a copy explicitly:

>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2].copy()  # explicit copy, O(n)
>>> b[:] = 0           # modifying the copy
>>> a                  # original is intact
array([1, 2, 3, 4, 5])

This isn't constant time, but the result isn't tied to the original array. The copy also contiguous in memory, which can make some operations on it faster.

Running multiple async tasks and waiting for them all to complete

Yet another answer...but I usually find myself in a case, when I need to load data simultaneously and put it into variables, like:

var cats = new List<Cat>();
var dog = new Dog();

var loadDataTasks = new Task[]
{
    Task.Run(async () => cats = await LoadCatsAsync()),
    Task.Run(async () => dog = await LoadDogAsync())
};

try
{
    await Task.WhenAll(loadDataTasks);
}
catch (Exception ex)
{
    // handle exception
}

How to check if a variable is an integer or a string?

Depending on your definition of shortly, you could use one of the following options:

Find records with a date field in the last 24 hours

SELECT * FROM news WHERE date < DATEADD(Day, -1, date)

MySQL SELECT x FROM a WHERE NOT IN ( SELECT x FROM b ) - Unexpected result

From documentation:

To comply with the SQL standard, IN returns NULL not only if the expression on the left hand side is NULL, but also if no match is found in the list and one of the expressions in the list is NULL.

This is exactly your case.

Both IN and NOT IN return NULL which is not an acceptable condition for WHERE clause.

Rewrite your query as follows:

SELECT  *
FROM    match m
WHERE   NOT EXISTS
        (
        SELECT  1
        FROM    email e
        WHERE   e.id = m.id
        )

how to open .mat file without using MATLAB?

Download Notepad++ (notepad-plus-plus.org) it opens nearly any file format and recognizes breaks, comments and does all the same color coding as the original language formatting.

How to access host port from docker container

For me (Windows 10, Docker Engine v19.03.8) it was a mix of https://stackoverflow.com/a/43541732/7924573 and https://stackoverflow.com/a/50866007/7924573 .

  1. change the host/ip to host.docker.internal
    e.g.: LOGGER_URL = "http://host.docker.internal:8085/log"
  2. set the network_mode to bridge (if you want to maintain the port forwarding; if not use host):
    version: '3.7' services: server: build: . ports: - "5000:5000" network_mode: bridge or alternatively: Use --net="bridge" if you are not using docker-compose (similar to https://stackoverflow.com/a/48806927/7924573)
    As pointed out in previous answers: This should only be used in a local development environment.
    For more information read: https://docs.docker.com/compose/compose-file/#network_mode and https://docs.docker.com/docker-for-windows/networking/#use-cases-and-workarounds

Timestamp to human readable format

use Date.prototype.toLocaleTimeString() as documented here

please note the locale example en-US in the url.

How to make a DIV not wrap?

Try using white-space: nowrap; in the container style (instead of overflow: hidden;)

C# Validating input for textbox on winforms

Description

There are many ways to validate your TextBox. You can do this on every keystroke, at a later time, or on the Validating event.

The Validating event gets fired if your TextBox looses focus. When the user clicks on a other Control, for example. If your set e.Cancel = true the TextBox doesn't lose the focus.

MSDN - Control.Validating Event When you change the focus by using the keyboard (TAB, SHIFT+TAB, and so on), by calling the Select or SelectNextControl methods, or by setting the ContainerControl.ActiveControl property to the current form, focus events occur in the following order

Enter

GotFocus

Leave

Validating

Validated

LostFocus

When you change the focus by using the mouse or by calling the Focus method, focus events occur in the following order:

Enter

GotFocus

LostFocus

Leave

Validating

Validated

Sample Validating Event

private void textBox1_Validating(object sender, CancelEventArgs e)
{
    if (textBox1.Text != "something")
        e.Cancel = true;
}

Update

You can use the ErrorProvider to visualize that your TextBox is not valid. Check out Using Error Provider Control in Windows Forms and C#

More Information

Define variable to use with IN operator (T-SQL)

Use a function like this:

CREATE function [dbo].[list_to_table] (@list varchar(4000))
returns @tab table (item varchar(100))
begin

if CHARINDEX(',',@list) = 0 or CHARINDEX(',',@list) is null
begin
    insert into @tab (item) values (@list);
    return;
end


declare @c_pos int;
declare @n_pos int;
declare @l_pos int;

set @c_pos = 0;
set @n_pos = CHARINDEX(',',@list,@c_pos);

while @n_pos > 0
begin
    insert into @tab (item) values (SUBSTRING(@list,@c_pos+1,@n_pos - @c_pos-1));
    set @c_pos = @n_pos;
    set @l_pos = @n_pos;
    set @n_pos = CHARINDEX(',',@list,@c_pos+1);
end;

insert into @tab (item) values (SUBSTRING(@list,@l_pos+1,4000));

return;
end;

Instead of using like, you make an inner join with the table returned by the function:

select * from table_1 where id in ('a','b','c')

becomes

select * from table_1 a inner join [dbo].[list_to_table] ('a,b,c') b on (a.id = b.item)

In an unindexed 1M record table the second version took about half the time...

cheers

What does axis in pandas mean?

The designer of pandas, Wes McKinney, used to work intensively on finance data. Think of columns as stock names and index as daily prices. You can then guess what the default behavior is (i.e., axis=0) with respect to this finance data. axis=1 can be simply thought as 'the other direction'.

For example, the statistics functions, such as mean(), sum(), describe(), count() all default to column-wise because it makes more sense to do them for each stock. sort_index(by=) also defaults to column. fillna(method='ffill') will fill along column because it is the same stock. dropna() defaults to row because you probably just want to discard the price on that day instead of throw away all prices of that stock.

Similarly, the square brackets indexing refers to the columns since it's more common to pick a stock instead of picking a day.

How to solve npm error "npm ERR! code ELIFECYCLE"

I've been bothered by this issue for a long time. For me, the version of node was the problem.

My npm and node were 6.1.0 and 8.11.3, respectively. However, I didn't realize that I had updated my node accidentally to 12.*.*.

It then began to install GCX stuff whenever npm i, which was unnecessary before.

I downgraded my node to 8 and it worked!

Using Linq select list inside list

After my previous answer disaster, I'm going to try something else.

List<Model> usrList  = 
(list.Where(n => n.application == "applicationame").ToList());
usrList.ForEach(n => n.users.RemoveAll(n => n.surname != "surname"));

How do you get a list of the names of all files present in a directory in Node.js?

This will work and store the result in test.txt file which will be present in the same directory

  fs.readdirSync(__dirname).forEach(file => {
    fs.appendFileSync("test.txt", file+"\n", function(err){
    })
})

jquery: change the URL address without redirecting?

See here - http://my.opera.com/community/forums/topic.dml?id=1319992&t=1331393279&page=1#comment11751402

Essentially:

history.pushState('data', '', 'http://your-domain/path');

You can manipulate the history object to make this work.

It only works on the same domain, but since you're satisfied with using the hash tag approach, that shouldn't matter.

Obviously would need to be cross-browser tested, but since that was posted on the Opera forum I'm safe to assume it would work in Opera, and I just tested it in Chrome and it worked fine.

Open Bootstrap Modal from code-behind

This method of opening the Modal would not display the Modal for me. I found this as a work arround.

I removed:

 ScriptManager.RegisterStartupScript(this,this.GetType(),"Pop", "openModal();", true);

Than I added an asp:label named lblJavaScript and in code behind call:

lblJavaScript.Text = "<script language=\"JavaScript\">openModal()</script>";

Now the Modal will display.

Java Try and Catch IOException Problem

The reason you are getting the the IOException is because you are not catching the IOException of your countLines method. You'll want to do something like this:

public static void main(String[] args) {
  int lines = 0;  

  // TODO - Need to get the filename to populate sFileName.  Could
  // come from the command line arguments.

   try {
       lines = LineCounter.countLines(sFileName);
    }
    catch(IOException ex){
        System.out.println (ex.toString());
        System.out.println("Could not find file " + sFileName);
    }

   if(lines > 0) {
     // Do rest of program.
   }
}

Single controller with multiple GET methods in ASP.NET Web API

Have you tried switching over to WebInvokeAttribute and setting the Method to "GET"?

I believe I had a similar problem and switched to explicitly telling which Method (GET/PUT/POST/DELETE) is expected on most, if not all, my methods.

public class SomeController : ApiController
{
    [WebInvoke(UriTemplate = "{itemSource}/Items"), Method="GET"]
    public SomeValue GetItems(CustomParam parameter) { ... }

    [WebInvoke(UriTemplate = "{itemSource}/Items/{parent}", Method = "GET")]
    public SomeValue GetChildItems(CustomParam parameter, SomeObject parent) { ... }
}

The WebGet should handle it but I've seen it have some issues with multiple Get much less multiple Get of the same return type.

[Edit: none of this is valid with the sunset of WCF WebAPI and the migration to ASP.Net WebAPI on the MVC stack]

Git conflict markers

The line (or lines) between the lines beginning <<<<<<< and ====== here:

<<<<<<< HEAD:file.txt
Hello world
=======

... is what you already had locally - you can tell because HEAD points to your current branch or commit. The line (or lines) between the lines beginning ======= and >>>>>>>:

=======
Goodbye
>>>>>>> 77976da35a11db4580b80ae27e8d65caf5208086:file.txt

... is what was introduced by the other (pulled) commit, in this case 77976da35a11. That is the object name (or "hash", "SHA1sum", etc.) of the commit that was merged into HEAD. All objects in git, whether they're commits (version), blobs (files), trees (directories) or tags have such an object name, which identifies them uniquely based on their content.

In Perl, how can I concisely check if a $variable is defined and contains a non zero length string?

It isn't always possible to do repetitive things in a simple and elegant way.

Just do what you always do when you have common code that gets replicated across many projects:

Search CPAN, someone may have already the code for you. For this issue I found Scalar::MoreUtils.

If you don't find something you like on CPAN, make a module and put the code in a subroutine:

package My::String::Util;
use strict;
use warnings;
our @ISA = qw( Exporter );
our @EXPORT = ();
our @EXPORT_OK = qw( is_nonempty);

use Carp  qw(croak);

sub is_nonempty ($) {
    croak "is_nonempty() requires an argument" 
        unless @_ == 1;

    no warnings 'uninitialized';

    return( defined $_[0] and length $_[0] != 0 );
}

1;

=head1 BOILERPLATE POD

blah blah blah

=head3 is_nonempty

Returns true if the argument is defined and has non-zero length.    

More boilerplate POD.

=cut

Then in your code call it:

use My::String::Util qw( is_nonempty );

if ( is_nonempty $name ) {
    # do something with $name
}

Or if you object to prototypes and don't object to the extra parens, skip the prototype in the module, and call it like: is_nonempty($name).

Jquery to change form action

Please, see this answer: https://stackoverflow.com/a/3863869/2096619

Quoting Tamlyn:

jQuery (1.4.2) gets confused if you have any form elements named "action". You can get around this by using the DOM attribute methods or simply avoid having form elements named "action".

<form action="foo">
  <button name="action" value="bar">Go</button>
</form>

<script type="text/javascript">
  $('form').attr('action', 'baz'); //this fails silently
  $('form').get(0).setAttribute('action', 'baz'); //this works
</script>

MySQL case sensitive query

MySQL queries are not case-sensitive by default. Following is a simple query that is looking for 'value'. However it will return 'VALUE', 'value', 'VaLuE', etc…

SELECT * FROM `table` WHERE `column` = 'value'

The good news is that if you need to make a case-sensitive query, it is very easy to do using the BINARY operator, which forces a byte by byte comparison:

SELECT * FROM `table` WHERE BINARY `column` = 'value'

Oracle Age calculation from Date of birth and Today

select (SYSDATE-DOB)/365 "Age" from dual

File content into unix variable with newlines

The assignment does not remove the newline characters, it's actually the echo doing this. You need simply put quotes around the string to maintain those newlines:

echo "$testvar"

This will give the result you want. See the following transcript for a demo:

pax> cat num1.txt ; x=$(cat num1.txt)
line 1
line 2

pax> echo $x ; echo '===' ; echo "$x"
line 1 line 2
===
line 1
line 2

The reason why newlines are replaced with spaces is not entirely to do with the echo command, rather it's a combination of things.

When given a command line, bash splits it into words according to the documentation for the IFS variable:

IFS: The Internal Field Separator that is used for word splitting after expansion ... the default value is <space><tab><newline>.

That specifies that, by default, any of those three characters can be used to split your command into individual words. After that, the word separators are gone, all you have left is a list of words.

Combine that with the echo documentation (a bash internal command), and you'll see why the spaces are output:

echo [-neE] [arg ...]: Output the args, separated by spaces, followed by a newline.

When you use echo "$x", it forces the entire x variable to be a single word according to bash, hence it's not split. You can see that with:

pax> function count {
...>    echo $#
...> }
pax> count 1 2 3
3
pax> count a b c d
4
pax> count $x
4
pax> count "$x"
1

Here, the count function simply prints out the number of arguments given. The 1 2 3 and a b c d variants show it in action.

Then we try it with the two variations on the x variable. The one without quotes shows that there are four words, "test", "1", "test" and "2". Adding the quotes makes it one single word "test 1\ntest 2".

'if' statement in jinja2 template

Why the loop?

You could simply do this:

{% if 'priority' in data %}
    <p>Priority: {{ data['priority'] }}</p>
{% endif %}

When you were originally doing your string comparison, you should have used == instead.

contenteditable change events

Here's what worked for me:

   var clicked = {} 
   $("[contenteditable='true']").each(function(){       
        var id = $(this).attr("id");
        $(this).bind('focus', function() {
            // store the original value of element first time it gets focus
            if(!(id in clicked)){
                clicked[id] = $(this).html()
            }
        });
   });

   // then once the user clicks on save
   $("#save").click(function(){
            for(var id in clicked){
                var original = clicked[id];
                var current = $("#"+id).html();
                // check if value changed
                if(original != current) save(id,current);
            }
   });

How can I convert an HTML element to a canvas element?

Sorry, the browser won't render HTML into a canvas.

It would be a potential security risk if you could, as HTML can include content (in particular images and iframes) from third-party sites. If canvas could turn HTML content into an image and then you read the image data, you could potentially extract privileged content from other sites.

To get a canvas from HTML, you'd have to basically write your own HTML renderer from scratch using drawImage and fillText, which is a potentially huge task. There's one such attempt here but it's a bit dodgy and a long way from complete. (It even attempts to parse the HTML/CSS from scratch, which I think is crazy! It'd be easier to start from a real DOM node with styles applied, and read the styling using getComputedStyle and relative positions of parts of it using offsetTop et al.)

How do you check if a string is not equal to an object or other string value in java?

Change your || to && so it will only exit if the answer is NEITHER "AM" nor "PM".

Android "gps requires ACCESS_FINE_LOCATION" error, even though my manifest file contains this

My simple solution is this

if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) ==
        PackageManager.PERMISSION_GRANTED &&
        ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) ==
        PackageManager.PERMISSION_GRANTED) {
    googleMap.setMyLocationEnabled(true);
    googleMap.getUiSettings().setMyLocationButtonEnabled(true);
} else {
    Toast.makeText(this, R.string.error_permission_map, Toast.LENGTH_LONG).show();
}

or you can open permission dialog in else like this

} else {
   ActivityCompat.requestPermissions(this, new String[] {
      Manifest.permission.ACCESS_FINE_LOCATION, 
      Manifest.permission.ACCESS_COARSE_LOCATION }, 
      TAG_CODE_PERMISSION_LOCATION);
}

Subclipse svn:ignore

I just figured out how to do this:

It appears that when you add a parent folder to version control, Eclipse adds all sub-folders. Once the sub-folders are added to version control, it is not possible to ignore them.

Here's how to do it:

Right click on the top level folder and add to version control Right click on the child folder you want to ignore, revert Right click on the child folder you want to ignore, svn:ignore (which will now be available)

Python match a string with regex

r stands for a raw string, so things like \ will be automatically escaped by Python.

Normally, if you wanted your pattern to include something like a backslash you'd need to escape it with another backslash. raw strings eliminate this problem.

short explanation

In your case, it does not matter much but it's a good habit to get into early otherwise something like \b will bite you in the behind if you are not careful (will be interpreted as backspace character instead of word boundary)

As per re.match vs re.search here's an example that will clarify it for you:

>>> import re
>>> testString = 'hello world'
>>> re.match('hello', testString)
<_sre.SRE_Match object at 0x015920C8>
>>> re.search('hello', testString)
<_sre.SRE_Match object at 0x02405560>
>>> re.match('world', testString)
>>> re.search('world', testString)
<_sre.SRE_Match object at 0x015920C8>

So search will find a match anywhere, match will only start at the beginning

select rows in sql with latest date for each ID repeated multiple times

Have you tried the following:

SELECT ID, COUNT(*), max(date)
FROM table 
GROUP BY ID;

Convert normal Java Array or ArrayList to Json Array in android

This is the correct syntax:

String arlist1 [] = { "value1`", "value2", "value3" };
JSONArray jsonArray1 = new JSONArray(arlist1);

How do I create a link to add an entry to a calendar?

UPDATE (free for personal use):
HTTPS IS NOW SUPPORTED

While my answer below detailing how-to for each service WILL work, IMO it's much easier now to go with a third-party like AddThisEvent [https://addthisevent.com]. It lets you customize lots of options as well as add to Facebook and more. Unfortunately, they've now made it a paid service for anything other than personal use and do enforce this.

I assume there are other third-party solutions like this one, but I can only speak to this one, and it has worked great for us so far.


For an "Add to my Google Calendar", they used to have a code generator form you could use, but have since taken it down. For more details on Google Calendar links, see squarecandy's answer below.

For Outlook, it's a BIT more complicated, but basically you need to create a .vcs file with the event's data, and just make a link to that file. Step-by-step instructions here.

For an iCal link, you could use a PHP class like this one, or follow this page's instructions on how to create an ics file (iCal file).

How to pause for specific amount of time? (Excel/VBA)

Most of the presented solutions use Application.Wait, which does not take in account the time (miliseconds) already elapsed since the currend second count started, so they have an intrinsic imprecision of up to 1 second.

The Timer approach is the best solution, but you have to take in account the reset at midnight, so here is a very precise Sleep method using Timer:

'You can use integer (1 for 1 second) or single (1.5 for 1 and a half second)
Public Sub Sleep(vSeconds As Variant)
    Dim t0 As Single, t1 As Single
    t0 = Timer
    Do
        t1 = Timer
        If t1 < t0 Then t1 = t1 + 86400 'Timer overflows at midnight
        DoEvents    'optional, to avoid excel freeze while sleeping
    Loop Until t1 - t0 >= vSeconds
End Sub

USE THIS TO TEST ANY SLEEP FUNCTION: (open debug Immediate window: CTRL+G)

Sub testSleep()
    t0 = Timer
    Debug.Print "Time before sleep:"; t0   'Timer format is in seconds since midnight

    Sleep (1.5)

    Debug.Print "Time after sleep:"; Timer
    Debug.Print "Slept for:"; Timer - t0; "seconds"

End Sub

Error executing command 'ant' on Mac OS X 10.9 Mavericks when building for Android with PhoneGap/Cordova

In my case, I have macport installed already. I simply updated my macport:

sudo port selfupdate

sudo port upgrade outdated

Then install apache-ant:

sudo port install apache-ant

Finally, I add ant to my alias list in my .bash_profile:

alias ant='/opt/local/bin/ant'

Then you are all set.

Regular expression include and exclude special characters

You haven't actually asked a question, but assuming you have one, this could be your answer...

Assuming all characters, except the "Special Characters" are allowed you can write

String regex = "^[^<>'\"/;`%]*$";

Eclipse Intellisense?

You don't have to press CTRL * space but maybe the delay is too big or you don't like the trigger (default is '.'). Go to

Window -> Preferences -> Java/Editor/Content Assist

And change the settings under Auto Activation to your likings.

If this does not work for windows users then see this answer.

How can I auto increment the C# assembly version via our CI platform (Hudson)?

A simple alternative is to let the C# environment increment the assembly version for you by setting the version attribute to major.minor.* (as described in the AssemblyInfo file template.)

You may be looking for a more comprehensive solution, though.

EDIT (Response to the question in a comment):

From AssemblyInfo.cs:

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version 
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Build and Revision Numbers 
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]

Generating a unique machine id

Why not use the MAC address of your network card?

How can I auto-elevate my batch file, so that it requests from UAC administrator rights if required?

I use PowerShell to re-launch the script elevated if it's not. Put these lines at the very top of your script.

net file 1>nul 2>nul && goto :run || powershell -ex unrestricted -Command "Start-Process -Verb RunAs -FilePath '%comspec%' -ArgumentList '/c %~fnx0 %*'"
goto :eof
:run
:: TODO: Put code here that needs elevation

I copied the 'net name' method from @Matt's answer. His answer is much better documented and has error messages and the like. This one has the advantage that PowerShell is already installed and available on Windows 7 and up. No temporary VBScript (*.vbs) files, and you don't have to download tools.

This method should work without any configuration or setup, as long as your PowerShell execution permissions aren't locked down.

Python update a key in dict if it doesn't exist

Since Python 3.9 you can use the merge operator | to merge two dictionaries. The dict on the right takes precedence:

new_dict = old_dict | { key: val }

For example:

new_dict = { 'a': 1, 'b': 2 } | { 'b': 42 }

print(new_dict} # {'a': 1, 'b': 42}

Note: this creates a new dictionary with the updated values.

What is this CSS selector? [class*="span"]

It's an attribute wildcard selector. In the sample you've given, it looks for any child element under .show-grid that has a class that CONTAINS span.

So would select the <strong> element in this example:

<div class="show-grid">
    <strong class="span6">Blah blah</strong>
</div>

You can also do searches for 'begins with...'

div[class^="something"] { }

which would work on something like this:-

<div class="something-else-class"></div>

and 'ends with...'

div[class$="something"] { }

which would work on

<div class="you-are-something"></div>

Good references

How to export a mysql database using Command Prompt?

I have used wamp server. I tried on

c:\wamp\bin\mysql\mysql5.5.8\bin\mysqldump -uroot -p db_name > c:\somefolder\filename.sql

root is my username for mysql, and if you have any password specify it with:

-p[yourpassword]

Hope it works.

Using If/Else on a data frame

Use ifelse:

frame$twohouses <- ifelse(frame$data>=2, 2, 1)
frame
   data twohouses
1     0         1
2     1         1
3     2         2
4     3         2
5     4         2
...
16    0         1
17    2         2
18    1         1
19    2         2
20    0         1
21    4         2

The difference between if and ifelse:

  • if is a control flow statement, taking a single logical value as an argument
  • ifelse is a vectorised function, taking vectors as all its arguments.

The help page for if, accessible via ?"if" will also point you to ?ifelse

List of special characters for SQL LIKE clause

You should add that you have to add an extra ' to escape an exising ' in SQL Server:

smith's -> smith''s

SQL ROWNUM how to return rows between a specific range

SELECT * FROM
(SELECT ROW_NUMBER() OVER(ORDER BY Id) AS RowNum, * FROM maps006) AS DerivedTable
WHERE RowNum BETWEEN 49 AND 101

Loading resources using getClass().getResource()

As a noobie I was confused by this until I realized that the so called "path" is the path relative to the MyClass.class file in the file system and not the MyClass.java file. My IDE copies the resources (like xx.jpg, xx.xml) to a directory local to the MyClass.class. For example, inside a pkg directory called "target/classes/pkg. The class-file location may be different for different IDE's and depending on how the build is structured for your application. You should first explore the file system and find the location of the MyClass.class file and the copied location of the associated resource you are seeking to extract. Then determine the path relative to the MyClass.class file and write that as a string value with "dots" and "slashes".

For example, here is how I make an app1.fxml file available to my javafx application where the relevant "MyClass.class" is implicitly "Main.class". The Main.java file is where this line of resource-calling code is contained. In my specific case the resources are copied to a location at the same level as the enclosing package folder. That is: /target/classes/pkg/Main.class and /target/classes/app1.fxml. So paraphrasing...the relative reference "../app1.fxml" is "start from Main.class, go up one directory level, now you can see the resource".

FXMLLoader loader = new FXMLLoader();
        loader.setLocation(getClass().getResource("../app1.fxml"));

Note that in this relative-path string "../app1.fxml", the first two dots reference the directory enclosing Main.class and the single "." indicates a file extension to follow. After these details become second nature, you will forget why it was confusing.

Verifying a specific parameter with Moq

I've been verifying calls in the same manner - I believe it is the right way to do it.

mockSomething.Verify(ms => ms.Method(
    It.IsAny<int>(), 
    It.Is<MyObject>(mo => mo.Id == 5 && mo.description == "test")
  ), Times.Once());

If your lambda expression becomes unwieldy, you could create a function that takes MyObject as input and outputs true/false...

mockSomething.Verify(ms => ms.Method(
    It.IsAny<int>(), 
    It.Is<MyObject>(mo => MyObjectFunc(mo))
  ), Times.Once());

private bool MyObjectFunc(MyObject myObject)
{
  return myObject.Id == 5 && myObject.description == "test";
}

Also, be aware of a bug with Mock where the error message states that the method was called multiple times when it wasn't called at all. They might have fixed it by now - but if you see that message you might consider verifying that the method was actually called.

EDIT: Here is an example of calling verify multiple times for those scenarios where you want to verify that you call a function for each object in a list (for example).

foreach (var item in myList)
  mockRepository.Verify(mr => mr.Update(
    It.Is<MyObject>(i => i.Id == item.Id && i.LastUpdated == item.LastUpdated),
    Times.Once());

Same approach for setup...

foreach (var item in myList) {
  var stuff = ... // some result specific to the item
  this.mockRepository
    .Setup(mr => mr.GetStuff(item.itemId))
    .Returns(stuff);
}

So each time GetStuff is called for that itemId, it will return stuff specific to that item. Alternatively, you could use a function that takes itemId as input and returns stuff.

this.mockRepository
    .Setup(mr => mr.GetStuff(It.IsAny<int>()))
    .Returns((int id) => SomeFunctionThatReturnsStuff(id));

One other method I saw on a blog some time back (Phil Haack perhaps?) had setup returning from some kind of dequeue object - each time the function was called it would pull an item from a queue.

how to show lines in common (reverse diff)?

I just learned the comm command from this thread, but wanted to add something extra: if the files are not sorted, and you don't want to touch the original files, you can pipe the outptut of the sort command. This leaves the original files intact. Works in bash, I can't say about other shells.

comm -1 -2 <(sort file1) <(sort file2)

This can be extended to compare command output, instead of files:

comm -1 -2 <(ls /dir1 | sort) <(ls /dir2 | sort)

Edit and replay XHR chrome/firefox etc?

My two suggestions:

  1. Chrome's Postman plugin + the Postman Interceptor Plugin. More Info: Postman Capturing Requests Docs

  2. If you're on Windows then Telerik's Fiddler is an option. It has a composer option to replay http requests, and it's free.

Run function from the command line

Something like this: call_from_terminal.py

# call_from_terminal.py
# Ex to run from terminal
# ip='"hi"'
# python -c "import call_from_terminal as cft; cft.test_term_fun(${ip})"
# or
# fun_name='call_from_terminal'
# python -c "import ${fun_name} as cft; cft.test_term_fun(${ip})"
def test_term_fun(ip):
    print ip

This works in bash.

$ ip='"hi"' ; fun_name='call_from_terminal' 
$ python -c "import ${fun_name} as cft; cft.test_term_fun(${ip})"
hi

Using Jquery Ajax to retrieve data from Mysql

This answer was for @
Neha Gandhi but I modified it for  people who use pdo and mysqli sing mysql functions are not supported. Here is the new answer 

    <html>
<!--Save this as index.php-->
      <script src="//code.jquery.com/jquery-1.9.1.js"></script>
        <script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
    
     <script type="text/javascript">
    
     $(document).ready(function() {
    
        $("#display").click(function() {                
    
          $.ajax({    //create an ajax request to display.php
            type: "GET",
            url: "display.php",             
            dataType: "html",   //expect html to be returned                
            success: function(response){                    
                $("#responsecontainer").html(response); 
                //alert(response);
            }
    
        });
    });
    });
    
    </script>
    
    <body>
    <h3 align="center">Manage Student Details</h3>
    <table border="1" align="center">
       <tr>
           <td> <input type="button" id="display" value="Display All Data" /> </td>
       </tr>
    </table>
    <div id="responsecontainer" align="center">
    
    </div>
    </body>
    </html>

<?php
// save this as display.php


    // show errors 
error_reporting(E_ALL);
ini_set('display_errors', 1);
    //errors ends here 
// call the page for connecting to the db
require_once('dbconnector.php');
?>
<?php
$get_member =" SELECT 
empid, lastName, firstName, email, usercode, companyid, userid, jobTitle, cell, employeetype, address ,initials   FROM employees";
$user_coder1 = $con->prepare($get_member);
$user_coder1 ->execute();

echo "<table border='1' >
<tr>
<td align=center> <b>Roll No</b></td>
<td align=center><b>Name</b></td>
<td align=center><b>Address</b></td>
<td align=center><b>Stream</b></td></td>
<td align=center><b>Status</b></td>";

while($row =$user_coder1->fetch(PDO::FETCH_ASSOC)){
$firstName = $row['firstName'];
$empid = $row['empid'];
$lastName =    $row['lastName'];
$cell =    $row['cell'];

    echo "<tr>";
    echo "<td align=center>$firstName</td>";
    echo "<td align=center>$empid</td>";
    echo "<td align=center>$lastName </td>";
    echo "<td align=center>$cell</td>";
    echo "<td align=center>$cell</td>";
    echo "</tr>";
}
echo "</table>";
?>

<?php
// save this as dbconnector.php
function connected_Db(){

    $dsn  = 'mysql:host=localhost;dbname=mydb;charset=utf8';
    $opt  = array(
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    );
    #echo "Yes we are connected";
    return new PDO($dsn,'username','password', $opt);
    
}
$con = connected_Db();
if($con){
//echo "me  is connected ";
}
else {
//echo "Connection faid ";
exit();
}
?>

Avoid web.config inheritance in child web application using inheritInChildApplications

It needs to go directly under the root <configuration> node and you need to set a path like this:

<?xml version="1.0"?>
<configuration>
    <location path="." inheritInChildApplications="false"> 
        <!-- Stuff that shouldn't be inherited goes in here -->
    </location>
</configuration>

A better way to handle configuration inheritance is to use a <clear/> in the child config wherever you don't want to inherit. So if you didn't want to inherit the parent config's connection strings you would do something like this:

<?xml version="1.0"?>
<configuration>
    <connectionStrings>
        <clear/>
        <!-- Child config's connection strings -->
    </connectionStrings>
</configuration>

How do I right align div elements?

Old answers. An update: use flexbox, pretty much works in all browsers now.

_x000D_
_x000D_
<div style="display: flex; justify-content: flex-end">_x000D_
  <div>I'm on the right</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

And you can get even fancier, simply:

_x000D_
_x000D_
<div style="display: flex; justify-content: space-around">_x000D_
  <div>Left</div>_x000D_
  <div>Right</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

And fancier:

_x000D_
_x000D_
<div style="display: flex; justify-content: space-around">_x000D_
   <div>Left</div>_x000D_
   <div>Middle</div>_x000D_
  <div>Right</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

ActionBar text color

just put this in your thme style.

<item name="android:textColorPrimary">@color/yourcolor</item>

disable horizontal scroll on mobile web

Depending on box sizing width 100% might not always be the best option. I would suggest

 width:100vw;
 overflow-x: scroll;

This can be applied in the context of body, html as has been suggested or you could just wrap the content that is having an issue in a div with these settings applied.

Using import fs from 'fs'

The new ECMAScript module support is able natively in Node.js 12

It was released on 2019-04-23 and it means there is no need to use the flag --experimental-modules.

To read more about it:

The new ECMAScript module support in Node.js 12

downcast and upcast

In case you need to check each of the Employee object whether it is a Manager object, use the OfType method:

List<Employee> employees = new List<Employee>();

//Code to add some Employee or Manager objects..

var onlyManagers = employees.OfType<Manager>();

foreach (Manager m in onlyManagers) {
  // Do Manager specific thing..
}

How to activate JMX on my JVM for access with jconsole?

I'm using WAS ND 7.0

My JVM need all the following arguments to be monitored in JConsole

    -Djavax.management.builder.initial= 
    -Dcom.sun.management.jmxremote 
    -Dcom.sun.management.jmxremote.port=8855 
    -Dcom.sun.management.jmxremote.authenticate=false 
    -Dcom.sun.management.jmxremote.ssl=false

Compiling Java 7 code via Maven

Diagnostics:

You can see which java version Maven uses by running "mvn --version"

Solution for Debian:

The mvn script sets the JAVA_HOME env variable internally by looking for javac (which javac). Therefore, if you have multiple java versions installed concurrently, e.g. JDK 6 and JDK 7 and use the Debian Alternatives system to choose between them, even though you changed the alternative for "java" to JDK 7, mvn will still use JDK 6. You have to change the alternative for "javac", too. E.g.:

# update-alternatives --set javac /usr/lib/jvm/java-7-openjdk-amd64/bin/javac

EDIT:

Actually, an even better solution is to use update-java-alternatives (e.g.)

# update-java-alternatives -s java-1.7.0-openjdk-amd64

as detailed in https://wiki.debian.org/JavaPackage, because this will change all the alternatives to various Java tools (there's a dozen or so).