Programs & Examples On #Clsid

A CLSID is a globally unique identifier that identifies a COM class object.

use "netsh wlan set hostednetwork ..." to create a wifi hotspot and the authentication can't work correctly

Use these commands on a windows command prompt(cmd) with administrator privilege (run as administrator):

netsh wlan set hostednetwork mode=allow ssid=tests key=tests123

netsh wlan start hostednetwork

Then you go to Network and sharing center and click on "change adapter settings" (I'm using windows 7, it can be a little different on windows 8)

Then right click on the lan connection (internet connection that you are using), properties.

Click on sharing tab, select the wireless connection tests (the name tests you can change on the command line) and check "Allow other network users to connect through this network connection"

This done, your connection is ready to use!

How to playback MKV video in web browser?

You can use this following code. work just on chrome browser.

_x000D_
_x000D_
 function failed(e) {_x000D_
   // video playback failed - show a message saying why_x000D_
   switch (e.target.error.code) {_x000D_
     case e.target.error.MEDIA_ERR_ABORTED:_x000D_
       alert('You aborted the video playback.');_x000D_
       break;_x000D_
     case e.target.error.MEDIA_ERR_NETWORK:_x000D_
       alert('A network error caused the video download to fail part-way.');_x000D_
       break;_x000D_
     case e.target.error.MEDIA_ERR_DECODE:_x000D_
       alert('The video playback was aborted due to a corruption problem or because the video used features your browser did not support.');_x000D_
       break;_x000D_
     case e.target.error.MEDIA_ERR_SRC_NOT_SUPPORTED:_x000D_
       alert('The video could not be loaded, either because the server or network failed or because the format is not supported.');_x000D_
       break;_x000D_
     default:_x000D_
       alert('An unknown error occurred.');_x000D_
       break;_x000D_
   }_x000D_
 }
_x000D_
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">_x000D_
_x000D_
<head>_x000D_
 <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />_x000D_
 <meta name="author" content="Amin Developer!" />_x000D_
_x000D_
 <title>Untitled 1</title>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<p><video src="http://jell.yfish.us/media/Jellyfish-3-Mbps.mkv" type='video/x-matroska; codecs="theora, vorbis"' autoplay controls onerror="failed(event)" ></video></p>_x000D_
<p><a href="YOU mkv FILE LINK GOES HERE TO DOWNLOAD">Download the video file</a>.</p>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

" netsh wlan start hostednetwork " command not working no matter what I try

Same issue.

I solved the problem first activating (right click mouse and select activate) from control panel (network connections) and later changing to set mode to allow (by netsh command), to finally starting the hostednetwork with other netsh command, that is:

1.- Activate (Network Connections) by right click

2.- netsh wlan set hostednetwork mode=allow

3.- netsh wlan start hosted network

Good luck mate !!!

Class not registered Error

I had the same problem. I tried lot of ways but at last solution was simple. Solution: Open IIS, In Application Pools, right click on the .net framework that is being used. Go to settings and change 'Enable 32-Bit Applications' to 'True'.

"Retrieving the COM class factory for component.... error: 80070005 Access is denied." (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))

I just created a simple application

What is the target processor of the application? I am guessing it is x86 - so either set it to x64 or anycpu.

I think the issue you are having is due to a 64bit process trying to access a 32bit dll.

Also, if you can't change the target processor you could try to enable 32-bit Applications from the Application Pools settings in IIS.

Embedding VLC plugin on HTML page

I found this piece of code somewhere in the web. Maybe it helps you and I give you an update so far I accomodated it for the same purpose... Maybe I don't.... who the futt knows... with all the nogodders and dobedders in here :-/

function runVLC(target, stream)
{
var support=true
var addr='rtsp://' + window.location.hostname + stream
if ($.browser.msie){
$(target).html('<object type = "application/x-vlc-plugin"' + 'version =  
"VideoLAN.VLCPlugin.2"' + 'classid = "clsid:9BE31822-FDAD-461B-AD51-BE1D1C159921"' + 
'events = "true"' + 'id = "vlc"></object>')
}
else if ($.browser.mozilla || $.browser.webkit){
$(target).html('<embed type = "application/x-vlc-plugin"' + 'class="vlc_plugin"' + 
'pluginspage="http://www.videolan.org"' + 'version="VideoLAN.VLCPlugin.2" ' + 
'width="660" height="372"' + 
'id="vlc"' + 'autoplay="true"' + 'allowfullscreen="false"' + 'windowless="true"' + 
'mute="false"' + 'loop="true"' + '<toolbar="false"' + 'bgcolor="#111111"' + 
'branding="false"' + 'controls="false"' + 'aspectRatio="16:9"' + 
'target="whatever.mp4"></embed>')
}
else{
support=false
$(target).empty().html('<div id = "dialog_error">Error: browser not supported!</div>')
}
if (support){
var vlc = document.getElementById('vlc')
if (vlc){
var opt = new Array(':network-caching=300')
try{
var id = vlc.playlist.add(addr, '', opt)
vlc.playlist.playItem(id)
}
catch (e){
$(target).empty().html('<div id = "dialog_error">Error: ' + e + '<br>URL: ' + addr + 
'</div>')
}
}
}
}
/* $(target + ' object').css({'width': '100%', 'height': '100%'}) */

Greets

Gee

I reduce the whole crap now to:

function runvlc(){
var target=$('body')
var error=$('#dialog_error')
var support=true
var addr='rtsp://../html/media/video/TESTCARD.MP4'
if (navigator.userAgent.toLowerCase().indexOf("msie")!=-1){
target.append('<object type = "application/x-vlc-plugin"' + 'version = "
VideoLAN.VLCPlugin.2"' + 'classid = "clsid:9BE31822-FDAD-461B-AD51-BE1D1C159921"' + 
'events = "true"' + 'id = "vlc"></object>')
}
else if (navigator.userAgent.toLowerCase().indexOf("msie")==-1){
target.append('<embed type = "application/x-vlc-plugin"' + 'class="vlc_plugin"' + 
'pluginspage="http://www.videolan.org"' + 'version="VideoLAN.VLCPlugin.2" ' + 
'width="660" height="372"' + 
'id="vlc"' + 'autoplay="true"' + 'allowfullscreen="false"' + 'windowless="true"' + 
'mute="false"' + 'loop="true"' + '<toolbar="false"' + 'bgcolor="#111111"' + 
'branding="false"' + 
'controls="false"' + 'aspectRatio="16:9"' + 'target="whatever.mp4">
</embed>')
}
else{
support=false
error.empty().html('Error: browser not supported!')
error.show()
if (support){
var vlc=document.getElementById('vlc')
if (vlc){
var options=new Array(':network-caching=300') /* set additional vlc--options */
try{ /* error handling */
var id = vlc.playlist.add(addr,'',options)
vlc.playlist.playItem(id)
}
catch (e){
error.empty().html('Error: ' + e + '<br>URL: ' + addr + '')
error.show()
}
}
}
}
};

Didn't get it to work in ie as well... 2b continued...

Greets

Gee

How to use Microsoft.Office.Interop.Excel on a machine without installed MS Office?

If the "Customer don't want to install and buy MS Office on a server not at any price", then you cannot use Excel ... But I cannot get the trick: it's all about one basic Office licence which costs something like 150 USD ... And I guess that spending time finding an alternative will cost by far more than this amount!

"Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))"

My fix was to create Platform in configuration manager in visual studio, and set to x64

how to display excel sheet in html page

You can upload it into Google Docs, and embed the Google Spreadsheet as detailed here: http://support.google.com/docs/bin/answer.py?hl=en&answer=55244

How to repair COMException error 80040154?

Move excel variables which are global declare in your form to local like in my form I have:

Dim xls As New MyExcel.Interop.Application  
Dim xlb As MyExcel.Interop.Workbook

above two lines were declare global in my form so i moved these two lines to local function and now tool is working fine.

How to send a pdf file directly to the printer using JavaScript?

There are two steps you need to take.

First, you need to put the PDF in an iframe.

  <iframe id="pdf" name="pdf" src="document.pdf"></iframe>

To print the iframe you can look at the answers here:

Javascript Print iframe contents only

If you want to print the iframe automatically after the PDF has loaded, you can add an onload handler to the <iframe>:

  <iframe onload="isLoaded()" id="pdf" name="pdf" src="document.pdf"></iframe>

the loader can look like this:

function isLoaded()
{
  var pdfFrame = window.frames["pdf"];
  pdfFrame.focus();
  pdfFrame.print();
}

This will display the browser's print dialog, and then print just the PDF document itself. (I personally use the onload handler to enable a "print" button so the user can decide to print the document, or not).

I'm using this code pretty much verbatim in Safari and Chrome, but am yet to try it on IE or Firefox.

How to avoid a System.Runtime.InteropServices.COMException?

Your code (or some code called by you) is making a call to a COM method which is returning an unknown value. If you can find that then you're half way there.

You could try breaking when the exception is thrown. Go to Debug > Exceptions... and use the Find... option to locate System.Runtime.InteropServices.COMException. Tick the option to break when it's thrown and then debug your application.

Hopefully it will break somewhere meaningful and you'll be able to trace back and find the source of the error.

Error 80040154 (Class not registered exception) when initializing VCProjectEngineObject (Microsoft.VisualStudio.VCProjectEngine.dll)

There are not many good reasons this would fail, especially the regsvr32 step. Run dumpbin /exports on that dll. If you don't see DllRegisterServer then you've got a corrupt install. It should have more side-effects, you wouldn't be able to build C/C++ projects anymore.

One standard failure mode is running this on a 64-bit operating system. This is 32-bit unmanaged code, you would indeed get the 'class not registered' exception. Project + Properties, Build tab, change Platform Target to x86.

HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))

This could also be an issue of building the code using a 64 bit configuration. You can try to select x86 as the build platform which can solve this issue. To do this right-click the solution and select Configuration Manager From there you can change the Platform of the project using the 32-bit .dll to x86

Retrieving the COM class factory for component with CLSID {XXXX} failed due to the following error: 80040154

The problem is that the server process is 64 bit and the library is 32-bit and it tries to create the COM component in the same process (in-proc server). Either you recompile the server and make it 32-bit or you leave the server unchanged and make the COM component out-of-process. The easiest way to make a COM server out-of-process is to create a COM+ application - Control Panel -> Administrative Tools -> ComponentServices.

Retrieving the COM class factory for component failed

There's one more issue you might need to address if you are using the Windows 2008 Server with IIS7. The server might report the following error:

Microsoft Office Excel cannot access the file 'c:\temp\test.xls'. There are several possible reasons:

  • The file name or path does not exist.
  • The file is being used by another program.
  • The workbook you are trying to save has the same name as a currently open workbook.

The solution is posted here (look for the text posted by user Ogawa): http://social.msdn.microsoft.com/Forums/en-US/innovateonoffice/thread/b81a3c4e-62db-488b-af06-44421818ef91?prof=required

How can Print Preview be called from Javascript?

I think the best that's possible in cross-browser JavaScript is window.print(), which (in Firefox 3, for me) brings up the 'print' dialog and not the print preview dialog.

FYI, the print dialog is your computer's Print popup, what you get when you do Ctrl-p. The print preview is Firefox's own Preview window, and it has more options. It's what you get with Firefox Menu > Print...

Python Linked List

llist — Linked list datatypes for Python

llist module implements linked list data structures. It supports a doubly linked list, i.e. dllist and a singly linked data structure sllist.

dllist objects

This object represents a doubly linked list data structure.

first

First dllistnode object in the list. None if list is empty.

last

Last dllistnode object in the list. None if list is empty.

dllist objects also support the following methods:

append(x)

Add x to the right side of the list and return inserted dllistnode.

appendleft(x)

Add x to the left side of the list and return inserted dllistnode.

appendright(x)

Add x to the right side of the list and return inserted dllistnode.

clear()

Remove all nodes from the list.

extend(iterable)

Append elements from iterable to the right side of the list.

extendleft(iterable)

Append elements from iterable to the left side of the list.

extendright(iterable)

Append elements from iterable to the right side of the list.

insert(x[, before])

Add x to the right side of the list if before is not specified, or insert x to the left side of dllistnode before. Return inserted dllistnode.

nodeat(index)

Return node (of type dllistnode) at index.

pop()

Remove and return an element’s value from the right side of the list.

popleft()

Remove and return an element’s value from the left side of the list.

popright()

Remove and return an element’s value from the right side of the list

remove(node)

Remove node from the list and return the element which was stored in it.

dllistnode objects

class llist.dllistnode([value])

Return a new doubly linked list node, initialized (optionally) with value.

dllistnode objects provide the following attributes:

next

Next node in the list. This attribute is read-only.

prev

Previous node in the list. This attribute is read-only.

value

Value stored in this node. Compiled from this reference

sllist

class llist.sllist([iterable]) Return a new singly linked list initialized with elements from iterable. If iterable is not specified, the new sllist is empty.

A similar set of attributes and operations are defined for this sllist object. See this reference for more information.

Disable same origin policy in Chrome

For Selenium Webdriver, you can have selenium start Chrome with the appropriate arguments (or "switches") in this case.

 @driver = Selenium::WebDriver.for(:Chrome, { 
       :detach => false,
       :switches => ["--disable-web-security"]
    })

No Main class found in NetBeans

In project properties, under the run tab, specify your main class. Moreover, To avoid this issue, you need to check "Create main class" during creating new project. Specifying main class in properties should always work, but if in some rare case it doesn't work, then the issue could be resolved by re-creating the project and not forgetting to check "Create main class" if it is unchecked.

How do you create optional arguments in php?

Some notes that I also found useful:

  • Keep your default values on the right side.

    function whatever($var1, $var2, $var3="constant", $var4="another")
    
  • The default value of the argument must be a constant expression. It can't be a variable or a function call.

How can I change the color of AlertDialog title and the color of the line under it

Instead of using divider in dialog, use the view in the custom layout and set the layout as custom layout in dialog.

custom_popup.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">

    <com.divago.view.TextViewMedium
        android:id="@+id/txtTitle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:paddingBottom="10dp"
        android:paddingTop="10dp"
        android:text="AlertDialog"
        android:textColor="@android:color/black"
        android:textSize="20sp" />

    <View
        android:id="@+id/border"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_below="@id/txtTitle"
        android:background="@color/txt_dark_grey" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/border"
        android:scrollbars="vertical">

        <com.divago.view.TextViewRegular
            android:id="@+id/txtPopup"
            android:layout_margin="15dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </ScrollView>
</RelativeLayout>

activity.java:

public void showPopUp(String title, String text) {

    LayoutInflater inflater = getLayoutInflater();
    View alertLayout = inflater.inflate(R.layout.custom_popup, null);

    TextView txtContent = alertLayout.findViewById(R.id.txtPopup);
    txtContent.setText(text);

    TextView txtTitle = alertLayout.findViewById(R.id.txtTitle);
    txtTitle.setText(title);

    AlertDialog.Builder alert = new AlertDialog.Builder(this);
    alert.setView(alertLayout);
    alert.setCancelable(true);

    alert.setPositiveButton("Done", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });

    AlertDialog dialog = alert.create();
    dialog.show();
}

Request UAC elevation from within a Python script?

A variation on Jorenko's work above allows the elevated process to use the same console (but see my comment below):

def spawn_as_administrator():
    """ Spawn ourself with administrator rights and wait for new process to exit
        Make the new process use the same console as the old one.
          Raise Exception() if we could not get a handle for the new re-run the process
          Raise pywintypes.error() if we could not re-spawn
        Return the exit code of the new process,
          or return None if already running the second admin process. """
    #pylint: disable=no-name-in-module,import-error
    import win32event, win32api, win32process
    import win32com.shell.shell as shell
    if '--admin' in sys.argv:
        return None
    script = os.path.abspath(sys.argv[0])
    params = ' '.join([script] + sys.argv[1:] + ['--admin'])
    SEE_MASK_NO_CONSOLE = 0x00008000
    SEE_MASK_NOCLOSE_PROCESS = 0x00000040
    process = shell.ShellExecuteEx(lpVerb='runas', lpFile=sys.executable, lpParameters=params, fMask=SEE_MASK_NO_CONSOLE|SEE_MASK_NOCLOSE_PROCESS)
    hProcess = process['hProcess']
    if not hProcess:
        raise Exception("Could not identify administrator process to install drivers")
    # It is necessary to wait for the elevated process or else
    #  stdin lines are shared between 2 processes: they get one line each
    INFINITE = -1
    win32event.WaitForSingleObject(hProcess, INFINITE)
    exitcode = win32process.GetExitCodeProcess(hProcess)
    win32api.CloseHandle(hProcess)
    return exitcode

Class 'DOMDocument' not found

On fedora 26:

dnf install php-dom

Fixes it !

How to convert BigDecimal to Double in Java?

Use doubleValue method present in BigDecimal class :

double doubleValue()

Converts this BigDecimal to a double.

Delete newline in Vim

It probably depends on your settings, but I usually do this with A<delete>

Where A is append at the end of the line. It probably requires nocompatible mode :)

When to use If-else if-else over switch statements and vice versa

I personally prefer to see switch statements over too many nested if-elses because they can be much easier to read. Switches are also better in readability terms for showing a state.

See also the comment in this post regarding pacman ifs.

Dividing two integers to produce a float result

Cast the operands to floats:

float ans = (float)a / (float)b;

Cross browser JavaScript (not jQuery...) scroll to top animation

Yet another approach is using window.scrollBy

JSFiddle

_x000D_
_x000D_
function scroll(pxPerFrame, duration) {_x000D_
        if (!pxPerFrame || !duration) return;_x000D_
        const end = new Date().getTime() + duration;_x000D_
        step(); _x000D_
_x000D_
        function step() {_x000D_
          window.scrollBy(0, pxPerFrame);_x000D_
          if (new Date().getTime() < end) {_x000D_
            window.setTimeout(step, 1000 / 60);_x000D_
          } else {_x000D_
            console.log('done scrolling'); _x000D_
          }_x000D_
        }_x000D_
      }
_x000D_
body {_x000D_
  width: 200px;_x000D_
}
_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>_x000D_
<p>_x000D_
<button onclick="scroll(-5, 3000)">_x000D_
scroll(-5, 3000)_x000D_
</button>_x000D_
</p>
_x000D_
_x000D_
_x000D_

How to solve PHP error 'Notice: Array to string conversion in...'

When you have many HTML inputs named C[] what you get in the POST array on the other end is an array of these values in $_POST['C']. So when you echo that, you are trying to print an array, so all it does is print Array and a notice.

To print properly an array, you either loop through it and echo each element, or you can use print_r.

Alternatively, if you don't know if it's an array or a string or whatever, you can use var_dump($var) which will tell you what type it is and what it's content is. Use that for debugging purposes only.

How do I configure php to enable pdo and include mysqli on CentOS?

mysqli is provided by php-mysql-5.3.3-40.el6_6.x86_64

You may need to try the following

yum install php-mysql-5.3.3-40.el6_6.x86_64

Is there any boolean type in Oracle databases?

There is a boolean type for use in pl/sql, but none that can be used as the data type of a column.

jQuery posting JSON

'data' should be a stringified JavaScript object:

data: JSON.stringify({ "userName": userName, "password" : password })

To send your formData, pass it to stringify:

data: JSON.stringify(formData)

Some servers also require the application/json content type:

contentType: 'application/json'

There's also a more detailed answer to a similar question here: Jquery Ajax Posting json to webservice

Prevent onmouseout when hovering child element of the parent absolute div WITHOUT jQuery

If you have access to the element which the event is attached to inside the mouseout method, you can use contains() to see if the event.relatedTarget is a child element or not.

As event.relatedTarget is the element to which the mouse has passed into, if it isn't a child element, you have moused out of the element.

div.onmouseout = function (event) {
    if (!div.contains(event.relatedTarget)) {
        // moused out of div
    }
}

PHP + MySQL transactions examples

<?php

// trans.php
function begin(){
    mysql_query("BEGIN");
}

function commit(){
    mysql_query("COMMIT");
}

function rollback(){
    mysql_query("ROLLBACK");
}

mysql_connect("localhost","Dude1", "SuperSecret") or die(mysql_error());

mysql_select_db("bedrock") or die(mysql_error());

$query = "INSERT INTO employee (ssn,name,phone) values ('123-45-6789','Matt','1-800-555-1212')";

begin(); // transaction begins

$result = mysql_query($query);

if(!$result){
    rollback(); // transaction rolls back
    echo "transaction rolled back";
    exit;
}else{
    commit(); // transaction is committed
    echo "Database transaction was successful";
}

?>

Static constant string (class member)

To use that in-class initialization syntax, the constant must be a static const of integral or enumeration type initialized by a constant expression.

This is the restriction. Hence, in this case you need to define variable outside the class. refer answwer from @AndreyT

Eclipse: "'Periodic workspace save.' has encountered a pro?blem."

Today I faced the same issue consistently, whenever I exit the eclipse. While trying the above solution provided by TS.xy, the below steps got rid of this issue for now.

  1. Switch to new workspace and close the Eclipse.
  2. Open the Eclipse with new workspace and after that switch to the actual workspace(in which exception occurs).
  3. Actual workspace loaded with all my previous projects.
  4. Now exiting the Eclipse, does not result in that exception.

Hope that this step may work for someone.

Difference between Method and Function?

From Object-Oriented Programming Concept:

If you have a function that is accessing/muttating the fields of your class, it becomes method. Otherwise, it is a function.

It will not be a crime if you keep calling all the functions in Java/C++ classes as methods. The reason is that you are directly/indirectly accessing/mutating class properties. So why not all the functions in Java/C++ classes are methods?

How to read a Parquet file into Pandas DataFrame?

Aside from pandas, Apache pyarrow also provides way to transform parquet to dataframe

The code is simple, just type:

import pyarrow.parquet as pq

df = pq.read_table(source=your_file_path).to_pandas()

For more information, see the document from Apache pyarrow Reading and Writing Single Files

What is the difference between logical data model and conceptual data model?

In the conceptual data model you worry only about the high level design - what tables should exist and the connections between them. In this phase you recognize entities in your model and the relationships between them.

The logical model comes after the conceptual modeling when you explicitly define what the columns in each table are. While writing the logical model, you might also take into consideration the actual database system you're designing for, but only if it affects the design (i.e., if there are no triggers you might want to remove some redundancy column etc.)

There is also physical model which elaborates on the logical model and assigns each column with it's type/length etc.

Here is a good table and picture that describes each of the three levels.

|----------------------|------------|---------|----------|
| Feature              | Conceptual | Logical | Physical | 
|----------------------|------------|---------|----------|
| Entity Names         | X          | X       |          |
| Entity Relationships | X          | X       |          |
| Attributes           |            | X       |          |
| Primary Keys         |            | X       | X        |
| Foreign Keys         |            | X       | X        |
| Table Names          |            |         | X        |
| Column Names         |            |         | X        |
| Column Data Types    |            |         | X        |
|----------------------|------------|---------|----------|

data modeling levels from https://www.1keydata.com/datawarehousing/data-modeling-levels.html

How to make an introduction page with Doxygen

As of v1.8.8 there is also the option USE_MDFILE_AS_MAINPAGE. So make sure to add your index file, e.g. README.md, to INPUT and set it as this option's value:

INPUT += README.md
USE_MDFILE_AS_MAINPAGE = README.md

Webpack how to build production code and how to use it

Use these plugins to optimize your production build:

  new webpack.optimize.CommonsChunkPlugin('common'),
  new webpack.optimize.DedupePlugin(),
  new webpack.optimize.UglifyJsPlugin(),
  new webpack.optimize.AggressiveMergingPlugin()

I recently came to know about compression-webpack-plugin which gzips your output bundle to reduce its size. Add this as well in the above listed plugins list to further optimize your production code.

new CompressionPlugin({
      asset: "[path].gz[query]",
      algorithm: "gzip",
      test: /\.js$|\.css$|\.html$/,
      threshold: 10240,
      minRatio: 0.8
})

Server side dynamic gzip compression is not recommended for serving static client-side files because of heavy CPU usage.

How to loop through an associative array and get the key?

I use the following loop to get the key and value from an associative array

foreach ($array as $key => $value)
{
  echo "<p>$key = $value</p>";
}

Find max and second max salary for a employee table MySQL

Here is another solution which uses sub query but instead of IN clause it uses < operator

SELECT MAX(Salary) From Employees WHERE Salary < ( SELECT Max(Salary) FROM Employees);

How do I debug "Error: spawn ENOENT" on node.js?

in windows, simply adding shell: true option solved my problem:

incorrect:

const { spawn } = require('child_process');
const child = spawn('dir');

correct:

const { spawn } = require('child_process');
const child = spawn('dir', [], {shell: true});

JRE installation directory in Windows

Not as a command, but this information is in the registry:

  • Open the key HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment
  • Read the CurrentVersion REG_SZ
  • Open the subkey under Java Runtime Environment named with the CurrentVersion value
  • Read the JavaHome REG_SZ to get the path

For example on my workstation i have

HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment
  CurrentVersion = "1.6"
HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\1.5
  JavaHome = "C:\Program Files\Java\jre1.5.0_20"
HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\1.6
  JavaHome = "C:\Program Files\Java\jre6"

So my current JRE is in C:\Program Files\Java\jre6

Where can I download JSTL jar

In the past, there was something like: https: //jstl.dev.java.net/download.html. But since a few days, there is something happening on dev.java.net.

Java.net will be modified, read this: http: //www.java.net/. So I think we have to wait. I also found: http: //java.net/projects/help/pages/RequestedProjects.

Maybe this is helpful.

Another option is to look into the maven repository: http://repo1.maven.org/maven2/javax/servlet/

C# DataTable.Select() - How do I format the filter criteria to include null?

Try this

myDataTable.Select("[Name] is NULL OR [Name] <> 'n/a'" )

Edit: Relevant sources:

How can I repeat a character in Bash?

Here's two interesting ways:

ubuntu@ubuntu:~$ yes = | head -10 | paste -s -d '' -
==========
ubuntu@ubuntu:~$ yes = | head -10 | tr -d "\n"
==========ubuntu@ubuntu:~$ 

Note these two are subtly different - The paste method ends in a new line. The tr method does not.

Does Android support near real time push notification?

I have recently developed http://pushdroid.org its a single application that should be installed on the phone just like google has implemented it in 2.2 this works from 1.5 and is broadcasting via intent.

How to find the remainder of a division in C?

Use the modulus operator %, it returns the remainder.

int a = 5;
int b = 3;

if (a % b != 0) {
   printf("The remainder is: %i", a%b);
}

Make an image responsive - the simplest way

To make an image responsive use the following:

CSS

.responsive-image {
        width: 950px;//Any width you want to set the image to.
        max-width: 100%;
        height: auto;
}

HTML

<img class="responsive-image" src="IMAGE URL">

How do I create a crontab through a script

For user crontabs (including root), you can do something like:

crontab -l -u user | cat - filename | crontab -u user -

where the file named "filename" contains items to append. You could also do text manipulation using sed or another tool in place of cat. You should use the crontab command instead of directly modifying the file.

A similar operation would be:

{ crontab -l -u user; echo 'crontab spec'; } | crontab -u user -

If you are modifying or creating system crontabs, those may be manipulated as you would ordinary text files. They are stored in the /etc/cron.d, /etc/cron.hourly, /etc/cron.daily, /etc/cron.weekly, /etc/cron.monthly directories and in the files /etc/crontab and /etc/anacrontab.

Easiest way to read from and write to files

@AlexeiLevenkov pointed me at another "easiest way" namely the extension method. It takes just a little coding, then provides the absolute easiest way to read/write, plus it offers the flexibility to create variations according to your personal needs. Here is a complete example:

This defines the extension method on the string type. Note that the only thing that really matters is the function argument with extra keyword this, that makes it refer to the object that the method is attached to. The class name does not matter; the class and method must be declared static.

using System.IO;//File, Directory, Path

namespace Lib
{
    /// <summary>
    /// Handy string methods
    /// </summary>
    public static class Strings
    {
        /// <summary>
        /// Extension method to write the string Str to a file
        /// </summary>
        /// <param name="Str"></param>
        /// <param name="Filename"></param>
        public static void WriteToFile(this string Str, string Filename)
        {
            File.WriteAllText(Filename, Str);
            return;
        }

        // of course you could add other useful string methods...
    }//end class
}//end ns

This is how to use the string extension method, note that it refers automagically to the class Strings:

using Lib;//(extension) method(s) for string
namespace ConsoleApp_Sandbox
{
    class Program
    {
        static void Main(string[] args)
        {
            "Hello World!".WriteToFile(@"c:\temp\helloworld.txt");
            return;
        }

    }//end class
}//end ns

I would never have found this myself, but it works great, so I wanted to share this. Have fun!

PostgreSQL: insert from another table

Just supply literal values in the SELECT:

INSERT INTO TABLE1 (id, col_1, col_2, col_3)
SELECT id, 'data1', 'data2', 'data3'
FROM TABLE2
WHERE col_a = 'something';

A select list can contain any value expression:

But the expressions in the select list do not have to reference any columns in the table expression of the FROM clause; they can be constant arithmetic expressions, for instance.

And a string literal is certainly a value expression.

HTTP Error 401.2 - Unauthorized You are not authorized to view this page due to invalid authentication headers

Make sure Anonymous access is enabled on IIS -> Authentication.

But also right click on it, then click on Edit, and choose a domain\username and password. (With access to the physical folder of the application).

The program can't start because MSVCR110.dll is missing from your computer

I was getting a similar issue from the Apache Lounge 32 bit version. After downloading the 64 bit version, the issue was resolved.

Here is an excellent video explain the steps involved: https://www.youtube.com/watch?v=17qhikHv5hY

Calling one Bash script from another Script passing it arguments with quotes and spaces

I found following program works for me

test1.sh 
a=xxx
test2.sh $a

in test2.sh you use $1 to refer variable a in test1.sh

echo $1

The output would be xxx

How to set custom header in Volley Request

Here is setting headers from github sample:

StringRequest myReq = new StringRequest(Method.POST,
                       "http://ave.bolyartech.com/params.php",
                        createMyReqSuccessListener(),
                        createMyReqErrorListener()) {

 protected Map<String, String> getParams() throws 
         com.android.volley.AuthFailureError {
                        Map<String, String> params = new HashMap<String, String>();
                        params.put("param1", num1);
                        params.put("param2", num2);
                        return params;
                    };
                };
                queue.add(myReq);

Get/pick an image from Android's built-in Gallery app programmatically

Above Answers are correct. I faced an different issue where in HTC M8 my application crashes when selecting an image from gallery. I'm getting null value for image path. I fixed and optimized with the following solution. in onActivityResult method

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if ((requestCode == RESULT_LOAD_IMAGE) && (resultCode == RESULT_OK)) {
     if (data != null) {

            Uri selectedImageUri = null;
            selectedImageUri = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            Cursor imageCursor = mainActivity.getContentResolver().query(
                    selectedImageUri, filePathColumn, null, null, null);

            if (imageCursor == null) {
                return;
            }

            imageCursor.moveToFirst();
            int columnIndex = imageCursor.getColumnIndex(filePathColumn[0]);
            picturePath = imageCursor.getString(columnIndex);
            if (picturePath == null) {
                picturePath = selectedImageUri.getPath();
                String wholeID = DocumentsContract
                        .getDocumentId(selectedImage);

                // Split at colon, use second item in the array
                String id = wholeID.split(":")[1];

                String[] column = { MediaStore.Images.Media.DATA };

                // where id is equal to
                String sel = MediaStore.Images.Media._ID + "=?";

                Cursor cursor = mainActivity.getContentResolver().query(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        column, sel, new String[] { id }, null);

                columnIndex = cursor.getColumnIndex(column[0]);

                if (cursor.moveToFirst()) {
                    picturePath = cursor.getString(columnIndex);
                }

                cursor.close();
            }
            picturePathAbs = new File(picturePath).getAbsolutePath();
            imageCursor.close();
        }

}

How can I merge the columns from two tables into one output?

I guess that what you want to do is an UNION of both tables.

If both tables have the same columns then you can just do

SELECT category_id, col1, col2, col3
  FROM items_a
UNION 
SELECT category_id, col1, col2, col3 
  FROM items_b

Else, you might have to do something like

SELECT category_id, col1, col2, col3
  FROM items_a 
UNION 
SELECT category_id, col_1 as col1, col_2 as col2, col_3 as col3
  FROM items_b

What EXACTLY is meant by "de-referencing a NULL pointer"?

A NULL pointer points to memory that doesn't exist. This may be address 0x00000000 or any other implementation-defined value (as long as it can never be a real address). Dereferencing it means trying to access whatever is pointed to by the pointer. The * operator is the dereferencing operator:

int a, b, c; // some integers
int *pi;     // a pointer to an integer

a = 5;
pi = &a; // pi points to a
b = *pi; // b is now 5
pi = NULL;
c = *pi; // this is a NULL pointer dereference

This is exactly the same thing as a NullReferenceException in C#, except that pointers in C can point to any data object, even elements inside an array.

int value under 10 convert to string two digit number

i.ToString("00")

or

i.ToString("000")

depending on what you want

Look at the MSDN article on custom numeric format strings for more options: http://msdn.microsoft.com/en-us/library/0c899ak8(VS.71).aspx

Error in MySQL when setting default value for DATE or DATETIME

I got into a situation where the data was mixed between NULL and 0000-00-00 for a date field. But I did not know how to update the '0000-00-00' to NULL, because

 update my_table set my_date_field=NULL where my_date_field='0000-00-00'

is not allowed any more. My workaround was quite simple:

update my_table set my_date_field=NULL where my_date_field<'1000-01-01'

because all the incorrect my_date_field values (whether correct dates or not) were from before this date.

Get last 5 characters in a string

Checks for errors:

Dim result As String = str
If str.Length > 5 Then
    result = str.Substring(str.Length - 5)
End If

VBA: Selecting range by variables

you are turning them into an address but Cells(#,#) uses integer inputs not address inputs so just use lastRow = ActiveSheet.UsedRange.Rows.count and lastColumn = ActiveSheet.UsedRange.Columns.Count

Node.js version on the command line? (not the REPL)

By default node package is nodejs, so use

$ nodejs -v

or

$ nodejs --version 

You can make a link using

$ sudo ln -s /usr/bin/nodejs /usr/bin/node

then u can use

$ node --version

or

$ node -v

Appending pandas dataframes generated in a for loop

you can try this.

data_you_need=pd.DataFrame()
for infile in glob.glob("*.xlsx"):
    data = pandas.read_excel(infile)
    data_you_need=data_you_need.append(data,ignore_index=True)

I hope it can help.

Convert date field into text in Excel

You don't need to convert the original entry - you can use TEXT function in the concatenation formula, e.g. with date in A1 use a formula like this

="Today is "&TEXT(A1,"dd-mm-yyyy")

You can change the "dd-mm-yyyy" part as required

Disable single warning error

#pragma push/pop are often a solution for this kind of problems, but in this case why don't you just remove the unreferenced variable?

try
{
    // ...
}
catch(const your_exception_type &) // type specified but no variable declared
{
    // ...
}

Chaining multiple filter() in Django, is this a bug?

Saw this in a comment and I thought it was the simplest explanation.

filter(A, B) is the AND filter(A).filter(B) is OR

iPhone 6 and 6 Plus Media Queries

For iPhone 5,

@media screen and (device-aspect-ratio: 40/71)

for iPhone 6,7,8

@media only screen and (min-device-width: 375px) and (max-device-width: 667px) and (orientation : portrait)

for iPhone 6+,7+,8+

@media screen and (-webkit-device-pixel-ratio: 3) and (min-device-width: 414px)

Working fine for me as of now.

Maven not found in Mac OSX mavericks

Maven is not installed any more by default on Mac OS X 10.9. You need to install it yourself, for example using Homebrew.

The command to install Maven using Homebrew is brew install maven

How to reload .bash_profile from the command line?

  1. Save .bash_profile file
  2. Goto user's home directory by typing cd
  3. Reload the profile with . .bash_profile

Which MySQL datatype to use for an IP address?

Since IPv4 addresses are 4 byte long, you could use an INT (UNSIGNED) that has exactly 4 bytes:

`ipv4` INT UNSIGNED

And INET_ATON and INET_NTOA to convert them:

INSERT INTO `table` (`ipv4`) VALUES (INET_ATON("127.0.0.1"));
SELECT INET_NTOA(`ipv4`) FROM `table`;

For IPv6 addresses you could use a BINARY instead:

`ipv6` BINARY(16)

And use PHP’s inet_pton and inet_ntop for conversion:

'INSERT INTO `table` (`ipv6`) VALUES ("'.mysqli_real_escape_string(inet_pton('2001:4860:a005::68')).'")'
'SELECT `ipv6` FROM `table`'
$ipv6 = inet_pton($row['ipv6']);

How to enable back/left swipe gesture in UINavigationController after setting leftBarButtonItem?

I did not need to add gestureRecognizer functions for it. It was enough for me to add following code blocks at viewDidLoad:

override func viewDidLoad() {
    super.viewDidLoad()
    self.navigationController?.interactivePopGestureRecognizer?.delegate = nil
    self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true
}

Blade if(isset) is not working Laravel

@forelse ($users as $user)
    <li>{{ $user->name }}</li>
@empty
    <p>No users</p>
@endforelse

How are software license keys generated?

The key system must have several properties:

  • very few keys must be valid
  • valid keys must not be derivable even given everything the user has.
  • a valid key on one system is not a valid key on another.
  • others

One solution that should give you these would be to use a public key signing scheme. Start with a "system hash" (say grab the macs on any NICs, sorted, and the CPU-ID info, plus some other stuff, concatenate it all together and take an MD5 of the result (you really don't want to be handling personally identifiable information if you don't have to)) append the CD's serial number and refuse to boot unless some registry key (or some datafile) has a valid signature for the blob. The user activates the program by shipping the blob to you and you ship back the signature.

Potential issues include that you are offering to sign practically anything so you need to assume someone will run a chosen plain text and/or chosen ciphertext attacks. That can be mitigated by checking the serial number provided and refusing to handle request from invalid ones as well as refusing to handle more than a given number of queries from a given s/n in an interval (say 2 per year)

I should point out a few things: First, a skilled and determined attacker will be able to bypass any and all security in the parts that they have unrestricted access to (i.e. everything on the CD), the best you can do on that account is make it harder to get illegitimate access than it is to get legitimate access. Second, I'm no expert so there could be serious flaws in this proposed scheme.

How do you determine what technology a website is built on?

yes there are some telltale signs for common CMSs like Drupal, Joomla, Pligg, and RoR etc .. .. ASP.NET stuff is easy to spot too .. but as the framework becomes more obscure it gets harder to deduce ..

What I usually is compare the site i am snooping with another site that I know is built using a particular tech. That sometimes works ..

Print range of numbers on same line

Python 2

for x in xrange(1,11):
    print x,

Python 3

for x in range(1,11):
    print(x, end=" ") 

Creating random numbers with no duplicates

Instead of doing all this create a LinkedHashSet object and random numbers to it by Math.random() function .... if any duplicated entry occurs the LinkedHashSet object won't add that number to its List ... Since in this Collection Class no duplicate values are allowed .. in the end u get a list of random numbers having no duplicated values .... :D

File.Move Does Not Work - File Already Exists

According to the docs for File.Move there is no "overwrite if exists" parameter. You tried to specify the destination folder, but you have to give the full file specification.

Reading the docs again ("providing the option to specify a new file name"), I think, adding a backslash to the destination folder spec may work.

bs4.FeatureNotFound: Couldn't find a tree builder with the features you requested: lxml. Do you need to install a parser library?

In some references, use the second instead of the first:

soup_object= BeautifulSoup(markup,'html-parser')
soup_object= BeautifulSoup(markup,'html.parser')

How do I find the absolute position of an element using jQuery?

Note that $(element).offset() tells you the position of an element relative to the document. This works great in most circumstances, but in the case of position:fixed you can get unexpected results.

If your document is longer than the viewport and you have scrolled vertically toward the bottom of the document, then your position:fixed element's offset() value will be greater than the expected value by the amount you have scrolled.

If you are looking for a value relative to the viewport (window), rather than the document on a position:fixed element, you can subtract the document's scrollTop() value from the fixed element's offset().top value. Example: $("#el").offset().top - $(document).scrollTop()

If the position:fixed element's offset parent is the document, you want to read parseInt($.css('top')) instead.

iPhone viewWillAppear not firing

I'm not 100% sure on this, but I think that adding a view to the view hierarchy directly means calling -addSubview: on the view controller's view (e.g., [viewController.view addSubview:anotherViewController.view]) instead of pushing a new view controller onto the navigation controller's stack.

Using sed and grep/egrep to search and replace

Another way to do this

find . -name *.xml -exec sed -i "s/4.6.0-SNAPSHOT/5.0.0-SNAPSHOT/" {} \;

Some help regarding the above command

The find will do the find for you on the current directory indicated by .

-name the name of the file in my case its pom.xml can give wild cards.

-exec execute

sed stream editor

-i ignore case

s is for substitute

/4.6.0.../ String to be searched

/5.0.0.../ String to be replaced

Sending HTML Code Through JSON

Just to expand on @T.J. Crowder's answer.

json_encode does well with simple html strings, in my experience however json_encode often becomes confused by, (or it becomes quite difficult to properly escape) longer complex nested html mixed with php. Two options to consider if you are in this position are: encoding/decoding the markup first with something like [base64_encode][1]/ decode (quite a bit of a performance hit), or (and perhaps preferably) be more selective in what you are passing via json, and generate the necessary markup on the client side instead.

Markdown to create pages and table of contents?

If using the Sublime Text editor, the MarkdownTOC plugin works beautifully! See:

  1. https://packagecontrol.io/packages/MarkdownTOC
  2. https://github.com/naokazuterada/MarkdownTOC

Once installed, go to Preferences --> Package Settings --> MarkdownTOC --> Settings -- User, to customize your settings. Here's the options you can choose: https://github.com/naokazuterada/MarkdownTOC#configuration.

I recommend the following:

{
  "defaults": {
    "autoanchor": true,
    "autolink": true,
    "bracket": "round",
    "levels": [1,2,3,4,5,6],
    "indent": "\t",
    "remove_image": true,
    "link_prefix": "",
    "bullets": ["-"],
    "lowercase": "only_ascii",
    "style": "ordered",
    "uri_encoding": true,
    "markdown_preview": ""
  },
  "id_replacements": [
    {
      "pattern": "\\s+",
      "replacement": "-"
    },
    {
      "pattern": "&lt;|&gt;|&amp;|&apos;|&quot;|&#60;|&#62;|&#38;|&#39;|&#34;|!|#|$|&|'|\\(|\\)|\\*|\\+|,|/|:|;|=|\\?|@|\\[|\\]|`|\"|\\.|\\\\|<|>|{|}|™|®|©|%",
      "replacement": ""
    }
  ],
  "logging": false
}

To insert a table of contents, simply click at the top of the document where you'd like to insert the table of contents, then go to Tools --> Markdown TOC --> Insert TOC.

It will insert something like this:

<!-- MarkdownTOC -->

1. [Helpful Links:](#helpful-links)
1. [Sublime Text Settings:](#sublime-text-settings)
1. [Packages to install](#packages-to-install)

<!-- /MarkdownTOC -->

Note the <!-- --> HTML comments it inserts for you. These are special markers that help the program know where the ToC is so that it can automatically update it for you every time you save! So, leave these intact.

To get extra fancy, add some <details> and <summary> HTML tags around it to make the ToC collapsible/expandable, like this:

<details>
<summary><b>Table of Contents</b> (click to open)</summary>
<!-- MarkdownTOC -->

1. [Helpful Links:](#helpful-links)
1. [Sublime Text Settings:](#sublime-text-settings)
1. [Packages to install](#packages-to-install)

<!-- /MarkdownTOC -->
</details>

Now, you get this super cool effect, as shown below. See it in action in my main eRCaGuy_dotfiles readme here, or in my Sublime_Text_editor readme here.

  1. Collapsed: enter image description here
  2. Expanded: enter image description here

For extra information about its usage and limitations, be sure to read my notes about the MarkdownTOC plugin in that readme too.

Htaccess: add/remove trailing slash from URL

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

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


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

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

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


If you are interested in more reading:

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

Filter array to have unique values

I've always used:

unique = (arr) => arr.filter((item, i, s) => s.lastIndexOf(item) == i);

But recently I had to get unique values for:

["1", 1, "2", 2, "3", 3]

And my old standby didn't cut it, so I came up with this:

uunique = (arr) => Object.keys(Object.assign({}, ...arr.map(a=>({[a]:true}))));

Can I use an HTML input type "date" to collect only a year?

No you can not but you may want to use input type number as a workaround. Look at the following example:

<input type="number" min="1900" max="2099" step="1" value="2016" />

rmagick gem install "Can't find Magick-config"

I had this problem when I had already installed ImageMagick with macports. I ran

    port contents ImageMagick | grep config

To find where the config file had been stored and then ran

    PATH=(insert your path here):${PATH} bundle

to install the gem using bundler. From now on, if you run a command that needs to reference ImageMagick, you can prefix it with that command. For example I had a migration that referenced it, so I ran

    PATH=/opt/local/bin/:${PATH} rake db:migrate

opt/local/bin/ is the path where my config file was stored.

Function to calculate distance between two coordinates

What you're using is called the haversine formula, which calculates the distance between two points on a sphere as the crow flies. The Google Maps link you provided shows the distance as 2.2 km because it's not a straight line.

Wolphram Alpha is a great resource for doing geographic calculations, and also shows a distance of 1.652 km between these two points.

Drive distance vs. straight line distance (red line mine).

If you're looking for straight-line distance (as the crow files), your function is working correctly. If what you want is driving distance (or biking distance or public transportation distance or walking distance), you'll have to use a mapping API (Google or Bing being the most popular) to get the appropriate route, which will include the distance.

Incidentally, the Google Maps API provides a packaged method for spherical distance, in its google.maps.geometry.spherical namespace (look for computeDistanceBetween). It's probably better than rolling your own (for starters, it uses a more precise value for the Earth's radius).

For the picky among us, when I say "straight-line distance", I'm referring to a "straight line on a sphere", which is actually a curved line (i.e. the great-circle distance), of course.

Django: Get list of model fields?

It is not clear whether you have an instance of the class or the class itself and trying to retrieve the fields, but either way, consider the following code

Using an instance

instance = User.objects.get(username="foo")
instance.__dict__ # returns a dictionary with all fields and their values
instance.__dict__.keys() # returns a dictionary with all fields
list(instance.__dict__.keys()) # returns list with all fields

Using a class

User._meta.__dict__.get("fields") # returns the fields

# to get the field names consider looping over the fields and calling __str__()
for field in User._meta.__dict__.get("fields"):
    field.__str__() # e.g. 'auth.User.id'

SQL MAX of multiple columns?

I prefer solutions based on case-when, my assumption is that it should have the least impact on possible performance drop compared to other possible solutions like those with cross-apply, values(), custom functions etc.

Here is the case-when version that handles null values with most of possible test cases:

SELECT
    CASE 
        WHEN Date1 > coalesce(Date2,'0001-01-01') AND Date1 > coalesce(Date3,'0001-01-01') THEN Date1 
        WHEN Date2 > coalesce(Date3,'0001-01-01') THEN Date2 
        ELSE Date3
    END AS MostRecentDate
    , *
from 
(values
     (  1, cast('2001-01-01' as Date), cast('2002-01-01' as Date), cast('2003-01-01' as Date))
    ,(  2, cast('2001-01-01' as Date), cast('2003-01-01' as Date), cast('2002-01-01' as Date))
    ,(  3, cast('2002-01-01' as Date), cast('2001-01-01' as Date), cast('2003-01-01' as Date))
    ,(  4, cast('2002-01-01' as Date), cast('2003-01-01' as Date), cast('2001-01-01' as Date))
    ,(  5, cast('2003-01-01' as Date), cast('2001-01-01' as Date), cast('2002-01-01' as Date))
    ,(  6, cast('2003-01-01' as Date), cast('2002-01-01' as Date), cast('2001-01-01' as Date))
    ,( 11, cast(NULL         as Date), cast('2002-01-01' as Date), cast('2003-01-01' as Date))
    ,( 12, cast(NULL         as Date), cast('2003-01-01' as Date), cast('2002-01-01' as Date))
    ,( 13, cast('2003-01-01' as Date), cast(NULL         as Date), cast('2002-01-01' as Date))
    ,( 14, cast('2002-01-01' as Date), cast(NULL         as Date), cast('2003-01-01' as Date))
    ,( 15, cast('2003-01-01' as Date), cast('2002-01-01' as Date), cast(NULL         as Date))
    ,( 16, cast('2002-01-01' as Date), cast('2003-01-01' as Date), cast(NULL         as Date))
    ,( 21, cast('2003-01-01' as Date), cast(NULL         as Date), cast(NULL         as Date))
    ,( 22, cast(NULL         as Date), cast('2003-01-01' as Date), cast(NULL         as Date))
    ,( 23, cast(NULL         as Date), cast(NULL         as Date), cast('2003-01-01' as Date))
    ,( 31, cast(NULL         as Date), cast(NULL         as Date), cast(NULL         as Date))

) as demoValues(id, Date1,Date2,Date3)
order by id
;

and the result is:

MostRecent    id   Date1      Date2      Date3
2003-01-01    1    2001-01-01 2002-01-01 2003-01-01
2003-01-01    2    2001-01-01 2003-01-01 2002-01-01
2003-01-01    3    2002-01-01 2001-01-01 2002-01-01
2003-01-01    4    2002-01-01 2003-01-01 2001-01-01
2003-01-01    5    2003-01-01 2001-01-01 2002-01-01
2003-01-01    6    2003-01-01 2002-01-01 2001-01-01
2003-01-01    11   NULL       2002-01-01 2003-01-01
2003-01-01    12   NULL       2003-01-01 2002-01-01
2003-01-01    13   2003-01-01 NULL       2002-01-01
2003-01-01    14   2002-01-01 NULL       2003-01-01
2003-01-01    15   2003-01-01 2002-01-01 NULL
2003-01-01    16   2002-01-01 2003-01-01 NULL
2003-01-01    21   2003-01-01 NULL       NULL
2003-01-01    22   NULL       2003-01-01 NULL
2003-01-01    23   NULL       NULL       2003-01-01
NULL          31   NULL       NULL       NULL

Replacing a fragment with another fragment inside activity group

You Can Use This code

((AppCompatActivity) getActivity()).getSupportFragmentManager().beginTransaction().replace(R.id.YourFrameLayout, new YourFragment()).commit();

or You Can This Use Code

YourFragment fragments=(YourFragment) getSupportFragmentManager().findFragmentById(R.id.FrameLayout);

        if (fragments==null) {
            getSupportFragmentManager().beginTransaction().replace(R.id.FrameLayout, new Fragment_News()).commit();
        }

How to extend available properties of User.Identity

Whenever you want to extend the properties of User.Identity with any additional properties like the question above, add these properties to the ApplicationUser class first like so:

public class ApplicationUser : IdentityUser
{
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        return userIdentity;
    }

    // Your Extended Properties
    public long? OrganizationId { get; set; }
}

Then what you need is to create an extension method like so (I create mine in an new Extensions folder):

namespace App.Extensions
{
    public static class IdentityExtensions
    {
        public static string GetOrganizationId(this IIdentity identity)
        {
            var claim = ((ClaimsIdentity)identity).FindFirst("OrganizationId");
            // Test for null to avoid issues during local testing
            return (claim != null) ? claim.Value : string.Empty;
        }
    }
}

When you create the Identity in the ApplicationUser class, just add the Claim -> OrganizationId like so:

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here => this.OrganizationId is a value stored in database against the user
        userIdentity.AddClaim(new Claim("OrganizationId", this.OrganizationId.ToString()));

        return userIdentity;
    }

Once you added the claim and have your extension method in place, to make it available as a property on your User.Identity, add a using statement on the page/file you want to access it:

in my case: using App.Extensions; within a Controller and @using. App.Extensions withing a .cshtml View file.

EDIT:

What you can also do to avoid adding a using statement in every View is to go to the Views folder, and locate the Web.config file in there. Now look for the <namespaces> tag and add your extension namespace there like so:

<add namespace="App.Extensions" />

Save your file and you're done. Now every View will know of your extensions.

You can access the Extension Method:

var orgId = User.Identity.GetOrganizationId();

What is the most efficient way to create HTML elements using jQuery?

personally i'd suggest (for readability):

$('<div>');

some numbers on the suggestions so far (safari 3.2.1 / mac os x):

var it = 50000;

var start = new Date().getTime();
for (i = 0; i < it; ++i)  {
  // test creation of an element 
  // see below statements
}
var end = new Date().getTime();
alert( end - start );                

var e = $( document.createElement('div') );  // ~300ms
var e = $('<div>');                          // ~3100ms
var e = $('<div></div>');                    // ~3200ms
var e = $('<div/>');                         // ~3500ms              

oracle plsql: how to parse XML and insert into table

CREATE OR REPLACE PROCEDURE ADDEMP
    (xml IN CLOB)
AS
BEGIN
    INSERT INTO EMPLOYEE (EMPID,EMPNAME,EMPDETAIL,CREATEDBY,CREATED)
    SELECT 
        ExtractValue(column_value,'/ROOT/EMPID') AS EMPID
       ,ExtractValue(column_value,'/ROOT/EMPNAME') AS EMPNAME
       ,ExtractValue(column_value,'/ROOT/EMPDETAIL') AS EMPDETAIL
       ,ExtractValue(column_value,'/ROOT/CREATEDBY') AS CREATEDBY
       ,ExtractValue(column_value,'/ROOT/CREATEDDATE') AS CREATEDDATE
    FROM   TABLE(XMLSequence( XMLType(xml))) XMLDUMMAY;

    COMMIT;
END;

Shell command to sum integers, one per line?

I would put a big WARNING on the commonly approved solution:

awk '{s+=$1} END {print s}' mydatafile # DO NOT USE THIS!!

that is because in this form awk uses a 32 bit signed integer representation: it will overflow for sums that exceed 2147483647 (i.e., 2^31).

A more general answer (for summing integers) would be:

awk '{s+=$1} END {printf "%.0f\n", s}' mydatafile # USE THIS INSTEAD

How to Correctly handle Weak Self in Swift Blocks with Arguments

If you are crashing than you probably need [weak self]

My guess is that the block you are creating is somehow still wired up.

Create a prepareForReuse and try clearing the onTextViewEditClosure block inside that.

func prepareForResuse() {
   onTextViewEditClosure = nil
   textView.delegate = nil
}

See if that prevents the crash. (It's just a guess).

How can I apply a border only inside a table?

For ordinary table markup, here's a short solution that works on all devices/browsers on BrowserStack, except IE 7 and below:

table { border-collapse: collapse; }

td + td,
th + th { border-left: 1px solid; }
tr + tr { border-top: 1px solid; }

For IE 7 support, add this:

tr + tr > td,
tr + tr > th { border-top: 1px solid; }

A test case can be seen here: http://codepen.io/dalgard/pen/wmcdE

Adding options to a <select> using jQuery?

I like to use non jquery approach:

mySelect.add(new Option('My option', 1));

how to call scalar function in sql server 2008

For some reason I was not able to use my scalar function until I referenced it using brackets, like so:

select [dbo].[fun_functional_score]('01091400003')

Android emulator failed to allocate memory 8

Go to edit Android Virtual Devices and change the 1024 Under Memory Options to 768. If it still doesn't work, keep going lower and lower.

How to get names of enum entries?

I find that solution more elegant:

for (let val in myEnum ) {

 if ( isNaN( parseInt( val )) )
     console.log( val );
}

It displays:

bar 
foo

Importing modules from parent folder

Here is an answer that's simple so you can see how it works, small and cross-platform.
It only uses built-in modules (os, sys and inspect) so should work
on any operating system (OS) because Python is designed for that.

Shorter code for answer - fewer lines and variables

from inspect import getsourcefile
import os.path as path, sys
current_dir = path.dirname(path.abspath(getsourcefile(lambda:0)))
sys.path.insert(0, current_dir[:current_dir.rfind(path.sep)])
import my_module  # Replace "my_module" here with the module name.
sys.path.pop(0)

For less lines than this, replace the second line with import os.path as path, sys, inspect,
add inspect. at the start of getsourcefile (line 3) and remove the first line.
- however this imports all of the module so could need more time, memory and resources.

The code for my answer (longer version)

from inspect import getsourcefile
import os.path
import sys

current_path = os.path.abspath(getsourcefile(lambda:0))
current_dir = os.path.dirname(current_path)
parent_dir = current_dir[:current_dir.rfind(os.path.sep)]

sys.path.insert(0, parent_dir)

import my_module  # Replace "my_module" here with the module name.

It uses an example from a Stack Overflow answer How do I get the path of the current
executed file in Python?
to find the source (filename) of running code with a built-in tool.

from inspect import getsourcefile  
from os.path import abspath  

Next, wherever you want to find the source file from you just use:

abspath(getsourcefile(lambda:0))

My code adds a file path to sys.path, the python path list
because this allows Python to import modules from that folder.

After importing a module in the code, it's a good idea to run sys.path.pop(0) on a new line
when that added folder has a module with the same name as another module that is imported
later in the program. You need to remove the list item added before the import, not other paths.
If your program doesn't import other modules, it's safe to not delete the file path because
after a program ends (or restarting the Python shell), any edits made to sys.path disappear.

Notes about a filename variable

My answer doesn't use the __file__ variable to get the file path/filename of running
code because users here have often described it as unreliable. You shouldn't use it
for importing modules from parent folder in programs used by other people.

Some examples where it doesn't work (quote from this Stack Overflow question):

• it can't be found on some platforms • it sometimes isn't the full file path

  • py2exe doesn't have a __file__ attribute, but there is a workaround
  • When you run from IDLE with execute() there is no __file__ attribute
  • OS X 10.6 where I get NameError: global name '__file__' is not defined

Can multiple different HTML elements have the same ID if they're different elements?

How about a pragmatic answer.

Let's go to youtube and run this code

Object.fromEntries(Object.entries([...document.querySelectorAll('[id]')].reduce((s, e) => { s[e.id] = (s[e.id] || 0) + 1; return s; }, {})).filter(([k,v]) => v > 1))

and see all the repeated ids.

enter image description here

Changing the code above to show ids repeated more than 10 times here's the list it produced

additional-metadata-line: 43
avatar: 46
avatar-link: 43
button: 120
buttons: 45
byline-container: 45
channel-name: 44
container: 51
content: 49
details: 43
dismissable: 46
dismissed: 46
dismissed-content: 43
hover-overlays: 45
img: 90
menu: 50
meta: 44
metadata: 44
metadata-line: 43
mouseover-overlay: 45
overlays: 45
repeat: 36
separator: 43
text: 49
text-container: 44
thumbnail: 46
tooltip: 80
top-level-buttons: 45
video-title: 43
video-title-link: 43

Other sites that use the same id more than once include Amazon.com, ebay.com, expedia.com, cnn.com

clearly ids are just another piece of metadata on an element.

getElementById is pretty much obsolete. You can use querySelectorAll for all elements or querySelector for the first, regardless of selector so if you want all elements with id foo then

document.querySelectorAll('#foo')  // returns all elements with id="foo"

where as if you want only the first element use querySelector

document.querySelector('#foo')  // returns the first element with id="foo"
document.querySelector('.foo')  // returns the first element with class "foo"
document.querySelector('foo')   // returns the first <foo> element
document.querySelector('foo .foo #foo') // returns the first element with
                                        // id="foo" that has an ancestor
                                        // with class "foo" who has an
                                        // ancestor <foo> element.

And we can see that using selectors we can find different elements with the same id.

_x000D_
_x000D_
function addClick(selector, add) {
  document.querySelector(selector).addEventListener('click', function() {
    const e = this.parentElement.querySelector('span');
    e.textContent = parseInt(e.textContent) + add;
  });
}
addClick('.e #foo', 1);
addClick('.f #foo', 10);
_x000D_
body { font-size: x-large; font-weight: bold; }
.a #foo { color: red; }
.b #foo { color: green; }
div:nth-child(3) #foo { color: blue; }
#foo { color: purple }
_x000D_
<div class="a"><span id="foo">a</span></div>
<div class="b"><span id="foo">b</span></div>
<div><span id="foo">c</span></div>
<span id="foo">d</span>
<div class="e"><button type="button" id="foo">+1</button>: <span>0</span></div>
<div class="f"><button type="button" id="foo">+10</button>: <span>0</span></div>
_x000D_
_x000D_
_x000D_

Where it matters that id is unique

  • <a> tags can reference ids as in <a href="#foo">. Clicking it will jump the document to the first element with id="foo". Similarly the hash tag in the URL which is effectively the same feature.

  • <label> tags have a for attribute that specifies which element they are labeling by id. Clicking the label clicks/activates/give-the-focus-to the corresponding element. The label will only affect the first element with a matching id

_x000D_
_x000D_
label { user-select: none; }
_x000D_
<p>nested for checking</p>
<form>
  <div><input type="checkbox" id="foo"><label for="foo">foo</label></div>
</form>
<form>
  <div><input type="checkbox" id="foo"><label for="foo">foo (clicking here will check first checkbox)</label></div>
</form>
_x000D_
_x000D_
_x000D_

Otherwise, id is just another tool in your toolbox.

How to discard uncommitted changes in SourceTree?

Ok so in Windows sourcetree that is simple, on macOS I looked as well for a while..

Click Command + Shift + R while in source tree a hidden popup will be shown that will let you discard individual files OR ALL! Why is this hidden? We will never know.. but it works!

enter image description here

python, sort descending dataframe with pandas

New syntax (either):

 test = df.sort_values(['one'], ascending=[False])
 test = df.sort_values(['one'], ascending=[0])

How to use NSURLConnection to connect with SSL for an untrusted cert?

In iOS 9, SSL connections will fail for all invalid or self-signed certificates. This is the default behavior of the new App Transport Security feature in iOS 9.0 or later, and on OS X 10.11 and later.

You can override this behavior in the Info.plist, by setting NSAllowsArbitraryLoads to YES in the NSAppTransportSecurity dictionary. However, I recommend overriding this setting for testing purposes only.

enter image description here

For information see App Transport Technote here.

Jquery Change Height based on Browser Size/Resize

Pay attention, there is a bug with Jquery 1.8.0, $(window).height() returns the all document height !

Does Python's time.time() return the local or UTC timestamp?

This is for the text form of a timestamp that can be used in your text files. (The title of the question was different in the past, so the introduction to this answer was changed to clarify how it could be interpreted as the time. [updated 2016-01-14])

You can get the timestamp as a string using the .now() or .utcnow() of the datetime.datetime:

>>> import datetime
>>> print datetime.datetime.utcnow()
2012-12-15 10:14:51.898000

The now differs from utcnow as expected -- otherwise they work the same way:

>>> print datetime.datetime.now()
2012-12-15 11:15:09.205000

You can render the timestamp to the string explicitly:

>>> str(datetime.datetime.now())
'2012-12-15 11:15:24.984000'

Or you can be even more explicit to format the timestamp the way you like:

>>> datetime.datetime.now().strftime("%A, %d. %B %Y %I:%M%p")
'Saturday, 15. December 2012 11:19AM'

If you want the ISO format, use the .isoformat() method of the object:

>>> datetime.datetime.now().isoformat()
'2013-11-18T08:18:31.809000'

You can use these in variables for calculations and printing without conversions.

>>> ts = datetime.datetime.now()
>>> tf = datetime.datetime.now()
>>> te = tf - ts
>>> print ts
2015-04-21 12:02:19.209915
>>> print tf
2015-04-21 12:02:30.449895
>>> print te
0:00:11.239980

R ggplot2: stat_count() must not be used with a y aesthetic error in Bar graph

I was looking for the same and this may also work

p.Wages.all.A_MEAN <- Wages.all %>%
                  group_by(`Career Cluster`, Year)%>%
                  summarize(ANNUAL.MEAN.WAGE = mean(A_MEAN))

names(p.Wages.all.A_MEAN) [1] "Career Cluster" "Year" "ANNUAL.MEAN.WAGE"

p.Wages.all.a.mean <- ggplot(p.Wages.all.A_MEAN, aes(Year, ANNUAL.MEAN.WAGE , color= `Career Cluster`))+
                  geom_point(aes(col=`Career Cluster` ), pch=15, size=2.75, alpha=1.5/4)+
                  theme(axis.text.x = element_text(color="#993333",  size=10, angle=0)) #face="italic",
p.Wages.all.a.mean

In android app Toolbar.setTitle method has no effect – application name is shown as title

Simply use this in your adapter, Where MainActivity is your AppCompactActivity. Call it from anywhere.

((MainActivity) context).getSupportActionBar().setTitle(titles.get(position));

Web Reference vs. Service Reference

Add Web Reference is the old-style, deprecated ASP.NET webservices (ASMX) technology (using only the XmlSerializer for your stuff) - if you do this, you get an ASMX client for an ASMX web service. You can do this in just about any project (Web App, Web Site, Console App, Winforms - you name it).

Add Service Reference is the new way of doing it, adding a WCF service reference, which gives you a much more advanced, much more flexible service model than just plain old ASMX stuff.

Since you're not ready to move to WCF, you can also still add the old-style web reference, if you really must: when you do a "Add Service Reference", on the dialog that comes up, click on the [Advanced] button in the button left corner:

alt text

and on the next dialog that comes up, pick the [Add Web Reference] button at the bottom.

How can I send and receive WebSocket messages on the server side?

Implementation in Go

Encode part (server -> browser)

func encode (message string) (result []byte) {
  rawBytes := []byte(message)
  var idxData int

  length := byte(len(rawBytes))
  if len(rawBytes) <= 125 { //one byte to store data length
    result = make([]byte, len(rawBytes) + 2)
    result[1] = length
    idxData = 2
  } else if len(rawBytes) >= 126 && len(rawBytes) <= 65535 { //two bytes to store data length
    result = make([]byte, len(rawBytes) + 4)
    result[1] = 126 //extra storage needed
    result[2] = ( length >> 8 ) & 255
    result[3] = ( length      ) & 255
    idxData = 4
  } else {
    result = make([]byte, len(rawBytes) + 10)
    result[1] = 127
    result[2] = ( length >> 56 ) & 255
    result[3] = ( length >> 48 ) & 255
    result[4] = ( length >> 40 ) & 255
    result[5] = ( length >> 32 ) & 255
    result[6] = ( length >> 24 ) & 255
    result[7] = ( length >> 16 ) & 255
    result[8] = ( length >>  8 ) & 255
    result[9] = ( length       ) & 255
    idxData = 10
  }

  result[0] = 129 //only text is supported

  // put raw data at the correct index
  for i, b := range rawBytes {
    result[idxData + i] = b
  }
  return
}

Decode part (browser -> server)

func decode (rawBytes []byte) string {
  var idxMask int
  if rawBytes[1] == 126 {
    idxMask = 4
  } else if rawBytes[1] == 127 {
    idxMask = 10
  } else {
    idxMask = 2
  }

  masks := rawBytes[idxMask:idxMask + 4]
  data := rawBytes[idxMask + 4:len(rawBytes)]
  decoded := make([]byte, len(rawBytes) - idxMask + 4)

  for i, b := range data {
    decoded[i] = b ^ masks[i % 4]
  }
  return string(decoded)
}

SQL to Entity Framework Count Group-By

Query syntax

var query = from p in context.People
            group p by p.name into g
            select new
            {
              name = g.Key,
              count = g.Count()
            };

Method syntax

var query = context.People
                   .GroupBy(p => p.name)
                   .Select(g => new { name = g.Key, count = g.Count() });

Changing specific text's color using NSMutableAttributedString in Swift

let mainString = "Hello World"
let stringToColor = "World"

SWIFT 5

let range = (mainString as NSString).range(of: stringToColor)

let mutableAttributedString = NSMutableAttributedString.init(string: mainString)
mutableAttributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red, range: range)

textField = UITextField.init(frame: CGRect(x:10, y:20, width:100, height: 100))
textField.attributedText = mutableAttributedString

SWIFT 4.2

let range = (mainString as NSString).range(of: stringToColor)
    

let mutableAttributedString = NSMutableAttributedString.init(string: mainString)
mutableAttributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red, range: range)     
    
textField = UITextField.init(frame: CGRect(x:10, y:20, width:100, height: 100))
textField.attributedText = mutableAttributedString

Check if a varchar is a number (TSQL)

Damien_The_Unbeliever noted that his was only good for digits

Wade73 added a bit to handle decimal points

neizan made an additional tweak as did notwhereuareat

Unfortunately, none appear to handle negative values and they appear to have issues with a comma in the value...

Here's my tweak to pick up negative values and those with commas

declare @MyTable table(MyVar nvarchar(10));
insert into @MyTable (MyVar) 
values 
(N'1234')
, (N'000005')
, (N'1,000')
, (N'293.8457')
, (N'x')
, (N'+')
, (N'293.8457.')
, (N'......')
, (N'.')
, (N'-375.4')
, (N'-00003')
, (N'-2,000')
, (N'3-3')
, (N'3000-')
;

-- This shows that Neizan's answer allows "." to slip through.
select * from (
select 
    MyVar
    , case when MyVar not like N'%[^0-9.]%' then 1 else 0 end as IsNumber 
from 
    @MyTable
) t order by IsNumber;

-- Notice the addition of "and MyVar not like '.'".
select * from (
select 
    MyVar
    , case when MyVar not like N'%[^0-9.]%' and MyVar not like N'%.%.%' and MyVar not like '.' then 1 else 0 end as IsNumber 
from 
    @MyTable
) t 
order by IsNumber;

--Trying to tweak for negative values and the comma
--Modified when comparison
select * from (
select 
    MyVar
    , case 
        when MyVar not like N'%[^0-9.,-]%' and MyVar not like '.' and isnumeric(MyVar) = 1 then 1
        else 0 
    end as IsNumber 
from 
    @MyTable
) t 
order by IsNumber;

Select data from date range between two dates

This query will help you:

select * 
from XXXX
where datepart(YYYY,create_date)>=2013 
and DATEPART(YYYY,create_date)<=2014

How can I increase the JVM memory?

Right click on project -> Run As -> Run Configurations..-> Select Arguments tab -> In VM Arguments you can increase your JVM memory allocation. Java HotSpot document will help you to setup your VM Argument HERE

I will not prefer to make any changes into eclipse.ini as minor mistake cause lot of issues. It's easier to play with VM Args

Error: No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'

I also had a similar problem

My problem was solved by doing the following:

enter image description here

enter image description here

How to send email from SQL Server?

sometimes while not found sp_send_dbmail directly. You may use 'msdb.dbo.sp_send_dbmail' to try (Work fine on Windows Server 2008 R2 and is tested)

How to change UINavigationBar background color from the AppDelegate

The colour code is the issue here. Instead of using 195/255, use 0.7647 or 195.f/255.f The problem is converting the float is not working properly. Try using exact float value.

What is the "continue" keyword and how does it work in Java?

"continue" in Java means go to end of the current loop, means: if the compiler sees continue in a loop it will go to the next iteration

Example: This is a code to print the odd numbers from 1 to 10

the compiler will ignore the print code whenever it sees continue moving into the next iteration

for (int i = 0; i < 10; i++) { 
    if (i%2 == 0) continue;    
    System.out.println(i+"");
}

Difference between UTF-8 and UTF-16?

I believe there are a lot of good articles about this around the Web, but here is a short summary.

Both UTF-8 and UTF-16 are variable length encodings. However, in UTF-8 a character may occupy a minimum of 8 bits, while in UTF-16 character length starts with 16 bits.

Main UTF-8 pros:

  • Basic ASCII characters like digits, Latin characters with no accents, etc. occupy one byte which is identical to US-ASCII representation. This way all US-ASCII strings become valid UTF-8, which provides decent backwards compatibility in many cases.
  • No null bytes, which allows to use null-terminated strings, this introduces a great deal of backwards compatibility too.
  • UTF-8 is independent of byte order, so you don't have to worry about Big Endian / Little Endian issue.

Main UTF-8 cons:

  • Many common characters have different length, which slows indexing by codepoint and calculating a codepoint count terribly.
  • Even though byte order doesn't matter, sometimes UTF-8 still has BOM (byte order mark) which serves to notify that the text is encoded in UTF-8, and also breaks compatibility with ASCII software even if the text only contains ASCII characters. Microsoft software (like Notepad) especially likes to add BOM to UTF-8.

Main UTF-16 pros:

  • BMP (basic multilingual plane) characters, including Latin, Cyrillic, most Chinese (the PRC made support for some codepoints outside BMP mandatory), most Japanese can be represented with 2 bytes. This speeds up indexing and calculating codepoint count in case the text does not contain supplementary characters.
  • Even if the text has supplementary characters, they are still represented by pairs of 16-bit values, which means that the total length is still divisible by two and allows to use 16-bit char as the primitive component of the string.

Main UTF-16 cons:

  • Lots of null bytes in US-ASCII strings, which means no null-terminated strings and a lot of wasted memory.
  • Using it as a fixed-length encoding “mostly works” in many common scenarios (especially in US / EU / countries with Cyrillic alphabets / Israel / Arab countries / Iran and many others), often leading to broken support where it doesn't. This means the programmers have to be aware of surrogate pairs and handle them properly in cases where it matters!
  • It's variable length, so counting or indexing codepoints is costly, though less than UTF-8.

In general, UTF-16 is usually better for in-memory representation because BE/LE is irrelevant there (just use native order) and indexing is faster (just don't forget to handle surrogate pairs properly). UTF-8, on the other hand, is extremely good for text files and network protocols because there is no BE/LE issue and null-termination often comes in handy, as well as ASCII-compatibility.

Java OCR implementation

Just found this one (don't know it, not tested, check yourself)

Ron Cemer Java OCR


As you only need this for curiosity you could look into the source of this applet.

It does OCR of handwritten characters with a neural network

Java OCR: Handwriting Recognition

Finding the median of an unsorted array

Quickselect works in O(n), this is also used in the partition step of Quicksort.

Does Python have “private” variables in classes?

It's cultural. In Python, you don't write to other classes' instance or class variables. In Java, nothing prevents you from doing the same if you really want to - after all, you can always edit the source of the class itself to achieve the same effect. Python drops that pretence of security and encourages programmers to be responsible. In practice, this works very nicely.

If you want to emulate private variables for some reason, you can always use the __ prefix from PEP 8. Python mangles the names of variables like __foo so that they're not easily visible to code outside the class that contains them (although you can get around it if you're determined enough, just like you can get around Java's protections if you work at it).

By the same convention, the _ prefix means stay away even if you're not technically prevented from doing so. You don't play around with another class's variables that look like __foo or _bar.

pip is not able to install packages correctly: Permission denied error

On a Mac, you need to use this command:

STATIC_DEPS=true sudo pip install lxml

How to transfer data from JSP to servlet when submitting HTML form

Well, there are plenty of database tutorials online for java (what you're looking for is called JDBC). But if you are using plain servlets, you will have a class that extends HttpServlet and inside it you will have two methods that look like

public void doPost(HttpServletRequest req, HttpServletResponse resp){

}

and

public void doGet(HttpServletRequest req, HttpServletResponse resp){

}

One of them is called to handle GET operations and another is used to handle POST operations. You will then use the HttpServletRequest object to get the parameters that were passed as part of the form like so:

String name = req.getParameter("name");

Then, once you have the data from the form, it's relatively easy to add it to a database using a JDBC tutorial that is widely available on the web. I also suggest searching for a basic Java servlet tutorial to get you started. It's very easy, although there are a number of steps that need to be configured correctly.

Case-insensitive string comparison in C++

My first thought for a non-unicode version was to do something like this:

bool caseInsensitiveStringCompare(const string& str1, const string& str2) {
    if (str1.size() != str2.size()) {
        return false;
    }
    for (string::const_iterator c1 = str1.begin(), c2 = str2.begin(); c1 != str1.end(); ++c1, ++c2) {
        if (tolower(static_cast<unsigned char>(*c1)) != tolower(static_cast<unsigned char>(*c2))) {
            return false;
        }
    }
    return true;
}

Replace X-axis with own values

Yo could also set labels = FALSE inside axis(...) and print the labels in a separate command with Text. With this option you can rotate the text the text in case you need it

lablist<-as.vector(c(1:10))
axis(1, at=seq(1, 10, by=1), labels = FALSE)
text(seq(1, 10, by=1), par("usr")[3] - 0.2, labels = lablist, srt = 45, pos = 1, xpd = TRUE)

Detailed explanation here

Image with rotated labels

How to Exit a Method without Exiting the Program?

In addition to Mark's answer, you also need to be aware of scope, which (as in C/C++) is specified using braces. So:

if (textBox1.Text == "" || textBox1.Text == String.Empty || textBox1.TextLength == 0)
    textBox3.Text += "[-] Listbox is Empty!!!!\r\n";
return;

will always return at that point. However:

if (textBox1.Text == "" || textBox1.Text == String.Empty || textBox1.TextLength == 0)
{
    textBox3.Text += "[-] Listbox is Empty!!!!\r\n";
    return;
}

will only return if it goes into that if statement.

Mongoose.js: Find user by username LIKE value

For those that were looking for a solution here it is:

var name = 'Peter';
model.findOne({name: new RegExp('^'+name+'$', "i")}, function(err, doc) {
  //Do your action here..
});

How can I send an xml body using requests library?

Pass in the straight XML instead of a dictionary.

How do I align a number like this in C?

Looking at the edited question, you need to find the number of digits in the largest number to be presented, and then generate the printf() format using sprintf(), or using %*d with the number of digits being passed as an int for the * and then the value. Once you've got the biggest number (and you have to determine that in advance), you can determine the number of digits with an 'integer logarithm' algorithm (how many times can you divide by 10 before you get to zero), or by using snprintf() with the buffer length of zero, the format %d and null for the string; the return value tells you how many characters would have been formatted.

If you don't know and cannot determine the maximum number ahead of its appearance, you are snookered - there is nothing you can do.

Invoking a jQuery function after .each() has completed

If you're willing to make it a couple of steps, this might work. It's dependent on the animations finishing in order, though. I don't think that should be a problem.

var elems = $(parentSelect).nextAll();
var lastID = elems.length - 1;

elems.each( function(i) {
    $(this).fadeOut(200, function() { 
        $(this).remove(); 
        if (i == lastID) {
           doMyThing();
        }
    });
});

Delete from a table based on date

or an ORACLE version:

delete
  from table_name
 where trunc(table_name.date) > to_date('01/01/2009','mm/dd/yyyy') 

JSON string to JS object

You can use eval(jsonString) if you trust the data in the string, otherwise you'll need to parse it properly - check json.org for some code samples.

How to remove all subviews of a view in Swift?

One-liner:

while view.subviews.count > 0  { (view.subviews[0] as? NSView)?.removeFromSuperview() } 

How to specify in crontab by what user to run script?

EDIT: Note that this method won't work with crontab -e, but only works if you edit /etc/crontab directly. Otherwise, you may get an error like /bin/sh: www-data: command not found

Just before the program name:

*/1 * * * * www-data php5 /var/www/web/includes/crontab/queue_process.php >> /var/www/web/includes/crontab/queue.log 2>&1

HTML 5 input type="number" element for floating point numbers on Chrome

Try this

_x000D_
_x000D_
<input onkeypress='return event.charCode >= 48 && _x000D_
                          event.charCode <= 57 || _x000D_
                          event.charCode == 46'>
_x000D_
_x000D_
_x000D_

HTTP Status 405 - Method Not Allowed Error for Rest API

I also had this problem and was able to solve it by enabling CORS support on the server. In my case it was an Azure server and it was easy: Enable CORS on Azure

So check for your server how it works and enable CORS. I didn't even need a browser plugin or proxy :)

How can I set the font-family & font-size inside of a div?

Append a semicolon to the following line to fix the issue.

font-family:    Arial, Helvetica, sans-serif;

Git: How to update/checkout a single file from remote origin master?

Or git stash (if you have changes) on the branch you're on, checkout master, pull for the latest changes, grab that file to your desktop (or the entire app). Checkout the branch you were on. Git stash apply back to the state you were at, then fix the changes manually or drag it replacing the file.

This way is not sooooo cool but it def works if you guys can't figure anything else out.

Does WGET timeout?

Since in your question you said it's a PHP script, maybe the best solution could be to simply add in your script:

ignore_user_abort(TRUE);

In this way even if wget terminates, the PHP script goes on being processed at least until it does not exceeds max_execution_time limit (ini directive: 30 seconds by default).

As per wget anyay you should not change its timeout, according to the UNIX manual the default wget timeout is 900 seconds (15 minutes), whis is much larger that the 5-6 minutes you need.

Replace multiple characters in a C# string

Ohhh, the performance horror! The answer is a bit outdated, but still...

public static class StringUtils
{
    #region Private members

    [ThreadStatic]
    private static StringBuilder m_ReplaceSB;

    private static StringBuilder GetReplaceSB(int capacity)
    {
        var result = m_ReplaceSB;

        if (null == result)
        {
            result = new StringBuilder(capacity);
            m_ReplaceSB = result;
        }
        else
        {
            result.Clear();
            result.EnsureCapacity(capacity);
        }

        return result;
    }


    public static string ReplaceAny(this string s, char replaceWith, params char[] chars)
    {
        if (null == chars)
            return s;

        if (null == s)
            return null;

        StringBuilder sb = null;

        for (int i = 0, count = s.Length; i < count; i++)
        {
            var temp = s[i];
            var replace = false;

            for (int j = 0, cc = chars.Length; j < cc; j++)
                if (temp == chars[j])
                {
                    if (null == sb)
                    {
                        sb = GetReplaceSB(count);
                        if (i > 0)
                            sb.Append(s, 0, i);
                    }

                    replace = true;
                    break;
                }

            if (replace)
                sb.Append(replaceWith);
            else
                if (null != sb)
                    sb.Append(temp);
        }

        return null == sb ? s : sb.ToString();
    }
}

How to set the locale inside a Debian/Ubuntu Docker container?

Rather than resetting the locale after the installation of the locales package you can answer the questions you would normally get asked (which is disabled by noninteractive) before installing the package so that the package scripts setup the locale correctly, this example sets the locale to english (British, UTF-8):

RUN echo locales locales/default_environment_locale select en_GB.UTF-8 | debconf-set-selections
RUN echo locales locales/locales_to_be_generated select "en_GB.UTF-8 UTF-8" | debconf-set-selections

RUN \
  apt-get update && \
  DEBIAN_FRONTEND=noninteractive apt-get install -y locales && \
  rm -rf /var/lib/apt/lists/*

Inputting a default image in case the src attribute of an html <img> is not valid?

Google threw out this page to the "image fallback html" keywords, but because non of the above helped me, and I was looking for a "svg fallback support for IE below 9", I kept on searching and this is what I found:

<img src="base-image.svg" alt="picture" />
<!--[if (lte IE 8)|(!IE)]><image src="fallback-image.png" alt="picture" /><![endif]-->

It might be off-topic, but it resolved my own issue and it might help someone else too.

How to install mscomct2.ocx file from .cab file (Excel User Form and VBA)

You're correct that this is really painful to hand out to others, but if you have to, this is how you do it.

  1. Just extract the .ocx file from the .cab file (it is similar to a zip)
  2. Copy to the system folder (c:\windows\sysWOW64 for 64 bit systems and c:\windows\system32 for 32 bit)
  3. Use regsvr32 through the command prompt to register the file (e.g. "regsvr32 c:\windows\sysWOW64\mscomct2.ocx")

References

JSON.stringify doesn't work with normal Javascript array

Json has to have key-value pairs. Tho you can still have an array as the value part. Thus add a "key" of your chousing:

var json = JSON.stringify({whatver: test});

ActionBarCompat: java.lang.IllegalStateException: You need to use a Theme.AppCompat

I encountered this error when I was trying to create a DialogBox when some action is taken inside the CustomAdapter class. This was not an Activity but an Adapter class. After 36 hrs of efforts and looking up for solutions, I came up with this.

Send the Activity as a parameter while calling the CustomAdapter.

CustomAdapter ca = new CustomAdapter(MyActivity.this,getApplicationContext(),records);

Define the variables in the custom Adapter.

Activity parentActivity;
Context context;

Call the constructor like this.

public CustomAdapter(Activity parentActivity,Context context,List<Record> records){
    this.parentActivity=parentActivity;
    this.context=context;
    this.records=records;
}

And finally when creating the dialog box inside the adapter class, do it like this.

AlertDialog ad = new AlertDialog.Builder(parentActivity).setTitle("Your title");

and so on..

I hope this helps you

Linux find file names with given string recursively

use ack its simple. just type ack <string to be searched>

How to dynamic new Anonymous Class?

Of cause it's possible to create dynamic classes using very cool ExpandoObject class. But recently I worked on project and faced that Expando Object is serealized in not the same format on xml as an simple Anonymous class, it was pity =( , that is why I decided to create my own class and share it with you. It's using reflection and dynamic directive , builds Assembly, Class and Instance truly dynamicly. You can add, remove and change properties that is included in your class on fly Here it is :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using static YourNamespace.DynamicTypeBuilderTest;

namespace YourNamespace
{

    /// This class builds Dynamic Anonymous Classes

    public class DynamicTypeBuilderTest
    {    
        ///   
        /// Create instance based on any Source class as example based on PersonalData
        ///
        public static object CreateAnonymousDynamicInstance(PersonalData personalData, Type dynamicType, List<ClassDescriptorKeyValue> classDescriptionList)
        {
            var obj = Activator.CreateInstance(dynamicType);

            var propInfos = dynamicType.GetProperties();

            classDescriptionList.ForEach(x => SetValueToProperty(obj, propInfos, personalData, x));

            return obj;
        }

        private static void SetValueToProperty(object obj, PropertyInfo[] propInfos, PersonalData aisMessage, ClassDescriptorKeyValue description)
        {
            propInfos.SingleOrDefault(x => x.Name == description.Name)?.SetValue(obj, description.ValueGetter(aisMessage), null);
        }

        public static dynamic CreateAnonymousDynamicType(string entityName, List<ClassDescriptorKeyValue> classDescriptionList)
        {
            AssemblyName asmName = new AssemblyName();
            asmName.Name = $"{entityName}Assembly";
            AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.RunAndCollect);

            ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule($"{asmName.Name}Module");

            TypeBuilder typeBuilder = moduleBuilder.DefineType($"{entityName}Dynamic", TypeAttributes.Public);

            classDescriptionList.ForEach(x => CreateDynamicProperty(typeBuilder, x));

            return typeBuilder.CreateTypeInfo().AsType();
        }

        private static void CreateDynamicProperty(TypeBuilder typeBuilder, ClassDescriptorKeyValue description)
        {
            CreateDynamicProperty(typeBuilder, description.Name, description.Type);
        }

        ///
        ///Creation Dynamic property (from MSDN) with some Magic
        ///
        public static void CreateDynamicProperty(TypeBuilder typeBuilder, string name, Type propType)
        {
            FieldBuilder fieldBuider = typeBuilder.DefineField($"{name.ToLower()}Field",
                                                            propType,
                                                            FieldAttributes.Private);

            PropertyBuilder propertyBuilder = typeBuilder.DefineProperty(name,
                                                             PropertyAttributes.HasDefault,
                                                             propType,
                                                             null);

            MethodAttributes getSetAttr =
                MethodAttributes.Public | MethodAttributes.SpecialName |
                    MethodAttributes.HideBySig;

            MethodBuilder methodGetBuilder =
                typeBuilder.DefineMethod($"get_{name}",
                                           getSetAttr,
                                           propType,
                                           Type.EmptyTypes);

            ILGenerator methodGetIL = methodGetBuilder.GetILGenerator();

            methodGetIL.Emit(OpCodes.Ldarg_0);
            methodGetIL.Emit(OpCodes.Ldfld, fieldBuider);
            methodGetIL.Emit(OpCodes.Ret);

            MethodBuilder methodSetBuilder =
                typeBuilder.DefineMethod($"set_{name}",
                                           getSetAttr,
                                           null,
                                           new Type[] { propType });

            ILGenerator methodSetIL = methodSetBuilder.GetILGenerator();

            methodSetIL.Emit(OpCodes.Ldarg_0);
            methodSetIL.Emit(OpCodes.Ldarg_1);
            methodSetIL.Emit(OpCodes.Stfld, fieldBuider);
            methodSetIL.Emit(OpCodes.Ret);

            propertyBuilder.SetGetMethod(methodGetBuilder);
            propertyBuilder.SetSetMethod(methodSetBuilder);

        }

        public class ClassDescriptorKeyValue
        {
            public ClassDescriptorKeyValue(string name, Type type, Func<PersonalData, object> valueGetter)
            {
                Name = name;
                ValueGetter = valueGetter;
                Type = type;
            }

            public string Name;
            public Type Type;
            public Func<PersonalData, object> ValueGetter;
        }

        ///
        ///Your Custom class description based on any source class for example
        /// PersonalData
        public static IEnumerable<ClassDescriptorKeyValue> GetAnonymousClassDescription(bool includeAddress, bool includeFacebook)
        {
            yield return new ClassDescriptorKeyValue("Id", typeof(string), x => x.Id);
            yield return new ClassDescriptorKeyValue("Name", typeof(string), x => x.FirstName);
            yield return new ClassDescriptorKeyValue("Surname", typeof(string), x => x.LastName);
            yield return new ClassDescriptorKeyValue("Country", typeof(string), x => x.Country);
            yield return new ClassDescriptorKeyValue("Age", typeof(int?), x => x.Age);
            yield return new ClassDescriptorKeyValue("IsChild", typeof(bool), x => x.Age < 21);

            if (includeAddress)
                yield return new ClassDescriptorKeyValue("Address", typeof(string), x => x?.Contacts["Address"]);
            if (includeFacebook)
                yield return new ClassDescriptorKeyValue("Facebook", typeof(string), x => x?.Contacts["Facebook"]);
        }

        ///
        ///Source Data Class for example
        /// of cause you can use any other class
        public class PersonalData
        { 
            public int Id { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public string Country { get; set; }
            public int Age { get; set; }

            public Dictionary<string, string> Contacts { get; set; }
        }

    }
}

It is also very simple to use DynamicTypeBuilder, you just need put few lines like this:

    public class ExampleOfUse
    {
        private readonly bool includeAddress;
        private readonly bool includeFacebook;
        private readonly dynamic dynamicType;
        private readonly List<ClassDescriptorKeyValue> classDiscriptionList;
        public ExampleOfUse(bool includeAddress = false, bool includeFacebook = false)
        {
            this.includeAddress = includeAddress;
            this.includeFacebook = includeFacebook;
            this.classDiscriptionList = DynamicTypeBuilderTest.GetAnonymousClassDescription(includeAddress, includeFacebook).ToList();
            this.dynamicType = DynamicTypeBuilderTest.CreateAnonymousDynamicType("VeryPrivateData", this.classDiscriptionList);
        }

        public object Map(PersonalData privateInfo)
        {
            object dynamicObject = DynamicTypeBuilderTest.CreateAnonymousDynamicInstance(privateInfo, this.dynamicType, classDiscriptionList);

            return dynamicObject;
        }

    }

I hope that this code snippet help somebody =) Enjoy!

Selecting non-blank cells in Excel with VBA

If you are looking for the last row of a column, use:

Sub SelectFirstColumn()
   SelectEntireColumn (1)
End Sub

Sub SelectSecondColumn()
    SelectEntireColumn (2)
End Sub

Sub SelectEntireColumn(columnNumber)
    Dim LastRow
    Sheets("sheet1").Select
    LastRow = ActiveSheet.Columns(columnNumber).SpecialCells(xlLastCell).Row

    ActiveSheet.Range(Cells(1, columnNumber), Cells(LastRow, columnNumber)).Select
End Sub

Other commands you will need to get familiar with are copy and paste commands:

Sub CopyOneToTwo()
    SelectEntireColumn (1)
    Selection.Copy

    Sheets("sheet1").Select
    ActiveSheet.Range("B1").PasteSpecial Paste:=xlPasteValues
End Sub

Finally, you can reference worksheets in other workbooks by using the following syntax:

Dim book2
Set book2 = Workbooks.Open("C:\book2.xls")
book2.Worksheets("sheet1")

When is JavaScript synchronous?

JavaScript is always synchronous and single-threaded. If you're executing a JavaScript block of code on a page then no other JavaScript on that page will currently be executed.

JavaScript is only asynchronous in the sense that it can make, for example, Ajax calls. The Ajax call will stop executing and other code will be able to execute until the call returns (successfully or otherwise), at which point the callback will run synchronously. No other code will be running at this point. It won't interrupt any other code that's currently running.

JavaScript timers operate with this same kind of callback.

Describing JavaScript as asynchronous is perhaps misleading. It's more accurate to say that JavaScript is synchronous and single-threaded with various callback mechanisms.

jQuery has an option on Ajax calls to make them synchronously (with the async: false option). Beginners might be tempted to use this incorrectly because it allows a more traditional programming model that one might be more used to. The reason it's problematic is that this option will block all JavaScript on the page until it finishes, including all event handlers and timers.

Measuring Query Performance : "Execution Plan Query Cost" vs "Time Taken"

SET STATISTICS TIME ON

SELECT * 

FROM Production.ProductCostHistory
WHERE StandardCost < 500.00;

SET STATISTICS TIME OFF;

And see the message tab it will look like this:

SQL Server Execution Times:

   CPU time = 0 ms,  elapsed time = 10 ms.

(778 row(s) affected)

SQL Server parse and compile time: 

   CPU time = 0 ms, elapsed time = 0 ms.

HTML img onclick Javascript

This might work for you...

<script type="text/javascript">
function image(img) {
    var src = img.src;
    window.open(src);
}
</script>
<img src="pond1.jpg" height="150" size="150" alt="Johnson Pond" onclick="image(this)">

JQuery Ajax Post results in 500 Internal Server Error

in case if someone using the codeigniter framework, the problem may be caused by the csrf protection config enabled.

What is the best way to get the first letter from a string in Java, returned as a string of length 1?

import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;

import java.util.concurrent.TimeUnit;

@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 1)
@Fork(value = 1)
@Measurement(iterations = 5, time = 1)
public class StringFirstCharBenchmark {

    private String source;

    @Setup
    public void init() {
        source = "MALE";
    }

    @Benchmark
    public String substring() {
        return source.substring(0, 1);
    }

    @Benchmark
    public String indexOf() {
        return String.valueOf(source.indexOf(0));
    }
}

Results:

+----------------------------------------------------------------------+
| Benchmark                           Mode  Cnt   Score   Error  Units |
+----------------------------------------------------------------------+
| StringFirstCharBenchmark.indexOf    avgt    5  23.777 ? 5.788  ns/op |
| StringFirstCharBenchmark.substring  avgt    5  11.305 ? 1.411  ns/op |
+----------------------------------------------------------------------+

How to set specific window (frame) size in java swing?

Well, you are using both frame.setSize() and frame.pack().

You should use one of them at one time.

Using setSize() you can give the size of frame you want but if you use pack(), it will automatically change the size of the frames according to the size of components in it. It will not consider the size you have mentioned earlier.

Try removing frame.pack() from your code or putting it before setting size and then run it.

How to uninstall Anaconda completely from macOS

To uninstall Anaconda open a terminal window:

  1. Remove the entire anaconda installation directory:
rm -rf ~/anaconda
  1. Edit ~/.bash_profile and remove the anaconda directory from your PATH environment variable.

Note: You may need to edit .bashrc and/or .profile files instead of .bash_profile

  1. Remove the following hidden files and directories, which may have been created in the home directory:

    • .condarc
    • .conda
    • .continuum

Use:

rm -rf ~/.condarc ~/.conda ~/.continuum

What is the difference between Builder Design pattern and Factory Design pattern?

IMHO

Builder is some kind of more complex Factory.

But in Builder you can instantiate objects with using another factories, that are required to build final and valid object.

So, talking about "Creational Patterns" evolution by complexity you can think about it in this way:

Dependency Injection Container -> Service Locator -> Builder -> Factory

What is difference between arm64 and armhf?

Update: Yes, I understand that this answer does not explain the difference between arm64 and armhf. There is a great answer that does explain that on this page. This answer was intended to help set the asker on the right path, as they clearly had a misunderstanding about the capabilities of the Raspberry Pi at the time of asking.

Where are you seeing that the architecture is armhf? On my Raspberry Pi 3, I get:

$ uname -a
armv7l

Anyway, armv7 indicates that the system architecture is 32-bit. The first ARM architecture offering 64-bit support is armv8. See this table for reference.

You are correct that the CPU in the Raspberry Pi 3 is 64-bit, but the Raspbian OS has not yet been updated for a 64-bit device. 32-bit software can run on a 64-bit system (but not vice versa). This is why you're not seeing the architecture reported as 64-bit.

You can follow the GitHub issue for 64-bit support here, if you're interested.

Change HTML email body font type and size in VBA

FYI I did a little research as well and if the name of the font-family you want to apply contains spaces (as an example I take Gill Alt One MT Light), you should write it this way :

strbody= "<BODY style=" & Chr(34) & "font-family:Gill Alt One MT Light" & Chr(34) & ">" & YOUR_TEXT & "</BODY>"

Effect of NOLOCK hint in SELECT statements

It will be faster because it doesnt have to wait for locks

C# Convert List<string> to Dictionary<string, string>

Use this:

var dict = list.ToDictionary(x => x);

See MSDN for more info.

As Pranay points out in the comments, this will fail if an item exists in the list multiple times.
Depending on your specific requirements, you can either use var dict = list.Distinct().ToDictionary(x => x); to get a dictionary of distinct items or you can use ToLookup instead:

var dict = list.ToLookup(x => x);

This will return an ILookup<string, string> which is essentially the same as IDictionary<string, IEnumerable<string>>, so you will have a list of distinct keys with each string instance under it.

jQuery Set Selected Option Using Next

This is what i just used, i like how clean it is :-)

$('select').val(function(){
    var nextOption = $(this).children(':selected').next();
    return $(nextOption).val();
}).change();

How to find the minimum value in an ArrayList, along with the index number? (Java)

try this:

public int getIndexOfMin(List<Float> data) {
    float min = Float.MAX_VALUE;
    int index = -1;
    for (int i = 0; i < data.size(); i++) {
        Float f = data.get(i);
        if (Float.compare(f.floatValue(), min) < 0) {
            min = f.floatValue();
            index = i;
        }
    }
    return index;
}

How to reshape data from long to wide format

Using your example dataframe, we could:

xtabs(value ~ name + numbers, data = dat1)

How to find out what type of a Mat object is with Mat::type() in OpenCV

For debugging purposes in case you want to look up a raw Mat::type in a debugger:

+--------+----+----+----+----+------+------+------+------+
|        | C1 | C2 | C3 | C4 | C(5) | C(6) | C(7) | C(8) |
+--------+----+----+----+----+------+------+------+------+
| CV_8U  |  0 |  8 | 16 | 24 |   32 |   40 |   48 |   56 |
| CV_8S  |  1 |  9 | 17 | 25 |   33 |   41 |   49 |   57 |
| CV_16U |  2 | 10 | 18 | 26 |   34 |   42 |   50 |   58 |
| CV_16S |  3 | 11 | 19 | 27 |   35 |   43 |   51 |   59 |
| CV_32S |  4 | 12 | 20 | 28 |   36 |   44 |   52 |   60 |
| CV_32F |  5 | 13 | 21 | 29 |   37 |   45 |   53 |   61 |
| CV_64F |  6 | 14 | 22 | 30 |   38 |   46 |   54 |   62 |
+--------+----+----+----+----+------+------+------+------+

So for example, if type = 30 then OpenCV data type is CV_64FC4. If type = 50 then the OpenCV data type is CV_16UC(7).

How can I count the number of elements of a given value in a matrix?

assume w contains week numbers ([1:7])

n = histc(M,w)

if you do not know the range of numbers in M:

n = histc(M,unique(M))

It is such as a SQL Group by command!

How do I get the last day of a month?

I don't know C# but, if it turns out there's not a convenient API way to get it, one of the ways you can do so is by following the logic:

today -> +1 month -> set day of month to 1 -> -1 day

Of course, that assumes you have date math of that type.

How does one output bold text in Bash?

I assume bash is running on a vt100-compatible terminal in which the user did not explicitly turn off the support for formatting.

First, turn on support for special characters in echo, using -e option. Later, use ansi escape sequence ESC[1m, like:

echo -e "\033[1mSome Text"

More on ansi escape sequences for example here: ascii-table.com/ansi-escape-sequences-vt-100.php

C++ IDE for Macs

If you are looking for a full-fledged IDE like Visual Studio, I think Eclipse might be your best bet.

Eclipse is also highly extensible and configurable.

See here: http://www.eclipse.org/downloads/

Nested routes with react router v4 / v5

React Router v6

allows to use both nested routes (like in v3) and separate, splitted routes (v4, v5).

Nested Routes

Keep all routes in one place for small/medium size apps:

<Routes>
  <Route path="/" element={<Home />} >
    <Route path="user" element={<User />} /> 
    <Route path="dash" element={<Dashboard />} /> 
  </Route>
</Routes>

_x000D_
_x000D_
const App = () => {
  return (
    <BrowserRouter>
      <Routes>
        // /js is start path of stack snippet
        <Route path="/js" element={<Home />} >
          <Route path="user" element={<User />} />
          <Route path="dash" element={<Dashboard />} />
        </Route>
      </Routes>
    </BrowserRouter>
  );
}

const Home = () => {
  const location = useLocation()
  return (
    <div>
      <p>URL path: {location.pathname}</p>
      <Outlet />
      <p>
        <Link to="user" style={{paddingRight: "10px"}}>user</Link>
        <Link to="dash">dashboard</Link>
      </p>
    </div>
  )
}

const User = () => <div>User profile</div>
const Dashboard = () => <div>Dashboard</div>

ReactDOM.render(<App />, document.getElementById("root"));
_x000D_
<div id="root"></div>
    <script src="https://unpkg.com/[email protected]/umd/react.production.min.js"></script>
    <script src="https://unpkg.com/[email protected]/umd/react-dom.production.min.js"></script>
    <script src="https://unpkg.com/[email protected]/umd/history.production.min.js"></script>
    <script src="https://unpkg.com/[email protected]/umd/react-router.production.min.js"></script>
    <script src="https://unpkg.com/[email protected]/umd/react-router-dom.production.min.js"></script>
    <script>var { BrowserRouter, Routes, Route, Link, Outlet, useNavigate, useLocation } = window.ReactRouterDOM;</script>
_x000D_
_x000D_
_x000D_

Alternative: Define your routes as plain JavaScript objects via useRoutes.

Separate Routes

You can use separates routes to meet requirements of larger apps like code splitting:

// inside App.jsx:
<Routes>
  <Route path="/*" element={<Home />} />
</Routes>

// inside Home.jsx:
<Routes>
  <Route path="user" element={<User />} />
  <Route path="dash" element={<Dashboard />} />
</Routes>

_x000D_
_x000D_
const App = () => {
  return (
    <BrowserRouter>
      <Routes>
        // /js is start path of stack snippet
        <Route path="/js/*" element={<Home />} />
      </Routes>
    </BrowserRouter>
  );
}

const Home = () => {
  const location = useLocation()
  return (
    <div>
      <p>URL path: {location.pathname}</p>
      <Routes>
        <Route path="user" element={<User />} />
        <Route path="dash" element={<Dashboard />} />
      </Routes>
      <p>
        <Link to="user" style={{paddingRight: "5px"}}>user</Link>
        <Link to="dash">dashboard</Link>
      </p>
    </div>
  )
}

const User = () => <div>User profile</div>
const Dashboard = () => <div>Dashboard</div>

ReactDOM.render(<App />, document.getElementById("root"));
_x000D_
<div id="root"></div>
    <script src="https://unpkg.com/[email protected]/umd/react.production.min.js"></script>
    <script src="https://unpkg.com/[email protected]/umd/react-dom.production.min.js"></script>
    <script src="https://unpkg.com/[email protected]/umd/history.production.min.js"></script>
    <script src="https://unpkg.com/[email protected]/umd/react-router.production.min.js"></script>
    <script src="https://unpkg.com/[email protected]/umd/react-router-dom.production.min.js"></script>
    <script>var { BrowserRouter, Routes, Route, Link, Outlet, useNavigate, useLocation } = window.ReactRouterDOM;</script>
_x000D_
_x000D_
_x000D_

Swift Error: Editor placeholder in source file

Go to Product > Clean Build Folder

Convert Iterable to Stream using Java 8 JDK

There's a much better answer than using spliteratorUnknownSize directly, which is both easier and gets a better result. Iterable has a spliterator() method, so you should just use that to get your spliterator. In the worst case, it's the same code (the default implementation uses spliteratorUnknownSize), but in the more common case, where your Iterable is already a collection, you'll get a better spliterator, and therefore better stream performance (maybe even good parallelism). It's also less code:

StreamSupport.stream(iterable.spliterator(), false)
             .filter(...)
             .moreStreamOps(...);

As you can see, getting a stream from an Iterable (see also this question) is not very painful.

How to get evaluated attributes inside a custom directive

Notice: I do update this answer as I find better solutions. I also keep the old answers for future reference as long as they remain related. Latest and best answer comes first.

Better answer:

Directives in angularjs are very powerful, but it takes time to comprehend which processes lie behind them.

While creating directives, angularjs allows you to create an isolated scope with some bindings to the parent scope. These bindings are specified by the attribute you attach the element in DOM and how you define scope property in the directive definition object.

There are 3 types of binding options which you can define in scope and you write those as prefixes related attribute.

angular.module("myApp", []).directive("myDirective", function () {
    return {
        restrict: "A",
        scope: {
            text: "@myText",
            twoWayBind: "=myTwoWayBind",
            oneWayBind: "&myOneWayBind"
        }
    };
}).controller("myController", function ($scope) {
    $scope.foo = {name: "Umur"};
    $scope.bar = "qwe";
});

HTML

<div ng-controller="myController">
    <div my-directive my-text="hello {{ bar }}" my-two-way-bind="foo" my-one-way-bind="bar">
    </div>
</div>

In that case, in the scope of directive (whether it's in linking function or controller), we can access these properties like this:

/* Directive scope */

in: $scope.text
out: "hello qwe"
// this would automatically update the changes of value in digest
// this is always string as dom attributes values are always strings

in: $scope.twoWayBind
out: {name:"Umur"}
// this would automatically update the changes of value in digest
// changes in this will be reflected in parent scope

// in directive's scope
in: $scope.twoWayBind.name = "John"

//in parent scope
in: $scope.foo.name
out: "John"


in: $scope.oneWayBind() // notice the function call, this binding is read only
out: "qwe"
// any changes here will not reflect in parent, as this only a getter .

"Still OK" Answer:

Since this answer got accepted, but has some issues, I'm going to update it to a better one. Apparently, $parse is a service which does not lie in properties of the current scope, which means it only takes angular expressions and cannot reach scope. {{,}} expressions are compiled while angularjs initiating which means when we try to access them in our directives postlink method, they are already compiled. ({{1+1}} is 2 in directive already).

This is how you would want to use:

var myApp = angular.module('myApp',[]);

myApp.directive('myDirective', function ($parse) {
    return function (scope, element, attr) {
        element.val("value=" + $parse(attr.myDirective)(scope));
    };
});

function MyCtrl($scope) {
    $scope.aaa = 3432;
}?

.

<div ng-controller="MyCtrl">
    <input my-directive="123">
    <input my-directive="1+1">
    <input my-directive="'1+1'">
    <input my-directive="aaa">
</div>????????

One thing you should notice here is that, if you want set the value string, you should wrap it in quotes. (See 3rd input)

Here is the fiddle to play with: http://jsfiddle.net/neuTA/6/

Old Answer:

I'm not removing this for folks who can be misled like me, note that using $eval is perfectly fine the correct way to do it, but $parse has a different behavior, you probably won't need this to use in most of the cases.

The way to do it is, once again, using scope.$eval. Not only it compiles the angular expression, it has also access to the current scope's properties.

var myApp = angular.module('myApp',[]);

myApp.directive('myDirective', function () {
    return function (scope, element, attr) {
        element.val("value = "+ scope.$eval(attr.value));
    }
});

function MyCtrl($scope) {
   
}?

What you are missing was $eval.

http://docs.angularjs.org/api/ng.$rootScope.Scope#$eval

Executes the expression on the current scope returning the result. Any exceptions in the expression are propagated (uncaught). This is useful when evaluating angular expressions.

Open Excel file for reading with VBA without display

A much simpler approach that doesn't involve manipulating active windows:

Dim wb As Workbook
Set wb = Workbooks.Open("workbook.xlsx")
wb.Windows(1).Visible = False

From what I can tell the Windows index on the workbook should always be 1. If anyone knows of any race conditions that would make this untrue please let me know.

How do I print the content of a .txt file in Python?

to input a file:

fin = open(filename) #filename should be a string type: e.g filename = 'file.txt'

to output this file you can do:

for element in fin:
    print element 

if the elements are a string you'd better add this before print:

element = element.strip()

strip() remove notations like this: /n

When use ResponseEntity<T> and @RestController for Spring RESTful applications

To complete the answer from Sotorios Delimanolis.

It's true that ResponseEntity gives you more flexibility but in most cases you won't need it and you'll end up with these ResponseEntity everywhere in your controller thus making it difficult to read and understand.

If you want to handle special cases like errors (Not Found, Conflict, etc.), you can add a HandlerExceptionResolver to your Spring configuration. So in your code, you just throw a specific exception (NotFoundException for instance) and decide what to do in your Handler (setting the HTTP status to 404), making the Controller code more clear.

How to assign execute permission to a .sh file in windows to be executed in linux

The ZIP file format does allow to store the permission bits, but Windows programs normally ignore it. The zip utility on Cygwin however does preserve the x bit, just like it does on Linux. If you do not want to use Cygwin, you can take a source code and tweak it so that all *.sh files get the executable bit set. Or write a script like explained here

Can I execute a function after setState is finished updating?

setState(updater[, callback]) is an async function:

https://facebook.github.io/react/docs/react-component.html#setstate

You can execute a function after setState is finishing using the second param callback like:

this.setState({
    someState: obj
}, () => {
    this.afterSetStateFinished();
});

The same can be done with hooks in React functional component:

https://github.com/the-road-to-learn-react/use-state-with-callback#usage

Look at useStateWithCallbackLazy:

import { useStateWithCallbackLazy } from 'use-state-with-callback';

const [count, setCount] = useStateWithCallbackLazy(0);

setCount(count + 1, () => {
   afterSetCountFinished();
});

How to prevent a click on a '#' link from jumping to top of page?

If the element doesn't have a meaningful href value, then it isn't really a link, so why not use some other element instead?

As suggested by Neothor, a span is just as appropriate and, if styled correctly, will be visibly obvious as an item that can be clicked on. You could even attach an hover event, to make the elemnt 'light up' as the user's mouse moves over it.

However, having said this, you may want to rethink the design of your site so that it functions without javascript, but is enhanced by javascript when it is available.

How can I create a Java method that accepts a variable number of arguments?

You could write a convenience method:

public PrintStream print(String format, Object... arguments) {
    return System.out.format(format, arguments);
}

But as you can see, you've simply just renamed format (or printf).

Here's how you could use it:

private void printScores(Player... players) {
    for (int i = 0; i < players.length; ++i) {
        Player player = players[i];
        String name   = player.getName();
        int    score  = player.getScore();
        // Print name and score followed by a newline
        System.out.format("%s: %d%n", name, score);
    }
}

// Print a single player, 3 players, and all players
printScores(player1);
System.out.println();
printScores(player2, player3, player4);
System.out.println();
printScores(playersArray);

// Output
Abe: 11

Bob: 22
Cal: 33
Dan: 44

Abe: 11
Bob: 22
Cal: 33
Dan: 44

Note there's also the similar System.out.printf method that behaves the same way, but if you peek at the implementation, printf just calls format, so you might as well use format directly.

how to read xml file from url using php

you can get the data from the XML by using "simplexml_load_file" Function. Please refer this link

http://php.net/manual/en/function.simplexml-load-file.php

$url = "http://maps.google.com/maps/api/directions/xml?origin=Quentin+Road+Brooklyn%2C+New+York%2C+11234+United+States&destination=550+Madison+Avenue+New+York%2C+New+York%2C+10001+United+States&sensor=false";
$xml = simplexml_load_file($url);
print_r($xml);

Getting "TypeError: failed to fetch" when the request hasn't actually failed

If your are invoking fetch on a localhost server, use non-SSL unless you have a valid certificate for localhost. fetch will fail on an invalid or self signed certificate especially on localhost.

How to print VARCHAR(MAX) using Print Statement?

I know it's an old question, but what I did is not mentioned here.

For me the following worked.

DECLARE @info NVARCHAR(MAX)

--SET @info to something big

PRINT CAST(@info AS NTEXT)

jQuery - select the associated label element of a input field

As long and your input and label elements are associated by their id and for attributes, you should be able to do something like this:

$('.input').each(function() { 
   $this = $(this);
   $label = $('label[for="'+ $this.attr('id') +'"]');
   if ($label.length > 0 ) {
       //this input has a label associated with it, lets do something!
   }
});

If for is not set then the elements have no semantic relation to each other anyway, and there is no benefit to using the label tag in that instance, so hopefully you will always have that relationship defined.

Service located in another namespace

It is so simple to do it

if you want to use it as host and want to resolve it

If you are using ambassador to any other API gateway for service located in another namespace it's always suggested to use :

            Use : <service name>
            Use : <service.name>.<namespace name>
            Not : <service.name>.<namespace name>.svc.cluster.local

it will be like : servicename.namespacename.svc.cluster.local

this will send request to a particular service inside the namespace you have mention.

example:

kind: Service
apiVersion: v1
metadata:
  name: service
spec:
  type: ExternalName
  externalName: <servicename>.<namespace>.svc.cluster.local

Here replace the <servicename> and <namespace> with the appropriate value.

In Kubernetes, namespaces are used to create virtual environment but all are connect with each other.

Bash write to file without echo?

There are multiple ways to do it, let's run this script called exercise.sh

#!/usr/bin/env bash

> file1.txt cat <<< "This is a here-string with random value $RANDOM"

# Or if you prefer to see what is happening and write to file as well
tee file2.txt <<< "Here is another here-string I can see and write to file"

# if you want to work multiline easily
cat <<EOF > file3.txt
You don't need to escape any quotes here, $ marks start of variables, unless escaped.
This is random value from variable $RANDOM
This is literal \$RANDOM
EOF

# Let's say you have a variable with multiline text and you want to manipulate it
a="
1
2
3
33
"

# Assume I want to have lines containing "3". Instead of grep it can even be another script
a=$(echo "$a" | grep 3)

# Then you want to write this to a file, although here-string is fine,
# if you don't need single-liner command, prefer heredoc
# Herestring. (If it's single liner, variable needs to be quoted to preserve newlines)
> file4.txt cat <<< "$a"
# Heredoc
cat <<EOF > file5.txt
$a
EOF

This is the output you should see:

$ bash exercise.sh
Here is another here-string I can see and write to file

And files should contain these:

$ ls
exercise.sh  file1.txt  file2.txt  file3.txt  file4.txt  file5.txt
$ cat file1.txt
This is a here-string with random value 20914
$ cat file2.txt
Here is another here-string I can see and write to file
$ cat file3.txt
You don't need to escape any quotes here, $ marks start of variables, unless escaped.
This is random value from variable 15899
This is literal $RANDOM
$ cat file4.txt
3
33
$ cat file5.txt
3
33

How to insert an object in an ArrayList at a specific position

Here is the simple arraylist example for insertion at specific index

ArrayList<Integer> str=new ArrayList<Integer>();
    str.add(0);
    str.add(1);
    str.add(2);
    str.add(3); 
    //Result = [0, 1, 2, 3]
    str.add(1, 11);
    str.add(2, 12);
    //Result = [0, 11, 12, 1, 2, 3]

How to set a value for a selectize.js input?

Here is my full code using tag from remote search. Hope this is helpful.

$('#myInput').selectize({
valueField: 'id',
labelField: 'name',
searchField: 'name',
options: [],
delimiter: ',',
persist: false,
create: false,
load: function(query, callback) {
    if (!query.length) return callback();
    $.ajax({
        url: '/api/all_cities.php',
        type: 'GET',
        dataType: 'json',
        data: {
            name: query,
        },
        error: function() {
            callback();
        },
        success: function(res) {
            callback(res);
        }
    });
},
onInitialize: function(){
    var selectize = this;
    $.get("/api/selected_cities.php", function( data ) {
        selectize.addOption(data); // This is will add to option
        var selected_items = [];
        $.each(data, function( i, obj) {
            selected_items.push(obj.id);
        });
        selectize.setValue(selected_items); //this will set option values as default
    });
}
});

How to Execute SQL Server Stored Procedure in SQL Developer?

Select * from Table name ..i.e(are you save table name in sql(TEST) k.

Select * from TEST then you will execute your project.

TypeError: ObjectId('') is not JSON serializable

If you will not be needing the _id of the records I will recommend unsetting it when querying the DB which will enable you to print the returned records directly e.g

To unset the _id when querying and then print data in a loop you write something like this

records = mycollection.find(query, {'_id': 0}) #second argument {'_id':0} unsets the id from the query
for record in records:
    print(record)

Automated Python to Java translation

Actually, this may or may not be much help but you could write a script which created a Java class for each Python class, including method stubs, placing the Python implementation of the method inside the Javadoc

In fact, this is probably pretty easy to knock up in Python.

I worked for a company which undertook a port to Java of a huge Smalltalk (similar-ish to Python) system and this is exactly what they did. Filling in the methods was manual but invaluable, because it got you to really think about what was going on. I doubt that a brute-force method would result in nice code.

Here's another possibility: can you convert your Python to Jython more easily? Jython is just Python for the JVM. It may be possible to use a Java decompiler (e.g. JAD) to then convert the bytecode back into Java code (or you may just wish to run on a JVM). I'm not sure about this however, perhaps someone else would have a better idea.

Default SecurityProtocol in .NET 4.5

The BEST solution to this problem appears to be to upgrade to at least .NET 4.6 or later, which will automatically choose strong protocols as well as strong ciphers.

If you can't upgrade to .NET 4.6, the advice of setting

System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

And using the registry settings:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft.NETFramework\v4.0.30319 – SchUseStrongCrypto = DWORD of 1 HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft.NETFramework\v4.0.30319 – SchUseStrongCrypto = DWORD of 1

Results in using something other than TLS 1.0 and a strong cipher.

In my testing, only the setting in the Wow6432Node made any difference, even though my test application was built for Any CPU.

Hash and salt passwords in C#

Use the System.Web.Helpers.Crypto NuGet package from Microsoft. It automatically adds salt to the hash.

You hash a password like this: var hash = Crypto.HashPassword("foo");

You verify a password like this: var verified = Crypto.VerifyHashedPassword(hash, "foo");

how to bold words within a paragraph in HTML/CSS?

if you want to just "bold", Mike Hofer's answer is mostly correct.

but notice that the tag bolds its contents by default, but you can change this behavior using css, example:

p strong {
    font-weight: normal;
    font-style: italic;
}

Now your "bold" is italic :)

So, try to use tags by its meaning, not by its default style.

Convert String to Float in Swift

Here is a Swift 3 adaptation of Paul Hegarty's solution from rdprado's answer, with some checking for optionals added to it (returning 0.0 if any part of the process fails):

var wageFloat:Float = 0.0

if let wageText = wage.text {
    if let wageNumber = NumberFormatter().number(from: wageText) {
        wageFloat = wageNumber.floatValue
    }
}

By the way, I took Stanford's CS193p class using iTunes University when it was still teaching Objective-C.

I found Paul Hegarty to be a FANTASTIC instructor, and I would highly recommend the class to anyone starting out as an iOS developer in Swift!!!

File to byte[] in Java

Simple way to do it:

File fff = new File("/path/to/file");
FileInputStream fileInputStream = new FileInputStream(fff);

// int byteLength = fff.length(); 

// In android the result of file.length() is long
long byteLength = fff.length(); // byte count of the file-content

byte[] filecontent = new byte[(int) byteLength];
fileInputStream.read(filecontent, 0, (int) byteLength);

Difference between a SOAP message and a WSDL?

A SOAP document is sent per request. Say we were a book store, and had a remote server we queried to learn the current price of a particular book. Say we needed to pass the Book's title, number of pages and ISBN number to the server.

Whenever we wanted to know the price, we'd send a unique SOAP message. It'd look something like this;

<SOAP-ENV:Envelope
  xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
  SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
  <SOAP-ENV:Body>
    <m:GetBookPrice xmlns:m="http://namespaces.my-example-book-info.com">
      <ISBN>978-0451524935</ISBN>
      <Title>1984</Title>
      <NumPages>328</NumPages>
    </m:GetBookPrice>
  </SOAP-ENV:Body>
</SOAP-ENV:Envelope> 

And we expect to get a SOAP response message back like;

<SOAP-ENV:Envelope
  xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
  SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
  <SOAP-ENV:Body>
    <m:GetBookPriceResponse xmlns:m="http://namespaces.my-example-book-info.com">
      <CurrentPrice>8.99</CurrentPrice>
      <Currency>USD</Currency>
    </m:GetBookPriceResponse>
  </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

The WSDL then describes how to handle/process this message when a server receives it. In our case, it describes what types the Title, NumPages & ISBN would be, whether we should expect a response from the GetBookPrice message and what that response should look like.

The types would look like this;

<wsdl:types>

  <!-- all type declarations are in a chunk of xsd -->
  <xsd:schema targetNamespace="http://namespaces.my-example-book-info.com"
    xmlns:xsd="http://www.w3.org/1999/XMLSchema">

    <xsd:element name="GetBookPrice">
      <xsd:complexType>
        <xsd:sequence>
          <xsd:element name="ISBN" type="string"/>
          <xsd:element name="Title" type="string"/>
          <xsd:element name="NumPages" type="integer"/>
        </xsd:sequence>
      </xsd:complexType>
    </xsd:element>

    <xsd:element name="GetBookPriceResponse">
      <xsd:complexType>
        <xsd:sequence>
          <xsd:element name="CurrentPrice" type="decimal" />
          <xsd:element name="Currency" type="string" />
        </xsd:sequence>
      </xsd:complexType>
    </xsd:element>

  </xsd:schema>
</wsdl:types>

But the WSDL also contains more information, about which functions link together to make operations, and what operations are avaliable in the service, and whereabouts on a network you can access the service/operations.

See also W3 Annotated WSDL Examples

Android Facebook 4.0 SDK How to get Email, Date of Birth and gender of User

This is worked for me, Hope to help someone (Using my own button not FB login button )

CallbackManager callbackManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FacebookSdk.sdkInitialize(getApplicationContext());
    setContentView(R.layout.activity_sign_in_user);



     LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {


            GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
                @Override
                public void onCompleted(JSONObject object, GraphResponse response) {
                    try {
                        Log.i("RESAULTS : ", object.getString("email"));
                    }catch (Exception e){

                    }
                }
            });
            Bundle parameters = new Bundle();
            parameters.putString("fields", "email");
            request.setParameters(parameters);
            request.executeAsync();

        }

        @Override
        public void onCancel() {

        }

        @Override
        public void onError(FacebookException error) {
            Log.i("RESAULTS : ", error.getMessage());
        }
    });


}

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


boolean isEmailValid(CharSequence email) {
    return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}

public void signupwith_facebook(View view) {

    LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile","email"));
}
}

libaio.so.1: cannot open shared object file

In case one does not have sudo privilege, but still needs to install the library.

Download source for the software/library using:

apt-get source libaio

or

wget https://src.fedoraproject.org/lookaside/pkgs/libaio/libaio-0.3.110.tar.gz/2a35602e43778383e2f4907a4ca39ab8/libaio-0.3.110.tar.gz

unzip the library

Install with the following command to user-specific library:

make prefix=`pwd`/usr install #(Copy from INSTALL file of libaio-0.3.110)

or

make prefix=/path/to/your/lib/libaio install

Include libaio library into LD_LIBRARY_PATH for your app:

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/path/to/your/lib/libaio/lib

Now, your app should be able to find libaio.so.1

Defining arrays in Google Scripts

I think that maybe it is because you are declaring a variable that you already declared:

var Name = new Array(6);
//...
var Name[0] = Name_cell.getValue();  //  <-- Here's the issue: 'var'

I think this should be like this:

var Name = new Array(6);
//...
Name[0] = Name_cell.getValue();

Tell me if it works! ;)

Configure Apache .conf for Alias

Sorry not sure what was going on this worked in the end:

<VirtualHost *> 
    ServerName example.com
    DocumentRoot /var/www/html/mjp

    Alias /ncn "/var/www/html/ncn"

    <Directory "/var/www/html/ncn">
        Options None
        AllowOverride None
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>

trying to align html button at the center of the my page

Place it inside another div, use CSS to move the button to the middle:

<div style="width:100%;height:100%;position:absolute;vertical-align:middle;text-align:center;">
    <button type="button" style="background-color:yellow;margin-left:auto;margin-right:auto;display:block;margin-top:22%;margin-bottom:0%">
mybuttonname</button> 
</div>?

Here is an example: JsFiddle

The ternary (conditional) operator in C

The fact that the ternary operator is an expression, not a statement, allows it to be used in macro expansions for function-like macros that are used as part of an expression. Const may not have been part of original C, but the macro pre-processor goes way back.

One place where I've seen it used is in an array package that used macros for bound-checked array accesses. The syntax for a checked reference was something like aref(arrayname, type, index), where arrayname was actually a pointer to a struct that included the array bounds and an unsigned char array for the data, type was the actual type of the data, and index was the index. The expansion of this was quite hairy (and I'm not going to do it from memory), but it used some ternary operators to do the bound checking.

You can't do this as a function call in C because of the need for polymorphism of the returned object. So a macro was needed to do the type casting in the expression. In C++ you could do this as a templated overloaded function call (probably for operator[]), but C doesn't have such features.

Edit: Here's the example I was talking about, from the Berkeley CAD array package (glu 1.4 edition). The documentation of the array_fetch usage is:

type
array_fetch(type, array, position)
typeof type;
array_t *array;
int position;

Fetch an element from an array. A runtime error occurs on an attempt to reference outside the bounds of the array. There is no type-checking that the value at the given position is actually of the type used when dereferencing the array.

and here is the macro defintion of array_fetch (note the use of the ternary operator and the comma sequencing operator to execute all the subexpressions with the right values in the right order as part of a single expression):

#define array_fetch(type, a, i)         \
(array_global_index = (i),              \
  (array_global_index >= (a)->num) ? array_abort((a),1) : 0,\
  *((type *) ((a)->space + array_global_index * (a)->obj_size)))

The expansion for array_insert ( which grows the array if necessary, like a C++ vector) is even hairier, involving multiple nested ternary operators.