Programs & Examples On #Double click

A double-click is the act of pressing a computer mouse button twice quickly without moving the mouse.

C# Listbox Item Double Click Event

void listBox1_MouseDoubleClick(object sender, MouseEventArgs e)
{
    int index = this.listBox1.IndexFromPoint(e.Location);
    if (index != System.Windows.Forms.ListBox.NoMatches)
    {
        MessageBox.Show(index.ToString());
    }
}

This should work...check

How to prevent a double-click using jQuery?

just put this method in your forms then it will handle double-click or more clicks in once. once request send it will not allow sending again and again request.

<script type="text/javascript">
    $(document).ready(function(){
            $("form").submit(function() {
                $(this).submit(function() {
                    return false;
                });
                return true;
            }); 
    }); 
</script>

it will help you for sure.

c# datagridview doubleclick on row with FullRowSelect

This will work, make sure your control Event is assigned to this code, it has probably been lost, I also noticed that Double click will only work if the cell is not empty. Try double clicking on a cell with content, don't mess with the designer

 private void dgvReport_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
 {

   //do something


 }

Android: How to detect double-tap?

This is my solution, it uses default setOnItemClickListener(). I had the same task to implement. Soon I'll post example and custom class on my github. Brief explanation is given. I'm not sure if the time in milliseconds is right difference for the system (See ViewConfiguration.getDoubleTapTimeout() source) to decide between single and double tap.

Edit: See it here: https://github.com/NikolaDespotoski/DoubleTapListView or https://github.com/NikolaDespotoski/DoubleTapListViewHandler

Android Preventing Double Click On A Button

In kotlin

button.setOnClickListener { 
    it?.apply { isEnabled = false; postDelayed({ isEnabled = true }, 400) } //400 ms
    //do your work
}

How to create Windows EventLog source from command line?

If someone is interested, it is also possible to create an event source manually by adding some registry values.

Save the following lines as a .reg file, then import it to registry by double clicking it:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\eventlog\Application\YOUR_EVENT_SOURCE_NAME_GOES_HERE]
"EventMessageFile"="C:\\Windows\\Microsoft.NET\\Framework64\\v4.0.30319\\EventLogMessages.dll"
"TypesSupported"=dword:00000007

This creates an event source named YOUR_EVENT_SOURCE_NAME_GOES_HERE.

Replacing all non-alphanumeric characters with empty strings

I made this method for creating filenames:

public static String safeChar(String input)
{
    char[] allowed = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_".toCharArray();
    char[] charArray = input.toString().toCharArray();
    StringBuilder result = new StringBuilder();
    for (char c : charArray)
    {
        for (char a : allowed)
        {
            if(c==a) result.append(a);
        }
    }
    return result.toString();
}

How to use android emulator for testing bluetooth application?

You can't. The emulator does not support Bluetooth, as mentioned in the SDK's docs and several other places. Android emulator does not have bluetooth capabilities".

You can only use real devices.

Emulator Limitations

The functional limitations of the emulator include:

  • No support for placing or receiving actual phone calls. However, You can simulate phone calls (placed and received) through the emulator console
  • No support for USB
  • No support for device-attached headphones
  • No support for determining SD card insert/eject
  • No support for WiFi, Bluetooth, NFC

Refer to the documentation

try/catch blocks with async/await

Alternative Similar To Error Handling In Golang

Because async/await uses promises under the hood, you can write a little utility function like this:

export function catchEm(promise) {
  return promise.then(data => [null, data])
    .catch(err => [err]);
}

Then import it whenever you need to catch some errors, and wrap your async function which returns a promise with it.

import catchEm from 'utility';

async performAsyncWork() {
  const [err, data] = await catchEm(asyncFunction(arg1, arg2));
  if (err) {
    // handle errors
  } else {
    // use data
  }
}

Illegal pattern character 'T' when parsing a date string to java.util.Date

There are two answers above up-to-now and they are both long (and tl;dr too short IMHO), so I write summary from my experience starting to use new java.time library (applicable as noted in other answers to Java version 8+). ISO 8601 sets standard way to write dates: YYYY-MM-DD so the format of date-time is only as below (could be 0, 3, 6 or 9 digits for milliseconds) and no formatting string necessary:

import java.time.Instant;
public static void main(String[] args) {
    String date="2010-10-02T12:23:23Z";
    try {
        Instant myDate = Instant.parse(date);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

I did not need it, but as getting year is in code from the question, then:
it is trickier, cannot be done from Instant directly, can be done via Calendar in way of questions Get integer value of the current year in Java and Converting java.time to Calendar but IMHO as format is fixed substring is more simple to use:

myDate.toString().substring(0,4);

Why would $_FILES be empty when uploading files to PHP?

I had similar problem and the issue was in wrong value in htaccess as shamittomar mentioned.

Change php_value post_max_size 10MB to php_value post_max_size 10M

Why not use tables for layout in HTML?

Having had to work with a website that involved 6 layers of nested tables generated by some application, and having had it generate invalid HTML, it was in fact a 3 hour job to rectify it breaking for a minor change.

This is of course the edge case, but table based design is unmaintainable. If you use css, you separate the style out so when fixing the HTML you have less to worry about breaking.

Also, try this with JavaScript. Move a single table cell from one place to another place in another table. Rather complicated to perform where div/span would just work copy-paste-wise.

"Does my boss care"

If I were your boss. You would care. ;) If you value your life.

Can you style html form buttons with css?

You can directly create your own style in this way:

 input[type=button]
 { 
//Change the style as you like
 }

How to export a CSV to Excel using Powershell

I had some problem getting the other examples to work.

EPPlus and other libraries produces OpenDocument Xml format, which is not the same as you get when you save from Excel as xlsx.

macks example with open CSV and just re-saving didn't work, I never managed to get the ',' delimiter to be used correctly.

Ansgar Wiechers example has some slight error which I found the answer for in the commencts.

Anyway, this is a complete working example. Save this in a File CsvToExcel.ps1

param (
[Parameter(Mandatory=$true)][string]$inputfile,
[Parameter(Mandatory=$true)][string]$outputfile
)

$excel = New-Object -ComObject Excel.Application
$excel.Visible = $false

$wb = $excel.Workbooks.Add()
$ws = $wb.Sheets.Item(1)

$ws.Cells.NumberFormat = "@"

write-output "Opening $inputfile"

$i = 1
Import-Csv $inputfile | Foreach-Object { 
    $j = 1
    foreach ($prop in $_.PSObject.Properties)
    {
        if ($i -eq 1) {
            $ws.Cells.Item($i, $j) = $prop.Name
        } else {
            $ws.Cells.Item($i, $j) = $prop.Value
        }
        $j++
    }
    $i++
}

$wb.SaveAs($outputfile,51)
$wb.Close()
$excel.Quit()
write-output "Success"

Execute with:

.\CsvToExcel.ps1 -inputfile "C:\Temp\X\data.csv" -outputfile "C:\Temp\X\data.xlsx"

Converting HTML to Excel?

So long as Excel can open the file, the functionality to change the format of the opened file is built in.

To convert an .html file, open it using Excel (File - Open) and then save it as a .xlsx file from Excel (File - Save as).

To do it using VBA, the code would look like this:

Sub Open_HTML_Save_XLSX()

    Workbooks.Open Filename:="C:\Temp\Example.html"
    ActiveWorkbook.SaveAs Filename:= _
        "C:\Temp\Example.xlsx", FileFormat:= _
        xlOpenXMLWorkbook

End Sub

How to make Regular expression into non-greedy?

I believe it would be like this

takedata.match(/(\[.+\])/g);

the g at the end means global, so it doesn't stop at the first match.

How to flush output of print function?

How to flush output of Python print?

I suggest five ways of doing this:

  • In Python 3, call print(..., flush=True) (the flush argument is not available in Python 2's print function, and there is no analogue for the print statement).
  • Call file.flush() on the output file (we can wrap python 2's print function to do this), for example, sys.stdout
  • apply this to every print function call in the module with a partial function,
    print = partial(print, flush=True) applied to the module global.
  • apply this to the process with a flag (-u) passed to the interpreter command
  • apply this to every python process in your environment with PYTHONUNBUFFERED=TRUE (and unset the variable to undo this).

Python 3.3+

Using Python 3.3 or higher, you can just provide flush=True as a keyword argument to the print function:

print('foo', flush=True) 

Python 2 (or < 3.3)

They did not backport the flush argument to Python 2.7 So if you're using Python 2 (or less than 3.3), and want code that's compatible with both 2 and 3, may I suggest the following compatibility code. (Note the __future__ import must be at/very "near the top of your module"):

from __future__ import print_function
import sys

if sys.version_info[:2] < (3, 3):
    old_print = print
    def print(*args, **kwargs):
        flush = kwargs.pop('flush', False)
        old_print(*args, **kwargs)
        if flush:
            file = kwargs.get('file', sys.stdout)
            # Why might file=None? IDK, but it works for print(i, file=None)
            file.flush() if file is not None else sys.stdout.flush()

The above compatibility code will cover most uses, but for a much more thorough treatment, see the six module.

Alternatively, you can just call file.flush() after printing, for example, with the print statement in Python 2:

import sys
print 'delayed output'
sys.stdout.flush()

Changing the default in one module to flush=True

You can change the default for the print function by using functools.partial on the global scope of a module:

import functools
print = functools.partial(print, flush=True)

if you look at our new partial function, at least in Python 3:

>>> print = functools.partial(print, flush=True)
>>> print
functools.partial(<built-in function print>, flush=True)

We can see it works just like normal:

>>> print('foo')
foo

And we can actually override the new default:

>>> print('foo', flush=False)
foo

Note again, this only changes the current global scope, because the print name on the current global scope will overshadow the builtin print function (or unreference the compatibility function, if using one in Python 2, in that current global scope).

If you want to do this inside a function instead of on a module's global scope, you should give it a different name, e.g.:

def foo():
    printf = functools.partial(print, flush=True)
    printf('print stuff like this')

If you declare it a global in a function, you're changing it on the module's global namespace, so you should just put it in the global namespace, unless that specific behavior is exactly what you want.

Changing the default for the process

I think the best option here is to use the -u flag to get unbuffered output.

$ python -u script.py

or

$ python -um package.module

From the docs:

Force stdin, stdout and stderr to be totally unbuffered. On systems where it matters, also put stdin, stdout and stderr in binary mode.

Note that there is internal buffering in file.readlines() and File Objects (for line in sys.stdin) which is not influenced by this option. To work around this, you will want to use file.readline() inside a while 1: loop.

Changing the default for the shell operating environment

You can get this behavior for all python processes in the environment or environments that inherit from the environment if you set the environment variable to a nonempty string:

e.g., in Linux or OSX:

$ export PYTHONUNBUFFERED=TRUE

or Windows:

C:\SET PYTHONUNBUFFERED=TRUE

from the docs:

PYTHONUNBUFFERED

If this is set to a non-empty string it is equivalent to specifying the -u option.


Addendum

Here's the help on the print function from Python 2.7.12 - note that there is no flush argument:

>>> from __future__ import print_function
>>> help(print)
print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout)
    
    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file: a file-like object (stream); defaults to the current sys.stdout.
    sep:  string inserted between values, default a space.
    end:  string appended after the last value, default a newline.

Document directory path of Xcode Device Simulator

NSLog below code somewhere in "AppDelegate", run your project and follow the path. This will be easy for you to get to the documents rather than searching randomly inside "~/Library/Developer/CoreSimulator/Devices/"

Objective-C

NSLog(@"%@",[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]);

Swift
If you are using Swift 1.2, use the code below which will only output in development when using the Simulator because of the #if #endif block:

#if arch(i386) || arch(x86_64)
  let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! NSString
  NSLog("Document Path: %@", documentsPath)
#endif

Copy your path from "/Users/ankur/Library/Developer/CoreSimulator/Devices/7BA821..." go to "Finder" and then "Go to Folder" or command + shift + g and paste your path, let the mac take you to your documents directory :)

How to mock static methods in c# using MOQ framework?

Moq cannot mock a static member of a class.

When designing code for testability it's important to avoid static members (and singletons). A design pattern that can help you refactoring your code for testability is Dependency Injection.

This means changing this:

public class Foo
{
    public Foo()
    {
        Bar = new Bar();
    }
}

to

public Foo(IBar bar)
{
    Bar = bar;
}

This allows you to use a mock from your unit tests. In production you use a Dependency Injection tool like Ninject or Unity wich can wire everything together.

I wrote a blog about this some time ago. It explains which patterns an be used for better testable code. Maybe it can help you: Unit Testing, hell or heaven?

Another solution could be to use the Microsoft Fakes Framework. This is not a replacement for writing good designed testable code but it can help you out. The Fakes framework allows you to mock static members and replace them at runtime with your own custom behavior.

Change the borderColor of the TextBox

With PictureBox1
    .Visible = False
    .Width = TextBox1.Width + 4
    .Height = TextBox1.Height + 4
    .Left = TextBox1.Left - 2
    .Top = TextBox1.Top - 2
    .SendToBack()
    .Visible = True
End With

How can I merge two commits into one if I already started rebase?

Let me suggest you an easier approach,

Instead of divind into GIT's deep consepts and bothering with the editor's crab, you could do the following;

Lets suppose you created a branch named bug1 from master. Made 2 commits to bug1. You only modified 2 files with these changes.

Copy these two files into a text editor. Checkout master. Paste the files. Commit.

That simple.

OpenCV get pixel channel value from Mat image

The below code works for me, for both accessing and changing a pixel value.

For accessing pixel's channel value :

for (int i = 0; i < image.cols; i++) {
    for (int j = 0; j < image.rows; j++) {
        Vec3b intensity = image.at<Vec3b>(j, i);
        for(int k = 0; k < image.channels(); k++) {
            uchar col = intensity.val[k]; 
        }   
    }
}

For changing a pixel value of a channel :

uchar pixValue;
for (int i = 0; i < image.cols; i++) {
    for (int j = 0; j < image.rows; j++) {
        Vec3b &intensity = image.at<Vec3b>(j, i);
        for(int k = 0; k < image.channels(); k++) {
            // calculate pixValue
            intensity.val[k] = pixValue;
        }
     }
}

`

Source : Accessing pixel value

What is the difference between Integer and int in Java?

In Java int is a primitive data type while Integer is a Helper class, it is use to convert for one data type to other.

For example:

         double doubleValue = 156.5d;
         Double doubleObject  = new Double(doubleValue);
         Byte myByteValue = doubleObject.byteValue ();
         String myStringValue = doubleObject.toString();

Primitive data types are store the fastest available memory where the Helper class is complex and store in heap memory.

reference from "David Gassner" Java Essential Training.

Python, TypeError: unhashable type: 'list'

The problem is that you can't use a list as the key in a dict, since dict keys need to be immutable. Use a tuple instead.

This is a list:

[x, y]

This is a tuple:

(x, y)

Note that in most cases, the ( and ) are optional, since , is what actually defines a tuple (as long as it's not surrounded by [] or {}, or used as a function argument).

You might find the section on tuples in the Python tutorial useful:

Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable, and usually contain an heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.

And in the section on dictionaries:

Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().


In case you're wondering what the error message means, it's complaining because there's no built-in hash function for lists (by design), and dictionaries are implemented as hash tables.

What is the difference between SessionState and ViewState?

Usage: If you're going to store information that you want to access on different web pages, you can use SessionState

If you want to store information that you want to access from the same page, then you can use Viewstate

Storage The Viewstate is stored within the page itself (in encrypted text), while the Sessionstate is stored in the server.

The SessionState will clear in the following conditions

  1. Cleared by programmer
  2. Cleared by user
  3. Timeout

Doctrine 2 ArrayCollection filter method

Doctrine now has Criteria which offers a single API for filtering collections with SQL and in PHP, depending on the context.

https://www.doctrine-project.org/projects/doctrine-orm/en/latest/reference/working-with-associations.html#filtering-collections

Update

This will achieve the result in the accepted answer, without getting everything from the database.

use Doctrine\Common\Collections\Criteria;

/**
 * @ORM\Entity
 */
class Member {
  // ...
  public function getCommentsFiltered($ids) {
    $criteria = Criteria::create()->where(Criteria::expr()->in("id", $ids));

    return $this->getComments()->matching($criteria); 
  }
}

Jquery bind double click and single click separately

i am implementing this simple solution , http://jsfiddle.net/533135/VHkLR/5/
html code

<p>Click on this paragraph.</p>
<b> </b>

script code

var dbclick=false;    
$("p").click(function(){
setTimeout(function(){
if(dbclick ==false){
$("b").html("clicked")
}

},200)

}).dblclick(function(){
dbclick = true
$("b").html("dbclicked")
setTimeout(function(){
dbclick = false


},300)
});


its not much laggy

Jquery, set value of td in a table?

use .html() along with selector to get/set HTML:

 $('#detailInfo').html('changed value');

SSL: CERTIFICATE_VERIFY_FAILED with Python3

When you are using a self signed cert urllib3 version 1.25.3 refuses to ignore the SSL cert

To fix remove urllib3-1.25.3 and install urllib3-1.24.3

pip3 uninstall urllib3

pip3 install urllib3==1.24.3

Tested on Linux MacOS and Window$

XML to CSV Using XSLT

Found an XML transform stylesheet here (wayback machine link, site itself is in german)

The stylesheet added here could be helpful:

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="iso-8859-1"/>

<xsl:strip-space elements="*" />

<xsl:template match="/*/child::*">
<xsl:for-each select="child::*">
<xsl:if test="position() != last()">"<xsl:value-of select="normalize-space(.)"/>",    </xsl:if>
<xsl:if test="position()  = last()">"<xsl:value-of select="normalize-space(.)"/>"<xsl:text>&#xD;</xsl:text>
</xsl:if>
</xsl:for-each>
</xsl:template>

</xsl:stylesheet>

Perhaps you want to remove the quotes inside the xsl:if tags so it doesn't put your values into quotes, depending on where you want to use the CSV file.

What is the use of GO in SQL Server Management Studio & Transact SQL?

Use herDatabase
GO ; 

Code says to execute the instructions above the GO marker. My default database is myDatabase, so instead of using myDatabase GO and makes current query to use herDatabase

Chrome net::ERR_INCOMPLETE_CHUNKED_ENCODING error

It is known Chrome problem. According to Chrome and Chromium bug trackers there is no universal solution for this. This problem is not related with server type and version, it is right in Chrome.

Setting Content-Encoding header to identity solved this problem to me.

from developer.mozilla.org

identity | Indicates the identity function (i.e. no compression, nor modification).

So, I can suggest, that in some cases Chrome can not perform gzip compress correctly.

Java: Converting String to and from ByteBuffer and associated problems

Unless things have changed, you're better off with

public static ByteBuffer str_to_bb(String msg, Charset charset){
    return ByteBuffer.wrap(msg.getBytes(charset));
}

public static String bb_to_str(ByteBuffer buffer, Charset charset){
    byte[] bytes;
    if(buffer.hasArray()) {
        bytes = buffer.array();
    } else {
        bytes = new byte[buffer.remaining()];
        buffer.get(bytes);
    }
    return new String(bytes, charset);
}

Usually buffer.hasArray() will be either always true or always false depending on your use case. In practice, unless you really want it to work under any circumstances, it's safe to optimize away the branch you don't need.

What underlies this JavaScript idiom: var self = this?

I think the variable name 'self' should not be used this way anymore, since modern browsers provide a global variable self pointing to the global object of either a normal window or a WebWorker.

To avoid confusion and potential conflicts, you can write var thiz = this or var that = this instead.

Some projects cannot be imported because they already exist in the workspace error in Eclipse

Another way I just found!

MOVE the project to some other folder and then import and if required copy to workspace

Should I use PATCH or PUT in my REST API?

I would generally prefer something a bit simpler, like activate/deactivate sub-resource (linked by a Link header with rel=service).

POST /groups/api/v1/groups/{group id}/activate

or

POST /groups/api/v1/groups/{group id}/deactivate

For the consumer, this interface is dead-simple, and it follows REST principles without bogging you down in conceptualizing "activations" as individual resources.

Using cURL with a username and password?

I had the same need in bash (Ubuntu 16.04 LTS) and the commands provided in the answers failed to work in my case. I had to use:

curl -X POST -F 'username="$USER"' -F 'password="$PASS"' "http://api.somesite.com/test/blah?something=123"

Double quotes in the -F arguments are only needed if you're using variables, thus from the command line ... -F 'username=myuser' ... will be fine.

Relevant Security Notice: as Mr. Mark Ribau points in comments this command shows the password ($PASS variable, expanded) in the processlist!

What is the symbol for whitespace in C?

No special escape sequence is required: you can just type the space directly:

if (char_i_want_to_test == ' ') { 
    // Do something because it is space
}

In ASCII, space is code 32, so you could specify space by '\x20' or even 32, but you really shouldn't do that.

Aside: the word "whitespace" is a catch all for space, tab, newline, and all of that. When you're referring specifically to the ordinary space character, you shouldn't use the term.

Regular expression for matching latitude/longitude coordinates?

Try this:

(?<!\d)([-+]?(?:[1-8]?\d(?:\.\d+)?|90(?:\.0+)?)),\s*([-+]?(?:180(?:\.0+)?|(?:(?:1[0-7]\d)|(?:[1-9]?\d))(?:\.\d+)?))(?!\d)`

How to obtain the absolute path of a file via Shell (BASH/ZSH/SH)?

#! /bin/sh
echo "$(cd "$(dirname "$1")"; pwd -P)/$(basename "$1")"

Using the "start" command with parameters passed to the started program

Instead of a batch file, you can create a shortcut on the desktop.

Set the target to:

"c:\program files\Microsoft Virtual PC\Virtual PC.exe" -pc "MY-PC" -launch

and you're all set. Since you're not starting up a command prompt to launch it, there will be no DOS Box.

What is Express.js?

1) What is Express.js?

Express.js is a Node.js framework. It's the most popular framework as of now (the most starred on NPM).

Enter image description here.

It's built around configuration and granular simplicity of Connect middleware. Some people compare Express.js to Ruby Sinatra vs. the bulky and opinionated Ruby on Rails.

2) What is the purpose of it with Node.js?

That you don't have to repeat same code over and over again. Node.js is a low-level I/O mechanism which has an HTTP module. If you just use an HTTP module, a lot of work like parsing the payload, cookies, storing sessions (in memory or in Redis), selecting the right route pattern based on regular expressions will have to be re-implemented. With Express.js, it is just there for you to use.

3) Why do we actually need Express.js? How it is useful for us to use with Node.js?

The first answer should answer your question. If no, then try to write a small REST API server in plain Node.js (that is, using only core modules) and then in Express.js. The latter will take you 5-10x less time and lines of code.

What is Redis? Does it come with Express.js?

Redis is a fast persistent key-value storage. You can optionally use it for storing sessions with Express.js, but you don't need to. By default, Express.js has memory storage for sessions. Redis also can be use for queueing jobs, for example, email jobs.

Check out my tutorial on REST API server with Express.js.

MVC but not by itself

Express.js is not an model-view-controller framework by itself. You need to bring your own object-relational mapping libraries such as Mongoose for MongoDB, Sequelize (http://sequelizejs.com) for SQL databases, Waterline (https://github.com/balderdashy/waterline) for many databases into the stack.

Alternatives

Other Node.js frameworks to consider (https://www.quora.com/Node-js/Which-Node-js-framework-is-best-for-building-a-RESTful-API):

UPDATE: I put together this resource that aid people in choosing Node.js frameworks: http://nodeframework.com

UPDATE2: We added some GitHub stats to nodeframework.com so now you can compare the level of social proof (GitHub stars) for 30+ frameworks on one page.

enter image description here

Full-stack:

Just REST API:

Ruby on Rails like:

Sinatra like:

Other:

Middleware:

Static site generators:

Checking if element exists with Python Selenium

You could also do it more concisely using

driver.find_element_by_id("some_id").size != 0

Using Keras & Tensorflow with AMD GPU

I'm writing an OpenCL 1.2 backend for Tensorflow at https://github.com/hughperkins/tensorflow-cl

This fork of tensorflow for OpenCL has the following characteristics:

  • it targets any/all OpenCL 1.2 devices. It doesnt need OpenCL 2.0, doesnt need SPIR-V, or SPIR. Doesnt need Shared Virtual Memory. And so on ...
  • it's based on an underlying library called 'cuda-on-cl', https://github.com/hughperkins/cuda-on-cl
    • cuda-on-cl targets to be able to take any NVIDIA® CUDA™ soure-code, and compile it for OpenCL 1.2 devices. It's a very general goal, and a very general compiler
  • for now, the following functionalities are implemented:
  • it is developed on Ubuntu 16.04 (using Intel HD5500, and NVIDIA GPUs) and Mac Sierra (using Intel HD 530, and Radeon Pro 450)

This is not the only OpenCL fork of Tensorflow available. There is also a fork being developed by Codeplay https://www.codeplay.com , using Computecpp, https://www.codeplay.com/products/computesuite/computecpp Their fork has stronger requirements than my own, as far as I know, in terms of which specific GPU devices it works on. You would need to check the Platform Support Notes (at the bottom of hte computecpp page), to determine whether your device is supported. The codeplay fork is actually an official Google fork, which is here: https://github.com/benoitsteiner/tensorflow-opencl

Removing header column from pandas dataframe

I think you cant remove column names, only reset them by range with shape:

print df.shape[1]
2

print range(df.shape[1])
[0, 1]

df.columns = range(df.shape[1])
print df
    0   1
0  23  12
1  21  44
2  98  21

This is same as using to_csv and read_csv:

print df.to_csv(header=None,index=False)
23,12
21,44
98,21

print pd.read_csv(io.StringIO(u""+df.to_csv(header=None,index=False)), header=None)
    0   1
0  23  12
1  21  44
2  98  21

Next solution with skiprows:

print df.to_csv(index=False)
A,B
23,12
21,44
98,21

print pd.read_csv(io.StringIO(u""+df.to_csv(index=False)), header=None, skiprows=1)
    0   1
0  23  12
1  21  44
2  98  21

Can I edit an iPad's host file?

Workarond I use for development purposes:

  1. Create your own proxy server (One option would be: Squid on Linux).
  2. Set your hosts file with your domains.
  3. Set the proxy server on the IPAD/IPHONE and you can use with your hosts.

JQuery / JavaScript - trigger button click from another button click event

this works fine, but file name does not display anymore.

$(document).ready(function(){ $("img.attach2").click(function(){ $("input.attach1").click(); return false; }); });

Add padding on view programmatically

The best way is not to write your own funcion.

Let me explain the motivaion - please lookup the official Android source code.

In TypedValue.java we have:

    public static int complexToDimensionPixelSize(int data,
            DisplayMetrics metrics)
    {
        final float value = complexToFloat(data);
        final float f = applyDimension(
                (data>>COMPLEX_UNIT_SHIFT)&COMPLEX_UNIT_MASK,
                value,
                metrics);
        final int res = (int) ((f >= 0) ? (f + 0.5f) : (f - 0.5f));
        if (res != 0) return res;
        if (value == 0) return 0;
        if (value > 0) return 1;
        return -1;
    }

and:

    public static float applyDimension(int unit, float value,
                                       DisplayMetrics metrics)
    {
        switch (unit) {
        case COMPLEX_UNIT_PX:
            return value;
        case COMPLEX_UNIT_DIP:
            return value * metrics.density;
        case COMPLEX_UNIT_SP:
            return value * metrics.scaledDensity;
        case COMPLEX_UNIT_PT:
            return value * metrics.xdpi * (1.0f/72);
        case COMPLEX_UNIT_IN:
            return value * metrics.xdpi;
        case COMPLEX_UNIT_MM:
            return value * metrics.xdpi * (1.0f/25.4f);
        }
        return 0;
    }

As you can see, DisplayMetrics metrics can differ, which means it would yield different values across Android-OS powered devices.

I strongly recommend putting your dp padding in dimen xml file and use the official Android conversions to have consistent behaviour with regard to how Android framework works.

selectOneMenu ajax events

The PrimeFaces ajax events sometimes are very poorly documented, so in most cases you must go to the source code and check yourself.

p:selectOneMenu supports change event:

<p:selectOneMenu ..>
    <p:ajax event="change" update="msgtext"
        listener="#{post.subjectSelectionChanged}" />
    <!--...-->
</p:selectOneMenu>

which triggers listener with AjaxBehaviorEvent as argument in signature:

public void subjectSelectionChanged(final AjaxBehaviorEvent event)  {...}

What's default HTML/CSS link color?

For me, on Chrome (updated June 2018) the color for an unvisited link is #2779F6. You can always get this by zooming in really close, taking a screenshot, and visiting a website like html-color-codes.info that will convert a screenshot to a color code.

How do I add a newline to a windows-forms TextBox?

Took this from JeffK and made it a little more compact.

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    Dim Newline As String = System.Environment.NewLine

    TextBox1.Text = "This is a test"
    TextBox1.Text += Newline + "This is another test"

End Sub

Bootstrap 3: Using img-circle, how to get circle from non-square image?

I use these two methods depending on the usage. FIDDLE

<div class="img-div">
<img src="http://placekitten.com/g/400/200" />
</div>
<div class="circle-image"></div>

div.img-div{
    height:200px;
    width:200px;
    overflow:hidden;
    border-radius:50%;
}

.img-div img{
    -webkit-transform:translate(-50%);
    margin-left:100px;
}

.circle-image{
    width:200px;
    height:200px;
    border-radius:50%;
    background-image:url("http://placekitten.com/g/200/400");
    display:block;
    background-position-y:25% 
}

How to round down to nearest integer in MySQL?

Use FLOOR(), if you want to round your decimal to the lower integer. Examples:

FLOOR(1.9) => 1
FLOOR(1.1) => 1

Use ROUND(), if you want to round your decimal to the nearest integer. Examples:

ROUND(1.9) => 2
ROUND(1.1) => 1

Use CEIL(), if you want to round your decimal to the upper integer. Examples:

CEIL(1.9) => 2
CEIL(1.1) => 2

Log4j output not displayed in Eclipse console

Thought this was a genuine defect but it turns out that my console size was limited, and caused the old content past 80000 characters to be cut off.

Right click on the console for the preferences and increase the console size limit.

Indentation shortcuts in Visual Studio

Ctrl-K, Ctrl-D

Will just prettify the entire document. Saves a lot of messing about, compared to delphi.

Make sure to remove all indents by first selecting everything with Ctrl+A then press Shift+Tab repeatedly until everything is aligned to the left. After you do that Ctrl+K, Ctrl+D will work the way you want them to.

You could also do the same but only to a selection of code by highlighting the block of code you want to realign, aligning it to the left side (Shift+Tab) and then after making sure you've selected the code you want to realign press Ctrl+K, Ctrl+F or just right click the highlighted code and select "Format Selection".

What characters are allowed in an email address?

For simplicity's sake, I sanitize the submission by removing all text within double quotes and those associated surrounding double quotes before validation, putting the kibosh on email address submissions based on what is disallowed. Just because someone can have the John.."The*$hizzle*Bizzle"[email protected] address doesn't mean I have to allow it in my system. We are living in the future where it maybe takes less time to get a free email address than to do a good job wiping your butt. And it isn't as if the email criteria are not plastered right next to the input saying what is and isn't allowed.

I also sanitize what is specifically not allowed by various RFCs after the quoted material is removed. The list of specifically disallowed characters and patterns seems to be a much shorter list to test for.

Disallowed:

    local part starts with a period ( [email protected] )
    local part ends with a period   ( [email protected] )
    two or more periods in series   ( [email protected] )
    &’`*|/                          ( some&thing`[email protected] )
    more than one @                 ( which@[email protected] )
    :%                              ( mo:characters%mo:[email protected] )

In the example given:

John.."The*$hizzle*Bizzle"[email protected] --> [email protected]

[email protected] --> [email protected]

Sending a confirm email message to the leftover result upon an attempt to add or change the email address is a good way to see if your code can handle the email address submitted. If the email passes validation after as many rounds of sanitization as needed, then fire off that confirmation. If a request comes back from the confirmation link, then the new email can be moved from the holding||temporary||purgatory status or storage to become a real, bonafide first-class stored email.

A notification of email address change failure or success can be sent to the old email address if you want to be considerate. Unconfirmed account setups might fall out of the system as failed attempts entirely after a reasonable amount of time.

I don't allow stinkhole emails on my system, maybe that is just throwing away money. But, 99.9% of the time people just do the right thing and have an email that doesn't push conformity limits to the brink utilizing edge case compatibility scenarios. Be careful of regex DDoS, this is a place where you can get into trouble. And this is related to the third thing I do, I put a limit on how long I am willing to process any one email. If it needs to slow down my machine to get validated-- it isn't getting past the my incoming data API endpoint logic.

Edit: This answer kept on getting dinged for being "bad", and maybe it deserved it. Maybe it is still bad, maybe not.

What's the best way of scraping data from a website?

Yes you can do it yourself. It is just a matter of grabbing the sources of the page and parsing them the way you want.

There are various possibilities. A good combo is using python-requests (built on top of urllib2, it is urllib.request in Python3) and BeautifulSoup4, which has its methods to select elements and also permits CSS selectors:

import requests
from BeautifulSoup4 import BeautifulSoup as bs
request = requests.get("http://foo.bar")
soup = bs(request.text) 
some_elements = soup.find_all("div", class_="myCssClass")

Some will prefer xpath parsing or jquery-like pyquery, lxml or something else.

When the data you want is produced by some JavaScript, the above won't work. You either need python-ghost or Selenium. I prefer the latter combined with PhantomJS, much lighter and simpler to install, and easy to use:

from selenium import webdriver
client = webdriver.PhantomJS()
client.get("http://foo")
soup = bs(client.page_source)

I would advice to start your own solution. You'll understand Scrapy's benefits doing so.

ps: take a look at scrapely: https://github.com/scrapy/scrapely

pps: take a look at Portia, to start extracting information visually, without programming knowledge: https://github.com/scrapinghub/portia

Size of character ('a') in C/C++

In C the type of character literals are int and char in C++. This is in C++ required to support function overloading. See this example:

void foo(char c)
{
    puts("char");
}
void foo(int i)
{
    puts("int");
}
int main()
{
    foo('i');
    return 0;
}

Output:

char

How do I use DrawerLayout to display over the ActionBar/Toolbar and under the status bar?

New functionality in the framework and support libs allow exactly this. There are three 'pieces of the puzzle':

  1. Using Toolbar so that you can embed your action bar into your view hierarchy.
  2. Making DrawerLayout fitsSystemWindows so that it is layed out behind the system bars.
  3. Disabling Theme.Material's normal status bar coloring so that DrawerLayout can draw there instead.

I'll assume that you will use the new appcompat.

First, your layout should look like this:

<!-- The important thing to note here is the added fitSystemWindows -->
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/my_drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <!-- Your normal content view -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <!-- We use a Toolbar so that our drawer can be displayed
             in front of the action bar -->
        <android.support.v7.widget.Toolbar  
            android:id="@+id/my_awesome_toolbar"
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:minHeight="?attr/actionBarSize"
            android:background="?attr/colorPrimary" />

        <!-- The rest of your content view -->

    </LinearLayout>

    <!-- Your drawer view. This can be any view, LinearLayout
         is just an example. As we have set fitSystemWindows=true
         this will be displayed under the status bar. -->
    <LinearLayout
        android:layout_width="304dp"
        android:layout_height="match_parent"
        android:layout_gravity="left|start"
        android:fitsSystemWindows="true">

        <!-- Your drawer content -->

    </LinearLayout>

</android.support.v4.widget.DrawerLayout>

Then in your Activity/Fragment:

public void onCreate(Bundled savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Your normal setup. Blah blah ...

    // As we're using a Toolbar, we should retrieve it and set it
    // to be our ActionBar
    Toolbar toolbar = (...) findViewById(R.id.my_awesome_toolbar);
    setSupportActionBar(toolbar);

    // Now retrieve the DrawerLayout so that we can set the status bar color.
    // This only takes effect on Lollipop, or when using translucentStatusBar
    // on KitKat.
    DrawerLayout drawerLayout = (...) findViewById(R.id.my_drawer_layout);
    drawerLayout.setStatusBarBackgroundColor(yourChosenColor);
}

Then you need to make sure that the DrawerLayout is visible behind the status bar. You do that by changing your values-v21 theme:

values-v21/themes.xml

<style name="Theme.MyApp" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="android:windowDrawsSystemBarBackgrounds">true</item>
    <item name="android:statusBarColor">@android:color/transparent</item>
    <item name="android:windowTranslucentStatus">true</item>
</style>

Note: If a <fragment android:name="fragments.NavigationDrawerFragment"> is used instead of

<LinearLayout
    android:layout_width="304dp"
    android:layout_height="match_parent"
    android:layout_gravity="left|start"
    android:fitsSystemWindows="true">

    <!-- Your drawer content -->

</LinearLayout>

the actual layout, the desired effect will be achieved if you call fitsSystemWindows(boolean) on a view that you return from onCreateView method.

@Override
public View onCreateView(LayoutInflater inflater, 
                         ViewGroup container,
                         Bundle savedInstanceState) {
    View mDrawerListView = inflater.inflate(
        R.layout.fragment_navigation_drawer, container, false);
    mDrawerListView.setFitsSystemWindows(true);
    return mDrawerListView;
}

Redirecting to authentication dialog - "An error occurred. Please try again later"

I just encountered this problem myself. I'm developing an app internally, so my host is 'localhost'. It wasn't obvious how to set 'localhost' up in the app configuration. If you want to develop locally, set up your app by following these steps:

  1. Go to the place where you manage your Facebook app. Specifically, you want to be in "Basic" under the "Settings" menu.
  2. Add 'localhost' to "App Domain".
  3. Under "Select how your app integrates with Facebook", select "Website", and enter "http://localhost/".

Save and wait a couple of minutes for the information to propagate, although it worked right away for me.

Adding rows to tbody of a table using jQuery

I have never ever come across such a strange problem like this! o.O

Do you know what the problem was? $ isn't working. I tried the same code with jQuery like jQuery("#tblEntAttributes tbody").append(newRowContent); and it works like a charm!

No idea why this strange problem occurs!

How to parse JSON without JSON.NET library?

You can use DataContractJsonSerializer. See this link for more details.

Maven dependency for Servlet 3.0 API?

Or you can use the Central Maven Repository with the Servlet 3.0 API which is also provided for the Tomcat Server 7.0.X

    <dependency>
        <groupId>org.apache.tomcat</groupId>
        <artifactId>tomcat-servlet-api</artifactId>
        <version>7.0.21</version>
        <scope>provided</scope>
    </dependency>

from here: http://repo2.maven.org/maven2/org/apache/tomcat/tomcat-servlet-api/7.0.21/

WPF User Control Parent

If you just want to get a specific parent, not only the window, a specific parent in the tree structure, and also not using recursion, or hard break loop counters, you can use the following:

public static T FindParent<T>(DependencyObject current)
    where T : class 
{
    var dependency = current;

    while((dependency = VisualTreeHelper.GetParent(dependency) ?? LogicalTreeHelper.GetParent(dependency)) != null
        && !(dependency is T)) { }

    return dependency as T;
}

Just don't put this call in a constructor (since the Parent property is not yet initialized). Add it in the loading event handler, or in other parts of your application.

How to 'restart' an android application programmatically

Checkout intent properties like no history , clear back stack etc ... Intent.setFlags

Intent mStartActivity = new Intent(HomeActivity.this, SplashScreen.class);
int mPendingIntentId = 123456;
PendingIntent mPendingIntent = PendingIntent.getActivity(HomeActivity.this, mPendingIntentId, mStartActivity,
PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager) HomeActivity.this.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
System.exit(0);

How can I tell when HttpClient has timed out?

Basically, you need to catch the OperationCanceledException and check the state of the cancellation token that was passed to SendAsync (or GetAsync, or whatever HttpClient method you're using):

  • if it was canceled (IsCancellationRequested is true), it means the request really was canceled
  • if not, it means the request timed out

Of course, this isn't very convenient... it would be better to receive a TimeoutException in case of timeout. I propose a solution here based on a custom HTTP message handler: Better timeout handling with HttpClient

Javascript ES6 export const vs export let

In ES6, imports are live read-only views on exported-values. As a result, when you do import a from "somemodule";, you cannot assign to a no matter how you declare a in the module.

However, since imported variables are live views, they do change according to the "raw" exported variable in exports. Consider the following code (borrowed from the reference article below):

//------ lib.js ------
export let counter = 3;
export function incCounter() {
    counter++;
}

//------ main1.js ------
import { counter, incCounter } from './lib';

// The imported value `counter` is live
console.log(counter); // 3
incCounter();
console.log(counter); // 4

// The imported value can’t be changed
counter++; // TypeError

As you can see, the difference really lies in lib.js, not main1.js.


To summarize:

  • You cannot assign to import-ed variables, no matter how you declare the corresponding variables in the module.
  • The traditional let-vs-const semantics applies to the declared variable in the module.
    • If the variable is declared const, it cannot be reassigned or rebound in anywhere.
    • If the variable is declared let, it can only be reassigned in the module (but not the user). If it is changed, the import-ed variable changes accordingly.

Reference: http://exploringjs.com/es6/ch_modules.html#leanpub-auto-in-es6-imports-are-live-read-only-views-on-exported-values

Transmitting newline character "\n"

Try to replace the \n with %0A just like you have spaces replaced with %20.

Why write <script type="text/javascript"> when the mime type is set by the server?

Boris Zbarsky (Mozilla), who probably knows more about the innards of Gecko than anyone else, provided at http://lists.w3.org/Archives/Public/public-html/2009Apr/0195.html the pseudocode repeated below to describe what Gecko based browsers do:

if (@type not set or empty) {
   if (@language not set or empty) {
     // Treat as default script language; what this is depends on the
     // content-script-type HTTP header or equivalent META tag
   } else {
     if (@language is one of "javascript", "livescript", "mocha",
                             "javascript1.0", "javascript1.1",
                             "javascript1.2", "javascript1.3",
                             "javascript1.4", "javascript1.5",
                             "javascript1.6", "javascript1.7",
                             "javascript1.8") {
       // Treat as javascript
     } else {
       // Treat as unknown script language; do not execute
     }
   }
} else {
   if (@type is one of "text/javascript", "text/ecmascript",
                       "application/javascript",
                       "application/ecmascript",
                       "application/x-javascript") {
     // Treat as javascript
   } else {
     // Treat as specified (e.g. if pyxpcom is installed and
     // python script is allowed in this context and the type
     // is one that the python runtime claims to handle, use that).
     // If we don't have a runtime for this type, do not execute.
   }
}

Array as session variable

session_start();          //php part
$_SESSION['student']=array();
$student_name=$_POST['student_name']; //student_name form field name
$student_city=$_POST['city_id'];   //city_id form field name
array_push($_SESSION['student'],$student_name,$student_city);   
//print_r($_SESSION['student']);


<table class="table">     //html part
    <tr>
      <th>Name</th>
      <th>City</th>
    </tr>

    <tr>
     <?php for($i = 0 ; $i < count($_SESSION['student']) ; $i++) {
     echo '<td>'.$_SESSION['student'][$i].'</td>';
     }  ?>
    </tr>
</table>

Barcode scanner for mobile phone for Website in form

There's a JS QrCode scanner, that works on mobile sites with a camera:

https://github.com/LazarSoft/jsqrcode

I have worked with it for one of my project and it works pretty good !

Python 3 - ValueError: not enough values to unpack (expected 3, got 2)

You probably want to assign the lastname you are reading out here

lastname = sheet.cell(row=r, column=3).value

to something; currently the program just forgets it

you could do that two lines after, like so

unpaidMembers[name] = lastname, email

your program will still crash at the same place, because .items() still won't give you 3-tuples but rather something that has this structure: (name, (lastname, email))

good news is, python can handle this

for name, (lastname, email) in unpaidMembers.items():

etc.

What is __declspec and when do I need to use it?

The canonical examples are __declspec(dllimport) and __declspec(dllexport), which instruct the linker to import and export (respectively) a symbol from or to a DLL.

// header
__declspec(dllimport) void foo();


// code - this calls foo() somewhere in a DLL
foo();

(__declspec(..) just wraps up Microsoft's specific stuff - to achieve compatibility, one would usually wrap it away with macros)

How to use a servlet filter in Java to change an incoming servlet request url?

A simple JSF Url Prettyfier filter based in the steps of BalusC's answer. The filter forwards all the requests starting with the /ui path (supposing you've got all your xhtml files stored there) to the same path, but adding the xhtml suffix.

public class UrlPrettyfierFilter implements Filter {

    private static final String JSF_VIEW_ROOT_PATH = "/ui";

    private static final String JSF_VIEW_SUFFIX = ".xhtml";

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpServletRequest = ((HttpServletRequest) request);
        String requestURI = httpServletRequest.getRequestURI();
        //Only process the paths starting with /ui, so as other requests get unprocessed. 
        //You can register the filter itself for /ui/* only, too
        if (requestURI.startsWith(JSF_VIEW_ROOT_PATH) 
                && !requestURI.contains(JSF_VIEW_SUFFIX)) {
            request.getRequestDispatcher(requestURI.concat(JSF_VIEW_SUFFIX))
                .forward(request,response);
        } else {
            chain.doFilter(httpServletRequest, response);
        }
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {

    }

}

Can I calculate z-score with R?

if x is a vector with raw scores then scale(x) is a vector with standardized scores.

Or manually: (x-mean(x))/sd(x)

Jenkins could not run git

I had the correct path to git in Jenkins, but I had not yet accepted the Xcode build tools EULA on a fresh install of OS X Yosemite, so git looked like it was failing in Jenkins. After trying "git --version" on the git at /usr/bin/git in a terminal, I was given a command-line interface to accept the EULA, and then Jenkins could then access the git URL I had given the build project.

How to uninstall jupyter

For Mac OS, you may use the below command in order to remove files manually.

sudo rm -rf /usr/local/bin/jupyter

Synchronous Requests in Node.js

See sync-request: https://github.com/ForbesLindesay/sync-request

Example:

var request = require('sync-request');
var res = request('GET', 'http://example.com');
console.log(res.getBody());

htmlentities() vs. htmlspecialchars()

**HTML Character Entity Reference Chart at W3.org**

https://dev.w3.org/html5/html-author/charref

&Tab;
&NewLine;
!
&excl;
"
&quot; &QUOT;
#
&num;
$
&dollar;
%
&percnt;
&
&amp; &AMP;
'
&apos;
(
&lpar;
)
&rpar;
*
&ast; &midast;
+
&plus;
,
&comma;
.
&period;
/
&sol;
:
&colon;
;
&semi;
<
&lt; &LT;
=
&equals;
>
&gt; &GT;
?
&quest;
@
&commat;
[
&lsqb; &lbrack;
\
&bsol;
]
&rsqb; &rbrack;
^
&Hat;
_
&lowbar;
`
&grave; &DiacriticalGrave;
{
&lcub; &lbrace;
|
&verbar; &vert; &VerticalLine;
}
&rcub; &rbrace;

&nbsp; &NonBreakingSpace;
¡
&iexcl;
¢
&cent;
£
&pound;
¤
&curren;
¥
&yen;
¦
&brvbar;
§
&sect;
¨
&Dot; &die; &DoubleDot; &uml;
©
&copy; &COPY;
ª
&ordf;
«
&laquo;
¬
&not;
&shy;
®
&reg; &circledR; &REG;
¯
&macr; &OverBar; &strns;
°
&deg;
±
&plusmn; &pm; &PlusMinus;
²
&sup2;
³
&sup3;
´
&acute; &DiacriticalAcute;
µ
&micro;
¶
&para;
·
&middot; &centerdot; &CenterDot;
¸
&cedil; &Cedilla;
¹
&sup1;
º
&ordm;
»
&raquo;
¼
&frac14;
½
&frac12; &half;
¾
&frac34;
¿
&iquest;
À
&Agrave;
Á
&Aacute;
Â
&Acirc;
Ã
&Atilde;
Ä
&Auml;
Å
&Aring;
Æ
&AElig;
Ç
&Ccedil;
È
&Egrave;
É
&Eacute;
Ê
&Ecirc;
Ë
&Euml;
Ì
&Igrave;
Í
&Iacute;
Î
&Icirc;
Ï
&Iuml;
Ð
&ETH;
Ñ
&Ntilde;
Ò
&Ograve;
Ó
&Oacute;
Ô
&Ocirc;
Õ
&Otilde;
Ö
&Ouml;
×
&times;
Ø
&Oslash;
Ù
&Ugrave;
Ú
&Uacute;
Û
&Ucirc;
Ü
&Uuml;
Ý
&Yacute;
Þ
&THORN;
ß
&szlig;
à
&agrave;
á
&aacute;
â
&acirc;
ã
&atilde;
ä
&auml;
å
&aring;
æ
&aelig;
ç
&ccedil;
è
&egrave;
é
&eacute;
ê
&ecirc;
ë
&euml;
ì
&igrave;
í
&iacute;
î
&icirc;
ï
&iuml;
ð
&eth;
ñ
&ntilde;
ò
&ograve;
ó
&oacute;
ô
&ocirc;
õ
&otilde;
ö
&ouml;
÷
&divide; &div;
ø
&oslash;
ù
&ugrave;
ú
&uacute;
û
&ucirc;
ü
&uuml;
ý
&yacute;
þ
&thorn;
ÿ
&yuml;
A
&Amacr;
a
&amacr;
A
&Abreve;
a
&abreve;
A
&Aogon;
a
&aogon;
C
&Cacute;
c
&cacute;
C
&Ccirc;
c
&ccirc;
C
&Cdot;
c
&cdot;
C
&Ccaron;
c
&ccaron;
D
&Dcaron;
d
&dcaron;
Ð
&Dstrok;
d
&dstrok;
E
&Emacr;
e
&emacr;
E
&Edot;
e
&edot;
E
&Eogon;
e
&eogon;
E
&Ecaron;
e
&ecaron;
G
&Gcirc;
g
&gcirc;
G
&Gbreve;
g
&gbreve;
G
&Gdot;
g
&gdot;
G
&Gcedil;
H
&Hcirc;
h
&hcirc;
H
&Hstrok;
h
&hstrok;
I
&Itilde;
i
&itilde;
I
&Imacr;
i
&imacr;
I
&Iogon;
i
&iogon;
I
&Idot;
i
&imath; &inodot;
?
&IJlig;
?
&ijlig;
J
&Jcirc;
j
&jcirc;
K
&Kcedil;
k
&kcedil;
?
&kgreen;
L
&Lacute;
l
&lacute;
L
&Lcedil;
l
&lcedil;
L
&Lcaron;
l
&lcaron;
?
&Lmidot;
?
&lmidot;
L
&Lstrok;
l
&lstrok;
N
&Nacute;
n
&nacute;
N
&Ncedil;
n
&ncedil;
N
&Ncaron;
n
&ncaron;
?
&napos;
?
&ENG;
?
&eng;
O
&Omacr;
o
&omacr;
O
&Odblac;
o
&odblac;
Œ
&OElig;
œ
&oelig;
R
&Racute;
r
&racute;
R
&Rcedil;
r
&rcedil;
R
&Rcaron;
r
&rcaron;
S
&Sacute;
s
&sacute;
S
&Scirc;
s
&scirc;
S
&Scedil;
s
&scedil;
Š
&Scaron;
š
&scaron;
T
&Tcedil;
t
&tcedil;
T
&Tcaron;
t
&tcaron;
T
&Tstrok;
t
&tstrok;
U
&Utilde;
u
&utilde;
U
&Umacr;
u
&umacr;
U
&Ubreve;
u
&ubreve;
U
&Uring;
u
&uring;
U
&Udblac;
u
&udblac;
U
&Uogon;
u
&uogon;
W
&Wcirc;
w
&wcirc;
Y
&Ycirc;
y
&ycirc;
Ÿ
&Yuml;
Z
&Zacute;
z
&zacute;
Z
&Zdot;
z
&zdot;
Ž
&Zcaron;
ž
&zcaron;
ƒ
&fnof;
?
&imped;
?
&gacute;
?
&jmath;
ˆ
&circ;
?
&caron; &Hacek;
?
&breve; &Breve;
?
&dot; &DiacriticalDot;
°
&ring;
?
&ogon;
˜
&tilde; &DiacriticalTilde;
?
&dblac; &DiacriticalDoubleAcute;
?
&DownBreve;
_
&UnderBar;
?
&Alpha;
?
&Beta;
G
&Gamma;
?
&Delta;
?
&Epsilon;
?
&Zeta;
?
&Eta;
T
&Theta;
?
&Iota;
?
&Kappa;
?
&Lambda;
?
&Mu;
?
&Nu;
?
&Xi;
?
&Omicron;
?
&Pi;
?
&Rho;
S
&Sigma;
?
&Tau;
?
&Upsilon;
F
&Phi;
?
&Chi;
?
&Psi;
O
&Omega;
a
&alpha;
ß
&beta;
?
&gamma;
d
&delta;
e
&epsiv; &varepsilon; &epsilon;
?
&zeta;
?
&eta;
?
&theta;
?
&iota;
?
&kappa;
?
&lambda;
µ
&mu;
?
&nu;
?
&xi;
?
&omicron;
p
&pi;
?
&rho;
?
&sigmav; &varsigma; &sigmaf;
s
&sigma;
t
&tau;
?
&upsi; &upsilon;
f
&phi; &phiv; &varphi;
?
&chi;
?
&psi;
?
&omega;
?
&thetav; &vartheta; &thetasym;
?
&Upsi; &upsih;
?
&straightphi;
?
&piv; &varpi;
?
&Gammad;
?
&gammad; &digamma;
?
&kappav; &varkappa;
?
&rhov; &varrho;
?
&epsi; &straightepsilon;
?
&bepsi; &backepsilon;
?
&IOcy;
?
&DJcy;
?
&GJcy;
?
&Jukcy;
?
&DScy;
?
&Iukcy;
?
&YIcy;
?
&Jsercy;
?
&LJcy;
?
&NJcy;
?
&TSHcy;
?
&KJcy;
?
&Ubrcy;
?
&DZcy;
?
&Acy;
?
&Bcy;
?
&Vcy;
?
&Gcy;
?
&Dcy;
?
&IEcy;
?
&ZHcy;
?
&Zcy;
?
&Icy;
?
&Jcy;
?
&Kcy;
?
&Lcy;
?
&Mcy;
?
&Ncy;
?
&Ocy;
?
&Pcy;
?
&Rcy;
?
&Scy;
?
&Tcy;
?
&Ucy;
?
&Fcy;
?
&KHcy;
?
&TScy;
?
&CHcy;
?
&SHcy;
?
&SHCHcy;
?
&HARDcy;
?
&Ycy;
?
&SOFTcy;
?
&Ecy;
?
&YUcy;
?
&YAcy;
?
&acy;
?
&bcy;
?
&vcy;
?
&gcy;
?
&dcy;
?
&iecy;
?
&zhcy;
?
&zcy;
?
&icy;
?
&jcy;
?
&kcy;
?
&lcy;
?
&mcy;
?
&ncy;
?
&ocy;
?
&pcy;
?
&rcy;
?
&scy;
?
&tcy;
?
&ucy;
?
&fcy;
?
&khcy;
?
&tscy;
?
&chcy;
?
&shcy;
?
&shchcy;
?
&hardcy;
?
&ycy;
?
&softcy;
?
&ecy;
?
&yucy;
?
&yacy;
?
&iocy;
?
&djcy;
?
&gjcy;
?
&jukcy;
?
&dscy;
?
&iukcy;
?
&yicy;
?
&jsercy;
?
&ljcy;
?
&njcy;
?
&tshcy;
?
&kjcy;
?
&ubrcy;
?
&dzcy;
 
&ensp;
 
&emsp;
 
&emsp13;
 
&emsp14;
 
&numsp;
 
&puncsp;
 
&thinsp; &ThinSpace;
 
&hairsp; &VeryThinSpace;
?
&ZeroWidthSpace; &NegativeVeryThinSpace; &NegativeThinSpace; &NegativeMediumSpace; &NegativeThickSpace;
?
&zwnj;
?
&zwj;
?
&lrm;
?
&rlm;
-
&hyphen; &dash;
–
&ndash;
—
&mdash;
-
&horbar;
?
&Verbar; &Vert;
‘
&lsquo; &OpenCurlyQuote;
’
&rsquo; &rsquor; &CloseCurlyQuote;
‚
&lsquor; &sbquo;
“
&ldquo; &OpenCurlyDoubleQuote;
”
&rdquo; &rdquor; &CloseCurlyDoubleQuote;
„
&ldquor; &bdquo;
†
&dagger;
‡
&Dagger; &ddagger;
•
&bull; &bullet;
?
&nldr;
…
&hellip; &mldr;
‰
&permil;
?
&pertenk;
'
&prime;
"
&Prime;
?
&tprime;
`
&bprime; &backprime;
‹
&lsaquo;
›
&rsaquo;
?
&oline;
?
&caret;
?
&hybull;
/
&frasl;
?
&bsemi;
?
&qprime;
?
&MediumSpace;
?
&NoBreak;
?
&ApplyFunction; &af;
?
&InvisibleTimes; &it;
?
&InvisibleComma; &ic;
€
&euro;
?
&tdot; &TripleDot;
?
&DotDot;
C
&Copf; &complexes;
?
&incare;
g
&gscr;
H
&hamilt; &HilbertSpace; &Hscr;
H
&Hfr; &Poincareplane;
H
&quaternions; &Hopf;
h
&planckh;
?
&planck; &hbar; &plankv; &hslash;
I
&Iscr; &imagline;
I
&image; &Im; &imagpart; &Ifr;
L
&Lscr; &lagran; &Laplacetrf;
l
&ell;
N
&Nopf; &naturals;
?
&numero;
?
&copysr;
P
&weierp; &wp;
P
&Popf; &primes;
Q
&rationals; &Qopf;
R
&Rscr; &realine;
R
&real; &Re; &realpart; &Rfr;
R
&reals; &Ropf;
?
&rx;
™
&trade; &TRADE;
Z
&integers; &Zopf;
?
&ohm;
?
&mho;
Z
&Zfr; &zeetrf;
?
&iiota;
Å
&angst;
B
&bernou; &Bernoullis; &Bscr;
C
&Cfr; &Cayleys;
e
&escr;
E
&Escr; &expectation;
F
&Fscr; &Fouriertrf;
M
&phmmat; &Mellintrf; &Mscr;
o
&order; &orderof; &oscr;
?
&alefsym; &aleph;
?
&beth;
?
&gimel;
?
&daleth;
?
&CapitalDifferentialD; &DD;
?
&DifferentialD; &dd;
?
&ExponentialE; &exponentiale; &ee;
?
&ImaginaryI; &ii;
?
&frac13;
?
&frac23;
?
&frac15;
?
&frac25;
?
&frac35;
?
&frac45;
?
&frac16;
?
&frac56;
?
&frac18;
?
&frac38;
?
&frac58;
?
&frac78;
?
&larr; &leftarrow; &LeftArrow; &slarr; &ShortLeftArrow;
?
&uarr; &uparrow; &UpArrow; &ShortUpArrow;
?
&rarr; &rightarrow; &RightArrow; &srarr; &ShortRightArrow;
?
&darr; &downarrow; &DownArrow; &ShortDownArrow;
?
&harr; &leftrightarrow; &LeftRightArrow;
?
&varr; &updownarrow; &UpDownArrow;
?
&nwarr; &UpperLeftArrow; &nwarrow;
?
&nearr; &UpperRightArrow; &nearrow;
?
&searr; &searrow; &LowerRightArrow;
?
&swarr; &swarrow; &LowerLeftArrow;
?
&nlarr; &nleftarrow;
?
&nrarr; &nrightarrow;
?
&rarrw; &rightsquigarrow;
?
&Larr; &twoheadleftarrow;
?
&Uarr;
?
&Rarr; &twoheadrightarrow;
?
&Darr;
?
&larrtl; &leftarrowtail;
?
&rarrtl; &rightarrowtail;
?
&LeftTeeArrow; &mapstoleft;
?
&UpTeeArrow; &mapstoup;
?
&map; &RightTeeArrow; &mapsto;
?
&DownTeeArrow; &mapstodown;
?
&larrhk; &hookleftarrow;
?
&rarrhk; &hookrightarrow;
?
&larrlp; &looparrowleft;
?
&rarrlp; &looparrowright;
?
&harrw; &leftrightsquigarrow;
?
&nharr; &nleftrightarrow;
?
&lsh; &Lsh;
?
&rsh; &Rsh;
?
&ldsh;
?
&rdsh;
?
&crarr;
?
&cularr; &curvearrowleft;
?
&curarr; &curvearrowright;
?
&olarr; &circlearrowleft;
?
&orarr; &circlearrowright;
?
&lharu; &LeftVector; &leftharpoonup;
?
&lhard; &leftharpoondown; &DownLeftVector;
?
&uharr; &upharpoonright; &RightUpVector;
?
&uharl; &upharpoonleft; &LeftUpVector;
?
&rharu; &RightVector; &rightharpoonup;
?
&rhard; &rightharpoondown; &DownRightVector;
?
&dharr; &RightDownVector; &downharpoonright;
?
&dharl; &LeftDownVector; &downharpoonleft;
?
&rlarr; &rightleftarrows; &RightArrowLeftArrow;
?
&udarr; &UpArrowDownArrow;
?
&lrarr; &leftrightarrows; &LeftArrowRightArrow;
?
&llarr; &leftleftarrows;
?
&uuarr; &upuparrows;
?
&rrarr; &rightrightarrows;
?
&ddarr; &downdownarrows;
?
&lrhar; &ReverseEquilibrium; &leftrightharpoons;
?
&rlhar; &rightleftharpoons; &Equilibrium;
?
&nlArr; &nLeftarrow;
?
&nhArr; &nLeftrightarrow;
?
&nrArr; &nRightarrow;
?
&lArr; &Leftarrow; &DoubleLeftArrow;
?
&uArr; &Uparrow; &DoubleUpArrow;
?
&rArr; &Rightarrow; &Implies; &DoubleRightArrow;
?
&dArr; &Downarrow; &DoubleDownArrow;
?
&hArr; &Leftrightarrow; &DoubleLeftRightArrow; &iff;
?
&vArr; &Updownarrow; &DoubleUpDownArrow;
?
&nwArr;
?
&neArr;
?
&seArr;
?
&swArr;
?
&lAarr; &Lleftarrow;
?
&rAarr; &Rrightarrow;
?
&zigrarr;
?
&larrb; &LeftArrowBar;
?
&rarrb; &RightArrowBar;
?
&duarr; &DownArrowUpArrow;
?
&loarr;
?
&roarr;
?
&hoarr;
?
&forall; &ForAll;
?
&comp; &complement;
?
&part; &PartialD;
?
&exist; &Exists;
?
&nexist; &NotExists; &nexists;
Ø
&empty; &emptyset; &emptyv; &varnothing;
?
&nabla; &Del;
?
&isin; &isinv; &Element; &in;
?
&notin; &NotElement; &notinva;
?
&niv; &ReverseElement; &ni; &SuchThat;
?
&notni; &notniva; &NotReverseElement;
?
&prod; &Product;
?
&coprod; &Coproduct;
?
&sum; &Sum;
-
&minus;
±
&mnplus; &mp; &MinusPlus;
?
&plusdo; &dotplus;
\
&setmn; &setminus; &Backslash; &ssetmn; &smallsetminus;
*
&lowast;
°
&compfn; &SmallCircle;
v
&radic; &Sqrt;
?
&prop; &propto; &Proportional; &vprop; &varpropto;
8
&infin;
?
&angrt;
?
&ang; &angle;
?
&angmsd; &measuredangle;
?
&angsph;
|
&mid; &VerticalBar; &smid; &shortmid;
?
&nmid; &NotVerticalBar; &nsmid; &nshortmid;
?
&par; &parallel; &DoubleVerticalBar; &spar; &shortparallel;
?
&npar; &nparallel; &NotDoubleVerticalBar; &nspar; &nshortparallel;
?
&and; &wedge;
?
&or; &vee;
n
&cap;
?
&cup;
?
&int; &Integral;
?
&Int;
?
&tint; &iiint;
?
&conint; &oint; &ContourIntegral;
?
&Conint; &DoubleContourIntegral;
?
&Cconint;
?
&cwint;
?
&cwconint; &ClockwiseContourIntegral;
?
&awconint; &CounterClockwiseContourIntegral;
?
&there4; &therefore; &Therefore;
?
&becaus; &because; &Because;
:
&ratio;
?
&Colon; &Proportion;
?
&minusd; &dotminus;
?
&mDDot;
?
&homtht;
~
&sim; &Tilde; &thksim; &thicksim;
?
&bsim; &backsim;
?
&ac; &mstpos;
?
&acd;
?
&wreath; &VerticalTilde; &wr;
?
&nsim; &NotTilde;
?
&esim; &EqualTilde; &eqsim;
?
&sime; &TildeEqual; &simeq;
?
&nsime; &nsimeq; &NotTildeEqual;
?
&cong; &TildeFullEqual;
?
&simne;
?
&ncong; &NotTildeFullEqual;
˜
&asymp; &ap; &TildeTilde; &approx; &thkap; &thickapprox;
?
&nap; &NotTildeTilde; &napprox;
?
&ape; &approxeq;
?
&apid;
?
&bcong; &backcong;
?
&asympeq; &CupCap;
?
&bump; &HumpDownHump; &Bumpeq;
?
&bumpe; &HumpEqual; &bumpeq;
?
&esdot; &DotEqual; &doteq;
?
&eDot; &doteqdot;
?
&efDot; &fallingdotseq;
?
&erDot; &risingdotseq;
?
&colone; &coloneq; &Assign;
?
&ecolon; &eqcolon;
?
&ecir; &eqcirc;
?
&cire; &circeq;
?
&wedgeq;
?
&veeeq;
?
&trie; &triangleq;
?
&equest; &questeq;
?
&ne; &NotEqual;
=
&equiv; &Congruent;
?
&nequiv; &NotCongruent;
=
&le; &leq;
=
&ge; &GreaterEqual; &geq;
?
&lE; &LessFullEqual; &leqq;
?
&gE; &GreaterFullEqual; &geqq;
?
&lnE; &lneqq;
?
&gnE; &gneqq;
«
&Lt; &NestedLessLess; &ll;
»
&Gt; &NestedGreaterGreater; &gg;
?
&twixt; &between;
?
&NotCupCap;
?
&nlt; &NotLess; &nless;
?
&ngt; &NotGreater; &ngtr;
?
&nle; &NotLessEqual; &nleq;
?
&nge; &NotGreaterEqual; &ngeq;
?
&lsim; &LessTilde; &lesssim;
?
&gsim; &gtrsim; &GreaterTilde;
?
&nlsim; &NotLessTilde;
?
&ngsim; &NotGreaterTilde;
?
&lg; &lessgtr; &LessGreater;
?
&gl; &gtrless; &GreaterLess;
?
&ntlg; &NotLessGreater;
?
&ntgl; &NotGreaterLess;
?
&pr; &Precedes; &prec;
?
&sc; &Succeeds; &succ;
?
&prcue; &PrecedesSlantEqual; &preccurlyeq;
?
&sccue; &SucceedsSlantEqual; &succcurlyeq;
?
&prsim; &precsim; &PrecedesTilde;
?
&scsim; &succsim; &SucceedsTilde;
?
&npr; &nprec; &NotPrecedes;
?
&nsc; &nsucc; &NotSucceeds;
?
&sub; &subset;
?
&sup; &supset; &Superset;
?
&nsub;
?
&nsup;
?
&sube; &SubsetEqual; &subseteq;
?
&supe; &supseteq; &SupersetEqual;
?
&nsube; &nsubseteq; &NotSubsetEqual;
?
&nsupe; &nsupseteq; &NotSupersetEqual;
?
&subne; &subsetneq;
?
&supne; &supsetneq;
?
&cupdot;
?
&uplus; &UnionPlus;
?
&sqsub; &SquareSubset; &sqsubset;
?
&sqsup; &SquareSuperset; &sqsupset;
?
&sqsube; &SquareSubsetEqual; &sqsubseteq;
?
&sqsupe; &SquareSupersetEqual; &sqsupseteq;
?
&sqcap; &SquareIntersection;
?
&sqcup; &SquareUnion;
?
&oplus; &CirclePlus;
?
&ominus; &CircleMinus;
?
&otimes; &CircleTimes;
?
&osol;
?
&odot; &CircleDot;
?
&ocir; &circledcirc;
?
&oast; &circledast;
?
&odash; &circleddash;
?
&plusb; &boxplus;
?
&minusb; &boxminus;
?
&timesb; &boxtimes;
?
&sdotb; &dotsquare;
?
&vdash; &RightTee;
?
&dashv; &LeftTee;
?
&top; &DownTee;
?
&bottom; &bot; &perp; &UpTee;
?
&models;
?
&vDash; &DoubleRightTee;
?
&Vdash;
?
&Vvdash;
?
&VDash;
?
&nvdash;
?
&nvDash;
?
&nVdash;
?
&nVDash;
?
&prurel;
?
&vltri; &vartriangleleft; &LeftTriangle;
?
&vrtri; &vartriangleright; &RightTriangle;
?
&ltrie; &trianglelefteq; &LeftTriangleEqual;
?
&rtrie; &trianglerighteq; &RightTriangleEqual;
?
&origof;
?
&imof;
?
&mumap; &multimap;
?
&hercon;
?
&intcal; &intercal;
?
&veebar;
?
&barvee;
?
&angrtvb;
?
&lrtri;
?
&xwedge; &Wedge; &bigwedge;
?
&xvee; &Vee; &bigvee;
?
&xcap; &Intersection; &bigcap;
?
&xcup; &Union; &bigcup;
?
&diam; &diamond; &Diamond;
·
&sdot;
?
&sstarf; &Star;
?
&divonx; &divideontimes;
?
&bowtie;
?
&ltimes;
?
&rtimes;
?
&lthree; &leftthreetimes;
?
&rthree; &rightthreetimes;
?
&bsime; &backsimeq;
?
&cuvee; &curlyvee;
?
&cuwed; &curlywedge;
?
&Sub; &Subset;
?
&Sup; &Supset;
?
&Cap;
?
&Cup;
?
&fork; &pitchfork;
?
&epar;
?
&ltdot; &lessdot;
?
&gtdot; &gtrdot;
?
&Ll;
?
&Gg; &ggg;
?
&leg; &LessEqualGreater; &lesseqgtr;
?
&gel; &gtreqless; &GreaterEqualLess;
?
&cuepr; &curlyeqprec;
?
&cuesc; &curlyeqsucc;
?
&nprcue; &NotPrecedesSlantEqual;
?
&nsccue; &NotSucceedsSlantEqual;
?
&nsqsube; &NotSquareSubsetEqual;
?
&nsqsupe; &NotSquareSupersetEqual;
?
&lnsim;
?
&gnsim;
?
&prnsim; &precnsim;
?
&scnsim; &succnsim;
?
&nltri; &ntriangleleft; &NotLeftTriangle;
?
&nrtri; &ntriangleright; &NotRightTriangle;
?
&nltrie; &ntrianglelefteq; &NotLeftTriangleEqual;
?
&nrtrie; &ntrianglerighteq; &NotRightTriangleEqual;
?
&vellip;
?
&ctdot;
?
&utdot;
?
&dtdot;
?
&disin;
?
&isinsv;
?
&isins;
?
&isindot;
?
&notinvc;
?
&notinvb;
?
&isinE;
?
&nisd;
?
&xnis;
?
&nis;
?
&notnivc;
?
&notnivb;
?
&barwed; &barwedge;
?
&Barwed; &doublebarwedge;
?
&lceil; &LeftCeiling;
?
&rceil; &RightCeiling;
?
&lfloor; &LeftFloor;
?
&rfloor; &RightFloor;
?
&drcrop;
?
&dlcrop;
?
&urcrop;
?
&ulcrop;
¬
&bnot;
?
&profline;
?
&profsurf;
?
&telrec;
?
&target;
?
&ulcorn; &ulcorner;
?
&urcorn; &urcorner;
?
&dlcorn; &llcorner;
?
&drcorn; &lrcorner;
?
&frown; &sfrown;
?
&smile; &ssmile;
?
&cylcty;
?
&profalar;
?
&topbot;
?
&ovbar;
?
&solbar;
?
&angzarr;
?
&lmoust; &lmoustache;
?
&rmoust; &rmoustache;
?
&tbrk; &OverBracket;
?
&bbrk; &UnderBracket;
?
&bbrktbrk;
?
&OverParenthesis;
?
&UnderParenthesis;
?
&OverBrace;
?
&UnderBrace;
?
&trpezium;
?
&elinters;
?
&blank;
?
&oS; &circledS;
-
&boxh; &HorizontalLine;
¦
&boxv;
+
&boxdr;
+
&boxdl;
+
&boxur;
+
&boxul;
+
&boxvr;
¦
&boxvl;
-
&boxhd;
-
&boxhu;
+
&boxvh;
-
&boxH;
¦
&boxV;
+
&boxdR;
+
&boxDr;
+
&boxDR;
+
&boxdL;
+
&boxDl;
+
&boxDL;
+
&boxuR;
+
&boxUr;
+
&boxUR;
+
&boxuL;
+
&boxUl;
+
&boxUL;
¦
&boxvR;
¦
&boxVr;
¦
&boxVR;
¦
&boxvL;
¦
&boxVl;
¦
&boxVL;
-
&boxHd;
-
&boxhD;
-
&boxHD;
-
&boxHu;
-
&boxhU;
-
&boxHU;
+
&boxvH;
+
&boxVh;
+
&boxVH;
¯
&uhblk;
_
&lhblk;
¦
&block;
¦
&blk14;
¦
&blk12;
¦
&blk34;
?
&squ; &square; &Square;
?
&squf; &squarf; &blacksquare; &FilledVerySmallSquare;
?
&EmptyVerySmallSquare;
?
&rect;
?
&marker;
?
&fltns;
?
&xutri; &bigtriangleup;
?
&utrif; &blacktriangle;
?
&utri; &triangle;
?
&rtrif; &blacktriangleright;
?
&rtri; &triangleright;
?
&xdtri; &bigtriangledown;
?
&dtrif; &blacktriangledown;
?
&dtri; &triangledown;
?
&ltrif; &blacktriangleleft;
?
&ltri; &triangleleft;
?
&loz; &lozenge;
?
&cir;
?
&tridot;
?
&xcirc; &bigcirc;
?
&ultri;
?
&urtri;
?
&lltri;
?
&EmptySmallSquare;
?
&FilledSmallSquare;
?
&starf; &bigstar;
?
&star;
?
&phone;
?
&female;
?
&male;
?
&spades; &spadesuit;
?
&clubs; &clubsuit;
?
&hearts; &heartsuit;
?
&diams; &diamondsuit;
?
&sung;
?
&flat;
?
&natur; &natural;
?
&sharp;
?
&check; &checkmark;
?
&cross;
?
&malt; &maltese;
?
&sext;
|
&VerticalSeparator;
?
&lbbrk;
?
&rbbrk;
?
&lobrk; &LeftDoubleBracket;
?
&robrk; &RightDoubleBracket;
?
&lang; &LeftAngleBracket; &langle;
?
&rang; &RightAngleBracket; &rangle;
?
&Lang;
?
&Rang;
?
&loang;
?
&roang;
?
&xlarr; &longleftarrow; &LongLeftArrow;
?
&xrarr; &longrightarrow; &LongRightArrow;
?
&xharr; &longleftrightarrow; &LongLeftRightArrow;
?
&xlArr; &Longleftarrow; &DoubleLongLeftArrow;
?
&xrArr; &Longrightarrow; &DoubleLongRightArrow;
?
&xhArr; &Longleftrightarrow; &DoubleLongLeftRightArrow;
?
&xmap; &longmapsto;
?
&dzigrarr;
?
&nvlArr;
?
&nvrArr;
?
&nvHarr;
?
&Map;
?
&lbarr;
?
&rbarr; &bkarow;
?
&lBarr;
?
&rBarr; &dbkarow;
?
&RBarr; &drbkarow;
?
&DDotrahd;
?
&UpArrowBar;
?
&DownArrowBar;
?
&Rarrtl;
?
&latail;
?
&ratail;
?
&lAtail;
?
&rAtail;
?
&larrfs;
?
&rarrfs;
?
&larrbfs;
?
&rarrbfs;
?
&nwarhk;
?
&nearhk;
?
&searhk; &hksearow;
?
&swarhk; &hkswarow;
?
&nwnear;
?
&nesear; &toea;
?
&seswar; &tosa;
?
&swnwar;
?
&rarrc;
?
&cudarrr;
?
&ldca;
?
&rdca;
?
&cudarrl;
?
&larrpl;
?
&curarrm;
?
&cularrp;
?
&rarrpl;
?
&harrcir;
?
&Uarrocir;
?
&lurdshar;
?
&ldrushar;
?
&LeftRightVector;
?
&RightUpDownVector;
?
&DownLeftRightVector;
?
&LeftUpDownVector;
?
&LeftVectorBar;
?
&RightVectorBar;
?
&RightUpVectorBar;
?
&RightDownVectorBar;
?
&DownLeftVectorBar;
?
&DownRightVectorBar;
?
&LeftUpVectorBar;
?
&LeftDownVectorBar;
?
&LeftTeeVector;
?
&RightTeeVector;
?
&RightUpTeeVector;
?
&RightDownTeeVector;
?
&DownLeftTeeVector;
?
&DownRightTeeVector;
?
&LeftUpTeeVector;
?
&LeftDownTeeVector;
?
&lHar;
?
&uHar;
?
&rHar;
?
&dHar;
?
&luruhar;
?
&ldrdhar;
?
&ruluhar;
?
&rdldhar;
?
&lharul;
?
&llhard;
?
&rharul;
?
&lrhard;
?
&udhar; &UpEquilibrium;
?
&duhar; &ReverseUpEquilibrium;
?
&RoundImplies;
?
&erarr;
?
&simrarr;
?
&larrsim;
?
&rarrsim;
?
&rarrap;
?
&ltlarr;
?
&gtrarr;
?
&subrarr;
?
&suplarr;
?
&lfisht;
?
&rfisht;
?
&ufisht;
?
&dfisht;
?
&lopar;
?
&ropar;
?
&lbrke;
?
&rbrke;
?
&lbrkslu;
?
&rbrksld;
?
&lbrksld;
?
&rbrkslu;
?
&langd;
?

Not fully, pls track the link for fully document.

Creating a blurring overlay view

This answer is based on Mitja Semolic's excellent earlier answer. I've converted it to swift 3, added an explanation to what's happening in coments, made it an extension of a UIViewController so any VC can call it at will, added an unblurred view to show selective application, and added a completion block so that the calling view controller can do whatever it wants at the completion of the blur.

    import UIKit
//This extension implements a blur to the entire screen, puts up a HUD and then waits and dismisses the view.
    extension UIViewController {
        func blurAndShowHUD(duration: Double, message: String, completion: @escaping () -> Void) { //with completion block
            //1. Create the blur effect & the view it will occupy
            let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.light)
            let blurEffectView = UIVisualEffectView()//(effect: blurEffect)
            blurEffectView.frame = self.view.bounds
            blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]

        //2. Add the effect view to the main view
            self.view.addSubview(blurEffectView)
        //3. Create the hud and add it to the main view
        let hud = HudView.getHUD(view: self.view, withMessage: message)
        self.view.addSubview(hud)
        //4. Begin applying the blur effect to the effect view
        UIView.animate(withDuration: 0.01, animations: {
            blurEffectView.effect = blurEffect
        })
        //5. Halt the blur effects application to achieve the desired blur radius
        self.view.pauseAnimationsInThisView(delay: 0.004)
        //6. Remove the view (& the HUD) after the completion of the duration
        DispatchQueue.main.asyncAfter(deadline: .now() + duration) {
            blurEffectView.removeFromSuperview()
            hud.removeFromSuperview()
            self.view.resumeAnimationsInThisView()
            completion()
        }
    }
}

extension UIView {
    public func pauseAnimationsInThisView(delay: Double) {
        let time = delay + CFAbsoluteTimeGetCurrent()
        let timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, time, 0, 0, 0, { timer in
            let layer = self.layer
            let pausedTime = layer.convertTime(CACurrentMediaTime(), from: nil)
            layer.speed = 0.0
            layer.timeOffset = pausedTime
        })
        CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, CFRunLoopMode.commonModes)
    }
    public func resumeAnimationsInThisView() {
        let pausedTime  = layer.timeOffset

        layer.speed = 1.0
        layer.timeOffset = 0.0
        layer.beginTime = layer.convertTime(CACurrentMediaTime(), from: nil) - pausedTime
    }
}

I've confirmed that it works with both iOS 10.3.1 and iOS 11

Using new line(\n) in string and rendering the same in HTML

You could use a pre tag instead of a div. This would automatically display your \n's in the correct way.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
         var display_txt = "1st line text" +"\n" + "2nd line text";
         $('#somediv').html(display_txt).css("color", "green");
});
</script>
</head>
<body>

<pre>
<p id="somediv"></p>
</pre>

</body>
</html>

Java ArrayList clear() function

data.removeAll(data); will do the work, I think.

Get the latest record from mongodb collection

This will give you one last document for a collection

db.collectionName.findOne({}, {sort:{$natural:-1}})

$natural:-1 means order opposite of the one that records are inserted in.

Edit: For all the downvoters, above is a Mongoose syntax, mongo CLI syntax is: db.collectionName.find({}).sort({$natural:-1}).limit(1)

What is the command to exit a Console application in C#?

You can use Environment.Exit(0); and Application.Exit

Environment.Exit(0) is cleaner.

Select all from table with Laravel and Eloquent

How to get all data from database to view using laravel, i hope this solution would be helpful for the beginners.

Inside your controller

public function get(){
        $types = select::all();
        return view('selectview')->with('types', $types);}

Import data model inside your controller, in my application the data model named as select.

use App\Select;

Inclusive of both my controller looks something like this

use App\Select;
class SelectController extends Controller{                             
    public function get(){
    $types = select::all();
    return view('selectview')->with('types', $types);}

select model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Select extends Model
{
    protected $fillable = [
        'name', 'email','phone','radio1','service',
    ];


    protected $table = 'selectdata';
    public $timestamps = false;
}

inside router

Route::get('/selectview', 'SelectController@get');

selectview.blade.php

@foreach($types as $type)
    <ul>
    <li>{{ $type->name }}</li>
    </ul>

    @endforeach

How to run iPhone emulator WITHOUT starting Xcode?

You can get it to launch via spotlight if you create an Automator launcher for it:

  1. Open Automator.app
  2. Choose type of Application
  3. Select Actions > Library > Utilities > Launch Application
  4. Open the dropdown of applications that can be launched and choose Other
  5. You can't directly select the Simulator app because it's inside the Xcode.app package. So instead you'll have to navigate to it in a separate Finder window and drag it onto the file selector window. It will be at one of the following paths depending on your version of Xcode (oldest to newest):
    • /Applications/Xcode.app/Contents/Developer/iOS Simulator.app
    • /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Applications/iOS Simulator.app
    • /Applications/Xcode.app/Contents/Developer/Applications/Simulator.app
  6. Finally, save this Automator app in your applications folder as iOS Simulator.app

Create Automator app

To get a nice icon for the Automator app you just made, you can do the following:

  1. Right click iOS Simulator.app and choose Get Info
  2. Click the icon in the upper left corner and do Cmd-C to copy it
  3. Right click your Automator app and choose Get Info
  4. Click the icon in the upper left corner and do Cmd-V to paste

Copy icon

How can I pair socks from a pile efficiently?

List<Sock> UnSearchedSocks = getAllSocks();
List<Sock> UnMatchedSocks = new list<Sock>();
List<PairOfSocks> PairedSocks = new list<PairOfSocks>();

foreach (Sock newSock in UnsearchedSocks)
{
  Sock MatchedSock = null;
  foreach(Sock UnmatchedSock in UnmatchedSocks)
  {
    if (UnmatchedSock.isPairOf(newSock))
    {
      MatchedSock = UnmatchedSock;
      break;
    }
  }
  if (MatchedSock != null)
  {
    UnmatchedSocks.remove(MatchedSock);
    PairedSocks.Add(new PairOfSocks(MatchedSock, NewSock));
  }
  else
  {
    UnmatchedSocks.Add(NewSock);
  }
}

How to convert byte array to string and vice versa?

This works fine for me:

String cd="Holding some value";

Converting from string to byte[]:

byte[] cookie = new sun.misc.BASE64Decoder().decodeBuffer(cd);

Converting from byte[] to string:

cd = new sun.misc.BASE64Encoder().encode(cookie);

iOS 7 App Icons, Launch images And Naming Convention While Keeping iOS 6 Icons

Absolutely Asset Catalog is you answer, it removes the need to follow naming conventions when you are adding or updating your app icons.

Below are the steps to Migrating an App Icon Set or Launch Image Set From Apple:

1- In the project navigator, select your target.

2- Select the General pane, and scroll to the App Icons section.

enter image description here

3- Specify an image in the App Icon table by clicking the folder icon on the right side of the image row and selecting the image file in the dialog that appears.

enter image description here

4-Migrate the images in the App Icon table to an asset catalog by clicking the Use Asset Catalog button, selecting an asset catalog from the popup menu, and clicking the Migrate button.

enter image description here

Alternatively, you can create an empty app icon set by choosing Editor > New App Icon, and add images to the set by dragging them from the Finder or by choosing Editor > Import.

How to get my project path?

var requiredPath = Path.GetDirectoryName(Path.GetDirectoryName(
System.IO.Path.GetDirectoryName( 
      System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase )));

Python requests - print entire http request (raw)?

A fork of @AntonioHerraizS answer (HTTP version missing as stated in comments)


Use this code to get a string representing the raw HTTP packet without sending it:

import requests


def get_raw_request(request):
    request = request.prepare() if isinstance(request, requests.Request) else request
    headers = '\r\n'.join(f'{k}: {v}' for k, v in request.headers.items())
    body = '' if request.body is None else request.body.decode() if isinstance(request.body, bytes) else request.body
    return f'{request.method} {request.path_url} HTTP/1.1\r\n{headers}\r\n\r\n{body}'


headers = {'User-Agent': 'Test'}
request = requests.Request('POST', 'https://stackoverflow.com', headers=headers, json={"hello": "world"})
raw_request = get_raw_request(request)
print(raw_request)

Result:

POST / HTTP/1.1
User-Agent: Test
Content-Length: 18
Content-Type: application/json

{"hello": "world"}

Can also print the request in the response object

r = requests.get('https://stackoverflow.com')
raw_request = get_raw_request(r.request)
print(raw_request)

Making a Simple Ajax call to controller in asp.net mvc

After the update you have done,

  1. its first calling the FirstAjax action with default HttpGet request and renders the blank Html view . (Earlier you were not having it)
  2. later on loading of DOM elements of that view your Ajax call get fired and displays alert.

Earlier you were only returning JSON to browser without rendering any HTML. Now it has a HTML view rendered where it can get your JSON Data.

You can't directly render JSON its plain data not HTML.

How to check for registry value using VbScript

Try this. This script gets current logged in user's name & home directory:

On Error Resume Next

Dim objShell, strTemp
Set objShell = WScript.CreateObject("WScript.Shell")

strTemp = "HKEY_CURRENT_USER\Volatile Environment\USERNAME"
WScript.Echo "Logged in User: " & objShell.RegRead(strTemp) 

strTemp = "HKEY_CURRENT_USER\Volatile Environment\USERPROFILE"
WScript.Echo "User Home: " & objShell.RegRead(strTemp) 

How to check if a variable is set in Bash?

if [[ ${1:+isset} ]]
then echo "It was set and not null." >&2
else echo "It was not set or it was null." >&2
fi

if [[ ${1+isset} ]]
then echo "It was set but might be null." >&2
else echo "It was was not set." >&2
fi

Generic htaccess redirect www to non-www

I am not sure why u want to remove www. But reverse version would be:

# non-www.* -> www.*, if subdomain exist, wont work
RewriteCond %{HTTP_HOST} ^whattimein\.com
RewriteRule ^(.*)$ http://www.whattimein.com/$1 [R=permanent,L]

And advantage of this script is: if u have something like test.whattimein.com or any other (enviroments for developing/testing) it wont redirect U to the original enviroment.

Python append() vs. + operator on lists, why do these give different results?

To explain "why":

The + operation adds the array elements to the original array. The array.append operation inserts the array (or any object) into the end of the original array, which results in a reference to self in that spot (hence the infinite recursion).

The difference here is that the + operation acts specific when you add an array (it's overloaded like others, see this chapter on sequences) by concatenating the element. The append-method however does literally what you ask: append the object on the right-hand side that you give it (the array or any other object), instead of taking its elements.

An alternative

Use extend() if you want to use a function that acts similar to the + operator (as others have shown here as well). It's not wise to do the opposite: to try to mimic append with the + operator for lists (see my earlier link on why).

Little history

For fun, a little history: the birth of the array module in Python in February 1993. it might surprise you, but arrays were added way after sequences and lists came into existence.

Python: call a function from string name

If it's in a class, you can use getattr:

class MyClass(object):
    def install(self):
          print "In install"

method_name = 'install' # set by the command line options
my_cls = MyClass()

method = None
try:
    method = getattr(my_cls, method_name)
except AttributeError:
    raise NotImplementedError("Class `{}` does not implement `{}`".format(my_cls.__class__.__name__, method_name))

method()

or if it's a function:

def install():
       print "In install"

method_name = 'install' # set by the command line options
possibles = globals().copy()
possibles.update(locals())
method = possibles.get(method_name)
if not method:
     raise NotImplementedError("Method %s not implemented" % method_name)
method()

Vertically align text next to an image?

You probably want this:

<div>
   <img style="width:30px; height:30px;">
   <span style="vertical-align:50%; line-height:30px;">Didn't work.</span>
</div>

As others have suggested, try vertical-align on the image:

<div>
   <img style="width:30px; height:30px; vertical-align:middle;">
   <span>Didn't work.</span>
</div>

CSS isn't annoying. You just don't read the documentation. ;P

List all liquibase sql types

For checking type conversions in version 3, you can go to their github and check into the different liquibase types and check the method toDatabaseDataType. For example, for Boolean, you can check here:

https://github.com/liquibase/liquibase/blob/master/liquibase-core/src/main/java/liquibase/datatype/core/BooleanType.java

For version 2.0.x, the conversion seems to be into database specific classes. For example, for Mysql:

https://github.com/liquibase/liquibase/blob/2_0_x/liquibase-core/src/main/java/liquibase/database/typeconversion/core/MySQLTypeConverter.java

How to set minDate to current date in jQuery UI Datepicker?

You can specify minDate as today by adding minDate: 0 to the options.

$("input.DateFrom").datepicker({
    minDate: 0,
    ...
});

Demo: http://jsfiddle.net/2CZtV/

Docs: http://jqueryui.com/datepicker/#min-max

Posting array from form

Why are you sending it through a post if you already have it on the server (PHP) side?

Why not just save the array to the $_SESSION variable so you can use it when the form gets submitted, that might make it more "secure" since then the client cannot change the variables by editing the source.

It will depend upon how you really want to do.

Cannot install Aptana Studio 3.6 on Windows

If your issue is related to a failed Windows install, and you are receiving a message related to installer _jsnode_windows.msi CRC error:

Aptana Studio (Aptana Studio 3, build: 3.6.1.201410201044) currently requires Nodejs 0.5.XX-0.11.xx

Even though the current release of nodejs seems to be 5.X.X . Apparently there will be a new release in Nov 2015 that corrects this defect.

Pre-installing x0.10.36-x64 allowed me to proceed with a successful install. If version numbers can be believed, this seems to be an ancient release of nodejs, but hey - I saw a very impressive demo of Aptana Studio and really wanted to install it. :-)

I also pre-installed GIT for windows, but I'm not sure if that was necessary or not.

How to add an object to an ArrayList in Java

You need to use the new operator when creating the object

Contacts.add(new Data(name, address, contact)); // Creating a new object and adding it to list - single step

or else

Data objt = new Data(name, address, contact); // Creating a new object
Contacts.add(objt); // Adding it to the list

and your constructor shouldn't contain void. Else it becomes a method in your class.

public Data(String n, String a, String c) { // Constructor has the same name as the class and no return type as such

NULL value for int in Update statement

Assuming the column is set to support NULL as a value:

UPDATE YOUR_TABLE
   SET column = NULL

Be aware of the database NULL handling - by default in SQL Server, NULL is an INT. So if the column is a different data type you need to CAST/CONVERT NULL to the proper data type:

UPDATE YOUR_TABLE
   SET column = CAST(NULL AS DATETIME)

...assuming column is a DATETIME data type in the example above.

Hive ParseException - cannot recognize input near 'end' 'string'

I solved this issue by doing like that:

insert into my_table(my_field_0, ..., my_field_n) values(my_value_0, ..., my_value_n)

Delete rows containing specific strings in R

You can use this function if it's multiple string df[!grepl("REVERSE|GENJJS", df$Name),]

how to use substr() function in jquery?

If you want to extract from a tag then

$('.dep_buttons').text().substr(0,25)

With the mouseover event,

$(this).text($(this).text().substr(0, 25));

The above will extract the text of a tag, then extract again assign it back.

Migration: Cannot add foreign key constraint

Another cause could be the DB engine types. Laravel by default uses MyISAM engine. So if you need to enforce foreign key reference checks, you should use InnoDB as your engine.

This setting is in your config/database.php file. Change the engine to 'engine' => 'InnoDB'

Also if you're trying to do this to an existing table, change the engine by using

DB::statement("ALTER TABLE `{$tableName}` ENGINE = 'InnoDB'");

batch script - read line by line

The "call" solution has some problems.

It fails with many different contents, as the parameters of a CALL are parsed twice by the parser.
These lines will produce more or less strange problems

one
two%222
three & 333
four=444
five"555"555"
six"&666
seven!777^!
the next line is empty

the end

Therefore you shouldn't use the value of %%a with a call, better move it to a variable and then call a function with only the name of the variable.

@echo off
SETLOCAL DisableDelayedExpansion
FOR /F "usebackq delims=" %%a in (`"findstr /n ^^ t.txt"`) do (
    set "myVar=%%a"
    call :processLine myVar
)
goto :eof

:processLine
SETLOCAL EnableDelayedExpansion
set "line=!%1!"
set "line=!line:*:=!"
echo(!line!
ENDLOCAL
goto :eof

Deny direct access to all .php files except index.php

An oblique answer to the question is to write all the code as classes, apart from the index.php files, which are then the only points of entry. PHP files that contain classes will not cause anything to happen, even if they are invoked directly through Apache.

A direct answer is to include the following in .htaccess:

<FilesMatch "\.php$">
    Order Allow,Deny
    Deny from all
</FilesMatch>
<FilesMatch "index[0-9]?\.php$">
    Order Allow,Deny
    Allow from all
</FilesMatch>

This will allow any file like index.php, index2.php etc to be accessed, but will refuse access of any kind to other .php files. It will not affect other file types.

Linux: command to open URL in default browser

I think a combination of xdg-open as described by shellholic and - if it fails - the solution to finding a browser using the which command as described here is probably the best solution.

how to use JSON.stringify and json_decode() properly

jsonText = $_REQUEST['myJSON'];

$decodedText = html_entity_decode($jsonText);

$myArray = json_decode($decodedText, true);`

Which programming languages can be used to develop in Android?

  • At launch, Java was the only officially supported programming language for building distributable third-party Android software.

  • Android Native Development Kit (Android NDK) which will allow developers to build Android software components with C and C++.

  • In addition to delivering support for native code, Google is also extending Android to support popular dynamic scripting languages. Earlier this month, Google launched the Android Scripting Environment (ASE) which allows third-party developers to build simple Android applications with perl, JRuby, Python, LUA and BeanShell. For having idea and usage of ASE, refer this Example link.

  • Scala is also supported. For having examples of Scala, refer these Example link-1 , Example link-2 , Example link-3 .

  • Just now i have referred one Article Here in which i found some useful information as follows:

    1. programming language is Java but bridges from other languages exist (C# .net - Mono, etc).
    2. can run script languages like LUA, Perl, Python, BeanShell, etc.

  • I have read 2nd article at Google Releases 'Simple' Android Programming Language . For example of this, refer this .

  • Just now (2 Aug 2010) i have read an article which describes regarding "Frink Programming language and Calculating Tool for Android", refer this links Link-1 , Link-2

  • On 4-Aug-2010, i have found Regarding RenderScript. Basically, It is said to be a C-like language for high performance graphics programming, which helps you easily write efficient Visual effects and animations in your Android Applications. Its not released yet as it isn't finished.

.ssh/config file for windows (git)

You can use multiple ssh keys on Windows 10 and specify the type of access allowed.

Assuming you have created the ssh secure keys already and they were stored in C:\Users\[User]\.ssh

  1. Open the folder C:\Users\[User]\.ssh

  2. Create the file config (no file extension)

  3. Open the file in a text editor like Notepad, and add these configuration details for the first remote host and user. Keep both CMD and BASH paths or only pick one format. Then copy-and-paste below it for the other host/user combinations and amend as required. Save the file.

    Host [git.domain.com]
    User [user]
    Port [number]
    IdentitiesOnly=yes
    PreferredAuthentications publickey
    PasswordAuthentication no
    # CMD
    IdentityFile C:\Users\[User]\.ssh\[name_of_PRIVATE_key_file]
    # BASH
    IdentityFile /c/Users/[User]/.ssh/[name_of_PRIVATE_key_file]
    
  4. Testing

  • Using Bash (Git for Windows)
    $ ssh -T git@[git.domain.com]
    Welcome to GitLab, @[User]!
    
  • Using Commandline (requires activation of Win 10 OpenSSH Client)
    C:\Users\[User]>ssh -T git@[git.domain.com]
    Welcome to GitLab, @[User]!
    
  1. For troubleshooting use ssh -Tv git@[git.domain.com] (or -Tvv or -Tvvv for higher verbosity levels).

C++ - struct vs. class

1) It is the only difference in C++.

2) POD: plain old data Other classes -> not POD

How to convert the following json string to java object?

No need to go with GSON for this; Jackson can do either plain Maps/Lists:

ObjectMapper mapper = new ObjectMapper();
Map<String,Object> map = mapper.readValue(json, Map.class);

or more convenient JSON Tree:

JsonNode rootNode = mapper.readTree(json);

By the way, there is no reason why you could not actually create Java classes and do it (IMO) more conveniently:

public class Library {
  @JsonProperty("libraryname")
  public String name;

  @JsonProperty("mymusic")
  public List<Song> songs;
}
public class Song {
  @JsonProperty("Artist Name") public String artistName;
  @JsonProperty("Song Name") public String songName;
}

Library lib = mapper.readValue(jsonString, Library.class);

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

This works like charm I did it for Ubuntu 16.04. Full credit to below link as I got it from there. [https://coderwall.com/p/j9btlg/reset-the-mysql-5-7-root-password-in-ubuntu-16-04-lts][1]

Stop MySQL

sudo service mysql stop

Make MySQL service directory. sudo mkdir /var/run/mysqld

Give MySQL user permission to write to the service directory.

sudo chown mysql: /var/run/mysqld

Start MySQL manually, without permission checks or networking.

sudo mysqld_safe --skip-grant-tables --skip-networking &

Log in without a password.

mysql -uroot mysql

Update the password for the root user. make sure at atleast root account gets updated by the below query. make some selection and check the existing values if you like

UPDATE mysql.user SET 
authentication_string=PASSWORD('YOURNEWPASSWORD'), 
plugin='mysql_native_password' WHERE User='root';
EXIT;

Turn off MySQL.

sudo mysqladmin -S /var/run/mysqld/mysqld.sock shutdown

Start the MySQL service normally.

sudo service mysql start

How to clean up R memory (without the need to restart my PC)?

memory.size(max=T) # gives the amount of memory obtained by the OS
[1] 1800
memory.size(max=F) # gives the amount of memory being used
[1] 261.17

Using Paul's example,

m = matrix(runif(10e7), 10000, 1000)

Now

memory.size(max=F)
[1] 1024.18

To clear up the memory

gc()
memory.size(max=F)
[1] 184.86

In other words, the memory should now be clear again. If you loop a code, it is a good idea to add a gc() as the last line of your loop, so that the memory is cleared up before starting the next iteration.

Notification Icon with the new Firebase Cloud Messaging system

My solution is similar to ATom's one, but easier to implement. You don't need to create a class that shadows FirebaseMessagingService completely, you can just override the method that receives the Intent (which is public, at least in version 9.6.1) and take the information to be displayed from the extras. The "hacky" part is that the method name is indeed obfuscated and is gonna change every time you update the Firebase sdk to a new version, but you can look it up quickly by inspecting FirebaseMessagingService with Android Studio and looking for a public method that takes an Intent as the only parameter. In version 9.6.1 it's called zzm. Here's how my service looks like:

public class MyNotificationService extends FirebaseMessagingService {

    public void onMessageReceived(RemoteMessage remoteMessage) {
        // do nothing
    }

    @Override
    public void zzm(Intent intent) {
        Intent launchIntent = new Intent(this, SplashScreenActivity.class);
        launchIntent.setAction(Intent.ACTION_MAIN);
        launchIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* R    equest code */, launchIntent,
                PendingIntent.FLAG_ONE_SHOT);
        Bitmap rawBitmap = BitmapFactory.decodeResource(getResources(),
                R.mipmap.ic_launcher);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_notification)
                .setLargeIcon(rawBitmap)
                .setContentTitle(intent.getStringExtra("gcm.notification.title"))
                .setContentText(intent.getStringExtra("gcm.notification.body"))
                .setAutoCancel(true)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager)     getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
    }
}

How can I build for release/distribution on the Xcode 4?

The short answer is:

  1. choose the iOS scheme from the drop-down near the run button from the menu bar
  2. choose product > archive in the window that pops-up
  3. click 'validate'
  4. upon successful validation, click 'submit'

An explicit value for the identity column in table can only be specified when a column list is used and IDENTITY_INSERT is ON SQL Server

Summary

SQL Server won't let you insert an explicit value in an identity column unless you use a column list. Thus, you have the following options:

  1. Make a column list (either manually or using tools, see below)

OR

  1. make the identity column in tbl_A_archive a regular, non-identity column: If your table is an archive table and you always specify an explicit value for the identity column, why do you even need an identity column? Just use a regular int instead.

Details on Solution 1

Instead of

SET IDENTITY_INSERT archive_table ON;

INSERT INTO archive_table
  SELECT *
  FROM source_table;

SET IDENTITY_INSERT archive_table OFF;

you need to write

SET IDENTITY_INSERT archive_table ON;

INSERT INTO archive_table (field1, field2, ...)
  SELECT field1, field2, ...
  FROM source_table;

SET IDENTITY_INSERT archive_table OFF;

with field1, field2, ... containing the names of all columns in your tables. If you want to auto-generate that list of columns, have a look at Dave's answer or Andomar's answer.


Details on Solution 2

Unfortunately, it is not possible to just "change the type" of an identity int column to a non-identity int column. Basically, you have the following options:

  • If the archive table does not contain data yet, drop the column and add a new one without identity.

OR

  • Use SQL Server Management Studio to set the Identity Specification/(Is Identity) property of the identity column in your archive table to No. Behind the scenes, this will create a script to re-create the table and copy existing data, so, to do that, you will also need to unset Tools/Options/Designers/Table and Database Designers/Prevent saving changes that require table re-creation.

OR

How to print the array?

There is no .length property in C. The .length property can only be applied to arrays in object oriented programming (OOP) languages. The .length property is inherited from the object class; the class all other classes & objects inherit from in an OOP language. Also, one would use .length-1 to return the number of the last index in an array; using just the .length will return the total length of the array.

I would suggest something like this:

int index;
int jdex;
for( index = 0; index < (sizeof( my_array ) / sizeof( my_array[0] )); index++){
   for( jdex = 0; jdex < (sizeof( my_array ) / sizeof( my_array[0] )); jdex++){
        printf( "%d", my_array[index][jdex] );
        printf( "\n" );
   }
}

The line (sizeof( my_array ) / sizeof( my_array[0] )) will give you the size of the array in question. The sizeof property will return the length in bytes, so one must divide the total size of the array in bytes by how many bytes make up each element, each element takes up 4 bytes because each element is of type int, respectively. The array is of total size 16 bytes and each element is of 4 bytes so 16/4 yields 4 the total number of elements in your array because indexing starts at 0 and not 1.

How do I get the Date & Time (VBS)

For VBScript use FormatDateTime, which has 5 numerical arguments to give you one of 5 predefined formats. Its not great.

  FormatDateTime(now, 4)
  08:12

How to handle configuration in Go

I have started using Gcfg which uses Ini-like files. It's simple - if you want something simple, this is a good choice.

Here's the loading code I am using currently, which has default settings and allows command line flags (not shown) that override some of my config:

package util

import (
    "code.google.com/p/gcfg"
)

type Config struct {
    Port int
    Verbose bool
    AccessLog string
    ErrorLog string
    DbDriver string
    DbConnection string
    DbTblPrefix string
}

type configFile struct {
    Server Config
}

const defaultConfig = `
    [server]
    port = 8000
    verbose = false
    accessLog = -
    errorLog  = -
    dbDriver     = mysql
    dbConnection = testuser:TestPasswd9@/test
    dbTblPrefix  =
`

func LoadConfiguration(cfgFile string, port int, verbose bool) Config {
    var err error
    var cfg configFile

    if cfgFile != "" {
        err = gcfg.ReadFileInto(&cfg, cfgFile)
    } else {
        err = gcfg.ReadStringInto(&cfg, defaultConfig)
    }

    PanicOnError(err)

    if port != 0 {
        cfg.Server.Port = port
    }
    if verbose {
        cfg.Server.Verbose = true
    }

    return cfg.Server
}

Dynamic array in C#

Dynamic Array Example:

Console.WriteLine("Define Array Size? ");
int number = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Enter numbers:\n");
int[] arr = new int[number];

for (int i = 0; i < number; i++)
{
    arr[i] = Convert.ToInt32(Console.ReadLine());
}
for (int i = 0; i < arr.Length; i++ )
{
    Console.WriteLine("Array Index: "+i + " AND Array Item: " + arr[i].ToString());
}
Console.ReadKey();

Adjust width of input field to its input

It sounds like your expectation is that the style be applied dynamically to the width of the textbox based on the contents of the textbox. If so you will need some js to run on textbox contents changing, something like this:

<input id="txt" type="text" onkeypress="this.style.width = ((this.value.length + 1) * 8) + 'px';">

Note: this solution only works when every character is exactly 8px wide.

How to check if a variable is equal to one string or another string?

if var == 'stringone' or var == 'stringtwo':
    do_something()

or more pythonic,

if var in ['string one', 'string two']:
    do_something()

C# Ignore certificate errors?

This code worked for me. I had to add TLS2 because that's what the URL I am interested in was using.

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
ServicePointManager.ServerCertificateValidationCallback +=
    (sender, cert, chain, sslPolicyErrors) => { return true; };
using (var client = new HttpClient())
{
    client.BaseAddress = new Uri(UserDataUrl);
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new
      MediaTypeWithQualityHeaderValue("application/json"));
    Task<string> response = client.GetStringAsync(UserDataUrl);
    response.Wait();

    if (response.Exception != null)
    {
         return null;
    }

    return JsonConvert.DeserializeObject<UserData>(response.Result);
}

How do I find out if first character of a string is a number?

Regular expressions are very strong but expensive tool. It is valid to use them for checking if the first character is a digit but it is not so elegant :) I prefer this way:

public boolean isLeadingDigit(final String value){
    final char c = value.charAt(0);
    return (c >= '0' && c <= '9');
}

What is the difference between null=True and blank=True in Django?

This is how the ORM maps blank & null fields for Django 1.8

class Test(models.Model):
    charNull        = models.CharField(max_length=10, null=True)
    charBlank       = models.CharField(max_length=10, blank=True)
    charNullBlank   = models.CharField(max_length=10, null=True, blank=True)

    intNull         = models.IntegerField(null=True)
    intBlank        = models.IntegerField(blank=True)
    intNullBlank    = models.IntegerField(null=True, blank=True)

    dateNull        = models.DateTimeField(null=True)
    dateBlank       = models.DateTimeField(blank=True)
    dateNullBlank   = models.DateTimeField(null=True, blank=True)        

The database fields created for PostgreSQL 9.4 are :

CREATE TABLE Test (
  id              serial                    NOT NULL,

  "charNull"      character varying(10),
  "charBlank"     character varying(10)     NOT NULL,
  "charNullBlank" character varying(10),

  "intNull"       integer,
  "intBlank"      integer                   NOT NULL,
  "intNullBlank"  integer,

  "dateNull"      timestamp with time zone,
  "dateBlank"     timestamp with time zone  NOT NULL,
  "dateNullBlank" timestamp with time zone,
  CONSTRAINT Test_pkey PRIMARY KEY (id)
)

The database fields created for MySQL 5.6 are :

CREATE TABLE Test (
     `id`            INT(11)     NOT  NULL    AUTO_INCREMENT,

     `charNull`      VARCHAR(10) NULL DEFAULT NULL,
     `charBlank`     VARCHAR(10) NOT  NULL,
     `charNullBlank` VARCHAR(10) NULL DEFAULT NULL,

     `intNull`       INT(11)     NULL DEFAULT NULL,
     `intBlank`      INT(11)     NOT  NULL,
     `intNullBlank`  INT(11)     NULL DEFAULT NULL,

     `dateNull`      DATETIME    NULL DEFAULT NULL,
     `dateBlank`     DATETIME    NOT  NULL,
     `dateNullBlank` DATETIME    NULL DEFAULT NULL
)

Operation must use an updatable query. (Error 3073) Microsoft Access

I would try building the UPDATE query in Access. I had an UPDATE query I wrote myself like

UPDATE TABLE1
SET Field1 = 
(SELECT Table2.Field2
 FROM Table2
 WHERE Table2.UniqueIDColumn = Table1.UniqueIDColumn)

The query gave me that error you're seeing. This worked on my SQL Server though, but just like earlier answers noted, Access UPDATE syntax isn't standard syntax. However, when I rebuilt it using Access's query wizard (it used the JOIN syntax) it worked fine. Normally I'd just make the UPDATE query a passthrough to use the non-JET syntax, but one of the tables I was joining with was a local Access table.

Windows command for file size only

Taken from here:

The following command finds folders that are greater than 100 MB in size on the D: drive:

diruse /s /m /q:100 /d d:

The /s option causes subdirectories to be searched, the /m option displays disk usage in megabytes, the /q:100 option causes folders that are greater than 100 MB to be marked, and the /d option displays only folders that exceed the threshold specified by /q.

Use the diskuse command to find files over a certain size. The following command displays files over 100 MB in size on the D: drive:

diskuse D: /x:104857600 /v /s

The /x:104857600 option causes files over 104,857,600 bytes to be displayed and is valid only if you include the /v option (verbose). The /s option means subdirectories from the specified path (in this case, the D: drive) are searched.

Using VBScript

' This code finds all files over a certain size.
' ------ SCRIPT CONFIGURATION ------
strComputer = "**<ServerName>**" 
intSizeBytes = 1024 * 1024 * 500  ' = 500 MB
' ------ END CONFIGURATION ---------
set objWMI = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
set colFiles = objWMI.ExecQuery _
    ("Select * from CIM_DataFile where FileSize > '" & intSizeBytes & "'")
for each objFile in colFiles
    Wscript.Echo objFile.Name & "  " & objFile.Filesize / 1024 / 1024 & "MB"
next

Differences between CHMOD 755 vs 750 permissions set

0755 = User:rwx Group:r-x World:r-x

0750 = User:rwx Group:r-x World:--- (i.e. World: no access)

r = read
w = write
x = execute (traverse for directories)

What is difference between monolithic and micro kernel?

  1. Monolithic kernel design is much older than the microkernel idea, which appeared at the end of the 1980's.

  2. Unix and Linux kernels are monolithic, while QNX, L4 and Hurd are microkernels. Mach was initially a microkernel (not Mac OS X), but later converted into a hybrid kernel. Minix (before version 3) wasn't a pure microkernel because device drivers were compiled as part of the kernel.

  3. Monolithic kernels are usually faster than microkernels. The first microkernel Mach was 50% slower than most monolithic kernels, while later ones like L4 were only 2% or 4% slower than the monolithic designs.

  4. Monolithic kernels are big in size, while microkernels are small in size - they usually fit into the processor's L1 cache (first generation microkernels).

  5. In monolithic kernels, the device drivers reside in the kernel space while in the microkernels the device drivers are user-space.

  6. Since monolithic kernels' device drivers reside in the kernel space, monolithic kernels are less secure than microkernels, and failures (exceptions) in the drivers may lead to crashes (displayed as BSODs in Windows). Microkernels are more secure than monolithic kernels, hence more often used in military devices.

  7. Monolithic kernels use signals and sockets to implement inter-process communication (IPC), microkernels use message queues. 1st gen microkernels didn't implement IPC well and were slow on context switches - that's what caused their poor performance.

  8. Adding a new feature to a monolithic system means recompiling the whole kernel or the corresponding kernel module (for modular monolithic kernels), whereas with microkernels you can add new features or patches without recompiling.

How to install Intellij IDEA on Ubuntu?

JetBrains has a new application called the Toolbox App which quickly and easily installs any JetBrains software you want, assuming you have the license. It also manages your login once to apply across all JetBrains software, a very useful feature.

To use it, download the tar.gz file here, then extract it and run the included executable jetbrains-toolbox. Then sign in, and press install next to IntelliJ IDEA:

enter image description here

If you want to move the executable to /usr/bin/ feel free, however it works fine out of the box wherever you extract it to.

This will also make the appropriate desktop entries upon install.

Detecting when the 'back' button is pressed on a navbar

7ynk3r's answer was really close to what I did use in the end but it needed some tweaks:

- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item {

    UIViewController *topViewController = self.topViewController;
    BOOL wasBackButtonClicked = topViewController.navigationItem == item;

    if (wasBackButtonClicked) {
        if ([topViewController respondsToSelector:@selector(navBackButtonPressed)]) {
            // if user did press back on the view controller where you handle the navBackButtonPressed
            [topViewController performSelector:@selector(navBackButtonPressed)];
            return NO;
        } else {
            // if user did press back but you are not on the view controller that can handle the navBackButtonPressed
            [self popViewControllerAnimated:YES];
            return YES;
        }
    } else {
        // when you call popViewController programmatically you do not want to pop it twice
        return YES;
    }
}

@synthesize vs @dynamic, what are the differences?

Take a look at this article; under the heading "Methods provided at runtime":

Some accessors are created dynamically at runtime, such as certain ones used in CoreData's NSManagedObject class. If you want to declare and use properties for these cases, but want to avoid warnings about methods missing at compile time, you can use the @dynamic directive instead of @synthesize.

...

Using the @dynamic directive essentially tells the compiler "don't worry about it, a method is on the way."

The @synthesize directive, on the other hand, generates the accessor methods for you at compile time (although as noted in the "Mixing Synthesized and Custom Accessors" section it is flexible and does not generate methods for you if either are implemented).

Find the host name and port using PSQL commands

From the terminal you can do:

\conninfo

I would suggest reading a documentation on their exhaustive list of all commands using:

\?

How do I declare a 2d array in C++ using new?

Although this popular answer will give you your desired indexing syntax, it is doubly inefficient: big and slow both in space and time. There's a better way.

Why That Answer is Big and Slow

The proposed solution is to create a dynamic array of pointers, then initializing each pointer to its own, independent dynamic array. The advantage of this approach is that it gives you the indexing syntax you're used to, so if you want to find the value of the matrix at position x,y, you say:

int val = matrix[ x ][ y ];

This works because matrix[x] returns a pointer to an array, which is then indexed with [y]. Breaking it down:

int* row = matrix[ x ];
int  val = row[ y ];

Convenient, yes? We like our [ x ][ y ] syntax.

But the solution has a big disadvantage, which is that it is both fat and slow.

Why?

The reason that it's both fat and slow is actually the same. Each "row" in the matrix is a separately allocated dynamic array. Making a heap allocation is expensive both in time and space. The allocator takes time to make the allocation, sometimes running O(n) algorithms to do it. And the allocator "pads" each of your row arrays with extra bytes for bookkeeping and alignment. That extra space costs...well...extra space. The deallocator will also take extra time when you go to deallocate the matrix, painstakingly free-ing up each individual row allocation. Gets me in a sweat just thinking about it.

There's another reason it's slow. These separate allocations tend to live in discontinuous parts of memory. One row may be at address 1,000, another at address 100,000—you get the idea. This means that when you're traversing the matrix, you're leaping through memory like a wild person. This tends to result in cache misses that vastly slow down your processing time.

So, if you absolute must have your cute [x][y] indexing syntax, use that solution. If you want quickness and smallness (and if you don't care about those, why are you working in C++?), you need a different solution.

A Different Solution

The better solution is to allocate your whole matrix as a single dynamic array, then use (slightly) clever indexing math of your own to access cells. The indexing math is only very slightly clever; nah, it's not clever at all: it's obvious.

class Matrix
{
    ...
    size_t index( int x, int y ) const { return x + m_width * y; }
};

Given this index() function (which I'm imagining is a member of a class because it needs to know the m_width of your matrix), you can access cells within your matrix array. The matrix array is allocated like this:

array = new int[ width * height ];

So the equivalent of this in the slow, fat solution:

array[ x ][ y ]

...is this in the quick, small solution:

array[ index( x, y )]

Sad, I know. But you'll get used to it. And your CPU will thank you.

Get table name by constraint name

ALL_CONSTRAINTS describes constraint definitions on tables accessible to the current user.

DBA_CONSTRAINTS describes all constraint definitions in the database.

USER_CONSTRAINTS describes constraint definitions on tables in the current user's schema

Select CONSTRAINT_NAME,CONSTRAINT_TYPE ,TABLE_NAME ,STATUS from 
USER_CONSTRAINTS;

How to make layout with View fill the remaining space?

use a Relativelayout to wrap LinearLayout

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:round="http://schemas.android.com/apk/res-auto"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="vertical">
    <Button
        android:layout_width = "wrap_content"
        android:layout_height = "wrap_content"
        android:text="&lt;"/>
    <TextView
        android:layout_width = "fill_parent"
        android:layout_height = "wrap_content"
        android:layout_weight = "1"/>
    <Button
        android:layout_width = "wrap_content"
        android:layout_height = "wrap_content"
        android:text="&gt;"/>

</LinearLayout>

</RelativeLayout>`

Can lambda functions be templated?

C++11 lambdas can't be templated as stated in other answers but decltype() seems to help when using a lambda within a templated class or function.

#include <iostream>
#include <string>

using namespace std;

template<typename T>
void boring_template_fn(T t){
    auto identity = [](decltype(t) t){ return t;};
    std::cout << identity(t) << std::endl;
}

int main(int argc, char *argv[]) {
    std::string s("My string");
    boring_template_fn(s);
    boring_template_fn(1024);
    boring_template_fn(true);
}

Prints:

My string
1024
1

I've found this technique is helps when working with templated code but realize it still means lambdas themselves can't be templated.

Encoding as Base64 in Java

On Android, use the static methods of the android.util.Base64 utility class. The referenced documentation says that the Base64 class was added in API level 8 (Android 2.2 (Froyo)).

import android.util.Base64;

byte[] encodedBytes = Base64.encode("Test".getBytes());
Log.d("tag", "encodedBytes " + new String(encodedBytes));

byte[] decodedBytes = Base64.decode(encodedBytes);
Log.d("tag", "decodedBytes " + new String(decodedBytes));

Docker Networking - nginx: [emerg] host not found in upstream

If you are so lost for read the last comment. I have reached another solution.

The main problem is the way that you named the services names.

In this case, if in your docker-compose.yml, the service for php are called "api" or something like that, you must ensure that in the file nginx.conf the line that begins with fastcgi_pass have the same name as the php service. i.e fastcgi_pass api:9000;

Assign command output to variable in batch file

You can't assign a process output directly into a var, you need to parse the output with a For /F loop:

@Echo OFF

FOR /F "Tokens=2,*" %%A IN (
    'Reg Query "HKEY_CURRENT_USER\Software\Macromedia\FlashPlayer" /v "CurrentVersion"'
) DO (
    REM Set "Version=%%B"
    Echo Version: %%B
)

Pause&Exit

http://ss64.com/nt/for_f.html

PS: Change the reg key used if needed.

Failed to load resource 404 (Not Found) - file location error?

Looks like the path you gave doesn't have any bootstrap files in them.

href="~/lib/bootstrap/dist/css/bootstrap.min.css"

Make sure the files exist over there , else point the files to the correct path, which should be in your case

href="~/node_modules/bootstrap/dist/css/bootstrap.min.css"

Symbolicating iPhone App Crash Reports

I use Airbrake in my apps, which does a fairly good job of remote error logging.

Here's how I symbolicate them with atos if the backtrace needs it:

  1. In Xcode (4.2) go to the organizer, right click on the archive from which the .ipa file was generated.

  2. In Terminal, cd into the xcarchive for instance MyCoolApp 10-27-11 1.30 PM.xcarchive

  3. Enter the following atos -arch armv7 -o 'MyCoolApp.app'/'MyCoolApp' (don't forget the single quotes)

  4. I don't include my symbol in that call. What you get is a block cursor on an empty line.

  5. Then I copy/paste my symbol code at that block cursor and press enter. You'll see something like:

    -[MyCoolVC dealloc] (in MyCoolApp) (MyCoolVC.m:34)

  6. You're back to a block cursor and you can paste in other symbols.

Being able to go through your backtrace one item without re-entering the first bit is a nice time saver.

Enjoy!

When to use RDLC over RDL reports?

While I currently lean toward RDL because it seems more flexible and easier to manage, RDLC has an advantage in that it seems to simplify your licensing. Because RDLC doesn’t need a Reporting Services instance, you won't need a Reporting Services License to use it.

I’m not sure if this still applies with the newer versions of SQL Server, but at one time if you chose to put the SQL Server Database and Reporting Services instances on two separate machines, you were required to have two separate SQL Server licenses:
http://social.msdn.microsoft.com/forums/en-US/sqlgetstarted/thread/82dd5acd-9427-4f64-aea6-511f09aac406/

You can Bing for other similar blogs and posts regarding Reporting Services licensing.

Gradle - Move a folder from ABC to XYZ

Your task declaration is incorrectly combining the Copy task type and project.copy method, resulting in a task that has nothing to copy and thus never runs. Besides, Copy isn't the right choice for renaming a directory. There is no Gradle API for renaming, but a bit of Groovy code (leveraging Java's File API) will do. Assuming Project1 is the project directory:

task renABCToXYZ {     doLast {         file("ABC").renameTo(file("XYZ"))     } } 

Looking at the bigger picture, it's probably better to add the renaming logic (i.e. the doLast task action) to the task that produces ABC.

Postgres could not connect to server

For me it was an apache upgrade that caused the problem. I could still run psql in console or call db directly from kdevelop. Also it worked to add "host=localhost" to connection string.

BUT the real problem was that apache had changed to private tmp.

Solution: Update /usr/lib/systemd/system/apache2.service and change PrivateTmp=true to PrivateTmp=false.

I am working on OpenSuse OS, but I guess that something similar could happen on Mac.

How to Parse a JSON Object In Android

In the end I solved it by using JSONObject.get rather than JSONObject.getString and then cast test to a String.

private void saveData(String result) {
    try {
        JSONObject json= (JSONObject) new JSONTokener(result).nextValue();
        JSONObject json2 = json.getJSONObject("results");
        test = (String) json2.get("name");
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

How eliminate the tab space in the column in SQL Server 2008

Try this code

SELECT REPLACE([Column], char(9), '') From [dbo.Table] 

char(9) is the TAB character

Trigger to fire only if a condition is met in SQL Server

The _ character is also a wildcard, BTW, but I'm not sure why this wasn't working for you:

CREATE TRIGGER 
    [dbo].[SystemParameterInsertUpdate]
ON 
    [dbo].[SystemParameter]
FOR INSERT, UPDATE 
AS
  BEGIN
    SET NOCOUNT ON
      INSERT INTO SystemParameterHistory 
      (
        Attribute,
        ParameterValue,
        ParameterDescription,
        ChangeDate
      )
    SELECT
      I.Attribute,
      I.ParameterValue,
      I.ParameterDescription,
      I.ChangeDate
    FROM Inserted AS I
    WHERE I.Attribute NOT LIKE 'NoHist[_]%'
END

How to indent HTML tags in Notepad++

Step 1: Open plugin manager in notepad++

Plugins -> Plugin Manager -> Show Plugin Manager.

Step 2:install XML Tool plugin

Search "XML TOOLS" from the "Available" option then click in install.

Now you can use shortcut key CTRL+ALT+SHIFT+B to indent the code.

How do I force a DIV block to extend to the bottom of a page even if it has no content?

Try Ryan Fait's "Sticky Footer" solution,

http://ryanfait.com/sticky-footer/
http://ryanfait.com/resources/footer-stick-to-bottom-of-page/

Works across IE, Firefox, Chrome, Safari and supposedly Opera too, but haven't tested that. It's a great solution. Very easy and reliable to implement.

How to close jQuery Dialog within the dialog?

you can close it programmatically by calling

$('#form-dialog').dialog('close')

whenever you want.

XAMPP keeps showing Dashboard/Welcome Page instead of the Configuration Page

Change the document root in the file C:\xampp\apache\conf\httpd.conf to the folder where is the index.php of your project.

Reduce size of legend area in barplot

The cex parameter will do that for you.

a <- c(3, 2, 2, 2, 1, 2 )
barplot(a, beside = T,
        col = 1:6, space = c(0, 2))
legend("topright", 
       legend = c("a", "b", "c", "d", "e", "f"), 
       fill = 1:6, ncol = 2,
       cex = 0.75)

The plot

Clear dropdownlist with JQuery

<select id="ddlvalue" name="ddlvaluename">
<option value='0' disabled selected>Select Value</option>
<option value='1' >Value 1</option>
<option value='2' >Value 2</option>
</select>

<input type="submit" id="btn_submit" value="click me"/>



<script>
$('#btn_submit').on('click',function(){
      $('#ddlvalue').val(0);
});
</script>

Editing dictionary values in a foreach loop

If you're feeling creative you could do something like this. Loop backwards through the dictionary to make your changes.

Dictionary<string, int> collection = new Dictionary<string, int>();
collection.Add("value1", 9);
collection.Add("value2", 7);
collection.Add("value3", 5);
collection.Add("value4", 3);
collection.Add("value5", 1);

for (int i = collection.Keys.Count; i-- > 0; ) {
    if (collection.Values.ElementAt(i) < 5) {
        collection.Remove(collection.Keys.ElementAt(i)); ;
    }

}

Certainly not identical, but you might be interested anyways...

Ship an application with a database

If the required data is not too large (limits I don´t know, would depend on a lot of things), you might also download the data (in XML, JSON, whatever) from a website/webapp. AFter receiving, execute the SQL statements using the received data creating your tables and inserting the data.

If your mobile app contains lots of data, it might be easier later on to update the data in the installed apps with more accurate data or changes.

How to set background color of a View

I tried all the above ways. But I havent achieve what i need. Here is my try. If you are using hexcode for color and want to set the color as background of image, then this is the kotlin code.

val bitmap = Bitmap.createBitmap(30, 30, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
val colorCode = "#ffffff"
canvas.drawColor(Color.parseColor(colorCode))
mImageViewLogo.setImageBitmap(bitmap)

How to turn off Wifi via ADB?

This works as of android 7.1.1, non-rooted

adb shell am start -a android.intent.action.MAIN -n com.android.settings/.wifi.WifiSettings && adb shell input keyevent 23 && adb shell input keyevent 23

This will launch the activity and then send the DPAD center keyevent. I added another DPAD center as an experiment to see if you can enable it in the same way.

What's the simplest way to print a Java array?

I came across this post in Vanilla #Java recently. It's not very convenient writing Arrays.toString(arr);, then importing java.util.Arrays; all the time.

Please note, this is not a permanent fix by any means. Just a hack that can make debugging simpler.

Printing an array directly gives the internal representation and the hashCode. Now, all classes have Object as the parent-type. So, why not hack the Object.toString()? Without modification, the Object class looks like this:

public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

What if this is changed to:

public String toString() {
    if (this instanceof boolean[])
        return Arrays.toString((boolean[]) this);
    if (this instanceof byte[])
        return Arrays.toString((byte[]) this);
    if (this instanceof short[])
        return Arrays.toString((short[]) this);
    if (this instanceof char[])
        return Arrays.toString((char[]) this);
    if (this instanceof int[])
        return Arrays.toString((int[]) this);
    if (this instanceof long[])
        return Arrays.toString((long[]) this);
    if (this instanceof float[])
        return Arrays.toString((float[]) this);
    if (this instanceof double[])
        return Arrays.toString((double[]) this);
    if (this instanceof Object[])
        return Arrays.deepToString((Object[]) this);
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

This modded class may simply be added to the class path by adding the following to the command line: -Xbootclasspath/p:target/classes.

Now, with the availability of deepToString(..) since Java 5, the toString(..) can easily be changed to deepToString(..) to add support for arrays that contain other arrays.

I found this to be a quite useful hack and it would be great if Java could simply add this. I understand potential issues with having very large arrays since the string representations could be problematic. Maybe pass something like a System.outor a PrintWriter for such eventualities.

How to identify platform/compiler from preprocessor macros?

See: http://predef.sourceforge.net/index.php

This project provides a reasonably comprehensive listing of pre-defined #defines for many operating systems, compilers, language and platform standards, and standard libraries.

What does "res.render" do, and what does the html file look like?

Renders a view and sends the rendered HTML string to the client.

res.render('index');

Or

res.render('index', function(err, html) {
  if(err) {...}
  res.send(html);
});

DOCS HERE: https://expressjs.com/en/api.html#res.render

How to pass arguments and redirect stdin from a file to program run in gdb?

Wouldn't it be nice to just type debug in front of any command to be able to debug it with gdb on shell level?

Below it this function. It even works with following:

"$program" "$@" < <(in) 1> >(out) 2> >(two) 3> >(three)

This is a call where you cannot control anything, everything is variable, can contain spaces, linefeeds and shell metacharacters. In this example, in, out, two, and three are arbitrary other commands which consume or produce data which must not be harmed.

Following bash function invokes gdb nearly cleanly in such an environment [Gist]:

debug()
{
  1000<&0 1001>&1 1002>&2 \
  0</dev/tty 1>/dev/tty 2>&0 \
  /usr/bin/gdb -q -nx -nw \
  -ex 'set exec-wrapper /bin/bash -c "exec 0<&1000 1>&1001 2>&1002 \"\$@\"" exec' \
  -ex r \
  --args "$@";
}

Example on how to apply this: Just type debug in front:

Before:

p=($'\n' $'I\'am\'evil' "  yay  ")
"b u g" "${p[@]}" < <(in) 1> >(out) 2> >(two) 3> >(three)

After:

p=($'\n' $'I\'am\'evil' "  yay  ")
debug "b u g" "${p[@]}" < <(in) 1> >(out) 2> >(two) 3> >(three)

That's it. Now it's an absolute no-brainer to debug with gdb. Except for a few details or more:

  • gdb does not quit automatically and hence keeps the IO redirection open until you exit gdb. But I call this a feature.

  • You cannot easily pass argv0 to the program like with exec -a arg0 command args. Following should do this trick: After exec-wrapper change "exec to "exec -a \"\${DEBUG_ARG0:-\$1}\".

  • There are FDs above 1000 open, which are normally closed. If this is a problem, change 0<&1000 1>&1001 2>&1002 to read 0<&1000 1>&1001 2>&1002 1000<&- 1001>&- 1002>&-

  • You cannot run two debuggers in parallel. There also might be issues, if some other command consumes /dev/tty (or STDIN). To fix that, replace /dev/tty with "${DEBUGTTY:-/dev/tty}". In some other TTY type tty; sleep inf and then use the printed TTY (i. E. /dev/pts/60) for debugging, as in DEBUGTTY=/dev/pts/60 debug command arg... That's the Power of Shell, get used to it!

Function explained:

  • 1000<&0 1001>&1 1002>&2 moves away the first 3 FDs
    • This assumes, that FDs 1000, 1001 and 1002 are free
  • 0</dev/tty 1>/dev/tty 2>&0 restores the first 3 FDs to point to your current TTY. So you can control gdb.
  • /usr/bin/gdb -q -nx -nw runs gdb invokes gdb on shell
  • -ex 'set exec-wrapper /bin/bash -c "exec 0<&1000 1>&1001 2>&1002 \"\$@\"" creates a startup wrapper, which restores the first 3 FDs which were saved to 1000 and above
  • -ex r starts the program using the exec-wrapper
  • --args "$@" passes the arguments as given

Wasn't that easy?

Authentication plugin 'caching_sha2_password' is not supported

I also got a similar error

  File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mysql\connector\authentication.py", line 191, in get_auth_plugin
    "Authentication plugin '{0}' is not supported".format(plugin_name))
mysql.connector.errors.NotSupportedError: Authentication plugin 'caching_sha2_password' is not supported

You have probably installed mysql-connector instead of mysql-connector-python. So you need to install it again for python3:

pip3 install mysql-connector-python

Format telephone and credit card numbers in AngularJS

I took aberke's solution and modified it to suit my taste.

  • It produces a single input element
  • It optionally accepts extensions
  • For US numbers it skips the leading country code
  • Standard naming conventions
  • Uses class from using code; doesn't make up a class
  • Allows use of any other attributes allowed on an input element

My Code Pen

_x000D_
_x000D_
var myApp = angular.module('myApp', []);_x000D_
_x000D_
myApp.controller('exampleController',_x000D_
  function exampleController($scope) {_x000D_
    $scope.user = { profile: {HomePhone: '(719) 465-0001 x1234'}};_x000D_
    $scope.homePhonePrompt = "Home Phone";_x000D_
  });_x000D_
_x000D_
myApp_x000D_
/*_x000D_
    Intended use:_x000D_
    <phone-number placeholder='prompt' model='someModel.phonenumber' />_x000D_
    Where: _x000D_
      someModel.phonenumber: {String} value which to bind formatted or unformatted phone number_x000D_
_x000D_
    prompt: {String} text to keep in placeholder when no numeric input entered_x000D_
*/_x000D_
.directive('phoneNumber',_x000D_
  ['$filter',_x000D_
  function ($filter) {_x000D_
    function link(scope, element, attributes) {_x000D_
_x000D_
      // scope.inputValue is the value of input element used in template_x000D_
      scope.inputValue = scope.phoneNumberModel;_x000D_
_x000D_
      scope.$watch('inputValue', function (value, oldValue) {_x000D_
_x000D_
        value = String(value);_x000D_
        var number = value.replace(/[^0-9]+/g, '');_x000D_
        scope.inputValue = $filter('phoneNumber')(number, scope.allowExtension);_x000D_
        scope.phoneNumberModel = scope.inputValue;_x000D_
      });_x000D_
    }_x000D_
_x000D_
    return {_x000D_
      link: link,_x000D_
      restrict: 'E',_x000D_
      replace: true,_x000D_
      scope: {_x000D_
        phoneNumberPlaceholder: '@placeholder',_x000D_
        phoneNumberModel: '=model',_x000D_
        allowExtension: '=extension'_x000D_
      },_x000D_
      template: '<input ng-model="inputValue" type="tel" placeholder="{{phoneNumberPlaceholder}}" />'_x000D_
    };_x000D_
  }_x000D_
  ]_x000D_
)_x000D_
/* _x000D_
    Format phonenumber as: (aaa) ppp-nnnnxeeeee_x000D_
    or as close as possible if phonenumber length is not 10_x000D_
    does not allow country code or extensions > 5 characters long_x000D_
*/_x000D_
.filter('phoneNumber', _x000D_
  function() {_x000D_
    return function(number, allowExtension) {_x000D_
      /* _x000D_
      @param {Number | String} number - Number that will be formatted as telephone number_x000D_
      Returns formatted number: (###) ###-#### x #####_x000D_
      if number.length < 4: ###_x000D_
      else if number.length < 7: (###) ###_x000D_
      removes country codes_x000D_
      */_x000D_
      if (!number) {_x000D_
        return '';_x000D_
      }_x000D_
_x000D_
      number = String(number);_x000D_
      number = number.replace(/[^0-9]+/g, '');_x000D_
      _x000D_
      // Will return formattedNumber. _x000D_
      // If phonenumber isn't longer than an area code, just show number_x000D_
      var formattedNumber = number;_x000D_
_x000D_
      // if the first character is '1', strip it out _x000D_
      var c = (number[0] == '1') ? '1 ' : '';_x000D_
      number = number[0] == '1' ? number.slice(1) : number;_x000D_
_x000D_
      // (###) ###-#### as (areaCode) prefix-endxextension_x000D_
      var areaCode = number.substring(0, 3);_x000D_
      var prefix = number.substring(3, 6);_x000D_
      var end = number.substring(6, 10);_x000D_
      var extension = number.substring(10, 15);_x000D_
_x000D_
      if (prefix) {_x000D_
        //formattedNumber = (c + "(" + area + ") " + front);_x000D_
        formattedNumber = ("(" + areaCode + ") " + prefix);_x000D_
      }_x000D_
      if (end) {_x000D_
        formattedNumber += ("-" + end);_x000D_
      }_x000D_
      if (allowExtension && extension) {_x000D_
        formattedNumber += ("x" + extension);_x000D_
      }_x000D_
      return formattedNumber;_x000D_
    };_x000D_
  }_x000D_
);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<div ng-app="myApp" ng-controller="exampleController">_x000D_
  <p>Phone Number Value: {{ user.profile.HomePhone || 'null' }}</p>_x000D_
  <p>Formatted Phone Number: {{ user.profile.HomePhone | phoneNumber }}</p>_x000D_
        <phone-number id="homePhone"_x000D_
                      class="form-control" _x000D_
                      placeholder="Home Phone" _x000D_
                      model="user.profile.HomePhone"_x000D_
                      ng-required="!(user.profile.HomePhone.length || user.profile.BusinessPhone.length || user.profile.MobilePhone.length)" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I force Maven to use my local repository rather than going out to remote repos to retrieve artifacts?

The -o option didn't work for me because the artifact is still in development and not yet uploaded and maven (3.5.x) still tries to download it from the remote repository because it's the first time, according to the error I get.

However this fixed it for me: https://maven.apache.org/general.html#importing-jars

After this manual install there's no need to use the offline option either.

UPDATE

I've just rebuilt the dependency and I had to re-import it: the regular mvn clean install was not sufficient for me

format statement in a string resource file

Quote from Android Docs:

If you need to format your strings using String.format(String, Object...), then you can do so by putting your format arguments in the string resource. For example, with the following resource:

<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>

In this example, the format string has two arguments: %1$s is a string and %2$d is a decimal number. You can format the string with arguments from your application like this:

Resources res = getResources();
String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);

crop text too long inside div

You can use:

overflow:hidden;

to hide the text outside the zone.

Note that it may cut the last letter (so a part of the last letter will still be displayed). A nicer way is to display an ellipsis at the end. You can do it by using text-overflow:

overflow: hidden;
white-space: nowrap; /* Don't forget this one */
text-overflow: ellipsis;

Hex transparency in colors

try this on google search (or click here)

255 * .2 to hex

it will generate 0x33 as a result.

However, google does not round off values so you can only use 1-digit multipliers. if you want to use say .85, you have to get the rounded-off value of 255 * .85 first, then type (rounded-value here) to hex in google search.

python ignore certificate validation urllib2

According to @Enno Gröper 's post, I've tried the SSLContext constructor and it works well on my machine. code as below:

import ssl
ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
urllib2.urlopen("https://your-test-server.local", context=ctx)

if you need opener, just added this context like:

opener = urllib2.build_opener(urllib2.HTTPSHandler(context=ctx))

NOTE: all above test environment is python 2.7.12. I use PROTOCOL_SSLv23 here since the doc says so, other protocol might also works but depends on your machine and remote server, please check the doc for detail.

do { ... } while (0) — what is it good for?

Generically, do/while is good for any sort of loop construct where one must execute the loop at least once. It is possible to emulate this sort of looping through either a straight while or even a for loop, but often the result is a little less elegant. I'll admit that specific applications of this pattern are fairly rare, but they do exist. One which springs to mind is a menu-based console application:

do {
    char c = read_input();

    process_input(c);
} while (c != 'Q');

javascript - Create Simple Dynamic Array

Some of us are referring to use from which is not good at the performance:

_x000D_
_x000D_
function getArrayViaFrom(input) {_x000D_
  console.time('Execution Time');_x000D_
  let output = Array.from(Array(input), (value, i) => (i + 1).toString())_x000D_
  console.timeEnd('Execution Time');_x000D_
_x000D_
  return output;_x000D_
}_x000D_
_x000D_
function getArrayViaFor(input) {_x000D_
  console.time('Execution Time 1');_x000D_
  var output = [];_x000D_
  for (var i = 1; i <= input; i++) {_x000D_
    output.push(i.toString());_x000D_
  }_x000D_
  console.timeEnd('Execution Time 1');_x000D_
_x000D_
  return output;_x000D_
}_x000D_
_x000D_
console.log(getArrayViaFrom(10)) // Takes 10x more than for that is 0.220ms_x000D_
console.log(getArrayViaFor(10))  // Takes 10x less than From that is 0.020ms
_x000D_
_x000D_
_x000D_

Centering controls within a form in .NET (Winforms)?

You could achieve this with the use of anchors. Or more precisely the non use of them.

Controls are anchored by default to the top left of the form which means when the form size will be changed, their distance from the top left side of the form will remain constant. If you change the control anchor to bottom left, then the control will keep the same distance from the bottom and left sides of the form when the form if resized.

Turning off the anchor in a direction will keep the control centered in that direction when resizing.

NOTE: Turning off anchoring via the properties window in VS2015 may require entering None, None (instead of default Top,Left)

(13: Permission denied) while connecting to upstream:[nginx]

if "502 Bad Gateway" error throws on centos api url for api gateway proxy pass on nginx , run following command to solve the issue

sudo setsebool -P httpd_can_network_connect 1

What is the difference between SQL, PL-SQL and T-SQL?

  • SQL a language for talking to the database. It lets you select data, mutate and create database objects (like tables, views, etc.), change database settings.
  • PL-SQL a procedural programming language (with embedded SQL)
  • T-SQL (procedural) extensions for SQL used by SQL Server

Set Value of Input Using Javascript Function

Try

gadget_url.value=''

_x000D_
_x000D_
addGadgetUrl.addEventListener('click', () => {_x000D_
   gadget_url.value = '';_x000D_
});
_x000D_
<div>_x000D_
  <p>URL</p>_x000D_
  <input type="text" name="gadget_url" id="gadget_url" style="width: 350px;" class="input" value="some value" />_x000D_
  <input type="button" id="addGadgetUrl" value="add gadget" />_x000D_
  <br>_x000D_
  <span id="error"></span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Update

I don't know why so many downovotes (and no comments) - however (for future readers) don't think that this solution not work - It works with html provided in OP question and this is SHORTEST working solution - you can try it by yourself HERE

Xcode 7.2 no matching provisioning profiles found

For me I tried following 2 steps which sadly did not work :

  • deleting all provisional profile from Xcode Preferences Accounts ? View Details , downloading freshly all provisional profiles.
  • Restarting Xcode everytime.

Instead, I tried to solve keychain certificate related another issue given here This certificate has an invalid issuer Apple Push Services

This certificate has an invalid issuer

enter image description here

  • In keychain access, go to View -> Show Expired Certificates.
  • Look for expired certificates in Login and System keychains and an "Apple Worldwide Developer Relations Certification Authority".
  • Delete all expired certificates.
  • After deleting expired certificates, visit the following URL and download the new AppleWWDRCA certificate, https://developer.apple.com/certificationauthority/AppleWWDRCA.cer
  • Double click on the newly downloaded certificate, and install it in your keychain. Can see certificate valid message.

enter image description here

Now go to xcode app. target ? Build Setting ? Provisioning Profile . Select value from 'automatic' to appropriate Provisioning profile . Bingo!!! profile mismatch issue is solved.

How to search a string in String array

At first shot, I could come up with something like this (but it's pseudo code and assuming you cannot use any .NET built-in libaries). Might require a bit of tweaking and re-thinking, but should be good enough for a head-start, maybe?

int findString(String var, String[] stringArray, int currentIndex, int stringMaxIndex)
    {
    if currentIndex > stringMaxIndex 
       return (-stringMaxIndex-1);
    else if var==arr[currentIndex] //or use any string comparison op or function
       return 0;
    else 
       return findString(var, stringArray, currentIndex++, stringMaxIndex) + 1 ;
    }



    //calling code
    int index = findString(var, arr, 0, getMaxIndex(arr));

    if index == -1 printOnScreen("Not found");
    else printOnScreen("Found on index: " + index);

Add custom buttons on Slick Carousel

its very easy. Use the bellow code, Its works for me. Here I have used fontawesome icon but you can use anything as image or any other Icon's code.

$(document).ready(function(){
    $('.slider').slick({
        autoplay:true,
        arrows: true,
        prevArrow:"<button type='button' class='slick-prev pull-left'><i class='fa fa-angle-left' aria-hidden='true'></i></button>",
        nextArrow:"<button type='button' class='slick-next pull-right'><i class='fa fa-angle-right' aria-hidden='true'></i></button>"
    });
});

How to tell Maven to disregard SSL errors (and trusting all certs)?

An alternative that worked for me is to tell Maven to use http: instead of https: when using Maven Central by adding the following to settings.xml:

<settings>
   .
   .
   .
  <mirrors>
    <mirror>
        <id>central-no-ssl</id>
        <name>Central without ssl</name>
        <url>http://repo.maven.apache.org/maven2</url>
        <mirrorOf>central</mirrorOf>
    </mirror>
  </mirrors>
   .
   .
   .
</settings>

Your mileage may vary of course.

Datetime in where clause

WHERE datetime_column >= '20081220 00:00:00.000'
  AND datetime_column < '20081221 00:00:00.000'

Docker how to change repository name or rename image?

docker image tag #imageId myname/server:latest

This works for me

Content Security Policy "data" not working for base64 Images in Chrome 28

Try this

data to load:

<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 4 5'><path fill='#343a40' d='M2 0L0 2h4zm0 5L0 3h4z'/></svg>

get a utf8 to base64 convertor and convert the "svg" string to:

PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCA0IDUn
PjxwYXRoIGZpbGw9JyMzNDNhNDAnIGQ9J00yIDBMMCAyaDR6bTAgNUwwIDNoNHonLz48L3N2Zz4=

and the CSP is

img-src data: image/svg+xml;base64,PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCA0IDUn
PjxwYXRoIGZpbGw9JyMzNDNhNDAnIGQ9J00yIDBMMCAyaDR6bTAgNUwwIDNoNHonLz48L3N2Zz4=

IFRAMEs and the Safari on the iPad, how can the user scroll the content?

Based on this article, I have put together the following snippet that provides some very basic functionality:

<div id = "container"></div>
<script>
function setPDFHeight(){ 
        $("#pdfObject")[0].height = $("#pdfObject")[0].offsetHeight;   
}   
$('#container').append('<div align="center" style="width: 100%; height:100%; overflow: auto !important; -webkit-overflow-scrolling: touch !important;">\
      <object id="pdfObject" width="100%" height="1000000000000" align="center" data="content/lessons/12/t.pdf" type="application/pdf" onload="setPDFHeight()">You have no plugin installed</object></div>');  
</script>

Obviously it is far from perfect (given that it practically expands your page height to infinity), but it's the only viable workaround I've found so far.

This API project is not authorized to use this API. Please ensure that this API is activated in the APIs Console

For me, it was Maps Embed API that I had to enable.

In the Google Cloud Console

Go to API tab, look through the Additional APIs section and try to enable any map-related APIs.

enter image description here

Add a summary row with totals

If you are on SQL Server 2008 or later version, you can use the ROLLUP() GROUP BY function:

SELECT
  Type = ISNULL(Type, 'Total'),
  TotalSales = SUM(TotalSales)
FROM atable
GROUP BY ROLLUP(Type)
;

This assumes that the Type column cannot have NULLs and so the NULL in this query would indicate the rollup row, the one with the grand total. However, if the Type column can have NULLs of its own, the more proper type of accounting for the total row would be like in @Declan_K's answer, i.e. using the GROUPING() function:

SELECT
  Type = CASE GROUPING(Type) WHEN 1 THEN 'Total' ELSE Type END,
  TotalSales = SUM(TotalSales)
FROM atable
GROUP BY ROLLUP(Type)
;

select rows in sql with latest date for each ID repeated multiple times

Here's one way. The inner query gets the max date for each id. Then you can join that back to your main table to get the rows that match.

select
*
from
<your table>
inner join 
(select id, max(<date col> as max_date) m
where yourtable.id = m.id
and yourtable.datecolumn = m.max_date)

Working Copy Locked

For PHPStorm or Intellij:

VCS -> Cleanup Project

Creating a LINQ select from multiple tables

You can use anonymous types for this, i.e.:

var pageObject = (from op in db.ObjectPermissions
                  join pg in db.Pages on op.ObjectPermissionName equals page.PageName
                  where pg.PageID == page.PageID
                  select new { pg, op }).SingleOrDefault();

This will make pageObject into an IEnumerable of an anonymous type so AFAIK you won't be able to pass it around to other methods, however if you're simply obtaining data to play with in the method you're currently in it's perfectly fine. You can also name properties in your anonymous type, i.e.:-

var pageObject = (from op in db.ObjectPermissions
                  join pg in db.Pages on op.ObjectPermissionName equals page.PageName
                  where pg.PageID == page.PageID
                  select new
                  {
                      PermissionName = pg, 
                      ObjectPermission = op
                  }).SingleOrDefault();

This will enable you to say:-

if (pageObject.PermissionName.FooBar == "golden goose") Application.Exit();

For example :-)

HAX kernel module is not installed

After reading many questions on stackoverflow I found out that my CPU does not support Virtualization. I have to upgrade to the cpu which supports Virtualization in order to install Intel X 86 Emulator accelerator(Haxm Installer)

"VT-x is not available" when I start my Virtual machine

VT-x can normally be disabled/enabled in your BIOS.

When your PC is just starting up you should press DEL (or something) to get to the BIOS settings. There you'll find an option to enable VT-technology (or something).

urllib2 and json

To read json response use json.loads(). Here is the sample.

import json
import urllib
import urllib2

post_params = {
    'foo' : bar
}

params = urllib.urlencode(post_params)
response = urllib2.urlopen(url, params)
json_response = json.loads(response.read())

Fastest way to download a GitHub project

Updated July 2016

As of July 2016, the Download ZIP button has moved under Clone or download to extreme-right of header under the Code tab:

Download ZIP (2013)


If you don't see the button:

  • Make sure you've selected <> Code tab from right side navigation menu, or
  • Repo may not have a zip prepared. Add /archive/master.zip to the end of the repository URL and to generate a zipfile of the master branch.

    http://github.com/user/repository/

-to-

http://github.com/user/repository/archive/master.zip

to get the master branch source code in a zip file. You can do the same with tags and branch names, by replacing master in the URL above with the name of the branch or tag.

Determine path of the executing script

I've made a package for this as of 2020-12-03 available on CRAN called "this.path".

Install it using:

install.packages("this.path")

and then use it by:

this.path::this.path()

or

library(this.path)

this.path()

I still have my original answer below, though it is less functional than the version in the package. On a Unix-alike OS, strange characters (such as " ") in the 'Rscript' command-line argument 'file' are replaced (such as "~+~"). R does this so that it is easier to use that filename for other system commands, but this isn't what we want. Given that we want a path usable in R, any such strange character sequences must be replaced.

Original Answer:

My answer is an improvement upon Jerry T's answer. The issue I found is that he is guessing whether a source call was made by checking if variable ofile is found in the first frame on the stack. This will not work with nested source calls, nor source calls made from a non-global environment. Additionally, a source call must be looked for before checking the command-line arguments, that has also been fixed. Here is my solution:

this.path <- function (verbose = getOption("verbose"))
{
    where <- function(x) if (verbose)
        cat("Source: ", x, "\n", sep = "")


    # loop through functions that lead here from most recent to earliest looking
    #     for an appropriate source call (a call to function base::source or base::sys.source)
    # an appropriate source call is a source call in which
    #     argument 'file' has been evaluated (forced)
    # this means, for example, the following is an inappropriate source call:
    #     source(this.path())
    # the argument 'file' is stored as a promise
    #     containing the expression "this.path()"
    # when the value of 'file' is requested, it assigns the value
    #     returned by evaluating "this.path()" to variable 'file'
    # there are two functions on the calling stack at
    #     this point being 'source' and 'this.path'
    # clearly, you don't want to request the 'file' argument from that source
    #     call because the value of 'file' is under evaluation right now!
    # the trick is to ask if variable ('ofile' for base::source, 'exprs' for base::sys.source)
    #     exists in that function's evaluation environment. this is because that
    #     variable is created AFTER argument 'file' has been forced
    # if that variable does exist, then argument 'file' has been forced and the
    #     source call is deemed appropriate. For base::source, the filename we want
    #     is the variable 'ofile' from that function's evaluation environment. For
    #     base::sys.source, the filename we want is the variable 'file' from that
    #     function's evaluation environment.
    # if that variable does NOT exist, then argument 'file' hasn't been forced and
    #     the source call is deemed inappropriate. The 'for' loop moves to the next
    #     function up the calling stack (if available)
    #
    # unfortunately, there is no way to check the argument 'fileName' has been forced
    #     for 'debugSource' since all the work is done internally in C. Instead,
    #     we have to use a 'tryCatch' statement. When we ask for an object by name
    #     using 'get', R is capable of realizing if a variable is asking for its
    #     own definition (a recursive definition). The exact error is "promise already
    #     under evaluation" which indicates that the promise evaluation is requesting
    #     its own value. So we use the 'tryCatch' to get the argument 'fileName'
    #     from the evaluation environment of 'debugSource', and if it does not raise
    #     an error, then we are safe to return that value. If not, the condition
    #     returns false and the 'for' loop moves to the next function up the calling
    #     stack (if available)


    if (.Platform$GUI == "RStudio")
        dbs <- get("debugSource", mode = "function", "tools:rstudio",
            inherits = FALSE)
    for (n in seq.int(sys.nframe(), 1L)[-1L]) {
        if (identical(sys.function(n), base::source) &&
            exists("ofile", envir = sys.frame(n), inherits = FALSE)) {
            path <- get("ofile", envir = sys.frame(n), inherits = FALSE)
            if (!is.character(path))
                path <- summary.connection(path)$description
            where("call to function source")
            return(normalizePath(path, mustWork = TRUE))
        }
        else if (identical(sys.function(n), base::sys.source) &&
            exists("exprs", envir = sys.frame(n), inherits = FALSE)) {
            path <- get("file", envir = sys.frame(n), inherits = FALSE)
            where("call to function sys.source")
            return(normalizePath(path, mustWork = TRUE))
        }
        else if (.Platform$GUI == "RStudio" && identical(sys.function(n), dbs) &&
            tryCatch({
                path <- get("fileName", envir = sys.frame(n), inherits = FALSE)
                TRUE
            }, error = function(c) {
                FALSE
            })) {
            where("call to function debugSource in RStudio")
            return(normalizePath(path, mustWork = TRUE))
        }
    }


    # if the for loop is passed, no appropriate
    #     source call was found up the calling stack
    # next, check if the user is running R from the command-line
    #     on a Windows OS, the GUI is "RTerm"
    #     on a Unix    OS, the GUI is "X11"


    if (.Platform$OS.type == "windows" && .Platform$GUI == "RTerm" ||  # running from Windows command-line
        .Platform$OS.type == "unix" && .Platform$GUI == "X11") {       # running from Unix command-line


        # get all command-line arguments that start with "--file="
        # check the number of command-line arguments starting with "--file="
        #     in case more or less than one were supplied


        path <- grep("^--file=", commandArgs(), value = TRUE)
        if (length(path) == 1L) {
            path <- sub("^--file=", "", path)
            where("Command-line argument 'file'")
            return(normalizePath(path, mustWork = TRUE))
        }
        else if (length(path)) {
            stop("'this.path' used in an inappropriate fashion\n",
                "* no appropriate source call was found up the calling stack\n",
                "* R is being run from the command-line and formal argument \"--file=\" matched by multiple actual arguments\n")
        }
        else stop("'this.path' used in an inappropriate fashion\n",
            "* no appropriate source call was found up the calling stack\n",
            "* R is being run from the command-line and argument \"--file=\" is missing\n")
    }
    else if (.Platform$GUI == "RStudio") {  # running R from 'RStudio'


        # function ".rs.api.getActiveDocumentContext" from the environment "tools:rstudio"
        #     returns a list of information about the document where your cursor is located
        #
        # function ".rs.api.getSourceEditorContext" from the environment "tools:rstudio"
        #     returns a list of information about the document open in the current tab
        #
        # element 'id' is a character string, an identification for the document
        # element 'path' is a character string, the path of the document


        adc <- get(".rs.api.getActiveDocumentContext",
            mode = "function", "tools:rstudio", inherits = FALSE)()
        if (adc$id != "#console") {
            path <- adc$path
            if (nzchar(path)) {
                where("active document in RStudio")
                return(normalizePath(path, mustWork = TRUE))
            }
            else stop("'this.path' used in an inappropriate fashion\n",
                "* no appropriate source call was found up the calling stack\n",
                "* active document in RStudio does not exist\n")
        }


        sec <- get(".rs.api.getSourceEditorContext", mode = "function",
            "tools:rstudio", inherits = FALSE)()
        if (!is.null(sec)) {
            path <- sec$path
            if (nzchar(path)) {
                where("source document in RStudio")
                return(normalizePath(path, mustWork = TRUE))
            }
            else stop("'this.path' used in an inappropriate fashion\n",
                "* no appropriate source call was found up the calling stack\n",
                "* source document in RStudio does not exist\n")
        }
        else stop("'this.path' used in an inappropriate fashion\n",
            "* no appropriate source call was found up the calling stack\n",
            "* R is being run from RStudio with no documents open\n")
    }
    else if (.Platform$OS.type == "windows" && .Platform$GUI == "Rgui") {  # running R from 'RGui' on Windows


        # on a Windows OS only, the function "getWindowsHandles" from the base
        # package "utils" returns a list of external pointers containing the windows
        # handles. The thing of interest are the names of this list, these should
        # be the names of the windows belonging to the current R process. Since
        # RGui can have files besides R scripts open (such as images), a regular
        # expression is used to subset only windows handles with names that exactly
        # match the string "R Console" or end with " - R Editor". I highly suggest
        # that you NEVER end a document's filename with " - R Editor". From there,
        # similar checks are done as in the above section for 'RStudio'


        wh <- names(utils::getWindowsHandles(pattern = "^R Console$| - R Editor$",
            minimized = TRUE))


        if (!length(wh))
            stop("this error SHOULD be unreachable, as far as I know it's impossible to have an R\n",
                "  process running without the R Console open. If you reached this error, please\n",
                "  send a bug report to the package maintainer")


        path <- wh[1L]
        if (path != "R Console") {
            path <- sub(" - R Editor$", "", path)
            if (path != "Untitled") {
                where("active document in RGui")
                return(normalizePath(path, mustWork = TRUE))
            }
            else stop("'this.path' used in an inappropriate fashion\n",
                "* no appropriate source call was found up the calling stack\n",
                "* active document in RGui does not exist\n")
        }


        path <- wh[2L]
        if (!is.na(path)) {
            path <- sub(" - R Editor$", "", path)
            if (path != "Untitled") {
                where("source document in RGui")
                return(normalizePath(path, mustWork = TRUE))
            }
            else stop("'this.path' used in an inappropriate fashion\n",
                "* no appropriate source call was found up the calling stack\n",
                "* source document in RGui does not exist\n")
        }
        else stop("'this.path' used in an inappropriate fashion\n",
            "* no appropriate source call was found up the calling stack\n",
            "* R is being run from RGui with no documents open\n")
    }
    else if (.Platform$OS.type == "unix" && .Platform$GUI == "AQUA") {  # running R from 'RGui' on Unix
        stop("'this.path' used in an inappropriate fashion\n",
            "* no appropriate source call was found up the calling stack\n",
            "* R is being run from AQUA which requires a source call on the calling stack\n")
    }
    else stop("'this.path' used in an inappropriate fashion\n",
        "* no appropriate source call was found up the calling stack\n",
        "* R is being run in an unrecognized manner\n")
}

JSON, REST, SOAP, WSDL, and SOA: How do they all link together

WSDL: Stands for Web Service Description Language

In SOAP(simple object access protocol), when you use web service and add a web service to your project, your client application(s) doesn't know about web service Functions. Nowadays it's somehow old-fashion and for each kind of different client you have to implement different WSDL files. For example you cannot use same file for .Net and php client. The WSDL file has some descriptions about web service functions. The type of this file is XML. SOAP is an alternative for REST.

REST: Stands for Representational State Transfer

It is another kind of API service, it is really easy to use for clients. They do not need to have special file extension like WSDL files. The CRUD operation can be implemented by different HTTP Verbs(GET for Reading, POST for Creation, PUT or PATCH for Updating and DELETE for Deleting the desired document) , They are based on HTTP protocol and most of times the response is in JSON or XML format. On the other hand the client application have to exactly call the related HTTP Verb via exact parameters names and types. Due to not having special file for definition, like WSDL, it is a manually job using the endpoint. But it is not a big deal because now we have a lot of plugins for different IDEs to generating the client-side implementation.

SOA: Stands for Service Oriented Architecture

Includes all of the programming with web services concepts and architecture. Imagine that you want to implement a large-scale application. One practice can be having some different services, called micro-services and the whole application mechanism would be calling needed web service at the right time. Both REST and SOAP web services are kind of SOA.

JSON: Stands for javascript Object Notation

when you serialize an object for javascript the type of object format is JSON. imagine that you have the human class :

class Human{
 string Name;
 string Family;
 int Age;
}

and you have some instances from this class :

Human h1 = new Human(){
  Name='Saman',
  Family='Gholami',
  Age=26
}

when you serialize the h1 object to JSON the result is :

  [h1:{Name:'saman',Family:'Gholami',Age:'26'}, ...]

javascript can evaluate this format by eval() function and make an associative array from this JSON string. This one is different concept in comparison to other concepts I described formerly.

Saving awk output to variable

variable=$(ps -ef | awk '/[p]ort 10/ {print $12}')

The [p] is a neat trick to remove the search from showing from ps

@Jeremy If you post the output of ps -ef | grep "port 10", and what you need from the line, it would be more easy to help you getting correct syntax

Center Align on a Absolutely Positioned Div

Your problem may be solved if you give your div a fixed width, as follows:

div#thing {
    position: absolute;
    top: 0px;
    z-index: 2;
    width:400px;
    margin-left:-200px;
    left:50%;
}