Programs & Examples On #Princely

JavaScript: How to find out if the user browser is Chrome?

var is_chrome = /chrome/.test( navigator.userAgent.toLowerCase() );

Close all infowindows in Google Maps API v3

For loops that creates infowindows dynamically, declare a global variable

var openwindow;

and then in the addListenerfunction call (which is within the loop):

google.maps.event.addListener(marker<?php echo $id; ?>, 'click', function() {
if(openwindow){
    eval(openwindow).close();
}
openwindow="myInfoWindow<?php echo $id; ?>";
myInfoWindow<?php echo $id; ?>.open(map, marker<?php echo $id; ?>);
});

Angular exception: Can't bind to 'ngForIn' since it isn't a known native property

TL;DR;

Use let...of instead of let...in !!


If you're new to Angular (>2.x) and possibly migrating from Angular1.x, most likely you're confusing in with of. As andreas has mentioned in the comments below for ... of iterates over values of an object while for ... in iterates over properties in an object. This is a new feature introduced in ES2015.

Simply replace:

<!-- Iterate over properties (incorrect in our case here) -->
<div *ngFor="let talk in talks">

with

<!-- Iterate over values (correct way to use here) -->
<div *ngFor="let talk of talks">

So, you must replace in with of inside ngFor directive to get the values.

Call a "local" function within module.exports from another function in module.exports?

const Service = {
  foo: (a, b) => a + b,
  bar: (a, b) => Service.foo(a, b) * b
}

module.exports = Service

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

The easiest solution to animate the DOM elements is using CSS transitions/animations but I think you already know that and you try to use canvas to do stuff CSS doesn't let you to do. What about CSS custom filters? you can transform your elements in any imaginable way if you know how to write shaders. Some other link and don't forget to check the CSS filter lab.
Note: As you can probably imagine browser support is bad.

Converting a JS object to an array using jQuery

I made a custom function:

    Object.prototype.toArray=function(){
    var arr=new Array();
    for( var i in this ) {
        if (this.hasOwnProperty(i)){
            arr.push(this[i]);
        }
    }
    return arr;
};

Htaccess: add/remove trailing slash from URL

To complement Jon Lin's answer, here is a no-trailing-slash technique that also works if the website is located in a directory (like example.org/blog/):

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [R=301,L]


For the sake of completeness, here is an alternative emphasizing that REQUEST_URI starts with a slash (at least in .htaccess files):

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} /(.*)/$
RewriteRule ^ /%1 [R=301,L] <-- added slash here too, don't forget it

Just don't use %{REQUEST_URI} (.*)/$. Because in the root directory REQUEST_URI equals /, the leading slash, and it would be misinterpreted as a trailing slash.


If you are interested in more reading:

(update: this technique is now implemented in Laravel 5.5)

Error: Could not find gradle wrapper within Android SDK. Might need to update your Android SDK - Android

Easy and simple solution for MAC

My Issue was

cordova build android
ANDROID_HOME=/Users/jerilkuruvila/Library/Android/sdk
JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_65.jdk/Contents/Home
Error: Could not find gradle wrapper within Android SDK. Might need to update your Android SDK.
Looked here: /Users/jerilkuruvila/Library/Android/sdk/tools/templates/gradle/wrapper

Solution

jerilkuruvila@Jerils-ENIAC tools $ cd templates
-bash: cd: mkdir: No such file or directory
jerilkuruvila@Jerils-ENIAC tools $ mkdir templates
jerilkuruvila@Jerils-ENIAC tools $ cp -rf gradle templates/
jerilkuruvila@Jerils-ENIAC tools $ chmod a+x templates/

cordova build android again working now !!!

how to activate a textbox if I select an other option in drop down box

Below is the core JavaScript you need to write:

<html> 
<head>  
<script type="text/javascript">
function CheckColors(val){
 var element=document.getElementById('color');
 if(val=='pick a color'||val=='others')
   element.style.display='block';
 else  
   element.style.display='none';
}

</script> 
</head>
<body>
  <select name="color" onchange='CheckColors(this.value);'> 
    <option>pick a color</option>  
    <option value="red">RED</option>
    <option value="blue">BLUE</option>
    <option value="others">others</option>
  </select>
<input type="text" name="color" id="color" style='display:none;'/>
</body>
</html>

Finding elements not in a list

>> items = [1,2,3,4]
>> Z = [3,4,5,6]

>> print list(set(items)-set(Z))
[1, 2]

Cannot connect to repo with TortoiseSVN

SVN is case-sensitive. Make sure that you're spelling it properly. If it got renamed, you can relocate the working folder to the new URL. See https://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-relocate.html

window.onload vs <body onload=""/>

If you're trying to write unobtrusive JS code (and you should be), then you shouldn't use <body onload="">.

It is my understanding that different browsers handle these two slightly differently but they operate similarly. In most browsers, if you define both, one will be ignored.

Add row to query result using select

In SQL Server, you would say:

Select name from users
UNION [ALL]
SELECT 'JASON'

In Oracle, you would say

Select name from user
UNION [ALL]
Select 'JASON' from DUAL

When do you use Java's @Override annotation and why?

I use it every time. It's more information that I can use to quickly figure out what is going on when I revisit the code in a year and I've forgotten what I was thinking the first time.

how to zip a folder itself using java

Java 7+, commons.io

public final class ZipUtils {

    public static void zipFolder(final File folder, final File zipFile) throws IOException {
        zipFolder(folder, new FileOutputStream(zipFile));
    }

    public static void zipFolder(final File folder, final OutputStream outputStream) throws IOException {
        try (ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream)) {
            processFolder(folder, zipOutputStream, folder.getPath().length() + 1);
        }
    }

    private static void processFolder(final File folder, final ZipOutputStream zipOutputStream, final int prefixLength)
            throws IOException {
        for (final File file : folder.listFiles()) {
            if (file.isFile()) {
                final ZipEntry zipEntry = new ZipEntry(file.getPath().substring(prefixLength));
                zipOutputStream.putNextEntry(zipEntry);
                try (FileInputStream inputStream = new FileInputStream(file)) {
                    IOUtils.copy(inputStream, zipOutputStream);
                }
                zipOutputStream.closeEntry();
            } else if (file.isDirectory()) {
                processFolder(file, zipOutputStream, prefixLength);
            }
        }
    }
}

C# listView, how do I add items to columns 2, 3 and 4 etc?

 private void MainTimesheetForm_Load(object sender, EventArgs e)
        {
            ListViewItem newList = new ListViewItem("1");
            newList.SubItems.Add("2");
            newList.SubItems.Add(DateTime.Now.ToLongTimeString());
            newList.SubItems.Add("3");
            newList.SubItems.Add("4");
            newList.SubItems.Add("5");
            newList.SubItems.Add("6");
            listViewTimeSheet.Items.Add(newList);

        }

DateTime format to SQL format using C#

   DateTime date1 = new DateTime();

    date1 = Convert.ToDateTime(TextBox1.Text);
    Label1.Text = (date1.ToLongTimeString()); //11:00 AM
    Label2.Text = date1.ToLongDateString(); //Friday, November 1, 2019;
    Label3.Text = date1.ToString();
    Label4.Text = date1.ToShortDateString();
    Label5.Text = date1.ToShortTimeString();

How do I check if a C++ std::string starts with a certain string, and convert a substring to an int?

Ok why the complicated use of libraries and stuff? C++ String objects overload the [] operator, so you can just compare chars.. Like what I just did, because I want to list all files in a directory and ignore invisible files and the .. and . pseudofiles.

while ((ep = readdir(dp)))
{
    string s(ep->d_name);
    if (!(s[0] == '.')) // Omit invisible files and .. or .
        files.push_back(s);
}

It's that simple..

What's the best way to build a string of delimited items in Java?

Why not write your own join() method? It would take as parameters collection of Strings and a delimiter String. Within the method iterate over the collection and build up your result in a StringBuffer.

Calling pylab.savefig without display in ipython

We don't need to plt.ioff() or plt.show() (if we use %matplotlib inline). You can test above code without plt.ioff(). plt.close() has the essential role. Try this one:

%matplotlib inline
import pylab as plt

# It doesn't matter you add line below. You can even replace it by 'plt.ion()', but you will see no changes.
## plt.ioff()

# Create a new figure, plot into it, then close it so it never gets displayed
fig = plt.figure()
plt.plot([1,2,3])
plt.savefig('test0.png')
plt.close(fig)

# Create a new figure, plot into it, then don't close it so it does get displayed
fig2 = plt.figure()
plt.plot([1,3,2])
plt.savefig('test1.png')

If you run this code in iPython, it will display a second plot, and if you add plt.close(fig2) to the end of it, you will see nothing.

In conclusion, if you close figure by plt.close(fig), it won't be displayed.

Converting string from snake_case to CamelCase in Ruby

I feel a little uneasy to add more answers here. Decided to go for the most readable and minimal pure ruby approach, disregarding the nice benchmark from @ulysse-bn. While :class mode is a copy of @user3869936, the :method mode I don't see in any other answer here.

  def snake_to_camel_case(str, mode: :class)
    case mode
    when :class
      str.split('_').map(&:capitalize).join
    when :method
      str.split('_').inject { |m, p| m + p.capitalize }
    else
      raise "unknown mode #{mode.inspect}"
    end
  end

Result is:

[28] pry(main)> snake_to_camel_case("asd_dsa_fds", mode: :class)
=> "AsdDsaFds"
[29] pry(main)> snake_to_camel_case("asd_dsa_fds", mode: :method)
=> "asdDsaFds"

Android: How to use webcam in emulator?

I would suggest checking the drivers and updating them if required.

Error CS1705: "which has a higher version than referenced assembly"

Handmade dll's collection folder
If you solution has a garbage folder for dll-files from different libraries
lib, source, libs, etc.
You can get this trouble if you'll open your solution (for a firs time) in Visual Studio. And your dll's collecting folder is missed for somehow or a concrete dll-file is missed.

Visual Studio will try silently to substitute dll's reference for something on its own. If VS will succeed then a new reference will be persistent for your local solution. Not for other clones/checkouts.

I.e. your <HintPath> will be ignored and you project file (.csproj) will not be changed.
As an example of me

<Reference Include="DocumentFormat.OpenXml, Version=2.0.5022.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
  <SpecificVersion>False</SpecificVersion>
  <HintPath>..\..\..\lib\DocumentFormat.OpenXml.dll</HintPath>
</Reference>

The DocumentFormat.OpenXml will be referenced from C:\Program Files (x86)\Open XML SDK\V2.5\lib not from a solution\..\lib folder.

fast Workaround

  • check and restore you dll's collecting folder
  • from Solution Explorer do Unload Project, then Reload Project.

right Workaround is to migrate to NuGet package manager.

How to define the css :hover state in a jQuery selector?

You can try this:

$(".myclass").mouseover(function() {
    $(this).find(" > div").css("background-color","red");
}).mouseout(function() {
    $(this).find(" > div").css("background-color","transparent");
});

DEMO

How do I get the APK of an installed app without root access?

Accessing /data/app is possible without root permission; the permissions on that directory are rwxrwx--x. Execute permission on a directory means you can access it, however lack of read permission means you cannot obtain a listing of its contents -- so in order to access it you must know the name of the file that you will be accessing. Android's package manager will tell you the name of the stored apk for a given package.

To do this from the command line, use adb shell pm list packages to get the list of installed packages and find the desired package.

With the package name, we can get the actual file name and location of the APK using adb shell pm path your-package-name.

And knowing the full directory, we can finally pull the adb using adb pull full/directory/of/the.apk

Credit to @tarn for pointing out that under Lollipop, the apk path will be /data/app/your-package-name-1/base.apk

How to replace specific values in a oracle database column?

I'm using Version 4.0.2.15 with Build 15.21

For me I needed this:

UPDATE table_name SET column_name = REPLACE(column_name,"search str","replace str");

Putting t.column_name in the first argument of replace did not work.

Aligning a button to the center

Here is what worked for me:

    <input type="submit" style="margin-left: 50%">

If you only add margin, without the left part, it will center the submit button into the middle of your entire page, making it difficult to find and rendering your form incomplete for people who don't have the patience to find a submit button lol. margin-left centers it within the same line, so it's not further down your page than you intended. You can also use pixels instead of percentage if you just want to indent the submit button a bit and not all the way halfway across the page.

Aborting a shell script if any command returns a non-zero value

An expression like

dosomething1 && dosomething2 && dosomething3

will stop processing when one of the commands returns with a non-zero value. For example, the following command will never print "done":

cat nosuchfile && echo "done"
echo $?
1

How to destroy a JavaScript object?

Structure your code so that all your temporary objects are located inside closures instead of global namespace / global object properties and go out of scope when you've done with them. GC will take care of the rest.

gcc warning" 'will be initialized after'

If you're seeing errors from library headers and you're using GCC, then you can disable warnings by including the headers using -isystem instead of -I.

Similar features exist in clang.

If you're using CMake, you can specify SYSTEM for include_directories.

SQL Query to add a new column after an existing column in SQL Server 2005

It's possible.

First, just add each column the usual way (as the last column).

Secondly, in SQL Server Management Studio Get into Tools => Options.

Under 'Designers' Tab => 'Table and Database Designers' menu, uncheck the option 'Prevent saving changes that require table re-creation'.

Afterwards, right click on your table and choose 'Design'. In 'Design' mode just drag the columns to order them.

Don't forget to save.

difference between iframe, embed and object elements

Another reason to use object over iframe is that object sub resources (when an <object> performs HTTP requests) are considered as passive/display in terms of Mixed content, which means it's more secure when you must have Mixed content.

Mixed content means that when you have https but your resource is from http.

Reference: https://developer.mozilla.org/en-US/docs/Web/Security/Mixed_content

Display XML content in HTML page

If you treat the content as text, not HTML, then DOM operations should cause the data to be properly encoded. Here's how you'd do it in jQuery:

$('#container').text(xmlString);

Here's how you'd do it with standard DOM methods:

document.getElementById('container')
        .appendChild(document.createTextNode(xmlString));

If you're placing the XML inside of HTML through server-side scripting, there are bound to be encoding functions to allow you to do that (if you add what your server-side technology is, we can give you specific examples of how you'd do it).

String to object in JS

I'm using JSON5, and it's works pretty well.

The good part is it contains no eval and no new Function, very safe to use.

Difference between dates in JavaScript

I have found this and it works fine for me:

Calculating the Difference between Two Known Dates

Unfortunately, calculating a date interval such as days, weeks, or months between two known dates is not as easy because you can't just add Date objects together. In order to use a Date object in any sort of calculation, we must first retrieve the Date's internal millisecond value, which is stored as a large integer. The function to do that is Date.getTime(). Once both Dates have been converted, subtracting the later one from the earlier one returns the difference in milliseconds. The desired interval can then be determined by dividing that number by the corresponding number of milliseconds. For instance, to obtain the number of days for a given number of milliseconds, we would divide by 86,400,000, the number of milliseconds in a day (1000 x 60 seconds x 60 minutes x 24 hours):

Date.daysBetween = function( date1, date2 ) {
  //Get 1 day in milliseconds
  var one_day=1000*60*60*24;

  // Convert both dates to milliseconds
  var date1_ms = date1.getTime();
  var date2_ms = date2.getTime();

  // Calculate the difference in milliseconds
  var difference_ms = date2_ms - date1_ms;

  // Convert back to days and return
  return Math.round(difference_ms/one_day); 
}

//Set the two dates
var y2k  = new Date(2000, 0, 1); 
var Jan1st2010 = new Date(y2k.getFullYear() + 10, y2k.getMonth(), y2k.getDate());
var today= new Date();
//displays 726
console.log( 'Days since ' 
           + Jan1st2010.toLocaleDateString() + ': ' 
           + Date.daysBetween(Jan1st2010, today));

The rounding is optional, depending on whether you want partial days or not.

Reference

Why does "pip install" inside Python raise a SyntaxError?

As @sinoroc suggested correct way of installing a package via pip is using separate process since pip may cause closing a thread or may require a restart of interpreter to load new installed package so this is the right way of using the API: subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'SomeProject']) but since Python allows to access internal API and you know what you're using the API for you may want to use internal API anyway eg. if you're building own GUI package manager with alternative resourcess like https://www.lfd.uci.edu/~gohlke/pythonlibs/

Following soulution is OUT OF DATE, instead of downvoting suggest updates. see https://github.com/pypa/pip/issues/7498 for reference.


UPDATE: Since pip version 10.x there is no more get_installed_distributions() or main method under import pip instead use import pip._internal as pip.

UPDATE ca. v.18 get_installed_distributions() has been removed. Instead you may use generator freeze like this:

from pip._internal.operations.freeze import freeze

print([package for package in freeze()])

# eg output ['pip==19.0.3']


If you want to use pip inside the Python interpreter, try this:

import pip

package_names=['selenium', 'requests'] #packages to install
pip.main(['install'] + package_names + ['--upgrade']) 
# --upgrade to install or update existing packages

If you need to update every installed package, use following:

import pip

for i in pip.get_installed_distributions():
    pip.main(['install', i.key, '--upgrade'])

If you want to stop installing other packages if any installation fails, use it in one single pip.main([]) call:

import pip

package_names = [i.key for i in pip.get_installed_distributions()]
pip.main(['install'] + package_names + ['--upgrade'])

Note: When you install from list in file with -r / --requirement parameter you do NOT need open() function.

pip.main(['install', '-r', 'filename'])

Warning: Some parameters as simple --help may cause python interpreter to stop.

Curiosity: By using pip.exe you actually use python interpreter and pip module anyway. If you unpack pip.exe or pip3.exe regardless it's python 2.x or 3.x, inside is the SAME single file __main__.py:

# -*- coding: utf-8 -*-
import re
import sys

from pip import main

if __name__ == '__main__':
    sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
    sys.exit(main())

Squaring all elements in a list

import numpy as np
a = [2 ,3, 4]
np.square(a)

Find and replace words/lines in a file

You might want to use Scanner to parse through and find the specific sections you want to modify. There's also Split and StringTokenizer that may work, but at the level you're working at Scanner might be what's needed.

Here's some additional info on what the difference is between them: Scanner vs. StringTokenizer vs. String.Split

How do you use the Immediate Window in Visual Studio?

Use the Immediate Window to Execute Commands

The Immediate Window can also be used to execute commands. Just type a > followed by the command.

enter image description here

For example >shell cmd will start a command shell (this can be useful to check what environment variables were passed to Visual Studio, for example). >cls will clear the screen.

Here is a list of commands that are so commonly used that they have their own aliases: https://msdn.microsoft.com/en-us/library/c3a0kd3x.aspx

How to install a .ipa file into my iPhone?

You need to install the provisioning profile (drag and drop it into iTunes). Then drag and drop the .ipa. Ensure you device is set to sync apps, and try again.

How to connect to a secure website using SSL in Java with a pkcs12 file?

I realise that this article may be outdated but still I would like to ask smithsv to correct his source code, it contains many mistakes, I managed to correct most of them but still don't know what kind of object x509 could be.Here is the source code as I think is should be:

import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.util.Enumeration;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;

public class Connection2 {
    public void connect() {
        /*
         * This is an example to use ONLY p12 file it's not optimazed but it
         * work. The pkcs12 file where generated by OpenSSL by me. Example how
         * to load p12 file and build Trust zone from it... It outputs
         * certificates from p12 file and add good certs to TrustStore
         */
        KeyStore ks = KeyStore.getInstance( "pkcs12" );
        ks.load( new FileInputStream( cert.pfx ), "passwrd".toCharArray() );

        KeyStore jks = KeyStore.getInstance( "JKS" );
        jks.load( null );

        for( Enumeration t = ks.aliases(); t.hasMoreElements(); ) {
            String alias = (String )t.nextElement();
            System.out.println( "@:" + alias );
            if( ks.isKeyEntry( alias ) ) {
                Certificate[] a = ks.getCertificateChain( alias );
                for( int i = 0; i == 0; )
                    jks.setCertificateEntry( x509Cert.getSubjectDN().toString(), x509 );

                System.out.println( ks.getCertificateAlias( x509 ) );
                System.out.println( "ok" );
            }
        }

        System.out.println( "init Stores..." );

        KeyManagerFactory kmf = KeyManagerFactory.getInstance( "SunX509" );
        kmf.init( ks, "c1".toCharArray() );

        TrustManagerFactory tmf = TrustManagerFactory.getInstance( "SunX509" );
        tmf.init( jks );

        SSLContext ctx = SSLContext.getInstance( "TLS" );
        ctx.init( kmf.getKeyManagers(), tmf.getTrustManagers(), null );
    }
}

Set the location in iPhone Simulator

As of the writing of this, the location option for IOS simulator has been moved to Features -> Location -> Custom Location

Searching word in vim?

If you are working in Ubuntu,follow the steps:

  1. Press / and type word to search
  2. To search in forward press 'SHIFT' key with * key
  3. To search in backward press 'SHIFT' key with # key

recursion versus iteration

Short answer: the trade off is recursion is faster and for loops take up less memory in almost all cases. However there are usually ways to change the for loop or recursion to make it run faster

Calculate the execution time of a method

StopWatch will use the high-resolution counter

The Stopwatch measures elapsed time by counting timer ticks in the underlying timer mechanism. If the installed hardware and operating system support a high-resolution performance counter, then the Stopwatch class uses that counter to measure elapsed time. Otherwise, the Stopwatch class uses the system timer to measure elapsed time. Use the Frequency and IsHighResolution fields to determine the precision and resolution of the Stopwatch timing implementation.

If you're measuring IO then your figures will likely be impacted by external events, and I would worry so much re. exactness (as you've indicated above). Instead I'd take a range of measurements and consider the mean and distribution of those figures.

HashMap(key: String, value: ArrayList) returns an Object instead of ArrayList?

The get method of the HashMap is returning an Object, but the variable current is expected to take a ArrayList:

ArrayList current = new ArrayList();
// ...
current = dictMap.get(dictCode);

For the above code to work, the Object must be cast to an ArrayList:

ArrayList current = new ArrayList();
// ...
current = (ArrayList)dictMap.get(dictCode);

However, probably the better way would be to use generic collection objects in the first place:

HashMap<String, ArrayList<Object>> dictMap =
    new HashMap<String, ArrayList<Object>>();

// Populate the HashMap.

ArrayList<Object> current = new ArrayList<Object>();      
if(dictMap.containsKey(dictCode)) {
    current = dictMap.get(dictCode);   
}

The above code is assuming that the ArrayList has a list of Objects, and that should be changed as necessary.

For more information on generics, The Java Tutorials has a lesson on generics.

Python syntax for "if a or b or c but not all of them"

This is basically a "some (but not all)" functionality (when contrasted with the any() and all() builtin functions).

This implies that there should be Falses and Trues among the results. Therefore, you can do the following:

some = lambda ii: frozenset(bool(i) for i in ii).issuperset((True, False))

# one way to test this is...
test = lambda iterable: (any(iterable) and (not all(iterable))) # see also http://stackoverflow.com/a/16522290/541412

# Some test cases...
assert(some(()) == False)       # all() is true, and any() is false
assert(some((False,)) == False) # any() is false
assert(some((True,)) == False)  # any() and all() are true

assert(some((False,False)) == False)
assert(some((True,True)) == False)
assert(some((True,False)) == True)
assert(some((False,True)) == True)

One advantage of this code is that you only need to iterate once through the resulting (booleans) items.

One disadvantage is that all these truth-expressions are always evaluated, and do not do short-circuiting like the or/and operators.

XOR operation with two strings in java

Note: this only works for low characters i.e. below 0x8000, This works for all ASCII characters.

I would do an XOR each charAt() to create a new String. Like

String s, key;

StringBuilder sb = new StringBuilder();
for(int i = 0; i < s.length(); i++)
    sb.append((char)(s.charAt(i) ^ key.charAt(i % key.length())));
String result = sb.toString();

In response to @user467257's comment

If your input/output is utf-8 and you xor "a" and "æ", you are left with an invalid utf-8 string consisting of one character (decimal 135, a continuation character).

It is the char values which are being xor'ed, but the byte values and this produces a character whichc an be UTF-8 encoded.

public static void main(String... args) throws UnsupportedEncodingException {
    char ch1 = 'a';
    char ch2 = 'æ';
    char ch3 = (char) (ch1 ^ ch2);
    System.out.println((int) ch3 + " UTF-8 encoded is " + Arrays.toString(String.valueOf(ch3).getBytes("UTF-8")));
}

prints

135 UTF-8 encoded is [-62, -121]

How to convert ZonedDateTime to Date?

If you are using the ThreeTen backport for Android and can't use the newer Date.from(Instant instant) (which requires minimum of API 26) you can use:

ZonedDateTime zdt = ZonedDateTime.now();
Date date = new Date(zdt.toInstant().toEpochMilli());

or:

Date date = DateTimeUtils.toDate(zdt.toInstant());

Please also read the advice in Basil Bourque's answer

How do I set a variable to the output of a command in Bash?

This is another way and is good to use with some text editors that are unable to correctly highlight every intricate code you create:

read -r -d '' str < <(cat somefile.txt)
echo "${#str}"
echo "$str"

Hide "NFC Tag type not supported" error on Samsung Galaxy devices

Before Android 4.4

What you are trying to do is simply not possible from an app (at least not on a non-rooted/non-modified device). The message "NFC tag type not supported" is displayed by the Android system (or more specifically the NFC system service) before and instead of dispatching the tag to your app. This means that the NFC system service filters MIFARE Classic tags and never notifies any app about them. Consequently, your app can't detect MIFARE Classic tags or circumvent that popup message.

On a rooted device, you may be able to bypass the message using either

  1. Xposed to modify the behavior of the NFC service, or
  2. the CSC (Consumer Software Customization) feature configuration files on the system partition (see /system/csc/. The NFC system service disables the popup and dispatches MIFARE Classic tags to apps if the CSC feature <CscFeature_NFC_EnableSecurityPromptPopup> is set to any value but "mifareclassic" or "all". For instance, you could use:

    <CscFeature_NFC_EnableSecurityPromptPopup>NONE</CscFeature_NFC_EnableSecurityPromptPopup>
    

    You could add this entry to, for instance, the file "/system/csc/others.xml" (within the section <FeatureSet> ... </FeatureSet> that already exists in that file).

Since, you asked for the Galaxy S6 (the question that you linked) as well: I have tested this method on the S4 when it came out. I have not verified if this still works in the latest firmware or on other devices (e.g. the S6).

Since Android 4.4

This is pure guessing, but according to this (link no longer available), it seems that some apps (e.g. NXP TagInfo) are capable of detecting MIFARE Classic tags on affected Samsung devices since Android 4.4. This might mean that foreground apps are capable of bypassing that popup using the reader-mode API (see NfcAdapter.enableReaderMode) possibly in combination with NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK.

Install apps silently, with granted INSTALL_PACKAGES permission

you can use this in terminal or shell

adb shell install -g MyApp.apk

see more in develope google

How can I make a button redirect my page to another page?

This is here:

 <button onClick="window.location='page_name.php';" value="click here" />

I have Python on my Ubuntu system, but gcc can't find Python.h

You need python-dev installed.
For Ubuntu :
sudo apt-get install python-dev # for python2.x installs sudo apt-get install python3-dev # for python3.x installs
For more distros, refer -
https://stackoverflow.com/a/21530768/6841045

How can I pass a reference to a function, with parameters?

The following is equivalent to your second code block:

var f = function () {
        //Some logic here...
    };

var fr = f;

fr(pars);

If you want to actually pass a reference to a function to some other function, you can do something like this:

function fiz(x, y, z) {
    return x + y + z;
}

// elsewhere...

function foo(fn, p, q, r) {
    return function () {
        return fn(p, q, r);
    }
}

// finally...

f = foo(fiz, 1, 2, 3);
f(); // returns 6

You're almost certainly better off using a framework for this sort of thing, though.

Not unique table/alias

Your query contains columns which could be present with the same name in more than one table you are referencing, hence the not unique error. It's best if you make the references explicit and/or use table aliases when joining.

Try

    SELECT pa.ProjectID, p.Project_Title, a.Account_ID, a.Username, a.Access_Type, c.First_Name, c.Last_Name
      FROM Project_Assigned pa
INNER JOIN Account a
        ON pa.AccountID = a.Account_ID
INNER JOIN Project p
        ON pa.ProjectID = p.Project_ID
INNER JOIN Clients c
        ON a.Account_ID = c.Account_ID
     WHERE a.Access_Type = 'Client';

Javascript Iframe innerHTML

Don't forget that you can not cross domains because of security.

So if this is the case, you should use JSON.

How to declare a variable in MySQL?

SET Value

 declare Regione int;   
 set Regione=(select  id from users
 where id=1) ;
 select Regione ;

Testing for empty or nil-value string

The second clause does not need a !variable.nil? check—if evaluation reaches that point, variable.nil is guaranteed to be false (because of short-circuiting).

This should be sufficient:

variable = id if variable.nil? || variable.empty?

If you're working with Ruby on Rails, Object.blank? solves this exact problem:

An object is blank if it’s false, empty, or a whitespace string. For example, "", " ", nil, [], and {} are all blank.

Two div blocks on same line

Try an HTML table or use the following CSS :

<div id="bloc1" style="float:left">...</div>
<div id="bloc2">...</div>

(or use an HTML table)

Form Validation With Bootstrap (jQuery)

Check this library, it's completable with booth bootstrap 3 and bootstrap 4

jQuery

<form>
    <div class="form-group">
        <input class="form-control" data-validator="required|min:4|max:10">
    </div>
</form>

Javascript

$(document).on('blur', '[data-validator]', function () {
    new Validator($(this));
});

Is there a simple way to remove multiple spaces in a string?

def unPretty(S):
   # Given a dictionary, JSON, list, float, int, or even a string...
   # return a string stripped of CR, LF replaced by space, with multiple spaces reduced to one.
   return ' '.join(str(S).replace('\n', ' ').replace('\r', '').split())

Visual studio equivalent of java System.out

Use Either Debug.WriteLine() or Trace.WriteLine(). If in release mode, only the latter will appear in the output window, in debug mode, both will.

Purpose of returning by const value?

It makes sure that the returned object (which is an RValue at that point) can't be modified. This makes sure the user can't do thinks like this:

myFunc() = Object(...);

That would work nicely if myFunc returned by reference, but is almost certainly a bug when returned by value (and probably won't be caught by the compiler). Of course in C++11 with its rvalues this convention doesn't make as much sense as it did earlier, since a const object can't be moved from, so this can have pretty heavy effects on performance.

Trigger change event <select> using jquery

$('#edit_user_details').find('select').trigger('change');

It would change the select html tag drop-down item with id="edit_user_details".

Programmatically set the initial view controller using Storyboards

If you prefer not to change applicationDidFinish, you can do the following trick:

Set Navigation controller as an initial view controller and assign to it a custom class 'MyNavigationController'. Then you can tweak its root view controller during viewDidLoad - it will override the root view controller that you set in your storyboard.

class MyNavigationController: UINavigationController {
    override func viewDidLoad() {
        super.viewDidLoad()
        if !isLoggedIn() {
            viewControllers = [R.storyboard.authentication.loginView()!]
        }
    }

    private func isLoggedIn() -> Bool {
        return false
    }

}

Set width of a "Position: fixed" div relative to parent div

There is an easy solution for this.

I have used a fixed position for parent div and a max-width for the contents.

You don't need to think about too much about other containers because fixed position only relative to the browser window.

_x000D_
_x000D_
       .fixed{_x000D_
            width:100%;_x000D_
            position:fixed;_x000D_
            height:100px;_x000D_
            background: red;_x000D_
        }_x000D_
_x000D_
        .fixed .content{_x000D_
            max-width: 500px;_x000D_
            background:blue;_x000D_
            margin: 0 auto;_x000D_
            text-align: center;_x000D_
            padding: 20px 0;_x000D_
        }
_x000D_
<div class="fixed">_x000D_
  <div class="content">_x000D_
     This is my content_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to read a text file from server using JavaScript?

Just a small point, I see some of the answers using innerhtml. I have toyed with a similar idea but decided not too, In the latest version react version the same process is now called dangerouslyinnerhtml, as you are giving your client a way into your OS by presenting html in the app. This could lead to various attacks as well as SQL injection attempts

tkinter: Open a new window with a button prompt

Here's the nearly shortest possible solution to your question. The solution works in python 3.x. For python 2.x change the import to Tkinter rather than tkinter (the difference being the capitalization):

import tkinter as tk
#import Tkinter as tk  # for python 2
    
def create_window():
    window = tk.Toplevel(root)

root = tk.Tk()
b = tk.Button(root, text="Create new window", command=create_window)
b.pack()

root.mainloop()

This is definitely not what I recommend as an example of good coding style, but it illustrates the basic concepts: a button with a command, and a function that creates a window.

Check if string contains only letters in javascript

With /^[a-zA-Z]/ you only check the first character:

  • ^: Assert position at the beginning of the string
  • [a-zA-Z]: Match a single character present in the list below:
    • a-z: A character in the range between "a" and "z"
    • A-Z: A character in the range between "A" and "Z"

If you want to check if all characters are letters, use this instead:

/^[a-zA-Z]+$/.test(str);
  • ^: Assert position at the beginning of the string
  • [a-zA-Z]: Match a single character present in the list below:
    • +: Between one and unlimited times, as many as possible, giving back as needed (greedy)
    • a-z: A character in the range between "a" and "z"
    • A-Z: A character in the range between "A" and "Z"
  • $: Assert position at the end of the string (or before the line break at the end of the string, if any)

Or, using the case-insensitive flag i, you could simplify it to

/^[a-z]+$/i.test(str);

Or, since you only want to test, and not match, you could check for the opposite, and negate it:

!/[^a-z]/i.test(str);

How to Empty Caches and Clean All Targets Xcode 4 and later

To delete all derived data and the module cache in /var/folders use this little ruby script.

derivedDataFolder = Dir.glob(Dir.home + "/Library/Developer/Xcode/DerivedData/*")
moduleCache = Dir.glob("/var/folders/**/com.apple.DeveloperTools*")
FileUtils.rm_rf derivedDataFolder + moduleCache

This just solved a fatal error: malformed or corrupted AST file: 'Unable to load module "/var/folders/ error for me.

How to order events bound with jQuery

You can try something like this:

/**
  * Guarantee that a event handler allways be the last to execute
  * @param owner The jquery object with any others events handlers $(selector)
  * @param event The event descriptor like 'click'
  * @param handler The event handler to be executed allways at the end.
**/
function bindAtTheEnd(owner,event,handler){
    var aux=function(){owner.unbind(event,handler);owner.bind(event,handler);};
    bindAtTheStart(owner,event,aux,true);

}
/**
  * Bind a event handler at the start of all others events handlers.
  * @param owner Jquery object with any others events handlers $(selector);
  * @param event The event descriptor for example 'click';
  * @param handler The event handler to bind at the start.
  * @param one If the function only be executed once.
**/
function bindAtTheStart(owner,event,handler,one){
    var eventos,index;
    var handlers=new Array();
    owner.unbind(event,handler);
    eventos=owner.data("events")[event];
    for(index=0;index<eventos.length;index+=1){
        handlers[index]=eventos[index];
    }
    owner.unbind(event);
    if(one){
        owner.one(event,handler);
    }
    else{
        owner.bind(event,handler);
    }
    for(index=0;index<handlers.length;index+=1){
        owner.bind(event,ownerhandlers[index]);
    }   
}

insert echo into the specific html element like div which has an id or class

The only things I can think of are

  1. including files
  2. replacing elements within files using preg_match_all
  3. using assigned variables

I have recently been using str_replace and setting text in the HTML portion like so

{{TEXT_TO_REPLACE}}

using file_get_contents() you can grab html data and then organise it how you like.

here is a demo

myReplacementCodeFunction(){
  $text = '<img src="'.$row['name'].'" />'; 
  $text .= "<div>".$row['name']."</div>";
  $text .= "<div>".$row['title']."</div>";
  $text .= "<div>".$row['description']."</div>";
  $text .= "<div>".$row['link']."</div>";
  $text .= "<br />";
  return $text;
}

$htmlContents = file_get_contents("myhtmlfile.html");
$htmlContents = str_replace("{{TEXT_TO_REPLACE}}", myReplacementCodeFunction(), $htmlContents);
echo $htmlContents;

and now a demo html file:

<html>
<head>
   <style type="text/css">
      body{background:#666666;}
      div{border:1px solid red;}
   </style>
  </head>
  <body>
    {{TEXT_TO_REPLACE}}
  </body>
</html>

AttributeError: 'module' object has no attribute 'urlopen'

import urllib
import urllib.request
from bs4 import BeautifulSoup


with urllib.request.urlopen("http://www.newegg.com/") as url:
    s = url.read()
    print(s)
soup = BeautifulSoup(s, "html.parser")
all_tag_a = soup.find_all("a", limit=10)

for links in all_tag_a:
    #print(links.get('href'))
    print(links)

“Unable to find manifest signing certificate in the certificate store” - even when add new key

  1. Open the .csproj file in Notepad.
  2. Delete the following information related to signing certificate in the certificate store

    <PropertyGroup>
      <ManifestCertificateThumbprint>xxxxx xxxxxx</ManifestCertificateThumbprint>
      <ManifestKeyFile>xxxxxxxx.pfx</ManifestKeyFile>
    <GenerateManifests>true</GenerateManifests>
    <SignManifests>false</SignManifests>
    </PropertyGroup>
    

Truncate Two decimal places without rounding

i am using this function to truncate value after decimal in a string variable

public static string TruncateFunction(string value)
    {
        if (string.IsNullOrEmpty(value)) return "";
        else
        {
            string[] split = value.Split('.');
            if (split.Length > 0)
            {
                string predecimal = split[0];
                string postdecimal = split[1];
                postdecimal = postdecimal.Length > 6 ? postdecimal.Substring(0, 6) : postdecimal;
                return predecimal + "." + postdecimal;

            }
            else return value;
        }
    }

No assembly found containing an OwinStartupAttribute Error

I was missing the attribute:

[assembly: OwinStartupAttribute(typeof(projectname.Startup))]

Which specifies the startup class. More details: https://docs.microsoft.com/en-us/aspnet/aspnet/overview/owin-and-katana/owin-startup-class-detection

Loading and parsing a JSON file with multiple JSON objects

That is ill-formatted. You have one JSON object per line, but they are not contained in a larger data structure (ie an array). You'll either need to reformat it so that it begins with [ and ends with ] with a comma at the end of each line, or parse it line by line as separate dictionaries.

SQL Server convert string to datetime

For instance you can use

update tablename set datetimefield='19980223 14:23:05'
update tablename set datetimefield='02/23/1998 14:23:05'
update tablename set datetimefield='1998-12-23 14:23:05'
update tablename set datetimefield='23 February 1998 14:23:05'
update tablename set datetimefield='1998-02-23T14:23:05'

You need to be careful of day/month order since this will be language dependent when the year is not specified first. If you specify the year first then there is no problem; date order will always be year-month-day.

The HTTP request is unauthorized with client authentication scheme 'Ntlm' The authentication header received from the server was 'NTLM'

Visual Studio 2005

  1. Create a new console application project in Visual Studio
  2. Add a "Web Reference" to the Lists.asmx web service.
    • Your URL will probably look like: http://servername/sites/SiteCollection/SubSite/_vti_bin/Lists.asmx
    • I named my web reference: ListsWebService
  3. Write the code in program.cs (I have an Issues list here)

Here is the code.

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;

namespace WebServicesConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                ListsWebService.Lists listsWebSvc = new WebServicesConsoleApp.ListsWebService.Lists();
                listsWebSvc.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
                listsWebSvc.Url = "http://servername/sites/SiteCollection/SubSite/_vti_bin/Lists.asmx";
                XmlNode node = listsWebSvc.GetList("Issues");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
    }
}

Visual Studio 2008

  1. Create a new console application project in Visual Studio
  2. Right click on References and Add Service Reference
  3. Put in the URL to the Lists.asmx service on your server
    • Ex: http://servername/sites/SiteCollection/SubSite/_vti_bin/Lists.asmx
  4. Click Go
  5. Click OK
  6. Make the following code changes:

Change your app.config file from:

<security mode="None">
    <transport clientCredentialType="None" proxyCredentialType="None"
        realm="" />
    <message clientCredentialType="UserName" algorithmSuite="Default" />
</security>

To:

<security mode="TransportCredentialOnly">
  <transport clientCredentialType="Ntlm"/>
</security>

Change your program.cs file and add the following code to your Main function:

ListsSoapClient client = new ListsSoapClient();
client.ClientCredentials.Windows.ClientCredential = System.Net.CredentialCache.DefaultNetworkCredentials;
client.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
XmlElement listCollection = client.GetListCollection();

Add the using statements:

using [your app name].ServiceReference1;
using System.Xml;

Reference: http://sharepointmagazine.net/technical/development/writing-caml-queries-for-retrieving-list-items-from-a-sharepoint-list

select count(*) from table of mysql in php

For mysqli users, the code will look like this:

$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_name);

$result = $mysqli->query("SELECT COUNT(*) AS Students_count FROM Students")->fetch_array();
var_dump($result['Students_count']);

or:

$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_name);

$result = $mysqli->query("SELECT COUNT(*) FROM Students")->fetch_array();
var_dump($result[0]);

how to read a long multiline string line by line in python

This answer fails in a couple of edge cases (see comments). The accepted solution above will handle these. str.splitlines() is the way to go. I will leave this answer nevertheless as reference.

Old (incorrect) answer:

s =  \
"""line1
line2
line3
"""

lines = s.split('\n')
print(lines)
for line in lines:
    print(line)

How can I get the source directory of a Bash script from within the script itself?

I tried the followings with 3 different executions.

echo $(realpath $_)

. application         # /correct/path/to/dir or /path/to/temporary_dir
bash application      # /path/to/bash
/PATH/TO/application  # /correct/path/to/dir

echo $(realpath $(dirname $0))

. application         # failed with `realpath: missing operand`
bash application      # /correct/path/to/dir
/PATH/TO/application  # /correct/path/to/dir

echo $(realpath $BASH_SOURCE)

$BASH_SOURCE is basically the same with ${BASH_SOURCE[0]}.

. application         # /correct/path/to/dir
bash application      # /correct/path/to/dir
/PATH/TO/application  # /correct/path/to/dir

Only $(realpath $BASH_SOURCE) seems to be reliable.

Open Sublime Text from Terminal in macOS

Close Sublime. Run this command. It will uninstall it. You won't lose your prefs. Then run it again. It will automatically bind subl.

brew install Caskroom/cask/sublime-text

How to remove stop words using nltk or python

I suppose you have a list of words (word_list) from which you want to remove stopwords. You could do something like this:

filtered_word_list = word_list[:] #make a copy of the word_list
for word in word_list: # iterate over word_list
  if word in stopwords.words('english'): 
    filtered_word_list.remove(word) # remove word from filtered_word_list if it is a stopword

javascript functions to show and hide divs

Rename the closing function as 'hide', for example and it will work.

function hide() {
    if(document.getElementById('benefits').style.display=='block') {
      document.getElementById('benefits').style.display='none';
    }
} 

Convert .class to .java

I'm guessing that either the class name is wrong - be sure to use the fully-resolved class name, with all packages - or it's not in the CLASSPATH so javap can't find it.

How can I give the Intellij compiler more heap space?

In my case the error was caused by the insufficient memory allocated to the "test" lifecycle of maven. It was fixed by adding <argLine>-Xms3512m -Xmx3512m</argLine> to:

<pluginManagement>
  <plugins>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.16</version>
        <configuration>
            <argLine>-Xms3512m -Xmx3512m</argLine>

Thanks @crazycoder for pointing this out (and also that it is not related to IntelliJ; in this case).

If your tests are forked, they run in a new JVM that doesn't inherit Maven JVM options. Custom memory options must be provided via the test runner in pom.xml, refer to Maven documentation for details, it has very little to do with the IDE.

How to change current Theme at runtime in Android

You can finish the Acivity and recreate it afterwards in this way your activity will be created again and all the views will be created with the new theme.

Can't ignore UserInterfaceState.xcuserstate

For me nothing worked, but this

add this line to your gitignore

*.xcuserdata

Open file by its full path in C++

You can use a full path with the fstream classes. The folowing code attempts to open the file demo.txt in the root of the C: drive. Note that as this is an input operation, the file must already exist.

#include <fstream>
#include <iostream>
using namespace std;

int main() {
   ifstream ifs( "c:/demo.txt" );       // note no mode needed
   if ( ! ifs.is_open() ) {                 
      cout <<" Failed to open" << endl;
   }
   else {
      cout <<"Opened OK" << endl;
   }
}

What does this code produce on your system?

How to format DateTime columns in DataGridView?

If it is a windows form Datagrid, you could use the below code to format the datetime for a column

dataGrid.Columns[2].DefaultCellStyle.Format = "MM/dd/yyyy HH:mm:ss";

EDIT :

Apart from this, if you need the datetime in AM/PM format, you could use the below code

dataGrid.Columns[2].DefaultCellStyle.Format = "MM/dd/yyyy hh:mm:ss tt";

how to split the ng-repeat data with three columns using bootstrap

I found myself in a similar case, wanting to generate display groups of 3 columns each. However, although I was using bootstrap, I was trying to separate these groups into different parent divs. I also wanted to make something generically useful.

I approached it with 2 ng-repeat as below:

<div ng-repeat="items in quotes" ng-if="!($index % 3)">
  <div ng-repeat="quote in quotes" ng-if="$index <= $parent.$index + 2 && $index >= $parent.$index">
                ... some content ...
  </div>
</div>

This makes it very easy to change to a different number of columns, and separated out into several parent divs.

How to convert all text to lowercase in Vim

If you are running under a flavor of Unix

:0,$!tr "[A-Z]" "[a-z]"

LINQ - Full Outer Join

I think that LINQ join clause isn't the correct solution to this problem, because of join clause purpose isn't to accumulate data in such way as required for this task solution. The code to merge created separate collections becomes too complicated, maybe it is OK for learning purposes, but not for real applications. One of the ways how to solve this problem is in the code below:

class Program
{
    static void Main(string[] args)
    {
        List<FirstName> firstNames = new List<FirstName>();
        firstNames.Add(new FirstName { ID = 1, Name = "John" });
        firstNames.Add(new FirstName { ID = 2, Name = "Sue" });

        List<LastName> lastNames = new List<LastName>();
        lastNames.Add(new LastName { ID = 1, Name = "Doe" });
        lastNames.Add(new LastName { ID = 3, Name = "Smith" });

        HashSet<int> ids = new HashSet<int>();
        foreach (var name in firstNames)
        {
            ids.Add(name.ID);
        }
        foreach (var name in lastNames)
        {
            ids.Add(name.ID);
        }
        List<FullName> fullNames = new List<FullName>();
        foreach (int id in ids)
        {
            FullName fullName = new FullName();
            fullName.ID = id;
            FirstName firstName = firstNames.Find(f => f.ID == id);
            fullName.FirstName = firstName != null ? firstName.Name : string.Empty;
            LastName lastName = lastNames.Find(l => l.ID == id);
            fullName.LastName = lastName != null ? lastName.Name : string.Empty;
            fullNames.Add(fullName);
        }
    }
}
public class FirstName
{
    public int ID;

    public string Name;
}

public class LastName
{
    public int ID;

    public string Name;
}
class FullName
{
    public int ID;

    public string FirstName;

    public string LastName;
}

If real collections are large for HashSet formation instead foreach loops can be used the code below:

List<int> firstIds = firstNames.Select(f => f.ID).ToList();
List<int> LastIds = lastNames.Select(l => l.ID).ToList();
HashSet<int> ids = new HashSet<int>(firstIds.Union(LastIds));//Only unique IDs will be included in HashSet

How to write and save html file in python?

shorter version of Nurul Akter Towhid's answer (the fp.close is automated):

with open("my.html","w") as fp:
   fp.write(html)

Differences Between vbLf, vbCrLf & vbCr Constants

The three constants have similar functions nowadays, but different historical origins, and very occasionally you may be required to use one or the other.

You need to think back to the days of old manual typewriters to get the origins of this. There are two distinct actions needed to start a new line of text:

  1. move the typing head back to the left. In practice in a typewriter this is done by moving the roll which carries the paper (the "carriage") all the way back to the right -- the typing head is fixed. This is a carriage return.
  2. move the paper up by the width of one line. This is a line feed.

In computers, these two actions are represented by two different characters - carriage return is CR, ASCII character 13, vbCr; line feed is LF, ASCII character 10, vbLf. In the old days of teletypes and line printers, the printer needed to be sent these two characters -- traditionally in the sequence CRLF -- to start a new line, and so the CRLF combination -- vbCrLf -- became a traditional line ending sequence, in some computing environments.

The problem was, of course, that it made just as much sense to only use one character to mark the line ending, and have the terminal or printer perform both the carriage return and line feed actions automatically. And so before you knew it, we had 3 different valid line endings: LF alone (used in Unix and Macintoshes), CR alone (apparently used in older Mac OSes) and the CRLF combination (used in DOS, and hence in Windows). This in turn led to the complications of DOS / Windows programs having the option of opening files in text mode, where any CRLF pair read from the file was converted to a single CR (and vice versa when writing).

So - to cut a (much too) long story short - there are historical reasons for the existence of the three separate line separators, which are now often irrelevant: and perhaps the best course of action in .NET is to use Environment.NewLine which means someone else has decided for you which to use, and future portability issues should be reduced.

Dependency Walker reports IESHIMS.DLL and WER.DLL missing?

1· Do I need these DLL's?

It depends since Dependency Walker is a little bit out of date and may report the wrong dependency.

  1. Where can I get them?

most dlls can be found at https://www.dll-files.com

I believe they are supposed to located in C:\Windows\System32\Wer.dll and C:\Program Files\Internet Explorer\Ieshims.dll

For me leshims.dll can be placed at C:\Windows\System32\. Context: windows 7 64bit.

How do you send an HTTP Get Web Request in Python?

You can use urllib2

import urllib2
content = urllib2.urlopen(some_url).read()
print content

Also you can use httplib

import httplib
conn = httplib.HTTPConnection("www.python.org")
conn.request("HEAD","/index.html")
res = conn.getresponse()
print res.status, res.reason
# Result:
200 OK

or the requests library

import requests
r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
r.status_code
# Result:
200

What characters are allowed in an email address?

You can start from wikipedia article:

  • Uppercase and lowercase English letters (a-z, A-Z)
  • Digits 0 to 9
  • Characters ! # $ % & ' * + - / = ? ^ _ ` { | } ~
  • Character . (dot, period, full stop) provided that it is not the first or last character, and provided also that it does not appear two or more times consecutively.

Should URL be case sensitive?

Depends on the hosting os. Sites that are hosted on Windows tend to be case insensitive as the underlying file system is case insensitive. Sites hosted on Unix type systems tend to be case sensitive as their underlying file systems are typically case sensitive. The host name part of the URL is always case insensitive, it's the rest of the path that varies.

How do I print the type or class of a variable in Swift?

Another important aspect that influences the class name returned from String(describing: type(of: self)) is Access Control.

Consider the following example, based on Swift 3.1.1, Xcode 8.3.3 (July 2017)

func printClassNames() {

    let className1 = SystemCall<String>().getClassName()
    print(className1) // prints: "SystemCall<String>"

    let className2 = DemoSystemCall().getClassName()
    print(className2) // prints: "DemoSystemCall"

    // private class example
    let className3 = PrivateDemoSystemCall().getClassName()
    print(className3) // prints: "(PrivateDemoSystemCall in _0FC31E1D2F85930208C245DE32035247)" 

    // fileprivate class example
    let className4 = FileprivateDemoSystemCall().getClassName()
    print(className4) // prints: "(FileprivateDemoSystemCall in _0FC31E1D2F85930208C245DE32035247)" 
}

class SystemCall<T> {
    func getClassName() -> String {
        return String(describing: type(of: self))
    }
}

class DemoSystemCall: SystemCall<String> { }

private class PrivateDemoSystemCall: SystemCall<String> { }

fileprivate class FileprivateDemoSystemCall: SystemCall<String> { }

As you can see, all classes in this example have different levels of access control which influence their String representation. In case the classes have private or fileprivate access control levels, Swift seems to append some kind of identifier related to the "nesting" class of the class in question.

The result for both PrivateDemoSystemCall and FileprivateDemoSystemCall is that the same identifier is appended because they both are nested in the same parent class.

I have not yet found a way to get rid of that, other than some hacky replace or regex function.

Just my 2 cents.

Connecting to SQL Server using windows authentication

Check out www.connectionstrings.com for a ton of samples of proper connection strings.

In your case, use this:

Server=localhost;Database=employeedetails;Integrated Security=SSPI

Update: obviously, the service account used to run ASP.NET web apps doesn't have access to SQL Server, and judging from that error message, you're probably using "anonymous authentication" on your web site.

So you either need to add this account IIS APPPOOL\ASP.NET V4.0 as a SQL Server login and give that login access to your database, or you need to switch to using "Windows authentication" on your ASP.NET web site so that the calling Windows account will be passed through to SQL Server and used as a login on SQL Server.

Prevent WebView from displaying "web page not available"

I would just change the webpage to whatever you are using for error handling:

getWindow().requestFeature(Window.FEATURE_PROGRESS);  
webview.getSettings().setJavaScriptEnabled(true);  
final Activity activity = this;  
webview.setWebChromeClient(new WebChromeClient() {  
public void onProgressChanged(WebView view, int progress) {  
 // Activities and WebViews measure progress with different scales.  
 // The progress meter will automatically disappear when we reach 100%  
 activity.setProgress(progress * 1000);  
 }  
});  
webview.setWebViewClient(new WebViewClient() {  
public void onReceivedError(WebView view, int errorCode, String description, String 
failingUrl) {  
 Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();  
}  
});  
webview.loadUrl("http://slashdot.org/");

this can all be found on http://developer.android.com/reference/android/webkit/WebView.html

Including external jar-files in a new jar-file build with Ant

From your ant buildfile, I assume that what you want is to create a single JAR archive that will contain not only your application classes, but also the contents of other JARs required by your application.

However your build-jar file is just putting required JARs inside your own JAR; this will not work as explained here (see note).

Try to modify this:

<jar destfile="${jar.file}" 
    basedir="${build.dir}" 
    manifest="${manifest.file}">
    <fileset dir="${classes.dir}" includes="**/*.class" />
    <fileset dir="${lib.dir}" includes="**/*.jar" />
</jar>

to this:

<jar destfile="${jar.file}" 
    basedir="${build.dir}" 
    manifest="${manifest.file}">
    <fileset dir="${classes.dir}" includes="**/*.class" />
    <zipgroupfileset dir="${lib.dir}" includes="**/*.jar" />
</jar>

More flexible and powerful solutions are the JarJar or One-Jar projects. Have a look into those if the above does not satisfy your requirements.

How to wait until an element exists?

The observe function below will allow you to listen to elements via a selector.

In the following example, after 2 seconds have passed, a .greeting will be inserted into the .container. Since we are listening to the insertion of this element, we can have a callback that triggers upon insertion.

_x000D_
_x000D_
const observe = (selector, callback, targetNode = document.body) =>
  new MutationObserver(mutations => [...mutations]
    .flatMap((mutation) => [...mutation.addedNodes])
    .filter((node) => node.matches && node.matches(selector))
    .forEach(callback))
  .observe(targetNode, { childList: true, subtree: true });

const createGreeting = () => {
  const el = document.createElement('DIV');
  el.textContent = 'Hello World';
  el.classList.add('greeting');
  return el;
};

const container = document.querySelector('.container');

observe('.greeting', el => console.log('I have arrived!', el), container);

new Promise(res => setTimeout(() => res(createGreeting()), 2000))
  .then(el => container.appendChild(el));
_x000D_
html, body { width: 100%; height: 100%; margin: 0; padding: 0; }
body { display: flex; }
.container { display: flex; flex: 1; align-items: center; justify-content: center; }
.greeting { font-weight: bold; font-size: 2em; }
_x000D_
<div class="container"></div>
_x000D_
_x000D_
_x000D_

JavaScript - Get minutes between two dates

var startTime = new Date('2012/10/09 12:00'); 
var endTime = new Date('2013/10/09 12:00');
var difference = endTime.getTime() - startTime.getTime(); // This will give difference in milliseconds
var resultInMinutes = Math.round(difference / 60000);

Branch from a previous commit using Git

Go to a particular commit of a git repository

Sometimes when working on a git repository you want to go back to a specific commit (revision) to have a snapshot of your project at a specific time. To do that all you need it the SHA-1 hash of the commit which you can easily find checking the log with the command:

git log --abbrev-commit --pretty=oneline

which will give you a compact list of all the commits and the short version of the SHA-1 hash.

Now that you know the hash of the commit you want to go to you can use one of the following 2 commands:

git checkout HASH

or

git reset --hard HASH

checkout

git checkout <commit> <paths>

Tells git to replace the current state of paths with their state in the given commit. Paths can be files or directories.

If no branch is given, git assumes the HEAD commit.

git checkout <path> // restores path from your last commit. It is a 'filesystem-undo'.

If no path is given, git moves HEAD to the given commit (thereby changing the commit you're sitting and working on).

git checkout branch //means switching branches.

reset

git reset <commit> //re-sets the current pointer to the given commit.

If you are on a branch (you should usually be), HEAD and this branch are moved to commit.

If you are in detached HEAD state, git reset does only move HEAD. To reset a branch, first check it out.

If you wanted to know more about the difference between git reset and git checkout I would recommend to read the official git blog.

Android Closing Activity Programmatically

You Can use just finish(); everywhere after Activity Start for clear that Activity from Stack.

How to add a color overlay to a background image?

background-image takes multiple values.

so a combination of just 1 color linear-gradient and css blend modes will do the trick.

.testclass {
    background-image: url("../images/image.jpg"), linear-gradient(rgba(0,0,0,0.5),rgba(0,0,0,0.5));
    background-blend-mode: overlay;
}

note that there is no support on IE/Edge for CSS blend-modes at all.

Using Default Arguments in a Function

You can also check if you have an empty string as argument so you can call like:

foo('blah', "", 'non-default y value', null);

Below the function:

function foo($blah, $x = null, $y = null, $z = null) {
    if (null === $x || "" === $x) {
        $x = "some value";
    }

    if (null === $y || "" === $y) {
        $y = "some other value";
    }

    if (null === $z || "" === $z) {
        $z = "some other value";
    }

    code here!

}

It doesn't matter if you fill null or "", you will still get the same result.

Recursive Lock (Mutex) vs Non-Recursive Lock (Mutex)

IMHO, most arguments against recursive locks (which are what I use 99.9% of the time over like 20 years of concurrent programming) mix the question if they are good or bad with other software design issues, which are quite unrelated. To name one, the "callback" problem, which is elaborated on exhaustively and without any multithreading related point of view, for example in the book Component software - beyond Object oriented programming.

As soon as you have some inversion of control (e.g. events fired), you face re-entrance problems. Independent of whether there are mutexes and threading involved or not.

class EvilFoo {
  std::vector<std::string> data;
  std::vector<std::function<void(EvilFoo&)> > changedEventHandlers;
public:
  size_t registerChangedHandler( std::function<void(EvilFoo&)> handler) { // ...  
  }
  void unregisterChangedHandler(size_t handlerId) { // ...
  }
  void fireChangedEvent() { 
    // bad bad, even evil idea!
    for( auto& handler : changedEventHandlers ) {
      handler(*this);
    }
  }
  void AddItem(const std::string& item) { 
    data.push_back(item);
    fireChangedEvent();
  }
};

Now, with code like the above you get all error cases, which would usually be named in the context of recursive locks - only without any of them. An event handler can unregister itself once it has been called, which would lead to a bug in a naively written fireChangedEvent(). Or it could call other member functions of EvilFoo which cause all sorts of problems. The root cause is re-entrance. Worst of all, this could not even be very obvious as it could be over a whole chain of events firing events and eventually we are back at our EvilFoo (non- local).

So, re-entrance is the root problem, not the recursive lock. Now, if you felt more on the safe side using a non-recursive lock, how would such a bug manifest itself? In a deadlock whenever unexpected re-entrance occurs. And with a recursive lock? The same way, it would manifest itself in code without any locks.

So the evil part of EvilFoo are the events and how they are implemented, not so much a recursive lock. fireChangedEvent() would need to first create a copy of changedEventHandlers and use that for iteration, for starters.

Another aspect often coming into the discussion is the definition of what a lock is supposed to do in the first place:

  • Protect a piece of code from re-entrance
  • Protect a resource from being used concurrently (by multiple threads).

The way I do my concurrent programming, I have a mental model of the latter (protect a resource). This is the main reason why I am good with recursive locks. If some (member) function needs locking of a resource, it locks. If it calls another (member) function while doing what it does and that function also needs locking - it locks. And I don't need an "alternate approach", because the ref-counting of the recursive lock is quite the same as if each function wrote something like:

void EvilFoo::bar() {
   auto_lock lock(this); // this->lock_holder = this->lock_if_not_already_locked_by_same_thread())
   // do what we gotta do
   
   // ~auto_lock() { if (lock_holder) unlock() }
}

And once events or similar constructs (visitors?!) come into play, I do not hope to get all the ensuing design problems solved by some non-recursive lock.

jQuery Selector: Id Ends With?

If you know the element type then: (eg: replace 'element' with 'div')

$("element[id$='txtTitle']")

If you don't know the element type:

$("[id$='txtTitle']")

More information available


_x000D_
_x000D_
// the old way, needs exact ID: document.getElementById("hi").value = "kk";_x000D_
$(function() {_x000D_
  $("[id$='txtTitle']").val("zz");_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input id="ctl_blabla_txtTitle" type="text" />
_x000D_
_x000D_
_x000D_

If a DOM Element is removed, are its listeners also removed from memory?

Yes, the garbage collector will remove them as well. Might not always be the case with legacy browsers though.

Easiest way to use SVG in Android?

UPDATE: DO NOT use this old answer, better use this: https://stackoverflow.com/a/39266840/4031815

Ok after some hours of research I found svg-android to be quite easy to use, so I'm leaving here step by step instructions:

  1. download lib from: https://code.google.com/p/svg-android/downloads/list Latest version at the moment of writing this is: svg-android-1.1.jar

  2. Put jar in lib dir.

  3. Save your *.svg file in res/drawable dir (In illustrator is as easy as pressing Save as and select svg)

  4. Code the following in your activity using the svg library:

    ImageView imageView = (ImageView) findViewById(R.id.imgView);
    SVG svg = SVGParser.getSVGFromResource(getResources(), R.drawable.example);
    //The following is needed because of image accelaration in some devices such as samsung
    imageView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    imageView.setImageDrawable(svg.createPictureDrawable());
    



You can reduce boilerplate code like this

Very easy I made a simple class to contain past code and reduce boilerplate code, like this:

import android.app.Activity;
import android.view.View;
import android.widget.ImageView;

import com.larvalabs.svgandroid.SVG;
import com.larvalabs.svgandroid.SVGParser;

public class SvgImage {

    private static ImageView imageView;
    private Activity activity;
    private SVG svg;
    private int xmlLayoutId;
    private int drawableId;


    public SvgImage(Activity activity, int layoutId, int drawableId) {
        imageView = (ImageView) activity.findViewById(layoutId);
        svg = SVGParser.getSVGFromResource(activity.getResources(), drawableId);
        //Needed because of image accelaration in some devices such as samsung
        imageView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        imageView.setImageDrawable(svg.createPictureDrawable());
    }
}

Now I can call it like this in activity:

    SvgImage rainSVG = new SvgImage(MainActivity.this, R.id.rainImageView, R.drawable.rain);
    SvgImage thunderSVG = new SvgImage(MainActivity.this, R.id.thunderImageView, R.drawable.thunder);
    SvgImage oceanSVG = new SvgImage(MainActivity.this, R.id.oceanImageView, R.drawable.ocean);
    SvgImage fireSVG = new SvgImage(MainActivity.this, R.id.fireImageView, R.drawable.fire);
    SvgImage windSVG = new SvgImage(MainActivity.this, R.id.windImageView,R.drawable.wind);
    SvgImage universeSVG = new SvgImage(MainActivity.this, R.id.universeImageView,R.drawable.universe);

How to compare datetime with only date in SQL Server

You can use LIKE statement instead of =. But to do this with DateStamp you need to CONVERT it first to VARCHAR:

SELECT * 
FROM [User] U
WHERE CONVERT(VARCHAR, U.DateCreated, 120) LIKE '2014-02-07%'

if statement checks for null but still throws a NullPointerException

The edit shows exactly the difference between code that works and code that doesn't.

This check always evaluates both of the conditions, throwing an exception if str is null:

 if (str == null | str.length() == 0) {

Whereas this (using || instead of |) is short-circuiting - if the first condition evaluates to true, the second is not evaluated.

See section 15.24 of the JLS for a description of ||, and section 15.22.2 for binary |. The intro to section 15.24 is the important bit though:

The conditional-or operator || operator is like | (§15.22.2), but evaluates its right-hand operand only if the value of its left-hand operand is false.

How to change border color of textarea on :focus

There is an input:focus as there is a textarea:focus

input:focus { 
    outline: none !important;
    border-color: #719ECE;
    box-shadow: 0 0 10px #719ECE;
}
textarea:focus { 
    outline: none !important;
    border-color: #719ECE;
    box-shadow: 0 0 10px #719ECE;
}

Writing outputs to log file and console

    #
    #------------------------------------------------------------------------------
    # echo pass params and print them to a log file and terminal
    # with timestamp and $host_name and $0 PID
    # usage:
    # doLog "INFO some info message"
    # doLog "DEBUG some debug message"
    # doLog "WARN some warning message"
    # doLog "ERROR some really ERROR message"
    # doLog "FATAL some really fatal message"
    #------------------------------------------------------------------------------
    doLog(){
        type_of_msg=$(echo $*|cut -d" " -f1)
        msg=$(echo "$*"|cut -d" " -f2-)
        [[ $type_of_msg == DEBUG ]] && [[ $do_print_debug_msgs -ne 1 ]] && return
        [[ $type_of_msg == INFO ]] && type_of_msg="INFO " # one space for aligning
        [[ $type_of_msg == WARN ]] && type_of_msg="WARN " # as well

        # print to the terminal if we have one
        test -t 1 && echo " [$type_of_msg] `date "+%Y.%m.%d-%H:%M:%S %Z"` [$run_unit][@$host_name] [$$] ""$msg"

        # define default log file none specified in cnf file
        test -z $log_file && \
            mkdir -p $product_instance_dir/dat/log/bash && \
                log_file="$product_instance_dir/dat/log/bash/$run_unit.`date "+%Y%m"`.log"
        echo " [$type_of_msg] `date "+%Y.%m.%d-%H:%M:%S %Z"` [$run_unit][@$host_name] [$$] ""$msg" >> $log_file
    }
    #eof func doLog

Cannot read property 'getContext' of null, using canvas

Put your JavaScript code after your tag <canvas></canvas>

Create File If File Does Not Exist

You don't even need to do the check manually, File.Open does it for you. Try:

using (StreamWriter sw = new StreamWriter(File.Open(path, System.IO.FileMode.Append))) 
{

Ref: http://msdn.microsoft.com/en-us/library/system.io.filemode.aspx

Excel: Creating a dropdown using a list in another sheet?

That cannot be done in excel 2007. The list must be in the same sheet as your data. It might work in later versions though.

Passing parameters to a JDBC PreparedStatement

There is a problem in your query..

   statement =con.prepareStatement("SELECT * from employee WHERE  userID = "+"''"+userID);
   ResultSet rs = statement.executeQuery();

You are using Prepare Statement.. So you need to set your parameter using statement.setInt() or statement.setString() depending upon what is the type of your userId

Replace it with: -

   statement =con.prepareStatement("SELECT * from employee WHERE  userID = :userId");
   statement.setString(userId, userID);
   ResultSet rs = statement.executeQuery();

Or, you can use ? in place of named value - :userId..

   statement =con.prepareStatement("SELECT * from employee WHERE  userID = ?");
   statement.setString(1, userID);

jQuery change URL of form submit

Try using this:

$(".move_to").on("click", function(e){
    e.preventDefault();
    $('#contactsForm').attr('action', "/test1").submit();
});

Moving the order in which you use .preventDefault() might fix your issue. You also didn't use function(e) so e.preventDefault(); wasn't working.

Here it is working: http://jsfiddle.net/TfTwe/1/ - first of all, click the 'Check action attribute.' link. You'll get an alert saying undefined. Then click 'Set action attribute.' and click 'Check action attribute.' again. You'll see that the form's action attribute has been correctly set to /test1.

how can I check if a file exists?

Start with this:

Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FileExists(path)) Then
   msg = path & " exists."
Else
   msg = path & " doesn't exist."
End If

Taken from the documentation.

Experimental decorators warning in TypeScript compilation

"javascript.implicitProjectConfig.experimentalDecorators": true

Will solve this problem.

Inverse dictionary lookup in Python

I'm using dictionaries as a sort of "database", so I need to find a key that I can reuse. For my case, if a key's value is None, then I can take it and reuse it without having to "allocate" another id. Just figured I'd share it.

db = {0:[], 1:[], ..., 5:None, 11:None, 19:[], ...}

keys_to_reallocate = [None]
allocate.extend(i for i in db.iterkeys() if db[i] is None)
free_id = keys_to_reallocate[-1]

I like this one because I don't have to try and catch any errors such as StopIteration or IndexError. If there's a key available, then free_id will contain one. If there isn't, then it will simply be None. Probably not pythonic, but I really didn't want to use a try here...

CSS3 scrollbar styling on a div

The problem with the css3 scroll bars is that, interaction can only be performed on the content. we can't interact with the scroll bar on touch devices.

Spring: how do I inject an HttpServletRequest into a request-scoped bean?

Spring exposes the current HttpServletRequest object (as well as the current HttpSession object) through a wrapper object of type ServletRequestAttributes. This wrapper object is bound to ThreadLocal and is obtained by calling the static method RequestContextHolder.currentRequestAttributes().

ServletRequestAttributes provides the method getRequest() to get the current request, getSession() to get the current session and other methods to get the attributes stored in both the scopes. The following code, though a bit ugly, should get you the current request object anywhere in the application:

HttpServletRequest curRequest = 
((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
.getRequest();

Note that the RequestContextHolder.currentRequestAttributes() method returns an interface and needs to be typecasted to ServletRequestAttributes that implements the interface.


Spring Javadoc: RequestContextHolder | ServletRequestAttributes

What is the difference between .*? and .* regular expressions?

On greedy vs non-greedy

Repetition in regex by default is greedy: they try to match as many reps as possible, and when this doesn't work and they have to backtrack, they try to match one fewer rep at a time, until a match of the whole pattern is found. As a result, when a match finally happens, a greedy repetition would match as many reps as possible.

The ? as a repetition quantifier changes this behavior into non-greedy, also called reluctant (in e.g. Java) (and sometimes "lazy"). In contrast, this repetition will first try to match as few reps as possible, and when this doesn't work and they have to backtrack, they start matching one more rept a time. As a result, when a match finally happens, a reluctant repetition would match as few reps as possible.

References


Example 1: From A to Z

Let's compare these two patterns: A.*Z and A.*?Z.

Given the following input:

eeeAiiZuuuuAoooZeeee

The patterns yield the following matches:

Let's first focus on what A.*Z does. When it matched the first A, the .*, being greedy, first tries to match as many . as possible.

eeeAiiZuuuuAoooZeeee
   \_______________/
    A.* matched, Z can't match

Since the Z doesn't match, the engine backtracks, and .* must then match one fewer .:

eeeAiiZuuuuAoooZeeee
   \______________/
    A.* matched, Z still can't match

This happens a few more times, until finally we come to this:

eeeAiiZuuuuAoooZeeee
   \__________/
    A.* matched, Z can now match

Now Z can match, so the overall pattern matches:

eeeAiiZuuuuAoooZeeee
   \___________/
    A.*Z matched

By contrast, the reluctant repetition in A.*?Z first matches as few . as possible, and then taking more . as necessary. This explains why it finds two matches in the input.

Here's a visual representation of what the two patterns matched:

eeeAiiZuuuuAoooZeeee
   \__/r   \___/r      r = reluctant
    \____g____/        g = greedy

Example: An alternative

In many applications, the two matches in the above input is what is desired, thus a reluctant .*? is used instead of the greedy .* to prevent overmatching. For this particular pattern, however, there is a better alternative, using negated character class.

The pattern A[^Z]*Z also finds the same two matches as the A.*?Z pattern for the above input (as seen on ideone.com). [^Z] is what is called a negated character class: it matches anything but Z.

The main difference between the two patterns is in performance: being more strict, the negated character class can only match one way for a given input. It doesn't matter if you use greedy or reluctant modifier for this pattern. In fact, in some flavors, you can do even better and use what is called possessive quantifier, which doesn't backtrack at all.

References


Example 2: From A to ZZ

This example should be illustrative: it shows how the greedy, reluctant, and negated character class patterns match differently given the same input.

eeAiiZooAuuZZeeeZZfff

These are the matches for the above input:

Here's a visual representation of what they matched:

         ___n
        /   \              n = negated character class
eeAiiZooAuuZZeeeZZfff      r = reluctant
  \_________/r   /         g = greedy
   \____________/g

Related topics

These are links to questions and answers on stackoverflow that cover some topics that may be of interest.

One greedy repetition can outgreed another

xlrd.biffh.XLRDError: Excel xlsx file; not supported

The previous version, xlrd 1.2.0, may appear to work, but it could also expose you to potential security vulnerabilities. With that warning out of the way, if you still want to give it a go, type the following command:

pip install xlrd==1.2.0

Better way to revert to a previous SVN revision of a file?

If you use the Eclipse IDE with the SVN plugin you can do as follows:

  1. Right-click the files that you want to revert (or the folder they were contained in, if you deleted them by mistake and you want to add them back)
  2. Select "Team > Switch"
  3. Choose the "Revision" radion button, and enter the revision number you'd like to revert to. Click OK
  4. Go to the Synchronize perspective
  5. Select all the files you want to revert
  6. Right-click on the selection and do "Override and Commit..."

This will revert the files to the revision that you want. Just keep in mind that SVN will see the changes as a new commit. That is, the change gets a new revision number, and there is no link between the old revision and the new one. You should specify in the commit comments that you are reverting those files to a specific revision.

jQuery - find table row containing table cell containing specific text

   <input type="text" id="text" name="search">
<table id="table_data">
        <tr class="listR"><td>PHP</td></tr>
        <tr class="listR"><td>MySql</td></tr>
        <tr class="listR"><td>AJAX</td></tr>
        <tr class="listR"><td>jQuery</td></tr>
        <tr class="listR"><td>JavaScript</td></tr>
        <tr class="listR"><td>HTML</td></tr>
        <tr class="listR"><td>CSS</td></tr>
        <tr class="listR"><td>CSS3</td></tr>
</table>

$("#textbox").on('keyup',function(){
        var f = $(this).val();
      $("#table_data tr.listR").each(function(){
            if ($(this).text().search(new RegExp(f, "i")) < 0) {
                $(this).fadeOut();
             } else {
                 $(this).show();
            }
        });
    });

Demo You can perform by search() method with use RegExp matching text

PostgreSQL: ERROR: operator does not exist: integer = character varying

I think it is telling you exactly what is wrong. You cannot compare an integer with a varchar. PostgreSQL is strict and does not do any magic typecasting for you. I'm guessing SQLServer does typecasting automagically (which is a bad thing).

If you want to compare these two different beasts, you will have to cast one to the other using the casting syntax ::.

Something along these lines:

create view view1
as 
select table1.col1,table2.col1,table3.col3
from table1 
inner join
table2 
inner join 
table3
on 
table1.col4::varchar = table2.col5
/* Here col4 of table1 is of "integer" type and col5 of table2 is of type "varchar" */
/* ERROR: operator does not exist: integer = character varying */
....;

Notice the varchar typecasting on the table1.col4.

Also note that typecasting might possibly render your index on that column unusable and has a performance penalty, which is pretty bad. An even better solution would be to see if you can permanently change one of the two column types to match the other one. Literately change your database design.

Or you could create a index on the casted values by using a custom, immutable function which casts the values on the column. But this too may prove suboptimal (but better than live casting).

CSS: How can I set image size relative to parent height?

you can use flex box for it.. this will solve your problem

.image-parent 
{
     height:33px; 
     display:flex; 
}

Removing object from array in Swift 3

Extension for array to do it easily and allow chaining for Swift 4.2 and up:

public extension Array where Element: Equatable {
    @discardableResult
    public mutating func remove(_ item: Element) -> Array {
        if let index = firstIndex(where: { item == $0 }) {
            remove(at: index)
        }
        return self
    }

    @discardableResult
    public mutating func removeAll(_ item: Element) -> Array {
        removeAll(where: { item == $0 })
        return self
    }
}

ImportError: No module named tensorflow

For Anaconda3, simply install in Anaconda Navigator: enter image description here

How to get the mouse position without events (without moving the mouse)?

The most simple solution but not 100% accurate

$(':hover').last().offset()

Result: {top: 148, left: 62.5}
The result depend on the nearest element size and return undefined when user switched the tab

What does it mean: The serializable class does not declare a static final serialVersionUID field?

The reasons for warning are documented here, and the simple fixes are to turn off the warning or put the following declaration in your code to supply the version UID. The actual value is not relevant, start with 999 if you like, but changing it when you make incompatible changes to the class is.

public class HelloWorldSwing extends JFrame {

        JTextArea m_resultArea = new JTextArea(6, 30);
        private static final long serialVersionUID = 1L;

Detect rotation of Android phone in the browser with JavaScript

you can try the solution, compatible with all browser.

Following is orientationchange compatibility pic: compatibility therefore, I author a orientaionchange polyfill, it is a based on @media attribute to fix orientationchange utility library——orientationchange-fix

window.addEventListener('orientationchange', function(){
 if(window.neworientation.current === 'portrait|landscape'){
    // do something……
 } else {
    // do something……
 }
}, false);

Check if a string is palindrome

// The below C++ function checks for a palindrome and 
// returns true if it is a palindrome and returns false otherwise

bool checkPalindrome ( string s )
{
    // This calculates the length of the string

    int n = s.length();

    // the for loop iterates until the first half of the string
    // and checks first element with the last element,
    // second element with second last element and so on.
    // if those two characters are not same, hence we return false because
    // this string is not a palindrome 

    for ( int i = 0; i <= n/2; i++ ) 
    {
        if ( s[i] != s[n-1-i] )
            return false;
    }
    
    // if the above for loop executes completely , 
    // this implies that the string is palindrome, 
    // hence we return true and exit

    return true;
}

Enum Naming Convention - Plural

I started out naming enums in the plural but have since changed to singular. Just seems to make more sense in the context of where they're used.

enum Status { Unknown = 0, Incomplete, Ready }

Status myStatus = Status.Ready;

Compare to:

Statuses myStatus = Statuses.Ready;

I find the singular form to sound more natural in context. We are in agreement that when declaring the enum, which happens in one place, we're thinking "this is a group of whatevers", but when using it, presumably in many places, that we're thinking "this is one whatever".

Auto height of div

As stated earlier by Jamie Dixon, a floated <div> is taken out of normal flow. All content that is still within normal flow will ignore it completely and not make space for it.

Try putting a different colored border border:solid 1px orange; around each of your <div> elements to see what they're doing. You might start by removing the floats and putting some dummy text inside the div. Then style them one at a time to get the desired layout.

Java, Check if integer is multiple of a number

Use modulo

whenever a number x is a multiple of some number y, then always x % y equal to 0, which can be used as a check. So use

if (j % 4 == 0) 

Maven plugin in Eclipse - Settings.xml file is missing

Working on Mac I followed the answer of Sean Patrick Floyd placing a settings.xml like above in my user folder /Users/user/.m2/

But this did not help. So I opened a Terminal and did a ls -la on the folder. This was showing

-rw-r--r--@

thus staff and everone can at least read the file. So I wondered if the message isn't wrong and if the real cause is the lack of write permissions. I set the file to:

-rw-r--rw-@

This did it. The message disappeared.

How to make google spreadsheet refresh itself every 1 minute?

use now() in any cell. then use that cell as a "dummy" parameter in a function. when now() changes every minute the formula recalculates. example: someFunction(a1,b1,c1) * (cell with now() / cell with now())

A required class was missing while executing org.apache.maven.plugins:maven-war-plugin:2.1.1:war

Make sure your Java version matches the project's Java version requirement. This could be an another cause for such kinds of issues.

React.js inline style best practices

It's really depends on how big your application is, if you wanna use bundlers like webpack and bundle CSS and JS together in the build and how you wanna mange your application flow! At the end of day, depends on your situation, you can make decision!

My preference for organising files in big projects are separating CSS and JS files, it could be easier to share, easier for UI people to just go through CSS files, also much neater file organising for the whole application!

Always think this way, make sure in developing phase everything are where they should be, named properly and be easy for other developers to find things...

I personally mix them depends on my need, for example... Try to use external css, but if needed React will accept style as well, you need to pass it as an object with key value, something like this below:

import React from 'react';

const App = props => {
  return (
    <div className="app" style={{background: 'red', color: 'white'}}>  /*<<<<look at style here*/
      Hello World...
    </div>
  )
}

export default App;

No process is on the other end of the pipe (SQL Server 2012)

The server was set to Windows Authentication only by default. There isn't any notification, that the origin of the errors is that, so it's hard to figure it out. The SQL Management studio dont alert, even if you create a user with SQL Authentication only.

So the answer is: Switch from Windows to SQL Authentication:

  1. Right click on the server name and select properties;
  2. Select security tab;
  3. Enable the SQL Server and Windows Authentication mode;
  4. Restart the SQL Server service.

You can now connect with your login/password.

What does "connection reset by peer" mean?

This means that a TCP RST was received and the connection is now closed. This occurs when a packet is sent from your end of the connection but the other end does not recognize the connection; it will send back a packet with the RST bit set in order to forcibly close the connection.

This can happen if the other side crashes and then comes back up or if it calls close() on the socket while there is data from you in transit, and is an indication to you that some of the data that you previously sent may not have been received.

It is up to you whether that is an error; if the information you were sending was only for the benefit of the remote client then it may not matter that any final data may have been lost. However you should close the socket and free up any other resources associated with the connection.

The difference between Classes, Objects, and Instances

Any kind of data your computer stores and processes is in its most basic representation a row of bits. The way those bits are interpreted is done through data types. Data types can be primitive or complex. Primitive data types are - for instance - int or double. They have a specific length and a specific way of being interpreted. In the case of an integer, usually the first bit is used for the sign, the others are used for the value.

Complex data types can be combinations of primitive and other complex data types and are called "Class" in Java.

You can define the complex data type PeopleName consisting of two Strings called first and last name. Each String in Java is another complex data type. Strings in return are (probably) implemented using the primitive data type char for which Java knows how many bits they take to store and how to interpret them.

When you create an instance of a data type, you get an object and your computers reserves some memory for it and remembers its location and the name of that instance. An instance of PeopleName in memory will take up the space of the two String variables plus a bit more for bookkeeping. An integer takes up 32 bits in Java.

Complex data types can have methods assigned to them. Methods can perform actions on their arguments or on the instance of the data type you call this method from. If you have two instances of PeopleName called p1 and p2 and you call a method p1.getFirstName(), it usually returns the first name of the first person but not the second person's.

How do I get a list of files in a directory in C++?

HANDLE WINAPI FindFirstFile(
  __in   LPCTSTR lpFileName,
  __out  LPWIN32_FIND_DATA lpFindFileData
);

Setup the attributes to only look for directories.

PHP - count specific array values

$array = array("Kyle","Ben","Sue","Phil","Ben","Mary","Sue","Ben");
$counts = array_count_values($array);
echo $counts['Ben'];

How to add two strings as if they were numbers?

If you need to add two strings together which are very large numbers you'll need to evaluate the addition at every string position:

function addStrings(str1, str2){
  str1a = str1.split('').reverse();
  str2a = str2.split('').reverse();
  let output = '';
  let longer = Math.max(str1.length, str2.length);
  let carry = false;
  for (let i = 0; i < longer; i++) {
    let result
    if (str1a[i] && str2a[i]) {
      result = parseInt(str1a[i]) + parseInt(str2a[i]);

    } else if (str1a[i] && !str2a[i]) {
      result = parseInt(str1a[i]);

    } else if (!str1a[i] && str2a[i]) {
      result = parseInt(str2a[i]);
    }

    if (carry) {
        result += 1;
        carry = false;
    }
    if(result >= 10) {
      carry = true;
      output += result.toString()[1];
    }else {
      output += result.toString();
    }
  }
  output = output.split('').reverse().join('');

  if(carry) {
    output = '1' + output;
  }
  return output;
}

How do I prevent the error "Index signature of object type implicitly has an 'any' type" when compiling typescript with noImplicitAny flag enabled?

I had two interfaces. First was child of other. I did following:

  1. Added index signature in parent interface.
  2. Used appropriate type using as keyword.

Complete code is as below:

Child Interface:

interface UVAmount {
  amount: number;
  price: number;
  quantity: number;
};

Parent Interface:

interface UVItem  {
// This is index signature which compiler is complaining about.
// Here we are mentioning key will string and value will any of the types mentioned.
  [key: string]:  UVAmount | string | number | object;

  name: string;
  initial: UVAmount;
  rating: number;
  others: object;
};

React Component:

let valueType = 'initial';

function getTotal(item: UVItem) {
// as keyword is the dealbreaker.
// If you don't use it, it will take string type by default and show errors.
  let itemValue = item[valueType] as UVAmount;

  return itemValue.price * itemValue.quantity;
}

Mocking python function based on input arguments

As indicated at Python Mock object with method called multiple times

A solution is to write my own side_effect

def my_side_effect(*args, **kwargs):
    if args[0] == 42:
        return "Called with 42"
    elif args[0] == 43:
        return "Called with 43"
    elif kwargs['foo'] == 7:
        return "Foo is seven"

mockobj.mockmethod.side_effect = my_side_effect

That does the trick

Easiest way to pass an AngularJS scope variable from directive to controller?

Edited on 2014/8/25: Here was where I forked it.

Thanks @anvarik.

Here is the JSFiddle. I forgot where I forked this. But this is a good example showing you the difference between = and @

<div ng-controller="MyCtrl">
    <h2>Parent Scope</h2>
    <input ng-model="foo"> <i>// Update to see how parent scope interacts with component scope</i>    
    <br><br>
    <!-- attribute-foo binds to a DOM attribute which is always
    a string. That is why we are wrapping it in curly braces so
    that it can be interpolated. -->
    <my-component attribute-foo="{{foo}}" binding-foo="foo"
        isolated-expression-foo="updateFoo(newFoo)" >
        <h2>Attribute</h2>
        <div>
            <strong>get:</strong> {{isolatedAttributeFoo}}
        </div>
        <div>
            <strong>set:</strong> <input ng-model="isolatedAttributeFoo">
            <i>// This does not update the parent scope.</i>
        </div>
        <h2>Binding</h2>
        <div>
            <strong>get:</strong> {{isolatedBindingFoo}}
        </div>
        <div>
            <strong>set:</strong> <input ng-model="isolatedBindingFoo">
            <i>// This does update the parent scope.</i>
        </div>
        <h2>Expression</h2>    
        <div>
            <input ng-model="isolatedFoo">
            <button class="btn" ng-click="isolatedExpressionFoo({newFoo:isolatedFoo})">Submit</button>
            <i>// And this calls a function on the parent scope.</i>
        </div>
    </my-component>
</div>
var myModule = angular.module('myModule', [])
    .directive('myComponent', function () {
        return {
            restrict:'E',
            scope:{
                /* NOTE: Normally I would set my attributes and bindings
                to be the same name but I wanted to delineate between
                parent and isolated scope. */                
                isolatedAttributeFoo:'@attributeFoo',
                isolatedBindingFoo:'=bindingFoo',
                isolatedExpressionFoo:'&'
            }        
        };
    })
    .controller('MyCtrl', ['$scope', function ($scope) {
        $scope.foo = 'Hello!';
        $scope.updateFoo = function (newFoo) {
            $scope.foo = newFoo;
        }
    }]);

How to modify WooCommerce cart, checkout pages (main theme portion)

WooCommerce has a number of options for modifying the cart, and checkout pages. Here are the three I'd recomend:

Use WooCommerce Conditional Tags

is_cart() and is_checkout() functions return true on their page. Example:

if ( is_cart() || is_checkout() ) {
    echo "This is the cart, or checkout page!";
}

Modify the template file

The main, cart template file is located at wp-content/themes/{current-theme}/woocommerce/cart/cart.php

The main, checkout template file is located at wp-content/themes/{current-theme}/woocommerce/checkout/form-checkout.php

To edit these, first copy them to your child theme.

Use wp-content/themes/{current-theme}/page-{slug}.php

page-{slug}.php is the second template that will be used, coming after manually assigned ones through the WP dashboard.

This is safer than my other solutions, because if you remove WooCommerce, but forget to remove this file, the code inside (that may rely on WooCommerce functions) won't break, because it's never called (unless of cause you have a page with slug {slug}).

For example:

  • wp-content/themes/{current-theme}/page-cart.php
  • wp-content/themes/{current-theme}/page-checkout.php

Tomcat starts but home page cannot open with url http://localhost:8080

I had the same issue. My tomcat was started but I was getting HTTP 404 page not found.However, in my situation, I installed tree instances of tomcat. Each instance contains conf, temp, work, webapps and logs folders. Unless I forgot, to copy the global web.xml under conf folder of each tomcat.

    e.g: /opt/tomcat/mytomcatInstance/conf/web.xml 

The web.xml Deployment Descriptor file describes how to deploy a web application in a servlet container.

So even if my tomcat was up, my web apps could not be deployed properly.

JDBC ODBC Driver Connection

As mentioned in the comments to the question, the JDBC-ODBC Bridge is - as the name indicates - only a mechanism for the JDBC layer to "talk to" the ODBC layer. Even if you had a JDBC-ODBC Bridge on your Mac you would also need to have

  • an implementation of ODBC itself, and
  • an appropriate ODBC driver for the target database (ACE/Jet, a.k.a. "Access")

So, for most people, using JDBC-ODBC Bridge technology to manipulate ACE/Jet ("Access") databases is really a practical option only under Windows. It is also important to note that the JDBC-ODBC Bridge will be has been removed in Java 8 (ref: here).

There are other ways of manipulating ACE/Jet databases from Java, such as UCanAccess and Jackcess. Both of these are pure Java implementations so they work on non-Windows platforms. For details on how to use UCanAccess see

Manipulating an Access database from Java without ODBC

Read a plain text file with php

$file="./doc.txt";
$doc=file_get_contents($file);

$line=explode("\n",$doc);
foreach($line as $newline){
    echo '<h3 style="color:#453288">'.$newline.'</h3><br>';

}

PHPExcel Make first row bold

Try this

$objPHPExcel->getActiveSheet()->getStyle('A1:D1')->getFont()->setBold(true);

Using Address Instead Of Longitude And Latitude With Google Maps API

See this example, initializes the map to "San Diego, CA".

Uses the Google Maps Javascript API v3 Geocoder to translate the address into coordinates that can be displayed on the map.

<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps JavaScript API v3 Example: Geocoding Simple</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
  var geocoder;
  var map;
  var address ="San Diego, CA";
  function initialize() {
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions = {
      zoom: 8,
      center: latlng,
    mapTypeControl: true,
    mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
    navigationControl: true,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    if (geocoder) {
      geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
          map.setCenter(results[0].geometry.location);

            var infowindow = new google.maps.InfoWindow(
                { content: '<b>'+address+'</b>',
                  size: new google.maps.Size(150,50)
                });
    
            var marker = new google.maps.Marker({
                position: results[0].geometry.location,
                map: map, 
                title:address
            }); 
            google.maps.event.addListener(marker, 'click', function() {
                infowindow.open(map,marker);
            });

          } else {
            alert("No results found");
          }
        } else {
          alert("Geocode was not successful for the following reason: " + status);
        }
      });
    }
  }
</script>
</head>
<body style="margin:0px; padding:0px;" onload="initialize()">
 <div id="map_canvas" style="width:100%; height:100%">
</body>
</html>

working code snippet:

_x000D_
_x000D_
var geocoder;
var map;
var address = "San Diego, CA";

function initialize() {
  geocoder = new google.maps.Geocoder();
  var latlng = new google.maps.LatLng(-34.397, 150.644);
  var myOptions = {
    zoom: 8,
    center: latlng,
    mapTypeControl: true,
    mapTypeControlOptions: {
      style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
    },
    navigationControl: true,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
  if (geocoder) {
    geocoder.geocode({
      'address': address
    }, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
          map.setCenter(results[0].geometry.location);

          var infowindow = new google.maps.InfoWindow({
            content: '<b>' + address + '</b>',
            size: new google.maps.Size(150, 50)
          });

          var marker = new google.maps.Marker({
            position: results[0].geometry.location,
            map: map,
            title: address
          });
          google.maps.event.addListener(marker, 'click', function() {
            infowindow.open(map, marker);
          });

        } else {
          alert("No results found");
        }
      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
  }
}
google.maps.event.addDomListener(window, 'load', initialize);
_x000D_
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
}
_x000D_
<script type="text/javascript" src="https://maps.google.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map_canvas" ></div>
_x000D_
_x000D_
_x000D_

How to concatenate strings in django templates?

And multiple concatenation:

from django import template
register = template.Library()


@register.simple_tag
def concat_all(*args):
    """concatenate all args"""
    return ''.join(map(str, args))

And in Template:

{% concat_all 'x' 'y' another_var as string_result %}
concatenated string: {{ string_result }}

Retrieve data from website in android app

You can use jsoup to parse any kind of web page. Here you can find the jsoup library and full source code.

Here is an example: http://desicoding.blogspot.com/2011/03/how-to-parse-html-in-java-jsoup.html

To install in Eclipse:

  1. Right Click on project
  2. BuildPath
  3. Add External Archives
  4. select the .jar file

You can parse according to tag/parent/child very comfortably

Bulk package updates using Conda

Before you proceed to conda update --all command, first update conda with conda update conda command if you haven't update it for a long time. It happent to me (Python 2.7.13 on Anaconda 64 bits).

SQL where datetime column equals today's date?

Easy way out is to use a condition like this ( use desired date > GETDATE()-1)

your sql statement "date specific" > GETDATE()-1

Troubleshooting "program does not contain a static 'Main' method" when it clearly does...?

I had this error and solved by this solution.

--> Right click on the project

--> and select "Properties"

--> then set "Output Type" to "Class Library".

What does SQL clause "GROUP BY 1" mean?

That means sql group by 1st column in your select clause, we always use this GROUP BY 1 together with ORDER BY 1, besides you can also use like this GROUP BY 1,2,3.., of course it is convenient for us but you need to pay attention to that condition the result may be not what you want if some one has modified your select columns, and it's not visualized

Form Submission without page refresh

The problem is the Method 'POST' your form is submitting by using the "post" method, and in the AJAX you are using "GET".

Does .NET provide an easy way convert bytes to KB, MB, GB, etc.?

I went for JerKimballs solution, and thumbs up to that. However, I would like to add / point out that this is indeed a matter of controversy as a whole. In my research (for other reasons) I have come up with the following pieces of information.

When normal people (I have heard they exist) speak of gigabytes they refer to the metric system wherein 1000 to the power of 3 from the original number of bytes == the number of gigabytes. However, of course there is the IEC / JEDEC standards which is nicely summed up in wikipedia, which instead of 1000 to the power of x they have 1024. Which for physical storage devices (and I guess logical such as amazon and others) means an ever increasing difference between metric vs IEC. So for instance 1 TB == 1 terabyte metric is 1000 to the power of 4, but IEC officially terms the similar number as 1 TiB, tebibyte as 1024 to the power of 4. But, alas, in non-technical applications (I would go by audience) the norm is metric, and in my own app for internal use currently I explain the difference in documentation. But for display purposes I do not even offer anything but metric. Internally even though it's not relevant in my app I only store bytes and do the calculation for display.

As a side note I find it somewhat lackluster that the .Net framework AFAIK (and I am frequently wrong thank the powers that be) even in it's 4.5 incarnation does not contain anything about this in any libraries internally. One would expect an open source library of some kind to be NuGettable at some point, but I admit this is a small peeve. On the other hand System.IO.DriveInfo and others also only have bytes (as long) which is rather clear.

How to launch html using Chrome at "--allow-file-access-from-files" mode?

As of this writing, in OS X, it will usually look like this

"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" --allow-file-access-from-files

If you are a freak like me, and put your apps in ~/Applications, then it will be

"/Users/yougohere/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" --allow-file-access-from-files

If neither of those are working, then type chrome://version in your Chrome address bar, and it will tell you what "command line" invocation you should be using. Just add --allow-file-access-from-files to that.

Sublime Text 2 - Show file navigation in sidebar

  1. open ST ( Sublime Text )

  2. add your project root folder into ST : link : https://stackoverflow.com/a/18798528/1241980

  3. show sidebar : Menu bar View > Side Bar > Show Side Bar

  4. Try Ctrl + P to open a file someFileName.py

Does a navigation panel for openned files and project folders appear in the left of ST ?

Extra : Want view the other files that are in the same directory with someFileName.py ?
While I found ST side bar seems doesn't support this, but you can try Ctrl + O (Open) keyshort in ST to open your system file browser, in which the ST will help you to locate into the folder that contains someFileName.py and it's sibling files.

How to use filter, map, and reduce in Python 3

One of the advantages of map, filter and reduce is how legible they become when you "chain" them together to do something complex. However, the built-in syntax isn't legible and is all "backwards". So, I suggest using the PyFunctional package (https://pypi.org/project/PyFunctional/). Here's a comparison of the two:

flight_destinations_dict = {'NY': {'London', 'Rome'}, 'Berlin': {'NY'}}

PyFunctional version

Very legible syntax. You can say:

"I have a sequence of flight destinations. Out of which I want to get the dict key if city is in the dict values. Finally, filter out the empty lists I created in the process."

from functional import seq  # PyFunctional package to allow easier syntax

def find_return_flights_PYFUNCTIONAL_SYNTAX(city, flight_destinations_dict):
    return seq(flight_destinations_dict.items()) \
        .map(lambda x: x[0] if city in x[1] else []) \
        .filter(lambda x: x != []) \

Default Python version

It's all backwards. You need to say:

"OK, so, there's a list. I want to filter empty lists out of it. Why? Because I first got the dict key if the city was in the dict values. Oh, the list I'm doing this to is flight_destinations_dict."

def find_return_flights_DEFAULT_SYNTAX(city, flight_destinations_dict):
    return list(
        filter(lambda x: x != [],
               map(lambda x: x[0] if city in x[1] else [], flight_destinations_dict.items())
               )
    )

Create a string of variable length, filled with a repeated character

A great ES6 option would be to padStart an empty string. Like this:

var str = ''.padStart(10, "#");

Note: this won't work in IE (without a polyfill).

error: expected primary-expression before ')' token (C)

You're passing a type as an argument, not an object. You need to do characterSelection(screen, test); where test is of type SelectionneNonSelectionne.

Required attribute on multiple checkboxes with the same name?

var verifyPaymentType = function () {
   //coloque os checkbox dentro de uma div com a class checkbox
  var inputs =  window.jQuery('.checkbox').find('input');
  var first = inputs.first()[0];

  inputs.on('change', function () {
    this.setCustomValidity('');
  });

  first.setCustomValidity( window.jQuery('.checkbox').find('input:checked').length === 0 ? 'Choose one' : '');
}

window.jQuery('#submit').click(verifyPaymentType);

}

Difference between "include" and "require" in php

Use include if you don't mind your script continuing without loading the file (in case it doesn't exist etc) and you can (although you shouldn't) live with a Warning error message being displayed.

Using require means your script will halt if it can't load the specified file, and throw a Fatal error.

How can I add a line to a file in a shell script?

To answer your original question, here's how you do it with sed:

sed -i '1icolumn1, column2, column3' testfile.csv

The "1i" command tells sed to go to line 1 and insert the text there.

The -i option causes the file to be edited "in place" and can also take an optional argument to create a backup file, for example

sed -i~ '1icolumn1, column2, column3' testfile.csv

would keep the original file in "testfile.csv~".

Get current time in milliseconds using C++ and Boost

Try this: import headers as mentioned.. gives seconds and milliseconds only. If you need to explain the code read this link.

#include <windows.h>

#include <stdio.h>

void main()
{

    SYSTEMTIME st;
    SYSTEMTIME lt;

    GetSystemTime(&st);
   // GetLocalTime(&lt);

     printf("The system time is: %02d:%03d\n", st.wSecond, st.wMilliseconds);
   //  printf("The local time is: %02d:%03d\n", lt.wSecond, lt.wMilliseconds);

}

"%%" and "%/%" for the remainder and the quotient

I think it is because % has often be associated with the modulus operator in many programming languages.

It is the case, e.g., in C, C++, C# and Java, and many other languages which derive their syntax from C (C itself took it from B).

JOptionPane Yes or No window

You are always checking for a true condition, hence your message will always show.

You should replace your if (true) statement with if ( n == JOptionPane.YES_OPTION)

When one of the showXxxDialog methods returns an integer, the possible values are:

YES_OPTION NO_OPTION CANCEL_OPTION OK_OPTION CLOSED_OPTION

From here

How can I link a photo in a Facebook album to a URL

Unfortunately, no. This feature is not available for facebook albums.

php - push array into array - key issue

first convert your array too JSON

while($query->fetch()){
   $col[] = json_encode($row,JSON_UNESCAPED_UNICODE);
}

then vonvert back it to array

foreach($col as &$array){
   $array = json_decode($array,true);
}

good luck

Rails: Why "sudo" command is not recognized?

Sudo is a Unix specific command designed to allow a user to carry out administrative tasks with the appropriate permissions. Windows doesn't not have (need?) this.

Yes, windows don't have sudo on its terminal. Try using pip instead.

  1. Install pip using the steps here.
  2. type pip install [package name] on the terminal. In this case, it may be pdfkit or wkhtmltopdf.

How to get URL parameter using jQuery or plain JavaScript?

What if there is & in URL parameter like filename="p&g.html"&uid=66

In this case the 1st function will not work properly. So I modified the code

function getUrlParameter(sParam) {
    var sURLVariables = window.location.search.substring(1).split('&'), sParameterName, i;

    for (i = 0; i < sURLVariables.length; i++) {
        sParameterName = sURLVariables[i].split('=');

        if (sParameterName[0] === sParam) {
            return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
        }
    }
}

How to convert comma-delimited string to list in Python?

In the case of integers that are included at the string, if you want to avoid casting them to int individually you can do:

mList = [int(e) if e.isdigit() else e for e in mStr.split(',')]

It is called list comprehension, and it is based on set builder notation.

ex:

>>> mStr = "1,A,B,3,4"
>>> mList = [int(e) if e.isdigit() else e for e in mStr.split(',')]
>>> mList
>>> [1,'A','B',3,4]

$(document).ready equivalent without jQuery

Three options:

  1. If script is the last tag of the body, the DOM would be ready before script tag executes
  2. When the DOM is ready, "readyState" will change to "complete"
  3. Put everything under 'DOMContentLoaded' event listener

onreadystatechange

  document.onreadystatechange = function () {
     if (document.readyState == "complete") {
     // document is ready. Do your stuff here
   }
 }

Source: MDN

DOMContentLoaded

document.addEventListener('DOMContentLoaded', function() {
   console.log('document is ready. I can sleep now');
});

Concerned about stone age browsers: Go to the jQuery source code and use the ready function. In that case you are not parsing+executing the whole library you're are doing only a very small part of it.

Calculate time difference in Windows batch file

If you do not mind using powershell within batch script:

@echo off
set start_date=%date% %time%
:: Simulate some type of processing using ping
ping 127.0.0.1  
set end_date=%date% %time%
powershell -command "&{$start_date1 = [datetime]::parse('%start_date%'); $end_date1 = [datetime]::parse('%date% %time%'); echo (-join('Duration in seconds: ', ($end_date1 - $start_date1).TotalSeconds)); }"

Why use ICollection and not IEnumerable or List<T> on many-many/one-many relationships?

Responding to your question about List<T>:

List<T> is a class; specifying an interface allows more flexibility of implementation. A better question is "why not IList<T>?"

To answer that question, consider what IList<T> adds to ICollection<T>: integer indexing, which means the items have some arbitrary order, and can be retrieved by reference to that order. This is probably not meaningful in most cases, since items probably need to be ordered differently in different contexts.

Get the current cell in Excel VB

If you're trying to grab a range with a dynamically generated string, then you just have to build the string like this:

Range(firstcol & firstrow & ":" & secondcol & secondrow).Select

How to access a RowDataPacket object

I found an easy way

Object.prototype.parseSqlResult = function () {
    return JSON.parse(JSON.stringify(this[0]))
}

At db layer do the parsing as

let users= await util.knex.raw('select * from user')
    return users.parseSqlResult()

This will return elements as normal JSON array.

How do I set specific environment variables when debugging in Visual Studio?

In Visual Studio for Mac and C# you can use:

Environment.SetEnvironmentVariable("<Variable_name>", "<Value>");

But you will need the following namespace

using System.Collections;

you can check the full list of variables with this:

foreach (DictionaryEntry de in Environment.GetEnvironmentVariables())
            Console.WriteLine("  {0} = {1}", de.Key, de.Value);

Bad Request - Invalid Hostname IIS7

Check your local hosts file (C:\Windows\System32\drivers\etc\hosts for example). In my case I had previously used this to point a URL to a dev box and then forgotten about it. When I then reused the same URL I kept getting Bad Request (Invalid Hostname) because the traffic was going to the wrong server.

Set type for function parameters?

You can implement a system that handles the type checks automatically, using a wrapper in your function.

With this approach, you can build a complete declarative type check system that will manage for you the type checks . If you are interested in taking a more in depth look at this concept, check the Functyped library

The following implementation illustrates the main idea, in a simplistic, but operative way :

_x000D_
_x000D_
/*_x000D_
 * checkType() : Test the type of the value. If succeds return true, _x000D_
 * if fails, throw an Error_x000D_
 */_x000D_
function checkType(value,type, i){_x000D_
  // perform the appropiate test to the passed _x000D_
  // value according to the provided type_x000D_
  switch(type){_x000D_
    case Boolean : _x000D_
      if(typeof value === 'boolean') return true;_x000D_
      break;_x000D_
    case String : _x000D_
      if(typeof value === 'string') return true;_x000D_
      break;_x000D_
    case Number : _x000D_
      if(typeof value === 'number') return true;_x000D_
      break;_x000D_
    default :_x000D_
      throw new Error(`TypeError : Unknown type provided in argument ${i+1}`);_x000D_
  }_x000D_
  // test didn't succeed , throw error_x000D_
  throw new Error(`TypeError : Expecting a ${type.name} in argument ${i+1}`);_x000D_
}_x000D_
_x000D_
_x000D_
/*_x000D_
 * typedFunction() : Constructor that returns a wrapper_x000D_
 * to handle each function call, performing automatic _x000D_
 * arguments type checking_x000D_
 */_x000D_
function typedFunction( parameterTypes, func ){_x000D_
  // types definitions and function parameters _x000D_
  // count must match_x000D_
  if(parameterTypes.length !== func.length) throw new Error(`Function has ${func.length} arguments, but type definition has ${parameterTypes.length}`);_x000D_
  // return the wrapper..._x000D_
  return function(...args){_x000D_
    // provided arguments count must match types_x000D_
    // definitions count_x000D_
    if(parameterTypes.length !== args.length) throw new Error(`Function expects ${func.length} arguments, instead ${args.length} found.`);_x000D_
    // iterate each argument value, and perform a_x000D_
    // type check against it, using the type definitions_x000D_
    // provided in the construction stage_x000D_
    for(let i=0; i<args.length;i++) checkType( args[i], parameterTypes[i] , i)_x000D_
    // if no error has been thrown, type check succeed_x000D_
    // execute function!_x000D_
    return func(...args);_x000D_
  }_x000D_
}_x000D_
_x000D_
// Play time! _x000D_
// Declare a function that expects 2 Numbers_x000D_
let myFunc = typedFunction( [ Number, Number ],  (a,b)=>{_x000D_
  return a+b;_x000D_
});_x000D_
_x000D_
// call the function, with an invalid second argument_x000D_
myFunc(123, '456')_x000D_
// ERROR! Uncaught Error: TypeError : Expecting a Number in argument 2
_x000D_
_x000D_
_x000D_

How to get the response of XMLHttpRequest?

The simple way to use XMLHttpRequest with pure JavaScript. You can set custom header but it's optional used based on requirement.

1. Using POST Method:

window.onload = function(){
    var request = new XMLHttpRequest();
    var params = "UID=CORS&name=CORS";

    request.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            console.log(this.responseText);
        }
    };

    request.open('POST', 'https://www.example.com/api/createUser', true);
    request.setRequestHeader('api-key', 'your-api-key');
    request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    request.send(params);
}

You can send params using POST method.

2. Using GET Method:

Please run below example and will get an JSON response.

_x000D_
_x000D_
window.onload = function(){_x000D_
    var request = new XMLHttpRequest();_x000D_
_x000D_
    request.onreadystatechange = function() {_x000D_
        if (this.readyState == 4 && this.status == 200) {_x000D_
            console.log(this.responseText);_x000D_
        }_x000D_
    };_x000D_
_x000D_
    request.open('GET', 'https://jsonplaceholder.typicode.com/users/1');_x000D_
    request.send();_x000D_
}
_x000D_
_x000D_
_x000D_

How does Zalgo text work?

The text uses combining characters, also known as combining marks. See section 2.11 of Combining Characters in the Unicode Standard (PDF).

In Unicode, character rendering does not use a simple character cell model where each glyph fits into a box with given height. Combining marks may be rendered above, below, or inside a base character

So you can easily construct a character sequence, consisting of a base character and “combining above” marks, of any length, to reach any desired visual height, assuming that the rendering software conforms to the Unicode rendering model. Such a sequence has no meaning of course, and even a monkey could produce it (e.g., given a keyboard with suitable driver).

And you can mix “combining above” and “combining below” marks.

The sample text in the question starts with:

How to save a pandas DataFrame table as a png

I had the same requirement for a project I am doing. But none of the answers came elegant to my requirement. Here is something which finally helped me, and might be useful for this case:

from bokeh.io import export_png, export_svgs
from bokeh.models import ColumnDataSource, DataTable, TableColumn

def save_df_as_image(df, path):
    source = ColumnDataSource(df)
    df_columns = [df.index.name]
    df_columns.extend(df.columns.values)
    columns_for_table=[]
    for column in df_columns:
        columns_for_table.append(TableColumn(field=column, title=column))

    data_table = DataTable(source=source, columns=columns_for_table,height_policy="auto",width_policy="auto",index_position=None)
    export_png(data_table, filename = path)

enter image description here