Programs & Examples On #Metalanguage

Return multiple values from a function, sub or type?

you can return 2 or more values to a function in VBA or any other visual basic stuff but you need to use the pointer method called Byref. See my example below. I will make a function to add and subtract 2 values say 5,6

sub Macro1
    ' now you call the function this way
    dim o1 as integer, o2 as integer
    AddSubtract 5, 6, o1, o2
    msgbox o2
    msgbox o1
end sub


function AddSubtract(a as integer, b as integer, ByRef sum as integer, ByRef dif as integer)
    sum = a + b
    dif = b - 1
end function

how do you increase the height of an html textbox

Use CSS:

<html>
<head>
<style>
.Large
{
    font-size: 16pt;
    height: 50px;
}
</style>
<body>
<input type="text" class="Large">
</body>
</html>

Unable to cast object of type 'System.DBNull' to type 'System.String`

Convert it Like

string s = System.DBNull.value.ToString();

see if two files have the same content in python

Yes, I think hashing the file would be the best way if you have to compare several files and store hashes for later comparison. As hash can clash, a byte-by-byte comparison may be done depending on the use case.

Generally byte-by-byte comparison would be sufficient and efficient, which filecmp module already does + other things too.

See http://docs.python.org/library/filecmp.html e.g.

>>> import filecmp
>>> filecmp.cmp('file1.txt', 'file1.txt')
True
>>> filecmp.cmp('file1.txt', 'file2.txt')
False

Speed consideration: Usually if only two files have to be compared, hashing them and comparing them would be slower instead of simple byte-by-byte comparison if done efficiently. e.g. code below tries to time hash vs byte-by-byte

Disclaimer: this is not the best way of timing or comparing two algo. and there is need for improvements but it does give rough idea. If you think it should be improved do tell me I will change it.

import random
import string
import hashlib
import time

def getRandText(N):
    return  "".join([random.choice(string.printable) for i in xrange(N)])

N=1000000
randText1 = getRandText(N)
randText2 = getRandText(N)

def cmpHash(text1, text2):
    hash1 = hashlib.md5()
    hash1.update(text1)
    hash1 = hash1.hexdigest()

    hash2 = hashlib.md5()
    hash2.update(text2)
    hash2 = hash2.hexdigest()

    return  hash1 == hash2

def cmpByteByByte(text1, text2):
    return text1 == text2

for cmpFunc in (cmpHash, cmpByteByByte):
    st = time.time()
    for i in range(10):
        cmpFunc(randText1, randText2)
    print cmpFunc.func_name,time.time()-st

and the output is

cmpHash 0.234999895096
cmpByteByByte 0.0

How to modify a text file?

Depends on what you want to do. To append you can open it with "a":

 with open("foo.txt", "a") as f:
     f.write("new line\n")

If you want to preprend something you have to read from the file first:

with open("foo.txt", "r+") as f:
     old = f.read() # read everything in the file
     f.seek(0) # rewind
     f.write("new line\n" + old) # write the new line before

What is correct media query for IPad Pro?

For those who want to target an iPad Pro 11" the device-width is 834px, device-height is 1194px and the device-pixel-ratio is 2. Source: screen.width, screen.height and devicePixelRatio reported by Safari on iOS Simulator.

Exact media query for portrait: (device-height: 1194px) and (device-width: 834px) and (-webkit-device-pixel-ratio: 2) and (orientation: portrait)

com.google.android.gms:play-services-measurement-base is being requested by various other libraries

Add to list of your dependencies. Now need to have it for proper work of all firebase dependencies:

implementation 'com.google.firebase:firebase-core:16.0.1'

CSS text-overflow in a table cell?

This is the version that works in IE 9.

http://jsfiddle.net/s27gf2n8/

<div style="display:table; table-layout: fixed; width:100%; " >
        <div style="display:table-row;">
            <div style="display:table-cell;">
                <table style="width: 100%; table-layout: fixed;">
                    <div style="text-overflow:ellipsis;overflow:hidden;white-space:nowrap;">First row. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</div>
                </table>
            </div>
            <div style="display:table-cell;">
                Top right Cell.
            </div>
        </div>
        <div style="display:table-row;">
            <div style="display:table-cell;">
                <table style="width: 100%; table-layout: fixed;">
                    <div style="text-overflow:ellipsis;overflow:hidden;white-space:nowrap;">Second row - Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</div>
                </table>
            </div>
            <div style="display:table-cell;">
                Bottom right cell.
            </div>
        </div>
    </div>

HttpContext.Current.Request.Url.Host what it returns?

Try this:

string callbackurl = Request.Url.Host != "localhost" 
    ? Request.Url.Host : Request.Url.Authority;

This will work for local as well as production environment. Because the local uses url with port no that is possible using Url.Host.

Inline JavaScript onclick function

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

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

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

How to deal with bad_alloc in C++?

You can catch it like any other exception:

try {
  foo();
}
catch (const std::bad_alloc&) {
  return -1;
}

Quite what you can usefully do from this point is up to you, but it's definitely feasible technically.



In general you cannot, and should not try, to respond to this error. bad_alloc indicates that a resource cannot be allocated because not enough memory is available. In most scenarios your program cannot hope to cope with that, and terminating soon is the only meaningful behaviour.

Worse, modern operating systems often over-allocate: on such systems, malloc and new can return a valid pointer even if there is not enough free memory left – std::bad_alloc will never be thrown, or is at least not a reliable sign of memory exhaustion. Instead, attempts to access the allocated memory will then result in a segmentation fault, which is not catchable (you can handle the segmentation fault signal, but you cannot resume the program afterwards).

The only thing you could do when catching std::bad_alloc is to perhaps log the error, and try to ensure a safe program termination by freeing outstanding resources (but this is done automatically in the normal course of stack unwinding after the error gets thrown if the program uses RAII appropriately).

In certain cases, the program may attempt to free some memory and try again, or use secondary memory (= disk) instead of RAM but these opportunities only exist in very specific scenarios with strict conditions:

  1. The application must ensure that it runs on a system that does not overcommit memory, i.e. it signals failure upon allocation rather than later.
  2. The application must be able to free memory immediately, without any further accidental allocations in the meantime.

It’s exceedingly rare that applications have control over point 1 — userspace applications never do, it’s a system-wide setting that requires root permissions to change.1

OK, so let’s assume you’ve fixed point 1. What you can now do is for instance use a LRU cache for some of your data (probably some particularly large business objects that can be regenerated or reloaded on demand). Next, you need to put the actual logic that may fail into a function that supports retry — in other words, if it gets aborted, you can just relaunch it:

lru_cache<widget> widget_cache;

double perform_operation(int widget_id) {
    std::optional<widget> maybe_widget = widget_cache.find_by_id(widget_id);
    if (not maybe_widget) {
        maybe_widget = widget_cache.store(widget_id, load_widget_from_disk(widget_id));
    }
    return maybe_widget->frobnicate();
}

…

for (int num_attempts = 0; num_attempts < MAX_NUM_ATTEMPTS; ++num_attempts) {
    try {
        return perform_operation(widget_id);
    } catch (std::bad_alloc const&) {
        if (widget_cache.empty()) throw; // memory error elsewhere.
        widget_cache.remove_oldest();
    }
}

// Handle too many failed attempts here.

But even here, using std::set_new_handler instead of handling std::bad_alloc provides the same benefit and would be much simpler.


1 If you’re creating an application that does control point 1, and you’re reading this answer, please shoot me an email, I’m genuinely curious about your circumstances.


What is the C++ Standard specified behavior of new in c++?

The usual notion is that if new operator cannot allocate dynamic memory of the requested size, then it should throw an exception of type std::bad_alloc.
However, something more happens even before a bad_alloc exception is thrown:

C++03 Section 3.7.4.1.3: says

An allocation function that fails to allocate storage can invoke the currently installed new_handler(18.4.2.2), if any. [Note: A program-supplied allocation function can obtain the address of the currently installed new_handler using the set_new_handler function (18.4.2.3).] If an allocation function declared with an empty exception-specification (15.4), throw(), fails to allocate storage, it shall return a null pointer. Any other allocation function that fails to allocate storage shall only indicate failure by throw-ing an exception of class std::bad_alloc (18.4.2.1) or a class derived from std::bad_alloc.

Consider the following code sample:

#include <iostream>
#include <cstdlib>

// function to call if operator new can't allocate enough memory or error arises
void outOfMemHandler()
{
    std::cerr << "Unable to satisfy request for memory\n";

    std::abort();
}

int main()
{
    //set the new_handler
    std::set_new_handler(outOfMemHandler);

    //Request huge memory size, that will cause ::operator new to fail
    int *pBigDataArray = new int[100000000L];

    return 0;
}

In the above example, operator new (most likely) will be unable to allocate space for 100,000,000 integers, and the function outOfMemHandler() will be called, and the program will abort after issuing an error message.

As seen here the default behavior of new operator when unable to fulfill a memory request, is to call the new-handler function repeatedly until it can find enough memory or there is no more new handlers. In the above example, unless we call std::abort(), outOfMemHandler() would be called repeatedly. Therefore, the handler should either ensure that the next allocation succeeds, or register another handler, or register no handler, or not return (i.e. terminate the program). If there is no new handler and the allocation fails, the operator will throw an exception.

What is the new_handler and set_new_handler?

new_handler is a typedef for a pointer to a function that takes and returns nothing, and set_new_handler is a function that takes and returns a new_handler.

Something like:

typedef void (*new_handler)();
new_handler set_new_handler(new_handler p) throw();

set_new_handler's parameter is a pointer to the function operator new should call if it can't allocate the requested memory. Its return value is a pointer to the previously registered handler function, or null if there was no previous handler.

How to handle out of memory conditions in C++?

Given the behavior of newa well designed user program should handle out of memory conditions by providing a proper new_handlerwhich does one of the following:

Make more memory available: This may allow the next memory allocation attempt inside operator new's loop to succeed. One way to implement this is to allocate a large block of memory at program start-up, then release it for use in the program the first time the new-handler is invoked.

Install a different new-handler: If the current new-handler can't make any more memory available, and of there is another new-handler that can, then the current new-handler can install the other new-handler in its place (by calling set_new_handler). The next time operator new calls the new-handler function, it will get the one most recently installed.

(A variation on this theme is for a new-handler to modify its own behavior, so the next time it's invoked, it does something different. One way to achieve this is to have the new-handler modify static, namespace-specific, or global data that affects the new-handler's behavior.)

Uninstall the new-handler: This is done by passing a null pointer to set_new_handler. With no new-handler installed, operator new will throw an exception ((convertible to) std::bad_alloc) when memory allocation is unsuccessful.

Throw an exception convertible to std::bad_alloc. Such exceptions are not be caught by operator new, but will propagate to the site originating the request for memory.

Not return: By calling abort or exit.

log4j vs logback

Should you? Yes.

Why? Log4J has essentially been deprecated by Logback.

Is it urgent? Maybe not.

Is it painless? Probably, but it may depend on your logging statements.

Note that if you really want to take full advantage of LogBack (or SLF4J), then you really need to write proper logging statements. This will yield advantages like faster code because of the lazy evaluation, and less lines of code because you can avoid guards.

Finally, I highly recommend SLF4J. (Why recreate the wheel with your own facade?)

How to remove application from app listings on Android Developer Console

Select Store Presense then Pricing Distribution and select Unpublish from App Availability. enter image description here

Google's help for this is here: https://support.google.com/googleplay/android-developer/answer/113476#unpublish (as of Feb-2020)

How to keep footer at bottom of screen

set its position:fixed and bottom:0 so that it will always reside at bottom of your browser windows

How to insert close button in popover for Bootstrap

enter image description here

The following is what i just used in my project .And hope it can help you

<a id="manualinputlabel" href="#" data-toggle="popover" title="weclome to use the sql quer" data-html=true  data-original-title="weclome to use the sql query" data-content="content">example</a>


$('#manualinputlabel').click(function(e) {
              $('.popover-title').append('<button id="popovercloseid" type="button" class="close">&times;</button>');
              $(this).popover();

          });

      $(document).click(function(e) {
         if(e.target.id=="popovercloseid" )
         {
              $('#manualinputlabel').popover('hide');                
         }

      });

tell pip to install the dependencies of packages listed in a requirement file

As @Ming mentioned:

pip install -r file.txt

Here's a simple line to force update all dependencies:

while read -r package; do pip install --upgrade --force-reinstall $package;done < pipfreeze.txt

Java: How to set Precision for double value?

BigDecimal value = new BigDecimal(10.0000);
value.setScale(4);

Fast and simple String encrypt/decrypt in JAVA

If you are using Android then you can use android.util.Base64 class.

Encode:

passwd = Base64.encodeToString( passwd.getBytes(), Base64.DEFAULT );

Decode:

passwd = new String( Base64.decode( passwd, Base64.DEFAULT ) );

A simple and fast single line solution.

How do I subtract minutes from a date in javascript?

Extend Date class with this function

// Add (or substract if value is negative) the value, expresed in timeUnit
// to the date and return the new date.
Date.dateAdd = function(currentDate, value, timeUnit) {

    timeUnit = timeUnit.toLowerCase();
    var multiplyBy = { w:604800000,
                     d:86400000,
                     h:3600000,
                     m:60000,
                     s:1000 };
    var updatedDate = new Date(currentDate.getTime() + multiplyBy[timeUnit] * value);

    return updatedDate;
};

So you can add or substract a number of minutes, seconds, hours, days... to any date.

add_10_minutes_to_current_date = Date.dateAdd( Date(), 10, "m");
subs_1_hour_to_a_date = Date.dateAdd( date_value, -1, "h");

How using try catch for exception handling is best practice

The second approach is a good one.

If you don't want to show the error and confuse the user of application by showing runtime exception(i.e. error) which is not related to them, then just log error and the technical team can look for the issue and resolve it.

try
{
  //do some work
}
catch(Exception exception)
{
   WriteException2LogFile(exception);//it will write the or log the error in a text file
}

I recommend that you go for the second approach for your whole application.

How to use the addr2line command in Linux?

Try adding the -f option to show the function names :

addr2line -f -e a.out 0x4005BDC

Executing Shell Scripts from the OS X Dock?

Someone wrote...

I just set all files that end in ".sh" to open with Terminal. It works fine and you don't have to change the name of each shell script you want to run.

How to show a running progress bar while page is loading

It’s a chicken-and-egg problem. You won’t be able to do it because you need to load the assets to display the progress bar widget, by which time your page will be either fully or partially downloaded. Also, you need to know the total size of the page prior to the user requesting in order to calculate a percentage.

It’s more hassle than it’s worth.

pythonw.exe or python.exe?

To summarize and complement the existing answers:

  • python.exe is a console (terminal) application for launching CLI-type scripts.

    • Unless run from an existing console window, python.exe opens a new console window.
    • Standard streams sys.stdin, sys.stdout and sys.stderr are connected to the console window.
    • Execution is synchronous when launched from a cmd.exe or PowerShell console window: See eryksun's 1st comment below.

      • If a new console window was created, it stays open until the script terminates.
      • When invoked from an existing console window, the prompt is blocked until the script terminates.
  • pythonw.exe is a GUI app for launching GUI/no-UI-at-all scripts.

    • NO console window is opened.
    • Execution is asynchronous:
      • When invoked from a console window, the script is merely launched and the prompt returns right away, whether the script is still running or not.
    • Standard streams sys.stdin, sys.stdout and sys.stderr are NOT available.
      • Caution: Unless you take extra steps, this has potentially unexpected side effects:
        • Unhandled exceptions cause the script to abort silently.
        • In Python 2.x, simply trying to use print() can cause that to happen (in 3.x, print() simply has no effect).
        • To prevent that from within your script, and to learn more, see this answer of mine.
        • Ad-hoc, you can use output redirection:Thanks, @handle.
          pythonw.exe yourScript.pyw 1>stdout.txt 2>stderr.txt
          (from PowerShell:
          cmd /c pythonw.exe yourScript.pyw 1>stdout.txt 2>stderr.txt) to capture stdout and stderr output in files.
          If you're confident that use of print() is the only reason your script fails silently with pythonw.exe, and you're not interested in stdout output, use @handle's command from the comments:
          pythonw.exe yourScript.pyw 1>NUL 2>&1
          Caveat: This output redirection technique does not work when invoking *.pyw scripts directly (as opposed to by passing the script file path to pythonw.exe). See eryksun's 2nd comment and its follow-ups below.

You can control which of the executables runs your script by default - such as when opened from Explorer - by choosing the right filename extension:

  • *.py files are by default associated (invoked) with python.exe
  • *.pyw files are by default associated (invoked) with pythonw.exe

How to resolve Value cannot be null. Parameter name: source in linq?

Value cannot be null. Parameter name: source

Above error comes in situation when you are querying the collection which is null.

For demonstration below code will result in such an exception.

Console.WriteLine("Hello World");
IEnumerable<int> list = null;
list.Where(d => d ==4).FirstOrDefault();

Here is the output of the above code.

Hello World Run-time exception (line 11): Value cannot be null. Parameter name: source

Stack Trace:

[System.ArgumentNullException: Value cannot be null. Parameter name: source] at Program.Main(): line 11

In your case ListMetadataKor is null. Here is the fiddle if you want to play around.

How to delete duplicate rows in SQL Server?

Microsoft has a vey ry neat guide on how to remove duplicates. Check out http://support.microsoft.com/kb/139444

In brief, here is the easiest way to delete duplicates when you have just a few rows to delete:

SET rowcount 1;
DELETE FROM t1 WHERE myprimarykey=1;

myprimarykey is the identifier for the row.

I set rowcount to 1 because I only had two rows that were duplicated. If I had had 3 rows duplicated then I would have set rowcount to 2 so that it deletes the first two that it sees and only leaves one in table t1.

Hope it helps anyone

What do these three dots in React do?

For someone who wants to understand this simple and fast:

First of all, this is not a syntax only to react. this is a syntax from ES6 called Spread syntax which iterate(merge, add..etc) array and object. read more about here

So answer to the question: let's imagine you have this tag:

<UserTag name="Supun" age="66" gender="male" />

and You do this:

const user = {
  "name"=>"Joe",
  "age"=>"50"      
  "test"=>"test-val"
};

<UserTag name="Supun" gender="male"  {...user} age="66" />

then the tag will equal this:

<UserTag name="Joe" gender="male" test="test-val" age="66" />

So what happened was when you use Spread syntax in a react tag it takes tag's attribute as object attributes which merge(replace if it exists) with the given object user. also, you might have noticed one thing that it only replaces before attribute, not after attributes. so in this example age remains as it is.

Hopes this helps :)

Load content with ajax in bootstrap modal

Easily done in Bootstrap 3 like so:

<a data-toggle="modal" href="remote.html" data-target="#modal">Click me</a>

Export javascript data to CSV file without server interaction

See adeneo's answer, but don't forget encodeURIComponent!

a.href     = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csvString);

Also, I needed to do "\r\n" not just "\n" for the row delimiter.

var csvString = csvRows.join("\r\n");

Revised fiddle: http://jsfiddle.net/7Q3c6/

enumerate() for dictionary in python

Since you are using enumerate hence your i is actually the index of the key rather than the key itself.

So, you are getting 3 in the first column of the row 3 4even though there is no key 3.

enumerate iterates through a data structure(be it list or a dictionary) while also providing the current iteration number.

Hence, the columns here are the iteration number followed by the key in dictionary enum

Others Solutions have already shown how to iterate over key and value pair so I won't repeat the same in mine.

Print empty line?

You can just do

print()

to get an empty line.

How do I create delegates in Objective-C?

Swift version

A delegate is just a class that does some work for another class. Read the following code for a somewhat silly (but hopefully enlightening) Playground example that shows how this is done in Swift.

// A protocol is just a list of methods (and/or properties) that must
// be used by any class that adopts the protocol.
protocol OlderSiblingDelegate: class {
    // This protocol only defines one required method
    func getYourNiceOlderSiblingAGlassOfWater() -> String
}

class BossyBigBrother {
    
    // The delegate is the BossyBigBrother's slave. This position can 
    // be assigned later to whoever is available (and conforms to the 
    // protocol).
    weak var delegate: OlderSiblingDelegate?
    
    func tellSomebodyToGetMeSomeWater() -> String? {
        // The delegate is optional because there might not be anyone
        // nearby to boss around.
        return delegate?.getYourNiceOlderSiblingAGlassOfWater()
    }
}

// PoorLittleSister conforms to the OlderSiblingDelegate protocol
class PoorLittleSister: OlderSiblingDelegate {

    // This method is repquired by the protocol, but the protocol said
    // nothing about how it needs to be implemented.
    func getYourNiceOlderSiblingAGlassOfWater() -> String {
        return "Go get it yourself!"
    }
    
}

// initialize the classes
let bigBro = BossyBigBrother()
let lilSis = PoorLittleSister()

// Set the delegate 
// bigBro could boss around anyone who conforms to the 
// OlderSiblingDelegate protocol, but since lilSis is here, 
// she is the unlucky choice.
bigBro.delegate = lilSis

// Because the delegate is set, there is a class to do bigBro's work for him.
// bigBro tells lilSis to get him some water.
if let replyFromLilSis = bigBro.tellSomebodyToGetMeSomeWater() {
    print(replyFromLilSis) // "Go get it yourself!"
}

In actual practice, delegates are often used in the following situations

  1. When a class needs to communicate some information to another class
  2. When a class wants to allow another class to customize it

The classes don't need to know anything about each other beforehand except that the delegate class conforms to the required protocol.

I highly recommend reading the following two articles. They helped me understand delegates even better than the documentation did.

Log to the base 2 in python

In python 3 or above, math class has the following functions

import math

math.log2(x)
math.log10(x)
math.log1p(x)

or you can generally use math.log(x, base) for any base you want.

Using union and count(*) together in SQL query

If you have supporting indexes, and relatively high counts, something like this may be considerably faster than the solutions suggested:

SELECT name, MAX(Rcount) + MAX(Acount) AS TotalCount
FROM (
  SELECT name, COUNT(*) AS Rcount, 0 AS Acount
  FROM Results GROUP BY name
  UNION ALL
  SELECT name, 0, count(*)
  FROM Archive_Results
  GROUP BY name
) AS Both
GROUP BY name
ORDER BY name;

Python Socket Multiple Clients

#!/usr/bin/python
import sys
import os
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)         
port = 50000

try:
    s.bind((socket.gethostname() , port))
except socket.error as msg:
    print(str(msg))
s.listen(10)
conn, addr = s.accept()  
print 'Got connection from'+addr[0]+':'+str(addr[1]))
while 1:
        msg = s.recv(1024)
        print +addr[0]+, ' >> ', msg
        msg = raw_input('SERVER >>'),host
        s.send(msg)
s.close()

How to set the project name/group/version, plus {source,target} compatibility in the same file?

gradle.properties:

theGroup=some.group
theName=someName
theVersion=1.0
theSourceCompatibility=1.6

settings.gradle:

rootProject.name = theName

build.gradle:

apply plugin: "java"

group = theGroup
version = theVersion
sourceCompatibility = theSourceCompatibility

Visual Studio 2015 doesn't have cl.exe

Visual Studio 2015 doesn't install C++ by default. You have to rerun the setup, select Modify and then check Programming Language -> C++

How can I get the active screen dimensions?

Adding a solution that doesn't use WinForms but NativeMethods instead. First you need to define the native methods needed.

public static class NativeMethods
{
    public const Int32 MONITOR_DEFAULTTOPRIMERTY = 0x00000001;
    public const Int32 MONITOR_DEFAULTTONEAREST = 0x00000002;


    [DllImport( "user32.dll" )]
    public static extern IntPtr MonitorFromWindow( IntPtr handle, Int32 flags );


    [DllImport( "user32.dll" )]
    public static extern Boolean GetMonitorInfo( IntPtr hMonitor, NativeMonitorInfo lpmi );


    [Serializable, StructLayout( LayoutKind.Sequential )]
    public struct NativeRectangle
    {
        public Int32 Left;
        public Int32 Top;
        public Int32 Right;
        public Int32 Bottom;


        public NativeRectangle( Int32 left, Int32 top, Int32 right, Int32 bottom )
        {
            this.Left = left;
            this.Top = top;
            this.Right = right;
            this.Bottom = bottom;
        }
    }


    [StructLayout( LayoutKind.Sequential, CharSet = CharSet.Auto )]
    public sealed class NativeMonitorInfo
    {
        public Int32 Size = Marshal.SizeOf( typeof( NativeMonitorInfo ) );
        public NativeRectangle Monitor;
        public NativeRectangle Work;
        public Int32 Flags;
    }
}

And then get the monitor handle and the monitor info like this.

        var hwnd = new WindowInteropHelper( this ).EnsureHandle();
        var monitor = NativeMethods.MonitorFromWindow( hwnd, NativeMethods.MONITOR_DEFAULTTONEAREST );

        if ( monitor != IntPtr.Zero )
        {
            var monitorInfo = new NativeMonitorInfo();
            NativeMethods.GetMonitorInfo( monitor, monitorInfo );

            var left = monitorInfo.Monitor.Left;
            var top = monitorInfo.Monitor.Top;
            var width = ( monitorInfo.Monitor.Right - monitorInfo.Monitor.Left );
            var height = ( monitorInfo.Monitor.Bottom - monitorInfo.Monitor.Top );
        }

How can I conditionally require form inputs with AngularJS?

if you want put a input required if other is written:

   <input type='text'
   name='name'
   ng-model='person.name'/>

   <input type='text'
   ng-model='person.lastname'             
   ng-required='person.name' />  

Regards.

Error while retrieving information from the server RPC:s-7:AEC-0 in Google play?

I had the same issue - it sorted itself out in ~3 hours after I uploaded the app to the Play console. According to Google:

Warning: It may take up to 2-3 hours after uploading the APK for Google Play to recognize your updated APK version. If you try to test your application before your uploaded APK is recognized by Google Play, your application will receive a ‘purchase cancelled’ response with an error message “This version of the application is not enabled for In-app Billing.

While the message is not the same, I suspect the root cause to be the same.

Displaying standard DataTables in MVC

This is not "wrong" at all, it's just not what the cool guys typically do with MVC. As an aside, I wish some of the early demos of ASP.NET MVC didn't try to cram in Linq-to-Sql at the same time. It's pretty awesome and well suited for MVC, sure, but it's not required. There is nothing about MVC that prevents you from using ADO.NET. For example:

Controller action:

public ActionResult Index()
{
    ViewData["Message"] = "Welcome to ASP.NET MVC!";

    DataTable dt = new DataTable("MyTable");
    dt.Columns.Add(new DataColumn("Col1", typeof(string)));
    dt.Columns.Add(new DataColumn("Col2", typeof(string)));
    dt.Columns.Add(new DataColumn("Col3", typeof(string)));

    for (int i = 0; i < 3; i++)
    {
        DataRow row = dt.NewRow();
        row["Col1"] = "col 1, row " + i;
        row["Col2"] = "col 2, row " + i;
        row["Col3"] = "col 3, row " + i;
        dt.Rows.Add(row);
    }

    return View(dt); //passing the DataTable as my Model
}

View: (w/ Model strongly typed as System.Data.DataTable)

<table border="1">
    <thead>
        <tr>
            <%foreach (System.Data.DataColumn col in Model.Columns) { %>
                <th><%=col.Caption %></th>
            <%} %>
        </tr>
    </thead>
    <tbody>
    <% foreach(System.Data.DataRow row in Model.Rows) { %>
        <tr>
            <% foreach (var cell in row.ItemArray) {%>
                <td><%=cell.ToString() %></td>
            <%} %>
        </tr>
    <%} %>         
    </tbody>
</table>

Now, I'm violating a whole lot of principles and "best-practices" of ASP.NET MVC here, so please understand this is just a simple demonstration. The code creating the DataTable should reside somewhere outside of the controller, and the code in the View might be better isolated to a partial, or html helper, to name a few ways you should do things.

You absolutely are supposed to pass objects to the View, if the view is supposed to present them. (Separation of concerns dictates the view shouldn't be responsible for creating them.) In this case I passed the DataTable as the actual view Model, but you could just as well have put it in ViewData collection. Alternatively you might make a specific IndexViewModel class that contains the DataTable and other objects, such as the welcome message.

I hope this helps!

what is the difference between OLE DB and ODBC data sources?

I'm not sure of all the details, but my understanding is that OLE DB and ODBC are two APIs that are available for connecting to various types of databases without having to deal with all the implementation specific details of each. According to the Wikipedia article on OLE DB, OLE DB is Microsoft's successor to ODBC, and provides some features that you might not be able to do with ODBC such as accessing spreadsheets as database sources.

Difference between "char" and "String" in Java

I would recommend you to read through the Java tutorial documentation hosted on Oracle's website whenever you are in doubt about anything related to Java.

You can get a clear understanding of the concepts by going through the following tutorials:

Pass a list to a function to act as multiple arguments

Since Python 3.5 you can unpack unlimited amount of lists.

PEP 448 - Additional Unpacking Generalizations

So this will work:

a = ['1', '2', '3', '4']
b = ['5', '6']
function_that_needs_strings(*a, *b)

AngularJS HTTP post to PHP and undefined

In the API I am developing I have a base controller and inside its __construct() method I have the following:

if(isset($_SERVER["CONTENT_TYPE"]) && strpos($_SERVER["CONTENT_TYPE"], "application/json") !== false) {
    $_POST = array_merge($_POST, (array) json_decode(trim(file_get_contents('php://input')), true));
}

This allows me to simply reference the json data as $_POST["var"] when needed. Works great.

That way if an authenticated user connects with a library such a jQuery that sends post data with a default of Content-Type: application/x-www-form-urlencoded or Content-Type: application/json the API will respond without error and will make the API a little more developer friendly.

Hope this helps.

How to URL encode a string in Ruby

str = "\x12\x34\x56\x78\x9a\xbc\xde\xf1\x23\x45\x67\x89\xab\xcd\xef\x12\x34\x56\x78\x9a".force_encoding('ASCII-8BIT')
puts CGI.escape str


=> "%124Vx%9A%BC%DE%F1%23Eg%89%AB%CD%EF%124Vx%9A"

Comparing two input values in a form validation with AngularJS

You have to look at the bigger problem. How to write the directives that solve one problem. You should try directive use-form-error. Would it help to solve this problem, and many others.

    <form name="ExampleForm">
  <label>Password</label>
  <input ng-model="password" required />
  <br>
   <label>Confirm password</label>
  <input ng-model="confirmPassword" required />
  <div use-form-error="isSame" use-error-expression="password && confirmPassword && password!=confirmPassword" ng-show="ExampleForm.$error.isSame">Passwords Do Not Match!</div>
</form>

Live example jsfiddle

MySQL "CREATE TABLE IF NOT EXISTS" -> Error 1050

create database if not exists `test`;

USE `test`;

SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;

/*Table structure for table `test` */

***CREATE TABLE IF NOT EXISTS `tblsample` (
  `id` int(11) NOT NULL auto_increment,   
  `recid` int(11) NOT NULL default '0',       
  `cvfilename` varchar(250)  NOT NULL default '',     
  `cvpagenumber`  int(11) NULL,     
  `cilineno` int(11)  NULL,    
  `batchname`  varchar(100) NOT NULL default '',
  `type` varchar(20) NOT NULL default '',    
  `data` varchar(100) NOT NULL default '',
   PRIMARY KEY  (`id`)
);***

Remote Linux server to remote linux server dir copy. How?

There are two ways I usually do this, both use ssh:

scp -r sourcedir/ [email protected]:/dest/dir/

or, the more robust and faster (in terms of transfer speed) method:

rsync -auv -e ssh --progress sourcedir/ [email protected]:/dest/dir/

Read the man pages for each command if you want more details about how they work.

Does MS Access support "CASE WHEN" clause if connect with ODBC?

Since you are using Access to compose the query, you have to stick to Access's version of SQL.

To choose between several different return values, use the switch() function. So to translate and extend your example a bit:

select switch(
  age > 40, 4,
  age > 25, 3,
  age > 20, 2,
  age > 10, 1,
  true, 0
) from demo

The 'true' case is the default one. If you don't have it and none of the other cases match, the function will return null.

The Office website has documentation on this but their example syntax is VBA and it's also wrong. I've given them feedback on this but you should be fine following the above example.

How to move text up using CSS when nothing is working

try a negative margin.

margin-top: -10px; /* as an example */

How to iterate through XML in Powershell?

PowerShell has built-in XML and XPath functions. You can use the Select-Xml cmdlet with an XPath query to select nodes from XML object and then .Node.'#text' to access node value.

[xml]$xml = Get-Content $serviceStatePath
$nodes = Select-Xml "//Object[Property/@Name='ServiceState' and Property='Running']/Property[@Name='DisplayName']" $xml
$nodes | ForEach-Object {$_.Node.'#text'}

Or shorter

[xml]$xml = Get-Content $serviceStatePath
Select-Xml "//Object[Property/@Name='ServiceState' and Property='Running']/Property[@Name='DisplayName']" $xml |
  % {$_.Node.'#text'}

Reversing an Array in Java

I would do something like this:

public int[] reverse3(int[] nums) {
  int[] numsReturn = new int[nums.length()]; 
  int count = nums.length()-1;
  for(int num : nums) {
    numsReturn[count] = num;
    count--;
  }
  return numsReturn;
}

Getting a POST variable

Use this for GET values:

Request.QueryString["key"]

And this for POST values

Request.Form["key"]

Also, this will work if you don't care whether it comes from GET or POST, or the HttpContext.Items collection:

Request["key"]

Another thing to note (if you need it) is you can check the type of request by using:

Request.RequestType

Which will be the verb used to access the page (usually GET or POST). Request.IsPostBack will usually work to check this, but only if the POST request includes the hidden fields added to the page by the ASP.NET framework.

How to call an async method from a getter or setter?

You can't call it asynchronously, since there is no asynchronous property support, only async methods. As such, there are two options, both taking advantage of the fact that asynchronous methods in the CTP are really just a method that returns Task<T> or Task:

// Make the property return a Task<T>
public Task<IEnumerable> MyList
{
    get
    {
         // Just call the method
         return MyAsyncMethod();
    }
}

Or:

// Make the property blocking
public IEnumerable MyList
{
    get
    {
         // Block via .Result
         return MyAsyncMethod().Result;
    }
}

MySQL Query to select data from last week?

It can be in a single line:

SELECT * FROM table WHERE Date BETWEEN (NOW() - INTERVAL 7 DAY) AND NOW()

What is the difference between typeof and instanceof and when should one be used vs. the other?

According to MDN documentation about typeof, objects instantiated with the "new" keyword are of type 'object':

typeof 'bla' === 'string';

// The following are confusing, dangerous, and wasteful. Avoid them.
typeof new Boolean(true) === 'object'; 
typeof new Number(1) === 'object'; 
typeof new String('abc') === 'object';

While documentation about instanceof points that:

const objectString = new String('String created with constructor');
objectString instanceOf String; // returns true
objectString instanceOf Object; // returns true

So if one wants to check e.g. that something is a string no matter how it was created, safest approach would be to use instanceof.

Increasing (or decreasing) the memory available to R processes

In RStudio, to increase:

file.edit(file.path("~", ".Rprofile"))

then in .Rprofile type this and save

invisible(utils::memory.limit(size = 60000))

To decrease: open .Rprofile

invisible(utils::memory.limit(size = 30000))

save and restart RStudio.

Rename multiple files by replacing a particular pattern in the filenames using a shell script

An example to help you get off the ground.

for f in *.jpg; do mv "$f" "$(echo "$f" | sed s/IMG/VACATION/)"; done

In this example, I am assuming that all your image files contain the string IMG and you want to replace IMG with VACATION.

The shell automatically evaluates *.jpg to all the matching files.

The second argument of mv (the new name of the file) is the output of the sed command that replaces IMG with VACATION.

If your filenames include whitespace pay careful attention to the "$f" notation. You need the double-quotes to preserve the whitespace.

Steps to upload an iPhone application to the AppStore

Apple provides detailed, illustrated instructions covering every step of the process. Log in to the iPhone developer site and click the "program portal" link. In the program portal you'll find a link to the program portal user's guide, which is a really good reference and guide on this topic.

How to load a UIView using a nib file created with Interface Builder

I'm not sure what some of the answers are talking about, but I need to put this answer here for when I search in Google next time. Keywords: "How to load a UIView from a nib" or "How to load a UIView from an NSBundle."

Here's the code almost 100% straight up from the Apress Beginning iPhone 3 book (page 247, "Using The New Table View Cell"):

- (void)viewDidLoad {
    [super viewDidLoad];
    NSArray *bundle = [[NSBundle mainBundle] loadNibNamed:@"Blah"
                                                 owner:self options:nil];
    Blah *blah;
    for (id object in bundle) {
        if ([object isKindOfClass:[Blah class]]) {
            blah = (Blah *)object;
            break;
        }
    }   
    assert(blah != nil && "blah can't be nil");
    [self.view addSubview: blah];
} 

This supposes you have a UIView subclass called Blah, a nib called Blah which contains a UIView which has its class set to Blah.


Category: NSObject+LoadFromNib

#import "NSObject+LoadFromNib.h"

@implementation NSObject (LoadFromNib)

+ (id)loadFromNib:(NSString *)name classToLoad:(Class)classToLoad {
    NSArray *bundle = [[NSBundle mainBundle] loadNibNamed:name owner:self options:nil];
    for (id object in bundle) {
        if ([object isKindOfClass:classToLoad]) {
            return object;
        }
    }
    return nil;
}

@end

Swift Extension

extension UIView {
    class func loadFromNib<T>(withName nibName: String) -> T? {
        let nib  = UINib.init(nibName: nibName, bundle: nil)
        let nibObjects = nib.instantiate(withOwner: nil, options: nil)
        for object in nibObjects {
            if let result = object as? T {
                return result
            }
        }
        return nil
    }
}

And an example in use:

class SomeView: UIView {
    class func loadFromNib() -> SomeView? {
        return self.loadFromNib(withName: "SomeView")
    }
}

How do I send a POST request with PHP?

Here is using just one command without cURL. Super simple.

echo file_get_contents('https://www.server.com', false, stream_context_create([
    'http' => [
        'method' => 'POST',
        'header'  => "Content-type: application/x-www-form-urlencoded",
        'content' => http_build_query([
            'key1' => 'Hello world!', 'key2' => 'second value'
        ])
    ]
]));

Checking for Undefined In React

You can try adding a question mark as below. This worked for me.

 componentWillReceiveProps(nextProps) {
    this.setState({
        title: nextProps?.blog?.title,
        body: nextProps?.blog?.content
     })
    }

Android: How to Programmatically set the size of a Layout

Java

This should work:

// Gets linearlayout
LinearLayout layout = findViewById(R.id.numberPadLayout);
// Gets the layout params that will allow you to resize the layout
LayoutParams params = layout.getLayoutParams();
// Changes the height and width to the specified *pixels*
params.height = 100;
params.width = 100;
layout.setLayoutParams(params);

If you want to convert dip to pixels, use this:

int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, <HEIGHT>, getResources().getDisplayMetrics());

Kotlin

create a white rgba / CSS3

I believe

rgba( 0, 0, 0, 0.8 )

is equivalent in shade with #333.

Live demo: http://jsfiddle.net/8MVC5/1/

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

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

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

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

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

Find stored procedure by name

Option 1: In SSMS go to View > Object Explorer Details or press F7. Use the Search box. Finally in the displayed list right click and select Synchronize to find the object in the Object Explorer tree.

Object Explorer Details

Option 2: Install an Add-On like dbForge Search. Right click on the displayed list and select Find in Object Explorer.

enter image description here

In Bash, how can I check if a string begins with some value?

I tweaked @markrushakoff's answer to make it a callable function:

function yesNo {
  # Prompts user with $1, returns true if response starts with y or Y or is empty string
  read -e -p "
$1 [Y/n] " YN

  [[ "$YN" == y* || "$YN" == Y* || "$YN" == "" ]]
}

Use it like this:

$ if yesNo "asfd"; then echo "true"; else echo "false"; fi

asfd [Y/n] y
true

$ if yesNo "asfd"; then echo "true"; else echo "false"; fi

asfd [Y/n] Y
true

$ if yesNo "asfd"; then echo "true"; else echo "false"; fi

asfd [Y/n] yes
true

$ if yesNo "asfd"; then echo "true"; else echo "false"; fi

asfd [Y/n]
true

$ if yesNo "asfd"; then echo "true"; else echo "false"; fi

asfd [Y/n] n
false

$ if yesNo "asfd"; then echo "true"; else echo "false"; fi

asfd [Y/n] ddddd
false

Here is a more complex version that provides for a specified default value:

function toLowerCase {
  echo "$1" | tr '[:upper:]' '[:lower:]'
}

function yesNo {
  # $1: user prompt
  # $2: default value (assumed to be Y if not specified)
  # Prompts user with $1, using default value of $2, returns true if response starts with y or Y or is empty string

  local DEFAULT=yes
  if [ "$2" ]; then local DEFAULT="$( toLowerCase "$2" )"; fi
  if [[ "$DEFAULT" == y* ]]; then
    local PROMPT="[Y/n]"
  else
    local PROMPT="[y/N]"
  fi
  read -e -p "
$1 $PROMPT " YN

  YN="$( toLowerCase "$YN" )"
  { [ "$YN" == "" ] && [[ "$PROMPT" = *Y* ]]; } || [[ "$YN" = y* ]]
}

Use it like this:

$ if yesNo "asfd" n; then echo "true"; else echo "false"; fi

asfd [y/N]
false

$ if yesNo "asfd" n; then echo "true"; else echo "false"; fi

asfd [y/N] y
true

$ if yesNo "asfd" y; then echo "true"; else echo "false"; fi

asfd [Y/n] n
false

In Perl, how to remove ^M from a file?

In vi hit :.

Then s/Control-VControl-M//g.

Control-V Control-M are obviously those keys. Don't spell it out.

Subtract minute from DateTime in SQL Server 2005

Use DATEPART to pull apart your interval, and DATEADD to subtract the parts:

select dateadd(
     hh,
    -1 * datepart(hh, cast('1:15' as datetime)),
    dateadd(
        mi,
        -1 * datepart(mi, cast('1:15' as datetime)),
        '2000-01-01 08:30:00'))

or, we can convert to minutes first (though OP would prefer not to):

declare @mins int
select @mins = datepart(mi, cast('1:15' as datetime)) + 60 * datepart(hh, cast('1:15' as datetime)) 
select dateadd(mi, -1 * @mins, '2000-01-01 08:30:00')

How to capture UIView to UIImage without loss of quality on retina display

I have created a Swift extension based on @Dima solution:

extension UIImage {
    class func imageWithView(view: UIView) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0)
        view.drawViewHierarchyInRect(view.bounds, afterScreenUpdates: true)
        let img = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return img
    }
}

EDIT: Swift 4 improved version

extension UIImage {
    class func imageWithView(_ view: UIView) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.isOpaque, 0)
        defer { UIGraphicsEndImageContext() }
        view.drawHierarchy(in: view.bounds, afterScreenUpdates: true)
        return UIGraphicsGetImageFromCurrentImageContext() ?? UIImage()
    }
}

Usage:

let view = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))  
let image = UIImage.imageWithView(view)

How to make a promise from setTimeout

Implementation:

// Promisify setTimeout
const pause = (ms, cb, ...args) =>
  new Promise((resolve, reject) => {
    setTimeout(async () => {
      try {
        resolve(await cb?.(...args))
      } catch (error) {
        reject(error)
      }
    }, ms)
  })

Tests:

// Test 1
pause(1000).then(() => console.log('called'))
// Test 2
pause(1000, (a, b, c) => [a, b, c], 1, 2, 3).then(value => console.log(value))
// Test 3
pause(1000, () => {
  throw Error('foo')
}).catch(error => console.error(error))

grabbing first row in a mysql query only

You didn't specify how the order is determined, but this will give you a rank value in MySQL:

SELECT t.*,
       @rownum := @rownum +1 AS rank
  FROM TBL_FOO t
  JOIN (SELECT @rownum := 0) r
 WHERE t.name = 'sarmen'

Then you can pick out what rows you want, based on the rank value.

Receiving "Attempted import error:" in react app

i had the same issue, but I just typed export on top and erased the default one on the bottom. Scroll down and check the comments.

import React, { Component } from "react";

export class Counter extends Component { // type this  
export default Counter; // this is eliminated  

take(1) vs first()

It turns out there's a very important distinction between the two methods: first() will emit an error if the stream completes before a value is emitted. Or, if you've provided a predicate (i.e. first(value => value === 'foo')), it will emit an error if the stream completes before a value that passes the predicate is emitted.

take(1), on the other hand, will happily carry on if a value is never emitted from the stream. Here's a simple example:

const subject$ = new Subject();

// logs "no elements in sequence" when the subject completes
subject$.first().subscribe(null, (err) => console.log(err.message));

// never does anything
subject$.take(1).subscribe(console.log);

subject$.complete();

Another example, using a predicate:

const observable$ = of(1, 2, 3);

// logs "no elements in sequence" when the observable completes
observable$
 .first((value) => value > 5)
 .subscribe(null, (err) => console.log(err.message));

// the above can also be written like this, and will never do
// anything because the filter predicate will never return true
observable$
 .filter((value) => value > 5);
 .take(1)
 .subscribe(console.log);

As a newcomer to RxJS, this behavior was very confusing to me, although it was my own fault because I made some incorrect assumptions. If I had bothered to check the docs, I would have seen that the behavior is clearly documented:

Throws an error if defaultValue was not provided and a matching element is not found.

The reason I've run into this so frequently is a fairly common Angular 2 pattern where observables are cleaned up manually during the OnDestroy lifecycle hook:

class MyComponent implements OnInit, OnDestroy {
  private stream$: Subject = someDelayedStream();
  private destroy$ = new Subject();

  ngOnInit() {
    this.stream$
      .takeUntil(this.destroy$)
      .first()
      .subscribe(doSomething);
  }

  ngOnDestroy() {
    this.destroy$.next(true);
  }
}

The code looks harmless at first, but problems arise when the component in destroyed before stream$ can emit a value. Because I'm using first(), an error is thrown when the component is destroyed. I'm usually only subscribing to a stream to get a value that is to be used within the component, so I don't care if the component gets destroyed before the stream emits. Because of this, I've started using take(1) in almost all places where I would have previously used first().

filter(fn).take(1) is a bit more verbose than first(fn), but in most cases I prefer a little more verbosity over handling errors that ultimately have no impact on the application.

Also important to note: The same applies for last() and takeLast(1).

reference

How to use curl to get a GET request exactly same as using Chrome?

Open Chrome Developer Tools, go to Network tab, make your request (you may need to check "Preserve Log" if the page refreshes). Find the request on the left, right-click, "Copy as cURL".

Alternative for <blink>

No, there isn't in HTML. There is a good reason why the developers chose to go out of their way to remove support for an element whose implementation was otherwise untouched for upwards of a decade.

That said... you could emulate it using a CSS animation, but if I were you, I wouldn't risk CSS animations being axed due to being abused in this manner :)

PHP - include a php file and also send query parameters

I have ran into this when doing ajax forms where I include multiple field sets. Taking for example an employment application. I start out with one professional reference set and I have a button that says "Add More". This does an ajax call with a $count parameter to include the input set again (name, contact, phone.. etc) This works fine on first page call as I do something like:

<?php 
include('references.php');`
?>

User presses a button that makes an ajax call ajax('references.php?count=1'); Then inside the references.php file I have something like:

<?php
$count = isset($_GET['count']) ? $_GET['count'] : 0;
?>

I also have other dynamic includes like this throughout the site that pass parameters. The problem happens when the user presses submit and there is a form error. So now to not duplicate code to include those extra field sets that where dynamically included, i created a function that will setup the include with the appropriate GET params.

<?php

function include_get_params($file) {
  $parts = explode('?', $file);
  if (isset($parts[1])) {
    parse_str($parts[1], $output);
    foreach ($output as $key => $value) {
      $_GET[$key] = $value;
    }
  }
  include($parts[0]);
}
?>

The function checks for query params, and automatically adds them to the $_GET variable. This has worked pretty good for my use cases.

Here is an example on the form page when called:

<?php
// We check for a total of 12
for ($i=0; $i<12; $i++) {
  if (isset($_POST['references_name_'.$i]) && !empty($_POST['references_name_'.$i])) {
   include_get_params(DIR .'references.php?count='. $i);
 } else {
   break;
 }
}
?>

Just another example of including GET params dynamically to accommodate certain use cases. Hope this helps. Please note this code isn't in its complete state but this should be enough to get anyone started pretty good for their use case.

How to get multiline input from user

Use the input() built-in function to get a input line from the user.

You can read the help here.

You can use the following code to get several line at once (finishing by an empty one):

while input() != '':
    do_thing

Applying a single font to an entire website with CSS

Ok so I was having this issue where I tried several different options.

The font i'm using is Ubuntu-LI , I created a font folder in my working directory. under the folder fonts

I was able to apply it... eventually here is my working code

I wanted this to apply to my entire website so I put it at the top of the css doc. above all of the Div tags (not that it matters, just know that any individual fonts you assign post your script will take precedence)

@font-face{
    font-family: "Ubuntu-LI";
    src: url("/fonts/Ubuntu/(Ubuntu-LI.ttf"),
    url("../fonts/Ubuntu/Ubuntu-LI.ttf");
}

*{
    font-family:"Ubuntu-LI";
}

If i then wanted all of my H1 tags to be something else lets say sans sarif I would do something like

h1{
   font-family: Sans-sarif;
}

From which case only my H1 tags would be the sans-sarif font and the rest of my page would be the Ubuntu-LI font

How to get date and time from server

No need to use date_default_timezone_set for the whole script, just specify the timezone you want with a DateTime object:

$now = new DateTime(null, new DateTimeZone('America/New_York'));
$now->setTimezone(new DateTimeZone('Europe/London'));    // Another way
echo $now->format("Y-m-d\TH:i:sO"); // something like "2015-02-11T06:16:47+0100" (ISO 8601)

How to convert SSH keypairs generated using PuTTYgen (Windows) into key-pairs used by ssh-agent and Keychain (Linux)

I recently had this problem as I was moving from Putty for Linux to Remmina for Linux. So I have a lot of PPK files for Putty in my .putty directory as I've been using it's for 8 years. For this I used a simple for command for bash shell to do all files:

cd ~/.putty
for X in *.ppk; do puttygen $X -L > ~/.ssh/$(echo $X | sed 's,./,,' | sed 's/.ppk//g').pub; puttygen $X -O private-openssh -o ~/.ssh/$(echo $X | sed 's,./,,' | sed 's/.ppk//g').pvk; done;

Very quick and to the point, got the job done for all files that putty had. If it finds a key with a password it will stop and ask for the password for that key first and then continue.

How to empty/destroy a session in rails?

To clear only certain parameters, you can use:

[:param1, :param2, :param3].each { |k| session.delete(k) }

cannot import name patterns

Pattern module in not available from django 1.8. So you need to remove pattern from your import and do something similar to the following:

from django.conf.urls import include, url
from django.contrib import admin

admin.autodiscover()

urlpatterns = [                 
    # here we are not using pattern module like in previous django versions
    url(r'^admin/', include(admin.site.urls)),
]

Setting network adapter metric priority in Windows 7

I had the same problem on Windows 7 64-bit Pro. I adjusted network adapters binding using Control panel but nothing changed. Also metrics where showing that Win should use Ethernet adapter as primary, but it didn't.

Then a tried to uninstall Ethernet adapter driver and then install it again (without restart) and then I checked metrics for sure.

After this, Windows started prioritize Ethernet adapter.

How to check if the given string is palindrome?

A more Ruby-style rewrite of Hal's Ruby version:

class String
  def palindrome?
    (test = gsub(/[^A-Za-z]/, '').downcase) == test.reverse
  end
end

Now you can call palindrome? on any string.

Creating stored procedure with declare and set variables

I assume you want to pass the Order ID in. So:

CREATE PROCEDURE [dbo].[Procedure_Name]
(
    @OrderID INT
) AS
BEGIN
    Declare @OrderItemID AS INT
    DECLARE @AppointmentID AS INT
    DECLARE @PurchaseOrderID AS INT
    DECLARE @PurchaseOrderItemID AS INT
    DECLARE @SalesOrderID AS INT
    DECLARE @SalesOrderItemID AS INT

    SET @OrderItemID = (SELECT OrderItemID FROM [OrderItem] WHERE OrderID = @OrderID)
    SET @AppointmentID = (SELECT AppoinmentID FROM [Appointment] WHERE OrderID = @OrderID)
    SET @PurchaseOrderID = (SELECT PurchaseOrderID FROM [PurchaseOrder] WHERE OrderID = @OrderID)
END

Twitter Bootstrap Use collapse.js on table cells [Almost Done]

I'm not sure you have gotten past this yet, but I had to work on something very similar today and I got your fiddle working like you are asking, basically what I did was make another table row under it, and then used the accordion control. I tried using just collapse but could not get it working and saw an example somewhere on SO that used accordion.

Here's your updated fiddle: http://jsfiddle.net/whytheday/2Dj7Y/11/

Since I need to post code here is what each collapsible "section" should look like ->

<tr data-toggle="collapse" data-target="#demo1" class="accordion-toggle">
    <td>1</td>
    <td>05 May 2013</td>
    <td>Credit Account</td>
    <td class="text-success">$150.00</td>
    <td class="text-error"></td>
    <td class="text-success">$150.00</td>
</tr>

<tr>
    <td colspan="6" class="hiddenRow">
        <div class="accordion-body collapse" id="demo1">Demo1</div>
    </td>
</tr>

You have not accepted the license agreements of the following SDK components

Maybe I'm late, but this helped me accept SDK licenses for OSX,

If you have android SDK tools installed, run the following command

~/Library/Android/sdk/tools/bin/sdkmanager --licenses

Accept all licenses by pressing y

Voila! You have accepted SDK licenses and are good to go..

"static const" vs "#define" vs "enum"

Another drawback of const in C is that you can't use the value in initializing another const.

static int const NUMBER_OF_FINGERS_PER_HAND = 5;
static int const NUMBER_OF_HANDS = 2;

// initializer element is not constant, this does not work.
static int const NUMBER_OF_FINGERS = NUMBER_OF_FINGERS_PER_HAND 
                                     * NUMBER_OF_HANDS;

Even this does not work with a const since the compiler does not see it as a constant:

static uint8_t const ARRAY_SIZE = 16;
static int8_t const lookup_table[ARRAY_SIZE] = {
    1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; // ARRAY_SIZE not a constant!

I'd be happy to use typed const in these cases, otherwise...

Getting the source HTML of the current page from chrome extension

Here is my solution:

chrome.runtime.onMessage.addListener(function(request, sender) {
        if (request.action == "getSource") {
            this.pageSource = request.source;
            var title = this.pageSource.match(/<title[^>]*>([^<]+)<\/title>/)[1];
            alert(title)
        }
    });

    chrome.tabs.query({ active: true, currentWindow: true }, tabs => {
        chrome.tabs.executeScript(
            tabs[0].id,
            { code: 'var s = document.documentElement.outerHTML; chrome.runtime.sendMessage({action: "getSource", source: s});' }
        );
    });

HQL "is null" And "!= null" on an Oracle column

If you do want to use null values with '=' or '<>' operators you may find the

answer from @egallardo hier

very useful.

Short example for '=': The expression

WHERE t.field = :param

you refactor like this

WHERE ((:param is null and t.field is null) or t.field = :param)

Now you can set the parameter param either to some non-null value or to null:

query.setParameter("param", "Hello World"); // Works
query.setParameter("param", null);          // Works also

Split string and get first value only

Actually, there is a better way to do it than split:

public string GetFirstFromSplit(string input, char delimiter)
{
    var i = input.IndexOf(delimiter);

    return i == -1 ? input : input.Substring(0, i);
}

And as extension methods:

public static string FirstFromSplit(this string source, char delimiter)
{
    var i = source.IndexOf(delimiter);

    return i == -1 ? source : source.Substring(0, i);
}

public static string FirstFromSplit(this string source, string delimiter)
{
    var i = source.IndexOf(delimiter);

    return i == -1 ? source : source.Substring(0, i);
}

Usage:

string result = "hi, hello, sup".FirstFromSplit(',');
Console.WriteLine(result); // "hi"

How to handle anchor hash linking in AngularJS

In my mind @slugslog had it, but I would change one thing. I would use replace instead so you don't have to set it back.

$scope.scrollTo = function(id) {
    var old = $location.hash();
    $location.hash(id).replace();
    $anchorScroll();
};

Docs Search for "Replace method"

How to get the size of a file in MB (Megabytes)?

Use the length() method of the File class to return the size of the file in bytes.

// Get file from file name
File file = new File("U:\intranet_root\intranet\R1112B2.zip");

// Get length of file in bytes
long fileSizeInBytes = file.length();
// Convert the bytes to Kilobytes (1 KB = 1024 Bytes)
long fileSizeInKB = fileSizeInBytes / 1024;
// Convert the KB to MegaBytes (1 MB = 1024 KBytes)
long fileSizeInMB = fileSizeInKB / 1024;

if (fileSizeInMB > 27) {
  ...
}

You could combine the conversion into one step, but I've tried to fully illustrate the process.

java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient

I did below modifications and I am able to start the Hive Shell without any errors:

1. ~/.bashrc

Inside bashrc file add the below environment variables at End Of File : sudo gedit ~/.bashrc

#Java Home directory configuration
export JAVA_HOME="/usr/lib/jvm/java-9-oracle"
export PATH="$PATH:$JAVA_HOME/bin"

# Hadoop home directory configuration
export HADOOP_HOME=/usr/local/hadoop
export PATH=$PATH:$HADOOP_HOME/bin
export PATH=$PATH:$HADOOP_HOME/sbin

export HIVE_HOME=/usr/lib/hive
export PATH=$PATH:$HIVE_HOME/bin

2. hive-site.xml

You have to create this file(hive-site.xml) in conf directory of Hive and add the below details

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>

<property>
  <name>javax.jdo.option.ConnectionURL</name>
  <value>jdbc:mysql://localhost/metastore?createDatabaseIfNotExist=true</value>
</property>


<property>
  <name>javax.jdo.option.ConnectionDriverName</name>
  <value>com.mysql.jdbc.Driver</value>
</property>

<property>
  <name>javax.jdo.option.ConnectionUserName</name>
  <value>root</value>
</property>

<property>
  <name>javax.jdo.option.ConnectionPassword</name>
  <value>root</value>
</property>

<property>
  <name>datanucleus.autoCreateSchema</name>
  <value>true</value>
</property>

<property>
  <name>datanucleus.fixedDatastore</name>
  <value>true</value>
</property>

<property>
 <name>datanucleus.autoCreateTables</name>
 <value>True</value>
 </property>

</configuration>

3. You also need to put the jar file(mysql-connector-java-5.1.28.jar) in the lib directory of Hive

4. Below installations required on your Ubuntu to Start the Hive Shell:

  1. MySql
  2. Hadoop
  3. Hive
  4. Java

5. Execution Part:

  1. Start all services of Hadoop: start-all.sh

  2. Enter the jps command to check whether all Hadoop services are up and running: jps

  3. Enter the hive command to enter into hive shell: hive

How do I find the CPU and RAM usage using PowerShell?

I use the following PowerShell snippet to get CPU usage for local or remote systems:

Get-Counter -ComputerName localhost '\Process(*)\% Processor Time' | Select-Object -ExpandProperty countersamples | Select-Object -Property instancename, cookedvalue| Sort-Object -Property cookedvalue -Descending| Select-Object -First 20| ft InstanceName,@{L='CPU';E={($_.Cookedvalue/100).toString('P')}} -AutoSize

Same script but formatted with line continuation:

Get-Counter -ComputerName localhost '\Process(*)\% Processor Time' `
    | Select-Object -ExpandProperty countersamples `
    | Select-Object -Property instancename, cookedvalue `
    | Sort-Object -Property cookedvalue -Descending | Select-Object -First 20 `
    | ft InstanceName,@{L='CPU';E={($_.Cookedvalue/100).toString('P')}} -AutoSize

On a 4 core system it will return results that look like this:

InstanceName          CPU
------------          ---
_total                399.61 %
idle                  314.75 %
system                26.23 %
services              24.69 %
setpoint              15.43 %
dwm                   3.09 %
policy.client.invoker 3.09 %
imobilityservice      1.54 %
mcshield              1.54 %
hipsvc                1.54 %
svchost               1.54 %
stacsv64              1.54 %
wmiprvse              1.54 %
chrome                1.54 %
dbgsvc                1.54 %
sqlservr              0.00 %
wlidsvc               0.00 %
iastordatamgrsvc      0.00 %
intelmefwservice      0.00 %
lms                   0.00 %

The ComputerName argument will accept a list of servers, so with a bit of extra formatting you can generate a list of top processes on each server. Something like:

$psstats = Get-Counter -ComputerName utdev1,utdev2,utdev3 '\Process(*)\% Processor Time' -ErrorAction SilentlyContinue | Select-Object -ExpandProperty countersamples | %{New-Object PSObject -Property @{ComputerName=$_.Path.Split('\')[2];Process=$_.instancename;CPUPct=("{0,4:N0}%" -f $_.Cookedvalue);CookedValue=$_.CookedValue}} | ?{$_.CookedValue -gt 0}| Sort-Object @{E='ComputerName'; A=$true },@{E='CookedValue'; D=$true },@{E='Process'; A=$true }
$psstats | ft @{E={"{0,25}" -f $_.Process};L="ProcessName"},CPUPct -AutoSize -GroupBy ComputerName -HideTableHeaders

Which would result in a $psstats variable with the raw data and the following display:

   ComputerName: utdev1

           _total  397%
             idle  358%
             3mws   28%
           webcrs   10%


   ComputerName: utdev2

           _total  400%
             idle  248%
             cpfs   42%
             cpfs   36%
             cpfs   34%
          svchost   21%
         services   19%


   ComputerName: utdev3

           _total  200%
             idle  200%

Function pointer to member function

While this is based on the sterling answers elsewhere on this page, I had a use case which wasn't completely solved by them; for a vector of pointers to functions do the following:

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

class A{
public:
  typedef vector<int> (A::*AFunc)(int I1,int I2);
  vector<AFunc> FuncList;
  inline int Subtract(int I1,int I2){return I1-I2;};
  inline int Add(int I1,int I2){return I1+I2;};
  ...
  void Populate();
  void ExecuteAll();
};

void A::Populate(){
    FuncList.push_back(&A::Subtract);
    FuncList.push_back(&A::Add);
    ...
}

void A::ExecuteAll(){
  int In1=1,In2=2,Out=0;
  for(size_t FuncId=0;FuncId<FuncList.size();FuncId++){
    Out=(this->*FuncList[FuncId])(In1,In2);
    printf("Function %ld output %d\n",FuncId,Out);
  }
}

int main(){
  A Demo;
  Demo.Populate();
  Demo.ExecuteAll();
  return 0;
}

Something like this is useful if you are writing a command interpreter with indexed functions that need to be married up with parameter syntax and help tips etc. Possibly also useful in menus.

How to cast Object to boolean?

If the object is actually a Boolean instance, then just cast it:

boolean di = (Boolean) someObject;

The explicit cast will do the conversion to Boolean, and then there's the auto-unboxing to the primitive value. Or you can do that explicitly:

boolean di = ((Boolean) someObject).booleanValue();

If someObject doesn't refer to a Boolean value though, what do you want the code to do?

How can I get the ID of an element using jQuery?

id is a property of an html Element. However, when you write $("#something"), it returns a jQuery object that wraps the matching DOM element(s). To get the first matching DOM element back, call get(0)

$("#test").get(0)

On this native element, you can call id, or any other native DOM property or function.

$("#test").get(0).id

That's the reason why id isn't working in your code.

Alternatively, use jQuery's attr method as other answers suggest to get the id attribute of the first matching element.

$("#test").attr("id")

How can I create a "Please Wait, Loading..." animation using jQuery?

Most of the solutions I have seen either expects us to design a loading overlay, keep it hidden and then unhide it when required, or, show a gif or image etc.

I wanted to develop a robust plugin, where with a simply jQuery call I can display the loading screen and tear it down when the task is completed.

Below is the code. It depends on Font awesome and jQuery:

/**
 * Raj: Used basic sources from here: http://jsfiddle.net/eys3d/741/
 **/


(function($){
    // Retain count concept: http://stackoverflow.com/a/2420247/260665
    // Callers should make sure that for every invocation of loadingSpinner method there has to be an equivalent invocation of removeLoadingSpinner
    var retainCount = 0;

    // http://stackoverflow.com/a/13992290/260665 difference between $.fn.extend and $.extend
    $.extend({
        loadingSpinner: function() {
            // add the overlay with loading image to the page
            var over = '<div id="custom-loading-overlay">' +
                '<i id="custom-loading" class="fa fa-spinner fa-spin fa-3x fa-fw" style="font-size:48px; color: #470A68;"></i>'+
                '</div>';
            if (0===retainCount) {
                $(over).appendTo('body');
            }
            retainCount++;
        },
        removeLoadingSpinner: function() {
            retainCount--;
            if (retainCount<=0) {
                $('#custom-loading-overlay').remove();
                retainCount = 0;
            }
        }
    });
}(jQuery)); 

Just put the above in a js file and include it throughout the project.

CSS addition:

#custom-loading-overlay {
    position: absolute;
    left: 0;
    top: 0;
    bottom: 0;
    right: 0;
    background: #000;
    opacity: 0.8;
    filter: alpha(opacity=80);
}
#custom-loading {
    width: 50px;
    height: 57px;
    position: absolute;
    top: 50%;
    left: 50%;
    margin: -28px 0 0 -25px;
}

Invocation:

$.loadingSpinner();
$.removeLoadingSpinner();

Formatting a field using ToText in a Crystal Reports formula field

I think you are looking for ToText(CCur(@Price}/{ValuationReport.YestPrice}*100-100))

You can use CCur to convert numbers or string to Curency formats. CCur(number) or CCur(string)


I think this may be what you are looking for,

Replace (ToText(CCur({field})),"$" , "") that will give the parentheses for negative numbers

It is a little hacky, but I'm not sure CR is very kind in the ways of formatting

HTML / CSS table with GRIDLINES

For internal gridlines, use the tag: td For external gridlines, use the tag: table

How can I create an editable dropdownlist in HTML?

ComboBox with TextBox (For Pre-defined Values as well as User-defined Values.)

ComboBox with TextBox (Click Here)

How to check if an array value exists?

in_array() is fine if you're only checking but if you need to check that a value exists and return the associated key, array_search is a better option.

$data = [
    'hello',
    'world'
];

$key = array_search('world', $data);

if ($key) {
    echo 'Key is ' . $key;
} else {
    echo 'Key not found';
}

This will print "Key is 1"

Replacing from match to end-of-line

awk

awk '{gsub(/two.*/,"")}1' file

Ruby

ruby -ne 'print $_.gsub(/two.*/,"")' file

How to list records with date from the last 10 days?

http://www.postgresql.org/docs/current/static/functions-datetime.html shows operators you can use for working with dates and times (and intervals).

So you want

SELECT "date"
FROM "Table"
WHERE "date" > (CURRENT_DATE - INTERVAL '10 days');

The operators/functions above are documented in detail:

How do I sort an NSMutableArray with custom objects in it?

I've used sortUsingFunction:: in some of my projects:

int SortPlays(id a, id b, void* context)
{
    Play* p1 = a;
    Play* p2 = b;
    if (p1.score<p2.score) 
        return NSOrderedDescending;
    else if (p1.score>p2.score) 
        return NSOrderedAscending;
    return NSOrderedSame;
}

...
[validPlays sortUsingFunction:SortPlays context:nil];

How do I read / convert an InputStream into a String in Java?

Here's my Java 8 based solution, which uses the new Stream API to collect all lines from an InputStream:

public static String toString(InputStream inputStream) {
    BufferedReader reader = new BufferedReader(
        new InputStreamReader(inputStream));
    return reader.lines().collect(Collectors.joining(
        System.getProperty("line.separator")));
}

Delete files older than 15 days using PowerShell

Esperento57's script doesn't work in older PowerShell versions. This example does:

Get-ChildItem -Path "C:\temp" -Recurse -force -ErrorAction SilentlyContinue | where {($_.LastwriteTime -lt  (Get-Date).AddDays(-15) ) -and (! $_.PSIsContainer)} | select name| Remove-Item -Verbose -Force -Recurse -ErrorAction SilentlyContinue

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

Using a dictionary for unique names without a name list:

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

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

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

Output:

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

Extracting text from a PDF file using PDFMiner in python?

Here is a working example of extracting text from a PDF file using the current version of PDFMiner(September 2016)

from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
from io import StringIO

def convert_pdf_to_txt(path):
    rsrcmgr = PDFResourceManager()
    retstr = StringIO()
    codec = 'utf-8'
    laparams = LAParams()
    device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)
    fp = open(path, 'rb')
    interpreter = PDFPageInterpreter(rsrcmgr, device)
    password = ""
    maxpages = 0
    caching = True
    pagenos=set()

    for page in PDFPage.get_pages(fp, pagenos, maxpages=maxpages, password=password,caching=caching, check_extractable=True):
        interpreter.process_page(page)

    text = retstr.getvalue()

    fp.close()
    device.close()
    retstr.close()
    return text

PDFMiner's structure changed recently, so this should work for extracting text from the PDF files.

Edit : Still working as of the June 7th of 2018. Verified in Python Version 3.x

Edit: The solution works with Python 3.7 at October 3, 2019. I used the Python library pdfminer.six, released on November 2018.

Set custom HTML5 required field validation message

HTML:

<form id="myform">
    <input id="email" oninvalid="InvalidMsg(this);" name="email" oninput="InvalidMsg(this);"  type="email" required="required" />
    <input type="submit" />
</form>

JAVASCRIPT :

function InvalidMsg(textbox) {
    if (textbox.value == '') {
        textbox.setCustomValidity('Required email address');
    }
    else if (textbox.validity.typeMismatch){{
        textbox.setCustomValidity('please enter a valid email address');
    }
    else {
       textbox.setCustomValidity('');
    }
    return true;
}

Demo :

http://jsfiddle.net/patelriki13/Sqq8e/

How to read response headers in angularjs?

response.headers();

will give you all the headers (defaulat & customs). worked for me !!

enter image description here

enter image description here

Note . I tested on the same domain only. We may need to add Access-Control-Expose-Headers header on the server for cross domain.

GitHub "fatal: remote origin already exists"

TL;DR you should just update the existing remote:

$ git remote set-url origin [email protected]:ppreyer/first_app.git

Long version:

As the error message indicates, there is already a remote configured with the same name. So you can either add the new remote with a different name or update the existing one if you don't need it:

To add a new remote, called for example github instead of origin (which obviously already exists in your system), do the following:

$ git remote add github [email protected]:ppreyer/first_app.git

Remember though, everywhere in the tutorial you see "origin" you should replace it with "github". For example $ git push origin master should now be $ git push github master.

However, if you want to see what that origin which already exists is, you can do a $ git remote -v. If you think this is there by some error, you can update it like so:

$ git remote set-url origin [email protected]:ppreyer/first_app.git

Convert Java string to Time, NOT Date

You might want to take a look at this example:

public static void main(String[] args) {

    String myTime = "10:30:54";
    SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
    Date date = null;
    try {
        date = sdf.parse(myTime);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    String formattedTime = sdf.format(date);

    System.out.println(formattedTime);

}

Spring - applicationContext.xml cannot be opened because it does not exist

I fixed it by adding applicationContext.xml into jar/target/test-classes for Maven project. And use

        XmlBeanFactory bf = new XmlBeanFactory( new ClassPathResource(
                "/applicationContext.xml", getClass() ) )

instead of

        XmlBeanFactory bf = new XmlBeanFactory( new ClassPathResource(
                "/WEB-INF/applicationContext.xml", getClass() ) )

JavaScript Array Push key value

You may use:


To create array of objects:

var source = ['left', 'top'];
const result = source.map(arrValue => ({[arrValue]: 0}));

Demo:

_x000D_
_x000D_
var source = ['left', 'top'];_x000D_
_x000D_
const result = source.map(value => ({[value]: 0}));_x000D_
_x000D_
console.log(result);
_x000D_
_x000D_
_x000D_


Or if you wants to create a single object from values of arrays:

var source = ['left', 'top'];
const result = source.reduce((obj, arrValue) => (obj[arrValue] = 0, obj), {});

Demo:

_x000D_
_x000D_
var source = ['left', 'top'];_x000D_
_x000D_
const result = source.reduce((obj, arrValue) => (obj[arrValue] = 0, obj), {});_x000D_
_x000D_
console.log(result);
_x000D_
_x000D_
_x000D_

How to retrieve inserted id after inserting row in SQLite using Python?

All credits to @Martijn Pieters in the comments:

You can use the function last_insert_rowid():

The last_insert_rowid() function returns the ROWID of the last row insert from the database connection which invoked the function. The last_insert_rowid() SQL function is a wrapper around the sqlite3_last_insert_rowid() C/C++ interface function.

Multiple file-extensions searchPattern for System.IO.Directory.GetFiles

Instead of the EndsWith function, I would choose to use the Path.GetExtension() method instead. Here is the full example:

var filteredFiles = Directory.EnumerateFiles( path )
.Where(
    file => Path.GetExtension(file).Equals( ".aspx", StringComparison.OrdinalIgnoreCase ) ||
            Path.GetExtension(file).Equals( ".ascx", StringComparison.OrdinalIgnoreCase ) );

or:

var filteredFiles = Directory.EnumerateFiles(path)
.Where(
    file => string.Equals( Path.GetExtension(file), ".aspx", StringComparison.OrdinalIgnoreCase ) ||
            string.Equals( Path.GetExtension(file), ".ascx", StringComparison.OrdinalIgnoreCase ) );

(Use StringComparison.OrdinalIgnoreCase if you care about performance: MSDN string comparisons)

Hive External Table Skip First Row

Header rows in data are a perpetual headache in Hive. Short of modifying the Hive source, I believe you can't get away without an intermediate step. (Edit: This is no longer true, see update below)

Unfortunately, that answers you question. I'll throw in some ideas for the intermediate step for completeness.

You can get away without an extra step in your data load if you are willing to filter out the header row on every query that touches the table. Unfortunately this adds an extra set just about everywhere else. And you will have to get clever/messy when the header row violates your schema. If you go with this approach, you might consider writing a custom SerDe that makes this row easier to filter. Unfortunately, SerDe's cannot remove the row entirely (or that might form a possible solution), they must return something like null. I've never seen this approach taken in practice to deal with header rows since it makes reading a pain, and reading tends to be much more common than writing. It might have a place if you are dealing with one-of tables or if the header row is just one row among many malformed rows.

You could do this filtering once with variations on deleting that first row in data load. A WHERE clause in an INSERT statement would do it. You could use utilities like sed to get rid of it. I've seen both approaches taken. There are trade-offs between which approach you take and neither is the one true way to deal with header rows. Unfortunately, both these approaches take time and require temporary duplication of the data. If you absolutely need the header row for another application, the duplication would be permanent.

Update:

From Hive v0.13.0, you can use skip.header.line.count. You could also specify the same while creating the table. For example:

create external table testtable (name string, message string)
row format delimited 
fields terminated by '\t' 
lines terminated by '\n' 
location '/testtable'
tblproperties ("skip.header.line.count"="1");

ASP.NET postback with JavaScript

Per Phairoh: Use this in the Page/Component just in case the panel name changes

<script type="text/javascript">
     <!--
     //must be global to be called by ExternalInterface
         function JSFunction() {
             __doPostBack('<%= myUpdatePanel.ClientID  %>', '');
         }
     -->
     </script>

How do I prevent Eclipse from hanging on startup?

I tried all of the answers in this thread, and none of them worked for me -- not the snap files, not moving the projects, none of them.

What did work, oddly, was moving all projects and the .metadata folder somewhere else, starting Eclipse, closing it, and then moving them all back.

OAuth 2.0 Authorization Header

For those looking for an example of how to pass the OAuth2 authorization (access token) in the header (as opposed to using a request or body parameter), here is how it's done:

Authorization: Bearer 0b79bab50daca910b000d4f1a2b675d604257e42

How to delete from a table where ID is in a list of IDs?

delete from t
where id in (1, 4, 6, 7)

Eclipse EGit Checkout conflict with files: - EGit doesn't want to continue

I guess the best way to do this is like this :

  1. Store all your changes in a separate branch.
  2. Then do a hard reset on the local master.
  3. Then merge back your changes from the locally created branch
  4. Then commit and push your changes.

That how I resolve mine, whenever it happens.

Add/Delete table rows dynamically using JavaScript

Easy Javascript Add more Rows with delete functionality

Cheers !

<TABLE id="dataTable">
<tr><td>
               <INPUT TYPE=submit name=submit id=button class=btn_medium VALUE=\'Save\'  >
               <INPUT type="button" value="AddMore" onclick="addRow(\'dataTable\')" class="btn_medium"    /> 
</td></tr>

<TR>
<TD> 
                <input type="text" size="20" name="values[]"/> <br><small><font color="gray">Enter Title</font></small> 
</TD>
</TR>
</table>



<script>


function addRow(tableID) {

        var table = document.getElementById(tableID);

        var rowCount = table.rows.length;
        var row = table.insertRow(rowCount);

        var cell3 = row.insertCell(0);
       cell3.innerHTML = cell3.innerHTML +' <input type="text" size="20" name="values[]"/> <INPUT type="button"  class="btn_medium" value="Remove" onclick="this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode);" /><br><small><font color="gray">Enter Title</font></small>';
  //cell3.innerHTML = cell3.innerHTML +' <input type="text" size="20" name="values[]"/> <INPUT type="button"  class="btn_medium" value="Remove" onclick="this.parentNode.parentNode.innerHTML=\'\';" /><br><small><font color="gray">Enter Title</font></small>';       
}

</script>

Parsing JSON array with PHP foreach

You maybe wanted to do the following:

foreach($user->data as $mydata)

    {
         echo $mydata->name . "\n";
         foreach($mydata->values as $values)
         {
              echo $values->value . "\n";
         }
    }        

Passing html values into javascript functions

Give the textbox an id of "txtValue" and change the input button declaration to the following:

<input type="button" value="submit" onclick="verifyorder(document.getElementById('txtValue').value)" />

Check if file is already open

Hi I really hope this helps.

I tried all the options before and none really work on Windows. The only think that helped me accomplish this was trying to move the file. Event to the same place under an ATOMIC_MOVE. If the file is being written by another program or Java thread, this definitely will produce an Exception.

 try{

      Files.move(Paths.get(currentFile.getPath()), 
               Paths.get(currentFile.getPath()), StandardCopyOption.ATOMIC_MOVE);

      // DO YOUR STUFF HERE SINCE IT IS NOT BEING WRITTEN BY ANOTHER PROGRAM

 } catch (Exception e){

      // DO NOT WRITE THEN SINCE THE FILE IS BEING WRITTEN BY ANOTHER PROGRAM

 }

Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $

Also worth checking is if there are any errors in the return type of your interface methods. I could reproduce this issue by having an unintended return type like Call<Call<ResponseBody>>

PHP cURL custom headers

$subscription_key  ='';
    $host = '';    
    $request_headers = array(
                    "X-Mashape-Key:" . $subscription_key,
                    "X-Mashape-Host:" . $host
                );

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers);

    $season_data = curl_exec($ch);

    if (curl_errno($ch)) {
        print "Error: " . curl_error($ch);
        exit();
    }

    // Show me the result
    curl_close($ch);
    $json= json_decode($season_data, true);

How to replace all occurrences of a character in string?

For completeness, here's how to do it with std::regex.

#include <regex>
#include <string>

int main()
{
    const std::string s = "example string";
    const std::string r = std::regex_replace(s, std::regex("x"), "y");
}

ERROR: Google Maps API error: MissingKeyMapError

Yes. Now Google wants an API key to authenticate users to access their APIs`.

You can get the API key from the following link. Go through the link and you need to enter a project and so on. But it is easy. Hassle free.

https://developers.google.com/maps/documentation/javascript/get-api-key

Once you get the API key change the previous

<script src="https://maps.googleapis.com/maps/api/js"></script>

to

<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=your_api_key_here"></script>

Now your google map is in action. In case if you are wondering to get the longitude and latitude to input to Maps. Just pin the location you want and check the URL of the browser. You can see longitude and latitude values there. Just copy those values and paste it as follows.

new google.maps.LatLng(longitude ,latitude )

How can I escape square brackets in a LIKE clause?

Here is what I actually used:

like 'WC![R]S123456' ESCAPE '!'

ios simulator: how to close an app

You can also do it with the keyboard shortcut shown under the simulator menu bar (Hardware-> Home).

The shortcut is ?+?+H, but you need to hit H twice in a row for it to simulate the double press that shows the apps.

Shell Script — Get all files modified after <date>

This script will find files having a modification date of two minutes before and after the given date (and you can change the values in the conditions as per your requirement)

PATH_SRC="/home/celvas/Documents/Imp_Task/"
PATH_DST="/home/celvas/Downloads/zeeshan/"

cd $PATH_SRC
TODAY=$(date  -d "$(date +%F)" +%s)
TODAY_TIME=$(date -d "$(date +%T)" +%s)


for f in `ls`;
do
#       echo "File -> $f"
        MOD_DATE=$(stat -c %y "$f")
        MOD_DATE=${MOD_DATE% *}
#       echo MOD_DATE: $MOD_DATE
        MOD_DATE1=$(date -d "$MOD_DATE" +%s)
#       echo MOD_DATE: $MOD_DATE

DIFF_IN_DATE=$[ $MOD_DATE1 - $TODAY ]
DIFF_IN_DATE1=$[ $MOD_DATE1 - $TODAY_TIME ]
#echo DIFF: $DIFF_IN_DATE
#echo DIFF1: $DIFF_IN_DATE1
if [[ ($DIFF_IN_DATE -ge -120) && ($DIFF_IN_DATE1 -le 120) && (DIFF_IN_DATE1 -ge -120) ]]
then
echo File lies in Next Hour = $f
echo MOD_DATE: $MOD_DATE

#mv $PATH_SRC/$f  $PATH_DST/$f
fi
done

For example you want files having modification date before the given date only, you may change 120 to 0 in $DIFF_IN_DATE parameter discarding the conditions of $DIFF_IN_DATE1 parameter.

Similarly if you want files having modification date 1 hour before and after given date, just replace 120 by 3600 in if CONDITION.

How to use regex with find command?

find . -regextype sed -regex ".*/[a-f0-9\-]\{36\}\.jpg"

Note that you need to specify .*/ in the beginning because find matches the whole path.

Example:

susam@nifty:~/so$ find . -name "*.jpg"
./foo-111.jpg
./test/81397018-b84a-11e0-9d2a-001b77dc0bed.jpg
./81397018-b84a-11e0-9d2a-001b77dc0bed.jpg
susam@nifty:~/so$ 
susam@nifty:~/so$ find . -regextype sed -regex ".*/[a-f0-9\-]\{36\}\.jpg"
./test/81397018-b84a-11e0-9d2a-001b77dc0bed.jpg
./81397018-b84a-11e0-9d2a-001b77dc0bed.jpg

My version of find:

$ find --version
find (GNU findutils) 4.4.2
Copyright (C) 2007 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Written by Eric B. Decker, James Youngman, and Kevin Dalley.
Built using GNU gnulib version e5573b1bad88bfabcda181b9e0125fb0c52b7d3b
Features enabled: D_TYPE O_NOFOLLOW(enabled) LEAF_OPTIMISATION FTS() CBO(level=0) 
susam@nifty:~/so$ 
susam@nifty:~/so$ find . -regextype foo -regex ".*/[a-f0-9\-]\{36\}\.jpg"
find: Unknown regular expression type `foo'; valid types are `findutils-default', `awk', `egrep', `ed', `emacs', `gnu-awk', `grep', `posix-awk', `posix-basic', `posix-egrep', `posix-extended', `posix-minimal-basic', `sed'.

get next and previous day with PHP

Use

$time = time();

For previous day -

date("Y-m-d", mktime(0,0,0,date("n", $time),date("j",$time)- 1 ,date("Y", $time)));

For 2 days ago

date("Y-m-d", mktime(0,0,0,date("n", $time),date("j",$time) -2 ,date("Y", $time)));

For Next day -

date("Y-m-d", mktime(0,0,0,date("n", $time),date("j",$time)+ 1 ,date("Y", $time)));

For next 2 days

date("Y-m-d", mktime(0,0,0,date("n", $time),date("j",$time) +2 ,date("Y", $time)));

PHP Constants Containing Arrays?

Can even work with Associative Arrays.. for example in a class.

class Test {

    const 
        CAN = [
            "can bark", "can meow", "can fly"
        ],
        ANIMALS = [
            self::CAN[0] => "dog",
            self::CAN[1] => "cat",
            self::CAN[2] => "bird"
        ];

    static function noParameter() {
        return self::ANIMALS[self::CAN[0]];
    }

    static function withParameter($which, $animal) {
        return "who {$which}? a {$animal}.";
    }

}

echo Test::noParameter() . "s " . Test::CAN[0] . ".<br>";
echo Test::withParameter(
    array_keys(Test::ANIMALS)[2], Test::ANIMALS["can fly"]
);

// dogs can bark.
// who can fly? a bird.

Difference between iCalendar (.ics) and the vCalendar (.vcs)

You can try VCS to ICS file converter (Java, works with Windows, Mac, Linux etc.). It has the feature of parsing events and todos. You can convert the VCS generated by your Nokia phone, with bluetooth export or via nbuexplorer.

  • Complete support for UTF-8
  • Quoted-printable encoded strings
  • Completely open source code (GPLv3 and Apache 2.0)
  • Standard iCalendar v2.0 output
  • Encodes multiple files at once (only one event per file)
  • Compatible with Android, iOS, Mozilla Lightning/Sunbird, Google Calendar and others
  • Multiplatform

How can I set a custom baud rate on Linux?

You can set a custom baud rate using the stty command on Linux. For example, to set a custom baud rate of 567890 on your serial port /dev/ttyX0, use the command:

stty -F /dev/ttyX0 567890

How to remove "rows" with a NA value?

dat <- data.frame(x1 = c(1,2,3, NA, 5), x2 = c(100, NA, 300, 400, 500))

na.omit(dat)
  x1  x2
1  1 100
3  3 300
5  5 500

Why not use tables for layout in HTML?

I think nobody cares how a website was designed/implemented when it behaves great and it works fast.

I use both "table" and "div"/"span" tags in HTML markup.

Let me give you few arguments why I am choosing divs:

  1. for a table you have to write at least 3 tags (table, tr, td, thead, tbody), for a nice design, sometimes you have a lot of nested tables

  2. I like to have components on the page. I don't know how to explain exactly but will try. Suppose you need a logo and this have to be placed, just a small piece of it, over the next page content. Using tables you have to cut 2 images and put this into 2 different TDs. Using DIVs you can have a simple CSS to arange it as you want. Which solution do you like best?

  3. when more then 3 nested tables for doing something I am thinking to redesign it using DIVs

BUT I am still using tables for:

  1. tabular data

  2. content that is expanding self

  3. fast solutions (prototypes), because DIVs box model is different on each browser, because many generators are using tables, etc

Resizing a button

try this one out resizeable button

<button type="submit me" style="height: 25px; width: 100px">submit me</button>

How to check if a string starts with one of several prefixes?

Do you mean this:

if (newStr4.startsWith("Mon") || newStr4.startsWith("Tues") || ...)

Or you could use regular expression:

if (newStr4.matches("(Mon|Tues|Wed|Thurs|Fri).*"))

T-SQL substring - separating first and last name

Assuming the FirstName is all of the characters up to the first space:

SELECT
  SUBSTRING(username, 1, CHARINDEX(' ', username) - 1) AS FirstName,
  SUBSTRING(username, CHARINDEX(' ', username) + 1, LEN(username)) AS LastName
FROM
  whereever

how to implement Pagination in reactJs

A ReactJS dumb component to render pagination. You can also use this Library:

https://www.npmjs.com/package/react-js-pagination

Some Examples are Here:

http://vayser.github.io/react-js-pagination/

OR

You can also Use this https://codepen.io/PiotrBerebecki/pen/pEYPbY

MySQL Calculate Percentage

try this

   SELECT group_name, employees, surveys, COUNT( surveys ) AS test1, 
        concat(round(( surveys/employees * 100 ),2),'%') AS percentage
    FROM a_test
    GROUP BY employees

DEMO HERE

CodeIgniter query: How to move a column value to another column in the same row and save the current time in the original column?

Yes, this is possible and I would like to provide a slight alternative to Rajeev's answer that does not pass a php-generated datetime formatted string to the query.

The important distinction about how to declare the values to be SET in the UPDATE query is that they must not be quoted as literal strings.

To prevent CodeIgniter from doing this "favor" automatically, use the set() method with a third parameter of false.

$userId = 444;
$this->db->set('Last', 'Current', false);
$this->db->set('Current', 'NOW()', false);
$this->db->where('Id', $userId);
// return $this->db->get_compiled_update('Login');  // uncomment to see the rendered query
$this->db->update('Login');
return $this->db->affected_rows();  // this is expected to return the integer: 1

The generated query (depending on your database adapter) would be like this:

UPDATE `Login` SET Last = Current, Current = NOW() WHERE `Id` = 444

Demonstrated proof that the query works: https://www.db-fiddle.com/f/vcc6PfMcYhDD87wZE5gBtw/0

In this case, Last and Current ARE MySQL Keywords, but they are not Reserved Keywords, so they don't need to be backtick-wrapped.

If your precise query needs to have properly quoted identifiers (table/column names), then there is always protectIdentifiers().

What does 'index 0 is out of bounds for axis 0 with size 0' mean?

In numpy, index and dimension numbering starts with 0. So axis 0 means the 1st dimension. Also in numpy a dimension can have length (size) 0. The simplest case is:

In [435]: x = np.zeros((0,), int)
In [436]: x
Out[436]: array([], dtype=int32)
In [437]: x[0]
...
IndexError: index 0 is out of bounds for axis 0 with size 0

I also get it if x = np.zeros((0,5), int), a 2d array with 0 rows, and 5 columns.

So someplace in your code you are creating an array with a size 0 first axis.

When asking about errors, it is expected that you tell us where the error occurs.

Also when debugging problems like this, the first thing you should do is print the shape (and maybe the dtype) of the suspected variables.

Applied to pandas

Resolving the error:

  1. Use a try-except block
  2. Verify the size of the array is not 0
    • if x.size != 0:

Format timedelta to string

I had a similar problem with the output of overtime calculation at work. The value should always show up in HH:MM, even when it is greater than one day and the value can get negative. I combined some of the shown solutions and maybe someone else find this solution useful. I realized that if the timedelta value is negative most of the shown solutions with the divmod method doesn't work out of the box:

def td2HHMMstr(td):
  '''Convert timedelta objects to a HH:MM string with (+/-) sign'''
  if td < datetime.timedelta(seconds=0):
    sign='-'
    td = -td
  else:
    sign = ''
  tdhours, rem = divmod(td.total_seconds(), 3600)
  tdminutes, rem = divmod(rem, 60)
  tdstr = '{}{:}:{:02d}'.format(sign, int(tdhours), int(tdminutes))
  return tdstr

timedelta to HH:MM string:

td2HHMMstr(datetime.timedelta(hours=1, minutes=45))
'1:54'

td2HHMMstr(datetime.timedelta(days=2, hours=3, minutes=2))
'51:02'

td2HHMMstr(datetime.timedelta(hours=-3, minutes=-2))
'-3:02'

td2HHMMstr(datetime.timedelta(days=-35, hours=-3, minutes=-2))
'-843:02'

What is the best (and safest) way to merge a Git branch into master?

I would first make the to-be-merged branch as clean as possible. Run your tests, make sure the state is as you want it. Clean up the new commits by git squash.

Besides KingCrunches answer, I suggest to use

git checkout master
git pull origin master
git merge --squash test
git commit
git push origin master

You might have made many commits in the other branch, which should only be one commit in the master branch. To keep the commit history as clean as possible, you might want to squash all your commits from the test branch into one commit in the master branch (see also: Git: To squash or not to squash?). Then you can also rewrite the commit message to something very expressive. Something that is easy to read and understand, without digging into the code.

edit: You might be interested in

So on GitHub, I end up doing the following for a feature branch mybranch:

Get the latest from origin

$ git checkout master
$ git pull origin master

Find the merge base hash:

$ git merge-base mybranch master
c193ea5e11f5699ae1f58b5b7029d1097395196f

$ git checkout mybranch
$ git rebase -i c193ea5e11f5699ae1f58b5b7029d1097395196f

Now make sure only the first is pick, the rest is s:

pick 00f1e76 Add first draft of the Pflichtenheft
s d1c84b6 Update to two class problem
s 7486cd8 Explain steps better

Next choose a very good commit message and push to GitHub. Make the pull request then.

After the merge of the pull request, you can delete it locally:

$ git branch -d mybranch

and on GitHub

$ git push origin :mybranch

Understanding `scale` in R

This is a late addition but I was looking for information on the scale function myself and though it might help somebody else as well.

To modify the response from Ricardo Saporta a little bit.
Scaling is not done using standard deviation, at least not in version 3.6.1 of R, I base this on "Becker, R. (2018). The new S language. CRC Press." and my own experimentation.

X.man.scaled <- X/sqrt(sum(X^2)/(length(X)-1))
X.aut.scaled <- scale(X, center = F)

The result of these rows are exactly the same, I show it without centering because of simplicity.

I would respond in a comment but did not have enough reputation.

What characters can be used for up/down triangle (arrow without stem) for display in HTML?

OPTION 1: UNICODE COLUMN SORT ARROWS

I found this one very handy for a single character column sorter. (Looks good upscaled).

&#x21D5; = ?

Unicode table column sort arrows

IMPORTANT NOTE (When using Unicode symbols)

Unicode support varies dependant on the symbol of choice, browser and the font family. If you find your chosen symbol does not work in some browsers then try using a different font-family. Microsoft recommends "Segoe UI Symbol" however it would be wise to include the font with your website as not many people have it on their computers.

Open this page in other browsers to see which symbols render with the default font.


Some more Unicode arrows.

You can copy them right off the page below or you can use the code.

Each row of arrows is numbered from left to right:

0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F

Simply insert the corresponding number/letter before the closing semi-colon as above.


&#x219;

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?


&#x21A;

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?


&#x21B;

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?


&#x21C;

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?


&#x21D;

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?


&#x21E;

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?


&#x21F;

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?


Additional HTML unicode symbols

A selected list of other helpful Unicode icons/symbols.

U+2302  ¦   HOUSE
U+2303  ^   UP ARROWHEAD
U+2304  ?   DOWN ARROWHEAD
U+2305  ?   PROJECTIVE
U+2306  ?   PERSPECTIVE
U+2307  ?   WAVY LINE
U+2315  ?   TELEPHONE RECORDER
U+2316  ?   POSITION INDICATOR
U+2317  ?   VIEWDATA SQUARE
U+2318  ?   PLACE OF INTEREST SIGN
U+231A  ?   WATCH
U+231B  ?   HOURGLASS
U+2326  ?   ERASE TO THE RIGHT
U+2327  ?   X IN A RECTANGLE BOX
U+2328  ?   KEYBOARD
U+2329  <   LEFT-POINTING ANGLE BRACKET
U+232A  >   RIGHT-POINTING ANGLE BRACKET
U+232B  ?   ERASE TO THE LEFT
U+23E9  ?   BLACK RIGHT-POINTING DOUBLE TRIANGLE
U+23EA  ?   BLACK LEFT-POINTING DOUBLE TRIANGLE
U+23EB  ?   BLACK UP-POINTING DOUBLE TRIANGLE
U+23EC  ?   BLACK DOWN-POINTING DOUBLE TRIANGLE
U+23ED  ?   BLACK RIGHT-POINTING DOUBLE TRIANGLE WITH VERTICAL BAR
U+23EE  ?   BLACK LEFT-POINTING DOUBLE TRIANGLE WITH VERTICAL BAR
U+23EF  ?   BLACK RIGHT-POINTING TRIANGLE WITH DOUBLE VERTICAL BAR
U+23F0  ?   ALARM CLOCK
U+23F1  ?   STOPWATCH
U+23F2  ?   TIMER CLOCK
U+23F3  ?   HOURGLASS WITH FLOWING SAND
U+2600  ?   BLACK SUN WITH RAYS
U+2601  ?   CLOUD
U+2602  ?   UMBRELLA
U+2603  ?   SNOWMAN
U+2604  ?   COMET
U+2605  ?   BLACK STAR
U+2606  ?   WHITE STAR
U+2607  ?   LIGHTNING
U+2608  ?   THUNDERSTORM
U+2609  ?   SUN
U+260A  ?   ASCENDING NODE
U+260B  ?   DESCENDING NODE
U+260C  ?   CONJUNCTION
U+260D  ?   OPPOSITION
U+260E  ?   BLACK TELEPHONE
U+260F  ?   WHITE TELEPHONE
U+2610  ?   BALLOT BOX
U+2611  ?   BALLOT BOX WITH CHECK
U+2612  ?   BALLOT BOX WITH X
U+2613  ?   SALTIRE
U+2614  ?   UMBRELLA WITH RAINDROPS
U+2615  ?   HOT BEVERAGE
U+2616  ?   WHITE SHOGI PIECE
U+2617  ?   BLACK SHOGI PIECE
U+2618  ?   SHAMROCK
U+2619  ?   REVERSED ROTATED FLORAL HEART BULLET
U+261A  ?   BLACK LEFT-POINTING INDEX
U+261B  ?   BLACK RIGHT-POINTING INDEX
U+261C  ?   WHITE LEFT POINTING INDEX
U+261D  ?   WHITE UP POINTING INDEX
U+261E  ?   WHITE RIGHT POINTING INDEX
U+261F  ?   WHITE DOWN POINTING INDEX
U+2620  ?   SKULL AND CROSSBONES
U+2621  ?   CAUTION SIGN
U+2622  ?   RADIOACTIVE SIGN
U+2623  ?   BIOHAZARD SIGN
U+262A  ?   STAR AND CRESCENT
U+262B  ?   FARSI SYMBOL
U+262C  ?   ADI SHAKTI
U+262D  ?   HAMMER AND SICKLE
U+262E  ?   PEACE SYMBOL
U+262F  ?   YIN YANG
U+2638  ?   WHEEL OF DHARMA
U+2639  ?   WHITE FROWNING FACE
U+263A  ?   WHITE SMILING FACE
U+263B  ?   BLACK SMILING FACE
U+263C  ¤   WHITE SUN WITH RAYS
U+263D  ?   FIRST QUARTER MOON
U+263E  ?   LAST QUARTER MOON
U+263F  ?   MERCURY
U+2640  ?   FEMALE SIGN
U+2641  ?   EARTH
U+2642  ?   MALE SIGN
U+2643  ?   JUPITER
U+2644  ?   SATURN
U+2645  ?   URANUS
U+2646  ?   NEPTUNE
U+2647  ?   PLUTO
U+2648  ?   ARIES
U+2649  ?   TAURUS
U+264A  ?   GEMINI
U+264B  ?   CANCER
U+264C  ?   LEO
U+264D  ?   VIRGO
U+264E  ?   LIBRA
U+264F  ?   SCORPIUS
U+2650  ?   SAGITTARIUS
U+2651  ?   CAPRICORN
U+2652  ?   AQUARIUS
U+2653  ?   PISCES
U+2654  ?   WHITE CHESS KING
U+2655  ?   WHITE CHESS QUEEN
U+2656  ?   WHITE CHESS ROOK
U+2657  ?   WHITE CHESS BISHOP
U+2658  ?   WHITE CHESS KNIGHT
U+2659  ?   WHITE CHESS PAWN
U+265A  ?   BLACK CHESS KING
U+265B  ?   BLACK CHESS QUEEN
U+265C  ?   BLACK CHESS ROOK
U+265D  ?   BLACK CHESS BISHOP
U+265E  ?   BLACK CHESS KNIGHT
U+265F  ?   BLACK CHESS PAWN
U+2660  ?   BLACK SPADE SUIT
U+2661  ?   WHITE HEART SUIT
U+2662  ?   WHITE DIAMOND SUIT
U+2663  ?   BLACK CLUB SUITE
U+2664  ?   WHITE SPADE SUIT
U+2665  ?   BLACK HEART SUIT
U+2666  ?   BLACK DIAMOND SUIT
U+2667  ?   WHITE CLUB SUITE
U+2668  ?   HOT SPRINGS
U+2669  ?   QUARTER NOTE
U+266A  ?   EIGHTH NOTE
U+266B  ?   BEAMED EIGHTH NOTES
U+266C  ?   BEAMED SIXTEENTH NOTES
U+266D  ?   MUSIC FLAT SIGN
U+266E  ?   MUSIC NATURAL SIGN
U+266F  ?   MUSIC SHARP SIGN
U+267A  ?   RECYCLING SYMBOL FOR GENERIC MATERIALS
U+267B  ?   BLACK UNIVERSAL RECYCLING SYMBOL
U+267C  ?   RECYCLED PAPER SYMBOL
U+267D  ?   PARTIALLY-RECYCLED PAPER SYMBOL
U+267E  ?   PERMANENT PAPER SIGN
U+267F  ?   WHEELCHAIR SYMBOL
U+2680  ?   DIE FACE-1
U+2681  ?   DIE FACE-2
U+2682  ?   DIE FACE-3
U+2683  ?   DIE FACE-4
U+2684  ?   DIE FACE-5
U+2685  ?   DIE FACE-6
U+2686  ?   WHITE CIRCLE WITH DOT RIGHT
U+2687  ?   WHITE CIRCLE WITH TWO DOTS
U+2688  ?   BLACK CIRCLE WITH WHITE DOT RIGHT
U+2689  ?   BLACK CIRCLE WITH TWO WHITE DOTS
U+268A  ?   MONOGRAM FOR YANG
U+268B  ?   MONOGRAM FOR YIN
U+268C  ?   DIGRAM FOR GREATER YANG
U+268D  ?   DIGRAM FOR LESSER YIN
U+268E  ?   DIGRAM FOR LESSER YANG
U+268F  ?   DIGRAM FOR GREATER YIN
U+2690  ?   WHITE FLAG
U+2691  ?   BLACK FLAG
U+2692  ?   HAMMER AND PICK
U+2693  ?   ANCHOR
U+2694  ?   CROSSED SWORDS
U+2695  ?   STAFF OF AESCULAPIUS
U+2696  ?   SCALES
U+2697  ?   ALEMBIC
U+2698  ?   FLOWER
U+2699  ?   GEAR
U+269A  ?   STAFF OF HERMES
U+269B  ?   ATOM SYMBOL
U+269C  ?   FLEUR-DE-LIS
U+269D  ?   OUTLINED WHITE STAR
U+269E  ?   THREE LINES CONVERGING RIGHT
U+269F  ?   THREE LINES CONVERGING LEFT
U+26A0  ?   WARNING SIGN
U+26A1  ?   HIGH VOLTAGE SIGN
U+26A2  ?   DOUBLED FEMALE SIGN
U+26A3  ?   DOUBLED MALE SIGN
U+26A4  ?   INTERLOCKED FEMALE AND MALE SIGN
U+26A5  ?   MALE AND FEMALE SIGN
U+26A6  ?   MALE WITH STROKE SIGN
U+26A7  ?   MALE WITH STROKE AND MALE AND FEMALE SIGN
U+26A8  ?   VERTICAL MALE WITH STROKE SIGN
U+26A9  ?   HORIZONTAL MALE WITH STROKE SIGN
U+26AA  ?   MEDIUM WHITE CIRCLE
U+26AB  ?   MEDIUM BLACK CIRCLE
U+26BD  ?   SOCCER BALL
U+26BE  ?   BASEBALL
U+26BF  ?   SQUARED KEY
U+26C0  ?   WHITE DRAUGHTSMAN
U+26C1  ?   WHITE DRAUGHTS KING
U+26C2  ?   BLACK DRAUGHTSMAN
U+26C3  ?   BLACK DRAUGHTS KING
U+26C4  ?   SNOWMAN WITHOUT SNOW
U+26C5  ?   SUN BEHIND CLOUD
U+26C6  ?   RAIN
U+26C7  ?   BLACK SNOWMAN
U+26C8  ?   THUNDER CLOUD AND RAIN
U+26C9  ?   TURNED WHITE SHOGI PIECE
U+26CA  ?   TURNED BLACK SHOGI PIECE
U+26CB  ?   WHITE DIAMOND IN SQUARE
U+26CC  ?   CROSSING LANES
U+26CD  ?   DISABLED CAR
U+26CE  ?   OPHIUCHUS
U+26CF  ?   PICK
U+26D0  ?   CAR SLIDING
U+26D1  ?   HELMET WITH WHITE CROSS
U+26D2  ?   CIRCLED CROSSING LANES
U+26D3  ?   CHAINS
U+26D4  ?   NO ENTRY
U+26D5  ?   ALTERNATE ONE-WAY LEFT WAY TRAFFIC
U+26D6  ?   BLACK TWO-WAY LEFT WAY TRAFFIC
U+26D7  ?   WHITE TWO-WAY LEFT WAY TRAFFIC
U+26D8  ?   BLACK LEFT LANE MERGE
U+26D9  ?   WHITE LEFT LANE MERGE
U+26DA  ?   DRIVE SLOW SIGN
U+26DB  ?   HEAVY WHITE DOWN-POINTING TRIANGLE
U+26DC  ?   LEFT CLOSED ENTRY
U+26DD  ?   SQUARED SALTIRE
U+26DE  ?   FALLING DIAGONAL IN WHITE CIRCLE IN BLACK SQUARE
U+26DF  ?   BLACK TRUCK
U+26E0  ?   RESTRICTED LEFT ENTRY-1
U+26E1  ?   RESTRICTED LEFT ENTRY-2
U+26E2  ?   ASTRONOMICAL SYMBOL FOR URANUS
U+26E3  ?   HEAVY CIRCLE WITH STROKE AND TWO DOTS ABOVE
U+26E4  ?   PENTAGRAM
U+26E5  ?   RIGHT-HANDED INTERLACED PENTAGRAM
U+26E6  ?   LEFT-HANDED INTERLACED PENTAGRAM
U+26E7  ?   INVERTED PENTAGRAM
U+26E8  ?   BLACK CROSS ON SHIELD
U+26E9  ?   SHINTO SHRINE
U+26EA  ?   CHURCH
U+26EB  ?   CASTLE
U+26EC  ?   HISTORIC SITE
U+26ED  ?   GEAR WITHOUT HUB
U+26EE  ?   GEAR WITH HANDLES
U+26EF  ?   MAP SYMBOL FOR LIGHTHOUSE
U+26F0  ?   MOUNTAIN
U+26F1  ?   UMBRELLA ON GROUND
U+26F2  ?   FOUNTAIN
U+26F3  ?   FLAG IN HOLE
U+26F4  ?   FERRY
U+26F5  ?   SAILBOAT
U+26F6  ?   SQUARE FOUR CORNERS
U+26F7  ?   SKIER
U+26F8  ?   ICE SKATE
U+26F9  ?   PERSON WITH BALL
U+26FA  ?   TENT
U+26FD  ?   FUEL PUMP
U+26FE  ?   CUP ON BLACK SQUARE
U+26FF  ?   WHITE FLAG WITH HORIZONTAL MIDDLE BLACK STRIPE
U+2701  ?   UPPER BLADE SCISSORS
U+2702  ?   BLACK SCISSORS
U+2703  ?   LOWER BLADE SCISSORS
U+2704  ?   WHITE SCISSORS
U+2705  ?   WHITE HEAVY CHECK MARK
U+2706  ?   TELEPHONE LOCATION SIGN
U+2707  ?   TAPE DRIVE
U+2708  ?   AIRPLANE
U+2709  ?   ENVELOPE
U+270A  ?   RAISED FIST
U+270B  ?   RAISED HAND
U+270C  ?   VICTORY HAND
U+270D  ?   WRITING HAND
U+270E  ?   LOWER RIGHT PENCIL
U+270F  ?   PENCIL
U+2710  ?   UPPER RIGHT PENCIL
U+2711  ?   WHITE NIB
U+2712  ?   BLACK NIB
U+2713  ?   CHECK MARK
U+2714  ?   HEAVY CHECK MARK
U+2715  ?   MULTIPLICATION X
U+2716  ?   HEAVY MULTIPLICATION X
U+2717  ?   BALLOT X
U+2718  ?   HEAVY BALLOT X
U+2719  ?   OUTLINED GREEK CROSS
U+271A  ?   HEAVY GREEK CROSS
U+271B  ?   OPEN CENTRE CROSS
U+271C  ?   HEAVY OPEN CENTRE CROSS
U+271D  ?   LATIN CROSS
U+271E  ?   SHADOWED WHITE LATIN CROSS
U+271F  ?   OUTLINED LATIN CROSS
U+2720  ?   MALTESE CROSS
U+2721  ?   STAR OF DAVID
U+2722  ?   FOUR TEARDROP-SPOKED ASTERISK
U+2723  ?   FOUR BALLOON-SPOKED ASTERISK
U+2724  ?   HEAVY FOUR BALLOON-SPOKED ASTERISK
U+2725  ?   FOUR CLUB-SPOKED ASTERISK
U+2726  ?   BLACK FOUR POINTED STAR
U+2727  ?   WHITE FOUR POINTED STAR
U+2728  ?   SPARKLES
U+2729  ?   STRESS OUTLINED WHITE STAR
U+272A  ?   CIRCLED WHITE STAR
U+272B  ?   OPEN CENTRE BLACK STAR
U+272C  ?   BLACK CENTRE WHITE STAR
U+272D  ?   OUTLINED BLACK STAR
U+272E  ?   HEAVY OUTLINED BLACK STAR
U+272F  ?   PINWHEEL STAR
U+2730  ?   SHADOWED WHITE STAR
U+2731  ?   HEAVY ASTERISK
U+2732  ?   OPEN CENTRE ASTERISK
U+2733  ?   EIGHT SPOKED ASTERISK
U+2734  ?   EIGHT POINTED BLACK STAR
U+2735  ?   EIGHT POINTED PINWHEEL STAR
U+2736  ?   SIX POINTED BLACK STAR
U+2737  ?   EIGHT POINTED RECTILINEAR BLACK STAR
U+2738  ?   HEAVY EIGHT POINTED RECTILINEAR BLACK STAR
U+2739  ?   TWELVE POINTED BLACK STAR
U+273A  ?   SIXTEEN POINTED ASTERISK
U+273B  ?   TEARDROP-SPOKED ASTERISK
U+273C  ?   OPEN CENTRE TEARDROP-SPOKED ASTERISK
U+273D  ?   HEAVY TEARDROP-SPOKED ASTERISK
U+273E  ?   SIX PETALLED BLACK AND WHITE FLORETTE
U+273F  ?   BLACK FLORETTE
U+2740  ?   WHITE FLORETTE
U+2741  ?   EIGHT PETALLED OUTLINED BLACK FLORETTE
U+2742  ?   CIRCLED OPEN CENTRE EIGHT POINTED STAR
U+2743  ?   HEAVY TEARDROP-SPOKED PINWHEEL ASTERISK
U+2744  ?   SNOWFLAKE
U+2745  ?   TIGHT TRIFOLIATE SNOWFLAKE
U+2746  ?   HEAVY CHEVRON SNOWFLAKE
U+2747  ?   SPARKLE
U+2748  ?   HEAVY SPARKLE
U+2749  ?   BALLOON-SPOKED ASTERISK
U+274A  ?   EIGHT TEARDROP-SPOKED PROPELLER ASTERISK
U+274B  ?   HEAVY EIGHT TEARDROP-SPOKED PROPELLER ASTERISK
U+274C  ?   CROSS MARK
U+274D  ?   SHADOWED WHITE CIRCLE
U+274E  ?   NEGATIVE SQUARED CROSS MARK
U+2753  ?   BLACK QUESTION MARK ORNAMENT
U+2754  ?   WHITE QUESTION MARK ORNAMENT
U+2755  ?   WHITE EXCLAMATION MARK ORNAMENT
U+2756  ?   BLACK DIAMOND MINUS WHITE X
U+2757  ?   HEAVY EXCLAMATION MARK SYMBOL
U+275B  ?   HEAVY SINGLE TURNED COMMA QUOTATION MARK ORNAMENT
U+275C  ?   HEAVY SINGLE COMMA QUOTATION MARK ORNAMENT
U+275D  ?   HEAVY DOUBLE TURNED COMMA QUOTATION MARK ORNAMENT
U+275E  ?   HEAVY DOUBLE COMMA QUOTATION MARK ORNAMENT
U+275F  ?   HEAVY LOW SINGLE COMMA QUOTATION MARK ORNAMENT
U+2760  ?   HEAVY LOW DOUBLE COMMA QUOTATION MARK ORNAMENT
U+2761  ?   CURVED STEM PARAGRAPH SIGN ORNAMENT
U+2762  ?   HEAVY EXCLAMATION MARK ORNAMENT
U+2763  ?   HEAVY HEART EXCLAMATION MARK ORNAMENT
U+2764  ?   HEAVY BLACK HEART
U+2765  ?   ROTATED HEAVY BLACK HEART BULLET
U+2766  ?   FLORAL HEART
U+2767  ?   ROTATED FLORAL HEART BULLET
U+276C  ?   MEDIUM LEFT-POINTING ANGLE BRACKET ORNAMENT
U+276D  ?   MEDIUM RIGHT-POINTING ANGLE BRACKET ORNAMENT
U+276E  ?   HEAVY LEFT-POINTING ANGLE QUOTATION MARK ORNAMENT
U+276F  ?   HEAVY RIGHT-POINTING ANGLE QUOTATION MARK ORNAMENT
U+2770  ?   HEAVY LEFT-POINTING ANGLE BRACKET ORNAMENT
U+2771  ?   HEAVY RIGHT-POINTING ANGLE BRACKET ORNAMENT
U+2794  ?   HEAVY WIDE-HEADED RIGHTWARDS ARROW
U+2795  ?   HEAVY PLUS SIGN
U+2796  ?   HEAVY MINUS SIGN
U+2797  ?   HEAVY DIVISION SIGN
U+2798  ?   HEAVY SOUTH EAST ARROW
U+2799  ?   HEAVY RIGHTWARDS ARROW
U+279A  ?   HEAVY NORTH EAST ARROW
U+279B  ?   DRAFTING POINT RIGHTWARDS ARROW
U+279C  ?   HEAVY ROUND-TIPPED RIGHTWARDS ARROW
U+279D  ?   TRIANGLE-HEADED RIGHTWARDS ARROW
U+279E  ?   HEAVY TRIANGLE-HEADED RIGHTWARDS ARROW
U+279F  ?   DASHED TRIANGLE-HEADED RIGHTWARDS ARROW
U+27A0  ?   HEAVY DASHED TRIANGLE-HEADED RIGHTWARDS ARROW
U+27A1  ?   BLACK RIGHTWARDS ARROW
U+27A2  ?   THREE-D TOP-LIGHTED RIGHTWARDS ARROWHEAD
U+27A3  ?   THREE-D BOTTOM-LIGHTED RIGHTWARDS ARROWHEAD
U+27A4  ?   BLACK RIGHTWARDS ARROWHEAD
U+27A5  ?   HEAVY BLACK CURVED DOWNWARDS AND RIGHTWARDS ARROW
U+27A6  ?   HEAVY BLACK CURVED UPWARDS AND RIGHTWARDS ARROW
U+27A7  ?   SQUAT BLACK RIGHTWARDS ARROW
U+27A8  ?   HEAVY CONCAVE-POINTED BLACK RIGHTWARDS ARROW
U+27A9  ?   RIGHT-SHADED WHITE RIGHTWARDS ARROW
U+27AA  ?   LEFT-SHADED WHITE RIGHTWARDS ARROW
U+27AB  ?   BACK-TILTED SHADOWED WHITE RIGHTWARDS ARROW
U+27AC  ?   FRONT-TILTED SHADOWED WHITE RIGHTWARDS ARROW
U+27AD  ?   HEAVY LOWER RIGHT-SHADOWED WHITE RIGHTWARDS ARROW
U+27AE  ?   HEAVY UPPER RIGHT-SHADOWED WHITE RIGHTWARDS ARROW
U+27AF  ?   NOTCHED LOWER RIGHT-SHADOWED WHITE RIGHTWARDS ARROW
U+27B0  ?   CURLY LOOP
U+27B1  ?   NOTCHED UPPER RIGHT-SHADOWED WHITE RIGHTWARDS ARROW
U+27B2  ?   CIRCLED HEAVY WHITE RIGHTWARDS ARROW
U+27B3  ?   WHITE-FEATHERED RIGHTWARDS ARROW
U+27B4  ?   BLACK-FEATHERED SOUTH EAST ARROW
U+27B5  ?   BLACK-FEATHERED RIGHTWARDS ARROW
U+27B6  ?   BLACK-FEATHERED NORTH EAST ARROW
U+27B7  ?   HEAVY BLACK-FEATHERED SOUTH EAST ARROW
U+27B8  ?   HEAVY BLACK-FEATHERED RIGHTWARDS ARROW
U+27B9  ?   HEAVY BLACK-FEATHERED NORTH EAST ARROW
U+27BA  ?   TEARDROP-BARBED RIGHTWARDS ARROW
U+27BB  ?   HEAVY TEARDROP-SHANKED RIGHTWARDS ARROW
U+27BC  ?   WEDGE-TAILED RIGHTWARDS ARROW
U+27BD  ?   HEAVY WEDGE-TAILED RIGHTWARDS ARROW
U+27BE  ?   OPEN-OUTLINED RIGHTWARDS ARROW
U+27C0  ?   THREE DIMENSIONAL ANGLE
U+27E8  ?   MATHEMATICAL LEFT ANGLE BRACKET
U+27E9  ?   MATHEMATICAL RIGHT ANGLE BRACKET
U+27EA  ?   MATHEMATICAL LEFT DOUBLE ANGLE BRACKET
U+27EB  ?   MATHEMATICAL RIGHT DOUBLE ANGLE BRACKET
U+27F0  ?   UPWARDS QUADRUPLE ARROW
U+27F1  ?   DOWNWARDS QUADRUPLE ARROW
U+27F2  ?   ANTICLOCKWISE GAPPED CIRCLE ARROW
U+27F3  ?   CLOCKWISE GAPPED CIRCLE ARROW
U+27F4  ?   RIGHT ARROW WITH CIRCLED PLUS
U+27F5  ?   LONG LEFTWARDS ARROW
U+27F6  ?   LONG RIGHTWARDS ARROW
U+27F7  ?   LONG LEFT RIGHT ARROW
U+27F8  ?   LONG LEFTWARDS DOUBLE ARROW
U+27F9  ?   LONG RIGHTWARDS DOUBLE ARROW
U+27FA  ?   LONG LEFT RIGHT DOUBLE ARROW
U+27FB  ?   LONG LEFTWARDS ARROW FROM BAR
U+27FC  ?   LONG RIGHTWARDS ARROW FROM BAR
U+27FD  ?   LONG LEFTWARDS DOUBLE ARROW FROM BAR
U+27FE  ?   LONG RIGHTWARDS DOUBLE ARROW FROM BAR
U+27FF  ?   LONG RIGHTWARDS SQUIGGLE ARROW
U+2900  ?   RIGHTWARDS TWO-HEADED ARROW WITH VERTICAL STROKE
U+2901  ?   RIGHTWARDS TWO-HEADED ARROW WITH DOUBLE VERTICAL STROKE
U+2902  ?   LEFTWARDS DOUBLE ARROW WITH VERTICAL STROKE
U+2903  ?   RIGHTWARDS DOUBLE ARROW WITH VERTICAL STROKE
U+2904  ?   LEFT RIGHT DOUBLE ARROW WITH VERTICAL STROKE
U+2905  ?   RIGHTWARDS TWO-HEADED ARROW FROM BAR
U+2906  ?   LEFTWARDS DOUBLE ARROW FROM BAR
U+2907  ?   RIGHTWARDS DOUBLE ARROW FROM BAR
U+2908  ?   DOWNWARDS ARROW WITH HORIZONTAL STROKE
U+2909  ?   UPWARDS ARROW WITH HORIZONTAL STROKE
U+290A  ?   UPWARDS TRIPLE ARROW
U+290B  ?   DOWNWARDS TRIPLE ARROW
U+290C  ?   LEFTWARDS DOUBLE DASH ARROW
U+290D  ?   RIGHTWARDS DOUBLE DASH ARROW
U+290E  ?   LEFTWARDS TRIPLE DASH ARROW
U+290F  ?   RIGHTWARDS TRIPLE DASH ARROW
U+2910  ?   RIGHTWARDS TWO-HEADED TRIPLE DASH ARROW
U+2911  ?   RIGHTWARDS ARROW WITH DOTTED STEM
U+2912  ?   UPWARDS ARROW TO BAR
U+2913  ?   DOWNWARDS ARROW TO BAR
U+2914  ?   RIGHTWARDS ARROW WITH TAIL WITH VERTICAL STROKE
U+2915  ?   RIGHTWARDS ARROW WITH TAIL WITH DOUBLE VERTICAL STROKE
U+2916  ?   RIGHTWARDS TWO-HEADED ARROW WITH TAIL
U+2917  ?   RIGHTWARDS TWO-HEADED ARROW WITH TAIL WITH VERTICAL STROKE
U+2918  ?   RIGHTWARDS TWO-HEADED ARROW WITH TAIL WITH DOUBLE VERTICAL STROKE
U+2919  ?   LEFTWARDS ARROW-TAIL
U+291A  ?   RIGHTWARDS ARROW-TAIL
U+291B  ?   LEFTWARDS DOUBLE ARROW-TAIL
U+291C  ?   RIGHTWARDS DOUBLE ARROW-TAIL
U+291D  ?   LEFTWARDS ARROW TO BLACK DIAMOND
U+291E  ?   RIGHTWARDS ARROW TO BLACK DIAMOND
U+291F  ?   LEFTWARDS ARROW FROM BAR TO BLACK DIAMOND
U+2920  ?   RIGHTWARDS ARROW FROM BAR TO BLACK DIAMOND
U+2921  ?   NORTHWEST AND SOUTH EAST ARROW
U+2922  ?   NORTHEAST AND SOUTH WEST ARROW
U+2923  ?   NORTH WEST ARROW WITH HOOK
U+2924  ?   NORTH EAST ARROW WITH HOOK
U+2925  ?   SOUTH EAST ARROW WITH HOOK
U+2926  ?   SOUTH WEST ARROW WITH HOOK
U+2927  ?   NORTH WEST ARROW AND NORTH EAST ARROW
U+2928  ?   NORTH EAST ARROW AND SOUTH EAST ARROW
U+2929  ?   SOUTH EAST ARROW AND SOUTH WEST ARROW
U+292A  ?   SOUTH WEST ARROW AND NORTH WEST ARROW
U+292B  ?   RISING DIAGONAL CROSSING FALLING DIAGONAL
U+292C  ?   FALLING DIAGONAL CROSSING RISING DIAGONAL
U+292D  ?   SOUTH EAST ARROW CROSSING NORTH EAST ARROW
U+292E  ?   NORTH EAST ARROW CROSSING SOUTH EAST ARROW
U+292F  ?   FALLING DIAGONAL CROSSING NORTH EAST ARROW
U+2930  ?   RISING DIAGONAL CROSSING SOUTH EAST ARROW
U+2931  ?   NORTH EAST ARROW CROSSING NORTH WEST ARROW
U+2932  ?   NORTH WEST ARROW CROSSING NORTH EAST ARROW
U+2933  ?   WAVE ARROW POINTING DIRECTLY RIGHT
U+2934  ?   ARROW POINTING RIGHTWARDS THEN CURVING UPWARDS
U+2935  ?   ARROW POINTING RIGHTWARDS THEN CURVING DOWNWARDS
U+2936  ?   ARROW POINTING DOWNWARDS THEN CURVING LEFTWARDS
U+2937  ?   ARROW POINTING DOWNWARDS THEN CURVING RIGHTWARDS
U+2938  ?   RIGHT-SIDE ARC CLOCKWISE ARROW
U+2939  ?   LEFT-SIDE ARC ANTICLOCKWISE ARROW
U+293A  ?   TOP ARC ANTICLOCKWISE ARROW
U+293B  ?   BOTTOM ARC ANTICLOCKWISE ARROW
U+293C  ?   TOP ARC CLOCKWISE ARROW WITH MINUS
U+293D  ?   TOP ARC ANTICLOCKWISE ARROW WITH PLUS
U+293E  ?   LOWER RIGHT SEMICIRCULAR CLOCKWISE ARROW
U+293F  ?   LOWER LEFT SEMICIRCULAR ANTICLOCKWISE ARROW
U+2940  ?   ANTICLOCKWISE CLOSED CIRCLE ARROW
U+2941  ?   CLOCKWISE CLOSED CIRCLE ARROW
U+2942  ?   RIGHTWARDS ARROW ABOVE SHORT LEFTWARDS ARROW
U+2943  ?   LEFTWARDS ARROW ABOVE SHORT RIGHTWARDS ARROW
U+2944  ?   SHORT RIGHTWARDS ARROW ABOVE LEFTWARDS ARROW
U+2945  ?   RIGHTWARDS ARROW WITH PLUS BELOW
U+2946  ?   LEFTWARDS ARROW WITH PLUS BELOW
U+2962  ?   LEFTWARDS HARPOON WITH BARB UP ABOVE LEFTWARDS HARPOON WITH BARB DOWN
U+2963  ?   UPWARDS HARPOON WITH BARB LEFT BESIDE UPWARDS HARPOON WITH BARB RIGHT
U+2964  ?   RIGHTWARDS HARPOON WITH BARB UP ABOVE RIGHTWARDS HARPOON WITH BARB DOWN
U+2965  ?   DOWNWARDS HARPOON WITH BARB LEFT BESIDE DOWNWARDS HARPOON WITH BARB RIGHT
U+2966  ?   LEFTWARDS HARPOON WITH BARB UP ABOVE RIGHTWARDS HARPOON WITH BARB UP
U+2967  ?   LEFTWARDS HARPOON WITH BARB DOWN ABOVE RIGHTWARDS HARPOON WITH BARB DOWN
U+2968  ?   RIGHTWARDS HARPOON WITH BARB UP ABOVE LEFTWARDS HARPOON WITH BARB UP
U+2969  ?   RIGHTWARDS HARPOON WITH BARB DOWN ABOVE LEFTWARDS HARPOON WITH BARB DOWN
U+296A  ?   LEFTWARDS HARPOON WITH BARB UP ABOVE LONG DASH
U+296B  ?   LEFTWARDS HARPOON WITH BARB DOWN BELOW LONG DASH
U+296C  ?   RIGHTWARDS HARPOON WITH BARB UP ABOVE LONG DASH
U+296D  ?   RIGHTWARDS HARPOON WITH BARB DOWN BELOW LONG DASH
U+296E  ?   UPWARDS HARPOON WITH BARB LEFT BESIDE DOWNWARDS HARPOON WITH BARB RIGHT
U+296F  ?   DOWNWARDS HARPOON WITH BARB LEFT BESIDE UPWARDS HARPOON WITH BARB RIGHT
U+2989  ?   Z NOTATION LEFT BINDING BRACKET
U+298A  ?   Z NOTATION RIGHT BINDING BRACKET
U+2991  ?   LEFT ANGLE BRACKET WITH DOT
U+2992  ?   RIGHT ANGLE BRACKET WITH DOT
U+2993  ?   LEFT ARC LESS-THAN BRACKET
U+2994  ?   RIGHT ARC GREATER-THAN BRACKET
U+2995  ?   DOUBLE LEFT ARC GREATER-THAN BRACKET
U+2996  ?   DOUBLE RIGHT ARC LESS-THAN BRACKET
U+29A8  ?   MEASURED ANGLE WITH OPEN ARM ENDING IN ARROW POINTING UP AND RIGHT
U+29A9  ?   MEASURED ANGLE WITH OPEN ARM ENDING IN ARROW POINTING UP AND LEFT
U+29AA  ?   MEASURED ANGLE WITH OPEN ARM ENDING IN ARROW POINTING DOWN AND RIGHT
U+29AB  ?   MEASURED ANGLE WITH OPEN ARM ENDING IN ARROW POINTING DOWN AND LEFT
U+29AC  ?   MEASURED ANGLE WITH OPEN ARM ENDING IN ARROW POINTING RIGHT AND UP
U+29AD  ?   MEASURED ANGLE WITH OPEN ARM ENDING IN ARROW POINTING LEFT AND UP
U+29AE  ?   MEASURED ANGLE WITH OPEN ARM ENDING IN ARROW POINTING RIGHT AND DOWN
U+29AF  ?   MEASURED ANGLE WITH OPEN ARM ENDING IN ARROW POINTING LEFT AND DOWN
U+29BE  ?   CIRCLED WHITE BULLET
U+29BF  ?   CIRCLED BULLET
U+29C9  ?   TWO JOINED SQUARES
U+29CE  ?   RIGHT TRIANGLE ABOVE LEFT TRIANGLE
U+29CF  ?   LEFT TRIANGLE BESIDE VERTICAL BAR
U+29D0  ?   VERTICAL BAR BESIDE RIGHT TRIANGLE
U+29D1  ?   BOWTIE WITH LEFT HALF BLACK
U+29D2  ?   BOWTIE WITH RIGHT HALF BLACK
U+29D3  ?   BLACK BOWTIE
U+29D4  ?   TIMES WITH LEFT HALF BLACK
U+29D5  ?   TIMES WITH RIGHT HALF BLACK
U+29D6  ?   WHITE HOURGLASS
U+29D7  ?   BLACK HOURGLASS
U+29E8  ?   DOWN-POINTING TRIANGLE WITH LEFT HALF BLACK
U+29E9  ?   DOWN-POINTING TRIANGLE WITH RIGHT HALF BLACK
U+29EA  ?   BLACK DIAMOND WITH DOWN ARROW
U+29EB  ?   BLACK LOZENGE
U+29EC  ?   WHITE CIRCLE WITH DOWN ARROW
U+29ED  ?   BLACK CIRCLE WITH DOWN ARROW
U+29F4  ?   RULE-DELAYED
U+29FC  ?   LEFT-POINTING CURVED ANGLE BRACKET
U+29FD  ?   RIGHT-POINTING CURVED ANGLE BRACKET
U+29FE  ?   TINY
U+29FF  ?   MINY
U+2B00  ?   NORTH EAST WHITE ARROW
U+2B01  ?   NORTH WEST WHITE ARROW
U+2B02  ?   SOUTH EAST WHITE ARROW
U+2B03  ?   SOUTH WEST WHITE ARROW
U+2B04  ?   LEFT RIGHT WHITE ARROW
U+2B05  ?   LEFTWARDS BLACK ARROW
U+2B06  ?   UPWARDS BLACK ARROW
U+2B07  ?   DOWNWARDS BLACK ARROW
U+2B08  ?   NORTH EAST BLACK ARROW
U+2B09  ?   NORTH WEST BLACK ARROW
U+2B0A  ?   SOUTH EAST BLACK ARROW
U+2B0B  ?   SOUTHWEST BLACK ARROW
U+2B0C  ?   LEFT RIGHT BLACK ARROW
U+2B0D  ?   UP DOWN BLACK ARROW
U+2B0E  ?   RIGHTWARDS ARROW WITH TIP DOWNWARDS
U+2B0F  ?   RIGHTWARDS ARROW WITH TIP UPWARDS
U+2B10  ?   LEFTWARDS ARROW WITH TIP DOWNWARDS
U+2B11  ?   LEFTWARDS ARROW WITH TIP UPWARDS
U+2B12  ?   SQUARE WITH TOP HALF BLACK
U+2B13  ?   SQUARE WITH BOTTOM HALF BLACK
U+2B14  ?   SQUARE WITH UPPER RIGHT DIAGONAL HALF BLACK
U+2B15  ?   SQUARE WITH LOWER LEFT DIAGONAL HALF BLACK
U+2B16  ?   DIAMOND WITH LEFT HALF BLACK
U+2B17  ?   DIAMOND WITH RIGHT HALF BLACK
U+2B18  ?   DIAMOND WITH TOP HALF BLACK
U+2B19  ?   DIAMOND WITH BOTTOM HALF BLACK
U+2B1A  ?   DOTTED SQUARE
U+2B1B  ?   BLACK LARGE SQUARE
U+2B1C  ?   WHITE LARGE SQUARE
U+2B1D  ?   BLACK VERY SMALL SQUARE
U+2B1E  ?   WHITE VERY SMALL SQUARE
U+2B1F  ?   BLACK PENTAGON
U+2B20  ?   WHITE PENTAGON
U+2B21  ?   WHITE HEXAGON
U+2B22  ?   BLACK HEXAGON
U+2B23  ?   HORIZONTAL BLACK HEXAGON
U+2B24  ?   BLACK LARGE CIRCLE
U+2B25  ?   BLACK MEDIUM DIAMOND
U+2B26  ?   WHITE MEDIUM DIAMOND
U+2B27  ?   BLACK MEDIUM LOZENGE
U+2B28  ?   WHITE MEDIUM LOZENGE
U+2B29  ?   BLACK SMALL DIAMOND
U+2B2A  ?   BLACK SMALL LOZENGE
U+2B2B  ?   WHITE SMALL LOZENGE
U+2B30  ?   LEFT ARROW WITH SMALL CIRCLE
U+2B31  ?   THREE LEFTWARDS ARROWS
U+2B32  ?   LEFT ARROW WITH CIRCLED PLUS
U+2B33  ?   LONG LEFTWARDS SQUIGGLE ARROW
U+2B34  ?   LEFTWARDS TWO-HEADED ARROW WITH VERTICAL STROKE
U+2B35  ?   LEFTWARDS TWO-HEADED ARROW WITH DOUBLE VERTICAL STROKE
U+2B36  ?   LEFTWARDS TWO-HEADED ARROW FROM BAR
U+2B37  ?   LEFTWARDS TWO-HEADED TRIPLE DASH ARROW
U+2B38  ?   LEFTWARDS ARROW WITH DOTTED STEM
U+2B39  ?   LEFTWARDS ARROW WITH TAIL WITH VERTICAL STROKE
U+2B3A  ?   LEFTWARDS ARROW WITH TAIL WITH DOUBLE VERTICAL STROKE
U+2B3B  ?   LEFTWARDS TWO-HEADED ARROW WITH TAIL
U+2B3C  ?   LEFTWARDS TWO-HEADED ARROW WITH TAIL WITH VERTICAL STROKE
U+2B3D  ?   LEFTWARDS TWO-HEADED ARROW WITH TAIL WITH DOUBLE VERTICAL STROKE
U+2B3E  ?   LEFTWARDS ARROW THROUGH X
U+2B3F  ?   WAVE ARROW POINTING DIRECTLY LEFT
U+2B40  ?   EQUALS SIGN ABOVE LEFTWARDS ARROW
U+2B41  ?   REVERSE TILDE OPERATOR ABOVE LEFTWARDS ARROW
U+2B42  ?   LEFTWARDS ARROW ABOVE REVERSE ALMOST EQUAL TO
U+2B43  ?   RIGHTWARDS ARROW THROUGH GREATER-THAN
U+2B44  ?   RIGHTWARDS ARROW THROUGH SUPERSET
U+2B45  ?   LEFTWARDS QUADRUPLE ARROW
U+2B46  ?   RIGHTWARDS QUADRUPLE ARROW
U+2B47  ?   REVERSE TILDE OPERATOR ABOVE RIGHTWARDS ARROW
U+2B48  ?   RIGHTWARDS ARROW ABOVE REVERSE ALMOST EQUAL TO
U+2B49  ?   TILDE OPERATOR ABOVE LEFTWARDS ARROW
U+2B4A  ?   LEFTWARDS ARROW ABOVE ALMOST EQUAL TO
U+2B4B  ?   LEFTWARDS ARROW ABOVE REVERSE TILDE OPERATOR
U+2B4C  ?   RIGHTWARDS ARROW ABOVE REVERSE TILDE OPERATOR
U+2B50  ?   WHITE MEDIUM STAR
U+2B51  ?   BLACK SMALL STAR
U+2B52  ?   WHITE SMALL STAR
U+2B53  ?   BLACK RIGHT-POINTING PENTAGON
U+2B54  ?   WHITE RIGHT-POINTING PENTAGON
U+2B55  ?   HEAVY LARGE CIRCLE
U+2B56  ?   HEAVY OVAL WITH OVAL INSIDE
U+2B57  ?   HEAVY CIRCLE WITH CIRCLE INSIDE
U+2B58  ?   HEAVY CIRCLE
U+2B59  ?   HEAVY CIRCLED SALTIRE

OPTION 2: PURE CSS CHEVRONS

I recently made an article about creating chevrons efficiently using only CSS (No images required).

How to simply alter:

  • ROTATION
  • THICKNESS
  • COLOR
  • SIZE

CLICK FOR DEMO ON JSFIDDLE


enter image description here


CSS (Efficient with cross browser support)

_x000D_
_x000D_
.Chevron{_x000D_
    position:relative;_x000D_
    display:block;_x000D_
    height:50px;/*height should be double border*/_x000D_
}_x000D_
.Chevron:before,_x000D_
.Chevron:after{_x000D_
    position:absolute;_x000D_
    display:block;_x000D_
    content:"";_x000D_
    border:25px solid transparent;/*adjust size*/_x000D_
}_x000D_
/* Replace all text `top` below with left/right/bottom to rotate the chevron */_x000D_
.Chevron:before{_x000D_
    top:0;_x000D_
    border-top-color:#b00;/*Chevron Color*/_x000D_
}_x000D_
.Chevron:after{_x000D_
    top:-10px;/*adjust thickness*/_x000D_
    border-top-color:#fff;/*Match background colour*/_x000D_
}
_x000D_
<i class="Chevron"></i>
_x000D_
_x000D_
_x000D_


OPTION 3: CSS BASE64 IMAGE ICONS

UP/DOWN UP/DOWN

DOWN DOWN

UP UP

Using only a few lines of CSS we can encode our images into base64.


CLICK FOR DEMO ON JSFIDDLE


PROS

  • No need to include additional resources in the form of images or fonts.
  • Supports full alpha transparency.
  • Full cross-browser support.
  • Small images/icons can be stored in a database.

CONS

  • Updating/editing can become a hassle.
  • Not suitable for large images due to excessive code markup that's generated.

CSS

.sorting,
.sorting_asc,
.sorting_desc{
    padding:4px 21px 4px 4px;
    cursor:pointer;
}
.sorting{
    background:url(data:image/gif;base64,R0lGODlhCwALAJEAAAAAAP///xUVFf///yH5BAEAAAMALAAAAAALAAsAAAIUnC2nKLnT4or00PvyrQwrPzUZshQAOw==) no-repeat center right;
}
.sorting_asc{
    background:url(data:image/gif;base64,R0lGODlhCwALAJEAAAAAAP///xUVFf///yH5BAEAAAMALAAAAAALAAsAAAIRnC2nKLnT4or00Puy3rx7VQAAOw==) no-repeat center right;
}
.sorting_desc{
    background:url(data:image/gif;base64,R0lGODlhCwALAJEAAAAAAP///xUVFf///yH5BAEAAAMALAAAAAALAAsAAAIPnI+py+0/hJzz0IruwjsVADs=) no-repeat center right;
}

Get the index of the object inside an array, matching a condition

How can I get the index of the object tha match a condition (without iterate along the array)?

You cannot, something has to iterate through the array (at least once).

If the condition changes a lot, then you'll have to loop through and look at the objects therein to see if they match the condition. However, on a system with ES5 features (or if you install a shim), that iteration can be done fairly concisely:

var index;
yourArray.some(function(entry, i) {
    if (entry.prop2 == "yutu") {
        index = i;
        return true;
    }
});

That uses the new(ish) Array#some function, which loops through the entries in the array until the function you give it returns true. The function I've given it saves the index of the matching entry, then returns true to stop the iteration.

Or of course, just use a for loop. Your various iteration options are covered in this other answer.

But if you're always going to be using the same property for this lookup, and if the property values are unique, you can loop just once and create an object to map them:

var prop2map = {};
yourArray.forEach(function(entry) {
    prop2map[entry.prop2] = entry;
});

(Or, again, you could use a for loop or any of your other options.)

Then if you need to find the entry with prop2 = "yutu", you can do this:

var entry = prop2map["yutu"];

I call this "cross-indexing" the array. Naturally, if you remove or add entries (or change their prop2 values), you need to update your mapping object as well.

Is null reference possible?

If your intention was to find a way to represent null in an enumeration of singleton objects, then it's a bad idea to (de)reference null (it C++11, nullptr).

Why not declare static singleton object that represents NULL within the class as follows and add a cast-to-pointer operator that returns nullptr ?

Edit: Corrected several mistypes and added if-statement in main() to test for the cast-to-pointer operator actually working (which I forgot to.. my bad) - March 10 2015 -

// Error.h
class Error {
public:
  static Error& NOT_FOUND;
  static Error& UNKNOWN;
  static Error& NONE; // singleton object that represents null

public:
  static vector<shared_ptr<Error>> _instances;
  static Error& NewInstance(const string& name, bool isNull = false);

private:
  bool _isNull;
  Error(const string& name, bool isNull = false) : _name(name), _isNull(isNull) {};
  Error() {};
  Error(const Error& src) {};
  Error& operator=(const Error& src) {};

public:
  operator Error*() { return _isNull ? nullptr : this; }
};

// Error.cpp
vector<shared_ptr<Error>> Error::_instances;
Error& Error::NewInstance(const string& name, bool isNull = false)
{
  shared_ptr<Error> pNewInst(new Error(name, isNull)).
  Error::_instances.push_back(pNewInst);
  return *pNewInst.get();
}

Error& Error::NOT_FOUND = Error::NewInstance("NOT_FOUND");
//Error& Error::NOT_FOUND = Error::NewInstance("UNKNOWN"); Edit: fixed
//Error& Error::NOT_FOUND = Error::NewInstance("NONE", true); Edit: fixed
Error& Error::UNKNOWN = Error::NewInstance("UNKNOWN");
Error& Error::NONE = Error::NewInstance("NONE");

// Main.cpp
#include "Error.h"

Error& getError() {
  return Error::UNKNOWN;
}

// Edit: To see the overload of "Error*()" in Error.h actually working
Error& getErrorNone() {
  return Error::NONE;
}

int main(void) {
  if(getError() != Error::NONE) {
    return EXIT_FAILURE;
  }

  // Edit: To see the overload of "Error*()" in Error.h actually working
  if(getErrorNone() != nullptr) {
    return EXIT_FAILURE;
  }
}

AndroidStudio SDK directory does not exists

I had a ; in the environment variable name, put it out and it will works !

  • refollow the steps after the verification of the ANDROID_HOME
  • react init
  • => run you emulator
  • => run-android

Using tr to replace newline with space

Best guess is you are on windows and your line ending settings are set for windows. See this topic: How to change line-ending settings

or use:

tr '\r\n' ' '

How to trigger jQuery change event in code

for me $('#element').val('...').change() is the best way.

Populating spinner directly in the layout xml

In regards to the first comment: If you do this you will get an error(in Android Studio). This is in regards to it being out of the Android namespace. If you don't know how to fix this error, check the example out below. Hope this helps!

Example -Before :

<string-array name="roomSize">
    <item>Small(0-4)</item>
    <item>Medium(4-8)</item>
    <item>Large(9+)</item>
</string-array>

Example - After:

<string-array android:name="roomSize">
    <item>Small(0-4)</item>
    <item>Medium(4-8)</item>
    <item>Large(9+)</item>
</string-array>

Attaching a Sass/SCSS to HTML docs

You can not "attach" a SASS/SCSS file to an HTML document.

SASS/SCSS is a CSS preprocessor that runs on the server and compiles to CSS code that your browser understands.

There are client-side alternatives to SASS that can be compiled in the browser using javascript such as LESS CSS, though I advise you compile to CSS for production use.

It's as simple as adding 2 lines of code to your HTML file.

<link rel="stylesheet/less" type="text/css" href="styles.less" />
<script src="less.js" type="text/javascript"></script>

How to get the type of a variable in MATLAB?

Be careful when using the isa function. This will be true if your object is of the specified type or one of its subclasses. You have to use strcmp with the class function to test if the object is specifically that type and not a subclass.

Sharepoint: How do I filter a document library view to show the contents of a subfolder?

Use a Page Viewer webpart and switch from Web Page to Folder. You can the specify the folder you want to display in the Link.

Meaning of 'const' last in a function declaration of a class?

Blair's answer is on the mark.

However note that there is a mutable qualifier which may be added to a class's data members. Any member so marked can be modified in a const method without violating the const contract.

You might want to use this (for example) if you want an object to remember how many times a particular method is called, whilst not affecting the "logical" constness of that method.

Datatables on-the-fly resizing

might be late also like the other answer but I did this early this year and the solution I came up with is using css.

    $(window).bind('resize', function () {
        /*the line below was causing the page to keep loading.
        $('#tableData').dataTable().fnAdjustColumnSizing();
        Below is a workaround. The above should automatically work.*/
        $('#tableData').css('width', '100%');
    } );

Read whole ASCII file into C++ std::string

If you happen to use glibmm you can try Glib::file_get_contents.

#include <iostream>
#include <glibmm.h>

int main() {
    auto filename = "my-file.txt";
    try {
        std::string contents = Glib::file_get_contents(filename);
        std::cout << "File data:\n" << contents << std::endl;
    catch (const Glib::FileError& e) {
        std::cout << "Oops, an error occurred:\n" << e.what() << std::endl;
    }

    return 0;
}

Updating version numbers of modules in a multi-module Maven project

versions:update-child-modules sounds like what you're looking for. You could do versions:set as mentioned, but this is a light-weight way to update the parent version numbers. For the child modules, it's my opinion that you should remove the <version> definitions, since they will inherit the parent module's version number.

Selecting empty text input using jQuery

As mentioned in the top ranked post, the following works with the Sizzle engine.

$('input:text[value=""]');

In the comments, it was noted that removing the :text portion of the selector causes the selector to fail. I believe what's happening is that Sizzle actually relies on the browser's built in selector engine when possible. When :text is added to the selector, it becomes a non-standard CSS selector and thereby must needs be handled by Sizzle itself. This means that Sizzle checks the current value of the INPUT, instead of the "value" attribute specified in the source HTML.

So it's a clever way to check for empty text fields, but I think it relies on a behavior specific to the Sizzle engine (that of using the current value of the INPUT instead of the attribute defined in the source code). While Sizzle might return elements that match this selector, document.querySelectorAll will only return elements that have value="" in the HTML. Caveat emptor.

Converting a char to ASCII?

Uhm, what's wrong with this:

#include <iostream>

using namespace std;

int main(int, char **)
{
    char c = 'A';

    int x = c; // Look ma! No cast!

    cout << "The character '" << c << "' has an ASCII code of " << x << endl;

    return 0;
}

Encode html entities in javascript

You can use this.

var escapeChars = {
  '¢' : 'cent',
  '£' : 'pound',
  '¥' : 'yen',
  '€': 'euro',
  '©' :'copy',
  '®' : 'reg',
  '<' : 'lt',
  '>' : 'gt',
  '"' : 'quot',
  '&' : 'amp',
  '\'' : '#39'
};

var regexString = '[';
for(var key in escapeChars) {
  regexString += key;
}
regexString += ']';

var regex = new RegExp( regexString, 'g');

function escapeHTML(str) {
  return str.replace(regex, function(m) {
    return '&' + escapeChars[m] + ';';
  });
};

https://github.com/epeli/underscore.string/blob/master/escapeHTML.js

var htmlEntities = {
    nbsp: ' ',
    cent: '¢',
    pound: '£',
    yen: '¥',
    euro: '€',
    copy: '©',
    reg: '®',
    lt: '<',
    gt: '>',
    quot: '"',
    amp: '&',
    apos: '\''
};

function unescapeHTML(str) {
    return str.replace(/\&([^;]+);/g, function (entity, entityCode) {
        var match;

        if (entityCode in htmlEntities) {
            return htmlEntities[entityCode];
            /*eslint no-cond-assign: 0*/
        } else if (match = entityCode.match(/^#x([\da-fA-F]+)$/)) {
            return String.fromCharCode(parseInt(match[1], 16));
            /*eslint no-cond-assign: 0*/
        } else if (match = entityCode.match(/^#(\d+)$/)) {
            return String.fromCharCode(~~match[1]);
        } else {
            return entity;
        }
    });
};

Best way to run scheduled tasks

I've used Abidar successfully in an ASP.NET project (here's some background information).

The only problem with this method is that the tasks won't run if the ASP.NET web application is unloaded from memory (ie. due to low usage). One thing I tried is creating a task to hit the web application every 5 minutes, keeping it alive, but this didn't seem to work reliably, so now I'm using the Windows scheduler and basic console application to do this instead.

The ideal solution is creating a Windows service, though this might not be possible (ie. if you're using a shared hosting environment). It also makes things a little easier from a maintenance perspective to keep things within the web application.

How can I protect my .NET assemblies from decompilation?

No obsfuscator can protect your application, not even any one described here. See this link, it's an deobsfuscator which can deobsfuscate almost every obsfuscator out there.

https://github.com/0xd4d/de4dot

The best way which can help you (but remember that they are also not full prof) is to use mixed codes, code your important codes in unmanaged language and make a DLL like in C or C++ and then protect them either with Armageddon or Themida. Themida is not for every cracker, it's one of the best protector in the market, it can also protect your .NET software.

jQuery - Call ajax every 10 seconds

You could try setInterval() instead:

var i = setInterval(function(){
   //Call ajax here
},10000)

Couldn't process file resx due to its being in the Internet or Restricted zone or having the mark of the web on the file

None of the above worked.

  • The "Unblock" option is not present in the explorer properties.
  • Recreating file, adding folder (and resx file) to Tools->Options->Trust Settings does not work.

The solution was to copy the project locally (from the network drive).

Transparent background in JPEG image

JPEG can't support transparency because it uses RGB color space. If you want transparency use a format that supports alpha values. Example PNG is an image format that uses RGBA color space where (r = red, g = green, b = blue, a = alpha value). Alpha value is used as an opacity measure, 0% is fully transparent and 100% is completely opaque. pixel.

What is class="mb-0" in Bootstrap 4?

Bootstrap 4

It is used to create a bottom margin of 0 (margin-bottom:0). You can see more of the new spacing utility classes here: https://getbootstrap.com/docs/4.0/utilities/spacing/

Related: How do I use the Spacing Utility Classes on Bootstrap 4

How to append multiple values to a list in Python

letter = ["a", "b", "c", "d"]
letter.extend(["e", "f", "g", "h"])
letter.extend(("e", "f", "g", "h"))
print(letter)
... 
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'e', 'f', 'g', 'h']
    

ImageButton in Android

I think you already solved this problem, and as other answers suggested

android:background="@drawable/eye"

is available. But I prefer

android:src="@drawable/eye"
android:background="00000000" // transparent

and it works well too.(of course former code will set image as a background and the other will set image as a image) But according to your selected answer, I guess you meant 9-patch.

How to rollback just one step using rake db:migrate

  try {
        $result=DB::table('users')->whereExists(function ($Query){
            $Query->where('id','<','14162756');
            $Query->whereBetween('password',[14162756,48384486]);
            $Query->whereIn('id',[3,8,12]);
        });
    }catch (\Exception $error){
        Log::error($error);
        DB::rollBack(1);
        return redirect()->route('bye');
    }

Cannot change version of project facet Dynamic Web Module to 3.0?

updating maven worked for me

select project then press ALT+F5 then select project click ok

How to POST a JSON object to a JAX-RS service

I faced the same 415 http error when sending objects, serialized into JSON, via PUT/PUSH requests to my JAX-rs services, in other words my server was not able to de-serialize the objects from JSON. In my case, the server was able to serialize successfully the same objects in JSON when sending them into its responses.

As mentioned in the other responses I have correctly set the Accept and Content-Type headers to application/json, but it doesn't suffice.

Solution

I simply forgot a default constructor with no parameters for my DTO objects. Yes this is the same reasoning behind @Entity objects, you need a constructor with no parameters for the ORM to instantiate objects and populate the fields later.

Adding the constructor with no parameters to my DTO objects solved my issue. Here follows an example that resembles my code:

Wrong

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class NumberDTO {
    public NumberDTO(Number number) {
        this.number = number;
    }

    private Number number;

    public Number getNumber() {
        return number;
    }

    public void setNumber(Number string) {
        this.number = string;
    }
}

Right

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class NumberDTO {

    public NumberDTO() {
    }

    public NumberDTO(Number number) {
        this.number = number;
    }

    private Number number;

    public Number getNumber() {
        return number;
    }

    public void setNumber(Number string) {
        this.number = string;
    }
}

I lost hours, I hope this'll save yours ;-)

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

You can use requests and beautifulsoup libraries to read data on a website. Just install these two libraries and type the following code.

import requests
import bs4
help(requests)
help(bs4)

You will get all the information you need about the library.

Returning unique_ptr from functions

I would like to mention one case where you must use std::move() otherwise it will give an error. Case: If the return type of the function differs from the type of the local variable.

class Base { ... };
class Derived : public Base { ... };
...
std::unique_ptr<Base> Foo() {
     std::unique_ptr<Derived> derived(new Derived());
     return std::move(derived); //std::move() must
}

Reference: https://www.chromium.org/developers/smart-pointer-guidelines

What is String pool in Java?

I don't think it actually does much, it looks like it's just a cache for string literals. If you have multiple Strings who's values are the same, they'll all point to the same string literal in the string pool.

String s1 = "Arul"; //case 1 
String s2 = "Arul"; //case 2 

In case 1, literal s1 is created newly and kept in the pool. But in case 2, literal s2 refer the s1, it will not create new one instead.

if(s1 == s2) System.out.println("equal"); //Prints equal. 

String n1 = new String("Arul"); 
String n2 = new String("Arul"); 
if(n1 == n2) System.out.println("equal"); //No output.  

http://p2p.wrox.com/java-espanol/29312-string-pooling.html

Aligning text and image on UIButton with imageEdgeInsets and titleEdgeInsets

In interface Builder. Select the UIButton -> Attributes Inspector -> Edge=Title and modify the edge insets

Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

i had the same problem and it seems like i didn't initiate the button used with click listener, in other words id didn't te

Can someone explain mappedBy in JPA and Hibernate?

MappedBy signals hibernate that the key for the relationship is on the other side.

This means that although you link 2 tables together, only 1 of those tables has a foreign key constraint to the other one. MappedBy allows you to still link from the table not containing the constraint to the other table.

How to change the color of a SwitchCompat from AppCompat library

To have greater control of the track color (no API controlled alpha changes), I extended SwitchCompat and style the elements programmatically:

    public class CustomizedSwitch extends SwitchCompat {

    public CustomizedSwitch(Context context) {
        super(context);
        initialize(context);
    }

    public CustomizedSwitch(Context context, AttributeSet attrs) {
        super(context, attrs);
        initialize(context);
    }

    public CustomizedSwitch(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initialize(context);
    }

    public void initialize(Context context) {
        // DisplayMeasurementConverter is just a utility to convert from dp to px and vice versa
        DisplayMeasurementConverter displayMeasurementConverter = new DisplayMeasurementConverter(context);
        // Sets the width of the switch
        this.setSwitchMinWidth(displayMeasurementConverter.dpToPx((int) getResources().getDimension(R.dimen.tp_toggle_width)));
        // Setting up my colors
        int mediumGreen = ContextCompat.getColor(context, R.color.medium_green);
        int mediumGrey = ContextCompat.getColor(context, R.color.medium_grey);
        int alphaMediumGreen = Color.argb(127, Color.red(mediumGreen), Color.green(mediumGreen), Color.blue(mediumGreen));
        int alphaMediumGrey = Color.argb(127, Color.red(mediumGrey), Color.green(mediumGrey), Color.blue(mediumGrey));
        // Sets the tints for the thumb in different states
        DrawableCompat.setTintList(this.getThumbDrawable(), new ColorStateList(
                new int[][]{
                        new int[]{android.R.attr.state_checked},
                        new int[]{}
                },
                new int[]{
                        mediumGreen,
                        ContextCompat.getColor(getContext(), R.color.light_grey)
                }));
        // Sets the tints for the track in different states
        DrawableCompat.setTintList(this.getTrackDrawable(), new ColorStateList(
                new int[][]{
                        new int[]{android.R.attr.state_checked},
                        new int[]{}
                },
                new int[]{
                        alphaMediumGreen,
                        alphaMediumGrey
                }));
    }
}

Whenever I want to use the CustomizedSwitch, I just add one to my xml file.

Convert string to Python class object?

In terms of arbitrary code execution, or undesired user passed names, you could have a list of acceptable function/class names, and if the input matches one in the list, it is eval'd.

PS: I know....kinda late....but it's for anyone else who stumbles across this in the future.

How can I get Docker Linux container information from within the container itself?

Docker sets the hostname to the container ID by default, but users can override this with --hostname. Instead, inspect /proc:

$ more /proc/self/cgroup
14:name=systemd:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
13:pids:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
12:hugetlb:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
11:net_prio:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
10:perf_event:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
9:net_cls:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
8:freezer:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
7:devices:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
6:memory:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
5:blkio:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
4:cpuacct:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
3:cpu:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
2:cpuset:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
1:name=openrc:/docker

Here's a handy one-liner to extract the container ID:

$ grep "memory:/" < /proc/self/cgroup | sed 's|.*/||'
7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605

Converting string from snake_case to CamelCase in Ruby

Extend String to Add Camelize

In pure Ruby you could extend the string class using code lifted from Rails .camelize

class String
  def camelize(uppercase_first_letter = true)
    string = self
    if uppercase_first_letter
      string = string.sub(/^[a-z\d]*/) { |match| match.capitalize }
    else
      string = string.sub(/^(?:(?=\b|[A-Z_])|\w)/) { |match| match.downcase }
    end
    string.gsub(/(?:_|(\/))([a-z\d]*)/) { "#{$1}#{$2.capitalize}" }.gsub("/", "::")
  end
end

Merging two images in C#/.NET

basically i use this in one of our apps: we want to overlay a playicon over a frame of a video:

Image playbutton;
try
{
    playbutton = Image.FromFile(/*somekindofpath*/);
}
catch (Exception ex)
{
    return;
}

Image frame;
try
{
    frame = Image.FromFile(/*somekindofpath*/);
}
catch (Exception ex)
{
    return;
}

using (frame)
{
    using (var bitmap = new Bitmap(width, height))
    {
        using (var canvas = Graphics.FromImage(bitmap))
        {
            canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
            canvas.DrawImage(frame,
                             new Rectangle(0,
                                           0,
                                           width,
                                           height),
                             new Rectangle(0,
                                           0,
                                           frame.Width,
                                           frame.Height),
                             GraphicsUnit.Pixel);
            canvas.DrawImage(playbutton,
                             (bitmap.Width / 2) - (playbutton.Width / 2),
                             (bitmap.Height / 2) - (playbutton.Height / 2));
            canvas.Save();
        }
        try
        {
            bitmap.Save(/*somekindofpath*/,
                        System.Drawing.Imaging.ImageFormat.Jpeg);
        }
        catch (Exception ex) { }
    }
}

How do I fix a compilation error for unhandled exception on call to Thread.sleep()?

Thread.sleep can throw an InterruptedException which is a checked exception. All checked exceptions must either be caught and handled or else you must declare that your method can throw it. You need to do this whether or not the exception actually will be thrown. Not declaring a checked exception that your method can throw is a compile error.

You either need to catch it:

try {
    Thread.sleep(1000);
} catch (InterruptedException e) {
    e.printStackTrace();
    // handle the exception...        
    // For example consider calling Thread.currentThread().interrupt(); here.
}

Or declare that your method can throw an InterruptedException:

public static void main(String[]args) throws InterruptedException

Related

Warning: Permanently added the RSA host key for IP address

If you are accessing your repositories over the SSH protocol, you will receive a warning message each time your client connects to a new IP address for github.com. As long as the IP address from the warning is in the range of IP addresses , you shouldn't be concerned. Specifically, the new addresses that are being added this time are in the range from 192.30.252.0 to 192.30.255.255. The warning message looks like this:

Warning: Permanently added the RSA host key for IP address '$IP' to the list of 

https://github.com/blog/1606-ip-address-changes

PHP Pass by reference in foreach

I found this example also tricky. Why that in the 2nd loop at the last iteration nothing happens ($v stays 'two'), is that $v points to $a[3] (and vice versa), so it cannot assign value to itself, so it keeps the previous assigned value :)

What is getattr() exactly and how do I use it?

I have tried in Python2.7.17

Some of the fellow folks already answered. However I have tried to call getattr(obj, 'set_value') and this didn't execute the set_value method, So i changed to getattr(obj, 'set_value')() --> This helps to invoke the same.

Example Code:

Example 1:

    class GETATT_VERIFY():
       name = "siva"
       def __init__(self):
           print "Ok"
       def set_value(self):
           self.value = "myself"
           print "oooh"
    obj = GETATT_VERIFY()
    print getattr(GETATT_VERIFY, 'name')
    getattr(obj, 'set_value')()
    print obj.value