Programs & Examples On #Packaging

Packaging is a configuration management process involved with capturing the knowledge needed to install or uninstall software on a target system.

Non-resolvable parent POM for Could not find artifact and 'parent.relativePath' points at wrong local POM

Give the relative path URL value to the pom.xml file
../parentfoldername/pom.xml

Including dependencies in a jar with Maven

If you want to do an executable jar file, them need set the main class too. So the full configuration should be.

    <plugins>
            <plugin>
                 <artifactId>maven-assembly-plugin</artifactId>
                 <executions>
                     <execution>
                          <phase>package</phase>
                          <goals>
                              <goal>single</goal>
                          </goals>
                      </execution>
                  </executions>
                  <configuration>
                       <!-- ... -->
                       <archive>
                           <manifest>
                                 <mainClass>fully.qualified.MainClass</mainClass>
                           </manifest>
                       </archive>
                       <descriptorRefs>
                           <descriptorRef>jar-with-dependencies</descriptorRef>
                      </descriptorRefs>
                 </configuration>
         </plugin>
   </plugins>

How to create Python egg file

I think you should use python wheels for distribution instead of egg now.

Wheels are the new standard of python distribution and are intended to replace eggs. Support is offered in pip >= 1.4 and setuptools >= 0.8.

How to build a Debian/Ubuntu package from source?

For what you want to do, you probably want to use the debian source diff, so your package is similar to the official one apart from the upstream version used. You can download the source diff from packages.debian.org, or can get it along with the .dsc and the original source archive by using "apt-get source".

Then you unpack your new version of the upstream source, change into that directory, and apply the diff you downloaded by doing

zcat ~/downloaded.diff.gz | patch -p1
chmod +x debian/rules

Then make the changes you wanted to compile options, and build the package by doing

dpkg-buildpackage -rfakeroot -us -uc

Process to convert simple Python script into Windows executable

1) Get py2exe from here, according to your Python version.

2) Make a file called "setup.py" in the same folder as the script you want to convert, having the following code:

from distutils.core import setup
import py2exe
setup(console=['myscript.py']) #change 'myscript' to your script

3) Go to command prompt, navigate to that folder, and type:

python setup.py py2exe

4) It will generate a "dist" folder in the same folder as the script. This folder contains the .exe file.

py2exe - generate single executable file

The way to do this using py2exe is to use the bundle_files option in your setup.py file. For a single file you will want to set bundle_files to 1, compressed to True, and set the zipfile option to None. That way it creates one compressed file for easy distribution.

Here is a more complete description of the bundle_file option quoted directly from the py2exe site*

Using "bundle_files" and "zipfile"

An easier (and better) way to create single-file executables is to set bundle_files to 1 or 2, and to set zipfile to None. This approach does not require extracting files to a temporary location, which provides much faster program startup.

Valid values for bundle_files are:

  • 3 (default) don't bundle
  • 2 bundle everything but the Python interpreter
  • 1 bundle everything, including the Python interpreter

If zipfile is set to None, the files will be bundle within the executable instead of library.zip.

Here is a sample setup.py:

from distutils.core import setup
import py2exe, sys, os

sys.argv.append('py2exe')

setup(
    options = {'py2exe': {'bundle_files': 1, 'compressed': True}},
    windows = [{'script': "single.py"}],
    zipfile = None,
)

How to secure phpMyAdmin

The biggest threat is that an attacker could leverage a vulnerability such as; directory traversal, or using SQL Injection to call load_file() to read the plain text username/password in the configuration file and then Login using phpmyadmin or over tcp port 3306. As a pentester I have used this attack pattern to compromise a system.

Here is a great way to lock down phpmyadmin:

  • DO NOT ALLOW REMOTE ROOT LOGINS! Instead phpmyadmin can be configured to use "Cookie Auth" to limit what user can access the system. If you need some root privileges, create a custom account that can add/drop/create but doesn't have grant or file_priv.
  • Remove file_priv permissions from every account. file_priv is one of the most dangerous privileges in MySQL because it allows an attacker to read files or upload a backdoor.
  • Whitelist IP address who have access to the phpmyadmin interface. Here is an example .htaccess reulset:
Order deny,allow
Deny from all
allow from 199.166.210.1
  • Do not have a predictable file location like: http://127.0.0.1/phpmyadmin. Vulnerability scanners like Nessus/Nikto/Acunetix/w3af will scan for this.

  • Firewall off tcp port 3306 so that it cannot be accessed by an attacker.

  • Use HTTPS, otherwise data and passwords can be leaked to an attacker. If you don't want to fork out the $30 for a cert, then use a self-signed. You'll accept it once, and even if it was changed due to a MITM you'll be notified.

How do I pass named parameters with Invoke-Command?

-ArgumentList is based on use with scriptblock commands, like:

Invoke-Command -Cn (gc Servers.txt) {param($Debug=$False, $Clear=$False) C:\Scripts\ArchiveEventLogs\ver5\ArchiveEventLogs.ps1 } -ArgumentList $False,$True

When you call it with a -File it still passes the parameters like a dumb splatted array. I've submitted a feature request to have that added to the command (please vote that up).

So, you have two options:

If you have a script that looked like this, in a network location accessible from the remote machine (note that -Debug is implied because when I use the Parameter attribute, the script gets CmdletBinding implicitly, and thus, all of the common parameters):

param(
   [Parameter(Position=0)]
   $one
,
   [Parameter(Position=1)]
   $two
,
   [Parameter()]
   [Switch]$Clear
)

"The test is for '$one' and '$two' ... and we $(if($DebugPreference -ne 'SilentlyContinue'){"will"}else{"won't"}) run in debug mode, and we $(if($Clear){"will"}else{"won't"}) clear the logs after."

Without getting hung up on the meaning of $Clear ... if you wanted to invoke that you could use either of the following Invoke-Command syntaxes:

icm -cn (gc Servers.txt) { 
    param($one,$two,$Debug=$False,$Clear=$False)
    C:\Scripts\ArchiveEventLogs\ver5\ArchiveEventLogs.ps1 @PSBoundParameters
} -ArgumentList "uno", "dos", $false, $true

In that one, I'm duplicating ALL the parameters I care about in the scriptblock so I can pass values. If I can hard-code them (which is what I actually did), there's no need to do that and use PSBoundParameters, I can just pass the ones I need to. In the second example below I'm going to pass the $Clear one, just to demonstrate how to pass switch parameters:

icm -cn $Env:ComputerName { 
    param([bool]$Clear)
    C:\Scripts\ArchiveEventLogs\ver5\ArchiveEventLogs.ps1 "uno" "dos" -Debug -Clear:$Clear
} -ArgumentList $(Test-Path $Profile)

The other option

If the script is on your local machine, and you don't want to change the parameters to be positional, or you want to specify parameters that are common parameters (so you can't control them) you will want to get the content of that script and embed it in your scriptblock:

$script = [scriptblock]::create( @"
param(`$one,`$two,`$Debug=`$False,`$Clear=`$False)
&{ $(Get-Content C:\Scripts\ArchiveEventLogs\ver5\ArchiveEventLogs.ps1 -delimiter ([char]0)) } @PSBoundParameters
"@ )

Invoke-Command -Script $script -Args "uno", "dos", $false, $true

PostScript:

If you really need to pass in a variable for the script name, what you'd do will depend on whether the variable is defined locally or remotely. In general, if you have a variable $Script or an environment variable $Env:Script with the name of a script, you can execute it with the call operator (&): &$Script or &$Env:Script

If it's an environment variable that's already defined on the remote computer, that's all there is to it. If it's a local variable, then you'll have to pass it to the remote script block:

Invoke-Command -cn $Env:ComputerName { 
    param([String]$Script, [bool]$Clear)
    & $ScriptPath "uno" "dos" -Debug -Clear:$Clear
} -ArgumentList $ScriptPath, (Test-Path $Profile)

Java balanced expressions check {[()]}

I hope this code can help:

import java.util.Stack;

public class BalancedParenthensies {

    public static void main(String args[]) {

        System.out.println(balancedParenthensies("{(a,b)}"));
        System.out.println(balancedParenthensies("{(a},b)"));
        System.out.println(balancedParenthensies("{)(a,b}"));
    }

    public static boolean balancedParenthensies(String s) {
        Stack<Character> stack  = new Stack<Character>();
        for(int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if(c == '[' || c == '(' || c == '{' ) {     
                stack.push(c);
            } else if(c == ']') {
                if(stack.isEmpty() || stack.pop() != '[') {
                    return false;
                }
            } else if(c == ')') {
                if(stack.isEmpty() || stack.pop() != '(') {
                    return false;
                }           
            } else if(c == '}') {
                if(stack.isEmpty() || stack.pop() != '{') {
                    return false;
                }
            }

        }
        return stack.isEmpty();
    }
}

What is the best way to insert source code examples into a Microsoft Word document?

There is an easy way if you want simple code formatting.

  1. Open word> Insert tab> click on "Get Add-ins"
  2. search for "Content mixer" 3.click on "Add"

Then content mixer add will open automatically and you can copy paste your code in there and click on "Insert" to insert it in word doc.

How to tell if string starts with a number with Python?

sometimes, you can use regex

>>> import re
>>> re.search('^\s*[0-9]',"0abc")
<_sre.SRE_Match object at 0xb7722fa8>

Provisioning Profiles menu item missing from Xcode 5

These settings have now moved to Preferences > Accounts:

enter image description here

Can you find all classes in a package using reflection?

Spring

This example is for Spring 4, but you can find the classpath scanner in earlier versions as well.

// create scanner and disable default filters (that is the 'false' argument)
final ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
// add include filters which matches all the classes (or use your own)
provider.addIncludeFilter(new RegexPatternTypeFilter(Pattern.compile(".*")));

// get matching classes defined in the package
final Set<BeanDefinition> classes = provider.findCandidateComponents("my.package.name");

// this is how you can load the class type from BeanDefinition instance
for (BeanDefinition bean: classes) {
    Class<?> clazz = Class.forName(bean.getBeanClassName());
    // ... do your magic with the class ...
}

Google Guava

Note: In version 14, the API is still marked as @Beta, so beware in production code.

final ClassLoader loader = Thread.currentThread().getContextClassLoader();

for (final ClassPath.ClassInfo info : ClassPath.from(loader).getTopLevelClasses()) {
  if (info.getName().startsWith("my.package.")) {
    final Class<?> clazz = info.load();
    // do something with your clazz
  }
}

How to get duplicate items from a list using LINQ?

I wrote this extension method based off @Lee's response to the OP. Note, a default parameter was used (requiring C# 4.0). However, an overloaded method call in C# 3.0 would suffice.

/// <summary>
/// Method that returns all the duplicates (distinct) in the collection.
/// </summary>
/// <typeparam name="T">The type of the collection.</typeparam>
/// <param name="source">The source collection to detect for duplicates</param>
/// <param name="distinct">Specify <b>true</b> to only return distinct elements.</param>
/// <returns>A distinct list of duplicates found in the source collection.</returns>
/// <remarks>This is an extension method to IEnumerable&lt;T&gt;</remarks>
public static IEnumerable<T> Duplicates<T>
         (this IEnumerable<T> source, bool distinct = true)
{
     if (source == null)
     {
        throw new ArgumentNullException("source");
     }

     // select the elements that are repeated
     IEnumerable<T> result = source.GroupBy(a => a).SelectMany(a => a.Skip(1));

     // distinct?
     if (distinct == true)
     {
        // deferred execution helps us here
        result = result.Distinct();
     }

     return result;
}

How to extract the file name from URI returned from Intent.ACTION_GET_CONTENT?

My version of the answer is actually very similar to the @Stefan Haustein. I found the answer on Android Developer page Retrieving File Information; the information here is even more condensed on this specific topic than on Storage Access Framework guide site. In the result from the query the column index containing file name is OpenableColumns.DISPLAY_NAME. None of other answers/solutions for column indexes worked for me. Below is the sample function:

 /**
 * @param uri uri of file.
 * @param contentResolver access to server app.
 * @return the name of the file.
 */
def extractFileName(uri: Uri, contentResolver: ContentResolver): Option[String] = {

    var fileName: Option[String] = None
    if (uri.getScheme.equals("file")) {

        fileName = Option(uri.getLastPathSegment)
    } else if (uri.getScheme.equals("content")) {

        var cursor: Cursor = null
        try {

            // Query the server app to get the file's display name and size.
            cursor = contentResolver.query(uri, null, null, null, null)

            // Get the column indexes of the data in the Cursor,
            // move to the first row in the Cursor, get the data.
            if (cursor != null && cursor.moveToFirst()) {

                val nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
                fileName = Option(cursor.getString(nameIndex))
            }

        } finally {

            if (cursor != null) {
                cursor.close()
            }

        }

    }

    fileName
}

Python dictionary: Get list of values for list of keys

Try This:

mydict = {'one': 1, 'two': 2, 'three': 3}
mykeys = ['three', 'one','ten']
newList=[mydict[k] for k in mykeys if k in mydict]
print newList
[3, 1]

Windows batch: formatted date into variable

Due to date and time format is location specific info, retrieving them from %date% and %time% variables will need extra effort to parse the string with format transform into consideration. A good idea is to use some API to retrieve the data structure and parse as you wish. WMIC is a good choice. Below example use Win32_LocalTime. You can also use Win32_CurrentTime or Win32_UTCTime.

@echo off  
SETLOCAL ENABLEDELAYEDEXPANSION  
for /f %%x in ('wmic path Win32_LocalTime get /format:list ^| findstr "="') do set %%x  
set yyyy=0000%Year%  
set mmmm=0000%Month%  
set dd=00%Day%  
set hh=00%Hour%  
set mm=00%Minute%  
set ss=00%Second%  
set ts=!yyyy:~-4!-!mmmm:~-2!-!dd:~-2!_!hh:~-2!:!mm:~-2!:!ss:~-2!  
echo %ts%  
ENDLOCAL  

Result:
2018-04-25_10:03:11

How to sort with lambda in Python

lst = [('candy','30','100'), ('apple','10','200'), ('baby','20','300')]
lst.sort(key=lambda x:x[1])
print(lst)

It will print as following:

[('apple', '10', '200'), ('baby', '20', '300'), ('candy', '30', '100')]

How to create a GUID / UUID

I wanted to understand broofa's answer, so I expanded it and added comments:

var uuid = function () {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(
        /[xy]/g,
        function (match) {
            /*
            * Create a random nibble. The two clever bits of this code:
            *
            * - Bitwise operations will truncate floating point numbers
            * - For a bitwise OR of any x, x | 0 = x
            *
            * So:
            *
            * Math.random * 16
            *
            * creates a random floating point number
            * between 0 (inclusive) and 16 (exclusive) and
            *
            * | 0
            *
            * truncates the floating point number into an integer.
            */
            var randomNibble = Math.random() * 16 | 0;

            /*
            * Resolves the variant field. If the variant field (delineated
            * as y in the initial string) is matched, the nibble must
            * match the mask (where x is a do-not-care bit):
            *
            * 10xx
            *
            * This is achieved by performing the following operations in
            * sequence (where x is an intermediate result):
            *
            * - x & 0x3, which is equivalent to x % 3
            * - x | 0x8, which is equivalent to x + 8
            *
            * This results in a nibble between 8 inclusive and 11 exclusive,
            * (or 1000 and 1011 in binary), all of which satisfy the variant
            * field mask above.
            */
            var nibble = (match == 'y') ?
                (randomNibble & 0x3 | 0x8) :
                randomNibble;

            /*
            * Ensure the nibble integer is encoded as base 16 (hexadecimal).
            */
            return nibble.toString(16);
        }
    );
};

What is the newline character in the C language: \r or \n?

'\r' = carriage return and '\n' = line feed.

In fact, there are some different behaviors when you use them in different OSes. On Unix it is '\n', but it is '\r''\n' on Windows.

Cannot set property 'display' of undefined

document.getElementsByClassName('btn-pageMenu') delivers a nodeList. You should use: document.getElementsByClassName('btn-pageMenu')[0].style.display (if it's the first element from that list you want to change.

If you want to change style.display for all nodes loop through the list:

var elems = document.getElementsByClassName('btn-pageMenu');
for (var i=0;i<elems.length;i+=1){
  elems[i].style.display = 'block';
}

to be complete: if you use jquery it is as simple as:

?$('.btn-pageMenu').css('display'???????????????????????????,'block');??????

How to find substring from string?

If you are utilizing arrays too much then you should include cstring.h because it has too many functions including finding substrings.

Vue.js img src concatenate variable and text

You can't use curlies (moustache tags) in attributes. Use the following to concat data:

<img v-bind:src="imgPreUrl + 'img/logo.png'">

Or the short version:

<img :src="imgPreUrl + 'img/logo.png'">

Read more on dynamic attributes in the Vue docs.

Regular expression field validation in jQuery

I believe this does it:

http://bassistance.de/jquery-plugins/jquery-plugin-validation/

It's got built-in patterns for stuff like URLs and e-mail addresses, and I think you can have it use your own as well.

What is Bootstrap?

By today's standards and web terminology, I'd say Bootstrap is actually not a framework, although that's what their website claims. Most developers consider Angular, Vue and React frameworks, while Bootstrap is commonly referred to as a "library".

But, to be exact and correct, Bootstrap is an open-source, mobile-first collection of CSS, JavaScript and HTML design utilities aimed at providing means to develop commonly used web elements considerably faster (and smarter) than having to code them from scratch.

A few core principles which contributed to Bootstrap's success:

  • it's reusable
  • it's flexible (i.e: allows custom grid systems, changing responsiveness breakpoints, column gutter sizes or state colors with ease; as a rule of thumb, most settings are controlled by global variables)
  • it's intuitive
  • it's modular (both JavaScript and (S)CSS use a modular approach; one can easily find tutorials on making custom Bootstrap builds, to include only the parts they need)
  • has above average cross-browser compatibility
  • web accessibility out of the box (screenreader ready)
  • it's fairly well documented

It contains design templates and functionality for: layout, typography, forms, navigation, menus (including dropdowns), buttons, panels, badges, modals, alerts, tabs, collapsible, accordions, carousels, lists, tables, pagination, media utilities (including embeds, images and image replacement), responsiveness utilities, color-based utilities (primary, secondary, danger, warning, info, light, dark, muted, white), other utilities (position, margin, padding, sizing, spacing, alignment, visibility), scrollspy, affix, tooltips, popovers.


By default it relies on jQuery, but you'll find jQuery free variants powered by each of the modern popular progressive JavaScript frameworks:

Working with Bootstrap relies heavily on applying certain classes (or, depending on JS framework: directives, methods or attributes/props) and on using particular markup structures.

Documentation typically contains generic examples which can be easily copy-pasted and used as starter templates.


Another advantage of developing with Bootstrap is its vibrant community, translated into an abundance of themes, templates and plugins available for it, most of which are open-source (i.e: calendars, date/time-pickers, plugins for tabular content management, as well as libraries/component collections built on top of Bootstrap, such as MDB, portfolio templates, admin templates, etc...)

Last, but not least, Bootstrap has been well maintained over the years, which makes it a solid choice for production-ready applications/websites.

Opening a remote machine's Windows C drive

By default, Windows makes the root of each drive available (provided you've got Administrator privileges) as (e.g.) \\server\c$. These are known as Administrative Shares.

Can't create handler inside thread which has not called Looper.prepare()

Activity.runOnUiThread() does not work for me. I worked around this issue by creating a regular thread this way:

public class PullTasksThread extends Thread {
   public void run () {
      Log.d(Prefs.TAG, "Thread run...");
   }
}

and calling it from the GL update this way:

new PullTasksThread().start();

How to discard all changes made to a branch?

Note: You CANNOT UNDO this.

Try git checkout -f this will discard any local changes which are not committed in ALL branches and master.

How to give a time delay of less than one second in excel vba?

No answer helped me, so I build this.

'   function Timestamp return current time in milliseconds.
'   compatible with JSON or JavaScript Date objects.

Public Function Timestamp () As Currency
    timestamp = (Round(Now(), 0) * 24 * 60 * 60 + Timer()) * 1000
End Function

'   function Sleep let system execute other programs while the milliseconds are not elapsed.

Public Function Sleep(milliseconds As Currency)

    If milliseconds < 0 Then Exit Function

    Dim start As Currency
    start = Timestamp ()

    While (Timestamp () < milliseconds + start)
        DoEvents
    Wend
End Function

Note : In Excel 2007, Now() send Double with decimals to seconds, so i use Timer() to get milliseconds.

Note : Application.Wait() accept seconds and no under (i.e. Application.Wait(Now()) ? Application.Wait(Now()+100*millisecond)))

Note : Application.Wait() doesn't let system execute other program but hardly reduce performance. Prefer usage of DoEvents.

How to uninstall Ruby from /usr/local?

If ruby was installed in the following way:

./configure --prefix=/usr/local
make
sudo make install

You can uninstall it in the following way:

Check installed ruby version; lets assume 2.1.2

wget http://cache.ruby-lang.org/pub/ruby/2.1/ruby-2.1.2.tar.bz2
bunzip ...
tar xfv ...
cd ruby-2.1.2
./configure --prefix=/usr/local
make
sudo checkinstall
  # will build deb or rpm package and try to install it

After installation, you can now remove the package and it will remove the directories/files/etc.

sudo rpm -e ruby # or dpkg -P ruby (for Debian-like systems)

There might be some artifacts left:

Removing ruby ...
  warning: while removing ruby, directory '/usr/local/lib/ruby/gems/2.1.0/gems' not empty so not removed.
  ...

Remove them manually.

Custom bullet symbol for <li> elements in <ul> that is a regular character, and not an image

try this

_x000D_
_x000D_
    ul.a {_x000D_
        list-style-type: circle;_x000D_
    }_x000D_
    _x000D_
    ul.b {_x000D_
        list-style-type: square;_x000D_
    }_x000D_
    _x000D_
    ol.c {_x000D_
        list-style-type: upper-roman;_x000D_
    }_x000D_
    _x000D_
    ol.d {_x000D_
        list-style-type: lower-alpha;_x000D_
    }_x000D_
    
_x000D_
<!DOCTYPE html>_x000D_
    <html>_x000D_
    <head>_x000D_
    _x000D_
    </head>_x000D_
    <body>_x000D_
    _x000D_
    <p>Example of unordered lists:</p>_x000D_
    <ul class="a">_x000D_
      <li>Coffee</li>_x000D_
      <li>Tea</li>_x000D_
      <li>Coca Cola</li>_x000D_
    </ul>_x000D_
    _x000D_
    <ul class="b">_x000D_
      <li>Coffee</li>_x000D_
      <li>Tea</li>_x000D_
      <li>Coca Cola</li>_x000D_
    </ul>_x000D_
    _x000D_
    <p>Example of ordered lists:</p>_x000D_
    <ol class="c">_x000D_
      <li>Coffee</li>_x000D_
      <li>Tea</li>_x000D_
      <li>Coca Cola</li>_x000D_
    </ol>_x000D_
    _x000D_
    <ol class="d">_x000D_
      <li>Coffee</li>_x000D_
      <li>Tea</li>_x000D_
      <li>Coca Cola</li>_x000D_
    </ol>_x000D_
    _x000D_
    </body>_x000D_
    </html>
_x000D_
_x000D_
_x000D_

How to trim a file extension from a String in JavaScript?

x.slice(0, -(x.split('.').pop().length + 1));

Reloading module giving NameError: name 'reload' is not defined

If you don't want to use external libs, then one solution is to recreate the reload method from python 2 for python 3 as below. Use this in the top of the module (assumes python 3.4+).

import sys
if(sys.version_info.major>=3):
    def reload(MODULE):        
        import importlib
        importlib.reload(MODULE)

BTW reload is very much required if you use python files as config files and want to avoid restarts of the application.....

PHP 7 simpleXML

For all those using Ubuntu with ppa:ondrej/php PPA this will fix the problem:

apt install php7.0-mbstring php7.0-zip php7.0-xml

(see https://launchpad.net/~ondrej/+archive/ubuntu/php)

Thanks @Alexandre Barbosa for pointing this out!

EDIT 20160423:

One-liner to fix this issue:

sudo add-apt-repository -y ppa:ondrej/php && sudo apt update && sudo apt install -y php7.0-mbstring php7.0-zip php7.0-xml

(this will add the ppa noted above and will also make sure you always have the latest php. We use Ondrej's PHP ppa for almost two years now and it's working like charm)

Return from lambda forEach() in java

The return there is returning from the lambda expression rather than from the containing method. Instead of forEach you need to filter the stream:

players.stream().filter(player -> player.getName().contains(name))
       .findFirst().orElse(null);

Here filter restricts the stream to those items that match the predicate, and findFirst then returns an Optional with the first matching entry.

This looks less efficient than the for-loop approach, but in fact findFirst() can short-circuit - it doesn't generate the entire filtered stream and then extract one element from it, rather it filters only as many elements as it needs to in order to find the first matching one. You could also use findAny() instead of findFirst() if you don't necessarily care about getting the first matching player from the (ordered) stream but simply any matching item. This allows for better efficiency when there's parallelism involved.

How to execute Python code from within Visual Studio Code

A simple and direct Python extension would save both time and efforts. Linting, debugging, code completion are the available features once installation is done. After this, to run the code proper Python installation path needs to be configured in order to run the code. General settings are available in User scope and Workspace can be configured for Python language– "python.pythonPath": "c:/python27/python.exe" With above steps at least the basic Python programs can be executed.

Unable to create/open lock file: /data/mongod.lock errno:13 Permission denied

My mongo (3.2.9) was installed on Ubuntu, and my log file had the following lines:

2016-09-28T11:32:07.821+0100 E STORAGE  [initandlisten] WiredTiger (13) [1475058727:821829][6785:0x7fa9684ecc80], file:WiredTiger.wt, connection: /var/lib/mongodb/WiredTiger.turtle: handle-open: open: Permission denied 
2016-09-28T11:32:07.822+0100 I -        [initandlisten] Assertion: 28595:13: Permission denied 
2016-09-28T11:32:07.822+0100 I STORAGE  [initandlisten] exception in initAndListen: 28595 13: Permission denied, terminating

2016-09-28T11:32:07.822+0100 I CONTROL [initandlisten] dbexit: rc: 100

So the problem was in permissions on /var/lib/mongodb folder.

sudo chown -R mongodb:mongodb /var/lib/mongodb/
sudo chmod -R 755 /var/lib/mongodb
  • Restart the server

Fixed it, although I do realise that may be not too secure (it's my own dev box I'm in my case), bit following the change both db and authentication worked.

Can I use return value of INSERT...RETURNING in another INSERT?

The best practice for this situation. Use RETURNING … INTO.

INSERT INTO teams VALUES (...) RETURNING id INTO last_id;

Note this is for PLPGSQL

How to fix a header on scroll

Hopefully this one piece of an alternate solution will be as valuable to someone else as it was for me.

Situation:
In an HTML5 page I had a menu that was a nav element inside a header (not THE header but a header in another element).
I wanted the navigation to stick to the top once a user scrolled to it, but previous to this the header was absolute positioned (so I could have it overlay something else slightly).
The solutions above never triggered a change because .offsetTop was not going to change as this was an absolute positioned element. Additionally the .scrollTop property was simply the top of the top most element... that is to say 0 and always would be 0.
Any tests I performed utilizing these two (and same with getBoundingClientRect results) would not tell me if the top of the navigation bar ever scrolled to the top of the viewable page (again, as reported in console, they simply stayed the same numbers while scrolling occurred).

Solution
The solution for me was utilizing

window.visualViewport.pageTop

The value of the pageTop property reflects the viewable section of the screen, therefore allowing me to track where an element is in reference to the boundaries of the viewable area.
This allowed a simple function assigned to the scroll event of the window to detect when the top of the navigation bar intersected with the top of the viewable area and apply the styling to make it stick to the top.

Probably unnecessary to say, anytime I am dealing with scrolling I expect to use this solution to programatically respond to movement of elements being scrolled.
Hope it helps someone else.

Disable Auto Zoom in Input "Text" tag - Safari on iPhone

I used Christina's solution above, but with a small modification for bootstrap and another rule to apply to desktop computers. Bootstrap's default font-size is 14px which causes the zoom. The following changes it to 16px for "form controls" in Bootstrap, preventing the zoom.

@media screen and (-webkit-min-device-pixel-ratio:0) {
  .form-control {
    font-size: 16px;
  }
}

And back to 14px for non-mobile browsers.

@media (min-width: 768px) {
  .form-control {
    font-size: 14px;
  }
}

I tried using .form-control:focus, which left it at 14px except on focus which changed it to 16px and it did not fix the zoom problem with iOS8. At least on my iPhone using iOS8, the font-size has to be 16px before focus for the iPhone to not zoom the page.

VBA module that runs other modules

I just learned something new thanks to Artiso. I gave each module a name in the properties box. These names were also what I declared in the module. When I tried to call my second module, I kept getting an error: Compile error: Expected variable or procedure, not module

After reading Artiso's comment above about not having the same names, I renamed my second module, called it from the first, and problem solved. Interesting stuff! Thanks for the info Artiso!

In case my experience is unclear:

Module Name: AllFSGroupsCY Public Sub AllFSGroupsCY()

Module Name: AllFSGroupsPY Public Sub AllFSGroupsPY()

From AllFSGroupsCY()

Public Sub FSGroupsCY()

    AllFSGroupsPY 'will error each time until the properties name is changed

End Sub

Document directory path of Xcode Device Simulator

iOS 11

if let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory,
                                                           .userDomainMask,
                                                           true).first {
    debugPrint("documentsPath = \(documentsPath)")
}

How to declare a global variable in C++

Declare extern int x; in file.h. And define int x; only in one cpp file.cpp.

Create file path from variables

You can also use an object-oriented path with pathlib (available as a standard library as of Python 3.4):

from pathlib import Path

start_path = Path('/my/root/directory')
final_path = start_path / 'in' / 'here'

Is there a command like "watch" or "inotifywait" on the Mac?

Apple OSX Folder Actions allow you to automate tasks based on actions taken on a folder.

Send Outlook Email Via Python?

Check via Google, there are lots of examples, see here for one.

Inlined for ease of viewing:

import win32com.client

def send_mail_via_com(text, subject, recipient, profilename="Outlook2003"):
    s = win32com.client.Dispatch("Mapi.Session")
    o = win32com.client.Dispatch("Outlook.Application")
    s.Logon(profilename)

    Msg = o.CreateItem(0)
    Msg.To = recipient

    Msg.CC = "moreaddresses here"
    Msg.BCC = "address"

    Msg.Subject = subject
    Msg.Body = text

    attachment1 = "Path to attachment no. 1"
    attachment2 = "Path to attachment no. 2"
    Msg.Attachments.Add(attachment1)
    Msg.Attachments.Add(attachment2)

    Msg.Send()

Base64 decode snippet in C++

I firstly made my own version and then found this topic.

Why does my version look simpler than others presented here? Am I doing something wrong? I didn't test it for speed.

inline char const* b64units = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

inline char* b64encode(void const* a, int64_t b) {
    ASSERT(a != nullptr);
    if (b > 0) {
        uint8_t const* aa = static_cast<uint8_t const*>(a);
        uint8_t v = 0;
        int64_t bp = 0;
        int64_t sb = 0;
        int8_t off = 0;
        int64_t nt = ((b + 2) / 3) * 4;
        int64_t nd = (b * 8) / 6;
        int64_t tl = ((b * 8) % 6) ? 1 : 0;
        int64_t nf = nt - nd - tl;
        int64_t ri = 0;
        char* r = new char[nt + 1]();
        for (int64_t i = 0; i < nd; i++) {
            v = (aa[sb] << off) | (aa[sb + 1] >> (8 - off));
            v >>= 2;
            r[ri] = b64units[v];
            ri += 1;
            bp += 6;
            sb = (bp / 8);
            off = (bp % 8);
        }
        if (tl > 0) {
            v = (aa[sb] << off);
            v >>= 2;
            r[ri] = b64units[v];
            ri += 1;
        }
        for (int64_t i = 0; i < nf; i++) {
            r[ri] = '=';
            ri += 1;
        }
        return r;
    } else return nullptr;
}

P.S.: My method works well. I tested it with Node.js:

let data = 'stackabuse.com';
let buff = new Buffer(data);
let base64data = buff.toString('base64');

How can I express that two values are not equal to eachother?

"Not equals" can be expressed with the "not" operator ! and the standard .equals.

if (a.equals(b)) // a equals b
if (!a.equals(b)) // a not equal to b

Configuring angularjs with eclipse IDE

Netbeans 8.0 (beta at the time of this post) has Angular support as well as HTML5 support.

Check out this Oracle article: https://blogs.oracle.com/geertjan/entry/integrated_angularjs_development

How to add image in a TextView text?

Try this ..

    txtview.setCompoundDrawablesWithIntrinsicBounds(
                    R.drawable.image, 0, 0, 0);

Also see this.. http://developer.android.com/reference/android/widget/TextView.html

Try this in xml file

    <TextView
        android:id="@+id/txtStatus"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:drawableLeft="@drawable/image"
        android:drawablePadding="5dp"
        android:maxLines="1"
        android:text="@string/name"/>

calling a java servlet from javascript

I really recommend you use jquery for the javascript calls and some implementation of JSR311 like jersey for the service layer, which would delegate to your controllers.

This will help you with all the underlying logic of handling the HTTP calls and your data serialization, which is a big help.

Navigate to another page with a button in angular 2

It is important that you decorate the router link and link with square brackets as follows:

<a [routerLink]="['/service']"> <button class="btn btn-info"> link to other page </button></a>

Where "/service" in this case is the path url specified in the routing component.

Adding content to a linear layout dynamically?

You can achieve LinearLayout cascading like this:

LinearLayout root = (LinearLayout) findViewById(R.id.my_root);    
LinearLayout llay1 = new LinearLayout(this);    
root.addView(llay1);
LinearLayout llay2 = new LinearLayout(this);    
llay1.addView(llay2);

Div not expanding even with content inside

div will not expand if it has other floating divs inside, so remove the float from the internal divs and it will expand.

How to view the dependency tree of a given npm module?

You can use the npm-remote-ls module. You can install it globally:

npm install -g npm-remote-ls

And then call:

npm-remote-ls bower

Alternatively, [email protected] installed then you can use npx and avoid globally installing the command - just call:

npx npm-remote-ls bower

How to get past the login page with Wget?

I use this chrome extension. It'll give you the wget command for any download link you open.

Returning a pointer to a vector element in c++

As long as your vector remains in global scope you can return:

&(*iterator)

I'll caution you that this is pretty dangerous in general. If your vector is ever moved out of global scope and is destructed, any pointers to myObject become invalid. If you're writing these functions as part of a larger project, returning a non-const pointer could lead someone to delete the return value. This will have undefined, and catastrophic, effects on the application.

I'd rewrite this as:

myObject myFunction(const vector<myObject>& objects)
{
    // find the object in question and return a copy
    return *iterator;
}

If you need to modify the returned myObject, store your values as pointers and allocate them on the heap:

myObject* myFunction(const vector<myObject*>& objects)
{
    return *iterator;
}

That way you have control over when they're destructed.

Something like this will break your app:

g_vector<tmpClass> myVector;

    tmpClass t;
    t.i = 30;
    myVector.push_back(t);

    // my function returns a pointer to a value in myVector
    std::auto_ptr<tmpClass> t2(myFunction());

What's the main difference between Java SE and Java EE?

JavaSE and JavaEE both are computing platform which allows the developed software to run.

There are three main computing platform released by Sun Microsystems, which was eventually taken over by the Oracle Corporation. The computing platforms are all based on the Java programming language. These computing platforms are:

Java SE, i.e. Java Standard Edition. It is normally used for developing desktop applications. It forms the core/base API.

Java EE, i.e. Java Enterprise Edition. This was originally known as Java 2 Platform, Enterprise Edition or J2EE. The name was eventually changed to Java Platform, Enterprise Edition or Java EE in version 5. Java EE is mainly used for applications which run on servers, such as web sites.

Java ME, i.e. Java Micro Edition. It is mainly used for applications which run on resource constrained devices (small scale devices) like cell phones, most commonly games.

Java heap terminology: young, old and permanent generations?

The Java virtual machine is organized into three generations: a young generation, an old generation, and a permanent generation. Most objects are initially allocated in the young generation. The old generation contains objects that have survived some number of young generation collections, as well as some large objects that may be allocated directly in the old generation. The permanent generation holds objects that the JVM finds convenient to have the garbage collector manage, such as objects describing classes and methods, as well as the classes and methods themselves.

How can I install an older version of a package via NuGet?

As of NuGet 2.8, there is a feature to downgrade a package.

NuGet 2.8 Release Notes

Example:

The following command entered into the Package Manager Console will downgrade the Couchbase client to version 1.3.1.0.

Update-Package CouchbaseNetClient -Version 1.3.1.0

Result:

Updating 'CouchbaseNetClient' from version '1.3.3' to '1.3.1.0' in project [project name].
Removing 'CouchbaseNetClient 1.3.3' from [project name].
Successfully removed 'CouchbaseNetClient 1.3.3' from [project name].

Something to note as per crimbo below:

This approach doesn't work for downgrading from one prerelease version to other prerelease version - it only works for downgrading to a release version

How can I echo HTML in PHP?

In addition to Chris B's answer, if you need to use echo anyway, still want to keep it simple and structured and don't want to spam the code with <?php stuff; ?>'s, you can use the syntax below.

For example you want to display the images of a gallery:

foreach($images as $image)
{
    echo
    '<li>',
        '<a href="', site_url(), 'images/', $image['name'], '">',
            '<img ',
                'class="image" ',
                'title="', $image['title'], '" ',
                'src="', site_url(), 'images/thumbs/', $image['filename'], '" ',
                'alt="', $image['description'], '"',
            '>',
        '</a>',
    '</li>';
}

Echo takes multiple parameters so with good indenting it looks pretty good. Also using echo with parameters is more effective than concatenating.

malloc for struct and pointer in C

The first time around, you allocate memory for Vector, which means the variables x,n.

However x doesn't yet point to anything useful.

So that is why second allocation is needed as well.

Getting CheckBoxList Item values

to get the items checked you can use CheckedItems or GetItemsChecked. I tried below code in .NET 4.5

Iterate through the CheckedItems collection. This will give you the item number in the list of checked items, not the overall list. So if the first item in the list is not checked and the second item is checked, the code below will display text like Checked Item 1 = MyListItem2.

//Determine if there are any items checked. 
if(chBoxListTables.CheckedItems.Count != 0)  
{
    //looped through all checked items and show results.
    string s = "";
    for (int x = 0; x < chBoxListTables.CheckedItems.Count; x++)
    {
        s = s + (x + 1).ToString() + " = " + chBoxListTables.CheckedItems[x].ToString()+ ", ";
    }
    MessageBox.Show(s);//show result
}

-OR-

Step through the Items collection and call the GetItemChecked method for each item. This will give you the item number in the overall list, so if the first item in the list is not checked and the second item is checked, it will display something like Item 2 = MyListItem2.

int i;  
string s;   
s = "Checked items:\n" ;  
for (i = 0; i < checkedListBox1.Items.Count; i++)  
{  
   if (checkedListBox1.GetItemChecked(i))  
   {  
      s = s + "Item " + (i+1).ToString() + " = " + checkedListBox1.Items[i].ToString() + "\n";  
   }  
}  
MessageBox.Show (s);

Hope this helps...

SQL Error: ORA-00913: too many values

If you are having 112 columns in one single table and you would like to insert data from source table, you could do as

create table employees as select * from source_employees where employee_id=100;

Or from sqlplus do as

copy from source_schema/password insert employees using select * from 
source_employees where employee_id=100;

Best way to create an empty map in Java

If you need an instance of HashMap, the best way is:

fileParameters = new HashMap<String,String>();

Since Map is an interface, you need to pick some class that instantiates it if you want to create an empty instance. HashMap seems as good as any other - so just use that.

PHP Fatal error: Class 'PDO' not found

If you have upgraded your PHP version, make sure that the old PHP version configuration in your .htaccess has been deleted. For more info, check this https://www.hostgator.com/help/article/php-configuration-plugin

I want to compare two lists in different worksheets in Excel to locate any duplicates

Without VBA...

If you can use a helper column, you can use the MATCH function to test if a value in one column exists in another column (or in another column on another worksheet). It will return an Error if there is no match

To simply identify duplicates, use a helper column

Assume data in Sheet1, Column A, and another list in Sheet2, Column A. In your helper column, row 1, place the following formula:

=If(IsError(Match(A1, 'Sheet2'!A:A,False)),"","Duplicate")

Drag/copy this forumla down, and it should identify the duplicates.

To highlight cells, use conditional formatting:

With some tinkering, you can use this MATCH function in a Conditional Formatting rule which would highlight duplicate values. I would probably do this instead of using a helper column, although the helper column is a great way to "see" results before you make the conditional formatting rule.

Something like:

=NOT(ISERROR(MATCH(A1, 'Sheet2'!A:A,FALSE)))

Conditional formatting for Excel 2010

For Excel 2007 and prior, you cannot use conditional formatting rules that reference other worksheets. In this case, use the helper column and set your formatting rule in column A like:

=B1="Duplicate"

This screenshot is from the 2010 UI, but the same rule should work in 2007/2003 Excel.

Conditional formatting using helper column for rule

Version of Apache installed on a Debian machine

Another way round to check a package (including Apache) installed version on Debian-based system, we can use:

apt-cache policy <package_name>

e.g. for Apache

apt-cache policy apache2

which will show something like (look at the Installed line):

$ apt-cache policy apache2
apache2:
  Installed: (none)
  Candidate: 2.2.22-1ubuntu1.9
  Version table:
     2.2.22-1ubuntu1.9 0
        500 http://hk.archive.ubuntu.com/ubuntu/ precise-updates/main amd64 Packages
        500 http://security.ubuntu.com/ubuntu/ precise-security/main amd64 Packages
     2.2.22-1ubuntu1 0
        500 http://hk.archive.ubuntu.com/ubuntu/ precise/main amd64 Packages

how to make a whole row in a table clickable as a link?

Here's an article that explains how to approach doing this in 2020: https://www.robertcooper.me/table-row-links

The article explains 3 possible solutions:

  1. Using JavaScript.
  2. Wrapping all table cells with anchorm elements.
  3. Using <div> elements instead of native HTML table elements in order to have tables rows as <a> elements.

The article goes into depth on how to implement each solution (with links to CodePens) and also considers edge cases, such as how to approach a situation where you want to add links inside you table cells (having nested <a> elements is not valid HTML, so you need to workaround that).

As @gameliela pointed out, it may also be worth trying to find an approach where you don't make your entire row a link, since it will simplify a lot of things. I do, however, think that it can be a good user experience to have an entire table row clickable as a link since it is convenient for the user to be able to click anywhere on a table to navigate to the corresponding page.

Import and Export Excel - What is the best library?

I've worked with excel jetcell for a long time and can really recommend it. http://www.devtriogroup.com/exceljetcell

  • Commercial product
  • Excel files XLS & XLSX
  • Based on own engine in pure net.

Dynamically replace img src attribute with jQuery

You need to check out the attr method in the jQuery docs. You are misusing it. What you are doing within the if statements simply replaces all image tags src with the string specified in the 2nd parameter.

http://api.jquery.com/attr/

A better way to approach replacing a series of images source would be to loop through each and check it's source.

Example:

$('img').each(function () {
  var curSrc = $(this).attr('src');
  if ( curSrc === 'http://example.com/smith.gif' ) {
      $(this).attr('src', 'http://example.com/johnson.gif');
  }
  if ( curSrc === 'http://example.com/williams.gif' ) {
      $(this).attr('src', 'http://example.com/brown.gif');
  }
});

Is there a standardized method to swap two variables in Python?

That is the standard way to swap two variables, yes.

Putty: Getting Server refused our key Error

I have this issue where sshd only reads from authorized_keys2.

Copying or renaming the file fixed the problem for me.

cd  ~/.ssh
sudo cat authorized_keys >> authorized_keys2

P.S. I'm using Putty from Windows and used PuTTyKeygen for key pair generation.

How to bind a List to a ComboBox?

Try something like this:

yourControl.DataSource = countryInstance.Cities;

And if you are using WebForms you will need to add this line:

yourControl.DataBind();

Jquery set radio button checked, using id and class selectors

"...by a class and a div."

I assume when you say "div" you mean "id"? Try this:

$('#test2.test1').prop('checked', true);

No need to muck about with your [attributename=value] style selectors because id has its own format as does class, and they're easily combined although given that id is supposed to be unique it should be enough on its own unless your meaning is "select that element only if it currently has the specified class".

Or more generally to select an input where you want to specify a multiple attribute selector:

$('input:radio[class=test1][id=test2]').prop('checked', true);

That is, list each attribute with its own square brackets.

Note that unless you have a pretty old version of jQuery you should use .prop() rather than .attr() for this purpose.

Input type for HTML form for integer

This might help:

<input type="number" step="1" pattern="\d+" />

step is for convenience (and could be set to another integer), but pattern does some actual enforcing.

Note that since pattern matches the whole expression, it wasn't necessary to express it as ^\d+$.

Even with this outwardly tight regular expression, Chrome and Firefox's implementations, interestingly allow for e here (presumably for scientific notation) as well as - for negative numbers, and Chrome also allows for . whereas Firefox is tighter in rejecting unless the . is followed by 0's only. (Firefox marks the field as red upon the input losing focus whereas Chrome doesn't let you input disallowed values in the first place.)

Since, as observed by others, one should always validate on the server (or on the client too, if using the value locally on the client or wishing to prevent the user from a roundtrip to the server).

Get only specific attributes with from Laravel Collection

this seems to work, but not sure if it's optimized for performance or not.

$request->user()->get(['id'])->groupBy('id')->keys()->all();

output:

array:2 [
  0 => 4
  1 => 1
]

SQL Server IF EXISTS THEN 1 ELSE 2

You can define a variable @Result to fill your data in it

DECLARE @Result AS INT

IF EXISTS (SELECT * FROM tblGLUserAccess WHERE GLUserName ='xxxxxxxx') 
SET @Result = 1 
else
SET @Result = 2

How can I create a self-signed cert for localhost?

I would recomment Pluralsight's tool for creating self-signed-certs: http://blog.pluralsight.com/selfcert-create-a-self-signed-certificate-interactively-gui-or-programmatically-in-net

Make your cert as a .pfx and import it into IIS. And add it as a trusted root cert authority.

How to access array elements in a Django template?

You can access sequence elements with arr.0 arr.1 and so on. See The Django template system chapter of the django book for more information.

Java Try Catch Finally blocks without Catch

A small note on try/finally: The finally will always execute unless

  • System.exit() is called.
  • The JVM crashes.
  • The try{} block never ends (e.g. endless loop).

Git: How to return from 'detached HEAD' state

If you remember which branch was checked out before (e.g. master) you could simply

git checkout master

to get out of detached HEAD state.

Generally speaking: git checkout <branchname> will get you out of that.

If you don't remember the last branch name, try

git checkout -

This also tries to check out your last checked out branch.

Mailto on submit button

Or you can create a form with action:mailto

<form action="mailto:[email protected]"> 

check this out.

http://webdesign.about.com/od/forms/a/aa072699mailto.htm

But this actually submits a form via email.Is this what you wanted? You can also use just

<button onclick=""> and then some javascript with it to ahieve this.

And you can make a <a> look like button. There can be a lot of ways to work this around. Do a little search.

Casting variables in Java

Casting in Java isn't magic, it's you telling the compiler that an Object of type A is actually of more specific type B, and thus gaining access to all the methods on B that you wouldn't have had otherwise. You're not performing any kind of magic or conversion when performing casting, you're essentially telling the compiler "trust me, I know what I'm doing and I can guarantee you that this Object at this line is actually an <Insert cast type here>." For example:

Object o = "str";
String str = (String)o;

The above is fine, not magic and all well. The object being stored in o is actually a string, and therefore we can cast to a string without any problems.

There's two ways this could go wrong. Firstly, if you're casting between two types in completely different inheritance hierarchies then the compiler will know you're being silly and stop you:

String o = "str";
Integer str = (Integer)o; //Compilation fails here

Secondly, if they're in the same hierarchy but still an invalid cast then a ClassCastException will be thrown at runtime:

Number o = new Integer(5);
Double n = (Double)o; //ClassCastException thrown here

This essentially means that you've violated the compiler's trust. You've told it you can guarantee the object is of a particular type, and it's not.

Why do you need casting? Well, to start with you only need it when going from a more general type to a more specific type. For instance, Integer inherits from Number, so if you want to store an Integer as a Number then that's ok (since all Integers are Numbers.) However, if you want to go the other way round you need a cast - not all Numbers are Integers (as well as Integer we have Double, Float, Byte, Long, etc.) And even if there's just one subclass in your project or the JDK, someone could easily create another and distribute that, so you've no guarantee even if you think it's a single, obvious choice!

Regarding use for casting, you still see the need for it in some libraries. Pre Java-5 it was used heavily in collections and various other classes, since all collections worked on adding objects and then casting the result that you got back out the collection. However, with the advent of generics much of the use for casting has gone away - it has been replaced by generics which provide a much safer alternative, without the potential for ClassCastExceptions (in fact if you use generics cleanly and it compiles with no warnings, you have a guarantee that you'll never get a ClassCastException.)

How to sort an STL vector?

Overload less than operator, then sort. This is an example I found off the web...

class MyData
{
public:
  int m_iData;
  string m_strSomeOtherData;
  bool operator<(const MyData &rhs) const { return m_iData < rhs.m_iData; }
};

std::sort(myvector.begin(), myvector.end());

Source: here

How to pass command line arguments to a rake task

Most of the methods described above did not work for me, maybe they are deprecated in the newer versions. The up-to-date guide can be found here: http://guides.rubyonrails.org/command_line.html#custom-rake-tasks

a copy-and-paste ans from the guide is here:

task :task_name, [:arg_1] => [:pre_1, :pre_2] do |t, args|
  # You can use args from here
end

Invoke it like this

bin/rake "task_name[value 1]" # entire argument string should be quoted

Xcode variables

The best source is probably Apple's official documentation. The specific variable you are looking for is CONFIGURATION.

Simple If/Else Razor Syntax

A little bit off topic maybe, but for modern browsers (IE9 and newer) you can use the css odd/even selectors to achieve want you want.

tr:nth-child(even) { /* your alt-row stuff */}
tr:nth-child(odd) { /* the other rows */ }

or

tr { /* all table rows */ }
tr:nth-child(even) { /* your alt-row stuff */}

More than one file was found with OS independent path 'META-INF/LICENSE'

I updated Studio from Java 7 to Java 8, and this problem occurred. Then I solved it this way:

android {
    defaultConfig {
    }
    buildTypes {
    }
    packagingOptions{
        exclude 'META-INF/rxjava.properties'
    }
}

String to HtmlDocument

For those who don't want to use HTML agility pack and want to get HtmlDocument from string using native .net code only here is a good article on how to convert string to HtmlDocument

Here is the code block to use

public System.Windows.Forms.HtmlDocument GetHtmlDocument(string html)
        {
            WebBrowser browser = new WebBrowser();
            browser.ScriptErrorsSuppressed = true;
            browser.DocumentText = html;
            browser.Document.OpenNew(true);
            browser.Document.Write(html);
            browser.Refresh();
            return browser.Document;
        }

How do I get the directory of the PowerShell script I execute?

PowerShell 3 has the $PSScriptRoot automatic variable:

Contains the directory from which a script is being run.

In Windows PowerShell 2.0, this variable is valid only in script modules (.psm1). Beginning in Windows PowerShell 3.0, it is valid in all scripts.

Don't be fooled by the poor wording. PSScriptRoot is the directory of the current file.

In PowerShell 2, you can calculate the value of $PSScriptRoot yourself:

# PowerShell v2
$PSScriptRoot = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition

IntelliJ how to zoom in / out

Update: This answer is old. Intellij has since added actions to adjust font size. Check out Wilker's answer for assigning the new actions to keymaps.

Try Ctrl+Mouse Wheel which can be enabled under File > Settings... > Editor > General : Change font size (Zoom) with Ctrl+Mouse Wheel

ASP.NET MVC Dropdown List From SelectList

You are missing setting what field is the Text and Value in the SelectList itself. That is why it does a .ToString() on each object in the list. You could think that given it is a list of SelectListItem it should be smart enough to detect this... but it is not.

u.UserTypeOptions = new SelectList(
    new List<SelectListItem>
    {
        new SelectListItem { Selected = true, Text = string.Empty, Value = "-1"},
        new SelectListItem { Selected = false, Text = "Homeowner", Value = ((int)UserType.Homeowner).ToString()},
        new SelectListItem { Selected = false, Text = "Contractor", Value = ((int)UserType.Contractor).ToString()},
    }, "Value" , "Text", 1);

BTW, you can use a list of array of any type... and then just set the name of the properties that will act as Text and Value.

I think it is better to do it like this:

u.UserTypeOptions = new SelectList(
    new List<SelectListItem>
    {
        new SelectListItem { Text = "Homeowner", Value = ((int)UserType.Homeowner).ToString()},
        new SelectListItem { Text = "Contractor", Value = ((int)UserType.Contractor).ToString()},
    }, "Value" , "Text");

I removed the -1 item, and the setting of each items selected true/false.

Then, in your view:

@Html.DropDownListFor(m => m.UserType, Model.UserTypeOptions, "Select one")

This way, if you set the "Select one" item, and you don't set one item as selected in the SelectList, the UserType will be null (the UserType need to be int? ).

If you need to set one of the SelectList items as selected, you can use:

u.UserTypeOptions = new SelectList(options, "Value" , "Text", userIdToBeSelected);

error 1265. Data truncated for column when trying to load data from txt file

This error means that at least one row in your Pickup_withoutproxy2.txt file has a value in its first column that is larger than an int (your PickupId field).

An Int can only accept values between -2147483648 to 2147483647.

Review your data to see what's going on. You could try to load it into a temp table with a varchar data type if your txt file is extremely large and difficult to see. Easy enough to check for an int once loaded in the database.

Good luck.

CSS3 background image transition

I've figured out a solution that worked for me...

If you have a list item (or div) containing only the link, and let's say this is for social links on your page to facebook, twitter, ect. and you're using a sprite image you can do this:

<li id="facebook"><a href="facebook.com"></a></li>

Make the "li"s background your button image

#facebook {
   width:30px;
   height:30px;
   background:url(images/social) no-repeat 0px 0px;
}

Then make the link's background image the hover state of the button. Also add the opacity attribute to this and set it to 0.

#facebook a {
   display:inline-block;
   background:url(images/social) no-repeat 0px -30px;
   opacity:0;
}

Now all you need is "opacity" under "a:hover" and set this to 1.

#facebook a:hover {
   opacity:1;
}

Add the opacity transition attributes for each browser to "a" and "a:hover" so the the final css will look something like this:

#facebook {
   width:30px;
   height:30px;
   background:url(images/social) no-repeat 0px 0px;
}
#facebook a {
   display:inline-block;
   background:url(images/social) no-repeat 0px -30px;
   opacity:0;
   -webkit-transition: opacity 200ms linear;
   -moz-transition: opacity 200ms linear;
   -o-transition: opacity 200ms linear;
   -ms-transition: opacity 200ms linear;
   transition: opacity 200ms linear;
}
#facebook a:hover {
   opacity:1;
   -webkit-transition: opacity 200ms linear;
   -moz-transition: opacity 200ms linear;
   -o-transition: opacity 200ms linear;
   -ms-transition: opacity 200ms linear;
   transition: opacity 200ms linear;
}

If I explained it correctly that should let you have a fading background image button, hope it helps at least!

Install php-zip on php 5.6 on Ubuntu

Try either

  • sudo apt-get install php-zip or
  • sudo apt-get install php5.6-zip

Then, you might have to restart your web server.

  • sudo service apache2 restart or
  • sudo service nginx restart

If you are installing on centos or fedora OS then use yum in place of apt-get. example:-

sudo yum install php-zip or sudo yum install php5.6-zip and sudo service httpd restart

What is the difference between Multiple R-squared and Adjusted R-squared in a single-variate least squares regression?

The R-squared is not dependent on the number of variables in the model. The adjusted R-squared is.

The adjusted R-squared adds a penalty for adding variables to the model that are uncorrelated with the variable your trying to explain. You can use it to test if a variable is relevant to the thing your trying to explain.

Adjusted R-squared is R-squared with some divisions added to make it dependent on the number of variables in the model.

Python 3 - Encode/Decode vs Bytes/Str

To add to Lennart Regebro's answer There is even the third way that can be used:

encoded3 = str.encode(original, 'utf-8')
print(encoded3)

Anyway, it is actually exactly the same as the first approach. It may also look that the second way is a syntactic sugar for the third approach.


A programming language is a means to express abstract ideas formally, to be executed by the machine. A programming language is considered good if it contains constructs that one needs. Python is a hybrid language -- i.e. more natural and more versatile than pure OO or pure procedural languages. Sometimes functions are more appropriate than the object methods, sometimes the reverse is true. It depends on mental picture of the solved problem.

Anyway, the feature mentioned in the question is probably a by-product of the language implementation/design. In my opinion, this is a nice example that show the alternative thinking about technically the same thing.

In other words, calling an object method means thinking in terms "let the object gives me the wanted result". Calling a function as the alternative means "let the outer code processes the passed argument and extracts the wanted value".

The first approach emphasizes the ability of the object to do the task on its own, the second approach emphasizes the ability of an separate algoritm to extract the data. Sometimes, the separate code may be that much special that it is not wise to add it as a general method to the class of the object.

What are the recommendations for html <base> tag?

Drupal initially relied on the <base> tag, and later on took the decision to not use due to problems with HTTP crawlers & caches.

I generally don't like to post links. But this one is really worth sharing as it could benefit those looking for the details of a real-world experience with the <base> tag:

http://drupal.org/node/13148

Changing SQL Server collation to case insensitive from case sensitive?

You can do that but the changes will affect for new data that is inserted on the database. On the long run follow as suggested above.

Also there are certain tricks you can override the collation, such as parameters for stored procedures or functions, alias data types, and variables are assigned the default collation of the database. To change the collation of an alias type, you must drop the alias and re-create it.

You can override the default collation of a literal string by using the COLLATE clause. If you do not specify a collation, the literal is assigned the database default collation. You can use DATABASEPROPERTYEX to find the current collation of the database.

You can override the server, database, or column collation by specifying a collation in the ORDER BY clause of a SELECT statement.

jQuery: Get height of hidden element in jQuery

I ran into the same problem with getting hidden element width, so I wrote this plugin call jQuery Actual to fix it. Instead of using

$('#some-element').height();

use

$('#some-element').actual('height');

will give you the right value for hidden element or element has a hidden parent.

Full documentation please see here. There is also a demo include in the page.

Hope this help :)

Reading JSON POST using PHP

Hello this is a snippet from an old project of mine that uses curl to get ip information from some free ip databases services which reply in json format. I think it might help you.

$ip_srv = array("http://freegeoip.net/json/$this->ip","http://smart-ip.net/geoip-json/$this->ip");

getUserLocation($ip_srv);

Function:

function getUserLocation($services) {

        $ctx = stream_context_create(array('http' => array('timeout' => 15))); // 15 seconds timeout

        for ($i = 0; $i < count($services); $i++) {

            // Configuring curl options
            $options = array (
                CURLOPT_RETURNTRANSFER => true, // return web page
                //CURLOPT_HEADER => false, // don't return headers
                CURLOPT_HTTPHEADER => array('Content-type: application/json'),
                CURLOPT_FOLLOWLOCATION => true, // follow redirects
                CURLOPT_ENCODING => "", // handle compressed
                CURLOPT_USERAGENT => "test", // who am i
                CURLOPT_AUTOREFERER => true, // set referer on redirect
                CURLOPT_CONNECTTIMEOUT => 5, // timeout on connect
                CURLOPT_TIMEOUT => 5, // timeout on response
                CURLOPT_MAXREDIRS => 10 // stop after 10 redirects
            ); 

            // Initializing curl
            $ch = curl_init($services[$i]);
            curl_setopt_array ( $ch, $options );

            $content = curl_exec ( $ch );
            $err = curl_errno ( $ch );
            $errmsg = curl_error ( $ch );
            $header = curl_getinfo ( $ch );
            $httpCode = curl_getinfo ( $ch, CURLINFO_HTTP_CODE );

            curl_close ( $ch );

            //echo 'service: ' . $services[$i] . '</br>';
            //echo 'err: '.$err.'</br>';
            //echo 'errmsg: '.$errmsg.'</br>';
            //echo 'httpCode: '.$httpCode.'</br>';
            //print_r($header);
            //print_r(json_decode($content, true));

            if ($err == 0 && $httpCode == 200 && $header['download_content_length'] > 0) {

                return json_decode($content, true);

            } 

        }
    }

C++11 introduced a standardized memory model. What does it mean? And how is it going to affect C++ programming?

C and C++ used to be defined by an execution trace of a well formed program.

Now they are half defined by an execution trace of a program, and half a posteriori by many orderings on synchronisation objects.

Meaning that these language definitions make no sense at all as no logical method to mix these two approaches. In particular, destruction of a mutex or atomic variable is not well defined.

Move view with keyboard using Swift

My two cents for beginners: in above samples someone changes coordinates, other uses "autoresizing mask", and other constraints:

As Apple says, do not mix these 3 types of logic. If You have constraints in Storyboard, do not try to change x/y. It definitively not work.

Centering text in a table in Twitter Bootstrap

just give the surrounding <tr> a custom class like:

<tr class="custom_centered">
  <td>1</td>
  <td>2</td>
  <td>3</td>
</tr>

and have the css only select <td>s that are inside an <tr> with your custom class.

tr.custom_centered td {
  text-align: center;
}

like this you don't risk to override other tables or even override a bootstrap base class (like some of my predecessors suggested).

What is a clearfix?

The clearfix allows a container to wrap its floated children. Without a clearfix or equivalent styling, a container does not wrap around its floated children and collapses, just as if its floated children were positioned absolutely.

There are several versions of the clearfix, with Nicolas Gallagher and Thierry Koblentz as key authors.

If you want support for older browsers, it's best to use this clearfix :

.clearfix:before, .clearfix:after {
    content: "";
    display: table;
}

.clearfix:after {
    clear: both;
}

.clearfix {
    *zoom: 1;
}

In SCSS, you could use the following technique :

%clearfix {
    &:before, &:after {
        content:" ";
        display:table;
    }

    &:after {
        clear:both;
    }

    & {
        *zoom:1;
    }
}

#clearfixedelement {
    @extend %clearfix;
}

If you don't care about supporting older browsers, there's a shorter version :

.clearfix:after {
    content:"";
    display:table;
    clear:both;
}

How to use ArgumentCaptor for stubbing?

Hypothetically, if search landed you on this question then you probably want this:

doReturn(someReturn).when(someObject).doSomething(argThat(argument -> argument.getName().equals("Bob")));

Why? Because like me you value time and you are not going to implement .equals just for the sake of the single test scenario.

And 99 % of tests fall apart with null returned from Mock and in a reasonable design you would avoid return null at all costs, use Optional or move to Kotlin. This implies that verify does not need to be used that often and ArgumentCaptors are just too tedious to write.

Split string in JavaScript and detect line break

Use the following:

var enteredText = document.getElementById("textArea").value;
var numberOfLineBreaks = (enteredText.match(/\n/g)||[]).length;
alert('Number of breaks: ' + numberOfLineBreaks);

DEMO

Now what I did was to split the string first using linebreaks, and then split it again like you did before. Note: you can also use jQuery combined with regex for this:

var splitted = $('#textArea').val().split("\n");           // will split on line breaks

Hope that helps you out!

Refresh certain row of UITableView based on Int in Swift

In addition, If you have sections for tableview, you should not try to find every rows you want to refresh, you should use reload sections. It is easy and more balanced process:

yourTableView.reloadSections(IndexSet, with: UITableViewRowAnimation)

unresolved external symbol __imp__fprintf and __imp____iob_func, SDL2

I don't know why but:

#ifdef main
#undef main
#endif

After the includes but before your main should fix it from my experience.

How can I generate a list or array of sequential integers in Java?

You can use the Interval class from Eclipse Collections.

List<Integer> range = Interval.oneTo(10);
range.forEach(System.out::print);  // prints 12345678910

The Interval class is lazy, so doesn't store all of the values.

LazyIterable<Integer> range = Interval.oneTo(10);
System.out.println(range.makeString(",")); // prints 1,2,3,4,5,6,7,8,9,10

Your method would be able to be implemented as follows:

public List<Integer> makeSequence(int begin, int end) {
    return Interval.fromTo(begin, end);
}

If you would like to avoid boxing ints as Integers, but would still like a list structure as a result, then you can use IntList with IntInterval from Eclipse Collections.

public IntList makeSequence(int begin, int end) {
    return IntInterval.fromTo(begin, end);
}

IntList has the methods sum(), min(), minIfEmpty(), max(), maxIfEmpty(), average() and median() available on the interface.

Update for clarity: 11/27/2017

An Interval is a List<Integer>, but it is lazy and immutable. It is extremely useful for generating test data, especially if you deal a lot with collections. If you want you can easily copy an interval to a List, Set or Bag as follows:

Interval integers = Interval.oneTo(10);
Set<Integer> set = integers.toSet();
List<Integer> list = integers.toList();
Bag<Integer> bag = integers.toBag();

An IntInterval is an ImmutableIntList which extends IntList. It also has converter methods.

IntInterval ints = IntInterval.oneTo(10);
IntSet set = ints.toSet();
IntList list = ints.toList();
IntBag bag = ints.toBag();

An Interval and an IntInterval do not have the same equals contract.

Update for Eclipse Collections 9.0

You can now create primitive collections from primitive streams. There are withAll and ofAll methods depending on your preference. If you are curious, I explain why we have both here. These methods exist for mutable and immutable Int/Long/Double Lists, Sets, Bags and Stacks.

Assert.assertEquals(
        IntInterval.oneTo(10),
        IntLists.mutable.withAll(IntStream.rangeClosed(1, 10)));

Assert.assertEquals(
        IntInterval.oneTo(10),
        IntLists.immutable.withAll(IntStream.rangeClosed(1, 10)));

Note: I am a committer for Eclipse Collections

How do I import a CSV file in R?

You would use the read.csv function; for example:

dat = read.csv("spam.csv", header = TRUE)

You can also reference this tutorial for more details.

Note: make sure the .csv file to read is in your working directory (using getwd()) or specify the right path to file. If you want, you can set the current directory using setwd.

Generate getters and setters in NetBeans

Position the cursor inside the class, then press ALT + Ins and select Getters and Setters from the contextual menu.

Excel 2013 horizontal secondary axis

You should follow the guidelines on Add a secondary horizontal axis:

Add a secondary horizontal axis

To complete this procedure, you must have a chart that displays a secondary vertical axis. To add a secondary vertical axis, see Add a secondary vertical axis.

  1. Click a chart that displays a secondary vertical axis. This displays the Chart Tools, adding the Design, Layout, and Format tabs.

  2. On the Layout tab, in the Axes group, click Axes.

    enter image description here

  3. Click Secondary Horizontal Axis, and then click the display option that you want.

enter image description here


Add a secondary vertical axis

You can plot data on a secondary vertical axis one data series at a time. To plot more than one data series on the secondary vertical axis, repeat this procedure for each data series that you want to display on the secondary vertical axis.

  1. In a chart, click the data series that you want to plot on a secondary vertical axis, or do the following to select the data series from a list of chart elements:

    • Click the chart.

      This displays the Chart Tools, adding the Design, Layout, and Format tabs.

    • On the Format tab, in the Current Selection group, click the arrow in the Chart Elements box, and then click the data series that you want to plot along a secondary vertical axis.

      enter image description here

  2. On the Format tab, in the Current Selection group, click Format Selection. The Format Data Series dialog box is displayed.

    Note: If a different dialog box is displayed, repeat step 1 and make sure that you select a data series in the chart.

  3. On the Series Options tab, under Plot Series On, click Secondary Axis and then click Close.

    A secondary vertical axis is displayed in the chart.

  4. To change the display of the secondary vertical axis, do the following:

    • On the Layout tab, in the Axes group, click Axes.

    • Click Secondary Vertical Axis, and then click the display option that you want.

  5. To change the axis options of the secondary vertical axis, do the following:

    • Right-click the secondary vertical axis, and then click Format Axis.

    • Under Axis Options, select the options that you want to use.

Laravel 5 Application Key

This line in your app.php, 'key' => env('APP_KEY', 'SomeRandomString'),, is saying that the key for your application can be found in your .env file on the line APP_KEY.

Basically it tells Laravel to look for the key in the .env file first and if there isn't one there then to use 'SomeRandomString'.

When you use the php artisan key:generate it will generate the new key to your .env file and not the app.php file.

As kotapeter said, your .env will be inside your root Laravel directory and may be hidden; xampp/htdocs/laravel/blog

Long press on UITableView

I've used Anna-Karenina's answer, and it works almost great with a very serious bug.

If you're using sections, long-pressing the section title will give you a wrong result of pressing the first row on that section, I've added a fixed version below (including the filtering of dummy calls based on the gesture state, per Anna-Karenina suggestion).

- (IBAction)handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer
{
    if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {

        CGPoint p = [gestureRecognizer locationInView:self.tableView];

        NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:p];
        if (indexPath == nil) {
            NSLog(@"long press on table view but not on a row");
        } else {
            UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
            if (cell.isHighlighted) {
                NSLog(@"long press on table view at section %d row %d", indexPath.section, indexPath.row);
            }
        }
    }
}

Razor view engine - How can I add Partial Views

If you don't want to duplicate code, and like me you just want to show stats, in your view model, you could just pass in the models you want to get data from like so:

public class GameViewModel
{
    public virtual Ship Ship { get; set; }
    public virtual GamePlayer GamePlayer { get; set; }     
}

Then, in your controller just run your queries on the respective models, pass them to the view model and return it, example:

GameViewModel PlayerStats = new GameViewModel();

GamePlayer currentPlayer = (from c in db.GamePlayer [more queries]).FirstOrDefault();

[code to check if results]

//pass current player into custom view model
PlayerStats.GamePlayer = currentPlayer;

Like I said, you should only really do this if you want to display stats from the relevant tables, and there's no other part of the CRUD process happening, for security reasons other people have mentioned above.

How to solve "Plugin execution not covered by lifecycle configuration" for Spring Data Maven Builds

If you are using Eclipse Juno, it could be the issue of Maven Integration For Eclipse WTP . So install the same from Eclipse Market Place.

In Eclipse IDE Help>>Eclipse Market Place >> type the query wtp and it will show maven integration for eclipse WTP for Juno, install it and update the maven dependencies and enjoy

What is the purpose of "pip install --user ..."?

Why not just put an executable somewhere in my $PATH

~/.local/bin directory is theoretically expected to be in your $PATH.

According to these people it's a bug not adding it in the $PATH when using systemd.

This answer explains it more extensively.

But even if your distro includes the ~/.local/bin directory to the $PATH, it might be in the following form (inside ~/.profile):

if [ -d "$HOME/.local/bin" ] ; then
    PATH="$HOME/.local/bin:$PATH"
fi

which would require you to logout and login again, if the directory was not there before.

pandas dataframe convert column type to string or categorical

With pandas >= 1.0 there is now a dedicated string datatype:

1) You can convert your column to this pandas string datatype using .astype('string'):

df['zipcode'] = df['zipcode'].astype('string')

2) This is different from using str which sets the pandas object datatype:

df['zipcode'] = df['zipcode'].astype(str)

3) For changing into categorical datatype use:

df['zipcode'] = df['zipcode'].astype('category')

You can see this difference in datatypes when you look at the info of the dataframe:

df = pd.DataFrame({
    'zipcode_str': [90210, 90211] ,
    'zipcode_string': [90210, 90211],
    'zipcode_category': [90210, 90211],
})

df['zipcode_str'] = df['zipcode_str'].astype(str)
df['zipcode_string'] = df['zipcode_str'].astype('string')
df['zipcode_category'] = df['zipcode_category'].astype('category')

df.info()

# you can see that the first column has dtype object
# while the second column has the new dtype string
# the third column has dtype category
 #   Column            Non-Null Count  Dtype   
---  ------            --------------  -----   
 0   zipcode_str       2 non-null      object  
 1   zipcode_string    2 non-null      string  
 2   zipcode_category  2 non-null      category
dtypes: category(1), object(1), string(1)

From the docs:

The 'string' extension type solves several issues with object-dtype NumPy arrays:

  1. You can accidentally store a mixture of strings and non-strings in an object dtype array. A StringArray can only store strings.

  2. object dtype breaks dtype-specific operations like DataFrame.select_dtypes(). There isn’t a clear way to select just text while excluding non-text, but still object-dtype columns.

  3. When reading code, the contents of an object dtype array is less clear than string.

More info on working with the new string datatype can be found here: https://pandas.pydata.org/pandas-docs/stable/user_guide/text.html

How to create a sticky navigation bar that becomes fixed to the top after scrolling

This worked great for me. Don't forget to put a filler div in there where the navigation bar used to be, or else the content will jump every time it's fixed/unfixed.

function setSkrollr(){
    var objDistance = $navbar.offset().top;
    $(window).scroll(function() {
        var myDistance = $(window).scrollTop();
        if (myDistance > objDistance){
            $navbar.addClass('navbar-fixed-top');
        }
        if (objDistance > myDistance){
            $navbar.removeClass('navbar-fixed-top');
        }
    });
}

Animated GIF in IE stopping

I came upon this post, and while it has already been answered, felt I should post some information that helped me with this problem specific to IE 10, and might help others arriving at this post with a similar problem.

I was baffled how animated gifs were just not displaying in IE 10 and then found this gem.

ToolsInternet OptionsAdvancedMultiMediaPlay animations in webpages

hope this helps.

ImportError: No module named _ssl

Unrelated to the original question, but because this is the first Google result... I hit this on Google AppEngine and had to add:

libraries:
- name: ssl
  version: latest

to app.yaml per: https://cloud.google.com/appengine/docs/python/sockets/ssl_support

Please NOTE: This seems to work upto Python version 2.7.9 but not for 2.7.10 or 2.7.11.

Cron and virtualenv

If you're on python and using a Conda Virtual Environment where your python script contains the shebang #!/usr/bin/env python the following works:

* * * * * cd /home/user/project && /home/user/anaconda3/envs/envname/bin/python script.py 2>&1

Additionally, if you want to capture any outputs in your script (e.g. print, errors, etc) you can use the following:

* * * * * cd /home/user/project && /home/user/anaconda3/envs/envname/bin/python script.py >> /home/user/folder/script_name.log 2>&1

Cannot use special principal dbo: Error 15405

Fix: Cannot use the special principal ‘sa’. Microsoft SQL Server, Error: 15405

When importing a database in your SQL instance you would find yourself with Cannot use the special principal 'sa'. Microsoft SQL Server, Error: 15405 popping out when setting the sa user as the DBO of the database. To fix this, Open SQL Management Studio and Click New Query. Type:

USE mydatabase
exec sp_changedbowner 'sa', 'true'

Close the new query and after viewing the security of the sa, you will find that that sa is the DBO of the database. (14444)

Source: http://www.noelpulis.com/fix-cannot-use-the-special-principal-sa-microsoft-sql-server-error-15405/

What's the best way to check if a String represents an integer in Java?

Another option:

private boolean isNumber(String s) {
    boolean isNumber = true;
    for (char c : s.toCharArray()) {
        isNumber = isNumber && Character.isDigit(c);
    }
    return isNumber;
}

assignment operator overloading in c++

Under the circumstances, you're almost certainly better off skipping the check for self-assignment -- when you're only assigning one member that seems to be a simple type (probably a double), it's generally faster to do that assignment than avoid it, so you'd end up with:

SimpleCircle & SimpleCircle::operator=(const SimpleCircle & rhs)
{
    itsRadius = rhs.getRadius(); // or just `itsRadius = rhs.itsRadius;`
    return *this;
}

I realize that many older and/or lower quality books advise checking for self assignment. At least in my experience, however, it's sufficiently rare that you're better off without it (and if the operator depends on it for correctness, it's almost certainly not exception safe).

As an aside, I'd note that to define a circle, you generally need a center and a radius, and when you copy or assign, you want to copy/assign both.

.htaccess redirect all pages to new domain

This is a bug in older versions of apache (and thus mod_rewrite) where the path prefix was appended to the rewritten path if it got changed. See here

I think it was fixed in apache2 V2.2.12, there is a special flag you need to use which i will add here when i find it, (i think it was NP for No Path)

RewriteRule ^(.*)$ http://newdomain.com/ [??]

Await operator can only be used within an Async method

You can only use await in an async method, and Main cannot be async.

You'll have to use your own async-compatible context, call Wait on the returned Task in the Main method, or just ignore the returned Task and just block on the call to Read. Note that Wait will wrap any exceptions in an AggregateException.

If you want a good intro, see my async/await intro post.

Git Bash is extremely slow on Windows 7 x64

Only turning off AMD Radeon Graphics (or Intel Graphics) in Device Manager helped me.

enter image description here

I found the answer here: https://superuser.com/questions/1160349/git-is-extremely-slow-on-windows#=

Unfinished Stubbing Detected in Mockito

org.mockito.exceptions.misusing.UnfinishedStubbingException: 
Unfinished stubbing detected here:
E.g. thenReturn() may be missing.

For mocking of void methods try out below:

//Kotlin Syntax

 Mockito.`when`(voidMethodCall())
           .then {
                Unit //Do Nothing
            }

try/catch blocks with async/await

A cleaner alternative would be the following:

Due to the fact that every async function is technically a promise

You can add catches to functions when calling them with await

async function a(){
    let error;

    // log the error on the parent
    await b().catch((err)=>console.log('b.failed'))

    // change an error variable
    await c().catch((err)=>{error=true; console.log(err)})

    // return whatever you want
    return error ? d() : null;
}
a().catch(()=>console.log('main program failed'))

No need for try catch, as all promises errors are handled, and you have no code errors, you can omit that in the parent!!

Lets say you are working with mongodb, if there is an error you might prefer to handle it in the function calling it than making wrappers, or using try catches.

PHP list of specific files in a directory

You should use glob.

glob('*.xml')

More about using glob and advanced filtering:

http://domexception.blogspot.fi/2013/08/php-using-functional-programming-for.html

Exception Error c0000005 in VC++

I was having the same problem while running bulk tests for an assignment. Turns out when I relocated some iostream operations (printing to console) from class constructor to a method in class it was solved.

I assume it was something to do with iostream manipulations in the constructor.

Here is the fix:

// Before
CommandPrompt::CommandPrompt() : afs(nullptr), aff(nullptr) {
    cout << "Some text I was printing.." << endl;
};


// After
CommandPrompt::CommandPrompt() : afs(nullptr), aff(nullptr) {

};

Please feel free to explain more what the error is behind the scenes since it goes beyond my cpp knowledge.

Breadth First Vs Depth First

These two terms differentiate between two different ways of walking a tree.

It is probably easiest just to exhibit the difference. Consider the tree:

    A
   / \
  B   C
 /   / \
D   E   F

A depth first traversal would visit the nodes in this order

A, B, D, C, E, F

Notice that you go all the way down one leg before moving on.

A breadth first traversal would visit the node in this order

A, B, C, D, E, F

Here we work all the way across each level before going down.

(Note that there is some ambiguity in the traversal orders, and I've cheated to maintain the "reading" order at each level of the tree. In either case I could get to B before or after C, and likewise I could get to E before or after F. This may or may not matter, depends on you application...)


Both kinds of traversal can be achieved with the pseudocode:

Store the root node in Container
While (there are nodes in Container)
   N = Get the "next" node from Container
   Store all the children of N in Container
   Do some work on N

The difference between the two traversal orders lies in the choice of Container.

  • For depth first use a stack. (The recursive implementation uses the call-stack...)
  • For breadth-first use a queue.

The recursive implementation looks like

ProcessNode(Node)
   Work on the payload Node
   Foreach child of Node
      ProcessNode(child)
   /* Alternate time to work on the payload Node (see below) */

The recursion ends when you reach a node that has no children, so it is guaranteed to end for finite, acyclic graphs.


At this point, I've still cheated a little. With a little cleverness you can also work-on the nodes in this order:

D, B, E, F, C, A

which is a variation of depth-first, where I don't do the work at each node until I'm walking back up the tree. I have however visited the higher nodes on the way down to find their children.

This traversal is fairly natural in the recursive implementation (use the "Alternate time" line above instead of the first "Work" line), and not too hard if you use a explicit stack, but I'll leave it as an exercise.

Import .bak file to a database in SQL server

You can use node package, if you often need to restore databases in development process.

Install:

npm install -g sql-bak-restore

Usage:

sql-bak-restore <bakPath> <dbName> <oldDbName> <owner>

Arguments:

  • bakpath, relative or absolute path to file
  • dbName, to which database to restore (!! database with this name will be deleted if exists !!)
  • oldDbName, database name (if you don't know, specify something and run, you will see available databases after run.)
  • owner, userName to make and give him db_owner privileges (password "1")

!! sqlcmd command line utility should be in your PATH variable.

https://github.com/vladimirbuskin/sql-bak-restore/

Using Python, how can I access a shared folder on windows network?

I had the same issue as OP but none of the current answers solved my issue so to add a slightly different answer that did work for me:

Running Python 3.6.5 on a Windows Machine, I used the format

r"\DriveName\then\file\path\txt.md"

so the combination of double backslashes from reading @Johnsyweb UNC link and adding the r in front as recommended solved my similar to OP's issue.

setting the id attribute of an input element dynamically in IE: alternative for setAttribute method

The documentation says:

When you need to set attributes that are also mapped to a JavaScript dot-property (such as href, style, src or event-handlers), favour that mapping instead.

So, just change id, value assignment and you should be done.

Excel VBA If cell.Value =... then

I think it would make more sense to use "Find" function in Excel instead of For Each loop. It works much much faster and it's designed for such actions. Try this:

 Sub FindSomeCells(strSearchQuery As String)   

    Set SearchRange = Worksheets("Sheet1").Range("A1:A100")
    FindWhat = strSearchQuery
    Set FoundCells = FindAll(SearchRange:=SearchRange, _
                            FindWhat:=FindWhat, _
                            LookIn:=xlValues, _
                            LookAt:=xlWhole, _
                            SearchOrder:=xlByColumns, _
                            MatchCase:=False, _
                            BeginsWith:=vbNullString, _
                            EndsWith:=vbNullString, _
                            BeginEndCompare:=vbTextCompare)
    If FoundCells Is Nothing Then
        Debug.Print "Value Not Found"
    Else
        For Each FoundCell In FoundCells
            FoundCell.Interior.Color = XlRgbColor.rgbLightGreen
        Next FoundCell
    End If

End Sub

That subroutine searches for some string and returns a collections of cells fullfilling your search criteria. Then you can do whatever you want with the cells in that collection. Forgot to add the FindAll function definition:

Function FindAll(SearchRange As Range, _
                FindWhat As Variant, _
               Optional LookIn As XlFindLookIn = xlValues, _
                Optional LookAt As XlLookAt = xlWhole, _
                Optional SearchOrder As XlSearchOrder = xlByRows, _
                Optional MatchCase As Boolean = False, _
                Optional BeginsWith As String = vbNullString, _
                Optional EndsWith As String = vbNullString, _
                Optional BeginEndCompare As VbCompareMethod = vbTextCompare) As Range
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' FindAll
' This searches the range specified by SearchRange and returns a Range object
' that contains all the cells in which FindWhat was found. The search parameters to
' this function have the same meaning and effect as they do with the
' Range.Find method. If the value was not found, the function return Nothing. If
' BeginsWith is not an empty string, only those cells that begin with BeginWith
' are included in the result. If EndsWith is not an empty string, only those cells
' that end with EndsWith are included in the result. Note that if a cell contains
' a single word that matches either BeginsWith or EndsWith, it is included in the
' result.  If BeginsWith or EndsWith is not an empty string, the LookAt parameter
' is automatically changed to xlPart. The tests for BeginsWith and EndsWith may be
' case-sensitive by setting BeginEndCompare to vbBinaryCompare. For case-insensitive
' comparisons, set BeginEndCompare to vbTextCompare. If this parameter is omitted,
' it defaults to vbTextCompare. The comparisons for BeginsWith and EndsWith are
' in an OR relationship. That is, if both BeginsWith and EndsWith are provided,
' a match if found if the text begins with BeginsWith OR the text ends with EndsWith.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

Dim FoundCell As Range
Dim FirstFound As Range
Dim LastCell As Range
Dim ResultRange As Range
Dim XLookAt As XlLookAt
Dim Include As Boolean
Dim CompMode As VbCompareMethod
Dim Area As Range
Dim MaxRow As Long
Dim MaxCol As Long
Dim BeginB As Boolean
Dim EndB As Boolean
CompMode = BeginEndCompare
If BeginsWith <> vbNullString Or EndsWith <> vbNullString Then
    XLookAt = xlPart
Else
    XLookAt = LookAt
End If
' this loop in Areas is to find the last cell
' of all the areas. That is, the cell whose row
' and column are greater than or equal to any cell
' in any Area.

For Each Area In SearchRange.Areas
    With Area
        If .Cells(.Cells.Count).Row > MaxRow Then
            MaxRow = .Cells(.Cells.Count).Row
        End If
        If .Cells(.Cells.Count).Column > MaxCol Then
            MaxCol = .Cells(.Cells.Count).Column
        End If
    End With
Next Area
Set LastCell = SearchRange.Worksheet.Cells(MaxRow, MaxCol)
On Error GoTo 0
Set FoundCell = SearchRange.Find(what:=FindWhat, _
        after:=LastCell, _
        LookIn:=LookIn, _
        LookAt:=XLookAt, _
        SearchOrder:=SearchOrder, _
        MatchCase:=MatchCase)
If Not FoundCell Is Nothing Then
    Set FirstFound = FoundCell
    Do Until False ' Loop forever. We'll "Exit Do" when necessary.
        Include = False
        If BeginsWith = vbNullString And EndsWith = vbNullString Then
            Include = True
        Else
            If BeginsWith <> vbNullString Then
                If StrComp(Left(FoundCell.Text, Len(BeginsWith)), BeginsWith, BeginEndCompare) = 0 Then
                    Include = True
                End If
            End If
            If EndsWith <> vbNullString Then
                If StrComp(Right(FoundCell.Text, Len(EndsWith)), EndsWith, BeginEndCompare) = 0 Then
                    Include = True
                End If
            End If
        End If
        If Include = True Then
            If ResultRange Is Nothing Then
                Set ResultRange = FoundCell
            Else
                Set ResultRange = Application.Union(ResultRange, FoundCell)
            End If
        End If
        Set FoundCell = SearchRange.FindNext(after:=FoundCell)
        If (FoundCell Is Nothing) Then
            Exit Do
        End If
        If (FoundCell.Address = FirstFound.Address) Then
            Exit Do
        End If
    Loop
End If
Set FindAll = ResultRange
End Function

How can I get the "network" time, (from the "Automatic" setting called "Use network-provided values"), NOT the time on the phone?

Get the library from http://commons.apache.org/net/download_net.cgi

//NTP server list: http://tf.nist.gov/tf-cgi/servers.cgi
public static final String TIME_SERVER = "time-a.nist.gov";

public static long getCurrentNetworkTime() {
    NTPUDPClient timeClient = new NTPUDPClient();
    InetAddress inetAddress = InetAddress.getByName(TIME_SERVER);
    TimeInfo timeInfo = timeClient.getTime(inetAddress);
    //long returnTime = timeInfo.getReturnTime();   //local device time
    long returnTime = timeInfo.getMessage().getTransmitTimeStamp().getTime();   //server time

    Date time = new Date(returnTime);
    Log.d(TAG, "Time from " + TIME_SERVER + ": " + time);

    return returnTime;
}

getReturnTime() is same as System.currentTimeMillis().

getReceiveTimeStamp() or getTransmitTimeStamp() method should be used.

You can see the difference after setting system time to 1 hour ago.

local time :
System.currentTimeMillis()
timeInfo.getReturnTime()
timeInfo.getMessage().getOriginateTimeStamp().getTime()

NTP server time :
timeInfo.getMessage().getReceiveTimeStamp().getTime()
timeInfo.getMessage().getTransmitTimeStamp().getTime()

How to get current route in Symfony 2?

With Twig : {{ app.request.attributes.get('_route') }}

What is an opaque response, and what purpose does it serve?

Opaque responses can't be accessed by JavaScript, but you can still cache them with the Cache API and respond with them in the fetch event handler in a service worker. So they're useful for making your app offline, also for resources that you can't control (e.g. resources on a CDN that doesn't set the CORS headers).

Associating existing Eclipse project with existing SVN repository

I came across the same issue. I checked out using Tortoise client and then tried to import the projects in Eclipse using import wizard. Eclipse did not recognize the svn location. I tried share option as mentioned in the above posts and it tried to commit these projects into SVN. But my issue was a version mismatch. I selected svn 1.8 version in eclipse (I was using 1.7 in eclipse and 1.8.8 in tortoise) and then re imported the projects. It resolved with no issues.

What are NR and FNR and what does "NR==FNR" imply?

In awk, FNR refers to the record number (typically the line number) in the current file and NR refers to the total record number. The operator == is a comparison operator, which returns true when the two surrounding operands are equal.

This means that the condition NR==FNR is only true for the first file, as FNR resets back to 1 for the first line of each file but NR keeps on increasing.

This pattern is typically used to perform actions on only the first file. The next inside the block means any further commands are skipped, so they are only run on files other than the first.

The condition FNR==NR compares the same two operands as NR==FNR, so it behaves in the same way.

Visual Studio 2010 shortcut to find classes and methods?

Use the "Go To Find Combo Box" with the ">of" command. CTRL+/ or CTRL+D are the standard hotkeys.

For example, go to the combo box (CTRL+/) and type: >of MyClassName. As you type, intellisense will refine the options in the dropdown.

In my experience, this is faster than Navigate To and doesn't bring up another dialog to deal with. Also, this combo box has a lot of other nifty little shortcut commands:

Using the Go To Find Combo Box

This textbox used to be the default on the Standard toolbar in Visual Studio. It was removed in Visual Studio 2012, so you have to add it back using menu Tools ? Customize. The hotkeys may have changed too: I'm not sure since mine are all customized.

SyntaxError: Unexpected Identifier in Chrome's Javascript console

copy this line and replace in your project

var myNewString = myOldString.replace ("username", visitorName);

there is a simple problem with coma (,)

Loop Through Each HTML Table Column and Get the Data using jQuery

Using a nested .each() means that your inner loop is doing one td at a time, so you can't set the productId and product and quantity all in the inner loop.

Also using function(key, val) and then val[key].innerHTML isn't right: the .each() method passes the index (an integer) and the actual element, so you'd use function(i, element) and then element.innerHTML. Though jQuery also sets this to the element, so you can just say this.innerHTML.

Anyway, here's a way to get it to work:

    table.find('tr').each(function (i, el) {
        var $tds = $(this).find('td'),
            productId = $tds.eq(0).text(),
            product = $tds.eq(1).text(),
            Quantity = $tds.eq(2).text();
        // do something with productId, product, Quantity
    });

Demo: http://jsfiddle.net/bqX7Q/

spark submit add multiple jars in classpath

For --driver-class-path option you can use : as delimeter to pass multiple jars. Below is the example with spark-shell command but I guess the same should work with spark-submit as well

    spark-shell --driver-class-path /path/to/example.jar:/path/to/another.jar

Spark version: 2.2.0

How do you see the entire command history in interactive Python?

Code for printing the entire history:

Python 3

One-liner (quick copy and paste):

import readline; print('\n'.join([str(readline.get_history_item(i + 1)) for i in range(readline.get_current_history_length())]))

(Or longer version...)

import readline
for i in range(readline.get_current_history_length()):
    print (readline.get_history_item(i + 1))

Python 2

One-liner (quick copy and paste):

import readline; print '\n'.join([str(readline.get_history_item(i + 1)) for i in range(readline.get_current_history_length())])

(Or longer version...)

import readline
for i in range(readline.get_current_history_length()):
    print readline.get_history_item(i + 1)

Note: get_history_item() is indexed from 1 to n.

DataColumn Name from DataRow (not DataTable)

use DataTable object instead:

 private void doMore(DataTable dt)
    {
    foreach(DataColumn dc in dt.Columns)
    {
    MessageBox.Show(dc.ColumnName);
    }
    }

Nested ng-repeat

Create a dummy tag that is not going to rendered on the page but it will work as holder for ng-repeat:

<dummyTag ng-repeat="featureItem in item.features">{{featureItem.feature}}</br> </dummyTag>

How do I access nested HashMaps in Java?

Yes.

See:

public static void main(String args[]) {

    HashMap<String, HashMap<String, Object>> map = new HashMap<String, HashMap<String,Object>>();
    map.put("key", new HashMap<String, Object>());
    map.get("key").put("key2", "val2");

    System.out.println(map.get("key").get("key2"));
}

Java error: Comparison method violates its general contract

You can use the following class to pinpoint transitivity bugs in your Comparators:

/**
 * @author Gili Tzabari
 */
public final class Comparators
{
    /**
     * Verify that a comparator is transitive.
     *
     * @param <T>        the type being compared
     * @param comparator the comparator to test
     * @param elements   the elements to test against
     * @throws AssertionError if the comparator is not transitive
     */
    public static <T> void verifyTransitivity(Comparator<T> comparator, Collection<T> elements)
    {
        for (T first: elements)
        {
            for (T second: elements)
            {
                int result1 = comparator.compare(first, second);
                int result2 = comparator.compare(second, first);
                if (result1 != -result2)
                {
                    // Uncomment the following line to step through the failed case
                    //comparator.compare(first, second);
                    throw new AssertionError("compare(" + first + ", " + second + ") == " + result1 +
                        " but swapping the parameters returns " + result2);
                }
            }
        }
        for (T first: elements)
        {
            for (T second: elements)
            {
                int firstGreaterThanSecond = comparator.compare(first, second);
                if (firstGreaterThanSecond <= 0)
                    continue;
                for (T third: elements)
                {
                    int secondGreaterThanThird = comparator.compare(second, third);
                    if (secondGreaterThanThird <= 0)
                        continue;
                    int firstGreaterThanThird = comparator.compare(first, third);
                    if (firstGreaterThanThird <= 0)
                    {
                        // Uncomment the following line to step through the failed case
                        //comparator.compare(first, third);
                        throw new AssertionError("compare(" + first + ", " + second + ") > 0, " +
                            "compare(" + second + ", " + third + ") > 0, but compare(" + first + ", " + third + ") == " +
                            firstGreaterThanThird);
                    }
                }
            }
        }
    }

    /**
     * Prevent construction.
     */
    private Comparators()
    {
    }
}

Simply invoke Comparators.verifyTransitivity(myComparator, myCollection) in front of the code that fails.

Good Hash Function for Strings

FNV-1 is rumoured to be a good hash function for strings.

For long strings (longer than, say, about 200 characters), you can get good performance out of the MD4 hash function. As a cryptographic function, it was broken about 15 years ago, but for non cryptographic purposes, it is still very good, and surprisingly fast. In the context of Java, you would have to convert the 16-bit char values into 32-bit words, e.g. by grouping such values into pairs. A fast implementation of MD4 in Java can be found in sphlib. Probably overkill in the context of a classroom assignment, but otherwise worth a try.

Is there a standard function to check for null, undefined, or blank variables in JavaScript?

The probably shortest answer is

val==null || val==''

if you change rigth side to val==='' then empty array will give false. Proof

_x000D_
_x000D_
function isEmpty(val){_x000D_
    return val==null || val==''_x000D_
}_x000D_
_x000D_
// ------------_x000D_
// TEST_x000D_
// ------------_x000D_
_x000D_
var log = (name,val) => console.log(`${name} -> ${isEmpty(val)}`);_x000D_
_x000D_
log('null', null);_x000D_
log('undefined', undefined);_x000D_
log('NaN', NaN);_x000D_
log('""', "");_x000D_
log('{}', {});_x000D_
log('[]', []);_x000D_
log('[1]', [1]);_x000D_
log('[0]', [0]);_x000D_
log('[[]]', [[]]);_x000D_
log('true', true);_x000D_
log('false', false);_x000D_
log('"true"', "true");_x000D_
log('"false"', "false");_x000D_
log('Infinity', Infinity);_x000D_
log('-Infinity', -Infinity);_x000D_
log('1', 1);_x000D_
log('0', 0);_x000D_
log('-1', -1);_x000D_
log('"1"', "1");_x000D_
log('"0"', "0");_x000D_
log('"-1"', "-1");_x000D_
_x000D_
// "void 0" case_x000D_
console.log('---\n"true" is:', true);_x000D_
console.log('"void 0" is:', void 0);_x000D_
log(void 0,void 0); // "void 0" is "undefined" - so we should get here TRUE
_x000D_
_x000D_
_x000D_

More details about == (source here)

Enter image description here

BONUS: Reason why === is more clear than ==

Enter image description here

To write clear and easy understandable code, use explicite list of accepted values

val===undefined || val===null || val===''|| (Array.isArray(val) && val.length===0)

_x000D_
_x000D_
function isEmpty(val){_x000D_
    return val===undefined || val===null || val==='' || (Array.isArray(val) && val.length===0)_x000D_
}_x000D_
_x000D_
// ------------_x000D_
// TEST_x000D_
// ------------_x000D_
_x000D_
var log = (name,val) => console.log(`${name} -> ${isEmpty(val)}`);_x000D_
_x000D_
log('null', null);_x000D_
log('undefined', undefined);_x000D_
log('NaN', NaN);_x000D_
log('""', "");_x000D_
log('{}', {});_x000D_
log('[]', []);_x000D_
log('[1]', [1]);_x000D_
log('[0]', [0]);_x000D_
log('[[]]', [[]]);_x000D_
log('true', true);_x000D_
log('false', false);_x000D_
log('"true"', "true");_x000D_
log('"false"', "false");_x000D_
log('Infinity', Infinity);_x000D_
log('-Infinity', -Infinity);_x000D_
log('1', 1);_x000D_
log('0', 0);_x000D_
log('-1', -1);_x000D_
log('"1"', "1");_x000D_
log('"0"', "0");_x000D_
log('"-1"', "-1");_x000D_
_x000D_
// "void 0" case_x000D_
console.log('---\n"true" is:', true);_x000D_
console.log('"void 0" is:', void 0);_x000D_
log(void 0,void 0); // "void 0" is "undefined" - so we should get here TRUE
_x000D_
_x000D_
_x000D_

Use different Python version with virtualenv

Since Python 3, the Python Docs suggest creating the virtual environment with the following command:

python3 -m venv <myenvname>

Please note that venv does not permit creating virtual environments with other versions of Python. For that, install and use the virtualenv package.


Obsolete information

The pyvenv script can be used to create a virtual environment

pyvenv /path/to/new/virtual/environment

but it has been deprecated since Python 3.6.

Insert multiple values using INSERT INTO (SQL Server 2005)

The syntax you are using is new to SQL Server 2008:

INSERT INTO [MyDB].[dbo].[MyTable]
       ([FieldID]
       ,[Description])
 VALUES
       (1000,N'test'),(1001,N'test2')

For SQL Server 2005, you will have to use multiple INSERT statements:

INSERT INTO [MyDB].[dbo].[MyTable]
       ([FieldID]
       ,[Description])
 VALUES
       (1000,N'test')

INSERT INTO [MyDB].[dbo].[MyTable]
       ([FieldID]
       ,[Description])
 VALUES
       (1001,N'test2')

One other option is to use UNION ALL:

INSERT INTO [MyDB].[dbo].[MyTable]
       ([FieldID]
       ,[Description])
SELECT 1000, N'test' UNION ALL
SELECT 1001, N'test2'

Create a tar.xz in one command

Use the -J compression option for xz. And remember to man tar :)

tar cfJ <archive.tar.xz> <files>

Edit 2015-08-10:

If you're passing the arguments to tar with dashes (ex: tar -cf as opposed to tar cf), then the -f option must come last, since it specifies the filename (thanks to @A-B-B for pointing that out!). In that case, the command looks like:

tar -cJf <archive.tar.xz> <files>

Regex that accepts only numbers (0-9) and NO characters

Your regex ^[0-9] matches anything beginning with a digit, including strings like "1A". To avoid a partial match, append a $ to the end:

^[0-9]*$

This accepts any number of digits, including none. To accept one or more digits, change the * to +. To accept exactly one digit, just remove the *.

UPDATE: You mixed up the arguments to IsMatch. The pattern should be the second argument, not the first:

if (!System.Text.RegularExpressions.Regex.IsMatch(textbox.Text, "^[0-9]*$"))

CAUTION: In JavaScript, \d is equivalent to [0-9], but in .NET, \d by default matches any Unicode decimal digit, including exotic fare like ? (Myanmar 2) and ? (N'Ko 9). Unless your app is prepared to deal with these characters, stick with [0-9] (or supply the RegexOptions.ECMAScript flag).

How to hide a TemplateField column in a GridView

protected void OnRowCreated(object sender, GridViewRowEventArgs e)
{
         e.Row.Cells[columnIndex].Visible = false;
}


If you don't prefer hard-coded index, the only workaround I can suggest is to provide a HeaderText for the GridViewColumn and then find the column using that HeaderText.

protected void UsersGrid_RowCreated(object sender, GridViewRowEventArgs e)
{
    ((DataControlField)UsersGrid.Columns
            .Cast<DataControlField>()
            .Where(fld => fld.HeaderText == "Email")
            .SingleOrDefault()).Visible = false;
}

How to plot all the columns of a data frame in R

With lattice:

library(lattice)

df <- data.frame(time = 1:10,
                 a = cumsum(rnorm(10)),
                 b = cumsum(rnorm(10)),
                 c = cumsum(rnorm(10)))

form <- as.formula(paste(paste(names(df)[- 1],  collapse = ' + '),  
                         'time',  sep = '~'))

xyplot(form,  data = df,  type = 'b',  outer = TRUE)

JavaScript query string

Function I wrote for a requirement similar to this with pure javascript string manipulation

"http://www.google.lk/?Name=John&Age=20&Gender=Male"

function queryize(sampleurl){
    var tokens = url.split('?')[1].split('&');
    var result = {};

    for(var i=0; i<tokens.length; i++){
        result[tokens[i].split('=')[0]] = tokens[i].split('=')[1];
    }

    return result;
}

Usage:

queryize(window.location.href)['Name'] //returns John
queryize(window.location.href)['Age'] //returns 20
queryize(window.location.href)['Gender'] //returns Male

Google Maps API warning: NoApiKeys

A key currently still is not required ("required" in the meaning "it will not work without"), but I think there is a good reason for the warning.

But in the documentation you may read now : "All JavaScript API applications require authentication."

I'm sure that it's planned for the future , that Javascript API Applications will not work without a key(as it has been in V2).

You better use a key when you want to be sure that your application will still work in 1 or 2 years.

How to set thousands separator in Java?

NumberFormat nf = DecimalFormat.getInstance(myLocale);
DecimalFormatSymbols customSymbol = new DecimalFormatSymbols();
customSymbol.setDecimalSeparator(',');
customSymbol.setGroupingSeparator(' ');
((DecimalFormat)nf).setDecimalFormatSymbols(customSymbol);
nf.setGroupingUsed(true);

Install tkinter for Python

For Fedora >= 25 and python >= 3, we might need to include the dependencies for Tkinter

sudo dnf install python3-tkinter

Why doesn't the height of a container element increase if it contains floated elements?

You are encountering the float bug (though I'm not sure if it's technically a bug due to how many browsers exhibit this behaviour). Here is what is happening:

Under normal circumstances, assuming that no explicit height has been set, a block level element such as a div will set its height based on its content. The bottom of the parent div will extend beyond the last element. Unfortunately, floating an element stops the parent from taking the floated element into account when determining its height. This means that if your last element is floated, it will not "stretch" the parent in the same way a normal element would.

Clearing

There are two common ways to fix this. The first is to add a "clearing" element; that is, another element below the floated one that will force the parent to stretch. So add the following html as the last child:

<div style="clear:both"></div>

It shouldn't be visible, and by using clear:both, you make sure that it won't sit next to the floated element, but after it.

Overflow:

The second method, which is preferred by most people (I think) is to change the CSS of the parent element so that the overflow is anything but "visible". So setting the overflow to "hidden" will force the parent to stretch beyond the bottom of the floated child. This is only true if you haven't set a height on the parent, of course.

Like I said, the second method is preferred as it doesn't require you to go and add semantically meaningless elements to your markup, but there are times when you need the overflow to be visible, in which case adding a clearing element is more than acceptable.

Unable to launch the IIS Express Web server

Before you try anything else, make sure you 1. restart visual studio (mostly for refreshing memory resident options from files) and 2. restart your system (mostly for invalid file locking). If your problem is such temporary or self-fixed those will do without changing anything. It worked for me with PC restart. Also if you work on a multi-user project make sure you have the latest workable version - someone else may had check in something invalid by mistake at e.g. the project file and you mess with your system for no reason. If those won't work, then you probably need to alter some setting(s) that are stuck, missing or need modification - there are plenty propositions on other answers.

How do I change the formatting of numbers on an axis with ggplot?

Another option is to format your axis tick labels with commas is by using the package scales, and add

 scale_y_continuous(name="Fluorescent intensity/arbitrary units", labels = comma)

to your ggplot statement.

If you don't want to load the package, use:

scale_y_continuous(name="Fluorescent intensity/arbitrary units", labels = scales::comma)

Create a view with ORDER BY clause

Error is: FROM (SELECT empno,name FROM table1 where location = 'A' ORDER BY emp_no)

And solution is : FROM (SELECT empno,name FROM table1 where location = 'A') ORDER BY emp_no

How to include bootstrap css and js in reactjs app?

Please follow below link to use bootstrap with React. https://react-bootstrap.github.io/

For installation :

$ npm install --save react react-dom
$ npm install --save react-bootstrap

------------------------------------OR-------------------------------------

Put Bootstrap CDN for CSS in tag of index.html file in react and Bootstrap CDN for Js in tag of index.html file. Use className instead of class follow below index.html

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="theme-color" content="#000000">

    <link rel="manifest" href="%PUBLIC_URL%/manifest.json">
    <link rel="shortcut icon" href="../src/images/dropbox_logo.svg">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">




  </head>
  <body>

    <div id="root"></div>

     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>

  </body>
</html>

Sending POST parameters with Postman doesn't work, but sending GET parameters does

I faced the same issue in PostMan and Advance REST Client both. I checked through fiddler and found that my request payload is not converted into JSON format.

I am passing my data in Body as x-www-form-urlencoded enter image description here

You can fix it by using Content-Type as application/x-www-form-urlencoded in request header. enter image description here

Inline JavaScript onclick function

This isn't really recommended, but you can do it all inline like so:

<a href="#" onClick="function test(){ /* Do something */  } test(); return false;"></a>

But I can't think of any situations off hand where this would be better than writing the function somewhere else and invoking it onClick.

Using multiple delimiters in awk

If your whitespace is consistent you could use that as a delimiter, also instead of inserting \t directly, you could set the output separator and it will be included automatically:

< file awk -v OFS='\t' -v FS='[/ ]' '{print $3, $5, $NF}'

Prevent div from moving while resizing the page

There are two types of measurements you can use for specifying widths, heights, margins etc: relative and fixed.

Relative

An example of a relative measurement is percentages, which you have used. Percentages are relevant to their containing element. If there is no containing element they are relative to the window.

<div style="width:100%"> 
<!-- This div will be the full width of the browser, whatever size it is -->
    <div style="width:300px">
    <!-- this div will be 300px, whatever size the browser is -->
        <p style="width:50%">
            This paragraph's width will be 50% of it's parent (150px).
        </p>
    </div>
</div>

Another relative measurement is ems which are relative to font size.

Fixed

An example of a fixed measurement is pixels but a fixed measurement can also be pt (points), cm (centimetres) etc. Fixed (sometimes called absolute) measurements are always the same size. A pixel is always a pixel, a centimetre is always a centimetre.

If you were to use fixed measurements for your sizes the browser size wouldn't affect the layout.

Renaming part of a filename

Something like this will do it. The for loop may need to be modified depending on which filenames you wish to capture.

for fspec1 in DET01-ABC-5_50-*.dat ; do
    fspec2=$(echo ${fspec1} | sed 's/-ABC-/-XYZ-/')
    mv ${fspec1} ${fspec2}
done

You should always test these scripts on copies of your data, by the way, and in totally different directories.

How to resolve ambiguous column names when retrieving results?

You can set aliases for the columns that you are selecting:

$query = 'SELECT news.id AS newsId, user.id AS userId, [OTHER FIELDS HERE] FROM news JOIN users ON news.user = user.id'

Running Windows batch file commands asynchronously

There's a third (and potentially much easier) option. If you want to spin up multiple instances of a single program, using a Unix-style command processor like Xargs or GNU Parallel can make that a fairly straightforward process.

There's a win32 Xargs clone called PPX2 that makes this fairly straightforward.

For instance, if you wanted to transcode a directory of video files, you could run the command:

dir /b *.mpg |ppx2 -P 4 -I {} -L 1 ffmpeg.exe -i "{}" -quality:v 1 "{}.mp4"

Picking this apart, dir /b *.mpg grabs a list of .mpg files in my current directory, the | operator pipes this list into ppx2, which then builds a series of commands to be executed in parallel; 4 at a time, as specified here by the -P 4 operator. The -L 1 operator tells ppx2 to only send one line of our directory listing to ffmpeg at a time.

After that, you just write your command line (ffmpeg.exe -i "{}" -quality:v 1 "{}.mp4"), and {} gets automatically substituted for each line of your directory listing.

It's not universally applicable to every case, but is a whole lot easier than using the batch file workarounds detailed above. Of course, if you're not dealing with a list of files, you could also pipe the contents of a textfile or any other program into the input of pxx2.

Convert string to BigDecimal in java

You are storing 135.69 as String in currency. But instead of passing variable currency, you are again passing 135.69(double value) into new BigDecimal(). So you are seeing a lot of numbers in the output. If you pass the currency variable, your output will be 135.69

How do I truncate a .NET string?

For the sake of (over)complexity I'll add my overloaded version which replaces the last 3 characters with an ellipsis in respect with the maxLength parameter.

public static string Truncate(this string value, int maxLength, bool replaceTruncatedCharWithEllipsis = false)
{
    if (replaceTruncatedCharWithEllipsis && maxLength <= 3)
        throw new ArgumentOutOfRangeException("maxLength",
            "maxLength should be greater than three when replacing with an ellipsis.");

    if (String.IsNullOrWhiteSpace(value)) 
        return String.Empty;

    if (replaceTruncatedCharWithEllipsis &&
        value.Length > maxLength)
    {
        return value.Substring(0, maxLength - 3) + "...";
    }

    return value.Substring(0, Math.Min(value.Length, maxLength)); 
}

C++ catching all exceptions

You can use

catch(...)

but that is very dangerous. In his book Debugging Windows, John Robbins tells a war story about a really nasty bug that was masked by a catch(...) command. You're much better off catching specific exceptions. Catch whatever you think your try block might reasonably throw, but let the code throw an exception higher up if something really unexpected happens.

What is the correct way to read from NetworkStream in .NET

As per your requirement, Thread.Sleep is perfectly fine to use because you are not sure when the data will be available so you might need to wait for the data to become available. I have slightly changed the logic of your function this might help you little further.

string SendCmd(string cmd, string ip, int port)
{
    var client = new TcpClient(ip, port);
    var data = Encoding.GetEncoding(1252).GetBytes(cmd);
    var stm = client.GetStream();
    stm.Write(data, 0, data.Length);
    byte[] resp = new byte[2048];
    var memStream = new MemoryStream();

    int bytes = 0;

    do
    {
        bytes = 0;
        while (!stm.DataAvailable)
            Thread.Sleep(20); // some delay
        bytes = stm.Read(resp, 0, resp.Length);
        memStream.Write(resp, 0, bytes);
    } 
    while (bytes > 0);

    return Encoding.GetEncoding(1252).GetString(memStream.ToArray());
}

Hope this helps!

Get Mouse Position

import java.awt.MouseInfo;
import java.awt.GridLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;

import javax.swing.*;

public class MyClass {
  public static void main(String[] args) throws InterruptedException{
    while(true){
      //Thread.sleep(100);
      System.out.println("(" + MouseInfo.getPointerInfo().getLocation().x + 
              ", " + 
              MouseInfo.getPointerInfo().getLocation().y + ")");
    }
  }
}

Scheduling Python Script to run every hour accurately

Run the script every 15 minutes of the hour. For example, you want to receive 15 minute stock price quotes, which are updated every 15 minutes.

while True:
    print("Update data:", datetime.now())
    sleep = 15 - datetime.now().minute % 15
    if sleep == 15:
        run_strategy()
        time.sleep(sleep * 60)
    else:
        time.sleep(sleep * 60)

How do you build a Singleton in Dart?

Hello what about something like this? Very simple implementation, Injector itself is singleton and also added classes into it. Of course can be extended very easily. If you are looking for something more sophisticated check this package: https://pub.dartlang.org/packages/flutter_simple_dependency_injection

void main() {  
  Injector injector = Injector();
  injector.add(() => Person('Filip'));
  injector.add(() => City('New York'));

  Person person =  injector.get<Person>(); 
  City city =  injector.get<City>();

  print(person.name);
  print(city.name);
}

class Person {
  String name;

  Person(this.name);
}

class City {
  String name;

  City(this.name);
}


typedef T CreateInstanceFn<T>();

class Injector {
  static final Injector _singleton =  Injector._internal();
  final _factories = Map<String, dynamic>();

  factory Injector() {
    return _singleton;
  }

  Injector._internal();

  String _generateKey<T>(T type) {
    return '${type.toString()}_instance';
  }

  void add<T>(CreateInstanceFn<T> createInstance) {
    final typeKey = _generateKey(T);
    _factories[typeKey] = createInstance();
  }

  T get<T>() {
    final typeKey = _generateKey(T);
    T instance = _factories[typeKey];
    if (instance == null) {
      print('Cannot find instance for type $typeKey');
    }

    return instance;
  }
}

Node.js Mongoose.js string to ObjectId function

You can do it like this:

var mongoose = require('mongoose');
var _id = mongoose.mongo.BSONPure.ObjectID.fromHexString("4eb6e7e7e9b7f4194e000001");

EDIT: New standard has fromHexString rather than fromString

What's the difference between a temp table and table variable in SQL Server?

In which scenarios does one out-perform the other?

For smaller tables (less than 1000 rows) use a temp variable, otherwise use a temp table.

How do you clear your Visual Studio cache on Windows Vista?

I experienced this today. The value in Config was the updated one but the application would return the older value, stop and starting the solution did nothing.

So I cleared the .Net Temp folder.

C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files

It shouldn't create bugs but to be safe close your solution down first. Clear the Temporary ASP.NET Files then load up your solution.

My issue was sorted.

git push to specific branch

I would like to add an updated answer - now I have been using git for a while, I find that I am often using the following commands to do any pushing (using the original question as the example):

  • git push origin amd_qlp_tester - push to the branch located in the remote called origin on remote-branch called amd_qlp_tester.
  • git push -u origin amd_qlp_tester - same as last one, but sets the upstream linking the local branch to the remote branch so that next time you can just use git push/pull if not already linked (only need to do it once).
  • git push - Once you have set the upstream you can just use this shorter version.

Note -u option is the short version of --set-upstream - they are the same.

Making a button invisible by clicking another button in HTML

For Visible:

document.getElementById("test").style.visibility="visible";

For Invisible:

document.getElementById("test").style.visibility="hidden";

If list index exists, do X

A lot of answers, not the simple one.

To check if a index 'id' exists at dictionary dict:

dic = {}
dic['name'] = "joao"
dic['age']  = "39"

if 'age' in dic

returns true if 'age' exists.

Printing Exception Message in java

try {
} catch (javax.script.ScriptException ex) {
// System.out.println(ex.getMessage());
}

How to force two figures to stay on the same page in LaTeX?

You can put two figures inside one figure environment. For example:

\begin{figure}[p]
\centering
\includegraphics{fig1}
\caption{Caption 1}
\includegraphics{fig2}
\caption{Caption 2}
\end{figure}

Each caption will generate a separate figure number.

How to determine tables size in Oracle

If you don't have DBA rights then you can use user_segments table:

select bytes/1024/1024 MB from user_segments where segment_name='Table_name'

Git asks for username every time I push

git config --global credential.helper cache

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

One simple line in base R:

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

Same in two lines, for clarity/efficiency:

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

Android Linear Layout - How to Keep Element At Bottom Of View?

DO LIKE THIS

 <LinearLayout
android:id="@+id/LinearLayouts02"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="bottom|end">

<TextView
    android:id="@+id/texts1"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:layout_weight="2"
    android:text="@string/forgotpass"
    android:padding="7dp"
    android:gravity="bottom|center_horizontal"
    android:paddingLeft="10dp"
    android:layout_marginBottom="30dp"
    android:bottomLeftRadius="10dp"
    android:bottomRightRadius="50dp"
    android:fontFamily="sans-serif-condensed"
    android:textColor="@color/colorAccent"
    android:textStyle="bold"
    android:textSize="16sp"
    android:topLeftRadius="10dp"
    android:topRightRadius="10dp"
   />

</LinearLayout>

How to increase dbms_output buffer?

You can Enable DBMS_OUTPUT and set the buffer size. The buffer size can be between 1 and 1,000,000.

dbms_output.enable(buffer_size IN INTEGER DEFAULT 20000);
exec dbms_output.enable(1000000);

Check this

EDIT

As per the comment posted by Frank and Mat, you can also enable it with Null

exec dbms_output.enable(NULL);

buffer_size : Upper limit, in bytes, the amount of buffered information. Setting buffer_size to NULL specifies that there should be no limit. The maximum size is 1,000,000, and the minimum is 2,000 when the user specifies buffer_size (NOT NULL).

Run git pull over all subdirectories

You can try this

find . -type d -name .git -exec sh -c "cd \"{}\"/../ && pwd && git pull" \;

Also, you can add your customized output by adding one more && argument like.

find . -type d -name .git -exec sh -c "cd \"{}\"/../ && pwd && git pull && git status" \;

Customizing Bootstrap CSS template

The best thing to do is.

1. fork twitter-bootstrap from github and clone locally.

they are changing really quickly the library/framework (they diverge internally. Some prefer library, i'd say that it's a framework, because change your layout from the time you load it on your page). Well... forking/cloning will let you fetch the new upcoming versions easily.

2. Do not modify the bootstrap.css file

It's gonna complicate your life when you need to upgrade bootstrap (and you will need to do it).

3. Create your own css file and overwrite whenever you want original bootstrap stuff

if they set a topbar with, let's say, color: black; but you wan it white, create a new very specific selector for this topbar and use this rule on the specific topbar. For a table for example, it would be <table class="zebra-striped mycustomclass">. If you declare your css file after bootstrap.css, this will overwrite whatever you want to.

iPhone SDK on Windows (alternative solutions)

There is another solution if you want to develop in C/C++. http://www.DragonFireSDK.com will allow you to build iPhone applications in Visual Studio on Windows. It's worth a look-see for sure.

dbms_lob.getlength() vs. length() to find blob size in oracle

length and dbms_lob.getlength return the number of characters when applied to a CLOB (Character LOB). When applied to a BLOB (Binary LOB), dbms_lob.getlength will return the number of bytes, which may differ from the number of characters in a multi-byte character set.

As the documentation doesn't specify what happens when you apply length on a BLOB, I would advise against using it in that case. If you want the number of bytes in a BLOB, use dbms_lob.getlength.

What does $ mean before a string?

Example Code

public class Person {
    public String firstName { get; set; }
    public String lastName { get; set; }
}

// Instantiate Person
var person = new Person { firstName = "Albert", lastName = "Einstein" };

// We can print fullname of the above person as follows
Console.WriteLine("Full-Name - " + person.firstName + " " + person.lastName);
Console.WriteLine("Full-Name - {0} {1}", person.firstName, person.lastName);
Console.WriteLine($"Full-Name - {person.firstName} {person.lastName}");

Output

Full-Name - Albert Einstein
Full-Name - Albert Einstein
Full-Name - Albert Einstein

It is Interpolated Strings. You can use an interpolated string anywhere you can use a string literal. When running your program would execute the code with the interpolated string literal, the code computes a new string literal by evaluating the interpolation expressions. This computation occurs each time the code with the interpolated string executes.

Following example produces a string value where all the string interpolation values have been computed. It is the final result and has type string. All occurrences of double curly braces (“{{“ and “}}”) are converted to a single curly brace.

string text = "World";
var message = $"Hello, {text}";

After executing above 2 lines, variable message contains "Hello, World".

Console.WriteLine(message); // Prints Hello, World

Reference - MSDN

Rails has_many with alias name

If you use has_many through, and want to alias:

has_many :alias_name, through: model_name, source: initial_name