Programs & Examples On #Directory structure

Questions that relate to the organization of files and directories in a filesystem.

mkdir's "-p" option

mkdir [-switch] foldername

-p is a switch which is optional, it will create subfolder and parent folder as well even parent folder doesn't exist.

From the man page:

-p, --parents no error if existing, make parent directories as needed

Example:

mkdir -p storage/framework/{sessions,views,cache}

This will create subfolder sessions,views,cache inside framework folder irrespective of 'framework' was available earlier or not.

Representing Directory & File Structure in Markdown Syntax

I made a node module to automate this task: mddir

Usage

node mddir "../relative/path/"

To install: npm install mddir -g

To generate markdown for current directory: mddir

To generate for any absolute path: mddir /absolute/path

To generate for a relative path: mddir ~/Documents/whatever.

The md file gets generated in your working directory.

Currently ignores node_modules, and .git folders.

Troubleshooting

If you receive the error 'node\r: No such file or directory', the issue is that your operating system uses different line endings and mddir can't parse them without you explicitly setting the line ending style to Unix. This usually affects Windows, but also some versions of Linux. Setting line endings to Unix style has to be performed within the mddir npm global bin folder.

Line endings fix

Get npm bin folder path with:

npm config get prefix

Cd into that folder

brew install dos2unix

dos2unix lib/node_modules/mddir/src/mddir.js

This converts line endings to Unix instead of Dos

Then run as normal with: node mddir "../relative/path/".

Example generated markdown file structure 'directoryList.md'

    |-- .bowerrc
    |-- .jshintrc
    |-- .jshintrc2
    |-- Gruntfile.js
    |-- README.md
    |-- bower.json
    |-- karma.conf.js
    |-- package.json
    |-- app
        |-- app.js
        |-- db.js
        |-- directoryList.md
        |-- index.html
        |-- mddir.js
        |-- routing.js
        |-- server.js
        |-- _api
            |-- api.groups.js
            |-- api.posts.js
            |-- api.users.js
            |-- api.widgets.js
        |-- _components
            |-- directives
                |-- directives.module.js
                |-- vendor
                    |-- directive.draganddrop.js
            |-- helpers
                |-- helpers.module.js
                |-- proprietary
                    |-- factory.actionDispatcher.js
            |-- services
                |-- services.cardTemplates.js
                |-- services.cards.js
                |-- services.groups.js
                |-- services.posts.js
                |-- services.users.js
                |-- services.widgets.js
        |-- _mocks
            |-- mocks.groups.js
            |-- mocks.posts.js
            |-- mocks.users.js
            |-- mocks.widgets.js

Java: How can I compile an entire directory structure of code ?

The already existing answers seem to only concern oneself with the *.java files themselves and not how to easily do it with library files that might be needed for the build.

A nice one-line situation which recursively gets all *.java files as well as includes *.jar files necessary for building is:

javac -cp ".:lib/*" -d bin $(find ./src/* | grep .java)

Here the bin file is the destination of class files, lib (and potentially the current working directory) contain the library files and all the java files in the src directory and beneath are compiled.

Best practice for Django project working directory structure

My answer is inspired on my own working experience, and mostly in the book Two Scoops of Django which I highly recommend, and where you can find a more detailed explanation of everything. I just will answer some of the points, and any improvement or correction will be welcomed. But there also can be more correct manners to achieve the same purpose.

Projects
I have a main folder in my personal directory where I maintain all the projects where I am working on.

Source Files
I personally use the django project root as repository root of my projects. But in the book is recommended to separate both things. I think that this is a better approach, so I hope to start making the change progressively on my projects.

project_repository_folder/
    .gitignore
    Makefile
    LICENSE.rst
    docs/
    README.rst
    requirements.txt
    project_folder/
        manage.py
        media/
        app-1/
        app-2/
        ...
        app-n/
        static/
        templates/
        project/
            __init__.py
            settings/
                __init__.py
                base.py
                dev.py
                local.py
                test.py
                production.py
            ulrs.py
            wsgi.py

Repository
Git or Mercurial seem to be the most popular version control systems among Django developers. And the most popular hosting services for backups GitHub and Bitbucket.

Virtual Environment
I use virtualenv and virtualenvwrapper. After installing the second one, you need to set up your working directory. Mine is on my /home/envs directory, as it is recommended on virtualenvwrapper installation guide. But I don't think the most important thing is where is it placed. The most important thing when working with virtual environments is keeping requirements.txt file up to date.

pip freeze -l > requirements.txt 

Static Root
Project folder

Media Root
Project folder

README
Repository root

LICENSE
Repository root

Documents
Repository root. This python packages can help you making easier mantaining your documentation:

Sketches

Examples

Database

What is the best project structure for a Python application?

The "Python Packaging Authority" has a sampleproject:

https://github.com/pypa/sampleproject

It is a sample project that exists as an aid to the Python Packaging User Guide's Tutorial on Packaging and Distributing Projects.

How to [recursively] Zip a directory in PHP?

Following @user2019515 answer, I needed to handle exclusions to my archive. here is the resulting function with an example.

Zip Function :

function Zip($source, $destination, $include_dir = false, $exclusions = false){
    // Remove existing archive
    if (file_exists($destination)) {
        unlink ($destination);
    }

    $zip = new ZipArchive();
    if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
        return false;
    }
    $source = str_replace('\\', '/', realpath($source));
    if (is_dir($source) === true){
        $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
        if ($include_dir) {
            $arr = explode("/",$source);
            $maindir = $arr[count($arr)- 1];
            $source = "";
            for ($i=0; $i < count($arr) - 1; $i++) {
                $source .= '/' . $arr[$i];
            }
            $source = substr($source, 1);
            $zip->addEmptyDir($maindir);
        }
        foreach ($files as $file){
            // Ignore "." and ".." folders
            $file = str_replace('\\', '/', $file);
            if(in_array(substr($file, strrpos($file, '/')+1), array('.', '..'))){
                continue;
            }

            // Add Exclusion
            if(($exclusions)&&(is_array($exclusions))){
                if(in_array(str_replace($source.'/', '', $file), $exclusions)){
                    continue;
                }
            }

            $file = realpath($file);
            if (is_dir($file) === true){
                $zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
            } elseif (is_file($file) === true){
                $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
            }
        }
    } elseif (is_file($source) === true){
        $zip->addFromString(basename($source), file_get_contents($source));
    }
    return $zip->close();
}

How to use it :

function backup(){
    $backup = 'tmp/backup-'.$this->site['version'].'.zip';
    $exclusions = [];
    // Excluding an entire directory
    $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('tmp/'), RecursiveIteratorIterator::SELF_FIRST);
    foreach ($files as $file){
        array_push($exclusions,$file);
    }
    // Excluding a file
    array_push($exclusions,'config/config.php');
    // Excluding the backup file
    array_push($exclusions,$backup);
    $this->Zip('.',$backup, false, $exclusions);
}

How to specify the JDK version in android studio?

For new Android Studio versions, go to C:\Program Files\Android\Android Studio\jre\bin(or to location of Android Studio installed files) and open command window at this location and type in following command in command prompt:-

java -version

List directory tree structure in python?

Here's a function to do that with formatting:

import os

def list_files(startpath):
    for root, dirs, files in os.walk(startpath):
        level = root.replace(startpath, '').count(os.sep)
        indent = ' ' * 4 * (level)
        print('{}{}/'.format(indent, os.path.basename(root)))
        subindent = ' ' * 4 * (level + 1)
        for f in files:
            print('{}{}'.format(subindent, f))

jQuery - What are differences between $(document).ready and $(window).load?

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  // executes when HTML-Document is loaded and DOM is ready_x000D_
  console.log("document is ready");_x000D_
});_x000D_
_x000D_
_x000D_
$(window).load(function() {_x000D_
  // executes when complete page is fully loaded, including all frames, objects and images_x000D_
  console.log("window is loaded");_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Query 3.0 version

Breaking change: .load(), .unload(), and .error() removed

These methods are shortcuts for event operations, but had several API limitations. The event .load() method conflicted with the ajax .load() method. The .error() method could not be used with window.onerror because of the way the DOM method is defined. If you need to attach events by these names, use the .on() method, e.g. change $("img").load(fn) to $(img).on("load", fn).1

$(window).load(function() {});

Should be changed to

$(window).on('load', function (e) {})

These are all equivalent:

$(function(){
}); 

jQuery(document).ready(function(){
});

$(document).ready(function(){
});

$(document).on('ready', function(){
})

Creating and Naming Worksheet in Excel VBA

Are you using an error handler? If you're ignoring errors and try to name a sheet the same as an existing sheet or a name with invalid characters, it could be just skipping over that line. See the CleanSheetName function here

http://www.dailydoseofexcel.com/archives/2005/01/04/naming-a-sheet-based-on-a-cell/

for a list of invalid characters that you may want to check for.

Update

Other things to try: Fully qualified references, throwing in a Doevents, code cleaning. This code qualifies your Sheets reference to ThisWorkbook (you can change it to ActiveWorkbook if that suits). It also adds a thousand DoEvents (stupid overkill, but if something's taking a while to get done, this will allow it to - you may only need one DoEvents if this actually fixes anything).

Dim WS As Worksheet
Dim i As Long

With ThisWorkbook
    Set WS = .Worksheets.Add(After:=.Sheets(.Sheets.Count))
End With

For i = 1 To 1000
    DoEvents
Next i

WS.Name = txtSheetName.Value

Finally, whenever I have a goofy VBA problem that just doesn't make sense, I use Rob Bovey's CodeCleaner. It's an add-in that exports all of your modules to text files then re-imports them. You can do it manually too. This process cleans out any corrupted p-code that's hanging around.

Java Timer vs ExecutorService?

Here's some more good practices around Timer use:

http://tech.puredanger.com/2008/09/22/timer-rules/

In general, I'd use Timer for quick and dirty stuff and Executor for more robust usage.

How to check if a variable is set in Bash?

My preferred way is this:

$ var=10
$ if ! ${var+false};then echo "is set";else echo "NOT set";fi
is set
$ unset -v var
$ if ! ${var+false};then echo "is set";else echo "NOT set";fi
NOT set

So basically, if a variable is set, it becomes "a negation of the resulting false" (what will be true = "is set").

And, if it is unset, it will become "a negation of the resulting true" (as the empty result evaluates to true) (so will end as being false = "NOT set").

Get city name using geolocation

As @PirateApp mentioned in his comment, it's explicitly against Google's Maps API Licensing to use the Maps API as you intend.

You have a number of alternatives, including downloading a Geoip database and querying it locally or using a third party API service, such as my service ipdata.co.

ipdata gives you the geolocation, organisation, currency, timezone, calling code, flag and Tor Exit Node status data from any IPv4 or IPv6 address.

And is scalable with 10 global endpoints each able to handle >10,000 requests per second!

This answer uses a 'test' API Key that is very limited and only meant for testing a few calls. Signup for your own Free API Key and get up to 1500 requests daily for development.

_x000D_
_x000D_
$.get("https://api.ipdata.co?api-key=test", function(response) {_x000D_
  $("#ip").html("IP: " + response.ip);_x000D_
  $("#city").html(response.city + ", " + response.region);_x000D_
  $("#response").html(JSON.stringify(response, null, 4));_x000D_
}, "jsonp");
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<h1><a href="https://ipdata.co">ipdata.co</a> - IP geolocation API</h1>_x000D_
_x000D_
<div id="ip"></div>_x000D_
<div id="city"></div>_x000D_
<pre id="response"></pre>
_x000D_
_x000D_
_x000D_

The fiddle; https://jsfiddle.net/ipdata/6wtf0q4g/922/

"undefined" function declared in another file?

Just use the command go run *.go to execute all the go files in your package!

Concatenating date with a string in Excel

This is the numerical representation of the date. The thing you get when referring to dates from formulas like that.

You'll have to do:

= A1 & TEXT(A2, "mm/dd/yyyy")

The biggest problem here is that the format specifier is locale-dependent. It will not work/produce not what expected if the file is opened with a differently localized Excel.

Now, you could have a user-defined function:

public function AsDisplayed(byval c as range) as string
  AsDisplayed = c.Text
end function

and then

= A1 & AsDisplayed(A2)

But then there's a bug (feature?) in Excel because of which the .Text property is suddenly not available during certain stages of the computation cycle, and your formulas display #VALUE instead of what they should.

That is, it's bad either way.

Passing on command line arguments to runnable JAR

You can also set a Java property, i.e. environment variable, on the command line and easily use it anywhere in your code.

The command line would be done this way:

c:/> java -jar -Dmyvar=enwiki-20111007-pages-articles.xml wiki2txt

and the java code accesses the value like this:

String context = System.getProperty("myvar"); 

See this question about argument passing in Java.

Adding click event for a button created dynamically using jQuery

Question 1: Use .delegate on the div to bind a click handler to the button.

Question 2: Use $(this).val() or this.value (the latter would be faster) inside of the click handler. this will refer to the button.

$("#pg_menu_content").on('click', '#btn_a', function () {
  alert($(this).val());
});

$div = $('<div data-role="fieldcontain"/>');
$("<input type='button' value='Dynamic Button' id='btn_a' />").appendTo($div.clone()).appendTo('#pg_menu_content');

Merge two Excel tables Based on matching data in Columns

Put the table in the second image on Sheet2, columns D to F.

In Sheet1, cell D2 use the formula

=iferror(vlookup($A2,Sheet2!$D$1:$F$100,column(A1),false),"")

copy across and down.

Edit: here is a picture. The data is in two sheets. On Sheet1, enter the formula into cell D2. Then copy the formula across to F2 and then down as many rows as you need.

enter image description here

String strip() for JavaScript?

Steven Levithan once wrote about how to implement a Faster JavaScript Trim. It’s definitely worth a look.

allowing only alphabets in text box using java script

You can try:

 function onlyAlphabets(e, t) {
        return (e.charCode > 64 && e.charCode < 91) || (e.charCode > 96 && e.charCode < 123) || e.charCode == 32;   
    }

Unix tail equivalent command in Windows Powershell

I took @hajamie's solution and wrapped it up into a slightly more convenient script wrapper.

I added an option to start from an offset before the end of the file, so you can use the tail-like functionality of reading a certain amount from the end of the file. Note the offset is in bytes, not lines.

There's also an option to continue waiting for more content.

Examples (assuming you save this as TailFile.ps1):

.\TailFile.ps1 -File .\path\to\myfile.log -InitialOffset 1000000
.\TailFile.ps1 -File .\path\to\myfile.log -InitialOffset 1000000 -Follow:$true
.\TailFile.ps1 -File .\path\to\myfile.log -Follow:$true

And here is the script itself...

param (
    [Parameter(Mandatory=$true,HelpMessage="Enter the path to a file to tail")][string]$File = "",
    [Parameter(Mandatory=$true,HelpMessage="Enter the number of bytes from the end of the file")][int]$InitialOffset = 10248,
    [Parameter(Mandatory=$false,HelpMessage="Continuing monitoring the file for new additions?")][boolean]$Follow = $false
)

$ci = get-childitem $File
$fullName = $ci.FullName

$reader = new-object System.IO.StreamReader(New-Object IO.FileStream($fullName, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [IO.FileShare]::ReadWrite))
#start at the end of the file
$lastMaxOffset = $reader.BaseStream.Length - $InitialOffset

while ($true)
{
    #if the file size has not changed, idle
    if ($reader.BaseStream.Length -ge $lastMaxOffset) {
        #seek to the last max offset
        $reader.BaseStream.Seek($lastMaxOffset, [System.IO.SeekOrigin]::Begin) | out-null

        #read out of the file until the EOF
        $line = ""
        while (($line = $reader.ReadLine()) -ne $null) {
            write-output $line
        }

        #update the last max offset
        $lastMaxOffset = $reader.BaseStream.Position
    }

    if($Follow){
        Start-Sleep -m 100
    } else {
        break;
    }
}

How to post raw body data with curl?

curl's --data will by default send Content-Type: application/x-www-form-urlencoded in the request header. However, when using Postman's raw body mode, Postman sends Content-Type: text/plain in the request header.

So to achieve the same thing as Postman, specify -H "Content-Type: text/plain" for curl:

curl -X POST -H "Content-Type: text/plain" --data "this is raw data" http://78.41.xx.xx:7778/

Note that if you want to watch the full request sent by Postman, you can enable debugging for packed app. Check this link for all instructions. Then you can inspect the app (right-click in Postman) and view all requests sent from Postman in the network tab :

enter image description here

Error "can't use subversion command line client : svn" when opening android project checked out from svn

There are better answers here, but how I fix this may be relevant for someone:

After checking out the project from SVN, instead of choosing the 1.7 version, I chose Subversion 1.6 and it worked.

How to display svg icons(.svg files) in UI using React Component?

There are two ways I want to show you.

The first one is just a simple import of the required SVG.

import MyImageSvg from '../../path/to.svg';

Just remember to use a loader for e.g. Webpack:

 {
     test: /\.(ttf|eot|svg|woff(2)?)(\?[a-z0-9=&.]+)?$/,
     include: [Path.join(__dirname, "src/assets")],
     loader: "file-loader?name=assets/[name].[ext]"
 }

Another (and more elegant way) is that you can define an SVG icon sprite and use a component to fetch the correct sprite of the SVG. For example:

import React from "react";
import Icons from "../../assets/icons/icons.svg"; // Path to your icons.svg
import PropTypes from 'prop-types';

const Icon = ({ name, color, size }) => (
  <svg className={`icon icon-${name}`} fill={color} width={size} height={size}>
    <use xlinkHref={`${Icons}#icon-${name}`} />
  </svg>
);

Icon.propTypes = {
  name: PropTypes.string.isRequired,
  color: PropTypes.string,
  size: PropTypes.number
};

export default Icon;

The icon sprite (icons.svg) can be defined as:

<svg xmlns="http://www.w3.org/2000/svg" style="display: none;">

    <symbol id="icon-account-group" viewBox="0 0 512 512">
      <path d="m256 301l0-41c7-7 19-24 21-60 10-5 16-16 16-30 0-12-4-22-12-28 7-13 18-37 12-60-7-28-48-39-81-39-29 0-65 8-77 30-12-1-20 2-26 9-15 16-8 46-4 62 1 2 2 4 2 5l0 42c0 41 24 63 42 71l0 39c-8 3-17 7-26 10-56 20-104 37-112 64-11 31-11 102-11 105 0 6 5 11 11 11l384 0c6 0 10-5 10-11 0-3 0-74-10-105-11-31-69-48-139-74z m-235 168c1-20 3-66 10-88 5-16 57-35 99-50 12-4 23-8 34-12 4-2 7-6 7-10l0-54c0-4-3-9-8-10-1 0-35-12-35-54l0-42c0-3-1-5-2-11-2-8-9-34-2-41 3-4 11-3 15-2 6 1 11-2 13-8 3-13 29-22 60-22 31 0 57 9 60 22 5 17-6 37-11 48-3 6-5 10-5 14 0 5 5 10 11 10 3 0 5 6 5 11 0 4-2 11-5 11-6 0-11 4-11 10 0 43-16 55-16 55-3 2-5 6-5 9l0 54c0 4 2 8 7 10 51 19 125 41 132 62 8 22 9 68 10 88l-363 0z m480-94c-8-25-49-51-138-84l0-20c7-7 19-25 21-61 4-2 7-5 10-9 4-5 6-13 6-20 0-13-5-23-13-28 7-15 19-41 13-64-4-15-21-31-40-39-19-7-38-6-54 5-5 3-6 10-3 15 3 4 10 6 15 3 12-9 25-6 34-3 15 6 25 18 27 24 4 17-6 40-12 52-3 6-4 10-4 13 0 3 1 6 3 8 2 2 4 3 7 3 4 0 6 6 6 11 0 3-1 6-3 8-1 2-2 2-3 2-6 0-10 5-10 11 0 43-17 55-17 55-3 2-5 5-5 9l0 32c0 4 3 8 7 10 83 31 127 56 133 73 7 22 9 68 10 88l-43 0c-6 0-11 5-11 11 0 6 5 11 11 11l53 0c6 0 11-5 11-11 0-3 0-74-11-105z"/>
    </symbol>

    <symbol id="icon-arrow-down" viewBox="0 0 512 512">
      <path d="m508 109c-4-4-11-3-15 1l-237 269-237-269c-4-4-11-5-15-1-5 4-5 11-1 15l245 278c2 2 5 3 8 3 3 0 6-1 8-3l245-278c4-4 4-11-1-15z"/>
    </symbol>

    <symbol id="icon-arrow-left" viewBox="0 0 512 512">
      <path d="m133 256l269-237c4-4 5-11 1-15-4-5-11-5-15-1l-278 245c-2 2-3 5-3 8 0 3 1 6 3 8l278 245c2 2 4 3 7 3 3 0 6-1 8-4 4-4 3-11-1-15z"/>
    </symbol>

    <symbol id="icon-arrow-right" viewBox="0 0 512 512">
      <path d="m402 248l-278-245c-4-4-11-4-15 1-4 4-3 11 1 15l269 237-269 237c-4 4-5 11-1 15 2 3 5 4 8 4 3 0 5-1 7-3l278-245c2-2 3-5 3-8 0-3-1-6-3-8z"/>
    </symbol>
</svg>

You can define your own icon sprite on http://fontastic.me/ for free.

And the usage: <Icon name="arrow-down" color="#FFFFFF" size={35} />

And possible add some simple styling for using the icons everywhere:

[class^="icon-"], [class*=" icon-"] {
    display: inline-block;
    vertical-align: middle;
}

How to calculate rolling / moving average using NumPy / SciPy?

In case you want to take care the edge conditions carefully (compute mean only from available elements at edges), the following function will do the trick.

import numpy as np

def running_mean(x, N):
    out = np.zeros_like(x, dtype=np.float64)
    dim_len = x.shape[0]
    for i in range(dim_len):
        if N%2 == 0:
            a, b = i - (N-1)//2, i + (N-1)//2 + 2
        else:
            a, b = i - (N-1)//2, i + (N-1)//2 + 1

        #cap indices to min and max indices
        a = max(0, a)
        b = min(dim_len, b)
        out[i] = np.mean(x[a:b])
    return out

>>> running_mean(np.array([1,2,3,4]), 2)
array([1.5, 2.5, 3.5, 4. ])

>>> running_mean(np.array([1,2,3,4]), 3)
array([1.5, 2. , 3. , 3.5])

How to watch for form changes in Angular

I thought about using the (ngModelChange) method, then thought about the FormBuilder method, and finally settled on a variation of Method 3. This saves decorating the template with extra attributes and automatically picks up changes to the model - reducing the possibility of forgetting something with Method 1 or 2.

Simplifying Method 3 a bit...

oldPerson = JSON.parse(JSON.stringify(this.person));

ngDoCheck(): void {
    if (JSON.stringify(this.person) !== JSON.stringify(this.oldPerson)) {
        this.doSomething();
        this.oldPerson = JSON.parse(JSON.stringify(this.person));
    }
}

You could add a timeout to only call doSomething() after x number of milliseconds to simulate debounce.

oldPerson = JSON.parse(JSON.stringify(this.person));

ngDoCheck(): void {
    if (JSON.stringify(this.person) !== JSON.stringify(this.oldPerson)) {
        if (timeOut) clearTimeout(timeOut);
        let timeOut = setTimeout(this.doSomething(), 2000);
        this.oldPerson = JSON.parse(JSON.stringify(this.person));
    }
}

Installing Homebrew on OS X

add the following in your terminal and click enter then follow the instruction in the terminal. /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

ArrayList - How to modify a member of an object?

Well u have used Pojo Entity so u can do this. u need to get object of that and have to set data.

myList.get(3).setEmail("email");

that way u can do that. or u can set other param too.

How to rollback a specific migration?

In Addition

When migration you deployed long ago does not let you migrate new one.

What happened is, I work in a larger Rails app with more than a thousand of migration files. And, it takes a month for us to ship a medium-sized feature. I was working on a feature and I had deployed a migration a month ago then in the review process the structure of migration and filename changed, now I try to deploy my new code, the build failed saying

ActiveRecord::StatementInvalid: PG::DuplicateColumn: ERROR:  column "my_new_field" of relation "accounts" already exists

none of the above-mentioned solutions worked for me because the old migration file was missing and the field I intended to create in my new migration file already existed in the DB. The only solution that worked for me is:

  1. I scped the file to the server
  2. I opened the rails console
  3. I required the file in the IRB session
  4. then AddNewMyNewFieldToAccounts.new.down

then I could run the deploy build again.

Hope it helps you too.

Build unsigned APK file with Android Studio

I solve it!

First off all, you should add these:

defaultConfig { 
 multiDexEnabled true
}

dependencies {
 implementation 'com.android.support:multidex:1.0.3'
}

After, you should click Build in top bar of Android Studio:

Build > Build Bundle(s) / APK(s) > Build APK(s)

Finally, you have an app-debug.apk file in:

app > build > outputs > apk > debug > app-debug.apk

Note: apk, debug, app-debug.apk files created automatically in outputs file by Android Studio.

How is Java platform-independent when it needs a JVM to run?

Javac – compiler that converts source code to byte code. JVM- interpreter that converts byte code to machine language code.

As we know java is both compile**r & **interpreter based language. Once the java code also known as source code is compiled, it gets converted to native code known as BYTE CODE which is portable & can be easily executed on all operating systems. Byte code generated is basically represented in hexa decimal format. This format is same on every platform be it Solaris work station or Macintosh, windows or Linux. After compilation, the interpreter reads the generated byte code & translates it according to the host machine. . Byte code is interpreted by Java Virtual Machine which is available with all the operating systems we install. so to port Java programs to a new platform all that is required is to port the interpreter and some of the library routines.

Hope it helps!!!

Initialising an array of fixed size in python

Well I would like to help you by posting a sample program and its output

Program:

t = input("")
x = [None]*t
y = [[None]*t]*t

for i in range(1, t+1):
    x[i-1] = i;

    for j in range(1, t+1):
        y[i-1][j-1] = j;

print x
print y

Output :-

2
[1, 2]
[[1, 2], [1, 2]]

I hope this clears some very basic concept of yours regarding their declaration. To initialize them with some other specific values, like initializing them with 0.. you can declare them as:

x = [0]*10

Hope it helps..!! ;)

How to display activity indicator in middle of the iphone screen?

You can set the position like this

        UIActivityIndicatorView *activityView = 
[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
activityView.frame = CGRectMake(120, 230, 50, 50);
[self.view addSubview:activityView];

Accordingly change the frame size.....

Add padding to HTML text input field

HTML

<div class="FieldElement"><input /></div>
<div class="searchIcon"><input type="submit" /></div>

For Other Browsers:

.FieldElement input {
width: 413px;
border:1px solid #ccc;
padding: 0 2.5em 0 0.5em;
}

.searchIcon
{
 background: url(searchicon-image-path) no-repeat;
 width: 17px;
 height: 17px;
 text-indent: -999em;
 display: inline-block;
 left: 432px;
 top: 9px;
}

For IE:

.FieldElement input {
width: 380px;
border:0;
}

.FieldElement {
 border:1px solid #ccc;
 width: 455px;     
 }

.searchIcon
{
 background: url(searchicon-image-path) no-repeat;
 width: 17px;
 height: 17px;
 text-indent: -999em;
 display: inline-block;
 left: 432px;
 top: 9px;
}

Android Design Support Library expandable Floating Action Button(FAB) menu

Got a better approach to implement the animating FAB menu without using any library or to write huge xml code for animations. hope this will help in future for someone who needs a simple way to implement this.

Just using animate().translationY() function, you can animate any view up or down just I did in my below code, check complete code in github. In case you are looking for the same code in kotlin, you can checkout the kotlin code repo Animating FAB Menu.

first define all your FAB at same place so they overlap each other, remember on top the FAB should be that you want to click and to show other. eg:

    <android.support.design.widget.FloatingActionButton
    android:id="@+id/fab3"
    android:layout_width="@dimen/standard_45"
    android:layout_height="@dimen/standard_45"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/standard_21"
    app:srcCompat="@android:drawable/ic_btn_speak_now" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab2"
    android:layout_width="@dimen/standard_45"
    android:layout_height="@dimen/standard_45"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/standard_21"
    app:srcCompat="@android:drawable/ic_menu_camera" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab1"
    android:layout_width="@dimen/standard_45"
    android:layout_height="@dimen/standard_45"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/standard_21"
    app:srcCompat="@android:drawable/ic_dialog_map" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/fab_margin"
    app:srcCompat="@android:drawable/ic_dialog_email" />

Now in your java class just define all your FAB and perform the click like shown below:

 FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab1 = (FloatingActionButton) findViewById(R.id.fab1);
    fab2 = (FloatingActionButton) findViewById(R.id.fab2);
    fab3 = (FloatingActionButton) findViewById(R.id.fab3);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if(!isFABOpen){
                showFABMenu();
            }else{
                closeFABMenu();
            }
        }
    });

Use the animation().translationY() to animate your FAB,I prefer you to use the attribute of this method in DP since only using an int will effect the display compatibility with higher resolution or lower resolution. as shown below:

 private void showFABMenu(){
    isFABOpen=true;
    fab1.animate().translationY(-getResources().getDimension(R.dimen.standard_55));
    fab2.animate().translationY(-getResources().getDimension(R.dimen.standard_105));
    fab3.animate().translationY(-getResources().getDimension(R.dimen.standard_155));
}

private void closeFABMenu(){
    isFABOpen=false;
    fab1.animate().translationY(0);
    fab2.animate().translationY(0);
    fab3.animate().translationY(0);
}

Now define the above mentioned dimension inside res->values->dimens.xml as shown below:

    <dimen name="standard_55">55dp</dimen>
<dimen name="standard_105">105dp</dimen>
<dimen name="standard_155">155dp</dimen>

That's all hope this solution will help the people in future, who are searching for simple solution.

EDITED

If you want to add label over the FAB then simply take a horizontal LinearLayout and put the FAB with textview as label, and animate the layouts if find any issue doing this, you can check my sample code in github, I have handelled all backward compatibility issues in that sample code. check my sample code for FABMenu in Github

to close the FAB on Backpress, override onBackPress() as showen below:

    @Override
public void onBackPressed() {
    if(!isFABOpen){
        this.super.onBackPressed();
    }else{
        closeFABMenu();
    }
}

The Screenshot have the title as well with the FAB,because I take it from my sample app present ingithub

enter image description here

Correct way to import lodash

If you are using webpack 4, the following code is tree shakable.

import { has } from 'lodash-es';

The points to note;

  1. CommonJS modules are not tree shakable so you should definitely use lodash-es, which is the Lodash library exported as ES Modules, rather than lodash (CommonJS).

  2. lodash-es's package.json contains "sideEffects": false, which notifies webpack 4 that all the files inside the package are side effect free (see https://webpack.js.org/guides/tree-shaking/#mark-the-file-as-side-effect-free).

  3. This information is crucial for tree shaking since module bundlers do not tree shake files which possibly contain side effects even if their exported members are not used in anywhere.

Edit

As of version 1.9.0, Parcel also supports "sideEffects": false, threrefore import { has } from 'lodash-es'; is also tree shakable with Parcel. It also supports tree shaking CommonJS modules, though it is likely tree shaking of ES Modules is more efficient than CommonJS according to my experiment.

When to use LinkedList over ArrayList in Java?

Joshua Bloch, the author of LinkedList:

Does anyone actually use LinkedList? I wrote it, and I never use it.

Link: https://twitter.com/joshbloch/status/583813919019573248

I'm sorry for the answer for being not that informative as the other answers, but I thought it would be the most interesting and self-explanatory.

Scala vs. Groovy vs. Clojure

Scala

Scala evolved out of a pure functional language known as Funnel and represents a clean-room implementation of almost all Java's syntax, differing only where a clear improvement could be made or where it would compromise the functional nature of the language. Such differences include singleton objects instead of static methods, and type inference.

Much of this was based on Martin Odersky's prior work with the Pizza language. The OO/FP integration goes far beyond mere closures and has led to the language being described as post-functional.

Despite this, it's the closest to Java in many ways. Mainly due to a combination of OO support and static typing, but also due to a explicit goal in the language design that it should integrate very tightly with Java.

Groovy

Groovy explicitly tackles two of Java's biggest criticisms by

  • being dynamically typed, which removes a lot of boilerplate and
  • adding closures to the language.

It's perhaps syntactically closest to Java, not offering some of the richer functional constructs that Clojure and Scala provide, but still offering a definite evolutionary improvement - especially for writing script-syle programs.

Groovy has the strongest commercial backing of the three languages, mostly via springsource.

Clojure

Clojure is a functional language in the LISP family, it's also dynamically typed.

Features such as STM support give it some of the best out-of-the-box concurrency support, whereas Scala requires a 3rd-party library such as Akka to duplicate this.

Syntactically, it's also the furthest of the three languages from typical Java code.

I also have to disclose that I'm most acquainted with Scala :)

Structs in Javascript

I use objects JSON style for dumb structs (no member functions).

How to extract duration time from ffmpeg output?

For those who want to perform the same calculations with no additional software in Windows, here is the script for command line script:

set input=video.ts

ffmpeg -i "%input%" 2> output.tmp

rem search "  Duration: HH:MM:SS.mm, start: NNNN.NNNN, bitrate: xxxx kb/s"
for /F "tokens=1,2,3,4,5,6 delims=:., " %%i in (output.tmp) do (
    if "%%i"=="Duration" call :calcLength %%j %%k %%l %%m
)
goto :EOF

:calcLength
set /A s=%3
set /A s=s+%2*60
set /A s=s+%1*60*60
set /A VIDEO_LENGTH_S = s
set /A VIDEO_LENGTH_MS = s*1000 + %4
echo Video duration %1:%2:%3.%4 = %VIDEO_LENGTH_MS%ms = %VIDEO_LENGTH_S%s

Same answer posted here: How to crop last N seconds from a TS video

What is the difference between --save and --save-dev?

--save-dev is used for modules used in development of the application,not require while running it in production envionment --save is used to add it in package.json and it is required for running of the application.

Example: express,body-parser,lodash,helmet,mysql all these are used while running the application use --save to put in dependencies while mocha,istanbul,chai,sonarqube-scanner all are used during development ,so put those in dev-dependencies .

npm link or npm install will also install the dev-dependency modules along with dependency modules in your project folder

Variable might not have been initialized error

Since no other answer has cited the Java language standard, I have decided to write an answer of my own:

In Java, local variables are not, by default, initialized with a certain value (unlike, for example, the field of classes). From the language specification one (§4.12.5) can read the following:

A local variable (§14.4, §14.14) must be explicitly given a value before it is used, by either initialization (§14.4) or assignment (§15.26), in a way that can be verified using the rules for definite assignment (§16 (Definite Assignment)).

Therefore, since the variables a and b are not initialized :

 for (int l= 0; l<x.length; l++) 
    {
        if (x[l] == 0) 
        a++ ;
        else if (x[l] == 1) 
        b++ ;
    }

the operations a++; and b++; could not produce any meaningful results, anyway. So it is logical for the compiler to notify you about it:

Rand.java:72: variable a might not have been initialized
                a++ ;
                ^
Rand.java:74: variable b might not have been initialized
                b++ ;
                ^

However, one needs to understand that the fact that a++; and b++; could not produce any meaningful results has nothing to do with the reason why the compiler displays an error. But rather because it is explicitly set on the Java language specification that

A local variable (§14.4, §14.14) must be explicitly given a value (...)

To showcase the aforementioned point, let us change a bit your code to:

public static Rand searchCount (int[] x) 
{
    if(x == null || x.length  == 0)
      return null;
    int a ; 
    int b ; 

    ...   

    for (int l= 0; l<x.length; l++) 
    {
        if(l == 0)
           a = l;
        if(l == 1)
           b = l;
    }

    ...   
}

So even though the code above can be formally proven to be valid (i.e., the variables a and b will be always assigned with the value 0 and 1, respectively) it is not the compiler job to try to analyze your application's logic, and neither does the rules of local variable initialization rely on that. The compiler checks if the variables a and b are initialized according to the local variable initialization rules, and reacts accordingly (e.g., displaying a compilation error).

Visual Studio popup: "the operation could not be completed"

Sometimes it is just a matter of closing Visual Studio 2015 and then open again.

Update: Visual Studio 2017 apparently as well.

I have had this happen on a few machines.

This does happen.

"Have you tried to delete the "Your_Solution_FileName.suo" file?"

Also computer crashing like e.g. power outage etc...

Applies to Update 2 and Update 3 as well as fresh base without any updates...

Regular expression to match URLs in Java

The problem with all suggested approaches: all RegEx is validating

All RegEx -based code is over-engineered: it will find only valid URLs! As a sample, it will ignore anything starting with "http://" and having non-ASCII characters inside.

Even more: I have encountered 1-2-seconds processing times (single-threaded, dedicated) with Java RegEx package (filtering Email addresses from text) for very small and simple sentences, nothing specific; possibly bug in Java 6 RegEx...

Simplest/Fastest solution would be to use StringTokenizer to split text into tokens, to remove tokens starting with "http://" etc., and to concatenate tokens into text again.

If you want to filter Emails from text (because later on you will do NLP staff etc) - just remove all tokens containing "@" inside.

This is simple text where RegEx of Java 6 fails. Try it in divverent variants of Java. It takes about 1000 milliseconds per RegEx call, in a long running single threaded test application:

pattern = Pattern.compile("[A-Za-z0-9](([_\\.\\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\\.\\-]?[a-zA-Z0-9]+)*)\\.([A-Za-z]{2,})", Pattern.CASE_INSENSITIVE);

"Avalanna is such a sweet little girl! It would b heartbreaking if cancer won. She's so precious! #BeliebersPrayForAvalanna");
"@AndySamuels31 Hahahahahahahahahhaha lol, you don't look like a girl hahahahhaahaha, you are... sexy.";

Do not rely on regular expressions if you only need to filter words with "@", "http://", "ftp://", "mailto:"; it is huge engineering overhead.

If you really want to use RegEx with Java, try Automaton

Determining the last row in a single column

Never too late to post an alternative answer I hope. Here's a snippet of my Find last Cell. I'm primarily interested in speed. On a DB I'm using with around 150,000 rows this function took (average) 0.087 seconds to find solution compared to @Mogsdad elegant JS solution above which takes (average) 0.53 sec on same data. Both arrays were pre-loaded before the function call. It makes use of recursion to do a binary search. For 100,000+ rows you should find it takes no more than 15 to 20 hops to return it's result.

I've left the Log calls in so you can test it in the console first and see its workings.

/* @OnlyCurrentDoc */

function myLastRow() {

var ss=SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var colArray = ss.getRange('A1:A').getDisplayValues();  // Change to relevant column label and put in Cache
var TestRow=ss.getLastRow();
var MaxRow=ss.getMaxRows(); 

Logger.log ('TestRow = %s',TestRow);
Logger.log ('MaxRow = %s',MaxRow);

var FoundRow=FindLastRow(TestRow,MaxRow);

Logger.log ('FoundRow = %s',FoundRow);    

function FindLastRow(v_TestRow,v_MaxRow) {

/* Some housekeeping/error trapping first
* 1) Check that LastRow doesn't = Max Rows. If so then suggest to add a few lines as this
* indicates the LastRow was the end of the sheet.
* 2) Check it's not a new sheet with no data ie, LastRow = 0 and/or cell A1 is empty.
* 3) A return result of 0 = an error otherwise any positive value is a valid result.
*/

 return   !(colArray[0][0]) ? 1                   // if first row is empty then presume it's a new empty sheet
        :!!(colArray[v_TestRow][0]) ? v_TestRow   // if the last row is not empty then column A was the longest
        : v_MaxRow==v_TestRow ? v_TestRow         // if Last=Max then consider adding a line here to extend row count, else
        : searchPair(0,v_TestRow);                // get on an find the last row
}

function searchPair(LowRow,HighRow){

var BinRow = ((LowRow+HighRow)/2)|0;   // force an INT to avoid row ambiguity

Logger.log ('LowRow/HighRow/BinRow = %s/%s/%s',LowRow, HighRow, BinRow);

/*   Check your log. You shoud find that the last row is always found in under 20 hops.
 *   This will be true whether your data rows are 100 or 100,000 long.
 *   The longest element of this script is loading the Cache (ColArray)
 */

 return   (!(colArray[BinRow-1][0]))^(!(colArray[BinRow][0])) ? BinRow
        : (!(colArray[BinRow-1][0]))&(!(colArray[BinRow][0])) ? searchPair(LowRow,BinRow-1)
        : (!!(colArray[BinRow-1][0]))|(!!(colArray[BinRow][0])) ? searchPair(BinRow+1,HighRow)
        : false;   // Error
 }
}

/* The premise for the above logic is that the binary search is looking for a specific pairing, <Text/No text>
 * on adjacent rows.  You said there are no gaps so the pairing <No Text/Text> is not tested as it's irrelevant.
 * If the logic finds <No Text/No Text> then it looks back up the sheet, if it finds <Text/Text> it looks further
 * down the sheet.  I think you'll find this is quite fast, especially on datasets > 100,000 rows.
 */

What is the best way to test for an empty string with jquery-out-of-the-box?

if((a.trim()=="")||(a=="")||(a==null))
{
    //empty condition
}
else
{
    //working condition
}

Make a link in the Android browser start up my app?

Just want to open the app through browser? You can achieve it using below code:

HTML:

<a href="intent:#Intent;action=packageName;category=android.intent.category.DEFAULT;category=android.intent.category.BROWSABLE;end">Click here</a>

Manifest:

<intent-filter>
      <action android:name="packageName" />
      <category android:name="android.intent.category.DEFAULT" />
      <category android:name="android.intent.category.BROWSABLE" />
</intent-filter>

This intent filter should be in Launcher Activity.

If you want to pass the data on click of browser link, just refer this link.

How to create a SQL Server function to "join" multiple rows from a subquery into a single delimited field?

From what I can see FOR XML (as posted earlier) is the only way to do it if you want to also select other columns (which I'd guess most would) as the OP does. Using COALESCE(@var... does not allow inclusion of other columns.

Update: Thanks to programmingsolutions.net there is a way to remove the "trailing" comma to. By making it into a leading comma and using the STUFF function of MSSQL you can replace the first character (leading comma) with an empty string as below:

stuff(
    (select ',' + Column 
     from Table
         inner where inner.Id = outer.Id 
     for xml path('')
), 1,1,'') as Values

Graphical user interface Tutorial in C

My favourite UI tutorials all come from zetcode.com:

These are tutorials I'd consider to be "starting tutorials". The example tutorial gets you up and going, but doesn't show you anything too advanced or give much explanation. Still, often, I find the big problem is "how do I start?" and these have always proved useful to me.

How to check if a line is blank using regex

Here Blank mean what you are meaning.
A line contains full of whitespaces or a line contains nothing.
If you want to match a line which contains nothing then use '/^$/'.

using wildcards in LDAP search filters/queries

This should work, at least according to the Search Filter Syntax article on MSDN network.

The "hang-up" you have noticed is probably just a delay. Try running the same query with narrower scope (for example the specific OU where the test object is located), as it may take very long time for processing if you run it against all AD objects.

You may also try separating the filter into two parts:

(|(displayName=*searchstring)(displayName=searchstring*))

Still Reachable Leak detected by Valgrind

There is more than one way to define "memory leak". In particular, there are two primary definitions of "memory leak" that are in common usage among programmers.

The first commonly used definition of "memory leak" is, "Memory was allocated and was not subsequently freed before the program terminated." However, many programmers (rightly) argue that certain types of memory leaks that fit this definition don't actually pose any sort of problem, and therefore should not be considered true "memory leaks".

An arguably stricter (and more useful) definition of "memory leak" is, "Memory was allocated and cannot be subsequently freed because the program no longer has any pointers to the allocated memory block." In other words, you cannot free memory that you no longer have any pointers to. Such memory is therefore a "memory leak". Valgrind uses this stricter definition of the term "memory leak". This is the type of leak which can potentially cause significant heap depletion, especially for long lived processes.

The "still reachable" category within Valgrind's leak report refers to allocations that fit only the first definition of "memory leak". These blocks were not freed, but they could have been freed (if the programmer had wanted to) because the program still was keeping track of pointers to those memory blocks.

In general, there is no need to worry about "still reachable" blocks. They don't pose the sort of problem that true memory leaks can cause. For instance, there is normally no potential for heap exhaustion from "still reachable" blocks. This is because these blocks are usually one-time allocations, references to which are kept throughout the duration of the process's lifetime. While you could go through and ensure that your program frees all allocated memory, there is usually no practical benefit from doing so since the operating system will reclaim all of the process's memory after the process terminates, anyway. Contrast this with true memory leaks which, if left unfixed, could cause a process to run out of memory if left running long enough, or will simply cause a process to consume far more memory than is necessary.

Probably the only time it is useful to ensure that all allocations have matching "frees" is if your leak detection tools cannot tell which blocks are "still reachable" (but Valgrind can do this) or if your operating system doesn't reclaim all of a terminating process's memory (all platforms which Valgrind has been ported to do this).

How do I view the full content of a text or varchar(MAX) column in SQL Server 2008 Management Studio?

Starting from SSMS 18.2, you can now view up to 2 million characters in the grid results. Source

Allow more data to be displayed (Result to Text) and stored in cells (Result to Grid). SSMS now allows up to 2M characters for both.

I verified this with the code below.

DECLARE @S varchar(max) = 'A'

SET @S =  REPLICATE(@S,2000000) + 'B' 

SELECT @S as a

How to check if an element does NOT have a specific class?

sdleihssirhc's answer is of course the correct one for the case in the question, but just as a reference if you need to select elements that don't have a certain class, you can use the not selector:

// select all divs that don't have class test
$( 'div' ).not( ".test" );
$( 'div:not(.test)' );  // <-- alternative 

Difference between JSONObject and JSONArray

The usage of both can be depended on the structure of your data.

Simply, You can use the Nested Objects approach if you plan to give priority to a unique identifier such as a Primary Key.

eg:

  {
     "Employees" : {
           "001" : {
               "Name" : "Alan",
               "Children" : ["Walker", "Dua", "Lipa"]
                },
           "002" : {
               "Name" : "Ezio",
               "Children" : ["Kenvey", "Connor", "Edward"]
                }
      }

Or, Use the Array first approach if you intend to store a set of values with no need to identify uniquely.

eg:

 [
     {
        "Employees":[
               {
                   "Name" : "Alan",
                   "Children" : ["Walker", "Dua", "Lipa"]
               },
               {
                   "Name" : "Ezio",
                   "Children" : ["Kenvey", "Connor", "Edward"]
               }
          ]
       }
   ]

Although you could use the second method with an identifier, it can be harder or too complex to query and understand in some scenarios. Also depending on the database one may have to apply a suitable approach. Eg: MongoDB / Firebase

Overloading and overriding

in C# there is no Java like hidden override, without keyword override on overriding method! see these C# implementations:

variant 1 without override: result is 200

    class Car {
        public int topSpeed() {
            return 200;
        }
    }

    class Ferrari : Car {
        public int topSpeed(){
                return 400;
        }
    }

    static void Main(string[] args){
        Car car = new Ferrari();
        int num= car.topSpeed();
        Console.WriteLine("Top speed for this car is: "+num);
        Console.ReadLine();
    }

variant 2 with override keyword: result is 400

    class Car {
        public virtual int topSpeed() {
            return 200;
        }
    }

    class Ferrari : Car {
        public override int topSpeed(){
                return 400;
        }
    }

    static void Main(string[] args){
        Car car = new Ferrari();
        int num= car.topSpeed();
        Console.WriteLine("Top speed for this car is: "+num);
        Console.ReadLine();
    }

keyword virtual on Car class is opposite for final on Java, means not final, you can override, or implement if Car was abstract

How to find the day, month and year with moment.js

Here's an example that you could use :

 var myDateVariable= moment("01/01/2019").format("dddd Do MMMM YYYY")
  • dddd : Full day Name

  • Do : day of the Month

  • MMMM : Full Month name

  • YYYY : 4 digits Year

For more informations :

https://flaviocopes.com/momentjs/

How can I copy data from one column to another in the same table?

UPDATE table_name SET
    destination_column_name=orig_column_name
WHERE condition_if_necessary

Command-line Unix ASCII-based charting / plotting tool

Try gnuplot. It has very powerful graphing possibilities.

It can output to your terminal in the following way:

gnuplot> set terminal dumb
Terminal type set to 'dumb'
Options are 'feed 79 24'
gnuplot> plot sin(x)

   1 ++----------------**---------------+----**-----------+--------**-----++
     +                *+ *              +   *  *          +  sin(x) ****** +
 0.8 ++              *    *                *    *                *    *   ++
     |               *    *                *    *                *    *    |
 0.6 ++              *     *              *      *              *      *  ++
     *              *       *             *       *             *      *   |
 0.4 +*             *       *             *       *             *      *  ++
     |*            *        *            *        *            *        *  |
 0.2 +*            *        *            *        *            *        * ++
     | *          *          *          *          *          *          * |
   0 ++*          *          *          *          *          *          *++
     |  *         *           *         *           *         *           *|
-0.2 ++ *         *           *         *           *         *           *+
     |   *       *            *        *            *        *            *|
-0.4 ++  *       *            *        *            *        *            *+
     |   *      *              *      *              *      *              *
-0.6 ++  *      *              *      *              *      *             ++
     |    *     *               *     *               *    *               |
-0.8 ++    *   *                 *   *                *    *              ++
     +     *  *        +         *  *   +              *  *                +
  -1 ++-----**---------+----------**----+---------------**+---------------++
    -10               -5                0                 5                10

Accessing localhost:port from Android emulator

If anybody is still looking for this, this is how it worked for me.

You need to find the IP of your machine with respect to the device/emulator you are connected. For Emulators on of the way is by following below steps;

  1. Go to VM Virtual box -> select connected device in the list.
  2. Select Settings ->Network-> Find out to which network the device is attached. For me it was 'VirtualBox Host-Only Ethernet Adapter #2'.
  3. In virtualbox go to Files->Preferences->Network->Host-Only Networks, and find out the IPv4 for the network specified in above step. (By Hovering you will get the info)

Provide this IP to access the localhost from emulator. The Port is same as you have provided while running/publishing your services.

Note #1 : Make sure you have taken care of firewalls and inbound rules.

Note #2 : Please check this IP after you restart your machine. For some reason, even If I provided "Use the following IP" The Host-Only IP got changed.

Sheet.getRange(1,1,1,12) what does the numbers in bracket specify?

Found these docu on the google docu pages:

  • row --- int --- top row of the range
  • column --- int--- leftmost column of the range
  • optNumRows --- int --- number of rows in the range.
  • optNumColumns --- int --- number of columns in the range

In your example, you would get (if you picked the 3rd row) "C3:O3", cause C --> O is 12 columns

edit

Using the example on the docu:

// The code below will get the number of columns for the range C2:G8
// in the active spreadsheet, which happens to be "4"
var count = SpreadsheetApp.getActiveSheet().getRange(2, 3, 6, 4).getNumColumns(); Browser.msgBox(count);

The values between brackets:
2: the starting row = 2
3: the starting col = C
6: the number of rows = 6 so from 2 to 8
4: the number of cols = 4 so from C to G

So you come to the range: C2:G8

How do you get a directory listing sorted by creation date in python?

from pathlib import Path
import os

sorted(Path('./').iterdir(), key=lambda t: t.stat().st_mtime)

or

sorted(Path('./').iterdir(), key=os.path.getmtime)

or

sorted(os.scandir('./'), key=lambda t: t.stat().st_mtime)

where m time is modified time.

Prompt Dialog in Windows Forms

It's generally not a real good idea to import the VisualBasic libraries into C# programs (not because they won't work, but just for compatibility, style, and ability to upgrade), but you can call Microsoft.VisualBasic.Interaction.InputBox() to display the kind of box you're looking for.

If you can create a Windows.Forms object, that would be best, but you say you cannot do that.

How to write hello world in assembler under Windows?

Flat Assembler does not need an extra linker. This makes assembler programming quite easy. It is also available for Linux.

This is hello.asm from the Fasm examples:

include 'win32ax.inc'

.code

  start:
    invoke  MessageBox,HWND_DESKTOP,"Hi! I'm the example program!",invoke GetCommandLine,MB_OK
    invoke  ExitProcess,0

.end start

Fasm creates an executable:

>fasm hello.asm
flat assembler  version 1.70.03  (1048575 kilobytes memory)
4 passes, 1536 bytes.

And this is the program in IDA:

enter image description here

You can see the three calls: GetCommandLine, MessageBox and ExitProcess.

SQL query for a carriage return in a string and ultimately removing carriage return

If you are considering creating a function, try this: DECLARE @schema sysname = 'dbo' , @tablename sysname = 'mvtEST' , @cmd NVarchar(2000) , @ColName sysname

    DECLARE @NewLine Table
    (ColumnName Varchar(100)
    ,Location Int
    ,ColumnValue Varchar(8000)
    )

    SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE  TABLE_SCHEMA = @schema AND TABLE_NAME =  @tablename AND DATA_TYPE LIKE '%CHAR%'

    DECLARE looper CURSOR FAST_FORWARD for
    SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = @schema AND TABLE_NAME =  @tablename AND DATA_TYPE LIKE '%CHAR%'
    OPEN looper
    FETCH NEXT FROM looper INTO @ColName

    WHILE @@fetch_status = 0
    BEGIN
    SELECT @cmd = 'select ''' +@ColName+    ''',  CHARINDEX(Char(10),  '+  @ColName +') , '+ @ColName + ' from '+@schema + '.'+@tablename +' where CHARINDEX(Char(10),  '+  @ColName +' ) > 0 or CHARINDEX(CHAR(13), '+@ColName +') > 0'
    PRINT @cmd
    INSERT @NewLine ( ColumnName, Location, ColumnValue )
    EXEC sp_executesql @cmd
    FETCH NEXT FROM looper INTO @ColName
    end
    CLOSE looper
    DEALLOCATE looper


    SELECT * FROM  @NewLine

How to create query parameters in Javascript?

URLSearchParams has increasing browser support.

const data = {
  var1: 'value1',
  var2: 'value2'
};

const searchParams = new URLSearchParams(data);

// searchParams.toString() === 'var1=value1&var2=value2'

Node.js offers the querystring module.

const querystring = require('querystring');

const data = {
  var1: 'value1',
  var2: 'value2'
};

const searchParams = querystring.stringify(data);

// searchParams === 'var1=value1&var2=value2'

WCF error - There was no endpoint listening at

You can solve the issue by clearing value of address in endpoint tag in web.config:

<endpoint address="" name="wsHttpEndpoint"  .......           />

How to find reason of failed Build without any error or warning

I had this same problem and I traced this issue down to the Error List options "Build + Intellisense".

If this option is selected then no errors are shown in the list. Switch to "Build Only" and the errors appear as expected.

Its look like a bug in Visual Studio. Restarting the visual studio solved this issue.

How to concatenate text from multiple rows into a single text string in SQL server?

This answer may return unexpected results For consistent results, use one of the FOR XML PATH methods detailed in other answers.

Use COALESCE:

DECLARE @Names VARCHAR(8000) 
SELECT @Names = COALESCE(@Names + ', ', '') + Name 
FROM People

Just some explanation (since this answer seems to get relatively regular views):

  • Coalesce is really just a helpful cheat that accomplishes two things:

1) No need to initialize @Names with an empty string value.

2) No need to strip off an extra separator at the end.

  • The solution above will give incorrect results if a row has a NULL Name value (if there is a NULL, the NULL will make @Names NULL after that row, and the next row will start over as an empty string again. Easily fixed with one of two solutions:
DECLARE @Names VARCHAR(8000) 
SELECT @Names = COALESCE(@Names + ', ', '') + Name
FROM People
WHERE Name IS NOT NULL

or:

DECLARE @Names VARCHAR(8000) 
SELECT @Names = COALESCE(@Names + ', ', '') + 
    ISNULL(Name, 'N/A')
FROM People

Depending on what behavior you want (the first option just filters NULLs out, the second option keeps them in the list with a marker message [replace 'N/A' with whatever is appropriate for you]).

Replace multiple strings with multiple other strings

using Array.prototype.reduce():

const arrayOfObjects = [
  { plants: 'men' },
  { smart:'dumb' },
  { peace: 'war' }
]
const sentence = 'plants are smart'

arrayOfObjects.reduce(
  (f, s) => `${f}`.replace(Object.keys(s)[0], s[Object.keys(s)[0]]), sentence
)

// as a reusable function
const replaceManyStr = (obj, sentence) => obj.reduce((f, s) => `${f}`.replace(Object.keys(s)[0], s[Object.keys(s)[0]]), sentence)

const result = replaceManyStr(arrayOfObjects , sentence1)

Example

_x000D_
_x000D_
// /////////////    1. replacing using reduce and objects_x000D_
_x000D_
// arrayOfObjects.reduce((f, s) => `${f}`.replace(Object.keys(s)[0], s[Object.keys(s)[0]]), sentence)_x000D_
_x000D_
// replaces the key in object with its value if found in the sentence_x000D_
// doesn't break if words aren't found_x000D_
_x000D_
// Example_x000D_
_x000D_
const arrayOfObjects = [_x000D_
  { plants: 'men' },_x000D_
  { smart:'dumb' },_x000D_
  { peace: 'war' }_x000D_
]_x000D_
const sentence1 = 'plants are smart'_x000D_
const result1 = arrayOfObjects.reduce((f, s) => `${f}`.replace(Object.keys(s)[0], s[Object.keys(s)[0]]), sentence1)_x000D_
_x000D_
console.log(result1)_x000D_
_x000D_
// result1: _x000D_
// men are dumb_x000D_
_x000D_
_x000D_
// Extra: string insertion python style with an array of words and indexes_x000D_
_x000D_
// usage_x000D_
_x000D_
// arrayOfWords.reduce((f, s, i) => `${f}`.replace(`{${i}}`, s), sentence)_x000D_
_x000D_
// where arrayOfWords has words you want to insert in sentence_x000D_
_x000D_
// Example_x000D_
_x000D_
// replaces as many words in the sentence as are defined in the arrayOfWords_x000D_
// use python type {0}, {1} etc notation_x000D_
_x000D_
// five to replace_x000D_
const sentence2 = '{0} is {1} and {2} are {3} every {5}'_x000D_
_x000D_
// but four in array? doesn't break_x000D_
const words2 = ['man','dumb','plants','smart']_x000D_
_x000D_
// what happens ?_x000D_
const result2 = words2.reduce((f, s, i) => `${f}`.replace(`{${i}}`, s), sentence2)_x000D_
_x000D_
console.log(result2)_x000D_
_x000D_
// result2: _x000D_
// man is dumb and plants are smart every {5}_x000D_
_x000D_
// replaces as many words as are defined in the array_x000D_
// three to replace_x000D_
const sentence3 = '{0} is {1} and {2}'_x000D_
_x000D_
// but five in array_x000D_
const words3 = ['man','dumb','plant','smart']_x000D_
_x000D_
// what happens ? doesn't break_x000D_
const result3 = words3.reduce((f, s, i) => `${f}`.replace(`{${i}}`, s), sentence3)_x000D_
_x000D_
console.log(result3)_x000D_
_x000D_
// result3: _x000D_
// man is dumb and plants
_x000D_
_x000D_
_x000D_

HAX kernel module is not installed

Since most modern CPUs support virtualization natively, the reason you received such message can be because virtualization is turned off on your machine. For example, that was the case on my HP laptop - the factory setting for hardware virtualization was "Disabled". So, go to your machine's BIOS and enable virtualization.

Best way to get the max value in a Spark dataframe column

import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.functions._

val testDataFrame = Seq(
  (1.0, 4.0), (2.0, 5.0), (3.0, 6.0)
).toDF("A", "B")

val (maxA, maxB) = testDataFrame.select(max("A"), max("B"))
  .as[(Double, Double)]
  .first()
println(maxA, maxB)

And the result is (3.0,6.0), which is the same to the testDataFrame.agg(max($"A"), max($"B")).collect()(0).However, testDataFrame.agg(max($"A"), max($"B")).collect()(0) returns a List, [3.0,6.0]

Generating a PDF file from React Components

You can use ReactDOMServer to render your component to HTML and then use this on jsPDF.

First do the imports:

import React from "react";
import ReactDOMServer from "react-dom/server";
import jsPDF from 'jspdf';

then:

var doc = new jsPDF();
doc.fromHTML(ReactDOMServer.renderToStaticMarkup(this.render()));
doc.save("myDocument.pdf");

Prefer to use:

renderToStaticMarkup

instead of:

renderToString

As the former include HTML code that react relies on.

Convert International String to \u Codes in java

You could probably hack if from this JavaScript code:

/* convert  to \uD83D\uDE4C */
function text_to_unicode(string) {
  'use strict';

  function is_whitespace(c) { return 9 === c || 10 === c || 13 === c || 32 === c;  }
  function left_pad(string) { return Array(4).concat(string).join('0').slice(-1 * Math.max(4, string.length)); }

  string = string.split('').map(function(c){ return "\\u" + left_pad(c.charCodeAt(0).toString(16).toUpperCase()); }).join('');

  return string;
}


/* convert \uD83D\uDE4C to  */
function unicode_to_text(string) {
  var  prefix = "\\\\u"
     , regex  = new RegExp(prefix + "([\da-f]{4})","ig")
     ; 

  string = string.replace(regex, function(match, backtrace1){
    return String.fromCharCode( parseInt(backtrace1, 16) )
  });

  return string;
}

source: iCompile - Yet Another JavaScript Unicode Encode/Decode

onSaveInstanceState () and onRestoreInstanceState ()

I can do like that (sorry it's c# not java but it's not a problem...) :

private int iValue = 1234567890;

function void MyTest()
{
    Intent oIntent = new Intent (this, typeof(Camera2Activity));
    Bundle oBundle = new Bundle();
    oBundle.PutInt("MYVALUE", iValue); //=> 1234567890
    oIntent.PutExtras (oBundle);
    iRequestCode = 1111;
    StartActivityForResult (oIntent, 1111);
}

AND IN YOUR ACTIVITY FOR RESULT

private int iValue = 0;

protected override void OnCreate(Bundle bundle)
{
    Bundle oBundle =  Intent.Extras;
    if (oBundle != null)
    {
        iValue = oBundle.GetInt("MYVALUE", 0);
        //=>1234567890
    }
}

private void FinishActivity(bool bResult)
{
    Intent oIntent = new Intent();
    Bundle oBundle = new Bundle();
    oBundle.PutInt("MYVALUE", iValue);//=>1234567890
    oIntent.PutExtras(oBundle);
    if (bResult)
        {
            SetResult (Result.Ok, oIntent);
        }
    else
        SetResult(Result.Canceled, oIntent);
    GC.Collect();
    Finish();
}

FINALLY

protected override void OnActivityResult(int iRequestCode, Android.App.Result oResultCode, Intent oIntent)
{
    base.OnActivityResult (iRequestCode, oResultCode, oIntent);
    iValue = oIntent.Extras.GetInt("MYVALUE", -1); //=> 1234567890
}

How to change the background color on a Java panel?

You could call:


getContentPane().setBackground(Color.black);

Or add a JPanel to the JFrame your using. Then add your components to the JPanel. This will allow you to call


setBackground(Color.black);

on the JPanel to set the background color.

Open file dialog box in JavaScript

_x000D_
_x000D_
    $("#logo").css('opacity','0');_x000D_
    _x000D_
    $("#select_logo").click(function(e){_x000D_
       e.preventDefault();_x000D_
       $("#logo").trigger('click');_x000D_
    });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<a href="#" id="select_logo">Select Logo</a> <input type="file" id="logo">
_x000D_
_x000D_
_x000D_

for IE add this:

$("#logo").css('filter','alpha(opacity = 0');

List of all special characters that need to be escaped in a regex

The Pattern.quote(String s) sort of does what you want. However it leaves a little left to be desired; it doesn't actually escape the individual characters, just wraps the string with \Q...\E.

There is not a method that does exactly what you are looking for, but the good news is that it is actually fairly simple to escape all of the special characters in a Java regular expression:

regex.replaceAll("[\\W]", "\\\\$0")

Why does this work? Well, the documentation for Pattern specifically says that its permissible to escape non-alphabetic characters that don't necessarily have to be escaped:

It is an error to use a backslash prior to any alphabetic character that does not denote an escaped construct; these are reserved for future extensions to the regular-expression language. A backslash may be used prior to a non-alphabetic character regardless of whether that character is part of an unescaped construct.

For example, ; is not a special character in a regular expression. However, if you escape it, Pattern will still interpret \; as ;. Here are a few more examples:

  • > becomes \> which is equivalent to >
  • [ becomes \[ which is the escaped form of [
  • 8 is still 8.
  • \) becomes \\\) which is the escaped forms of \ and ( concatenated.

Note: The key is is the definition of "non-alphabetic", which in the documentation really means "non-word" characters, or characters outside the character set [a-zA-Z_0-9].

Trigger insert old values- values that was updated

In your trigger, you have two pseudo-tables available, Inserted and Deleted, which contain those values.

In the case of an UPDATE, the Deleted table will contain the old values, while the Inserted table contains the new values.

So if you want to log the ID, OldValue, NewValue in your trigger, you'd need to write something like:

CREATE TRIGGER trgEmployeeUpdate
ON dbo.Employees AFTER UPDATE
AS 
   INSERT INTO dbo.LogTable(ID, OldValue, NewValue)
      SELECT i.ID, d.Name, i.Name
      FROM Inserted i
      INNER JOIN Deleted d ON i.ID = d.ID

Basically, you join the Inserted and Deleted pseudo-tables, grab the ID (which is the same, I presume, in both cases), the old value from the Deleted table, the new value from the Inserted table, and you store everything in the LogTable

ORA-00907: missing right parenthesis

Firstly, in histories_T, you are referencing table T_customer (should be T_customers) and secondly, you are missing the FOREIGN KEY clause that REFERENCES orders; which is not being created (or dropped) with the code you provided.

There may be additional errors as well, and I admit Oracle has never been very good at describing the cause of errors - "Mutating Tables" is a case in point.

Let me know if there additional problems you are missing.

How to initialize an array in Java?

Maybe this will work:

public class Array {

    int data[] = new int[10]; 
    /* Creates a new instance of Array */
    public Array() {
        data= {10,20,30,40,50,60,71,80,90,91};
    }
}

How to navigate through a vector using iterators? (C++)

Vector's iterators are random access iterators which means they look and feel like plain pointers.

You can access the nth element by adding n to the iterator returned from the container's begin() method, or you can use operator [].

std::vector<int> vec(10);
std::vector<int>::iterator it = vec.begin();

int sixth = *(it + 5);
int third = *(2 + it);
int second = it[1];

Alternatively you can use the advance function which works with all kinds of iterators. (You'd have to consider whether you really want to perform "random access" with non-random-access iterators, since that might be an expensive thing to do.)

std::vector<int> vec(10);
std::vector<int>::iterator it = vec.begin();

std::advance(it, 5);
int sixth = *it;

Get the size of a 2D array

In Java, 2D arrays are really arrays of arrays with possibly different lengths (there are no guarantees that in 2D arrays that the 2nd dimension arrays all be the same length)

You can get the length of any 2nd dimension array as z[n].length where 0 <= n < z.length.

If you're treating your 2D array as a matrix, you can simply get z.length and z[0].length, but note that you might be making an assumption that for each array in the 2nd dimension that the length is the same (for some programs this might be a reasonable assumption).

How do you implement a Stack and a Queue in JavaScript?

Arrays.

Stack:

var stack = [];

//put value on top of stack
stack.push(1);

//remove value from top of stack
var value = stack.pop();

Queue:

var queue = [];

//put value on end of queue
queue.push(1);

//Take first value from queue
var value = queue.shift();

How to open the Chrome Developer Tools in a new window?

Just type ctrl+shift+I in google chrome & you will land in an isolated developer window.

Move seaborn plot legend to a different position?

Building on @user308827's answer: you can use legend=False in factorplot and specify the legend through matplotlib:

import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="whitegrid")

titanic = sns.load_dataset("titanic")

g = sns.factorplot("class", "survived", "sex",
                   data=titanic, kind="bar",
                   size=6, palette="muted",
                   legend=False)
g.despine(left=True)
plt.legend(loc='upper left')
g.set_ylabels("survival probability")

Fatal error: Class 'Illuminate\Foundation\Application' not found

Easy as this, that worked for my project

  • Delete /vendor folder
  • and execute composer install
  • then run project php artisan serve

Converting string format to datetime in mm/dd/yyyy

You can change the format too by doing this

string fecha = DateTime.Now.ToString(format:"dd-MM-yyyy");

// this change the "/" for the "-"

Spring Boot: How can I set the logging level with application.properties?

Update: Starting with Spring Boot v1.2.0.RELEASE, the settings in application.properties or application.yml do apply. See the Log Levels section of the reference guide.

logging.level.org.springframework.web: DEBUG
logging.level.org.hibernate: ERROR

For earlier versions of Spring Boot you cannot. You simply have to use the normal configuration for your logging framework (log4j, logback) for that. Add the appropriate config file (log4j.xml or logback.xml) to the src/main/resources directory and configure to your liking.

You can enable debug logging by specifying --debug when starting the application from the command-line.

Spring Boot provides also a nice starting point for logback to configure some defaults, coloring etc. the base.xml file which you can simply include in your logback.xml file. (This is also recommended from the default logback.xml in Spring Boot.

<include resource="org/springframework/boot/logging/logback/base.xml"/>     

How to calculate probability in a normal distribution given mean & standard deviation?

There's one in scipy.stats:

>>> import scipy.stats
>>> scipy.stats.norm(0, 1)
<scipy.stats.distributions.rv_frozen object at 0x928352c>
>>> scipy.stats.norm(0, 1).pdf(0)
0.3989422804014327
>>> scipy.stats.norm(0, 1).cdf(0)
0.5
>>> scipy.stats.norm(100, 12)
<scipy.stats.distributions.rv_frozen object at 0x928352c>
>>> scipy.stats.norm(100, 12).pdf(98)
0.032786643008494994
>>> scipy.stats.norm(100, 12).cdf(98)
0.43381616738909634
>>> scipy.stats.norm(100, 12).cdf(100)
0.5

[One thing to beware of -- just a tip -- is that the parameter passing is a little broad. Because of the way the code is set up, if you accidentally write scipy.stats.norm(mean=100, std=12) instead of scipy.stats.norm(100, 12) or scipy.stats.norm(loc=100, scale=12), then it'll accept it, but silently discard those extra keyword arguments and give you the default (0,1).]

What is the function of FormulaR1C1?

I find the most valuable feature of .FormulaR1C1 is sheer speed. Versus eg a couple of very large loops filling some data into a sheet, If you can convert what you are doing into a .FormulaR1C1 form. Then a single operation eg myrange.FormulaR1C1 = "my particular formuala" is blindingly fast (can be a thousand times faster). No looping and counting - just fill the range at high speed.

How to delete a file or folder?

Python syntax to delete a file

import os
os.remove("/tmp/<file_name>.txt")

Or

import os
os.unlink("/tmp/<file_name>.txt")

Or

pathlib Library for Python version >= 3.4

file_to_rem = pathlib.Path("/tmp/<file_name>.txt")
file_to_rem.unlink()

Path.unlink(missing_ok=False)

Unlink method used to remove the file or the symbolik link.

If missing_ok is false (the default), FileNotFoundError is raised if the path does not exist.
If missing_ok is true, FileNotFoundError exceptions will be ignored (same behavior as the POSIX rm -f command).
Changed in version 3.8: The missing_ok parameter was added.

Best practice

  1. First, check whether the file or folder exists or not then only delete that file. This can be achieved in two ways :
    a. os.path.isfile("/path/to/file")
    b. Use exception handling.

EXAMPLE for os.path.isfile

#!/usr/bin/python
import os
myfile="/tmp/foo.txt"

## If file exists, delete it ##
if os.path.isfile(myfile):
    os.remove(myfile)
else:    ## Show an error ##
    print("Error: %s file not found" % myfile)

Exception Handling

#!/usr/bin/python
import os

## Get input ##
myfile= raw_input("Enter file name to delete: ")

## Try to delete the file ##
try:
    os.remove(myfile)
except OSError as e:  ## if failed, report it back to the user ##
    print ("Error: %s - %s." % (e.filename, e.strerror))

RESPECTIVE OUTPUT

Enter file name to delete : demo.txt
Error: demo.txt - No such file or directory.

Enter file name to delete : rrr.txt
Error: rrr.txt - Operation not permitted.

Enter file name to delete : foo.txt

Python syntax to delete a folder

shutil.rmtree()

Example for shutil.rmtree()

#!/usr/bin/python
import os
import sys
import shutil

# Get directory name
mydir= raw_input("Enter directory name: ")

## Try to remove tree; if failed show an error using try...except on screen
try:
    shutil.rmtree(mydir)
except OSError as e:
    print ("Error: %s - %s." % (e.filename, e.strerror))

Putting text in top left corner of matplotlib plot

You can use text.

text(x, y, s, fontsize=12)

text coordinates can be given relative to the axis, so the position of your text will be independent of the size of the plot:

The default transform specifies that text is in data coords, alternatively, you can specify text in axis coords (0,0 is lower-left and 1,1 is upper-right). The example below places text in the center of the axes::

text(0.5, 0.5,'matplotlib',
     horizontalalignment='center',
     verticalalignment='center',
     transform = ax.transAxes)

To prevent the text to interfere with any point of your scatter is more difficult afaik. The easier method is to set y_axis (ymax in ylim((ymin,ymax))) to a value a bit higher than the max y-coordinate of your points. In this way you will always have this free space for the text.

EDIT: here you have an example:

In [17]: from pylab import figure, text, scatter, show
In [18]: f = figure()
In [19]: ax = f.add_subplot(111)
In [20]: scatter([3,5,2,6,8],[5,3,2,1,5])
Out[20]: <matplotlib.collections.CircleCollection object at 0x0000000007439A90>
In [21]: text(0.1, 0.9,'matplotlib', ha='center', va='center', transform=ax.transAxes)
Out[21]: <matplotlib.text.Text object at 0x0000000007415B38>
In [22]:

enter image description here

The ha and va parameters set the alignment of your text relative to the insertion point. ie. ha='left' is a good set to prevent a long text to go out of the left axis when the frame is reduced (made narrower) manually.

Using Java with Nvidia GPUs (CUDA)

There is not much information on the nature of the problem and the data, so difficult to advise. However, would recommend to assess the feasibility of other solutions, that can be easier to integrate with java and enables horizontal as well as vertical scaling. The first I would suggest to look at is an open source analytical engine called Apache Spark https://spark.apache.org/ that is available on Microsoft Azure but probably on other cloud IaaS providers too. If you stick to involving your GPU then the suggestion is to look at other GPU supported analytical databases on the market that fits in the budget of your organisation.

Display all views on oracle database

Open a new worksheet on the related instance (Alt-F10) and run the following query

SELECT view_name, owner
FROM sys.all_views 
ORDER BY owner, view_name

Which Android phones out there do have a gyroscope?

Since I have recently developed an Android application using gyroscope data (steady compass), I tried to collect a list with such devices. This is not an exhaustive list at all, but it is what I have so far:

*** Phones:

  • HTC Sensation
  • HTC Sensation XL
  • HTC Evo 3D
  • HTC One S
  • HTC One X
  • Huawei Ascend P1
  • Huawei Ascend X (U9000)
  • Huawei Honor (U8860)
  • LG Nitro HD (P930)
  • LG Optimus 2x (P990)
  • LG Optimus Black (P970)
  • LG Optimus 3D (P920)
  • Samsung Galaxy S II (i9100)
  • Samsung Galaxy S III (i9300)
  • Samsung Galaxy R (i9103)
  • Samsung Google Nexus S (i9020)
  • Samsung Galaxy Nexus (i9250)
  • Samsung Galaxy J3 (2017) model
  • Samsung Galaxy Note (n7000)
  • Sony Xperia P (LT22i)
  • Sony Xperia S (LT26i)

*** Tablets:

  • Acer Iconia Tab A100 (7")
  • Acer Iconia Tab A500 (10.1")
  • Asus Eee Pad Transformer (TF101)
  • Asus Eee Pad Transformer Prime (TF201)
  • Motorola Xoom (mz604)
  • Samsung Galaxy Tab (p1000)
  • Samsung Galaxy Tab 7 plus (p6200)
  • Samsung Galaxy Tab 10.1 (p7100)
  • Sony Tablet P
  • Sony Tablet S
  • Toshiba Thrive 7"
  • Toshiba Trhive 10"

Hope the list keeps growing and hope that gyros will be soon available on mid and low price smartphones.

How to limit the maximum value of a numeric field in a Django model?

You can use Django's built-in validators

from django.db.models import IntegerField, Model
from django.core.validators import MaxValueValidator, MinValueValidator

class CoolModelBro(Model):
    limited_integer_field = IntegerField(
        default=1,
        validators=[
            MaxValueValidator(100),
            MinValueValidator(1)
        ]
     )

Edit: When working directly with the model, make sure to call the model full_clean method before saving the model in order to trigger the validators. This is not required when using ModelForm since the forms will do that automatically.

Object spread vs. Object.assign

For reference object rest/spread is finalised in ECMAScript 2018 as a stage 4. The proposal can be found here.

For the most part object reset and spread work the same way, the key difference is that spread defines properties, whilst Object.assign() sets them. This means Object.assign() triggers setters.

It's worth remembering that other than this, object rest/spread 1:1 maps to Object.assign() and acts differently to array (iterable) spread. For example, when spreading an array null values are spread. However using object spread null values are silently spread to nothing.

Array (Iterable) Spread Example

const x = [1, 2, null , 3];
const y = [...x, 4, 5];
const z = null;

console.log(y); // [1, 2, null, 3, 4, 5];
console.log([...z]); // TypeError

Object Spread Example

const x = null;
const y = {a: 1, b: 2};
const z = {...x, ...y};

console.log(z); //{a: 1, b: 2}

This is consistent with how Object.assign() would work, both silently exclude the null value with no error.

const x = null;
const y = {a: 1, b: 2};
const z = Object.assign({}, x, y);

console.log(z); //{a: 1, b: 2}

How to have git log show filenames like svn log -v

For full path names of changed files:

git log --name-only

For full path names and status of changed files:

git log --name-status

For abbreviated pathnames and a diffstat of changed files:

git log --stat

There's a lot more options, check out the docs.

How to return only the Date from a SQL Server DateTime datatype

SELECT CONVERT(VARCHAR,DATEADD(DAY,-1,GETDATE()),103) --21/09/2011

SELECT CONVERT(VARCHAR,DATEADD(DAY,-1,GETDATE()),101) --09/21/2011

SELECT CONVERT(VARCHAR,DATEADD(DAY,-1,GETDATE()),111) --2011/09/21

SELECT CONVERT(VARCHAR,DATEADD(DAY,-1,GETDATE()),107) --Sep 21, 2011

"Please try running this command again as Root/Administrator" error when trying to install LESS

Just prepend sudo to the beginning of your command. As stated before, an installation runs some scripts that might be dangerous but I saw installing globally helps a lot and is way simpler.

Run sudo npm install -g less

Error Installing Homebrew - Brew Command Not Found

You can use this:

ruby -e "$(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)" 

to install homebrew.

How do I read a file line by line in VB Script?

When in doubt, read the documentation:

filename = "C:\Temp\vblist.txt"

Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(filename)

Do Until f.AtEndOfStream
  WScript.Echo f.ReadLine
Loop

f.Close

HTML select dropdown list

<select>
  <option value="" disabled selected hidden>Select an Option</option>
  <option value="one">Option 1</option>
  <option value="two">Option 2</option>
</select>

How to copy a row from one SQL Server table to another

SELECT * INTO < new_table > FROM < existing_table > WHERE < clause >

Infinite Recursion with Jackson JSON and Hibernate JPA issue

You may use @JsonIgnore to break the cycle (reference).

You need to import org.codehaus.jackson.annotate.JsonIgnore (legacy versions) or com.fasterxml.jackson.annotation.JsonIgnore (current versions).

java.lang.OutOfMemoryError: Java heap space

In netbeans, Go to 'Run' toolbar, --> 'Set Project Configuration' --> 'Customise' --> 'run' of its popped up windo --> 'VM Option' --> fill in '-Xms2048m -Xmx2048m'. It could solve heap size problem.

How to get two or more commands together into a batch file

You can use the following command. The SET will set the input from the user console to the variable comment and then you can use that variable using %comment%

SET /P comment=Comment: 
echo %comment%
pause

Difference between java HH:mm and hh:mm on SimpleDateFormat

Please take a look here

HH is hour in a day (starting from 0 to 23)

hh are hours in am/pm format

kk is hour in day (starting from 1 to 24)

mm is minute in hour

ss are the seconds in a minute

ASP.NET MVC: Html.EditorFor and multi-line text boxes

in your view, instead of:

@Html.EditorFor(model => model.Comments[0].Comment)

just use:

@Html.TextAreaFor(model => model.Comments[0].Comment, 5, 1, null)

Remove all classes that begin with a certain string

Prestaul's answer was helpful, but it didn't quite work for me. The jQuery way to select an object by id didn't work. I had to use

document.getElementById("a").className

instead of

$("#a").className

Send auto email programmatically

It might be an easiest way-

    String recipientList = mEditTextTo.getText().toString();
    String[] recipients = recipientList.split(",");

    String subject = mEditTextSubject.getText().toString();
    String message = mEditTextMessage.getText().toString();

    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.putExtra(Intent.EXTRA_EMAIL, recipients);
    intent.putExtra(Intent.EXTRA_SUBJECT, subject);
    intent.putExtra(Intent.EXTRA_TEXT, message);

    intent.setType("message/rfc822");
    startActivity(Intent.createChooser(intent, "Choose an email client"));

How to efficiently calculate a running standard deviation?

Perhaps not what you were asking, but ... If you use a numpy array, it will do the work for you, efficiently:

from numpy import array

nums = array(((0.01, 0.01, 0.02, 0.04, 0.03),
              (0.00, 0.02, 0.02, 0.03, 0.02),
              (0.01, 0.02, 0.02, 0.03, 0.02),
              (0.01, 0.00, 0.01, 0.05, 0.03)))

print nums.std(axis=1)
# [ 0.0116619   0.00979796  0.00632456  0.01788854]

print nums.mean(axis=1)
# [ 0.022  0.018  0.02   0.02 ]

By the way, there's some interesting discussion in this blog post and comments on one-pass methods for computing means and variances:

How can I map "insert='false' update='false'" on a composite-id key-property which is also used in a one-to-many FK?

I think the annotation you are looking for is:

public class CompanyName implements Serializable {
//...
@JoinColumn(name = "COMPANY_ID", referencedColumnName = "COMPANY_ID", insertable = false, updatable = false)
private Company company;

And you should be able to use similar mappings in a hbm.xml as shown here (in 23.4.2):

http://docs.jboss.org/hibernate/core/3.3/reference/en/html/example-mappings.html

Using CSS in Laravel views?

Copy the css or js file that you want to include, to public folder or you may want to store those in public/css or public/js folders.

Eg. you are using style.css file from css folder in public directory then you can use

<link rel="stylesheet" href="{{ url() }}./css/style.css" type="text/css"/>

But in Laravel 5.2 you will have to use

<link rel="stylesheet" href="{{ url('/') }}./css/style.css" type="text/css"/>

and if you want to include javascript files from public/js folder, it's fairly simple too

<script src="{{ url() }}./js/jquery.min.js"></script>

and in Laravel 5.2 you wll have to use

<script src="{{ url('/') }}./js/jquery.min.js"></script>

the function url() is a laravel helper function which will generate fully qualified URL to given path.

#include errors detected in vscode

In my case I did not need to close the whole VS-Code, closing the opened file (and sometimes even saving it) solved the issue.

run program in Python shell

From the same folder, you can do:

import test

Alter column in SQL Server

To set a default value to a column, try this:

ALTER TABLE tb_TableName
ALTER COLUMN Record_Status SET DEFAULT 'default value'

Limit String Length

You can use something similar to the below:

if (strlen($str) > 10)
   $str = substr($str, 0, 7) . '...';

How can I sort a std::map first by value, then by key?

EDIT: The other two answers make a good point. I'm assuming that you want to order them into some other structure, or in order to print them out.

"Best" can mean a number of different things. Do you mean "easiest," "fastest," "most efficient," "least code," "most readable?"

The most obvious approach is to loop through twice. On the first pass, order the values:

if(current_value > examined_value)
{
    current_value = examined_value
    (and then swap them, however you like)
}

Then on the second pass, alphabetize the words, but only if their values match.

if(current_value == examined_value)
{
    (alphabetize the two)
}

Strictly speaking, this is a "bubble sort" which is slow because every time you make a swap, you have to start over. One "pass" is finished when you get through the whole list without making any swaps.

There are other sorting algorithms, but the principle would be the same: order by value, then alphabetize.

get path for my .exe

In addition:

AppDomain.CurrentDomain.BaseDirectory
Assembly.GetEntryAssembly().Location

What is your single most favorite command-line trick using Bash?

Insert preceding lines final parameter

ALT-. the most useful key combination ever, try it and see, for some reason no one knows about this one.

Press it again and again to select older last parameters.

Great when you want to do something else to something you used just a moment ago.

HTML5 Form Input Pattern Currency Format

I'm wrote this price pattern without zero price.

(0\.((0[1-9]{1})|([1-9]{1}([0-9]{1})?)))|(([1-9]+[0-9]*)(\.([0-9]{1,2}))?)

Valid For:

  • 1.00
  • 1
  • 1.5
  • 0.10
  • 0.1
  • 0.01
  • 2500.00

Invalid For:

  • 0
  • 0.00
  • 0.0
  • 2500.
  • 2500.0000

Check my code online: http://regexr.com/3binj

What is a file with extension .a?

.a files are static libraries typically generated by the archive tool. You usually include the header files associated with that static library and then link to the library when you are compiling.

What's the equivalent of Java's Thread.sleep() in JavaScript?

The simple answer is that there is no such function.

The closest thing you have is:

var millisecondsToWait = 500;
setTimeout(function() {
    // Whatever you want to do after the wait
}, millisecondsToWait);

Note that you especially don't want to busy-wait (e.g. in a spin loop), since your browser is almost certainly executing your JavaScript in a single-threaded environment.

Here are a couple of other SO questions that deal with threads in JavaScript:

And this question may also be helpful:

How to scanf only integer and repeat reading if the user enters non-numeric characters?

Use scanf("%d",&rows) instead of scanf("%s",input)

This allow you to get direcly the integer value from stdin without need to convert to int.

If the user enter a string containing a non numeric characters then you have to clean your stdin before the next scanf("%d",&rows).

your code could look like this:

#include <stdio.h>  
#include <stdlib.h> 

int clean_stdin()
{
    while (getchar()!='\n');
    return 1;
}

int main(void)  
{ 
    int rows =0;  
    char c;
    do
    {  
        printf("\nEnter an integer from 1 to 23: ");

    } while (((scanf("%d%c", &rows, &c)!=2 || c!='\n') && clean_stdin()) || rows<1 || rows>23);

    return 0;  
}

Explanation

1)

scanf("%d%c", &rows, &c)

This means expecting from the user input an integer and close to it a non numeric character.

Example1: If the user enter aaddk and then ENTER, the scanf will return 0. Nothing capted

Example2: If the user enter 45 and then ENTER, the scanf will return 2 (2 elements are capted). Here %d is capting 45 and %c is capting \n

Example3: If the user enter 45aaadd and then ENTER, the scanf will return 2 (2 elements are capted). Here %d is capting 45 and %c is capting a

2)

(scanf("%d%c", &rows, &c)!=2 || c!='\n')

In the example1: this condition is TRUE because scanf return 0 (!=2)

In the example2: this condition is FALSE because scanf return 2 and c == '\n'

In the example3: this condition is TRUE because scanf return 2 and c == 'a' (!='\n')

3)

((scanf("%d%c", &rows, &c)!=2 || c!='\n') && clean_stdin())

clean_stdin() is always TRUE because the function return always 1

In the example1: The (scanf("%d%c", &rows, &c)!=2 || c!='\n') is TRUE so the condition after the && should be checked so the clean_stdin() will be executed and the whole condition is TRUE

In the example2: The (scanf("%d%c", &rows, &c)!=2 || c!='\n') is FALSE so the condition after the && will not checked (because what ever its result is the whole condition will be FALSE ) so the clean_stdin() will not be executed and the whole condition is FALSE

In the example3: The (scanf("%d%c", &rows, &c)!=2 || c!='\n') is TRUE so the condition after the && should be checked so the clean_stdin() will be executed and the whole condition is TRUE

So you can remark that clean_stdin() will be executed only if the user enter a string containing non numeric character.

And this condition ((scanf("%d%c", &rows, &c)!=2 || c!='\n') && clean_stdin()) will return FALSE only if the user enter an integer and nothing else

And if the condition ((scanf("%d%c", &rows, &c)!=2 || c!='\n') && clean_stdin()) is FALSE and the integer is between and 1 and 23 then the while loop will break else the while loop will continue

What is the difference between single and double quotes in SQL?

I use this mnemonic:

  • Single quotes are for strings (one thing)
  • Double quotes are for tables names and column names (two things)

This is not 100% correct according to the specs, but this mnemonic helps me (human being).

Primefaces valueChangeListener or <p:ajax listener not firing for p:selectOneMenu

If you want to use valueChangeListener, you need to submit the form every time a new option is chosen. Something like this:

<p:selectOneMenu value="#{mymb.employee}" onchange="submit()"
                 valueChangeListener="#{mymb.handleChange}" >
    <f:selectItems value="#{mymb.employeesList}" var="emp"
                   itemLabel="#{emp.employeeName}" itemValue="#{emp.employeeID}" />
</p:selectOneMenu>

public void handleChange(ValueChangeEvent event){  
    System.out.println("New value: " + event.getNewValue());
}

Or else, if you want to use <p:ajax>, it should look like this:

<p:selectOneMenu value="#{mymb.employee}" >
    <p:ajax listener="#{mymb.handleChange}" />
    <f:selectItems value="#{mymb.employeesList}" var="emp"
                   itemLabel="#{emp.employeeName}" itemValue="#{emp.employeeID}" />
</p:selectOneMenu>

private String employeeID;

public void handleChange(){  
    System.out.println("New value: " + employee);
}

One thing to note is that in your example code, I saw that the value attribute of your <p:selectOneMenu> is #{mymb.employeesList} which is the same as the value of <f:selectItems>. The value of your <p:selectOneMenu> should be similar to my examples above which point to a single employee, not a list of employees.

Error: Address already in use while binding socket with address but the port number is shown free by `netstat`

the error i received was:

cockpit.socket: Failed to listen on sockets: Address already in use

the fix I discovered is:

  1. I had to disable selinux
  2. in /usr/lib/systemd/system/cockpit service i changed the line :

    #ExecStartPre=/usr/sbin/remotectl certificate --ensure --user=root --group=cockpit-ws --selinux-type=etc_t
    

    to:

    #ExecStartPre=/usr/sbin/remotectl certificate --ensure --user=root --group=cockpit-ws 
    

so as you can see i took out the argument about selinux then i ran:

systemctl daemon-reload
systemctl start cockpit.service

then I browsed to:

I accepted the self-signed certificate and was able to login successfully to cockpit and use it normally.

this is all on a fedora25 machine. the 9090 port had already been added using firewall-cmd

Formatting MM/DD/YYYY dates in textbox in VBA

You could use an input mask on the text box, too. If you set the mask to ##/##/#### it will always be formatted as you type and you don't need to do any coding other than checking to see if what was entered was a true date.

Which just a few easy lines

txtUserName.SetFocus
If IsDate(txtUserName.text) Then
    Debug.Print Format(CDate(txtUserName.text), "MM/DD/YYYY")
Else
    Debug.Print "Not a real date"
End If

How to run Conda?

Run

cat ~/.bash_profile

to check if anaconda is there. If not you should add its path there. If conda is there copy the entire row that you see the Anaconda there from "export" to the end of line. like this:

export PATH=~/anaconda3/bin:$PATH

Run this in your terminal. Then run

conda --version

to see if it is exported and running!

Is <img> element block level or inline level?

For almost all purposes think of them as an inline element with a width set. Basically you are free to dictate how you would like images to display using CSS. I generally set a few image classes like so:

img.center {display:block;margin:0 auto;}

img.left {float:left;margin-right:10px;}

img.right  {float:right;margin-left:10px;}

img.border  {border:1px solid #333;}

MVC 4 - how do I pass model data to a partial view?

I know question is specific to MVC4. But since we are way past MVC4 and if anyone looking for ASP.NET Core, you can use:

<partial name="_My_Partial" model="Model.MyInfo" />

How do you transfer or export SQL Server 2005 data to Excel

I've found an easy way to export query results from SQL Server Management Studio 2005 to Excel.

1) Select menu item Query -> Query Options.

2) Set check box in Results -> Grid -> Include column headers when copying or saving the results.

After that, when you Select All and Copy the query results, you can paste them to Excel, and the column headers will be present.

MySQL: How to reset or change the MySQL root password?

I faced problems with ubuntu 18.04 and mysql 5.7, this is the solution

Try restart mysql-server before execution the comands

sudo service mysql restart

MYSQL-SERVER >= 5.7

sudo mysql -uroot -p
USE mysql;
UPDATE user SET authentication_string=PASSWORD('YOUR_PASSWORD') WHERE User='root';
UPDATE user SET plugin="mysql_native_password";
FLUSH PRIVILEGES;
quit;

MYSQL-SERVER < 5.7

sudo mysql -uroot -p
USE mysql;
UPDATE user SET password=PASSWORD('YOUR_PASSWORD') WHERE User='root';
UPDATE user SET plugin="mysql_native_password";
FLUSH PRIVILEGES;
quit;

Java SSLException: hostname in certificate didn't match

I had similar problem. I was using Android's DefaultHttpClient. I have read that HttpsURLConnection can handle this kind of exception. So I created custom HostnameVerifier which uses the verifier from HttpsURLConnection. I also wrapped the implementation to custom HttpClient.

public class CustomHttpClient extends DefaultHttpClient {

public CustomHttpClient() {
    super();
    SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
    socketFactory.setHostnameVerifier(new CustomHostnameVerifier());
    Scheme scheme = (new Scheme("https", socketFactory, 443));
    getConnectionManager().getSchemeRegistry().register(scheme);
}

Here is the CustomHostnameVerifier class:

public class CustomHostnameVerifier implements org.apache.http.conn.ssl.X509HostnameVerifier {

@Override
public boolean verify(String host, SSLSession session) {
    HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();
    return hv.verify(host, session);
}

@Override
public void verify(String host, SSLSocket ssl) throws IOException {
}

@Override
public void verify(String host, X509Certificate cert) throws SSLException {

}

@Override
public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {

}

}

What is copy-on-write?

Copy-on-write is a technique to reduce the memory usage of resource copies using deferred copy. The resource copies are initially virtual (i.e. they share memory) and only become real (i.e. they have their own memory) on the first write operation, hence the name ‘copy-on-write’.

Here after is a Python implementation of the copy-on-write technique using the proxy design pattern. A ValueProxy object (the proxy) implements the copy-on-write technique by:

  • having an attribute bound to an immutable Value object (the subject);
  • translating copy requests to the creation of a new ValueProxy object sharing the same subject attribute as the original ValueProxy object;
  • forwarding read requests to the subject attribute;
  • translating write requests to the creation of a new immutable Value object with the new state and the rebinding of the subject attribute to this new immutable Value object.
import abc

class BaseValue(abc.ABC):
    @abc.abstractmethod
    def read(self):
        raise NotImplementedError
    @abc.abstractmethod
    def write(self, data):
        raise NotImplementedError

class Value(BaseValue):
    def __init__(self, data):
        self.data = data
    def read(self):
        return self.data
    def write(self, data):
        pass

class ValueProxy(BaseValue):
    def __init__(self, subject):
        self.subject = subject
    def read(self):
        return self.subject.read()
    def write(self, data):
        self.subject = Value(data)
    def clone(self):
        return ValueProxy(self.subject)

v1 = ValueProxy(Value('foo'))
v2 = v1.clone()  # shares the immutable Value object between the copies
assert v1.subject is v2.subject
v2.write('bar')  # creates a new immutable Value object with the new state
assert v1.subject is not v2.subject

Calling an executable program using awk

I use the power of awk to delete some of my stopped docker containers. Observe carefully how i construct the cmd string first before passing it to system.

docker ps -a | awk '$3 ~ "/bin/clish" { cmd="docker rm "$1;system(cmd)}'

Here, I use the 3rd column having the pattern "/bin/clish" and then I extract the container ID in the first column to construct my cmd string and passed that to system.

Open existing file, append a single line

Or you could use File.AppendAllLines(string, IEnumerable<string>)

File.AppendAllLines(@"C:\Path\file.txt", new[] { "my text content" });

Delete entire row if cell contains the string X

I'd like to add to @MBK's answer. Although I found @MBK's answer to be very helpful in solving a similar problem, it'd be better if @MBK included a screenshot of how to filter a particular column.enter image description here

CSS change button style after click

Try to check outline on button's focus:

button:focus {
    outline: blue auto 5px; 
}

If you have it, just set it to none.

Way to *ngFor loop defined number of times instead of repeating over array?

Within your component, you can define an array of number (ES6) as described below:

export class SampleComponent {
  constructor() {
    this.numbers = Array(5).fill(0).map((x,i)=>i);
  }
}

See this link for the array creation: Tersest way to create an array of integers from 1..20 in JavaScript.

You can then iterate over this array with ngFor:

@View({
  template: `
    <ul>
      <li *ngFor="let number of numbers">{{number}}</li>
    </ul>
  `
})
export class SampleComponent {
  (...)
}

Or shortly:

@View({
  template: `
    <ul>
      <li *ngFor="let number of [0,1,2,3,4]">{{number}}</li>
    </ul>
  `
})
export class SampleComponent {
  (...)
}

Hope it helps you, Thierry

Edit: Fixed the fill statement and template syntax.

How to Set Focus on Input Field using JQuery

Try this, to set the focus to the first input field:

$(this).parent().siblings('div.bottom').find("input.post").focus();

How do I point Crystal Reports at a new database

Use the Database menu and "Set Datasource Location" menu option to change the name or location of each table in a report.

This works for changing the location of a database, changing to a new database, and changing the location or name of an individual table being used in your report.

To change the datasource connection, go the Database menu and click Set Datasource Location.

  1. Change the Datasource Connection:
    1. From the Current Data Source list (the top box), click once on the datasource connection that you want to change.
    2. In the Replace with list (the bottom box), click once on the new datasource connection.
    3. Click Update.
  2. Change Individual Tables:
    1. From the Current Data Source list (the top box), expand the datasource connection that you want to change.
    2. Find the table for which you want to update the location or name.
    3. In the Replace with list (the bottom box), expand the new datasource connection.
    4. Find the new table you want to update to point to.
    5. Click Update.
    6. Note that if the table name has changed, the old table name will still appear in the Field Explorer even though it is now using the new table. (You can confirm this be looking at the Table Name of the table's properties in Current Data Source in Set Datasource Location. Screenshot http://i.imgur.com/gzGYVTZ.png) It's possible to rename the old table name to the new name from the context menu in Database Expert -> Selected Tables.
  3. Change Subreports:
    1. Repeat each of the above steps for any subreports you might have embedded in your report.
    2. Close the Set Datasource Location window.
  4. Any Commands or SQL Expressions:
    1. Go to the Database menu and click Database Expert.
    2. If the report designer used "Add Command" to write custom SQL it will be shown in the Selected Tables box on the right.
    3. Right click that command and choose "Edit Command".
    4. Check if that SQL is specifying a specific database. If so you might need to change it.
    5. Close the Database Expert window.
    6. In the Field Explorer pane on the right, right click any SQL Expressions.
    7. Check if the SQL Expressions are specifying a specific database. If so you might need to change it also.
    8. Save and close your Formula Editor window when you're done editing.

And try running the report again.

The key is to change the datasource connection first, then any tables you need to update, then the other stuff. The connection won't automatically change the tables underneath. Those tables are like goslings that've imprinted on the first large goose-like animal they see. They'll continue to bypass all reason and logic and go to where they've always gone unless you specifically manually change them.

To make it more convenient, here's a tip: You can "Show SQL Query" in the Database menu, and you'll see table names qualified with the database (like "Sales"."dbo"."Customers") for any tables that go straight to a specific database. That might make the hunting easier if you have a lot of stuff going on. When I tackled this problem I had to change each and every table to point to the new table in the new database.

Remove characters from NSString?

You can try this

- (NSString *)stripRemoveSpaceFrom:(NSString *)str {
    while ([str rangeOfString:@"  "].location != NSNotFound) {
        str = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
    }
    return str;
}

Hope this will help you out.

How to set different colors in HTML in one statement?

Use the span tag

<style>
    .redText
    {
        color:red;
    }
    .blackText
    {
        color:black;
        font-weight:bold;
    }
</style>

<span class="redText">My Name is:</span>&nbsp;<span class="blackText">Tintincute</span>

It's also a good idea to avoid inline styling. Use a custom CSS class instead.

How to enable/disable bluetooth programmatically in android

try this:

//this method to check bluetooth is enable or not: true if enable, false is not enable
public static boolean isBluetoothEnabled()
    {
        BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (!mBluetoothAdapter.isEnabled()) {
            // Bluetooth is not enable :)
            return false;
        }
        else{
            return true;
        }

    }

//method to enable bluetooth
    public static void enableBluetooth(){
        BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (!mBluetoothAdapter.isEnabled()) {
            mBluetoothAdapter.enable();
        }
    }

//method to disable bluetooth
    public static void disableBluetooth(){
        BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter.isEnabled()) {
            mBluetoothAdapter.disable();
        }
    }

Add these permissions in manifest

<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

onclick go full screen

I tried other answers on this question, and there are mistakes with the different browser APIs, particularly Fullscreen vs FullScreen. Here is my code that works with the major browsers (as of Q1 2019) and should continue to work as they standardize.

function fullScreenTgl() {
    let doc=document,elm=doc.documentElement;
    if      (elm.requestFullscreen      ) { (!doc.fullscreenElement   ? elm.requestFullscreen()       : doc.exitFullscreen()        ) }
    else if (elm.mozRequestFullScreen   ) { (!doc.mozFullScreen       ? elm.mozRequestFullScreen()    : doc.mozCancelFullScreen()   ) }
    else if (elm.msRequestFullscreen    ) { (!doc.msFullscreenElement ? elm.msRequestFullscreen()     : doc.msExitFullscreen()      ) }
    else if (elm.webkitRequestFullscreen) { (!doc.webkitIsFullscreen  ? elm.webkitRequestFullscreen() : doc.webkitCancelFullscreen()) }
    else                                  { console.log("Fullscreen support not detected.");                                          }
    }

Copy row but with new id

This works in MySQL all versions and Amazon RDS Aurora:

INSERT INTO my_table SELECT 0,tmp.* FROM tmp;

or

Setting the index column to NULL and then doing the INSERT.

But not in MariaDB, I tested version 10.

Difference between core and processor

CPU is a central processing unit. Since 2002 we have only single core processor i.e. we will only perform a single task or a program at a time.

For having multiple programs run at a time we have to use the multiple processor for executing multi processes at a time so we required another motherboard for that and that is very expensive.

So, Intel introduced the concept of hyper threading i.e. it will convert the single CPU into two virtual CPUs i.e we have two cores for our task. Now the CPU is single, but it is only pretending (masqueraded) that it has a dual CPU and performs multiple tasks. But having real multiple cores will be better than that so people develop making multi-core processor i.e. multiple processors on a single box i.e. grabbing a multiple CPU on single big CPU. I.e. multiple cores.

AngularJS - Passing data between pages

What you should do is create a service to share data between controllers.

Nice tutorial https://www.youtube.com/watch?v=HXpHV5gWgyk

Why is vertical-align: middle not working on my span or div?

This is a modern approach and it utilizes the CSS Flexbox functionality. You can now vertically align the content within your parent container by just adding these styles to the .main container

.main {
        display: flex;
        flex-direction: column;
        justify-content: center;
}

And you are good to go!

C dynamically growing array

I can use pointers, but I am a bit afraid of using them.

If you need a dynamic array, you can't escape pointers. Why are you afraid though? They won't bite (as long as you're careful, that is). There's no built-in dynamic array in C, you'll just have to write one yourself. In C++, you can use the built-in std::vector class. C# and just about every other high-level language also have some similar class that manages dynamic arrays for you.

If you do plan to write your own, here's something to get you started: most dynamic array implementations work by starting off with an array of some (small) default size, then whenever you run out of space when adding a new element, double the size of the array. As you can see in the example below, it's not very difficult at all: (I've omitted safety checks for brevity)

typedef struct {
  int *array;
  size_t used;
  size_t size;
} Array;

void initArray(Array *a, size_t initialSize) {
  a->array = malloc(initialSize * sizeof(int));
  a->used = 0;
  a->size = initialSize;
}

void insertArray(Array *a, int element) {
  // a->used is the number of used entries, because a->array[a->used++] updates a->used only *after* the array has been accessed.
  // Therefore a->used can go up to a->size 
  if (a->used == a->size) {
    a->size *= 2;
    a->array = realloc(a->array, a->size * sizeof(int));
  }
  a->array[a->used++] = element;
}

void freeArray(Array *a) {
  free(a->array);
  a->array = NULL;
  a->used = a->size = 0;
}

Using it is just as simple:

Array a;
int i;

initArray(&a, 5);  // initially 5 elements
for (i = 0; i < 100; i++)
  insertArray(&a, i);  // automatically resizes as necessary
printf("%d\n", a.array[9]);  // print 10th element
printf("%d\n", a.used);  // print number of elements
freeArray(&a);

Removing duplicates from rows based on specific columns in an RDD/Spark DataFrame

Pyspark does include a dropDuplicates() method, which was introduced in 1.4. https://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.DataFrame.dropDuplicates

>>> from pyspark.sql import Row
>>> df = sc.parallelize([ \
...     Row(name='Alice', age=5, height=80), \
...     Row(name='Alice', age=5, height=80), \
...     Row(name='Alice', age=10, height=80)]).toDF()
>>> df.dropDuplicates().show()
+---+------+-----+
|age|height| name|
+---+------+-----+
|  5|    80|Alice|
| 10|    80|Alice|
+---+------+-----+

>>> df.dropDuplicates(['name', 'height']).show()
+---+------+-----+
|age|height| name|
+---+------+-----+
|  5|    80|Alice|
+---+------+-----+

What is the (function() { } )() construct in JavaScript?

One more use case is memoization where a cache object is not global:

var calculate = (function() {
  var cache = {};
  return function(a) {

    if (cache[a]) {
      return cache[a];
    } else {
      // Calculate heavy operation
      cache[a] = heavyOperation(a);
      return cache[a];
    }
  }
})();

document .click function for touch device

the approved answer does not include the essential return false to prevent touchstart from calling click if click is implemented which will result in running the handler twoce.

do:

$(btn).on('click touchstart', e => { 
   your code ...
   return false; 
});

Can attributes be added dynamically in C#?

This really depends on what exactly you're trying to accomplish.

The System.ComponentModel.TypeDescriptor stuff can be used to add attributes to types, properties and object instances, and it has the limitation that you have to use it to retrieve those properties as well. If you're writing the code that consumes those attributes, and you can live within those limitations, then I'd definitely suggest it.

As far as I know, the PropertyGrid control and the visual studio design surface are the only things in the BCL that consume the TypeDescriptor stuff. In fact, that's how they do about half the things they really need to do.

Image size (Python, OpenCV)

I use numpy.size() to do the same:

import numpy as np
import cv2

image = cv2.imread('image.jpg')
height = np.size(image, 0)
width = np.size(image, 1)

Concat scripts in order with Gulp

I had a similar problem recently with Grunt when building my AngularJS app. Here's a question I posted.

What I ended up doing is to explicitly list the files in order in the grunt config. The config file will then look like this:

[
  '/path/to/app.js',
  '/path/to/mymodule/mymodule.js',
  '/path/to/mymodule/mymodule/*.js'
]

Grunt is able to figure out which files are duplicates and not include them. The same technique will work with Gulp as well.

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;

intellij idea - Error: java: invalid source release 1.9

For anyone struggling with this issue who tried DeanM's solution but to no avail, there's something else worth checking, which is the version of the JDK you have configured for your project. What I'm trying to say is that if you have configured JDK 8u191 (for example) for your project, but have the language level set to anything higher than 8, you're gonna get this error.

In this case, it's probably better to ask whoever's in charge of the project, which version of the JDK would be preferable to compile the sources.

What are the obj and bin folders (created by Visual Studio) used for?

The obj folder holds object, or intermediate, files, which are compiled binary files that haven't been linked yet. They're essentially fragments that will be combined to produce the final executable. The compiler generates one object file for each source file, and those files are placed into the obj folder.

The bin folder holds binary files, which are the actual executable code for your application or library.

Each of these folders are further subdivided into Debug and Release folders, which simply correspond to the project's build configurations. The two types of files discussed above are placed into the appropriate folder, depending on which type of build you perform. This makes it easy for you to determine which executables are built with debugging symbols, and which were built with optimizations enabled and ready for release.

Note that you can change where Visual Studio outputs your executable files during a compile in your project's Properties. You can also change the names and selected options for your build configurations.

how to loop through rows columns in excel VBA Macro

This one is similar to @Wilhelm's solution. The loop automates based on a range created by evaluating the populated date column. This was slapped together based strictly on the conversation here and screenshots.

Please note: This assumes that the headers will always be on the same row (row 8). Changing the first row of data (moving the header up/down) will cause the range automation to break unless you edit the range block to take in the header row dynamically. Other assumptions include that VOL and CAPACITY formula column headers are named "Vol" and "Cap" respectively.

Sub Loop3()

Dim dtCnt As Long
Dim rng As Range
Dim frmlas() As String

Application.ScreenUpdating = False

'The following code block sets up the formula output range
dtCnt = Sheets("Loop").Range("A1048576").End(xlUp).Row              'lowest date column populated
endHead = Sheets("Loop").Range("XFD8").End(xlToLeft).Column         'right most header populated
Set rng = Sheets("Loop").Range(Cells(9, 2), Cells(dtCnt, endHead))  'assigns range for automation

ReDim frmlas(1)      'array assigned to formula strings
    'VOL column formula
frmlas(0) = "VOL FORMULA"
    'CAPACITY column formula
frmlas(1) = "CAP FORMULA"

For i = 1 To rng.Columns.count
If rng(0, i).Value = "Vol" Then         'checks for volume formula column
    For j = 1 To rng.Rows.count
        rng(j, i).Formula= frmlas(0)    'inserts volume formula
    Next j
ElseIf rng(0, i).Value = "Cap" Then     'checks for capacity formula column
    For j = 1 To rng.Rows.count
        rng(j, i).Formula = frmlas(1)   'inserts capacity formula
    Next j
End If
Next i

Application.ScreenUpdating = True

End Sub

Proper way to rename solution (and directories) in Visual Studio

You can also export template and then create a new project from the exported template changing the name as you prefer

Use jquery to set value of div tag

if your value is a pure text (like 'test') you could use the text() method as well. like this:

$('div.total-title').text('test');

anyway, about the problem you are sharing, I think you might be calling the JavaScript code before the HTML code for the DIV is being sent to the browser. make sure you are calling the jQuery line in a <script> tag after the <div>, or in a statement like this:

$(document).ready(
    function() {
        $('div.total-title').text('test');
    }
);

this way the script executes after the HTML of the div is parsed by the browser.

PHP JSON String, escape Double Quotes for JS output

This is a solutions that takes care of single and double quotes:

<?php
$php_data = array("title"=>"Example string's with \"special\" characters");

$escaped_data = json_encode( $php_data, JSON_HEX_QUOT|JSON_HEX_APOS );
$escaped_data = str_replace("\u0022", "\\\"", $escaped_data );
$escaped_data = str_replace("\u0027", "\\'",  $escaped_data );
?>
<script>
// no need to use JSON.parse()...
var js_data = <?= $escaped_data ?>;
alert(js_data.title); // should alert `Example string's with "special" characters`
</script>

Testing if a checkbox is checked with jQuery

There are Several options are there like....

 1. $("#ans").is(':checked') 
 2. $("#ans:checked")
 3. $('input:checkbox:checked'); 

If all these option return true then you can set value accourdingly.

Change first commit of project with Git?

As mentioned by ecdpalma below, git 1.7.12+ (August 2012) has enhanced the option --root for git rebase:

"git rebase [-i] --root $tip" can now be used to rewrite all the history leading to "$tip" down to the root commit.

That new behavior was initially discussed here:

I personally think "git rebase -i --root" should be made to just work without requiring "--onto" and let you "edit" even the first one in the history.
It is understandable that nobody bothered, as people are a lot less often rewriting near the very beginning of the history than otherwise.

The patch followed.


(original answer, February 2010)

As mentioned in the Git FAQ (and this SO question), the idea is:

  1. Create new temporary branch
  2. Rewind it to the commit you want to change using git reset --hard
  3. Change that commit (it would be top of current HEAD, and you can modify the content of any file)
  4. Rebase branch on top of changed commit, using:

    git rebase --onto <tmp branch> <commit after changed> <branch>`
    

The trick is to be sure the information you want to remove is not reintroduced by a later commit somewhere else in your file. If you suspect that, then you have to use filter-branch --tree-filter to make sure the content of that file does not contain in any commit the sensible information.

In both cases, you end up rewriting the SHA1 of every commit, so be careful if you have already published the branch you are modifying the contents of. You probably shouldn’t do it unless your project isn’t yet public and other people haven’t based work off the commits you’re about to rewrite.

How change default SVN username and password to commit changes?

To use alternate credentials for a single operation, use the --username and --password switches for svn.

To clear previously-saved credentials, delete ~/.subversion/auth. You'll be prompted for credentials the next time they're needed.

These settings are saved in the user's home directory, so if you're using a shared account on "this laptop", be careful - if you allow the client to save your credentials, someone can impersonate you. The first option I provided is the better way to go in this case. At least until you stop using shared accounts on computers, which you shouldn't be doing.

To change credentials you need to do:

  • rm -rf ~/.subversion/auth
  • svn up ( it'll ask you for new username & password )

Assign variable in if condition statement, good practice or not?

I would consider this more of an old-school C style; it is not really good practice in JavaScript so you should avoid it.

Python Decimals format

Only first part of Justin's answer is correct. Using "%.3g" will not work for all cases as .3 is not the precision, but total number of digits. Try it for numbers like 1000.123 and it breaks.

So, I would use what Justin is suggesting:

>>> ('%.4f' % 12340.123456).rstrip('0').rstrip('.')
'12340.1235'
>>> ('%.4f' % -400).rstrip('0').rstrip('.')
'-400'
>>> ('%.4f' % 0).rstrip('0').rstrip('.')
'0'
>>> ('%.4f' % .1).rstrip('0').rstrip('.')
'0.1'

Are static methods inherited in Java?

If that's what the book really says, it's wrong.[1]

The Java Language Specification #8.4.8 states:

8.4.8 Inheritance, Overriding, and Hiding

A class C inherits from its direct superclass all concrete methods m (both static and instance) of the superclass for which all of the following are true:

  • m is a member of the direct superclass of C.

  • m is public, protected, or declared with package access in the same package as C.

  • No method declared in C has a signature that is a subsignature (§8.4.2) of the signature of m.

[1] It doesn't say that in my copy, 1st edition, 2000.

HTML form with side by side input fields

You should put the input for the last name into the same div where you have the first name.

<div>
    <label for="username">First Name</label>
    <input id="user_first_name" name="user[first_name]" size="30" type="text" />
    <input id="user_last_name" name="user[last_name]" size="30" type="text" />
</div>

Then, in your CSS give your #user_first_name and #user_last_name height and float them both to the left. For example:

#user_first_name{
    max-width:100px; /*max-width for responsiveness*/
    float:left;
}

#user_lastname_name{
    max-width:100px;
    float:left;
}

Put quotes around a variable string in JavaScript

var text = "http://example.com";

text = "'"+text+"'";

Would attach the single quotes (') to the front and the back of the string.

Get all inherited classes of an abstract class

Assuming they are all defined in the same assembly, you can do:

IEnumerable<AbstractDataExport> exporters = typeof(AbstractDataExport)
    .Assembly.GetTypes()
    .Where(t => t.IsSubclassOf(typeof(AbstractDataExport)) && !t.IsAbstract)
    .Select(t => (AbstractDataExport)Activator.CreateInstance(t));

How to remove all CSS classes using jQuery/JavaScript?

$("#item").removeClass();

Calling removeClass with no parameters will remove all of the item's classes.


You can also use (but is not necessarily recommended, the correct way is the one above):

$("#item").removeAttr('class');
$("#item").attr('class', '');
$('#item')[0].className = '';

If you didn't have jQuery, then this would be pretty much your only option:

document.getElementById('item').className = '';

How can I find whitespace in a String?

public static void main(String[] args) {
    System.out.println("test word".contains(" "));
}

How to find rows in one table that have no corresponding row in another table

I can't tell you which of these methods will be best on H2 (or even if all of them will work), but I did write an article detailing all of the (good) methods available in TSQL. You can give them a shot and see if any of them works for you:

http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=QueryBasedUponAbsenceOfData&referringTitle=Home

Python: most idiomatic way to convert None to empty string?

Variation on the above if you need to be compatible with Python 2.4

xstr = lambda s: s is not None and s or ''

Can't fix Unsupported major.minor version 52.0 even after fixing compatibility

Several possiblies that causes this problem. The root cause is mismatched of compiler version between projects and IDE. For windows environment you can refer to this blog to do the detail troubleshooting.

installing requests module in python 2.7 windows

There are four options here:

  1. Get virtualenv set up. Each virtual environment you create will automatically have pip.

  2. Get pip set up globally.

  3. Learn how to install Python packages manually—in most cases it's as simple as download, unzip, python setup.py install, but not always.

  4. Use Christoph Gohlke's binary installers.

Redirecting Output from within Batch file

echo some output >"your logfile"

or

(
 echo some output
 echo more output
)>"Your logfile"

should fill the bill.

If you want to APPEND the output, use >> instead of >. > will start a new logfile.

Simple and fast method to compare images for similarity

If for matching identical images - code for L2 distance

// Compare two images by getting the L2 error (square-root of sum of squared error).
double getSimilarity( const Mat A, const Mat B ) {
if ( A.rows > 0 && A.rows == B.rows && A.cols > 0 && A.cols == B.cols ) {
    // Calculate the L2 relative error between images.
    double errorL2 = norm( A, B, CV_L2 );
    // Convert to a reasonable scale, since L2 error is summed across all pixels of the image.
    double similarity = errorL2 / (double)( A.rows * A.cols );
    return similarity;
}
else {
    //Images have a different size
    return 100000000.0;  // Return a bad value
}

Fast. But not robust to changes in lighting/viewpoint etc. Source

Convert all first letter to upper case, rest lower for each word

There's a couple of ways to go about converting the first char of a string to upper case.

The first way is to create a method that simply caps the first char and appends the rest of the string using a substring:

public string UppercaseFirst(string s)
    {
        return char.ToUpper(s[0]) + s.Substring(1);
    }

The second way (which is slightly faster) is to split the string into a char array and then re-build the string:

public string UppercaseFirst(string s)
    {
        char[] a = s.ToCharArray();
        a[0] = char.ToUpper(a[0]);
        return new string(a);
    }

EOFException - how to handle?

Put your code inside the try catch block: i.e :

try{
  if(in.available()!=0){
    // ------
  }
}catch(EOFException eof){
  //
}catch(Exception e){
  //
}
}

how to calculate binary search complexity

Log2(n) is the maximum number of searches that are required to find something in a binary search. The average case involves log2(n)-1 searches. Here's more info:

http://en.wikipedia.org/wiki/Binary_search#Performance

Jackson and generic type reference

This is a well-known problem with Java type erasure: T is just a type variable, and you must indicate actual class, usually as Class argument. Without such information, best that can be done is to use bounds; and plain T is roughly same as 'T extends Object'. And Jackson will then bind JSON Objects as Maps.

In this case, tester method needs to have access to Class, and you can construct

JavaType type = mapper.getTypeFactory().
  constructCollectionType(List.class, Foo.class)

and then

List<Foo> list = mapper.readValue(new File("input.json"), type);

Cleanest way to build an SQL string in Java

I tend to use Spring's Named JDBC Parameters so I can write a standard string like "select * from blah where colX=':someValue'"; I think that's pretty readable.

An alternative would be to supply the string in a separate .sql file and read the contents in using a utility method.

Oh, also worth having a look at Squill: https://squill.dev.java.net/docs/tutorial.html

Java escape JSON String?

Consider Moshi's JsonWriter class (source). It has a wonderful API and it reduces copying to a minimum, everything is nicely streamed to the OutputStream.

OutputStream os = ...;
JsonWriter json = new JsonWriter(Okio.sink(os));
json
  .beginObject()
  .name("id").value(userID)
  .name("type").value(methodn)
  ...
  .endObject();

How to implement class constructor in Visual Basic?

A class with a field:

Public Class MyStudent
   Public StudentId As Integer

The constructor:

    Public Sub New(newStudentId As Integer)
        StudentId = newStudentId
    End Sub
End Class

Pycharm: run only part of my Python file

I found out an easier way.

  • go to File -> Settings -> Keymap
  • Search for Execute Selection in Console and reassign it to a new shortcut, like Crl + Enter.

This is the same shortcut to the same action in Spyder and R-Studio.

How do I run a command on an already existing Docker container?

Assuming the image is using the default entrypoint /bin/sh -c, running /bin/bash will exit immediately in daemon mode (-d). If you want this container to run an interactive shell, use -it instead of -d. If you want to execute arbitrary commands in a container usually executing another process, you might want to try nsenter or nsinit. Have a look at https://blog.codecentric.de/en/2014/07/enter-docker-container/ for the details.

How can I use the python HTMLParser library to extract data from a specific div tag?

Have You tried BeautifulSoup ?

from bs4 import BeautifulSoup
soup = BeautifulSoup('<div id="remository">20</div>')
tag=soup.div
print(tag.string)

This gives You 20 on output.

Can Powershell Run Commands in Parallel?

If you're using latest cross platform powershell (which you should btw) https://github.com/powershell/powershell#get-powershell, you can add single & to run parallel scripts. (Use ; to run sequentially)

In my case I needed to run 2 npm scripts in parallel: npm run hotReload & npm run dev


You can also setup npm to use powershell for its scripts (by default it uses cmd on windows).

Run from project root folder: npm config set script-shell pwsh --userconfig ./.npmrc and then use single npm script command: npm run start

"start":"npm run hotReload & npm run dev"

How to generate unique ID with node.js

used https://www.npmjs.com/package/uniqid in npm

npm i uniqid

It will always create unique id's based on the current time, process and machine name.

  • With the current time the ID's are always unique in a single process.
  • With the Process ID the ID's are unique even if called at the same time from multiple processes.
  • With the MAC Address the ID's are unique even if called at the same time from multiple machines and processes.

Features:-

  • Very fast
  • Generates unique id's on multiple processes and machines even if called at the same time.
  • Shorter 8 and 12 byte versions with less uniqueness.

Multiple line comment in Python

Try this

'''
This is a multiline
comment. I can type here whatever I want.
'''

Python does have a multiline string/comment syntax in the sense that unless used as docstrings, multiline strings generate no bytecode -- just like #-prepended comments. In effect, it acts exactly like a comment.

On the other hand, if you say this behavior must be documented in the official docs to be a true comment syntax, then yes, you would be right to say it is not guaranteed as part of the language specification.

In any case your editor should also be able to easily comment-out a selected region (by placing a # in front of each line individually). If not, switch to an editor that does.

Programming in Python without certain text editing features can be a painful experience. Finding the right editor (and knowing how to use it) can make a big difference in how the Python programming experience is perceived.

Not only should the editor be able to comment-out selected regions, it should also be able to shift blocks of code to the left and right easily, and should automatically place the cursor at the current indentation level when you press Enter. Code folding can also be useful.

How to append something to an array?

Let the array length property do the work:

myarray[myarray.length] = 'new element value added to the end of the array';

myarray.length returns the number of strings in the array. JS is zero based so the next element key of the array will be the current length of the array. EX:

var myarray = [0, 1, 2, 3],
    myarrayLength = myarray.length; //myarrayLength is set to 4

T-SQL string replace in Update

If anyone cares, for NTEXT, use the following format:

SELECT CAST(REPLACE(CAST([ColumnValue] AS NVARCHAR(MAX)),'find','replace') AS NTEXT) 
    FROM [DataTable]

How can I get the baseurl of site?

The popular GetLeftPart solution is not supported in the PCL version of Uri, unfortunately. GetComponents is, however, so if you need portability, this should do the trick:

uri.GetComponents(
    UriComponents.SchemeAndServer | UriComponents.UserInfo, UriFormat.Unescaped);

How to display HTML in TextView?

May I suggest a somewhat hacky but still genius solution! I got the idea from this article and adapted it for Android. Basically you use a WebView and insert the HTML you want to show and edit in an editable div tag. This way when the user taps the WebView the keyboard appears and allows editing. They you just add some JavaScript to get back the edited HTML and voila!

Here is the code:

public class HtmlTextEditor extends WebView {

    class JsObject {
        // This field always keeps the latest edited text
        public String text;
        @JavascriptInterface
        public void textDidChange(String newText) {
            text = newText.replace("\n", "");
        }
    }

    private JsObject mJsObject;

    public HtmlTextEditor(Context context, AttributeSet attrs) {
        super(context, attrs);

        getSettings().setJavaScriptEnabled(true);
        mJsObject = new JsObject();
        addJavascriptInterface(mJsObject, "injectedObject");
        setWebViewClient(new WebViewClient(){
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                loadUrl(
                        "javascript:(function() { " +
                            "    var editor = document.getElementById(\"editor\");" +
                            "    editor.addEventListener(\"input\", function() {" +
                            "        injectedObject.textDidChange(editor.innerHTML);" +
                            "    }, false)" +
                            "})()");
            }
        });
    }

    public void setText(String text) {
        if (text == null) { text = ""; }

        String editableHtmlTemplate = "<!DOCTYPE html>" + "<html>" + "<head>" + "<meta name=\"viewport\" content=\"initial-scale=1.0\" />" + "</head>" + "<body>" + "<div id=\"editor\" contenteditable=\"true\">___REPLACE___</div>" + "</body>" + "</html>";
        String editableHtml = editableHtmlTemplate.replace("___REPLACE___", text);
        loadData(editableHtml, "text/html; charset=utf-8", "UTF-8");
        // Init the text field in case it's read without editing the text before
        mJsObject.text = text;
    }

    public String getText() {
        return mJsObject.text;
    }
}

And here is the component as a Gist.

Note: I didn't need the height change callback from the original solution so that's missing here but you can easily add it if needed.

Refused to load the script because it violates the following Content Security Policy directive

We used this:

<meta http-equiv="Content-Security-Policy" content="default-src gap://ready file://* *; style-src 'self' http://* https://* 'unsafe-inline'; script-src 'self' http://* https://* 'unsafe-inline' 'unsafe-eval'">

Regular expression for address field validation

I have succesfully used ;

Dim regexString = New stringbuilder
    With regexString
       .Append("(?<h>^[\d]+[ ])(?<s>.+$)|")                'find the 2013 1st ambonstreet 
       .Append("(?<s>^.*?)(?<h>[ ][\d]+[ ])(?<e>[\D]+$)|") 'find the 1-7-4 Dual Ampstreet 130 A
       .Append("(?<s>^[\D]+[ ])(?<h>[\d]+)(?<e>.*?$)|")    'find the Terheydenlaan 320 B3 
       .Append("(?<s>^.*?)(?<h>\d*?$)")                    'find the 245e oosterkade 9
    End With

    Dim Address As Match = Regex.Match(DataRow("customerAddressLine1"), regexString.ToString(), RegexOptions.Multiline)

    If Not String.IsNullOrEmpty(Address.Groups("s").Value) Then StreetName = Address.Groups("s").Value
    If Not String.IsNullOrEmpty(Address.Groups("h").Value) Then HouseNumber = Address.Groups("h").Value
    If Not String.IsNullOrEmpty(Address.Groups("e").Value) Then Extension = Address.Groups("e").Value

The regex will attempt to find a result, if there is none, it move to the next alternative. If no result is found, none of the 4 formats where present.

how to make negative numbers into positive

abs() is for integers only. For floating point, use fabs() (or one of the fabs() line with the correct precision for whatever a actually is)

Pass by Reference / Value in C++

Thanks so much everyone for all these input!

I quoted that sentence from a lecture note online: http://www.cs.cornell.edu/courses/cs213/2002fa/lectures/Lecture02/Lecture02.pdf

the first page the 6th slide

" Pass by VALUE The value of a variable is passed along to the function If the function modifies that value, the modifications stay within the scope of that function.

Pass by REFERENCE A reference to the variable is passed along to the function If the function modifies that value, the modifications appear also within the scope of the calling function.

"

Thanks so much again!

Tests not running in Test Explorer

Well i know i am late to the party, but logging my answer here , incase, someone is facing similar issue as mine. I have faced this issue many times. 90% it gets solved by these two steps

project > properties > Build > Platform target > x64 (x32)

Test -> Test Settings > Default Processor Architecture > X64 (x32)

However i found one more common cause. The Solution files often change developer systems and they start pointing to wrong MSTest.TestAdapter. Especially if you are using custom path of nuget packages. I solved this issue by

  1. Opening the .csproj file in notepad.

  2. Manually correcting reference to MSTest.TestAdapter in import instructions like this.

How to use WPF Background Worker

  1. Add using
using System.ComponentModel;
  1. Declare Background Worker:
private readonly BackgroundWorker worker = new BackgroundWorker();
  1. Subscribe to events:
worker.DoWork += worker_DoWork;
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
  1. Implement two methods:
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
  // run all background tasks here
}

private void worker_RunWorkerCompleted(object sender, 
                                           RunWorkerCompletedEventArgs e)
{
  //update ui once worker complete his work
}
  1. Run worker async whenever your need.
worker.RunWorkerAsync();
  1. Track progress (optional, but often useful)

    a) subscribe to ProgressChanged event and use ReportProgress(Int32) in DoWork

    b) set worker.WorkerReportsProgress = true; (credits to @zagy)