Programs & Examples On #Qcubed

QCubed is a PHP framework for rapid web development. Building on top of jQuery, with OOP at its core, QCubed provides a powerful solution for building database-driven Web 2.0 applications.

Run react-native on android emulator

It happened to me that I had an instance of the packager running with an old project (I ran react-native start as usual). I was using Ubuntu 14.04. So what I did was to stop that instance and go to my project folder and in two different console tabs I ran these two commands separately:

npm start #here I used to run react-native start
react-native run-android

npm start is defined in my package.json as:

"start": "node_modules/react-native/packager/packager.sh"

I don't know if there is a sort of confusing stuff for react-native but that did the trick.

How to show/hide JPanels in a JFrame?

Call parent.remove(panel), where parent is the container that you want the frame in and panel is the panel you want to add.

In Unix, how do you remove everything in the current directory and below it?

This simplest safe & general solution is probably:

find -mindepth 1 -maxdepth 1 -print0 | xargs -0 rm -rf

How can I find out a file's MIME type (Content-Type)?

Try the file command with -i option.

-i option Causes the file command to output mime type strings rather than the more traditional human readable ones. Thus it may say text/plain; charset=us-ascii rather than ASCII text.

/usr/bin/codesign failed with exit code 1

I had the exact same error, and tried everything under the sun, including what was elsewhere on this page, with no success. What the problem was for me was that in Keychain Access, the actual Apple WWDR certificate was marked as "Always Trust". It needed to be "System Defaults". That goes for your Development and Distribution certificates, too. If any of them are incorrectly set to "Always Trust", that can apparently cause this problem.

So, in Keychain Access, click on the Apple Worldwide Developer Relations Certificate Authority certificate, select Get Info. Then, expand the Trust settings, and for the combo box for "When using this certificate:", choose "System Defaults".

Others have commented that you may have to do this in System and login keychains for these errors.

What is the boundary in multipart/form-data?

Is the ??? free to be defined by the user?

Yes.

or is it supplied by the HTML?

No. HTML has nothing to do with that. Read below.

Is it possible for me to define the ??? as abcdefg?

Yes.

If you want to send the following data to the web server:

name = John
age = 12

using application/x-www-form-urlencoded would be like this:

name=John&age=12

As you can see, the server knows that parameters are separated by an ampersand &. If & is required for a parameter value then it must be encoded.

So how does the server know where a parameter value starts and ends when it receives an HTTP request using multipart/form-data?

Using the boundary, similar to &.

For example:

--XXX
Content-Disposition: form-data; name="name"

John
--XXX
Content-Disposition: form-data; name="age"

12
--XXX--

In that case, the boundary value is XXX. You specify it in the Content-Type header so that the server knows how to split the data it receives.

So you need to:

  • Use a value that won't appear in the HTTP data sent to the server.

  • Be consistent and use the same value everywhere in the request message.

What is char ** in C?

It is a pointer to a pointer, so yes, in a way it's a 2D character array. In the same way that a char* could indicate an array of chars, a char** could indicate that it points to and array of char*s.

Sql Server string to date conversion

For this problem the best solution I use is to have a CLR function in Sql Server 2005 that uses one of DateTime.Parse or ParseExact function to return the DateTime value with a specified format.

Styling the arrow on bootstrap tooltips

I have created fiddle for you.

Take a look at here

<p>
    <a class="tooltip" href="#">Tooltip
        <span>
            <img alt="CSS Tooltip callout"
                 src="http://www.menucool.com/tooltip/src/callout.gif" class="callout">
            <strong>Most Light-weight Tooltip</strong><br>
            This is the easy-to-use Tooltip driven purely by CSS.
        </span>
    </a>
</p>

 

a.tooltip {
    outline: none;
}

a.tooltip strong {
    line-height: 30px;
}

a.tooltip:hover {
    text-decoration: none;
}

a.tooltip span {
    z-index: 10;
    display: none;
    padding: 14px 20px;
    margin-top: -30px;
    margin-left: 28px;
    width: 240px;
    line-height: 16px;
}

a.tooltip:hover span {
    display: inline;
    position: absolute;
    color: #111;
    border: 1px solid #DCA;
    background: #fffAF0;
}

.callout {
    z-index: 20;
    position: absolute;
    top: 30px;
    border: 0;
    left: -12px;
}
/*CSS3 extras*/
a.tooltip span {
    border-radius: 4px;
    -moz-border-radius: 4px;
    -webkit-border-radius: 4px;
    -moz-box-shadow: 5px 5px 8px #CCC;
    -webkit-box-shadow: 5px 5px 8px #CCC;
    box-shadow: 5px 5px 8px #CCC;
}

HTML Table different number of columns in different rows

On the realisation that you're unfamiliar with colspan, I presumed you're also unfamiliar with rowspan, so I thought I'd throw that in for free.

One important point to note, when using rowspan: the following tr elements must contain fewer td elements, because of the cells using rowspan in the previous row (or previous rows).

_x000D_
_x000D_
table {_x000D_
  border: 1px solid #000;_x000D_
  border-collapse: collapse;_x000D_
}_x000D_
_x000D_
th,_x000D_
td {_x000D_
  border: 1px solid #000;_x000D_
}
_x000D_
<table>_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th colspan="2">Column one and two</th>_x000D_
      <th>Column three</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td rowspan="2" colspan="2">A large cell</td>_x000D_
      <td>a smaller cell</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <!-- note that this row only has _one_ td, since the preceding row_x000D_
                     takes up some of this row -->_x000D_
      <td>Another small cell</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

python socket.error: [Errno 98] Address already in use

There is obviously another process listening on the port. You might find out that process by using the following command:

$ lsof -i :8000

or change your tornado app's port. tornado's error info not Explicitly on this.

A failure occurred while executing com.android.build.gradle.internal.tasks

Clean Project -> Invalidate caches/restart. My problem resolved with this.

XMLHttpRequest Origin null is not allowed Access-Control-Allow-Origin for file:/// to file:/// (Serverless)

You can try putting 'Access-Control-Allow-Origin':'*' in response.writeHead(, {[here]}).

Button background as transparent

You can do it easily by adding below attribute in xml file. This code was tested plenty of time.

android:background="@android:color/transparent"

COLLATION 'utf8_general_ci' is not valid for CHARACTER SET 'latin1'

Firstly run this query

SHOW VARIABLES LIKE '%char%';

You have character_set_server='latin1'

If so,go into your config file,my.cnf and add or uncomment these lines:

character-set-server = utf8
collation-server = utf8_unicode_ci

Restart the server. Yes late to the party,just encountered the same issue.

How do I fit an image (img) inside a div and keep the aspect ratio?

I was having a lot of problems to get this working, every single solution I found didn't seem to work.

I realized that I had to set the div display to flex, so basically this is my CSS:

div{
display: flex;
}

div img{ 
max-height: 100%;
max-width: 100%;
}

Attempted to read or write protected memory. This is often an indication that other memory is corrupt

i had this problem too . i was running different solutions at the same time using visual studio , when closing other solutions and running just the target solution , it worked fine without that error .

VSCode Change Default Terminal

I just type following keywords in the opened terminal;

  1. powershell
  2. bash
  3. cmd
  4. node
  5. python (or python3)

See details in the below image. (VSCode version 1.19.1 - windows 10 OS) enter image description here

It works on VS Code Mac as well. I tried it with VSCode (Version 1.20.1)

Convert string to int if string is a number

Just use Val():

currentLoad = Int(Val([f4]))

Now currentLoad has a integer value, zero if [f4] is not numeric.

MySQL Select Multiple VALUES

Try this -

 select * from table where id in (3,4) or [name] in ('andy','paul');

How do I find all files containing specific text on Linux?

Use:

grep -Erni + "text you wanna search"

The command will search recursively in all files and directories of the current directory and print the result.

Note: if your grep output isn't colored, you can change it by using the grep='grep --color=always' alias in your shell source file.

Return from a promise then()

You cannot return value after resolving promise. Instead call another function when promise is resolved:

function justTesting() {
    promise.then(function(output) {
        // instead of return call another function
        afterResolve(output + 1);
    });
}

function afterResolve(result) {
    // do something with result
}

var test = justTesting();

Automatically add all files in a folder to a target using CMake?

Extension for @Kleist answer:

Since CMake 3.12 additional option CONFIGURE_DEPENDS is supported by commands file(GLOB) and file(GLOB_RECURSE). With this option there is no needs to manually re-run CMake after addition/deletion of a source file in the directory - CMake will be re-run automatically on next building the project.

However, the option CONFIGURE_DEPENDS implies that corresponding directory will be re-checked every time building is requested, so build process would consume more time than without CONFIGURE_DEPENDS.

Even with CONFIGURE_DEPENDS option available CMake documentation still does not recommend using file(GLOB) or file(GLOB_RECURSE) for collect the sources.

Creating NSData from NSString in Swift

To create not optional data I recommend using it:

let key = "1234567"
let keyData = Data(key.utf8)

java.util.zip.ZipException: duplicate entry during packageAllDebugClassesForMultiDex

I have faced this issue as i have manually copied the jar in libs as well as mentioned the dependency in gradle file. You also check in your project structure, whether the same jar file is copied in any other folder like libs or in project folder.

Make Bootstrap Popover Appear/Disappear on Hover instead of Click

The functionality, you described, can be easily achieved using the Bootstrap tooltip.

<button id="example1" data-toggle="tooltip">Tooltip on left</button>

Then call tooltip() function for the element.

$('#example1').tooltip();

http://getbootstrap.com/javascript/#tooltips

Get Hours and Minutes (HH:MM) from date

Just use the first 5 characters...?

 SELECT CONVERT(VARCHAR(5),getdate(),108) 

Print a string as hex bytes?

Print a string as hex bytes?

The accepted answer gives:

s = "Hello world !!"
":".join("{:02x}".format(ord(c)) for c in s)

returns:

'48:65:6c:6c:6f:20:77:6f:72:6c:64:20:21:21'

The accepted answer works only so long as you use bytes (mostly ascii characters). But if you use unicode, e.g.:

a_string = u"?????? ???!!" # "Prevyet mir", or "Hello World" in Russian.

You need to convert to bytes somehow.

If your terminal doesn't accept these characters, you can decode from UTF-8 or use the names (so you can paste and run the code along with me):

a_string = (
    "\N{CYRILLIC CAPITAL LETTER PE}"
    "\N{CYRILLIC SMALL LETTER ER}"
    "\N{CYRILLIC SMALL LETTER I}"
    "\N{CYRILLIC SMALL LETTER VE}"
    "\N{CYRILLIC SMALL LETTER IE}"
    "\N{CYRILLIC SMALL LETTER TE}"
    "\N{SPACE}"
    "\N{CYRILLIC SMALL LETTER EM}"
    "\N{CYRILLIC SMALL LETTER I}"
    "\N{CYRILLIC SMALL LETTER ER}"
    "\N{EXCLAMATION MARK}"
    "\N{EXCLAMATION MARK}"
)

So we see that:

":".join("{:02x}".format(ord(c)) for c in a_string)

returns

'41f:440:438:432:435:442:20:43c:438:440:21:21'

a poor/unexpected result - these are the code points that combine to make the graphemes we see in Unicode, from the Unicode Consortium - representing languages all over the world. This is not how we actually store this information so it can be interpreted by other sources, though.

To allow another source to use this data, we would usually need to convert to UTF-8 encoding, for example, to save this string in bytes to disk or to publish to html. So we need that encoding to convert the code points to the code units of UTF-8 - in Python 3, ord is not needed because bytes are iterables of integers:

>>> ":".join("{:02x}".format(c) for c in a_string.encode('utf-8'))
'd0:9f:d1:80:d0:b8:d0:b2:d0:b5:d1:82:20:d0:bc:d0:b8:d1:80:21:21'

Or perhaps more elegantly, using the new f-strings (only available in Python 3):

>>> ":".join(f'{c:02x}' for c in a_string.encode('utf-8'))
'd0:9f:d1:80:d0:b8:d0:b2:d0:b5:d1:82:20:d0:bc:d0:b8:d1:80:21:21'

In Python 2, pass c to ord first, i.e. ord(c) - more examples:

>>> ":".join("{:02x}".format(ord(c)) for c in a_string.encode('utf-8'))
'd0:9f:d1:80:d0:b8:d0:b2:d0:b5:d1:82:20:d0:bc:d0:b8:d1:80:21:21'
>>> ":".join(format(ord(c), '02x') for c in a_string.encode('utf-8'))
'd0:9f:d1:80:d0:b8:d0:b2:d0:b5:d1:82:20:d0:bc:d0:b8:d1:80:21:21'

Print Html template in Angular 2 (ng-print in Angular 2)

Print service

import { Injectable } from '@angular/core';

@Injectable()
export class PrintingService {

public print(printEl: HTMLElement) {
    let printContainer: HTMLElement = document.querySelector('#print-container');

    if (!printContainer) {
      printContainer = document.createElement('div');
      printContainer.id = 'print-container';
    } 

    printContainer.innerHTML = '';

    let elementCopy = printEl.cloneNode(true);
    printContainer.appendChild(elementCopy);
    document.body.appendChild(printContainer);

    window.print();
  }
}

?omponent that I want to print

@Component({
  selector: 'app-component',
  templateUrl: './component.component.html',
  styleUrls: ['./component.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class MyComponent {
  @ViewChild('printEl') printEl: ElementRef;

  constructor(private printingService: PrintingService) {}

  public print(): void {
    this.printingService.print(this.printEl.nativeElement);
 }

}

Not the best choice, but works.

Reorder / reset auto increment primary key

My opinion is to create a new column called row_order. then reorder that column. I'm not accepting the changes to the primary key. As an example, if the order column is banner_position, I have done something like this, This is for deleting, updating, creating of banner position column. Call this function reorder them respectively.

public function updatePositions(){
    $offers = Offer::select('banner_position')->orderBy('banner_position')->get();
    $offersCount = Offer::max('banner_position');
    $range = range(1, $offersCount);

    $existingBannerPositions = [];
    foreach($offers as $offer){
        $existingBannerPositions[] = $offer->banner_position;
    }
    sort($existingBannerPositions);
    foreach($existingBannerPositions as $key => $position){
        $numbersLessThanPosition = range(1,$position);
        $freshNumbersLessThanPosition = array_diff($numbersLessThanPosition, $existingBannerPositions);
        if(count($freshNumbersLessThanPosition)>0) {
            $existingBannerPositions[$key] = current($freshNumbersLessThanPosition);
            Offer::where('banner_position',$position)->update(array('banner_position'=> current($freshNumbersLessThanPosition)));
        }
    }
}

Custom Date/Time formatting in SQL Server

I'm adding this answer (for myself) as relevant to custom formatting.

For underscore yyyy_MM_dd

REPLACE(SUBSTRING(CONVERT(VARCHAR, @dt, 120), 1, 10),'-','_')

How to correct indentation in IntelliJ

Just select the code and

  • on Windows do Ctrl + Alt + L

  • on Linux do Ctrl + Windows Key + Alt + L

  • on Mac do CMD + Option + L

get launchable activity name of package from adb

$ adb shell pm dump PACKAGE_NAME | grep -A 1 MAIN

How to replace all dots in a string using JavaScript

String.prototype.replaceAll = function(character,replaceChar){
    var word = this.valueOf();

    while(word.indexOf(character) != -1)
        word = word.replace(character,replaceChar);

    return word;
}

How to use: while not in

anding strings does not do what you think it does - use any to check if any of the strings are in the list:

while not any(word in list_of_words for word in ['AND', 'OR', 'NOT']):
    print 'No boolean'

Also, if you want a simple check, an if might be better suited than a while...

Failed to build gem native extension — Rails install

mkmf is part of the ruby1.9.1-dev package. This package contains the header files needed for extension libraries for Ruby 1.9.1. You need to install the ruby1.9.1-dev package by doing:

sudo apt-get install ruby1.9.1-dev

Then you can install Rails as per normal.

Generally it's easier to just do:

sudo apt-get install ruby-dev

/bin/sh: apt-get: not found

The image you're using is Alpine based, so you can't use apt-get because it's Ubuntu's package manager.

To fix this just use:

apk update and apk add

How to set cellpadding and cellspacing in table with CSS?

Use padding on the cells and border-spacing on the table. The former will give you cellpadding while the latter will give you cellspacing.

table { border-spacing: 5px; } /* cellspacing */

th, td { padding: 5px; } /* cellpadding */

jsFiddle Demo

Unable to Build using MAVEN with ERROR - Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile

Your Maven is reading Java version as 1.6.0_65, Where as the pom.xml says the version is 1.7.

Try installing the required verison.

If already installed check your $JAVA_HOME environment variable, it should contain the path of Java JDK 7. If you dont find it, fix your environment variable.

also remove the lines

 <fork>true</fork>
     <executable>${JAVA_1_7_HOME}/bin/javac</executable>

from the pom.xml

How to only find files in a given directory, and ignore subdirectories using bash

If you just want to limit the find to the first level you can do:

 find /dev -maxdepth 1 -name 'abc-*'

... or if you particularly want to exclude the .udev directory, you can do:

 find /dev -name '.udev' -prune -o -name 'abc-*' -print

Open a URL without using a browser from a batch file

If all you want is to request the URL and if it needs to be done from batch file, without anything outside of the OS, this can help you:

@if (@This==@IsBatch) @then
@echo off
rem **** batch zone *********************************************************

    setlocal enableextensions disabledelayedexpansion

    rem The batch file will delegate all the work to the script engine
    if not "%~1"=="" (
        wscript //E:JScript "%~dpnx0" %1
    )

    rem End of batch file area. Ensure the batch file ends execution
    rem before reaching the JavaScript zone
    exit /b

@end


// **** JavaScript zone *****************************************************
// Instantiate the needed component to make URL queries
var http = WScript.CreateObject('Msxml2.XMLHTTP.6.0');

// Retrieve the URL parameter
var url = WScript.Arguments.Item(0)

// Make the request

http.open("GET", url, false);
http.send();

// All done. Exit
WScript.Quit(0);

It is just a hybrid batch/JavaScript file and is saved as callurl.cmd and called as callurl "http://www.google.es". It will do what you ask for. No error check, no post, just a skeleton.

If it is possible to use something outside of the OS, wget or curl are available as Windows executables and are the best options available.

If you are limited by some kind of security policy, you can get the Internet Information Services (IIS) 6.0 Resource Kit Tools. It includes tinyget and wfetch tools that can do what you need.

How to downgrade Java from 9 to 8 on a MACOS. Eclipse is not running with Java 9

You don't need to down grade. You can run more than one version of Java on MacOS. You can set the version of your terminal with this command in MacOS.

# List Java versions installed
/usr/libexec/java_home -V

# Java 11
export JAVA_HOME=$(/usr/libexec/java_home -v 11)

# Java 1.8
export JAVA_HOME=$(/usr/libexec/java_home -v 1.8)

# Java 1.7
export JAVA_HOME=$(/usr/libexec/java_home -v 1.7)

# Java 1.6
export JAVA_HOME=$(/usr/libexec/java_home -v 1.6)

You can set the default value in the .bashrc, .profile, or .zprofile

Detect Route Change with react-router

import React from 'react';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import Sidebar from './Sidebar';
import Chat from './Chat';

<Router>
    <Sidebar />
        <Switch>
            <Route path="/rooms/:roomId" component={Chat}>
            </Route>
        </Switch>
</Router>

import { useHistory } from 'react-router-dom';
function SidebarChat(props) {
    **const history = useHistory();**
    var openChat = function (id) {
        **//To navigate**
        history.push("/rooms/" + id);
    }
}

**//To Detect the navigation change or param change**
import { useParams } from 'react-router-dom';
function Chat(props) {
    var { roomId } = useParams();
    var roomId = props.match.params.roomId;

    useEffect(() => {
       //Detect the paramter change
    }, [roomId])

    useEffect(() => {
       //Detect the location/url change
    }, [location])
}

How to fix curl: (60) SSL certificate: Invalid certificate chain

Another cause of this can be duplicate keys in your KeyChain. I've seen this problem on two macs where there were duplicate "DigiCert High Assurance EV Root CA". One was in the login keychain, the other in the system one. Removing the certificate from the login keychain solved the problem.

This affected Safari browser as well as git on the command line.

How to embed image or picture in jupyter notebook, either from a local machine or from a web resource?

If you want to use the Jupyter Notebook API (and not the IPython one anymore), I find the ipywidgets Jupyter's sub-project. You have an Image widget. Docstring specifies that you have a value parameter which is a bytes. So you can do:

import requests
from ipywidgets import Image

Image(value=requests.get('https://octodex.github.com/images/yaktocat.png').content)

I agree, it's simpler to use the Markdown style. But it shows you the Image display Notebook API. You can also resize the image with the width and height parameters.

Mean Squared Error in Numpy?

Just for kicks

mse = (np.linalg.norm(A-B)**2)/len(A)

finding the type of an element using jQuery

You can use .prop() with tagName as the name of the property that you want to get:

$("#elementId").prop('tagName'); 

laravel throwing MethodNotAllowedHttpException

The problem is the you are using POST but actually you have to perform PATCH To fix this add

<input name="_method" type="hidden" value="PATCH">

Just after the Form::model line

Why is my locally-created script not allowed to run under the RemoteSigned execution policy?

I finally tracked this down to .NET Code Access Security. I have some internally-developed binary modules that are stored on and executed from a network share. To get .NET 2.0/PowerShell 2.0 to load them, I had added a URL rule to the Intranet code group to trust that directory:

PS> & "$Env:SystemRoot\Microsoft.NET\Framework64\v2.0.50727\caspol.exe" -machine -listgroups
Microsoft (R) .NET Framework CasPol 2.0.50727.5420
Copyright (c) Microsoft Corporation.  All rights reserved.

Security is ON
Execution checking is ON
Policy change prompt is ON

Level = Machine

Code Groups:

1.  All code: Nothing
    1.1.  Zone - MyComputer: FullTrust
        1.1.1.  StrongName - ...: FullTrust
        1.1.2.  StrongName - ...: FullTrust
    1.2.  Zone - Intranet: LocalIntranet
        1.2.1.  All code: Same site Web
        1.2.2.  All code: Same directory FileIO - 'Read, PathDiscovery'
        1.2.3.  Url - file://Server/Share/Directory/WindowsPowerShell/Modules/*: FullTrust
    1.3.  Zone - Internet: Internet
        1.3.1.  All code: Same site Web
    1.4.  Zone - Untrusted: Nothing
    1.5.  Zone - Trusted: Internet
        1.5.1.  All code: Same site Web

Note that, depending on which versions of .NET are installed and whether it's 32- or 64-bit Windows, caspol.exe can exist in the following locations, each with their own security configuration (security.config):

  • $Env:SystemRoot\Microsoft.NET\Framework\v2.0.50727\
  • $Env:SystemRoot\Microsoft.NET\Framework64\v2.0.50727\
  • $Env:SystemRoot\Microsoft.NET\Framework\v4.0.30319\
  • $Env:SystemRoot\Microsoft.NET\Framework64\v4.0.30319\

After deleting group 1.2.3....

PS> & "$Env:SystemRoot\Microsoft.NET\Framework64\v2.0.50727\caspol.exe" -machine -remgroup 1.2.3.
Microsoft (R) .NET Framework CasPol 2.0.50727.9136
Copyright (c) Microsoft Corporation.  All rights reserved.

The operation you are performing will alter security policy.
Are you sure you want to perform this operation? (yes/no)
yes
Removed code group from the Machine level.
Success

...I am left with the default CAS configuration and local scripts now work again. It's been a while since I've tinkered with CAS, and I'm not sure why my rule would seem to interfere with those granting FullTrust to MyComputer, but since CAS is deprecated as of .NET 4.0 (on which PowerShell 3.0 is based), I guess it's a moot point now.

How to search images from private 1.0 registry in docker?

Currently there's no search support for Docker Registry v2.

There was a long-running thread on the topic. The current plan is to support search with an extension in the end, which should be ready by v2.1.

As a workaround, execute the following on the machine where your registry v2 is running:

> docker exec -it <your_registry_container_id> bash
> ls /var/lib/registry/docker/registry/v2/repositories/

The images are in subdirectories corresponding to their namespace, e.g. jwilder/nginx-proxy

Display string as html in asp.net mvc view

You are close you want to use @Html.Raw(str)

@Html.Encode takes strings and ensures that all the special characters are handled properly. These include characters like spaces.

In Java, should I escape a single quotation mark (') in String (double quoted)?

You don't need to escape the ' character in a String (wrapped in "), and you don't have to escape a " character in a char (wrapped in ').

Javascript date.getYear() returns 111 in 2011?

In order to comply with boneheaded precedent, getYear() returns the number of years since 1900.

Instead, you should call getFullYear(), which returns the actual year.

How to build an android library with Android Studio and gradle?

Note: This answer is a pure Gradle answer, I use this in IntelliJ on a regular basis but I don't know how the integration is with Android Studio. I am a believer in knowing what is going on for me, so this is how I use Gradle and Android.

TL;DR Full Example - https://github.com/ethankhall/driving-time-tracker/

Disclaimer: This is a project I am/was working on.

Gradle has a defined structure ( that you can change, link at the bottom tells you how ) that is very similar to Maven if you have ever used it.

Project Root
+-- src
|   +-- main (your project)
|   |   +-- java (where your java code goes)
|   |   +-- res  (where your res go)
|   |   +-- assets (where your assets go)
|   |   \-- AndroidManifest.xml
|   \-- instrumentTest (test project)
|       \-- java (where your java code goes)
+-- build.gradle
\-- settings.gradle

If you only have the one project, the settings.gradle file isn't needed. However you want to add more projects, so we need it.

Now let's take a peek at that build.gradle file. You are going to need this in it (to add the android tools)

build.gradle

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.3'
    }
}

Now we need to tell Gradle about some of the Android parts. It's pretty simple. A basic one (that works in most of my cases) looks like the following. I have a comment in this block, it will allow me to specify the version name and code when generating the APK.

build.gradle

apply plugin: "android"
android {
        compileSdkVersion 17
        /*
        defaultConfig {
            versionCode = 1
            versionName = "0.0.0"
        }
        */
    }

Something we are going to want to add, to help out anyone that hasn't seen the light of Gradle yet, a way for them to use the project without installing it.

build.gradle

task wrapper(type: org.gradle.api.tasks.wrapper.Wrapper) {
    gradleVersion = '1.4'
}

So now we have one project to build. Now we are going to add the others. I put them in a directory, maybe call it deps, or subProjects. It doesn't really matter, but you will need to know where you put it. To tell Gradle where the projects are you are going to need to add them to the settings.gradle.

Directory Structure:

Project Root
+-- src (see above)
+-- subProjects (where projects are held)
|   +-- reallyCoolProject1 (your first included project)
|       \-- See project structure for a normal app
|   \-- reallyCoolProject2 (your second included project)
|       \-- See project structure for a normal app
+-- build.gradle
\-- settings.gradle

settings.gradle:

include ':subProjects:reallyCoolProject1'
include ':subProjects:reallyCoolProject2'

The last thing you should make sure of is the subProjects/reallyCoolProject1/build.gradle has apply plugin: "android-library" instead of apply plugin: "android".

Like every Gradle project (and Maven) we now need to tell the root project about it's dependency. This can also include any normal Java dependencies that you want.

build.gradle

dependencies{
    compile 'com.fasterxml.jackson.core:jackson-core:2.1.4'
    compile 'com.fasterxml.jackson.core:jackson-databind:2.1.4'
    compile project(":subProjects:reallyCoolProject1")
    compile project(':subProjects:reallyCoolProject2')
}

I know this seems like a lot of steps, but they are pretty easy once you do it once or twice. This way will also allow you to build on a CI server assuming you have the Android SDK installed there.

NDK Side Note: If you are going to use the NDK you are going to need something like below. Example build.gradle file can be found here: https://gist.github.com/khernyo/4226923

build.gradle

task copyNativeLibs(type: Copy) {
    from fileTree(dir: 'libs', include: '**/*.so' )  into  'build/native-libs'
}
tasks.withType(Compile) { compileTask -> compileTask.dependsOn copyNativeLibs }

clean.dependsOn 'cleanCopyNativeLibs'

tasks.withType(com.android.build.gradle.tasks.PackageApplication) { pkgTask ->
  pkgTask.jniDir new File('build/native-libs')
}

Sources:

  1. http://tools.android.com/tech-docs/new-build-system/user-guide
  2. https://gist.github.com/khernyo/4226923
  3. https://github.com/ethankhall/driving-time-tracker/

Iterate through a HashMap

Smarter:

for (String key : hashMap.keySet()) {
    System.out.println("Key: " + key + ", Value: " + map.get(key));
}

How to show grep result with complete path or file name

Use:

grep somethingtosearch *.log

and the filenames will be printed out along with the matches.

Launching Spring application Address already in use

Spring Boot uses embedded Tomcat by default, but it handles it differently without using tomcat-maven-plugin. To change the port use --server.port parameter for example:

java -jar target/gs-serving-web-content-0.1.0.jar --server.port=8181

Update. Alternatively put server.port=8181 into application.properties (or application.yml).

Execute Stored Procedure from a Function

Functions are not allowed to have side-effects such as altering table contents.

Stored Procedures are.

If a function called a stored procedure, the function would become able to have side-effects.


So, sorry, but no, you can't call a stored procedure from a function.

How to create multiple class objects with a loop in python?

Using a dictionary for unique names without a name list:

class MyClass:
    def __init__(self, name):
        self.name = name
        self.pretty_print_name()

    def pretty_print_name(self):
    print("This object's name is {}.".format(self.name))

my_objects = {}
for i in range(1,11):
    name = 'obj_{}'.format(i)
    my_objects[name] = my_objects.get(name, MyClass(name = name))

Output:

"This object's name is obj_1."
"This object's name is obj_2."
"This object's name is obj_3."
"This object's name is obj_4."
"This object's name is obj_5."
"This object's name is obj_6."
"This object's name is obj_7."
"This object's name is obj_8."
"This object's name is obj_9."
"This object's name is obj_10."

Temporarily disable all foreign key constraints

Use the built-in sp_msforeachtable stored procedure.

To disable all constraints:

EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT ALL";

To enable all constraints:

EXEC sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT ALL";

To drop all the tables:

EXEC sp_msforeachtable "DROP TABLE ?";

Max or Default?

int max = list.Any() ? list.Max(i => i.MyCounter) : 0;

If the list has any elements (ie. not empty), it will take the max of the MyCounter field, else will return 0.

How to filter an array/object by checking multiple values

You can use .filter() with boolean operators ie &&:

     var find = my_array.filter(function(result) {
       return result.param1 === "srting1" && result.param2 === 'string2';
     });
     
     return find[0];

Parse date without timezone javascript

simple solution

const handler1 = {
  construct(target, args) {
    let newDate = new target(...args);
    var tzDifference = newDate.getTimezoneOffset();
    return new target(newDate.getTime() + tzDifference * 60 * 1000);
  }
};

Date = new Proxy(Date, handler1);

D3 transform scale and translate

I realize this question is fairly old, but wanted to share a quick demo of group transforms, paths/shapes, and relative positioning, for anyone else who found their way here looking for more info:

http://bl.ocks.org/dustinlarimer/6050773

How to redirect docker container logs to a single file?

docker logs -f <yourContainer> &> your.log &

Explanation:

  • -f (i.e.--follow): writes all existing logs and continues (follows) logging everything that comes next.
  • &> redirects both the standard output and standard error.
  • Likely you want to run that method in the background, thus the &.
  • You can separate output and stderr by: > output.log 2> error.log (instead of using &>).

Instance member cannot be used on type

It is saying you have an instance variable (the var is only visible/accessible when you have an instance of that class) and you are trying to use it in the context of a static scope (class method).

You can make your instance variable a class variable by adding static/class attribute.

You instantiate an instance of your class and call the instance method on that variable.

How to convert an ArrayList containing Integers to primitive int array?

If you're using Eclipse Collections, you can use the collectInt() method to switch from an object container to a primitive int container.

List<Integer> integers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
MutableIntList intList =
  ListAdapter.adapt(integers).collectInt(i -> i);
Assert.assertArrayEquals(new int[]{1, 2, 3, 4, 5}, intList.toArray());

If you can convert your ArrayList to a FastList, you can get rid of the adapter.

Assert.assertArrayEquals(
  new int[]{1, 2, 3, 4, 5},
  Lists.mutable.with(1, 2, 3, 4, 5)
    .collectInt(i -> i).toArray());

Note: I am a committer for Eclipse collections.

Http post and get request in angular 6

Update : In angular 7, they are the same as 6

In angular 6

the complete answer found in live example

  /** POST: add a new hero to the database */
  addHero (hero: Hero): Observable<Hero> {
 return this.http.post<Hero>(this.heroesUrl, hero, httpOptions)
  .pipe(
    catchError(this.handleError('addHero', hero))
  );
}
  /** GET heroes from the server */
 getHeroes (): Observable<Hero[]> {
return this.http.get<Hero[]>(this.heroesUrl)
  .pipe(
    catchError(this.handleError('getHeroes', []))
  );
}

it's because of pipeable/lettable operators which now angular is able to use tree-shakable and remove unused imports and optimize the app

some rxjs functions are changed

do -> tap
catch -> catchError
switch -> switchAll
finally -> finalize

more in MIGRATION

and Import paths

For JavaScript developers, the general rule is as follows:

rxjs: Creation methods, types, schedulers and utilities

import { Observable, Subject, asapScheduler, pipe, of, from, interval, merge, fromEvent } from 'rxjs';

rxjs/operators: All pipeable operators:

import { map, filter, scan } from 'rxjs/operators';

rxjs/webSocket: The web socket subject implementation

import { webSocket } from 'rxjs/webSocket';

rxjs/ajax: The Rx ajax implementation

import { ajax } from 'rxjs/ajax';

rxjs/testing: The testing utilities

import { TestScheduler } from 'rxjs/testing';

and for backward compatability you can use rxjs-compat

How to markdown nested list items in Bitbucket?

4 spaces do the trick even inside definition list:

Endpoint
: `/listAgencies`

Method
: `GET`

Arguments
:   * `level` - bla-bla.
    * `withDisabled` - should we include disabled `AGENT`s.
    * `userId` - bla-bla.

I am documenting API using BitBucket Wiki and Markdown proprietary extension for definition list is most pleasing (MD's table syntax is awful, imaging multiline and embedding requirements...).

How to dump a table to console?

I've found this one useful. Because if the recursion it can print nested tables too. It doesn't give the prettiest formatting in the output but for such a simple function it's hard to beat for debugging.

function dump(o)
   if type(o) == 'table' then
      local s = '{ '
      for k,v in pairs(o) do
         if type(k) ~= 'number' then k = '"'..k..'"' end
         s = s .. '['..k..'] = ' .. dump(v) .. ','
      end
      return s .. '} '
   else
      return tostring(o)
   end
end

e.g.

local people = {
   {
      name = "Fred",
      address = "16 Long Street",
      phone = "123456"
   },

   {
      name = "Wilma",
      address = "16 Long Street",
      phone = "123456"
   },

   {
      name = "Barney",
      address = "17 Long Street",
      phone = "123457"
   }

}

print("People:", dump(people))

Produces the following output:

People: { [1] = { ["address"] = 16 Long Street,["phone"] = 123456,["name"] = Fred,} ,[2] = { ["address"] = 16 Long Street,["phone"] = 123456,["name"] = Wilma,} ,[3] = { ["address"] = 17 Long Street,["phone"] = 123457,["name"] = Barney,} ,}

.setAttribute("disabled", false); changes editable attribute to false

the disabled attributes value is actally not considered.. usually if you have noticed the attribute is set as disabled="disabled" the "disabled" here is not necessary persay.. thus the best thing to do is to remove the attribute.

element.removeAttribute("disabled");     

also you could do

element.disabled=false;

ASP.NET MVC Custom Error Handling Application_Error Global.asax?

I struggled with the idea of centralizing a global error handling routine in an MVC app before. I have a post on the ASP.NET forums.

It basically handles all your application errors in the global.asax without the need for an error controller, decorating with the [HandlerError] attribute, or fiddling with the customErrors node in the web.config.

What does the PHP error message "Notice: Use of undefined constant" mean?

You missed putting single quotes around your array keys:

$_POST[email]

should be:

$_POST['email']

Format numbers in JavaScript similar to C#

Here are some solutions, all pass the test suite, test suite and benchmark included, if you want copy and paste to test, try This Gist.

Method 0 (RegExp)

Base on https://stackoverflow.com/a/14428340/1877620, but fix if there is no decimal point.

if (typeof Number.prototype.format === 'undefined') {
    Number.prototype.format = function (precision) {
        if (!isFinite(this)) {
            return this.toString();
        }

        var a = this.toFixed(precision).split('.');
        a[0] = a[0].replace(/\d(?=(\d{3})+$)/g, '$&,');
        return a.join('.');
    }
}

Method 1

if (typeof Number.prototype.format1 === 'undefined') {
    Number.prototype.format1 = function (precision) {
        if (!isFinite(this)) {
            return this.toString();
        }

        var a = this.toFixed(precision).split('.'),
            // skip the '-' sign
            head = Number(this < 0);

        // skip the digits that's before the first thousands separator 
        head += (a[0].length - head) % 3 || 3;

        a[0] = a[0].slice(0, head) + a[0].slice(head).replace(/\d{3}/g, ',$&');
        return a.join('.');
    };
}

Method 2 (Split to Array)

if (typeof Number.prototype.format2 === 'undefined') {
    Number.prototype.format2 = function (precision) {
        if (!isFinite(this)) {
            return this.toString();
        }

        var a = this.toFixed(precision).split('.');

        a[0] = a[0]
            .split('').reverse().join('')
            .replace(/\d{3}(?=\d)/g, '$&,')
            .split('').reverse().join('');

        return a.join('.');
    };
}

Method 3 (Loop)

if (typeof Number.prototype.format3 === 'undefined') {
    Number.prototype.format3 = function (precision) {
        if (!isFinite(this)) {
            return this.toString();
        }

        var a = this.toFixed(precision).split('');
        a.push('.');

        var i = a.indexOf('.') - 3;
        while (i > 0 && a[i-1] !== '-') {
            a.splice(i, 0, ',');
            i -= 3;
        }

        a.pop();
        return a.join('');
    };
}

Example

console.log('======== Demo ========')
var n = 0;
for (var i=1; i<20; i++) {
    n = (n * 10) + (i % 10)/100;
    console.log(n.format(2), (-n).format(2));
}

Separator

If we want custom thousands separator or decimal separator, use replace():

123456.78.format(2).replace(',', ' ').replace('.', ' ');

Test suite

function assertEqual(a, b) {
    if (a !== b) {
        throw a + ' !== ' + b;
    }
}

function test(format_function) {
    console.log(format_function);
    assertEqual('NaN', format_function.call(NaN, 0))
    assertEqual('Infinity', format_function.call(Infinity, 0))
    assertEqual('-Infinity', format_function.call(-Infinity, 0))

    assertEqual('0', format_function.call(0, 0))
    assertEqual('0.00', format_function.call(0, 2))
    assertEqual('1', format_function.call(1, 0))
    assertEqual('-1', format_function.call(-1, 0))
    // decimal padding
    assertEqual('1.00', format_function.call(1, 2))
    assertEqual('-1.00', format_function.call(-1, 2))
    // decimal rounding
    assertEqual('0.12', format_function.call(0.123456, 2))
    assertEqual('0.1235', format_function.call(0.123456, 4))
    assertEqual('-0.12', format_function.call(-0.123456, 2))
    assertEqual('-0.1235', format_function.call(-0.123456, 4))
    // thousands separator
    assertEqual('1,234', format_function.call(1234.123456, 0))
    assertEqual('12,345', format_function.call(12345.123456, 0))
    assertEqual('123,456', format_function.call(123456.123456, 0))
    assertEqual('1,234,567', format_function.call(1234567.123456, 0))
    assertEqual('12,345,678', format_function.call(12345678.123456, 0))
    assertEqual('123,456,789', format_function.call(123456789.123456, 0))
    assertEqual('-1,234', format_function.call(-1234.123456, 0))
    assertEqual('-12,345', format_function.call(-12345.123456, 0))
    assertEqual('-123,456', format_function.call(-123456.123456, 0))
    assertEqual('-1,234,567', format_function.call(-1234567.123456, 0))
    assertEqual('-12,345,678', format_function.call(-12345678.123456, 0))
    assertEqual('-123,456,789', format_function.call(-123456789.123456, 0))
    // thousands separator and decimal
    assertEqual('1,234.12', format_function.call(1234.123456, 2))
    assertEqual('12,345.12', format_function.call(12345.123456, 2))
    assertEqual('123,456.12', format_function.call(123456.123456, 2))
    assertEqual('1,234,567.12', format_function.call(1234567.123456, 2))
    assertEqual('12,345,678.12', format_function.call(12345678.123456, 2))
    assertEqual('123,456,789.12', format_function.call(123456789.123456, 2))
    assertEqual('-1,234.12', format_function.call(-1234.123456, 2))
    assertEqual('-12,345.12', format_function.call(-12345.123456, 2))
    assertEqual('-123,456.12', format_function.call(-123456.123456, 2))
    assertEqual('-1,234,567.12', format_function.call(-1234567.123456, 2))
    assertEqual('-12,345,678.12', format_function.call(-12345678.123456, 2))
    assertEqual('-123,456,789.12', format_function.call(-123456789.123456, 2))
}

console.log('======== Testing ========');
test(Number.prototype.format);
test(Number.prototype.format1);
test(Number.prototype.format2);
test(Number.prototype.format3);

Benchmark

function benchmark(f) {
    var start = new Date().getTime();
    f();
    return new Date().getTime() - start;
}

function benchmark_format(f) {
    console.log(f);
    time = benchmark(function () {
        for (var i = 0; i < 100000; i++) {
            f.call(123456789, 0);
            f.call(123456789, 2);
        }
    });
    console.log(time.format(0) + 'ms');
}

async = [];
function next() {
    setTimeout(function () {
        f = async.shift();
        f && f();
        next();
    }, 10);
}

console.log('======== Benchmark ========');
async.push(function () { benchmark_format(Number.prototype.format); });
async.push(function () { benchmark_format(Number.prototype.format1); });
async.push(function () { benchmark_format(Number.prototype.format2); });
async.push(function () { benchmark_format(Number.prototype.format3); });
next();

Delete empty lines using sed

sed '/^$/d' should be fine, are you expecting to modify the file in place? If so you should use the -i flag.

Maybe those lines are not empty, so if that's the case, look at this question Remove empty lines from txtfiles, remove spaces from start and end of line I believe that's what you're trying to achieve.

Windows Explorer "Command Prompt Here"

As a very quick solution I can give you this. I tested this on Windows 8.1

1- Find File and Right Click on Command Prompt on File Explorer and then add command prompt to your Quick Access Toolbar:

Instruction 1

2- After adding it you can access the folder from here:

Instruction 2

That will open a command prompt in there for you.

Android Endless List

You can detect end of the list with help of onScrollListener, working code is presented below:

@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
    if (view.getAdapter() != null && ((firstVisibleItem + visibleItemCount) >= totalItemCount) && totalItemCount != mPrevTotalItemCount) {
        Log.v(TAG, "onListEnd, extending list");
        mPrevTotalItemCount = totalItemCount;
        mAdapter.addMoreData();
    }
}

Another way to do that (inside adapter) is as following:

    public View getView(int pos, View v, ViewGroup p) {
            if(pos==getCount()-1){
                addMoreData(); //should be asynctask or thread
            }
            return view;
    }

Be aware that this method will be called many times, so you need to add another condition to block multiple calls of addMoreData().

When you add all elements to the list, please call notifyDataSetChanged() inside yours adapter to update the View (it should be run on UI thread - runOnUiThread)

Python WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect:

I had this problem with Django and it was because I had forgotten to start the virtual environment on the backend.

How to copy directories in OS X 10.7.3?

tl;dr

cp -R "/src/project 1/App" "/src/project 2"

Explanation:

Using quotes will cater for spaces in the directory names

cp -R "/src/project 1/App" "/src/project 2"

If the App directory is specified in the destination directory:

cp -R "/src/project 1/App" "/src/project 2/App"

and "/src/project 2/App" already exists the result will be "/src/project 2/App/App"

Best not to specify the directory copied in the destination so that the command can be repeated over and over with the expected result.

Inside a bash script:

cp -R "${1}/App" "${2}"

.NET HttpClient. How to POST string value?

Here I found this article which is send post request using JsonConvert.SerializeObject() & StringContent() to HttpClient.PostAsync data

static async Task Main(string[] args)
{
    var person = new Person();
    person.Name = "John Doe";
    person.Occupation = "gardener";

    var json = Newtonsoft.Json.JsonConvert.SerializeObject(person);
    var data = new System.Net.Http.StringContent(json, Encoding.UTF8, "application/json");

    var url = "https://httpbin.org/post";
    using var client = new HttpClient();

    var response = await client.PostAsync(url, data);

    string result = response.Content.ReadAsStringAsync().Result;
    Console.WriteLine(result);
}

cannot redeclare block scoped variable (typescript)

For those coming here in this age, here is a simple solution to this issue. It at least worked for me in the backend. I haven't checked with the frontend code.

Just add:

export {};

at the top of your code.

Credit to EUGENE MURAVITSKY

How to get device make and model on iOS?

Swift 4 or later

extension UIDevice {
    var modelName: String {
        if let modelName = ProcessInfo.processInfo.environment["SIMULATOR_MODEL_IDENTIFIER"] { return modelName }
        var info = utsname()
        uname(&info)
        return String(String.UnicodeScalarView(
                   Mirror(reflecting: info.machine)
                    .children
                    .compactMap {
                        guard let value = $0.value as? Int8 else { return nil }
                        let unicode = UnicodeScalar(UInt8(value))
                        return unicode.isASCII ? unicode : nil
                    }))
    }
}

UIDevice.current.modelName   // "iPad6,4"

Getting the docstring from a function

On ipython or jupyter notebook, you can use all the above mentioned ways, but i go with

my_func?

or

?my_func

for quick summary of both method signature and docstring.

I avoid using

my_func??

(as commented by @rohan) for docstring and use it only to check the source code

Difference between HttpModule and HttpClientModule

HttpClient is a new API that came with 4.3, it has updated API's with support for progress events, json deserialization by default, Interceptors and many other great features. See more here https://angular.io/guide/http

Http is the older API and will eventually be deprecated.

Since their usage is very similar for basic tasks I would advise using HttpClient since it is the more modern and easy to use alternative.

How do I check if a string is unicode or ascii?

One simple approach is to check if unicode is a builtin function. If so, you're in Python 2 and your string will be a string. To ensure everything is in unicode one can do:

import builtins

i = 'cats'
if 'unicode' in dir(builtins):     # True in python 2, False in 3
  i = unicode(i)

How can I convert String to Int?

If you're looking for the long way, just create your one method:

static int convertToInt(string a)
    {
        int x = 0;

        Char[] charArray = a.ToCharArray();
        int j = charArray.Length;

        for (int i = 0; i < charArray.Length; i++)
        {
            j--;
            int s = (int)Math.Pow(10, j);

            x += ((int)Char.GetNumericValue(charArray[i]) * s);
        }
        return x;
    }

How to compare different branches in Visual Studio Code

2019 answer

Here is the step by step guide:

  1. Install the GitLens extension: GitLens
  2. The GitLens icon will show up in nav bar. Click on it.

    Git lens icon

  3. Click on compare

    Enter image description here

  4. Select branches to compare

    enter image description here

  5. Now you can see the difference. You can select any file for which you want to see the diff for.

    Enter image description here

Create listview in fragment android

Please use ListFragment. Otherwise, it won't work.

EDIT 1: Then you'll only need setListAdapter() and getListView().

Error:(9, 5) error: resource android:attr/dialogCornerRadius not found

Maybe it's too late but i found a solution:

You have to edit in the build.gradle either the compileSdkVersion --> to lastest (now it is 28). Like that:

android {
compileSdkVersion 28
defaultConfig {
    applicationId "NAME_OF_YOUR_PROJECT_DIRECTORY"
    minSdkVersion 21
    targetSdkVersion 28
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}

or you can change the version of implementation:

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    api 'com.android.support:design:27.+'
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

Center form submit buttons HTML / CSS

I'm assuming that the buttons are supposed to be next to each other on the same line, they should not each be centered using the 'auto' margin, but placed inside a div with a defined width that has a margin '0 auto':

CSS:

#centerbuttons{
   width:250px; 
   margin:0 auto;
}       

HTML (after removing the margin properties from your buttons' CSS):

<div id="centerbuttons">
     <input value="Search" title="Search" type="submit"> 
     <input value="I'm Feeling Lucky" title="I'm Feeling Lucky" name="lucky" type="submit">
</div>

Close application and launch home screen on Android

You can not do System.exit(), it's not safe.

You can do this one: Process.killProcess(Process.myPid());

Where does Anaconda Python install on Windows?

You can search for "Anaconda prompt" in installed programs and run it.
When it opens, it shows the directory anaconda is working from.
enter image description here

As you can see c:\programdata\anaconda2 is my installed directory.
*side note: programdata folder is hidden in windows so you'll have to enter its path in the folder explorer to access it.

Tomcat Server Error - Port 8080 already in use

All I had to do was to change the port numbers. enter image description here

  1. Open Eclipse

  2. Go to Servers panel

  3. Right click on Tomcat Server select Open, Overview window will appear.

  4. Open the Portstab. You will get the following:

    • Tomcat adminport

    • HTTP/1.1

    • AJP/1.3

  5. I changed the port number of HTTP/1.1 (i.e. to 8081)

  6. You might have to also change the port of Tomcat adminport (i.e. to 8006) and of AJP/1.3 (i.e. to 8010).

  7. Access your app in the browser at http://localhost:8081/...

How to initialize a private static const map in C++?

A different approach to the problem:

struct A {
    static const map<int, string> * singleton_map() {
        static map<int, string>* m = NULL;
        if (!m) {
            m = new map<int, string>;
            m[42] = "42"
            // ... other initializations
        }
        return m;
    }

    // rest of the class
}

This is more efficient, as there is no one-type copy from stack to heap (including constructor, destructors on all elements). Whether this matters or not depends on your use case. Does not matter with strings! (but you may or may not find this version "cleaner")

How to pass optional parameters while omitting some other optional parameters?

you can use optional variable by ? or if you have multiple optional variable by ..., example:

function details(name: string, country="CA", address?: string, ...hobbies: string) {
    // ...
}

In the above:

  • name is required
  • country is required and has a default value
  • address is optional
  • hobbies is an array of optional params

How to convert entire dataframe to numeric while preserving decimals?

Using dplyr (a bit like sapply..)

df2 <- mutate_all(df1, function(x) as.numeric(as.character(x)))

which gives:

glimpse(df2)
Observations: 4
Variables: 2
$ a <dbl> 0.01, 0.02, 0.03, 0.04
$ b <dbl> 2, 4, 5, 7

from your df1 which was:

glimpse(df1)
Observations: 4
Variables: 2
$ a <fctr> 0.01, 0.02, 0.03, 0.04
$ b <dbl> 2, 4, 5, 7

MatPlotLib: Multiple datasets on the same scatter plot

I don't know, it works fine for me. Exact commands:

import scipy, pylab
ax = pylab.subplot(111)
ax.scatter(scipy.randn(100), scipy.randn(100), c='b')
ax.scatter(scipy.randn(100), scipy.randn(100), c='r')
ax.figure.show()

error: command 'gcc' failed with exit status 1 on CentOS

I bet you have to install libxml2-devel or libxml++-devel or even python-devel. But it is only a wild guess, not seeing the actual error from the log file. But it seems gcc is missing either a header file or a library file.

SQL Server Text type vs. varchar data type

TEXT is used for large pieces of string data. If the length of the field exceeed a certain threshold, the text is stored out of row.

VARCHAR is always stored in row and has a limit of 8000 characters. If you try to create a VARCHAR(x), where x > 8000, you get an error:

Server: Msg 131, Level 15, State 3, Line 1

The size () given to the type ‘varchar’ exceeds the maximum allowed for any data type (8000)

These length limitations do not concern VARCHAR(MAX) in SQL Server 2005, which may be stored out of row, just like TEXT.

Note that MAX is not a kind of constant here, VARCHAR and VARCHAR(MAX) are very different types, the latter being very close to TEXT.

In prior versions of SQL Server you could not access the TEXT directly, you only could get a TEXTPTR and use it in READTEXT and WRITETEXT functions.

In SQL Server 2005 you can directly access TEXT columns (though you still need an explicit cast to VARCHAR to assign a value for them).

TEXT is good:

  • If you need to store large texts in your database
  • If you do not search on the value of the column
  • If you select this column rarely and do not join on it.

VARCHAR is good:

  • If you store little strings
  • If you search on the string value
  • If you always select it or use it in joins.

By selecting here I mean issuing any queries that return the value of the column.

By searching here I mean issuing any queries whose result depends on the value of the TEXT or VARCHAR column. This includes using it in any JOIN or WHERE condition.

As the TEXT is stored out of row, the queries not involving the TEXT column are usually faster.

Some examples of what TEXT is good for:

  • Blog comments
  • Wiki pages
  • Code source

Some examples of what VARCHAR is good for:

  • Usernames
  • Page titles
  • Filenames

As a rule of thumb, if you ever need you text value to exceed 200 characters AND do not use join on this column, use TEXT.

Otherwise use VARCHAR.

P.S. The same applies to UNICODE enabled NTEXT and NVARCHAR as well, which you should use for examples above.

P.P.S. The same applies to VARCHAR(MAX) and NVARCHAR(MAX) that SQL Server 2005+ uses instead of TEXT and NTEXT. You'll need to enable large value types out of row for them with sp_tableoption if you want them to be always stored out of row.

As mentioned above and here, TEXT is going to be deprecated in future releases:

The text in row option will be removed in a future version of SQL Server. Avoid using this option in new development work, and plan to modify applications that currently use text in row. We recommend that you store large data by using the varchar(max), nvarchar(max), or varbinary(max) data types. To control in-row and out-of-row behavior of these data types, use the large value types out of row option.

Using the "animated circle" in an ImageView while loading stuff

You can do this by using the following xml

<RelativeLayout
    style="@style/GenericProgressBackground"
    android:id="@+id/loadingPanel"
    >
    <ProgressBar
        style="@style/GenericProgressIndicator"/>
</RelativeLayout>

With this style

<style name="GenericProgressBackground" parent="android:Theme">
    <item name="android:layout_width">fill_parent</item>    
    <item name="android:layout_height">fill_parent</item>
    <item name="android:background">#DD111111</item>    
    <item name="android:gravity">center</item>  
</style>
<style name="GenericProgressIndicator" parent="@android:style/Widget.ProgressBar.Small">
    <item name="android:layout_width">wrap_content</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:indeterminate">true</item> 
</style>

To use this, you must hide your UI elements by setting the visibility value to GONE and whenever the data is loaded, call setVisibility(View.VISIBLE) on all your views to restore them. Don't forget to call findViewById(R.id.loadingPanel).setVisiblity(View.GONE) to hide the loading animation.

If you dont have a loading event/function but just want the loading panel to disappear after x seconds use a Handle to trigger the hiding/showing.

How do I install Python OpenCV through Conda?

I installed it like this:

$ conda install --channel https://conda.anaconda.org/conda-forge opencv

I tried conda install opencv directly, but it does not work for me since I am using Python 3.5 which is higher version that default OpenCV library in conda. Later, I tried 'anaconda/opencv', but it does not work either. I found finally that conda-forge/opencv works for Python 3.5.

javac not working in windows command prompt

for /d %i in ("\Program Files\Java\jdk*") do set JAVA_HOME=%i
set JAVA_HOME

this solution worked to me

Eclipse change project files location

You can copy your .classpath and .project files to the root of the new project directory and then choose 'Import...' from the file menu, and select 'General/Existing Projects into Workspace.' In the resulting dialog, locate the root of the new project directory and finish. Make sure that you have deleted the old project from the work space before importing.

Turning error reporting off php

Read up on the configuration settings (e.g., display_errors, display_startup_errors, log_errors) and update your php.ini or .htaccess or .user.ini file, whichever is appropriate.

It works.

how to add value to combobox item

I am assuming that you are wanting to add items to a ComboBox on an Windows form. Although Klaus is on the right track I believe that the ListItem class is a member of the System.Web.UI.WebControls namespace. So you shouldn't be using it in a Windows forms solution. You can, however, create your own class that you can use in its place. Create a simple class called MyListItem (or whatever name you choose) like this:

Public Class MyListItem
    Private mText As String
    Private mValue As String

    Public Sub New(ByVal pText As String, ByVal pValue As String)
        mText = pText
        mValue = pValue
    End Sub

    Public ReadOnly Property Text() As String
        Get
            Return mText
        End Get
    End Property

    Public ReadOnly Property Value() As String
        Get
            Return mValue
        End Get
    End Property

    Public Overrides Function ToString() As String
        Return mText
    End Function
End Class

Now when you want to add the items to your ComboBox you can do it like this:

myComboBox.Items.Add(New MyListItem("Text to be displayed", "value of the item"))

Now when you want to retrieve the value of the selected item from your ComboBox you can do it like this:

Dim oItem As MyListItem = CType(myComboBox.SelectedItem, MyListItem)
MessageBox.Show("The Value of the Item selected is: " & oItem.Value)

One of the keys here is overriding the ToString method in the class. This is where the ComboBox gets the text that is displayed.


Matt made an excellent point, in his comment below, about using Generics to make this even more flexible. So I wondered what that would look like.

Here's the new and improved GenericListItem class:

Public Class GenericListItem(Of T)
    Private mText As String
    Private mValue As T

    Public Sub New(ByVal pText As String, ByVal pValue As T)
        mText = pText
        mValue = pValue
    End Sub

    Public ReadOnly Property Text() As String
        Get
            Return mText
        End Get
    End Property

    Public ReadOnly Property Value() As T
        Get
            Return mValue
        End Get
    End Property

    Public Overrides Function ToString() As String
        Return mText
    End Function
End Class

And here is how you would now add Generic items to your ComboBox. In this case an Integer:

Me.myComboBox.Items.Add(New GenericListItem(Of Integer)("Text to be displayed", 1))

And now the retrieval of the item:

Dim oItem As GenericListItem(Of Integer) = CType(Me.myComboBox.SelectedItem, GenericListItem(Of Integer))
MessageBox.Show("The value of the Item selected is: " & oItem.Value.ToString())

Keep in mind that the type Integer can be any type of object or value type. If you want it to be an object from one of your own custom classes that's fine. Basically anything goes with this approach.

Best way to create enum of strings?

Get and set with default values.

public enum Status {

    STATUS_A("Status A"),  STATUS_B("Status B"),

    private String status;

    Status(String status) {
        this.status = status;
    }

    public String getStatus() {
        return status;
    }
}

gradlew: Permission Denied

Jenkins > Project Dashboard > (select gradle project) Configure > Build

x Use Gradle Wrapper

Make gradlew executable x

enter image description here

Array to Hash Ruby

You could try like this, for single array

irb(main):019:0> a = ["item 1", "item 2", "item 3", "item 4"]
  => ["item 1", "item 2", "item 3", "item 4"]
irb(main):020:0> Hash[*a]
  => {"item 1"=>"item 2", "item 3"=>"item 4"}

for array of array

irb(main):022:0> a = [[1, 2], [3, 4]]
  => [[1, 2], [3, 4]]
irb(main):023:0> Hash[*a.flatten]
  => {1=>2, 3=>4}

How to import component into another root component in Angular 2

Angular RC5 & RC6

If you are getting the above mentioned error in your Jasmine tests, it is most likely because you have to declare the unrenderable component in your TestBed.configureTestingModule({}).

The TestBed configures and initializes an environment for unit testing and provides methods for mocking/creating/injecting components and services in unit tests.

If you don't declare the component before your unit tests are executed, Angular will not know what <courses></courses> is in your template file.

Here is an example:

import {async, ComponentFixture, TestBed} from "@angular/core/testing";
import {AppComponent} from "../app.component";
import {CoursesComponent} from './courses.component';

describe('CoursesComponent', () => {
  let component: CoursesComponent;
  let fixture: ComponentFixture<CoursesComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent,
        CoursesComponent
      ],
      imports: [
        BrowserModule
        // If you have any other imports add them here
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(CoursesComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

Histogram with Logarithmic Scale and custom breaks

Here's a pretty ggplot2 solution:

library(ggplot2)
library(scales)  # makes pretty labels on the x-axis

breaks=c(0,1,2,3,4,5,25)

ggplot(mydata,aes(x = V3)) + 
  geom_histogram(breaks = log10(breaks)) + 
  scale_x_log10(
    breaks = breaks,
    labels = scales::trans_format("log10", scales::math_format(10^.x))
  )

Note that to set the breaks in geom_histogram, they had to be transformed to work with scale_x_log10

How to attach a process in gdb

The first argument should be the path to the executable program. So

gdb progname 12271

how to fire event on file select

<input id="fusk" type="file" name="upload" style="display: none;"
    onChange=" document.getElementById('myForm').submit();"
>

How to quickly edit values in table in SQL Server Management Studio?

Brendan is correct. You can edit the Select command to edit a filtered list of records. For instance "WHERE dept_no = 200".

Apache error: _default_ virtualhost overlap on port 443

It is highly unlikely that adding NameVirtualHost *:443 is the right solution, because there are a limited number of situations in which it is possible to support name-based virtual hosts over SSL. Read this and this for some details (there may be better docs out there; these were just ones I found that discuss the issue in detail).

If you're running a relatively stock Apache configuration, you probably have this somewhere:

<VirtualHost _default_:443>

Your best bet is to either:

  • Place your additional SSL configuration into this existing VirtualHost container, or
  • Comment out this entire VirtualHost block and create a new one. Don't forget to include all the relevant SSL options.

SQL UPDATE with sub-query that references the same table in MySQL

I needed this for SQL Server. Here it is:

UPDATE user_account 
SET student_education_facility_id = cnt.education_facility_id
from  (
   SELECT user_account_id,education_facility_id
   FROM user_account 
   WHERE user_type = 'ROLE_TEACHER'
) as cnt
WHERE user_account.user_type = 'ROLE_STUDENT' and cnt.user_account_id = user_account.teacher_id

I think it works with other RDBMSes (please confirm). I like the syntax because it's extensible.

The format I needed was this actually:

UPDATE table1 
SET f1 = cnt.computed_column
from  (
   SELECT id,computed_column --can be any complex subquery
   FROM table1
) as cnt
WHERE cnt.id = table1.id

Windows 7 SDK installation failure

You should really check the log. It seems that quite a few components can cause the Windows SDK installer to fail to install with this useless error message. For instance it could be the Visual C++ Redistributable Package as mentioned there.

How to install cron

Install cron on Linux/Unix:

apt-get install cron

Use cron on Linux/Unix

crontab -e

See the canonical answer about cron for more details: https://serverfault.com/questions/449651/why-is-my-crontab-not-working-and-how-can-i-troubleshoot-it

java.net.URLEncoder.encode(String) is deprecated, what should I use instead?

The first parameter is the String to encode; the second is the name of the character encoding to use (e.g., UTF-8).

How to remove/ignore :hover css style on touch devices

If Your issue is when you touch/tap on android and whole div covered by blue transparent color! Then you need to just change the

CURSOR : POINTER; to CURSOR : DEFAULT;

use mediaQuery to hide in mobile phone/Tablet.

This works for me.

extract month from date in python

Alternate solution

Create a column that will store the month:

data['month'] = data['date'].dt.month

Create a column that will store the year:

data['year'] = data['date'].dt.year

How to pass parameters to a Script tag?

I wanted solutions with as much support of old browsers as possible. Otherwise I'd say either the currentScript or the data attributes method would be most stylish.

This is the only of these methods not brought up here yet. Particularly, if for some reason you have great amounts of data, then the best option might be:

localStorage

/* On the original page, you add an inline JS Script: */
<script>
   localStorage.setItem('data-1', 'I got a lot of data.');
   localStorage.setItem('data-2', 'More of my data.');
   localStorage.setItem('data-3', 'Even more data.');
</script>

/* External target JS Script, where your data is needed: */
var data1 = localStorage.getItem('data-1');
var data2 = localStorage.getItem('data-2');
var data3 = localStorage.getItem('data-3');

localStorage has full modern browser support, and surprisingly good support of older browsers too, back to IE 8, Firefox 3,5 and Safari 4 [eleven years back] among others.

If you don't have a lot of data, but still want extensive browser support, maybe the best option is:

Meta tags [by Robidu]

/* HTML: */
<meta name="yourData" content="Your data is here" />

/* JS: */
var data1 = document.getElementsByName('yourData')[0].content;

The flaw of this, is that the correct place to put meta tags [up until HTML 4] is in the head tag, and you might not want this data up there. To avoid that, or putting meta tags in body, you could use a:

Hidden paragraph

/* HTML: */
<p hidden id="yourData">Your data is here</p>

/* JS: */
var yourData = document.getElementById('yourData').innerHTML;

For even more browser support, you could use a CSS class instead of the hidden attribute:

/* CSS: */
.hidden {
   display: none;
}

/* HTML: */
<p class="hidden" id="yourData">Your data is here</p>

Iterating over all the keys of a map

Here's some easy way to get slice of the map-keys.

// Return keys of the given map
func Keys(m map[string]interface{}) (keys []string) {
    for k := range m {
        keys = append(keys, k)
    }
    return keys
}

// use `Keys` func
func main() {
    m := map[string]interface{}{
        "foo": 1,
        "bar": true,
        "baz": "baz",
    }
    fmt.Println(Keys(m)) // [foo bar baz]
}

Select unique or distinct values from a list in UNIX shell script

Unique, as requested, (but not sorted);
uses fewer system resources for less than ~70 elements (as tested with time);
written to take input from stdin,
(or modify and include in another script):
(Bash)

bag2set () {
    # Reduce a_bag to a_set.
    local -i i j n=${#a_bag[@]}
    for ((i=0; i < n; i++)); do
        if [[ -n ${a_bag[i]} ]]; then
            a_set[i]=${a_bag[i]}
            a_bag[i]=$'\0'
            for ((j=i+1; j < n; j++)); do
                [[ ${a_set[i]} == ${a_bag[j]} ]] && a_bag[j]=$'\0'
            done
        fi
    done
}
declare -a a_bag=() a_set=()
stdin="$(</dev/stdin)"
declare -i i=0
for e in $stdin; do
    a_bag[i]=$e
    i=$i+1
done
bag2set
echo "${a_set[@]}"

How do I pre-populate a jQuery Datepicker textbox with today's date?

This works better for me as sometimes I have troubles calling .datepicker('setDate', new Date()); as it messes if if i have the datepicker already configured with parameters.

$("#myDateText").val(moment(new Date()).format('DD/MM/YYYY'));

How to store Configuration file and read it using React

With webpack you can put env-specific config into the externals field in webpack.config.js

externals: {
  'Config': JSON.stringify(process.env.NODE_ENV === 'production' ? {
    serverUrl: "https://myserver.com"
  } : {
    serverUrl: "http://localhost:8090"
  })
}

If you want to store the configs in a separate JSON file, that's possible too, you can require that file and assign to Config:

externals: {
  'Config': JSON.stringify(process.env.NODE_ENV === 'production' ? require('./config.prod.json') : require('./config.dev.json'))
}

Then in your modules, you can use the config:

var Config = require('Config')
fetchData(Config.serverUrl + '/Enterprises/...')

For React:

import Config from 'Config';
axios.get(this.app_url, {
        'headers': Config.headers
        }).then(...);

Not sure if it covers your use case but it's been working pretty well for us.

Change the image source on rollover using jQuery

I've made something like the following code :)

It works only, when you have a second file named with _hover, for example, facebook.png and facebook_hover.png

$('#social').find('a').hover(function() {
    var target = $(this).find('img').attr('src');
    //console.log(target);
    var newTarg = target.replace('.png', '_hover.png');
    $(this).find('img').attr("src", newTarg);
}, function() {
    var target = $(this).find('img').attr('src');
    var newTarg = target.replace('_hover.png', '.png');
    $(this).find('img').attr("src", newTarg);
});

Revert to Eclipse default settings

I am not an expert on this, but I'll share my example with you. One guy suggested to create new eclipse preferences file or epf file using another clean install of eclipse. I made a file called clean.epf and compared it with RainbowDrops.epf (the one which messed up my highlighting and such). I noticed a huge difference between the two epf files. So, you might not want to use this method.

The whole windows --- preferences thing did not help. So, I just closed eclipse. Went to

My workspace directory/.metadata/.plugins/org.eclipse.core.runtime/.settings/

and deleted the file org.eclipse.ui.editors.prefs and opened eclipse. It works. BTW, keep a back up of your .settings folders just in case.

In case you want to see some difference between rainbow and clean epf -

Rainbow -

file_export_version=3.0
/instance/ccw.core/ccw.preferences.editor_color.FUNCTION=167,236,33
/instance/ccw.core/ccw.preferences.editor_color.FUNCTION.bold=false
/instance/ccw.core/ccw.preferences.editor_color.FUNCTION.enabled=true
/instance/ccw.core/ccw.preferences.editor_color.FUNCTION.italic=false
/instance/ccw.core/ccw.preferences.editor_color.GLOBAL_VAR=141,218,248
...more here

Clean (exporting all) -

/instance/org.eclipse.jdt.ui/tabWidthPropagated=true
/instance/org.eclipse.mylyn.monitor.ui/org.eclipse.mylyn.monitor.activity.tracking.enabled.checked=true
/instance/org.eclipse.mylyn.tasks.ui/org.eclipse.mylyn.tasks.ui.filters.nonmatching.encouraged=true
@org.eclipse.mylyn.monitor.ui=3.13.0.v20140702-2155
/instance/org.eclipse.jdt.ui/useQuickDiffPrefPage=true
...more here

Clean (exporting only java) -

file_export_version=3.0
/instance/org.eclipse.jdt.ui/org.eclipse.jdt.ui.formatterprofiles.version=12
@org.eclipse.jdt.ui=3.10.100.v20140905-1343
\!/=
...end of file

So, I am not sure if this is the best way to go.

How do I compare two files using Eclipse? Is there any option provided by Eclipse?

To compare two files in Eclipse, first select them in the Project Explorer / Package Explorer / Navigator with control-click. Now right-click on one of the files, and the following context menu will appear. Select Compare With / Each Other.

enter image description here

jQuery - Trigger event when an element is removed from the DOM

I couldn't get this answer to work with unbinding (despite the update see here), but was able to figure out a way around it. The answer was to create a 'destroy_proxy' special event that triggered a 'destroyed' event. You put the event listener on both 'destroyed_proxy' and 'destroyed', then when you want to unbind, you just unbind the 'destroyed' event:

var count = 1;
(function ($) {
    $.event.special.destroyed_proxy = {
        remove: function (o) {
            $(this).trigger('destroyed');
        }
    }
})(jQuery)

$('.remove').on('click', function () {
    $(this).parent().remove();
});

$('li').on('destroyed_proxy destroyed', function () {
    console.log('Element removed');
    if (count > 2) {
        $('li').off('destroyed');
        console.log('unbinded');
    }
    count++;
});

Here is a fiddle

How to consume a SOAP web service in Java

Here you can find a nice tutorial of how you can create and consume a SOAP service through WSDL. Long story short you need to call wsimport tool from command line (you can find it in your jdk) with parameters like -s (source for .java files) -d (destination for .class files) and the wsdl link.

$ wsimport -s "C:\workspace\soap\src\main\java\com\test\soap\ws" -d "C:\workspace\soap\target\classes\com\test\soap\ws" http://localhost:8855/soap/test?wsdl

After the stubs are created, you can call the webservices very easy something like:

TestHarnessService harnessService = new TestHarnessService();
ITestApi testApi = harnessService.getBasicHttpBindingITestApi();
testApi.resetLogMemoryTarget();

How do I UPDATE from a SELECT in SQL Server?

One way

UPDATE t 
SET t.col1 = o.col1, 
    t.col2 = o.col2
FROM 
    other_table o 
  JOIN 
    t ON t.id = o.id
WHERE 
    o.sql = 'cool'

Using git commit -a with vim

To exit hitting :q will let you quit.

If you want to quit without saving you can hit :q!

A google search on "vim cheatsheet" can provide you with a reference you should print out with a collection of quick shortcuts.

http://www.fprintf.net/vimCheatSheet.html

PHP unable to load php_curl.dll extension

After having tried everything here I had to simply upgrade Apache to a newer version in order to make curl extension work.

I was upgrading PHP from 7.0.2 to 7.1.15 after which curl did not work. Only way to fix it was upgrade Apache (which was version 2.4.18) to the latest 2.4.29.

Didn't have to copy any of the lib/ssleay dll files to either Apache or Windows - possibly because I already have the PHP folder in my system path.

Running Windows 10, 64-bit, thread-safe versions, VC14.

Changing background color of selected cell?

in Swift 3, converted from illuminates answer.

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)
    if(selected) {
        self.selectionStyle = .none
        self.backgroundColor = UIColor.green
    } else {
        self.backgroundColor = UIColor.blue
    }
}

(however the view only changes once the selection is confirmed by releasing your finger)

Get current user id in ASP.NET Identity 2.0

Just in case you are like me and the Id Field of the User Entity is an Int or something else other than a string,

using Microsoft.AspNet.Identity;

int userId = User.Identity.GetUserId<int>();

will do the trick

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

Due to the mixed comments about BuildConfig.DEBUG, I used the following to disable crashlytics (and analytics) in debug mode :

update /app/build.gradle

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.1"

    defaultConfig {
        applicationId "your.awesome.app"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 100
        versionName "1.0.0"
        buildConfigField 'boolean', 'ENABLE_CRASHLYTICS', 'true'
    }
    buildTypes {
        debug {
            debuggable true
            minifyEnabled false
            buildConfigField 'boolean', 'ENABLE_CRASHLYTICS', 'false'
        }
        release {
            debuggable false
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

then, in your code you detect the ENABLE_CRASHLYTICS flag as follows:

    if (BuildConfig.ENABLE_CRASHLYTICS)
    {
        // enable crashlytics and answers (Crashlytics by default includes Answers)
        Fabric.with(this, new Crashlytics());
    }

use the same concept in your app and rename ENABLE_CRASHLYTICS to anything you want. I like this approach because I can see the flag in the configuration and I can control the flag.

Is a Python dictionary an example of a hash table?

To expand upon nosklo's explanation:

a = {}
b = ['some', 'list']
a[b] = 'some' # this won't work
a[tuple(b)] = 'some' # this will, same as a['some', 'list']

Static vs class functions/variables in Swift classes?

There's one more difference. class can be used to define type properties of computed type only. If you need a stored type property use static instead.

Class :- reference type

struct :- value type

HTML text input allow only numeric input

Below function will check for every input char if it is number.

numeric: value => {
    let numset = new Set(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']);
    console.log(numset.has(value.substring(value.length - 1, value.length)));
}

How to replace all special character into a string using C#

Also, It can be done with LINQ

var str = "Hello@Hello&Hello(Hello)";
var characters = str.Select(c => char.IsLetter(c) ? c : ',')).ToArray();             
var output = new string(characters);
Console.WriteLine(output);

Leave only two decimal places after the dot

Alternatively, you may also use the composite operator F then indicating how many decimal spots you wish to appear after the decimal.

string.Format("{0:F2}", 123.456789);     //123.46
string.Format("{0:F3}", 123.456789);     //123.457
string.Format("{0:F4}", 123.456789);     //123.4568

It will round up so be aware of that.

I sourced the general documentation. There are a ton of other formatting operators there as well that you may check out.

Source: https://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx

Converting XML to JSON using Python?

This stuff here is actively maintained and so far is my favorite: xml2json in python

Multiple submit buttons in an HTML form

Give your submit buttons the same name like this:

<input type="submit" name="submitButton" value="Previous Page" />
<input type="submit" name="submitButton" value="Next Page" />

When the user presses Enter and the request goes to the server, you can check the value for submitButton on your server-side code which contains a collection of form name/value pairs. For example, in ASP Classic:

If Request.Form("submitButton") = "Previous Page" Then
    ' Code for the previous page
ElseIf Request.Form("submitButton") = "Next Page" Then
    ' Code for the next page
End If

Reference: Using multiple submit buttons on a single form

Prevent wrapping of span or div

Try this:

_x000D_
_x000D_
.slideContainer {_x000D_
    overflow-x: scroll;_x000D_
    white-space: nowrap;_x000D_
}_x000D_
.slide {_x000D_
    display: inline-block;_x000D_
    width: 600px;_x000D_
    white-space: normal;_x000D_
}
_x000D_
<div class="slideContainer">_x000D_
    <span class="slide">Some content</span>_x000D_
    <span class="slide">More content. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</span>_x000D_
    <span class="slide">Even more content!</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Note that you can omit .slideContainer { overflow-x: scroll; } (which browsers may or may not support when you read this), and you'll get a scrollbar on the window instead of on this container.

The key here is display: inline-block. This has decent cross-browser support nowadays, but as usual, it's worth testing in all target browsers to be sure.

Using Python's ftplib to get a directory listing, portably

Try to use ftp.nlst(dir).

However, note that if the folder is empty, it might throw an error:

files = []

try:
    files = ftp.nlst()
except ftplib.error_perm, resp:
    if str(resp) == "550 No files found":
        print "No files in this directory"
    else:
        raise

for f in files:
    print f

How to remove folders with a certain name

Combining multiple answers, here's a command that works on both Linux and MacOS

rm -rf $(find . -type d -name __pycache__)

What is the purpose of mvnw and mvnw.cmd files?

By far the best option nowadays would be using a maven container as a builder tool. A mvn.sh script like this would be enough:

#!/bin/bash
docker run --rm -ti \
 -v $(pwd):/opt/app \
 -w /opt/app \
 -e TERM=xterm \
 -v $HOME/.m2:/root/.m2 \
 maven mvn "$@"

How to reference Microsoft.Office.Interop.Excel dll?

Instead of early binding the reference, there's an open source project called NetOffice that abstracts this from your project, making life much easier. That way you don't have to rely on your users having a specific version of Office installed.

NetOffice Codeplex site.

Caused by: java.security.UnrecoverableKeyException: Cannot recover key

Check if password you are using is correct one by running below command

keytool -keypasswd -new temp123 -keystore awsdemo-keystore.jks -storepass temp123 -alias movie-service -keypass changeit

If you are getting below error then your password is wrong

keytool error: java.security.UnrecoverableKeyException: Cannot recover key

phpexcel to download

Use this call

$objWriter->save('php://output');

To output the XLS sheet to the page you are on, just make sure that the page you are on has no other echo's,print's, outputs.

Check if checkbox is NOT checked on click - jQuery

Try this:

if(!$(this).is(':checked'))

demo

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

I was inserting script tags dynamically with this usual alternative to eval and simply set a global property currentComponentScript right before adding to the DOM.

  const old = el.querySelector("script")[0];
  const replacement = document.createElement("script");
  replacement.setAttribute("type", "module");
  replacement.appendChild(document.createTextNode(old.innerHTML));
  window.currentComponentScript = replacement;
  old.replaceWith(replacement);

Doesn't work in a loop though. The DOM doesn't run the scripts until the next macrotask so a batch of them will only see the last value set. You'd have to setTimeout the whole paragraph, and then setTimeout the next one after the previous finishes. I.e. chain the setTimeouts, not just call setTimeout multiple times in a row from a loop.

How to Get a Specific Column Value from a DataTable?

string countryName = "USA";
DataTable dt = new DataTable();
int id = (from DataRow dr in dt.Rows
              where (string)dr["CountryName"] == countryName
              select (int)dr["id"]).FirstOrDefault();

C char array initialization

This is not how you initialize an array, but for:

  1. The first declaration:

    char buf[10] = "";
    

    is equivalent to

    char buf[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    
  2. The second declaration:

    char buf[10] = " ";
    

    is equivalent to

    char buf[10] = {' ', 0, 0, 0, 0, 0, 0, 0, 0, 0};
    
  3. The third declaration:

    char buf[10] = "a";
    

    is equivalent to

    char buf[10] = {'a', 0, 0, 0, 0, 0, 0, 0, 0, 0};
    

As you can see, no random content: if there are fewer initializers, the remaining of the array is initialized with 0. This the case even if the array is declared inside a function.

How can I get the latest JRE / JDK as a zip file rather than EXE or MSI installer?

Download JAVA SE with JDK

  1. Download jdk from Oracle website: http://www.oracle.com/technetwork/java/javase/downloads/index.html
  2. Unzip the exe. For example: jdk-8u5-windows-x64.exe
  3. Unzip the following file: tools.zip (found under the unzipped folder) to the desired JAVA_HOME.
  4. Update the JAVA_HOME environment variable to point to your desired path.

Tested for version: jdk-7u60-windows-x64.exe, jdk-7u60-windows-x64.exe

Download JAVA EE with JDK

  1. Download jdk from Oracle website: http://www.oracle.com/technetwork/java/javaee/downloads/index.html
  2. Unzip the exe. For example: jdk-7u55-windows-x64.exe
  3. Unzip the following file: Product\Packages\jdk.zip (found under the unzipped folder) to the desired JAVA_HOME.
  4. Update the JAVA_HOME environment variable to point to your desired path.

Tested for version: jdk-7u55-windows-x64.exe

Is it possible to add an array or object to SharedPreferences on Android

This is the shared preferences code i use successfully, Refer this link:

  public class MainActivity extends Activity {

private static final int RESULT_SETTINGS = 1;
Button button;
public String a="dd";

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

 button = (Button) findViewById(R.id.btnoptions);


setContentView(R.layout.activity_main);

  // showUserSettings();
  }

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.settings, menu);
return true;
 }

@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {

case R.id.menu_settings:
 Intent i = new Intent(this, UserSettingActivity.class);
 startActivityForResult(i, RESULT_SETTINGS);
 break;

 }

return true;
}

@Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data)     {
  super.onActivityResult(requestCode, resultCode, data);

 switch (requestCode) {
 case RESULT_SETTINGS:
 showUserSettings();
 break;

 } 

  }

  private void showUserSettings() {
 SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(this);

 StringBuilder builder = new StringBuilder();

 builder.append("\n Pet: "
  + sharedPrefs.getString("prefpetname", "NULL"));

 builder.append("\n Address:"
 + sharedPrefs.getString("prefaddress","NULL" ));

 builder.append("\n Your name: "
 + sharedPrefs.getString("prefname", "NULL"));

 TextView settingsTextView = (TextView) findViewById(R.id.textUserSettings);


  settingsTextView.setText(builder.toString());


    }

   }

HAPPY CODING!

How to redirect 'print' output to a file using python?

If you are using Linux I suggest you to use the tee command. The implementation goes like this:

python python_file.py | tee any_file_name.txt

If you don't want to change anything in the code, I think this might be the best possible solution. You can also implement logger but you need do some changes in the code.

Change WPF window background image in C# code

img.UriSource = new Uri("pack://application:,,,/images/" + fileName, UriKind.Absolute);

Javascript: 'window' is not defined

The window object represents an open window in a browser. Since you are not running your code within a browser, but via Windows Script Host, the interpreter won't be able to find the window object, since it does not exist, since you're not within a web browser.

How to read a local text file?

How to read a local file?

By using this you will load a file by loadText() then JS will asynchronously wait until the file is read and loaded after that it will execture readText() function allowing you to continue with your normal JS logic (you can also write a try catch block on the loadText() function in the case any error arises) but for this example I keep it at minimal.

async function loadText(url) {
    text = await fetch(url);
    //awaits for text.text() prop 
    //and then sends it to readText()
    readText(await text.text());
}

function readText(text){
    //here you can continue with your JS normal logic
    console.log(text);
}

loadText('test.txt');

SQL server query to get the list of columns in a table along with Data types, NOT NULL, and PRIMARY KEY constraints

In SQL 2012 you can use:

EXEC sp_describe_first_result_set N'SELECT * FROM [TableName]'

This will give you the column names along with their properties.

$http.get(...).success is not a function

This might be redundant but the above most voted answer says .then(function (success) and that didn't work for me as of Angular version 1.5.8. Instead use response then inside the block response.data got me my json data I was looking for.

$http({
    method: 'get', 
    url: 'data/data.json'
}).then(function (response) {
    console.log(response, 'res');
    data = response.data;
},function (error){
    console.log(error, 'can not get data.');
});

What is this weird colon-member (" : ") syntax in the constructor?

You are correct, this is indeed a way to initialize member variables. I'm not sure that there's much benefit to this, other than clearly expressing that it's an initialization. Having a "bar=num" inside the code could get moved around, deleted, or misinterpreted much more easily.

How to split a comma separated string and process in a loop using JavaScript

Try the following snippet:

var mystring = 'this,is,an,example';
var splits = mystring.split(",");
alert(splits[0]); // output: this

Determine if JavaScript value is an "integer"?

Here's a polyfill for the Number predicate functions:

"use strict";

Number.isNaN = Number.isNaN ||
    n => n !== n; // only NaN

Number.isNumeric = Number.isNumeric ||
    n => n === +n; // all numbers excluding NaN

Number.isFinite = Number.isFinite ||
    n => n === +n               // all numbers excluding NaN
      && n >= Number.MIN_VALUE  // and -Infinity
      && n <= Number.MAX_VALUE; // and +Infinity

Number.isInteger = Number.isInteger ||
    n => n === +n              // all numbers excluding NaN
      && n >= Number.MIN_VALUE // and -Infinity
      && n <= Number.MAX_VALUE // and +Infinity
      && !(n % 1);             // and non-whole numbers

Number.isSafeInteger = Number.isSafeInteger ||
    n => n === +n                     // all numbers excluding NaN
      && n >= Number.MIN_SAFE_INTEGER // and small unsafe numbers
      && n <= Number.MAX_SAFE_INTEGER // and big unsafe numbers
      && !(n % 1);                    // and non-whole numbers

All major browsers support these functions, except isNumeric, which is not in the specification because I made it up. Hence, you can reduce the size of this polyfill:

"use strict";

Number.isNumeric = Number.isNumeric ||
    n => n === +n; // all numbers excluding NaN

Alternatively, just inline the expression n === +n manually.

How do I concatenate strings with variables in PowerShell?

You could use the PowerShell equivalent of String.Format - it's usually the easiest way to build up a string. Place {0}, {1}, etc. where you want the variables in the string, put a -f immediately after the string and then the list of variables separated by commas.

Get-ChildItem c:\code|%{'{0}\{1}\{2}.dll' -f $_.fullname,$buildconfig,$_.name}

(I've also taken the dash out of the $buildconfig variable name as I have seen that causes issues before too.)

How to scroll HTML page to given anchor?

$(document).ready ->
  $("a[href^='#']").click ->
    $(document.body).animate
      scrollTop: $($(this).attr("href")).offset().top, 1000

favicon.png vs favicon.ico - why should I use PNG instead of ICO?

Avoid PNG in any case if you want reliable IE6 compatibility.

Pass react component as props

Using this.props.children is the idiomatic way to pass instantiated components to a react component

const Label = props => <span>{props.children}</span>
const Tab = props => <div>{props.children}</div>
const Page = () => <Tab><Label>Foo</Label></Tab>

When you pass a component as a parameter directly, you pass it uninstantiated and instantiate it by retrieving it from the props. This is an idiomatic way of passing down component classes which will then be instantiated by the components down the tree (e.g. if a component uses custom styles on a tag, but it wants to let the consumer choose whether that tag is a div or span):

const Label = props => <span>{props.children}</span>
const Button = props => {
    const Inner = props.inner; // Note: variable name _must_ start with a capital letter 
    return <button><Inner>Foo</Inner></button>
}
const Page = () => <Button inner={Label}/>

If what you want to do is to pass a children-like parameter as a prop, you can do that:

const Label = props => <span>{props.content}</span>
const Tab = props => <div>{props.content}</div>
const Page = () => <Tab content={<Label content='Foo' />} />

After all, properties in React are just regular JavaScript object properties and can hold any value - be it a string, function or a complex object.

JavaScript getElementByID() not working

At the point you are calling your function, the rest of the page has not rendered and so the element is not in existence at that point. Try calling your function on window.onload maybe. Something like this:

<html>
<head>
    <title></title>
    <script type="text/javascript">
        window.onload = function(){
           var refButton = document.getElementById("btnButton");

            refButton.onclick = function() {
                alert('I am clicked!');
            }
        };
    </script>
</head>
<body>
    <form id="form1">
    <div>
        <input id="btnButton" type="button" value="Click me"/>
    </div>
    </form>
</body>
</html>

How to change shape color dynamically?

This works for me, with an initial xml resource:

example.setBackgroundResource(R.drawable.myshape);
GradientDrawable gd = (GradientDrawable) example.getBackground().getCurrent();
gd.setColor(Color.parseColor("#000000"));
gd.setCornerRadii(new float[]{30, 30, 30, 30, 0, 0, 30, 30});
gd.setStroke(2, Color.parseColor("#00FFFF"), 5, 6);

Result of the above: http://i.stack.imgur.com/hKUR7.png

How do I create a folder in a GitHub repository?

Here is an easy and quick, presently available browser approach to creating folders inside a repository

1)Click the repository / create a new repository.

2)Click create Add file and then create a new file.

3)Give the folder name you want to create with a ' / ' mark and then add a file in it

4)Commit the changes

Click here for the visual representation of the above steps in order.

Datatable date sorting dd/mm/yyyy issue

This solution is completely wrong. You can't convert a date to a number just adding each component of the date. If you try this logic for example with the following dates, you'll see it won't match correctly:

20/01/2014 = 2035 15/02/2014 = 2031

Witch date comes first, ascending? 20 of january? Not according to this logic :P

The correct way of doing the parsedate method is to convert the string to a valid datetime, and them use the getTime function to properly order the table.

var day = a.split('/')[0]
var month = a.split('/')[1]
var year = a.split('/')[2]

var date = new Date(month + "/" + day + "/" + year)
return date.getTime()

Guzzle 6: no more json() method for responses

I use $response->getBody()->getContents() to get JSON from response. Guzzle version 6.3.0.

How to input matrix (2D list) in Python?

The problem is on the initialization step.

for i in range (0,m):
  matrix[i] = columns

This code actually makes every row of your matrix refer to the same columns object. If any item in any column changes - every other column will change:

>>> for i in range (0,m):
...     matrix[i] = columns
... 
>>> matrix
[[0, 0, 0], [0, 0, 0]]
>>> matrix[1][1] = 2
>>> matrix
[[0, 2, 0], [0, 2, 0]]

You can initialize your matrix in a nested loop, like this:

matrix = []
for i in range(0,m):
    matrix.append([])
    for j in range(0,n):
        matrix[i].append(0)

or, in a one-liner by using list comprehension:

matrix = [[0 for j in range(n)] for i in range(m)]

or:

matrix = [x[:] for x in [[0]*n]*m]

See also:

Hope that helps.

How to SSH to a VirtualBox guest externally through a host?

SSH Back to Your Home / Office VirtualBox Guest Machine From The INTERNET

The answers provided by other users here : How to SSH to a VirtualBox guest externally through a host?

... helped me to accomplish the task of connecting from out on the internet to my home computer's guest machine. You should be able to connect using computers, tablets, and smart phones (android, IPhone,etc). I add a few more step in case it might be helpful to someone else:

Here is a quick diagram of my setup:

  • Remote device ---> INTERNET --> MODEM --> ROUTER --> HOST MACHINE --> GUEST VM

  • Remote device (ssh client) ---> PASS THRU DEVICES ---> GUEST VM (ssh server)

  • Remote device (leave ssh port 3022) ---> INTERNET --> MODEM --> ROUTER (FWD frm:p3022 to:p3022)--> HOST MACHINE (FWD frm:p3022 to:p22) --> GUEST VM (arrive ssh port 22)

The key for me was to realize that ALL connections was PASSING-THROUGH intermediary devices to get from my remote PC to my guest virtual-machine at home --Hence port forwarding!

Notes: * Need ssh client to request a secure connection and a running ssh server to process the secure connection.

  • I will forward the port 3022 as used in the chosen answer from above.

  • Enter your IPs where needed (home modem/router, host IP, guest IP,etc.), Names chosen are just examples-use or change.

1.Create ssh tunnel to port 3022 on your modem's IP / router's external IP address.

ssh client/device possible commands: ssh -p 3022 user-name@home_external_IP

2.Port forward = we are passing thru the connection from router to host machine

  • Also make sure firewall /IPtable rules on router is allowing ports to be forward (open if needed)

  • Router's Pfwd SCREEN required entries: AppName:SSH_Fwd, Port_from: 3022, Protocol:both (UDP/TCP), IP_address:hostIP_address, Port_to:3022, everything else can be blank

DD-WRT router software resources / Info:

3.Host Machine Firewall: open port 3022 #so forwarded port can pass thru to guest machine

  • Host Machine: Install VirtualBox, guest additions, and guest machine if not done already

  • Configure guest machine and then follow the Network section below

  • I used VirtualBox GUI to setup guest's network- easier than CLI

  • If you want to use other methods refer to : VirtualBox/manual/ch06.html#natforward

4.Some suggest using Network Bridge adapter for guest = access to LAN and other machines on your LAN. This also pose an increase security risk, because now your guest machine is now exposed to LAN machines and possibly the INTERNET hackers if firewall not setup properly. So I selected Network adapter attached to NAT for less exposure to bridged security risks.

On the guest machine do the following:

  • Guest Machine VirtualBox Network settings: Adapter 1: Attached to NAT
  • Guest Machine VirtualBox Port Forwarding Rule: Name:External_SSH, Protocol:TCP, Host Port: 3022, Guest Port 22, Host&guest IPs:leave blank
  • click on advance in Network section then click on Port forwarding to enter rules
  • Guest Machine Firewall: open port 22 #so ssh connection can enter
  • Guest Machine: Make sure that ssh server is installed, configured properly, and running
  • LINUX test to see if ssh server running w/command: sudo service ssh status
  • Can check netstat to see if connection made to port 22 on the guest machine

Also there are different ssh servers and clients depending on platform using.

  • wikipedia/Secure_Shell
  • wikipedia/Comparison_of_SSH_servers
  • wikipedia/Comparison_of_SSH_clients

For Ubuntu Users:

  • ubuntu community: SSHOpenSSH/Configuring
  • ubuntu/community: OpenSSH/Keys

That should be it. If I made a mistake or want to add anything -feel free to do so-- I am still a noob.

Hope this helps someone. Good luck!

How to uninstall/upgrade Angular CLI?

Run this command

npm uninstall angular-cli

What are the differences in die() and exit() in PHP?

This output from https://3v4l.org demonstrates that die and exit are functionally identical. enter image description here

How do I initialize the base (super) class?

As of python 3.5.2, you can use:

class C(B):
def method(self, arg):
    super().method(arg)    # This does the same thing as:
                           # super(C, self).method(arg)

https://docs.python.org/3/library/functions.html#super

The character encoding of the plain text document was not declared - mootool script

I got this error using Spring Boot (in Mozilla),

because I was just testing some basic controller -> service -> repository communication by directly returning some entities from the database to the browser (as JSON).

I forgot to put data in the database, so my method wasn't returning anything... and I got this error.

Now that I put some data in my db, it works fine (the error is removed). :D

Switch statement multiple cases in JavaScript

This works in regular JavaScript:

function theTest(val) {
  var answer = "";
  switch( val ) {
    case 1: case 2: case 3:
      answer = "Low";
      break;
    case 4: case 5: case 6:
      answer = "Mid";
      break;
    case 7: case 8: case 9:
      answer = "High";
      break;
    default:
      answer = "Massive or Tiny?";
  }
  return answer;
}

theTest(9);

The name 'InitializeComponent' does not exist in the current context

I had the same issue, I had to convert my shared project into a portable class library.

No connection string named 'MyEntities' could be found in the application config file

I had this error when attempting to use EF within an AutoCAD plugin. CAD plugins get the connection string from the acad.exe.config file. Add the connect string as mentioned above to the acad config file and it works.

Credit goes to Norman.Yuan from ADN.Network.

adb devices command not working

Every answer I've read indicates the SUBSYSTEM=="usb". However, my (perhaps ancient) udev needed this to be changed to DRIVER=="usb". At last I can run the adb server as a non-root user... yay.

It can be instructive to look at the output of udevmonitor --env, followed by the output of

udevinfo -a -p <DEVICE_PATH_AS_REPORTED_BY-udevmonitor>

Timestamp Difference In Hours for PostgreSQL

postgresql get seconds difference between timestamps

SELECT (
    (extract (epoch from (
        '2012-01-01 18:25:00'::timestamp - '2012-01-01 18:25:02'::timestamp
                         )
             )
    )
)::integer

which prints:

-2

Because the timestamps are two seconds apart. Take the number and divide by 60 to get minutes, divide by 60 again to get hours.

How to put multiple statements in one line?

You could use the built-in exec statement, eg.:

exec("try: \n \t if sam[0] != 'harry': \n \t\t print('hello',  sam) \nexcept: pass")

Where \n is a newline and \t is used as indentation (a tab).
Also, you should count the spaces you use, so your indentation matches exactly.

However, as all the other answers already said, this is of course only to be used when you really have to put it on one line.

exec is quite a dangerous statement (especially when building a webapp) since it allows execution of arbitrary Python code.

What is the easiest way to get current GMT time in Unix timestamp format?

from datetime import datetime as dt
dt.utcnow().strftime("%s")

Output:

1544524990

How does bitshifting work in Java?

You can't write binary literals like 00101011 in Java so you can write it in hexadecimal instead:

byte x = 0x2b;

To calculate the result of x >> 2 you can then just write exactly that and print the result.

System.out.println(x >> 2);

Get yesterday's date using Date

Try this one:

private String toDate() {
    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

    // Create a calendar object with today date. Calendar is in java.util pakage.
    Calendar calendar = Calendar.getInstance();

    // Move calendar to yesterday
    calendar.add(Calendar.DATE, -1);

    // Get current date of calendar which point to the yesterday now
    Date yesterday = calendar.getTime();

    return dateFormat.format(yesterday).toString();
}

Sort Pandas Dataframe by Date

@JAB's answer is fast and concise. But it changes the DataFrame you are trying to sort, which you may or may not want.

(Note: You almost certainly will want it, because your date columns should be dates, not strings!)

In the unlikely event that you don't want to change the dates into dates, you can also do it a different way.

First, get the index from your sorted Date column:

In [25]: pd.to_datetime(df.Date).order().index
Out[25]: Int64Index([0, 2, 1], dtype='int64')

Then use it to index your original DataFrame, leaving it untouched:

In [26]: df.ix[pd.to_datetime(df.Date).order().index]
Out[26]: 
        Date Symbol
0 2015-02-20      A
2 2015-08-21      A
1 2016-01-15      A

Magic!

Note: for Pandas versions 0.20.0 and later, use loc instead of ix, which is now deprecated.

Reading data from DataGridView in C#

something like

for (int rows = 0; rows < dataGrid.Rows.Count; rows++)
{
     for (int col= 0; col < dataGrid.Rows[rows].Cells.Count; col++)
    {
        string value = dataGrid.Rows[rows].Cells[col].Value.ToString();

    }
} 

example without using index

foreach (DataGridViewRow row in dataGrid.Rows)
{ 
    foreach (DataGridViewCell cell in row.Cells)
    {
        string value = cell.Value.ToString();

    }
}

Minimal web server using netcat

I had the same need/problem but nothing here worked for me (or I didn't understand everything), so this is my solution.

I post my minimal_http_server.sh (working with my /bin/bash (4.3.11) but not /bin/sh because of the redirection):

rm -f out
mkfifo out
trap "rm -f out" EXIT
while true
do
  cat out | nc -l 1500 > >( # parse the netcat output, to build the answer redirected to the pipe "out".
    export REQUEST=
    while read -r line
    do
      line=$(echo "$line" | tr -d '\r\n')

      if echo "$line" | grep -qE '^GET /' # if line starts with "GET /"
      then
        REQUEST=$(echo "$line" | cut -d ' ' -f2) # extract the request
      elif [ -z "$line" ] # empty line / end of request
      then
        # call a script here
        # Note: REQUEST is exported, so the script can parse it (to answer 200/403/404 status code + content)
        ./a_script.sh > out
      fi
    done
  )
done

And my a_script.sh (with your need):

#!/bin/bash

echo -e "HTTP/1.1 200 OK\r"
echo "Content-type: text/html"
echo

date

C# Get/Set Syntax Usage

I do not understand what this is unclear

Properties are members that provide a flexible mechanism to read, write, or compute the values of private fields. Properties can be used as though they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily while still providing the safety and flexibility of methods.

In this example, the class TimePeriod stores a time period. Internally the class stores the time in seconds, but a property called Hours is provided that allows a client to specify a time in hours. The accessors for the Hours property perform the conversion between hours and seconds.

Example

class TimePeriod
{
    private double seconds;

    public double Hours
    {
        get { return seconds / 3600; }
        set { seconds = value * 3600; }
    }
}

class Program
{
    static void Main()
    {
        TimePeriod t = new TimePeriod();

        // Assigning the Hours property causes the 'set' accessor to be called.
        t.Hours = 24;

        // Evaluating the Hours property causes the 'get' accessor to be called.
        System.Console.WriteLine("Time in hours: " + t.Hours);
    }
}

Properties Overview

Properties enable a class to expose a public way of getting and setting values, while hiding implementation or verification code.

A get property accessor is used to return the property value, and a set accessor is used to assign a new value. These accessors can have different access levels.

The value keyword is used to define the value being assigned by the set indexer.

Properties that do not implement a set method are read only.

http://msdn.microsoft.com/en-US/library/x9fsa0sw%28v=vs.80%29.aspx

What's the difference between align-content and align-items?

according to what I understood from here:

when you use align-item or justify-item, you are adjusting "the content inside a grid item along the column axis or row axis respectively.

But: if you use align-content or justify-content, you are setting the position a grid along the column axis or the row axis. it occurs when you have a grid in a bigger container and width or height are inflexible (using px).

External resource not being loaded by AngularJs

I ran into the same problem using Videogular. I was getting the following when using ng-src:

Error: [$interpolate:interr] Can't interpolate: {{url}}
Error: [$sce:insecurl] Blocked loading resource from url not allowed by $sceDelegate policy

I fixed the problem by writing a basic directive:

angular.module('app').directive('dynamicUrl', function () {
return {
  restrict: 'A',
  link: function postLink(scope, element, attrs) {
    element.attr('src', scope.content.fullUrl);
  }
};
});

The html:

 <div videogular vg-width="200" vg-height="300" vg-theme="config.theme">
    <video class='videoPlayer' controls preload='none'>
          <source dynamic-url src='' type='{{ content.mimeType }}'>
    </video>
 </div>

add image to uitableview cell

Try this code:--

UIImageView *imv = [[UIImageView alloc]initWithFrame:CGRectMake(3,2, 20, 25)];
imv.image=[UIImage imageNamed:@"arrow2.png"];
[cell addSubview:imv];
[imv release];

CSS Auto hide elements after 5 seconds

Why not try fadeOut?

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $('#plsme').fadeOut(5000); // 5 seconds x 1000 milisec = 5000 milisec_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<div id='plsme'>Loading... Please Wait</div>
_x000D_
_x000D_
_x000D_

fadeOut (Javascript Pure):

How to make fadeOut effect with pure JavaScript