Programs & Examples On #Dojo

Dojo Toolkit is an open source modular JavaScript library designed to ease the rapid development of cross-platform, JavaScript/Ajax-based applications and web sites. It is dual-licensed under the BSD License and the Academic Free License. Dojo uses the Asynchronous Module Definition (AMD) format for its source code, allowing completely modular web application development.

Node.JS: Getting error : [nodemon] Internal watch failed: watch ENOSPC

[nodemon] Internal watch failed: watch /home/Document/nmmExpressServer/bin ENOSPC
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] start: `nodemon ./bin/www`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the [email protected] start script.

This is the error I got when running nodemon ./bin/www.

The solution was closing an Atom window that had a entire directory of folders open in the project window.

I don't know why, but I'm assuming Atom and nodemon use similar processes to watch files/folders.

How to identify and switch to the frame in selenium webdriver when frame does not have id

Make sure you switch to default content before switching to frame:

driver.switchTo().defaultContent();
driver.switchTo().frame(x);

x can be the frame number or you can do a driver.findlement and use any of the options you have available eg: driver.findElementByName("Name").

How to export JavaScript array info to csv (on client side)?

//It work in Chrome and IE ... I reviewed and readed a lot of answer. then i used it and tested in both ... 

var link = document.createElement("a");

if (link.download !== undefined) { // feature detection
    // Browsers that support HTML5 download attribute
    var blob = new Blob([CSV], { type: 'text/csv;charset=utf-8;' });
    var url = URL.createObjectURL(blob);            
    link.setAttribute("href", url);
    link.setAttribute("download", fileName);
    link.style = "visibility:hidden";
}

if (navigator.msSaveBlob) { // IE 10+
   link.addEventListener("click", function (event) {
     var blob = new Blob([CSV], {
       "type": "text/csv;charset=utf-8;"
     });
   navigator.msSaveBlob(blob, fileName);
  }, false);
}

document.body.appendChild(link);
link.click();
document.body.removeChild(link);

//Regards

JavaScript code to stop form submission

The following works as of now (tested in Chrome and Firefox):

<form onsubmit="event.preventDefault(); validateMyForm();">

Where validateMyForm() is a function that returns false if validation fails. The key point is to use the name event. We cannot use for e.g. e.preventDefault().

How to make HTML table cell editable?

This is the essential point although you don't need to make the code this messy. Instead you could just iterate through all the <td> and add the <input> with the attributes and finally put in the values.

_x000D_
_x000D_
function edit(el) {_x000D_
  el.childNodes[0].removeAttribute("disabled");_x000D_
  el.childNodes[0].focus();_x000D_
  window.getSelection().removeAllRanges();_x000D_
}_x000D_
function disable(el) {_x000D_
  el.setAttribute("disabled","");_x000D_
}
_x000D_
<table border>_x000D_
<tr>_x000D_
<td ondblclick="edit(this)"><input value="cell1" disabled onblur="disable(this)"></td>_x000D_
<td ondblclick="edit(this)"><input value="cell2" disabled onblur="disable(this)"></td>_x000D_
<td ondblclick="edit(this)"><input value="cell3" disabled onblur="disable(this)"></td>_x000D_
<td ondblclick="edit(this)"><input value="so forth..." disabled onblur="disable(this)">_x000D_
</td>_x000D_
</tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How to create a css rule for all elements except one class?

The safest bet is to create a class on those tables and use that. Currently getting something like this to work in all major browsers is unlikely.

Can I get the name of the currently running function in JavaScript?

In ES5 and above, there is no access to that information.

In older versions of JS you can get it by using arguments.callee.

You may have to parse out the name though, as it will probably include some extra junk. Though, in some implementations you can simply get the name using arguments.callee.name.

Parsing:

function DisplayMyName() 
{
   var myName = arguments.callee.toString();
   myName = myName.substr('function '.length);
   myName = myName.substr(0, myName.indexOf('('));

   alert(myName);
}

Source: Javascript - get current function name.

jQuery override default validation error message display (Css) Popup/Tooltip like

Add following css to your .validate method to change the css or functionality

 errorElement: "div",
    wrapper: "div",
    errorPlacement: function(error, element) {
        offset = element.offset();
        error.insertAfter(element)
        error.css('color','red');
    }

Remove all the children DOM elements in div

node.innerHTML = "";

Non-standard, but fast and well supported.

How do I implement basic "Long Polling"?

I think the client looks like a normal asynchronous AJAX request, but you expect it to take a "long time" to come back.

The server then looks like this.

while (!hasNewData())
    usleep(50);

outputNewData();

So, the AJAX request goes to the server, probably including a timestamp of when it was last update so that your hasNewData() knows what data you have already got. The server then sits in a loop sleeping until new data is available. All the while, your AJAX request is still connected, just hanging there waiting for data. Finally, when new data is available, the server gives it to your AJAX request and closes the connection.

How to stop a goroutine

Typically, you pass the goroutine a (possibly separate) signal channel. That signal channel is used to push a value into when you want the goroutine to stop. The goroutine polls that channel regularly. As soon as it detects a signal, it quits.

quit := make(chan bool)
go func() {
    for {
        select {
        case <- quit:
            return
        default:
            // Do other stuff
        }
    }
}()

// Do stuff

// Quit goroutine
quit <- true

How to get request URL in Spring Boot RestController

You may try adding an additional argument of type HttpServletRequest to the getUrlValue() method:

@RequestMapping(value ="/",produces = "application/json")
public String getURLValue(HttpServletRequest request){
    String test = request.getRequestURI();
    return test;
}

How can I determine the current CPU utilization from the shell?

Try this command:

cat /proc/stat

This will be something like this:

cpu  55366 271 17283 75381807 22953 13468 94542 0
cpu0 3374 0 2187 9462432 1393 2 665 0
cpu1 2074 12 1314 9459589 841 2 43 0
cpu2 1664 0 1109 9447191 666 1 571 0
cpu3 864 0 716 9429250 387 2 118 0
cpu4 27667 110 5553 9358851 13900 2598 21784 0
cpu5 16625 146 2861 9388654 4556 4026 24979 0
cpu6 1790 0 1836 9436782 480 3307 19623 0
cpu7 1306 0 1702 9399053 726 3529 26756 0
intr 4421041070 559 10 0 4 5 0 0 0 26 0 0 0 111 0 129692 0 0 0 0 0 95 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 369 91027 1580921706 1277926101 570026630 991666971 0 277768 0 0 0 0 0 0 0 0 0 0 0 0 0
ctxt 8097121
btime 1251365089
processes 63692
procs_running 2
procs_blocked 0

More details:

http://www.mail-archive.com/[email protected]/msg01690.html http://www.linuxhowtos.org/System/procstat.htm

Jquery to get SelectedText from dropdown

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="jquery-3.1.0.js"></script>
    <script>
        $(function () {
            $('#selectnumber').change(function(){
                alert('.val() = ' + $('#selectnumber').val() + '  AND  html() = ' + $('#selectnumber option:selected').html() + '  AND .text() = ' + $('#selectnumber option:selected').text());
            })
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <select id="selectnumber">
            <option value="1">one</option>
            <option value="2">two</option>
            <option value="3">three</option>
            <option value="4">four</option>
        </select>

    </div>
    </form>
</body>
</html>

Click to see Output Screen

Thanks...:)

How to select where ID in Array Rails ActiveRecord without exception

If it is just avoiding the exception you are worried about, the "find_all_by.." family of functions works without throwing exceptions.

Comment.find_all_by_id([2, 3, 5])

will work even if some of the ids don't exist. This works in the

user.comments.find_all_by_id(potentially_nonexistent_ids)

case as well.

Update: Rails 4

Comment.where(id: [2, 3, 5])

How to convert a full date to a short date in javascript?

Built-in toLocaleDateString() does the job, but it will remove the leading 0s for the day and month, so we will get something like "1/9/1970", which is not perfect in my opinion. To get a proper format MM/DD/YYYY we can use something like:

new Date(dateString).toLocaleDateString('en-US', {
  day: '2-digit',
  month: '2-digit',
  year: 'numeric',
})

ObservableCollection not noticing when Item in it changes (even with INotifyPropertyChanged)

Just adding my 2 cents on this topic. Felt the TrulyObservableCollection required the two other constructors as found with ObservableCollection:

public TrulyObservableCollection()
        : base()
    {
        HookupCollectionChangedEvent();
    }

    public TrulyObservableCollection(IEnumerable<T> collection)
        : base(collection)
    {
        foreach (T item in collection)
            item.PropertyChanged += ItemPropertyChanged;

        HookupCollectionChangedEvent();
    }

    public TrulyObservableCollection(List<T> list)
        : base(list)
    {
        list.ForEach(item => item.PropertyChanged += ItemPropertyChanged);

        HookupCollectionChangedEvent();
    }

    private void HookupCollectionChangedEvent()
    {
        CollectionChanged += new NotifyCollectionChangedEventHandler(TrulyObservableCollectionChanged);
    }

"Can't find Project or Library" for standard VBA functions

I had the same problem. This worked for me:

  • In VB go to Tools » References
  • Uncheck the library "Crystal Analysis Common Controls 1.0". Or any library.
  • Just leave these 5 references:
    1. Visual Basic For Applications (This is the library that defines the VBA language.)
    2. Microsoft Excel Object Library (This defines all of the elements of Excel.)
    3. OLE Automation (This specifies the types for linking and embedding documents and for automation of other applications and the "plumbing" of the COM system that Excel uses to communicate with the outside world.)
    4. Microsoft Office (This defines things that are common to all Office programs such as Command Bars and Command Bar controls.)
    5. Microsoft Forms 2.0 This is required if you are using a User Form. This library defines things like the user form and the controls that you can place on a form.
  • Then Save.

Clear the cache in JavaScript

Maybe "clearing cache" is not as easy as it should be. Instead of clearing cache on my browsers, I realized that "touching" the file will actually change the date of the source file cached on the server (Tested on Edge, Chrome and Firefox) and most browsers will automatically download the most current fresh copy of whats on your server (code, graphics any multimedia too). I suggest you just copy the most current scripts on the server and "do the touch thing" solution before your program runs, so it will change the date of all your problem files to a most current date and time, then it downloads a fresh copy to your browser:

<?php
    touch('/www/control/file1.js');
    touch('/www/control/file2.js');
    touch('/www/control/file2.js');
?>

...the rest of your program...

It took me some time to resolve this issue (as many browsers act differently to different commands, but they all check time of files and compare to your downloaded copy in your browser, if different date and time, will do the refresh), If you can't go the supposed right way, there is always another usable and better solution to it. Best Regards and happy camping.

Powershell script to check if service is started, if not then start it

The below is a compact script that will check if "running" and attempt start service until the service returns as running.

$Service = 'ServiceName'
If ((Get-Service $Service).Status -ne 'Running') {
   do {
       Start-Service $Service -ErrorAction SilentlyContinue
       Start-Sleep 10
   } until ((Get-Service $Service).Status -eq 'Running')
} Return "$($Service) has STARTED"

Load different application.yml in SpringBoot Test

Starting with Spring 4.1, We can directly set the property in application.yml using the @TestPropertySource annotation.

@RunWith(SpringRunner.class)
@SpringBootTest
@TestPropertySource(properties = {"yoursection.yourparameter=your_value"})
public MyIntTest
{
 //your test methods
}

Just convert your yaml parameters into complete property structure. For example: If content of application.yml is like below

yoursection:
  yourparameter:your_value

Then value to go inside the @TestPropertySource will be,

yoursection.yourparameter=your_value

Chaining Observables in RxJS

About promise composition vs. Rxjs, as this is a frequently asked question, you can refer to a number of previously asked questions on SO, among which :

Basically, flatMap is the equivalent of Promise.then.

For your second question, do you want to replay values already emitted, or do you want to process new values as they arrive? In the first case, check the publishReplay operator. In the second case, standard subscription is enough. However you might need to be aware of the cold. vs. hot dichotomy depending on your source (cf. Hot and Cold observables : are there 'hot' and 'cold' operators? for an illustrated explanation of the concept)

Exception.Message vs Exception.ToString()

In addition to what's already been said, don't use ToString() on the exception object for displaying to the user. Just the Message property should suffice, or a higher level custom message.

In terms of logging purposes, definitely use ToString() on the Exception, not just the Message property, as in most scenarios, you will be left scratching your head where specifically this exception occurred, and what the call stack was. The stacktrace would have told you all that.

MySQL: Get column name or alias from query

Looks like MySQLdb doesn't actually provide a translation for that API call. The relevant C API call is mysql_fetch_fields, and there is no MySQLdb translation for that

How do I make an Event in the Usercontrol and have it handled in the Main Form?

You need to create an event handler for the user control that is raised when an event from within the user control is fired. This will allow you to bubble the event up the chain so you can handle the event from the form.

When clicking Button1 on the UserControl, i'll fire Button1_Click which triggers UserControl_ButtonClick on the form:

User control:

[Browsable(true)] [Category("Action")] 
[Description("Invoked when user clicks button")]
public event EventHandler ButtonClick;

protected void Button1_Click(object sender, EventArgs e)
{
    //bubble the event up to the parent
    if (this.ButtonClick!= null)
        this.ButtonClick(this, e);               
}

Form:

UserControl1.ButtonClick += new EventHandler(UserControl_ButtonClick);

protected void UserControl_ButtonClick(object sender, EventArgs e)
{
    //handle the event 
}

Notes:

  • Newer Visual Studio versions suggest that instead of if (this.ButtonClick!= null) this.ButtonClick(this, e); you can use ButtonClick?.Invoke(this, e);, which does essentially the same, but is shorter.

  • The Browsable attribute makes the event visible in Visual Studio's designer (events view), Category shows it in the "Action" category, and Description provides a description for it. You can omit these attributes completely, but making it available to the designer it is much more comfortable, since VS handles it for you.

How do you fadeIn and animate at the same time?

For people still looking a couple of years later, things have changed a bit. You can now use the queue for .fadeIn() as well so that it will work like this:

$('.tooltip').fadeIn({queue: false, duration: 'slow'});
$('.tooltip').animate({ top: "-10px" }, 'slow');

This has the benefit of working on display: none elements so you don't need the extra two lines of code.

Why does the program give "illegal start of type" error?

You have an extra '{' before return type. You may also want to put '==' instead of '=' in if and else condition.

Filter by process/PID in Wireshark

Use strace is more suitable for this situation.

strace -f -e trace=network -s 10000 -p <PID>;

options -f to also trace all forked processes, -e trace=netwrok to only filter network system-call and -s to display string length up to 10000 char.

You can also only trace certain calls like send,recv, read operations.

strace -f -e trace=send,recv,read -s 10000 -p <PID>;

keycode 13 is for which key

The Enter key should have the keycode 13. Is it not working?

From io.Reader to string in Go

var b bytes.Buffer
b.ReadFrom(r)

// b.String()

How to know/change current directory in Python shell?

You can try this:

import os

current_dir = os.path.dirname(os.path.abspath(__file__))   # Can also use os.getcwd()
print(current_dir)                                         # prints(say)- D:\abc\def\ghi\jkl\mno"
new_dir = os.chdir('..\\..\\..\\')                         
print(new_dir)                                             # prints "D:\abc\def\ghi"


error LNK2038: mismatch detected for '_ITERATOR_DEBUG_LEVEL': value '0' doesn't match value '2' in main.obj

Try change _DEBUG to NDEBUG macro definition in C++ project properties (for Release configuration) Configuration Properties -> C/C++ -> Preprocessor -> Preprocessor Definitions

Can I pass column name as input parameter in SQL stored Procedure

You can pass the column name but you cannot use it in a sql statemnt like

Select @Columnname From Table

One could build a dynamic sql string and execute it like EXEC (@SQL)

For more information see this answer on dynamic sql.

Dynamic SQL Pros and Cons

SQL Server - calculate elapsed time between two datetime stamps in HH:MM:SS format

Hope this helps you in getting the exact time between two time stamps

Create PROC TimeDurationbetween2times(@iTime as time,@oTime as time) 
As  
Begin  

DECLARE @Dh int, @Dm int, @Ds int ,@Im int, @Om int, @Is int,@Os int     

SET @Im=DATEPART(MI,@iTime)  
SET @Om=DATEPART(MI,@oTime)  
SET @Is=DATEPART(SS,@iTime)  
SET @Os=DATEPART(SS,@oTime)  

SET @Dh=DATEDIFF(hh,@iTime,@oTime)  
SET @Dm = DATEDIFF(mi,@iTime,@oTime)  
SET @Ds = DATEDIFF(ss,@iTime,@oTime)  

DECLARE @HH as int, @MI as int, @SS as int  

if(@Im>@Om)  
begin  
SET @Dh=@Dh-1  
end  
if(@Is>@Os)  
begin  
SET @Dm=@Dm-1  
end  

SET @HH = @Dh  
SET @MI = @Dm-(60*@HH)  
SET @SS = @Ds-(60*@Dm)  

DECLARE @hrsWkd as varchar(8)         

SET @hrsWkd = cast(@HH as char(2))+':'+cast(@MI as char(2))+':'+cast(@SS as char(2))          

select @hrsWkd as TimeDuration   

End

Python OpenCV2 (cv2) wrapper to get image size?

cv2 uses numpy for manipulating images, so the proper and best way to get the size of an image is using numpy.shape. Assuming you are working with BGR images, here is an example:

>>> import numpy as np
>>> import cv2
>>> img = cv2.imread('foo.jpg')
>>> height, width, channels = img.shape
>>> print height, width, channels
  600 800 3

In case you were working with binary images, img will have two dimensions, and therefore you must change the code to: height, width = img.shape

Iterating through map in template

As Herman pointed out, you can get the index and element from each iteration.

{{range $index, $element := .}}{{$index}}
{{range $element}}{{.Value}}
{{end}}
{{end}}

Working example:

package main

import (
    "html/template"
    "os"
)

type EntetiesClass struct {
    Name string
    Value int32
}

// In the template, we use rangeStruct to turn our struct values
// into a slice we can iterate over
var htmlTemplate = `{{range $index, $element := .}}{{$index}}
{{range $element}}{{.Value}}
{{end}}
{{end}}`

func main() {
    data := map[string][]EntetiesClass{
        "Yoga": {{"Yoga", 15}, {"Yoga", 51}},
        "Pilates": {{"Pilates", 3}, {"Pilates", 6}, {"Pilates", 9}},
    }

    t := template.New("t")
    t, err := t.Parse(htmlTemplate)
    if err != nil {
        panic(err)
    }

    err = t.Execute(os.Stdout, data)
    if err != nil {
        panic(err)
    }

}

Output:

Pilates
3
6
9

Yoga
15
51

Playground: http://play.golang.org/p/4ISxcFKG7v

How to include *.so library in Android Studio?

Current Solution

Create the folder project/app/src/main/jniLibs, and then put your *.so files within their abi folders in that location. E.g.,

project/
+--libs/
|  +-- *.jar       <-- if your library has jar files, they go here
+--src/
   +-- main/
       +-- AndroidManifest.xml
       +-- java/
       +-- jniLibs/ 
           +-- arm64-v8a/                       <-- ARM 64bit
           ¦   +-- yourlib.so
           +-- armeabi-v7a/                     <-- ARM 32bit
           ¦   +-- yourlib.so
           +-- x86/                             <-- Intel 32bit
               +-- yourlib.so

Deprecated solution

Add both code snippets in your module gradle.build file as a dependency:

compile fileTree(dir: "$buildDir/native-libs", include: 'native-libs.jar')

How to create this custom jar:

task nativeLibsToJar(type: Jar, description: 'create a jar archive of the native libs') {
    destinationDir file("$buildDir/native-libs")
    baseName 'native-libs'
    from fileTree(dir: 'libs', include: '**/*.so')
    into 'lib/'
}

tasks.withType(JavaCompile) {
    compileTask -> compileTask.dependsOn(nativeLibsToJar)
}

Same answer can also be found in related question: Include .so library in apk in android studio

Opacity CSS not working in IE8

Apparently alpha transparency only works on block level elements in IE 8. Set display: block.

Annotation @Transactional. How to rollback?

or programatically

TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

Javascript / Chrome - How to copy an object from the webkit inspector as code

This should help stringify deep objects by leaving out recursive Window and Node objects.

function stringifyObject(e) {
  const obj = {};
  for (let k in e) {
    obj[k] = e[k];
  }

  return JSON.stringify(obj, (k, v) => {
    if (v instanceof Node) return 'Node';
    if (v instanceof Window) return 'Window';
    return v;
  }, ' ');
}

Bootstrap 3 hidden-xs makes row narrower

How does it work if you only are using visible-md at Col4 instead? Do you use the -lg at all? If not this might work.

<div class="container">
    <div class="row">
        <div class="col-xs-4 col-sm-2 col-md-1" align="center">
            Col1
        </div>
        <div class="col-xs-4 col-sm-2" align="center">
            Col2
        </div>
        <div class="hidden-xs col-sm-6 col-md-5" align="center">
            Col3
        </div>
        <div class="visible-md col-md-3 " align="center">
            Col4
        </div>
        <div class="col-xs-4 col-sm-2 col-md-1" align="center">
            Col5
        </div>
    </div>
</div>

Prevent Caching in ASP.NET MVC for specific actions using an attribute

Correct attribute value for Asp.Net MVC Core to prevent browser caching (including Internet Explorer 11) is:

[ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]

as described in Microsoft documentation:

Response caching in ASP.NET Core - NoStore and Location.None

How can I customize the tab-to-space conversion factor?

I tried to change editor.tabSize to 4, but .editorConfig overrides whatever settings I had specified, so there is no need to change any configuration in user settings. You just need to edit .editorConfig file:

set indent_size = 4

How to use "svn export" command to get a single file from the repository?

I know the OP was asking about doing the export from the command line, but just in case this is helpful to anyone else out there...

You could just let Eclipse (plus one of the plugins discussed here) do the work for you.

Obviously, downloading Eclipse just for doing a single export is overkill, but if you are already using it for development, you can also do an svn export simply from your IDE's context menu when browsing an SVN repository.

Advantages:

  • easier for those not so familiar with using SVN at the command-line level (but you can learn about what happens at the command-line level by looking at the SVN console with a range of commands)
  • you'd already have your SVN details set up and wouldn't have to worry about authenticating, etc.
  • you don't have to worry about mistyping the URL, or remembering the order of parameters
  • you can specify in a dialog which directory you'd like to export to
  • you can specify in a dialog whether you'd like to export from TRUNK/HEAD or use a specific revision

How do you create a dropdownlist from an enum in ASP.NET MVC?

So without Extension functions if you are looking for simple and easy.. This is what I did

<%= Html.DropDownListFor(x => x.CurrentAddress.State, new SelectList(Enum.GetValues(typeof(XXXXX.Sites.YYYY.Models.State))))%>

where XXXXX.Sites.YYYY.Models.State is an enum

Probably better to do helper function, but when time is short this will get the job done.

Function that creates a timestamp in c#

when you need in a timestamp in seconds, you can use the following:

var timestamp = (int)(DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1)).TotalSeconds;

DataTable: Hide the Show Entries dropdown but keep the Search box

You can find more information directly on this link: http://datatables.net/examples/basic_init/filter_only.html

$(document).ready(function() {
$('#example').dataTable({
    "bPaginate": false,
    "bLengthChange": false,
    "bFilter": true,
    "bInfo": false,
    "bAutoWidth": false });
});

Hope that helps !

EDIT : If you are lazy, "bLengthChange": false, is the one you need to change :)

In CSS Flexbox, why are there no "justify-items" and "justify-self" properties?

I know this doesn't use flexbox, but for the simple use-case of three items (one at left, one at center, one at right), this can be accomplished easily using display: grid on the parent, grid-area: 1/1/1/1; on the children, and justify-self for positioning of those children.

_x000D_
_x000D_
<div style="border: 1px solid red; display: grid; width: 100px; height: 25px;">_x000D_
  <div style="border: 1px solid blue; width: 25px; grid-area: 1/1/1/1; justify-self: left;"></div>_x000D_
  <div style="border: 1px solid blue; width: 25px; grid-area: 1/1/1/1; justify-self: center;"></div>_x000D_
  <div style="border: 1px solid blue; width: 25px; grid-area: 1/1/1/1; justify-self: right;"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What causes a SIGSEGV

segmentation fault arrives when you access memory which is not declared by the program. You can do this through pointers i.e through memory addresses. Or this may also be due to stackoverflow for eg:

void rec_func() {int q = 5; rec_func();}

int main() {rec_func();}

This call will keep on consuming stack memory until it's completely filled and thus finally stackoverflow happens. Note: it might not be visible in some competitive questions as it leads to timeouterror first but for those in which timeout doesn't happens its a hard time figuring out sigsemv.

Making PHP var_dump() values display one line per value

I didn't wanna stop using var_dump($variable);die(); and using pre tags and loops seems overkill to me, so since I am looking at the dump in a browser, I just right click the page and choose Inspect (I use Chrome). The Elements section of the Developer Tools show the variable in a very readable format.

Javascript to display the current date and time

(new Date()).toLocaleString()

Will output the date and time using your local format. For example: "5/1/2020, 10:35:41 AM"

Alternating Row Colors in Bootstrap 3 - No Table

There isn't really a way to do this without the css getting a little convoluted, but here's the cleanest solution I could put together (the breakpoints in this are just for example purposes, change them to whatever breakpoints you're actually using.) The key is :nth-of-type (or :nth-child -- either would work in this case.)

Smallest viewport:

@media (max-width:$smallest-breakpoint) {

  .row div {
     background: #eee;
   }

  .row div:nth-of-type(2n) {
     background: #fff;
   }

}

Medium viewport:

@media (min-width:$smallest-breakpoint) and (max-width:$mid-breakpoint) {

  .row div {
    background: #eee;
  }

  .row div:nth-of-type(4n+1), .row div:nth-of-type(4n+2) {
    background: #fff;
  }

}

Largest viewport:

@media (min-width:$mid-breakpoint) and (max-width:9999px) {

  .row div {
    background: #eee;
  }

  .row div:nth-of-type(6n+4), 
  .row div:nth-of-type(6n+5), 
  .row div:nth-of-type(6n+6) {
      background: #fff;
  }
}

Working fiddle here

Regular Expression to match valid dates

I landed here because the title of this question is broad and I was looking for a regex that I could use to match on a specific date format (like the OP). But I then discovered, as many of the answers and comments have comprehensively highlighted, there are many pitfalls that make constructing an effective pattern very tricky when extracting dates that are mixed-in with poor quality or non-structured source data.

In my exploration of the issues, I have come up with a system that enables you to build a regular expression by arranging together four simpler sub-expressions that match on the delimiter, and valid ranges for the year, month and day fields in the order you require.

These are :-

Delimeters

[^\w\d\r\n:] 

This will match anything that is not a word character, digit character, carriage return, new line or colon. The colon has to be there to prevent matching on times that look like dates (see my test Data)

You can optimise this part of the pattern to speed up matching, but this is a good foundation that detects most valid delimiters.

Note however; It will match a string with mixed delimiters like this 2/12-73 that may not actually be a valid date.

Year Values

(\d{4}|\d{2})

This matches a group of two or 4 digits, in most cases this is acceptable, but if you're dealing with data from the years 0-999 or beyond 9999 you need to decide how to handle that because in most cases a 1, 3 or >4 digit year is garbage.

Month Values

(0?[1-9]|1[0-2])

Matches any number between 1 and 12 with or without a leading zero - note: 0 and 00 is not matched.

Date Values

(0?[1-9]|[12]\d|30|31)

Matches any number between 1 and 31 with or without a leading zero - note: 0 and 00 is not matched.

This expression matches Date, Month, Year formatted dates

(0?[1-9]|[12]\d|30|31)[^\w\d\r\n:](0?[1-9]|1[0-2])[^\w\d\r\n:](\d{4}|\d{2})

But it will also match some of the Year, Month Date ones. It should also be bookended with the boundary operators to ensure the whole date string is selected and prevent valid sub-dates being extracted from data that is not well-formed i.e. without boundary tags 20/12/194 matches as 20/12/19 and 101/12/1974 matches as 01/12/1974

Compare the results of the next expression to the one above with the test data in the nonsense section (below)

\b(0?[1-9]|[12]\d|30|31)[^\w\d\r\n:](0?[1-9]|1[0-2])[^\w\d\r\n:](\d{4}|\d{2})\b

There's no validation in this regex so a well-formed but invalid date such as 31/02/2001 would be matched. That is a data quality issue, and as others have said, your regex shouldn't need to validate the data.

Because you (as a developer) can't guarantee the quality of the source data you do need to perform and handle additional validation in your code, if you try to match and validate the data in the RegEx it gets very messy and becomes difficult to support without very concise documentation.

Garbage in, garbage out.

Having said that, if you do have mixed formats where the date values vary, and you have to extract as much as you can; You can combine a couple of expressions together like so;

This (disastrous) expression matches DMY and YMD dates

(\b(0?[1-9]|[12]\d|30|31)[^\w\d\r\n:](0?[1-9]|1[0-2])[^\w\d\r\n:](\d{4}|\d{2})\b)|(\b(0?[1-9]|1[0-2])[^\w\d\r\n:](0?[1-9]|[12]\d|30|31)[^\w\d\r\n:](\d{4}|\d{2})\b)

BUT you won't be able to tell if dates like 6/9/1973 are the 6th of September or the 9th of June. I'm struggling to think of a scenario where that is not going to cause a problem somewhere down the line, it's bad practice and you shouldn't have to deal with it like that - find the data owner and hit them with the governance hammer.

Finally, if you want to match a YYYYMMDD string with no delimiters you can take some of the uncertainty out and the expression looks like this

\b(\d{4})(0[1-9]|1[0-2])(0[1-9]|[12]\d|30|31)\b

But note again, it will match on well-formed but invalid values like 20010231 (31th Feb!) :)

Test data

In experimenting with the solutions in this thread I ended up with a test data set that includes a variety of valid and non-valid dates and some tricky situations where you may or may not want to match i.e. Times that could match as dates and dates on multiple lines.

I hope this is useful to someone.

Valid Dates in various formats

Day, month, year
2/11/73
02/11/1973
2/1/73
02/01/73
31/1/1973
02/1/1973
31.1.2011
31-1-2001
29/2/1973
29/02/1976 
03/06/2010
12/6/90

month, day, year
02/24/1975 
06/19/66 
03.31.1991
2.29.2003
02-29-55
03-13-55
03-13-1955
12\24\1974
12\30\1974
1\31\1974
03/31/2001
01/21/2001
12/13/2001

Match both DMY and MDY
12/12/1978
6/6/78
06/6/1978
6/06/1978

using whitespace as a delimiter

13 11 2001
11 13 2001
11 13 01 
13 11 01
1 1 01
1 1 2001

Year Month Day order
76/02/02
1976/02/29
1976/2/13
76/09/31

YYYYMMDD sortable format
19741213
19750101

Valid dates before Epoch
12/1/10
12/01/660
12/01/00
12/01/0000

Valid date after 2038

01/01/2039
01/01/39

Valid date beyond the year 9999

01/01/10000

Dates with leading or trailing characters

12/31/21/
31/12/1921AD
31/12/1921.10:55
12/10/2016  8:26:00.39
wfuwdf12/11/74iuhwf
fwefew13/11/1974
01/12/1974vdwdfwe
01/01/99werwer
12321301/01/99

Times that look like dates

12:13:56
13:12:01
1:12:01PM
1:12:01 AM

Dates that runs across two lines

1/12/19
74

01/12/19
74/13/1946

31/12/20
08:13

Invalid, corrupted or nonsense dates

0/1/2001
1/0/2001
00/01/2100
01/0/2001
0101/2001
01/131/2001
31/31/2001
101/12/1974
56/56/56
00/00/0000
0/0/1999
12/01/0
12/10/-100
74/2/29
12/32/45
20/12/194

2/12-73

What does the explicit keyword mean?

Cpp Reference is always helpful!!! Details about explicit specifier can be found here. You may need to look at implicit conversions and copy-initialization too.

Quick look

The explicit specifier specifies that a constructor or conversion function (since C++11) doesn't allow implicit conversions or copy-initialization.

Example as follows:

struct A
{
    A(int) { }      // converting constructor
    A(int, int) { } // converting constructor (C++11)
    operator bool() const { return true; }
};

struct B
{
    explicit B(int) { }
    explicit B(int, int) { }
    explicit operator bool() const { return true; }
};

int main()
{
    A a1 = 1;      // OK: copy-initialization selects A::A(int)
    A a2(2);       // OK: direct-initialization selects A::A(int)
    A a3 {4, 5};   // OK: direct-list-initialization selects A::A(int, int)
    A a4 = {4, 5}; // OK: copy-list-initialization selects A::A(int, int)
    A a5 = (A)1;   // OK: explicit cast performs static_cast
    if (a1) cout << "true" << endl; // OK: A::operator bool()
    bool na1 = a1; // OK: copy-initialization selects A::operator bool()
    bool na2 = static_cast<bool>(a1); // OK: static_cast performs direct-initialization

//  B b1 = 1;      // error: copy-initialization does not consider B::B(int)
    B b2(2);       // OK: direct-initialization selects B::B(int)
    B b3 {4, 5};   // OK: direct-list-initialization selects B::B(int, int)
//  B b4 = {4, 5}; // error: copy-list-initialization does not consider B::B(int,int)
    B b5 = (B)1;   // OK: explicit cast performs static_cast
    if (b5) cout << "true" << endl; // OK: B::operator bool()
//  bool nb1 = b2; // error: copy-initialization does not consider B::operator bool()
    bool nb2 = static_cast<bool>(b2); // OK: static_cast performs direct-initialization
}

Converting file size in bytes to human-readable string

For those who use Angular, there's a package called angular-pipes that has a pipe for this:

File

import { BytesPipe } from 'angular-pipes';

Usage

{{ 150 | bytes }} <!-- 150 B -->
{{ 1024 | bytes }} <!-- 1 KB -->
{{ 1048576 | bytes }} <!-- 1 MB -->
{{ 1024 | bytes: 0 : 'KB' }} <!-- 1 MB -->
{{ 1073741824 | bytes }} <!-- 1 GB -->
{{ 1099511627776 | bytes }} <!-- 1 TB -->
{{ 1073741824 | bytes : 0 : 'B' : 'MB' }} <!-- 1024 MB -->

Link to the docs.

Modifying local variable from inside lambda

Use a wrapper

Any kind of wrapper is good.

With Java 8+, use either an AtomicInteger:

AtomicInteger ordinal = new AtomicInteger(0);
list.forEach(s -> {
  s.setOrdinal(ordinal.getAndIncrement());
});

... or an array:

int[] ordinal = { 0 };
list.forEach(s -> {
  s.setOrdinal(ordinal[0]++);
});

With Java 10+:

var wrapper = new Object(){ int ordinal = 0; };
list.forEach(s -> {
  s.setOrdinal(wrapper.ordinal++);
});

Note: be very careful if you use a parallel stream. You might not end up with the expected result. Other solutions like Stuart's might be more adapted for those cases.

For types other than int

Of course, this is still valid for types other than int. You only need to change the wrapping type to an AtomicReference or an array of that type. For instance, if you use a String, just do the following:

AtomicReference<String> value = new AtomicReference<>();
list.forEach(s -> {
  value.set("blah");
});

Use an array:

String[] value = { null };
list.forEach(s-> {
  value[0] = "blah";
});

Or with Java 10+:

var wrapper = new Object(){ String value; };
list.forEach(s->{
  wrapper.value = "blah";
});

remove None value from a list without removing the 0 value

If it is all a list of lists, you could modify sir @Raymond's answer

L = [ [None], [123], [None], [151] ] no_none_val = list(filter(None.__ne__, [x[0] for x in L] ) ) for python 2 however

no_none_val = [x[0] for x in L if x[0] is not None] """ Both returns [123, 151]"""

<< list_indice[0] for variable in List if variable is not None >>

How to launch an Activity from another Application in Android

I know this has been answered but here is how I implemented something similar:

Intent intent = getPackageManager().getLaunchIntentForPackage("com.package.name");
if (intent != null) {
    // We found the activity now start the activity
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);
} else {
    // Bring user to the market or let them choose an app?
    intent = new Intent(Intent.ACTION_VIEW);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.setData(Uri.parse("market://details?id=" + "com.package.name"));
    startActivity(intent);
}

Even better, here is the method:

public void startNewActivity(Context context, String packageName) {
    Intent intent = context.getPackageManager().getLaunchIntentForPackage(packageName);
    if (intent != null) {
        // We found the activity now start the activity
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    } else {
        // Bring user to the market or let them choose an app?
        intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setData(Uri.parse("market://details?id=" + packageName));
        context.startActivity(intent);
    }
}

Removed duplicate code:

public void startNewActivity(Context context, String packageName) {
    Intent intent = context.getPackageManager().getLaunchIntentForPackage(packageName);
    if (intent == null) {
        // Bring user to the market or let them choose an app?
        intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse("market://details?id=" + packageName));
    }
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(intent);
}

Open URL in new window with JavaScript

Use window.open():

<a onclick="window.open(document.URL, '_blank', 'location=yes,height=570,width=520,scrollbars=yes,status=yes');">
  Share Page
</a>

This will create a link titled Share Page which opens the current url in a new window with a height of 570 and width of 520.

PHP 7 simpleXML

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

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

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

Thanks @Alexandre Barbosa for pointing this out!

EDIT 20160423:

One-liner to fix this issue:

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

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

difference between throw and throw new Exception()

The first preserves the original stacktrace:

try { ... }
catch
{
    // Do something.
    throw;
}

The second allows you to change the type of the exception and/or the message and other data:

try { ... } catch (Exception e)
{
    throw new BarException("Something broke!");
}

There's also a third way where you pass an inner exception:

try { ... }
catch (FooException e) {
    throw new BarException("foo", e);
} 

I'd recommend using:

  • the first if you want to do some cleanup in error situation without destroying information or adding information about the error.
  • the third if you want to add more information about the error.
  • the second if you want to hide information (from untrusted users).

How do I fill arrays in Java?

Check out the Arrays.fill methods.

int[] array = new int[4];
Arrays.fill(array, 0);

How to make program go back to the top of the code instead of closing

Use an infinite loop:

while True:
    print('Hello world!')

This certainly can apply to your start() function as well; you can exit the loop with either break, or use return to exit the function altogether, which also terminates the loop:

def start():
    print ("Welcome to the converter toolkit made by Alan.")

    while True:
        op = input ("Please input what operation you wish to perform. 1 for Fahrenheit to Celsius, 2 for meters to centimetres and 3 for megabytes to gigabytes")

        if op == "1":
            f1 = input ("Please enter your fahrenheit temperature: ")
            f1 = int(f1)

            a1 = (f1 - 32) / 1.8
            a1 = str(a1)

            print (a1+" celsius") 

        elif op == "2":
            m1 = input ("Please input your the amount of meters you wish to convert: ")
            m1 = int(m1)
            m2 = (m1 * 100)

            m2 = str(m2)
            print (m2+" m")

        if op == "3":
            mb1 = input ("Please input the amount of megabytes you want to convert")
            mb1 = int(mb1)
            mb2 = (mb1 / 1024)
            mb3 = (mb2 / 1024)

            mb3 = str(mb3)

            print (mb3+" GB")

        else:
            print ("Sorry, that was an invalid command!")

If you were to add an option to quit as well, that could be:

if op.lower() in {'q', 'quit', 'e', 'exit'}:
    print("Goodbye!")
    return

for example.

How to determine programmatically the current active profile using Spring boot

It doesn't matter is your app Boot or just raw Spring. There is just enough to inject org.springframework.core.env.Environment to your bean.

@Autowired
private Environment environment;
....

this.environment.getActiveProfiles();

Method with a bool return

Long version:

private bool booleanMethod () {
    if (your_condition) {
        return true;
    } else {
        return false;
    }
}

But since you are using the outcome of your condition as the result of the method you can shorten it to

private bool booleanMethod () {
    return your_condition;
}

Convert number to varchar in SQL with formatting

Here's an alternative following the last answer

declare @t tinyint,@v tinyint
set @t=23
set @v=232
Select replace(str(@t,4),' ','0'),replace(str(@t,5),' ','0')

This will work on any number and by varying the length of the str() function you can stipulate how many leading zeros you require. Provided of course that your string length is always >= maximum number of digits your number type can hold.

Get CPU Usage from Windows Command Prompt

typeperf gives me issues when it randomly doesn't work on some computers (Error: No valid counters.) or if the account has insufficient rights. Otherwise, here is a way to extract just the value from its output. It still needs rounding though:

@for /f "delims=, tokens=2" %p in ('typeperf "\Processor(_Total)\% Processor Time" -sc 3 ^| find ":"') do @echo %~p%

Powershell has two cmdlets to get the percent utilization for all CPUs: Get-Counter (preferred) or Get-WmiObject:

Powershell "Get-Counter '\Processor(*)\% Processor Time' | Select -Expand Countersamples | Select InstanceName, CookedValue"

Or,

Powershell "Get-WmiObject Win32_PerfFormattedData_PerfOS_Processor | Select Name, PercentProcessorTime"


To get the overall CPU load with formatted output exactly like the question:

Powershell "[string][int](Get-Counter '\Processor(*)\% Processor Time').Countersamples[0].CookedValue + '%'"

Or,

 Powershell "gwmi Win32_PerfFormattedData_PerfOS_Processor | Select -First 1 | %{'{0}%' -f $_.PercentProcessorTime}"

How do I remove a key from a JavaScript object?

If you are using Underscore.js or Lodash, there is a function 'omit' that will do it.
http://underscorejs.org/#omit

var thisIsObject= {
    'Cow' : 'Moo',
    'Cat' : 'Meow',
    'Dog' : 'Bark'
};
_.omit(thisIsObject,'Cow'); //It will return a new object

=> {'Cat' : 'Meow', 'Dog' : 'Bark'}  //result

If you want to modify the current object, assign the returning object to the current object.

thisIsObject = _.omit(thisIsObject,'Cow');

With pure JavaScript, use:

delete thisIsObject['Cow'];

Another option with pure JavaScript.

thisIsObject.cow = undefined;

thisIsObject = JSON.parse(JSON.stringify(thisIsObject ));

how to get the child node in div using javascript

If you give your table a unique id, its easier:

<div id="ctl00_ContentPlaceHolder1_Jobs_dlItems_ctl01_a"
    onmouseup="checkMultipleSelection(this,event);">
       <table id="ctl00_ContentPlaceHolder1_Jobs_dlItems_ctl01_a_table" 
              cellpadding="0" cellspacing="0" border="0" width="100%">
           <tr>
              <td style="width:50px; text-align:left;">09:15 AM</td>
              <td style="width:50px; text-align:left;">Item001</td>
              <td style="width:50px; text-align:left;">10</td>
              <td style="width:50px; text-align:left;">Address1</td>
              <td style="width:50px; text-align:left;">46545465</td>
              <td style="width:50px; text-align:left;">ref1</td>
           </tr>
       </table>
</div>


var multiselect = 
    document.getElementById(
               'ctl00_ContentPlaceHolder1_Jobs_dlItems_ctl01_a_table'
            ).rows[0].cells,
    timeXaddr = [multiselect[0].innerHTML, multiselect[2].innerHTML];

//=> timeXaddr now an array containing ['09:15 AM', 'Address1'];

Could not install packages due to an EnvironmentError: [Errno 13]

This worked for me:

 python3 -m venv env
 source ./env/bin/activate
 python -m pip install package

(From Github: https://github.com/googlesamples/assistant-sdk-python/issues/236 )

How can I check if a jQuery plugin is loaded?

This sort of approach should work.

var plugin_exists = true;

try {
  // some code that requires that plugin here
} catch(err) {
  plugin_exists = false;
}

Error : getaddrinfo ENOTFOUND registry.npmjs.org registry.npmjs.org:443

I spent over 5 hours trying to get rid of this message under Windows 8.1. So I would like to share my case and save someones time. I was not behind the proxy... but setting proxy helped to resolve the problem. So I go deep and found that issue was caused by Comodo Firewall... which blocked cmd since I was installing packages too fast (turning off and even closing Firewall did not help, which caused me so long to find the issue... seems like there was some other process of Firewall running in background). You may have same issue with any other firewall/antivirus installed so make sure that cmd is not blocked by them. Good luck!

Does MySQL ignore null values on unique constraints?

A simple answer would be : No, it doesn't

Explanation : According to the definition of unique constraints (SQL-92)

A unique constraint is satisfied if and only if no two rows in a table have the same non-null values in the unique columns

This statement can have two interpretations as :

  • No two rows can have same values i.e. NULL and NULL is not allowed
  • No two non-null rows can have values i.e NULL and NULL is fine, but StackOverflow and StackOverflow is not allowed

Since MySQL follows second interpretation, multiple NULL values are allowed in UNIQUE constraint column. Second, if you would try to understand the concept of NULL in SQL, you will find that two NULL values can be compared at all since NULL in SQL refers to unavailable or unassigned value (you can't compare nothing with nothing). Now, if you are not allowing multiple NULL values in UNIQUE constraint column, you are contracting the meaning of NULL in SQL. I would summarise my answer by saying :

MySQL supports UNIQUE constraint but not on the cost of ignoring NULL values

Converting timestamp to time ago in PHP e.g 1 day ago, 2 days ago...

The following is a very simple and extremely efficient solution.

function timeElapsed($originalTime){

        $timeElapsed=time()-$originalTime;

        /*
          You can change the values of the following 2 variables 
          based on your opinion. For 100% accuracy, you can call
          php's cal_days_in_month() and do some additional coding
          using the values you get for each month. After all the
          coding, your final answer will be approximately equal to
          mine. That is why it is okay to simply use the average
          values below.
        */
        $averageNumbDaysPerMonth=(365.242/12);
        $averageNumbWeeksPerMonth=($averageNumbDaysPerMonth/7);

        $time1=(((($timeElapsed/60)/60)/24)/365.242);
        $time2=floor($time1);//Years
        $time3=($time1-$time2)*(365.242);
        $time4=($time3/$averageNumbDaysPerMonth);
        $time5=floor($time4);//Months
        $time6=($time4-$time5)*$averageNumbWeeksPerMonth;
        $time7=floor($time6);//Weeks
        $time8=($time6-$time7)*7;
        $time9=floor($time8);//Days
        $time10=($time8-$time9)*24;
        $time11=floor($time10);//Hours
        $time12=($time10-$time11)*60;
        $time13=floor($time12);//Minutes
        $time14=($time12-$time13)*60;
        $time15=round($time14);//Seconds

        $timeElapsed=$time2 . 'yrs ' . $time5 . 'months ' . $time7 . 
                     'weeks ' . $time9 .  'days ' . $time11 . 'hrs '
                     . $time13 . 'mins and ' . $time15 . 'secs.';

        return $timeElapsed;

}

echo timeElapsed(1201570814);

Sample output:

6yrs 4months 3weeks 4days 12hrs 40mins and 36secs.

Bootstrap 3: Text overlay on image

try the following example. Image overlay with text on image. demo

<div class="thumbnail">
  <img src="https://s3.amazonaws.com/discount_now_staging/uploads/ed964a11-e089-4c61-b927-9623a3fe9dcb/direct_uploader_2F50cc1daf-465f-48f0-8417-b04ac68a999d_2FN_19_jewelry.jpg" alt="..."   />
  <div class="caption post-content">  
  </div> 
  <div class="details">
    <h3>Robots!</h3>
    <p>Lorem ipsum dolor sit amet</p>   
  </div>  
</div>

css

.post-content {
    background: rgba(0, 0, 0, 0.7) none repeat scroll 0 0;
    opacity: 0.5;
    top:0;
    left:0;
    min-width: 500px;
    min-height: 500px; 
    position: absolute;
    color: #ffffff; 
}

.thumbnail{
    position:relative;

}
.details {
    position: absolute; 
    z-index: 2; 
    top: 0;
    color: #ffffff; 
}

Decimal values in SQL for dividing results

There may be other ways to get your desired result.

Declare @a int
Declare @b int
SET @a = 3
SET @b=2
SELECT cast((cast(@a as float)/ cast(@b as float)) as float)

Show/hide widgets in Flutter programmatically

For beginner try this too.

class Visibility extends StatefulWidget {
  @override
  _VisibilityState createState() => _VisibilityState();
}

class _VisibilityState extends State<Visibility> {
  bool a = true;
  String mText = "Press to hide";

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: "Visibility",
      home: new Scaffold(
          body: new Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              new RaisedButton(
                onPressed: _visibilitymethod, child: new Text(mText),),
                a == true ? new Container(
                width: 300.0,
                height: 300.0,
                color: Colors.red,
              ) : new Container(),
            ],
          )
      ),
    );
  }

  void _visibilitymethod() {
    setState(() {
      if (a) {
        a = false;
        mText = "Press to show";
      } else {
        a = true;
        mText = "Press to hide";
      }
    });
  }
}

java.lang.OutOfMemoryError: Java heap space in Maven

When I run maven test, java.lang.OutOfMemoryError happens. I google it for solutions and have tried to export MAVEN_OPTS=-Xmx1024m, but it did not work.

Setting the Xmx options using MAVEN_OPTS does work, it does configure the JVM used to start Maven. That being said, the maven-surefire-plugin forks a new JVM by default, and your MAVEN_OPTS are thus not passed.

To configure the sizing of the JVM used by the maven-surefire-plugin, you would either have to:

  • change the forkMode to never (which is be a not so good idea because Maven won't be isolated from the test) ~or~
  • use the argLine parameter (the right way):

In the later case, something like this:

<configuration>
  <argLine>-Xmx1024m</argLine>
</configuration>

But I have to say that I tend to agree with Stephen here, there is very likely something wrong with one of your test and I'm not sure that giving more memory is the right solution to "solve" (hide?) your problem.

References

Using Spring MVC Test to unit test multipart POST request

The method MockMvcRequestBuilders.fileUpload is deprecated use MockMvcRequestBuilders.multipart instead.

This is an example:

import static org.hamcrest.CoreMatchers.containsString;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.multipart.MultipartFile;


/**
 * Unit test New Controller.
 *
 */
@RunWith(SpringRunner.class)
@WebMvcTest(NewController.class)
public class NewControllerTest {

    private MockMvc mockMvc;

    @Autowired
    WebApplicationContext wContext;

    @MockBean
    private NewController newController;

    @Before
    public void setup() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(wContext)
                   .alwaysDo(MockMvcResultHandlers.print())
                   .build();
    }

   @Test
    public void test() throws Exception {
       // Mock Request
        MockMultipartFile jsonFile = new MockMultipartFile("test.json", "", "application/json", "{\"key1\": \"value1\"}".getBytes());

        // Mock Response
        NewControllerResponseDto response = new NewControllerDto();
        Mockito.when(newController.postV1(Mockito.any(Integer.class), Mockito.any(MultipartFile.class))).thenReturn(response);

        mockMvc.perform(MockMvcRequestBuilders.multipart("/fileUpload")
                .file("file", jsonFile.getBytes())
                .characterEncoding("UTF-8"))
        .andExpect(status().isOk());

    }

}

Multi-select dropdown list in ASP.NET

Try this server control which inherits directly from CheckBoxList (free, open source): http://dropdowncheckboxes.codeplex.com/

List<T> or IList<T>

public void Foo(IList<Bar> list)
{
     // Do Something with the list here.
}

In this case you could pass in any class which implements the IList<Bar> interface. If you used List<Bar> instead, only a List<Bar> instance could be passed in.

The IList<Bar> way is more loosely coupled than the List<Bar> way.

iOS Launching Settings -> Restrictions URL Scheme

If you add the prefs URL scheme to your iOS app, it will allow you to use all those schemes that we could in iOS 5. I've tested it on iOS 9, but I think it will work on older versions too.

How can I pass a username/password in the header to a SOAP WCF Service

Suppose you are calling a web service using HttpWebRequest and HttpWebResponse, because .Net client doest support the structure of the WSLD that your are trying to consume.

In that case you can add the security credentials on the headers like:

<soap:Envelpe>
<soap:Header>
    <wsse:Security soap:mustUnderstand='true' xmlns:wsse='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd' xmlns:wsu='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd'><wsse:UsernameToken wsu:Id='UsernameToken-3DAJDJSKJDHFJASDKJFKJ234JL2K3H2K3J42'><wsse:Username>YOU_USERNAME/wsse:Username><wsse:Password Type='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText'>YOU_PASSWORD</wsse:Password><wsse:Nonce EncodingType='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary'>3WSOKcKKm0jdi3943ts1AQ==</wsse:Nonce><wsu:Created>2015-01-12T16:46:58.386Z</wsu:Created></wsse:UsernameToken></wsse:Security>
</soapHeather>
<soap:Body>
</soap:Body>


</soap:Envelope>

You can use SOAPUI to get the wsse Security, using the http log.

Be careful because it is not a safe scenario.

Use SELECT inside an UPDATE query

I know this topic is old, but I thought I could add something to it.

I could not make an Update with Select query work using SQL in MS Access 2010. I used Tomalak's suggestion to make this work. I had a screenshot, but am apparently too much of a newb on this site to be able to post it.

I was able to do this using the Query Design tool, but even as I was looking at a confirmed successful update query, Access was not able to show me the SQL that made it happen. So I could not make this work with SQL code alone.

I created and saved my select query as a separate query. In the Query Design tool, I added the table I'm trying to update the the select query I had saved (I put the unique key in the select query so it had a link between them). Just as Tomalak had suggested, I changed the Query Type to Update. I then just had to choose the fields (and designate the table) I was trying to update. In the "Update To" fields, I typed in the name of the fields from the select query I had brought in.

This format was successful and updated the original table.

Extract elements of list at odd positions

list_ = list(range(9)) print(list_[1::2])

How to copy multiple files in one layer using a Dockerfile?

It might be worth mentioning that you can also create a .dockerignore file, to exclude the files that you don't want to copy:

https://docs.docker.com/engine/reference/builder/#dockerignore-file

Before the docker CLI sends the context to the docker daemon, it looks for a file named .dockerignore in the root directory of the context. If this file exists, the CLI modifies the context to exclude files and directories that match patterns in it. This helps to avoid unnecessarily sending large or sensitive files and directories to the daemon and potentially adding them to images using ADD or COPY.

MongoDB running but can't connect using shell

I had a similar problem, well actually the same (mongo process is running but can't connect to it). What I did was went to my database path and removed mongod.lock, and then gave it another try (restarted mongo). After that it worked.

Hope it works for you too. mongodb repair on ubuntu

Notepad++ - How can I replace blank lines

By the way, in Notepad++ there's built-in plugin that can handle this: TextFX -> TextFX Edit -> Delete Blank Lines (first press CTRL+A to select all).

What is TypeScript and why would I use it in place of JavaScript?

TypeScript's relation to JavaScript

TypeScript is a typed superset of JavaScript that compiles to plain JavaScript - typescriptlang.org.

JavaScript is a programming language that is developed by EMCA's Technical Committee 39, which is a group of people composed of many different stakeholders. TC39 is a committee hosted by ECMA: an internal standards organization. JavaScript has many different implementations by many different vendors (e.g. Google, Microsoft, Oracle, etc.). The goal of JavaScript is to be the lingua franca of the web.

TypeScript is a superset of the JavaScript language that has a single open-source compiler and is developed mainly by a single vendor: Microsoft. The goal of TypeScript is to help catch mistakes early through a type system and to make JavaScript development more efficient.

Essentially TypeScript achieves its goals in three ways:

  1. Support for modern JavaScript features - The JavaScript language (not the runtime) is standardized through the ECMAScript standards. Not all browsers and JavaScript runtimes support all features of all ECMAScript standards (see this overview). TypeScript allows for the use of many of the latest ECMAScript features and translates them to older ECMAScript targets of your choosing (see the list of compile targets under the --target compiler option). This means that you can safely use new features, like modules, lambda functions, classes, the spread operator and destructuring, while remaining backwards compatible with older browsers and JavaScript runtimes.

  2. Advanced type system - The type support is not part of the ECMAScript standard and will likely never be due to the interpreted nature instead of compiled nature of JavaScript. The type system of TypeScript is incredibly rich and includes: interfaces, enums, hybrid types, generics, union/intersection types, access modifiers and much more. The official website of TypeScript gives an overview of these features. Typescript's type system is on-par with most other typed languages and in some cases arguably more powerful.

  3. Developer tooling support - TypeScript's compiler can run as a background process to support both incremental compilation and IDE integration such that you can more easily navigate, identify problems, inspect possibilities and refactor your codebase.

TypeScript's relation to other JavaScript targeting languages

TypeScript has a unique philosophy compared to other languages that compile to JavaScript. JavaScript code is valid TypeScript code; TypeScript is a superset of JavaScript. You can almost rename your .js files to .ts files and start using TypeScript (see "JavaScript interoperability" below). TypeScript files are compiled to readable JavaScript, so that migration back is possible and understanding the compiled TypeScript is not hard at all. TypeScript builds on the successes of JavaScript while improving on its weaknesses.

On the one hand, you have future proof tools that take modern ECMAScript standards and compile it down to older JavaScript versions with Babel being the most popular one. On the other hand, you have languages that may totally differ from JavaScript which target JavaScript, like CoffeeScript, Clojure, Dart, Elm, Haxe, Scala.js, and a whole host more (see this list). These languages, though they might be better than where JavaScript's future might ever lead, run a greater risk of not finding enough adoption for their futures to be guaranteed. You might also have more trouble finding experienced developers for some of these languages, though the ones you will find can often be more enthusiastic. Interop with JavaScript can also be a bit more involved, since they are farther removed from what JavaScript actually is.

TypeScript sits in between these two extremes, thus balancing the risk. TypeScript is not a risky choice by any standard. It takes very little effort to get used to if you are familiar with JavaScript, since it is not a completely different language, has excellent JavaScript interoperability support and it has seen a lot of adoption recently.

Optionally static typing and type inference

JavaScript is dynamically typed. This means JavaScript does not know what type a variable is until it is actually instantiated at run-time. This also means that it may be too late. TypeScript adds type support to JavaScript and catches type errors during compilation to JavaScript. Bugs that are caused by false assumptions of some variable being of a certain type can be completely eradicated if you play your cards right (how strict you type your code or if you type your code at all is up to you).

TypeScript makes typing a bit easier and a lot less explicit by the usage of type inference. For example: var x = "hello" in TypeScript is the same as var x : string = "hello". The type is simply inferred from its use. Even it you don't explicitly type the types, they are still there to save you from doing something which otherwise would result in a run-time error.

TypeScript is optionally typed by default. For example function divideByTwo(x) { return x / 2 } is a valid function in TypeScript which can be called with any kind of parameter, even though calling it with a string will obviously result in a runtime error. Just like you are used to in JavaScript. This works, because when no type was explicitly assigned and the type could not be inferred, like in the divideByTwo example, TypeScript will implicitly assign the type any. This means the divideByTwo function's type signature automatically becomes function divideByTwo(x : any) : any. There is a compiler flag to disallow this behavior: --noImplicitAny. Enabling this flag gives you a greater degree of safety, but also means you will have to do more typing.

Types have a cost associated with them. First of all, there is a learning curve, and second of all, of course, it will cost you a bit more time to set up a codebase using proper strict typing too. In my experience, these costs are totally worth it on any serious codebase you are sharing with others. A Large Scale Study of Programming Languages and Code Quality in Github suggests that "statically typed languages, in general, are less defect prone than the dynamic types, and that strong typing is better than weak typing in the same regard".

It is interesting to note that this very same paper finds that TypeScript is less error-prone than JavaScript:

For those with positive coefficients we can expect that the language is associated with, ceteris paribus, a greater number of defect fixes. These languages include C, C++, JavaScript, Objective-C, Php, and Python. The languages Clojure, Haskell, Ruby, Scala, and TypeScript, all have negative coefficients implying that these languages are less likely than the average to result in defect fixing commits.

Enhanced IDE support

The development experience with TypeScript is a great improvement over JavaScript. The IDE is informed in real-time by the TypeScript compiler on its rich type information. This gives a couple of major advantages. For example, with TypeScript, you can safely do refactorings like renames across your entire codebase. Through code completion, you can get inline help on whatever functions a library might offer. No more need to remember them or look them up in online references. Compilation errors are reported directly in the IDE with a red squiggly line while you are busy coding. All in all, this allows for a significant gain in productivity compared to working with JavaScript. One can spend more time coding and less time debugging.

There is a wide range of IDEs that have excellent support for TypeScript, like Visual Studio Code, WebStorm, Atom and Sublime.

Strict null checks

Runtime errors of the form cannot read property 'x' of undefined or undefined is not a function are very commonly caused by bugs in JavaScript code. Out of the box TypeScript already reduces the probability of these kinds of errors occurring, since one cannot use a variable that is not known to the TypeScript compiler (with the exception of properties of any typed variables). It is still possible though to mistakenly utilize a variable that is set to undefined. However, with the 2.0 version of TypeScript you can eliminate these kinds of errors all together through the usage of non-nullable types. This works as follows:

With strict null checks enabled (--strictNullChecks compiler flag) the TypeScript compiler will not allow undefined to be assigned to a variable unless you explicitly declare it to be of nullable type. For example, let x : number = undefined will result in a compile error. This fits perfectly with type theory since undefined is not a number. One can define x to be a sum type of number and undefined to correct this: let x : number | undefined = undefined.

Once a type is known to be nullable, meaning it is of a type that can also be of the value null or undefined, the TypeScript compiler can determine through control flow based type analysis whether or not your code can safely use a variable or not. In other words when you check a variable is undefined through for example an if statement the TypeScript compiler will infer that the type in that branch of your code's control flow is not anymore nullable and therefore can safely be used. Here is a simple example:

let x: number | undefined;
if (x !== undefined) x += 1; // this line will compile, because x is checked.
x += 1; // this line will fail compilation, because x might be undefined.

During the build, 2016 conference co-designer of TypeScript Anders Hejlsberg gave a detailed explanation and demonstration of this feature: video (from 44:30 to 56:30).

Compilation

To use TypeScript you need a build process to compile to JavaScript code. The build process generally takes only a couple of seconds depending of course on the size of your project. The TypeScript compiler supports incremental compilation (--watch compiler flag) so that all subsequent changes can be compiled at greater speed.

The TypeScript compiler can inline source map information in the generated .js files or create separate .map files. Source map information can be used by debugging utilities like the Chrome DevTools and other IDE's to relate the lines in the JavaScript to the ones that generated them in the TypeScript. This makes it possible for you to set breakpoints and inspect variables during runtime directly on your TypeScript code. Source map information works pretty well, it was around long before TypeScript, but debugging TypeScript is generally not as great as when using JavaScript directly. Take the this keyword for example. Due to the changed semantics of the this keyword around closures since ES2015, this may actually exists during runtime as a variable called _this (see this answer). This may confuse you during debugging but generally is not a problem if you know about it or inspect the JavaScript code. It should be noted that Babel suffers the exact same kind of issue.

There are a few other tricks the TypeScript compiler can do, like generating intercepting code based on decorators, generating module loading code for different module systems and parsing JSX. However, you will likely require a build tool besides the Typescript compiler. For example, if you want to compress your code you will have to add other tools to your build process to do so.

There are TypeScript compilation plugins available for Webpack, Gulp, Grunt and pretty much any other JavaScript build tool out there. The TypeScript documentation has a section on integrating with build tools covering them all. A linter is also available in case you would like even more build time checking. There are also a great number of seed projects out there that will get you started with TypeScript in combination with a bunch of other technologies like Angular 2, React, Ember, SystemJS, Webpack, Gulp, etc.

JavaScript interoperability

Since TypeScript is so closely related to JavaScript it has great interoperability capabilities, but some extra work is required to work with JavaScript libraries in TypeScript. TypeScript definitions are needed so that the TypeScript compiler understands that function calls like _.groupBy or angular.copy or $.fadeOut are not in fact illegal statements. The definitions for these functions are placed in .d.ts files.

The simplest form a definition can take is to allow an identifier to be used in any way. For example, when using Lodash, a single line definition file declare var _ : any will allow you to call any function you want on _, but then, of course, you are also still able to make mistakes: _.foobar() would be a legal TypeScript call, but is, of course, an illegal call at run-time. If you want proper type support and code completion your definition file needs to to be more exact (see lodash definitions for an example).

Npm modules that come pre-packaged with their own type definitions are automatically understood by the TypeScript compiler (see documentation). For pretty much any other semi-popular JavaScript library that does not include its own definitions somebody out there has already made type definitions available through another npm module. These modules are prefixed with "@types/" and come from a Github repository called DefinitelyTyped.

There is one caveat: the type definitions must match the version of the library you are using at run-time. If they do not, TypeScript might disallow you from calling a function or dereferencing a variable that exists or allow you to call a function or dereference a variable that does not exist, simply because the types do not match the run-time at compile-time. So make sure you load the right version of the type definitions for the right version of the library you are using.

To be honest, there is a slight hassle to this and it may be one of the reasons you do not choose TypeScript, but instead go for something like Babel that does not suffer from having to get type definitions at all. On the other hand, if you know what you are doing you can easily overcome any kind of issues caused by incorrect or missing definition files.

Converting from JavaScript to TypeScript

Any .js file can be renamed to a .ts file and ran through the TypeScript compiler to get syntactically the same JavaScript code as an output (if it was syntactically correct in the first place). Even when the TypeScript compiler gets compilation errors it will still produce a .js file. It can even accept .js files as input with the --allowJs flag. This allows you to start with TypeScript right away. Unfortunately, compilation errors are likely to occur in the beginning. One does need to remember that these are not show-stopping errors like you may be used to with other compilers.

The compilation errors one gets in the beginning when converting a JavaScript project to a TypeScript project are unavoidable by TypeScript's nature. TypeScript checks all code for validity and thus it needs to know about all functions and variables that are used. Thus type definitions need to be in place for all of them otherwise compilation errors are bound to occur. As mentioned in the chapter above, for pretty much any JavaScript framework there are .d.ts files that can easily be acquired with the installation of DefinitelyTyped packages. It might, however, be that you've used some obscure library for which no TypeScript definitions are available or that you've polyfilled some JavaScript primitives. In that case, you must supply type definitions for these bits for the compilation errors to disappear. Just create a .d.ts file and include it in the tsconfig.json's files array, so that it is always considered by the TypeScript compiler. In it declare those bits that TypeScript does not know about as type any. Once you've eliminated all errors you can gradually introduce typing to those parts according to your needs.

Some work on (re)configuring your build pipeline will also be needed to get TypeScript into the build pipeline. As mentioned in the chapter on compilation there are plenty of good resources out there and I encourage you to look for seed projects that use the combination of tools you want to be working with.

The biggest hurdle is the learning curve. I encourage you to play around with a small project at first. Look how it works, how it builds, which files it uses, how it is configured, how it functions in your IDE, how it is structured, which tools it uses, etc. Converting a large JavaScript codebase to TypeScript is doable when you know what you are doing. Read this blog for example on converting 600k lines to typescript in 72 hours). Just make sure you have a good grasp of the language before you make the jump.

Adoption

TypeScript is open-source (Apache 2 licensed, see GitHub) and backed by Microsoft. Anders Hejlsberg, the lead architect of C# is spearheading the project. It's a very active project; the TypeScript team has been releasing a lot of new features in the last few years and a lot of great ones are still planned to come (see the roadmap).

Some facts about adoption and popularity:

  • In the 2017 StackOverflow developer survey TypeScript was the most popular JavaScript transpiler (9th place overall) and won third place in the most loved programming language category.
  • In the 2018 state of js survey TypeScript was declared as one of the two big winners in the JavaScript flavors category (with ES6 being the other).
  • In the 2019 StackOverlow deverloper survey TypeScript rose to the 9th place of most popular languages amongst professional developers, overtaking both C and C++. It again took third place amongst most the most loved languages.

Setting dropdownlist selecteditem programmatically

If you need to select your list item based on an expression:

foreach (ListItem listItem in list.Items)
{
    listItem.Selected = listItem.Value.Contains("some value");
}

Difference between Mutable objects and Immutable objects

Immutable objects are simply objects whose state (the object's data) cannot change after construction. Examples of immutable objects from the JDK include String and Integer.

For example:(Point is mutable and string immutable)

     Point myPoint = new Point( 0, 0 );
    System.out.println( myPoint );
    myPoint.setLocation( 1.0, 0.0 );
    System.out.println( myPoint );

    String myString = new String( "old String" );
    System.out.println( myString );
    myString.replaceAll( "old", "new" );
    System.out.println( myString );

The output is:

java.awt.Point[0.0, 0.0]
java.awt.Point[1.0, 0.0]
old String
old String

Jenkins: Can comments be added to a Jenkinsfile?

The Jenkinsfile is written in groovy which uses the Java (and C) form of comments:

/* this
   is a
   multi-line comment */

// this is a single line comment

Timer function to provide time in nano seconds using C++

plf::nanotimer is a lightweight option for this, works in Windows, Linux, Mac and BSD etc. Has ~microsecond accuracy depending on OS:

  #include "plf_nanotimer.h"
  #include <iostream>

  int main(int argc, char** argv)
  {
      plf::nanotimer timer;

      timer.start()

      // Do something here

      double results = timer.get_elapsed_ns();
      std::cout << "Timing: " << results << " nanoseconds." << std::endl;    
      return 0;
  }

Can an interface extend multiple interfaces in Java?

From the Oracle documentation page about multiple inheritance type,we can find the accurate answer here. Here we should first know the type of multiple inheritance in java:-

  1. Multiple inheritance of state.
  2. Multiple inheritance of implementation.
  3. Multiple inheritance of type.

Java "doesn't support the multiple inheritance of state, but it support multiple inheritance of implementation with default methods since java 8 release and multiple inheritance of type with interfaces.

Then here the question arises for "diamond problem" and how Java deal with that:-

  1. In case of multiple inheritance of implementation java compiler gives compilation error and asks the user to fix it by specifying the interface name. Example here:-

                interface A {
                    void method();
                }
    
                interface B extends A {
                    @Override
                    default void method() {
                        System.out.println("B");
                    }
                }
    
                interface C extends A { 
                    @Override
                    default void method() {
                        System.out.println("C");
                    }
                }
    
                interface D extends B, C {
    
                }
    

So here we will get error as:- interface D inherits unrelated defaults for method() from types B and C interface D extends B, C

You can fix it like:-

interface D extends B, C {
                @Override
                default void method() {
                    B.super.method();
                }
            }
  1. In multiple inheritance of type java allows it because interface doesn't contain mutable fields and only one implementation will belong to the class so java doesn't give any issue and it allows you to do so.

In Conclusion we can say that java doesn't support multiple inheritance of state but it does support multiple inheritance of implementation and multiple inheritance of type.

To get total number of columns in a table in sql

In my situation, I was comparing table schema column count for 2 identical tables in 2 databases; one is the main database and the other is the archival database. I did this (SQL 2012+):

DECLARE @colCount1 INT;
DECLARE @colCount2 INT;

SELECT @colCount1 = COUNT(COLUMN_NAME) FROM MainDB.INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'SomeTable';
SELECT @colCount2 = COUNT(COLUMN_NAME) FROM ArchiveDB.INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'SomeTable';

IF (@colCount1 != @colCount2) THROW 5000, 'Number of columns in both tables are not equal. The archive schema may need to be updated.', 16;

The important thing to notice here is qualifying the database name before INFORMATION_SCHEMA (which is a schema, like dbo). This will allow the code to break, in case columns were added to the main database and not to the archival database, in which if the procedure were allowed to run, data loss would almost certainly occur.

Twig: in_array or similar possible within if statement?

It should help you.

{% for user in users if user.active and user.id not 1 %}
   {{ user.name }}
{% endfor %}

More info: http://twig.sensiolabs.org/doc/tags/for.html

How to make picturebox transparent?

GameBoard is control of type DataGridView; The image should be type of PNG with transparent alpha channel background;

        Image test = Properties.Resources.checker_black;
        PictureBox b = new PictureBox();
        b.Parent = GameBoard;
        b.Image = test;
        b.Width = test.Width*2;
        b.Height = test.Height*2;
        b.Location = new Point(0, 90);
        b.BackColor = Color.Transparent;
        b.BringToFront();

enter image description here

MySQL : transaction within a stored procedure

Just an alternative to the code by rkosegi,

BEGIN

    .. Declare statements ..

    DECLARE EXIT HANDLER FOR SQLEXCEPTION 
    BEGIN
          .. set any flags etc  eg. SET @flag = 0; ..
          ROLLBACK;
    END;

    START TRANSACTION;

        .. Query 1 ..
        .. Query 2 ..
        .. Query 3 ..

    COMMIT;
    .. eg. SET @flag = 1; ..

END

Case insensitive 'Contains(string)'

Just convert the string to uppercase or to lower case to match the search criteria, i.e:

string title = "ASTRINGTOTEST"; title.ToLower().Contains("string");

How can I access localhost from another computer in the same network?

You need to find what your local network's IP of that computer is. Then other people can access to your site by that IP.

You can find your local network's IP by go to Command Prompt or press Windows + R then type in ipconfig. It will give out some information and your local IP should look like 192.168.1.x.

How to chain scope queries with OR instead of AND?

In case anyone is looking for an updated answer to this one, it looks like there is an existing pull request to get this into Rails: https://github.com/rails/rails/pull/9052.

Thanks to @j-mcnally's monkey patch for ActiveRecord (https://gist.github.com/j-mcnally/250eaaceef234dd8971b) you can do the following:

Person.where(name: 'John').or.where(last_name: 'Smith').all

Even more valuable is the ability to chain scopes with OR:

scope :first_or_last_name, ->(name) { where(name: name.split(' ').first).or.where(last_name: name.split(' ').last) }
scope :parent_last_name, ->(name) { includes(:parents).where(last_name: name) }

Then you can find all Persons with first or last name or whose parent with last name

Person.first_or_last_name('John Smith').or.parent_last_name('Smith')

Not the best example for the use of this, but just trying to fit it with the question.

Javascript array value is undefined ... how do I test for that

You are checking it the array index contains a string "undefined", you should either use the typeof operator:

typeof predQuery[preId] == 'undefined'

Or use the undefined global property:

predQuery[preId] === undefined

The first way is safer, because the undefined global property is writable, and it can be changed to any other value.

Change background color on mouseover and remove it after mouseout

If you don't care about IE =6, you could use pure CSS ...

.forum:hover { background-color: #380606; }

_x000D_
_x000D_
.forum { color: white; }_x000D_
.forum:hover { background-color: #380606 !important; }_x000D_
/* we use !important here to override specificity. see http://stackoverflow.com/q/5805040/ */_x000D_
_x000D_
#blue { background-color: blue; }
_x000D_
<meta charset=utf-8>_x000D_
_x000D_
<p class="forum" style="background-color:red;">Red</p>_x000D_
<p class="forum" style="background:green;">Green</p>_x000D_
<p class="forum" id="blue">Blue</p>
_x000D_
_x000D_
_x000D_


With jQuery, usually it is better to create a specific class for this style:

.forum_hover { background-color: #380606; }

and then apply the class on mouseover, and remove it on mouseout.

$('.forum').hover(function(){$(this).toggleClass('forum_hover');});

_x000D_
_x000D_
$(document).ready(function(){_x000D_
  $('.forum').hover(function(){$(this).toggleClass('forum_hover');});_x000D_
});
_x000D_
.forum_hover { background-color: #380606 !important; }_x000D_
_x000D_
.forum { color: white; }_x000D_
#blue { background-color: blue; }
_x000D_
<meta charset=utf-8>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<p class="forum" style="background-color:red;">Red</p>_x000D_
<p class="forum" style="background:green;">Green</p>_x000D_
<p class="forum" id="blue">Blue</p>
_x000D_
_x000D_
_x000D_


If you must not modify the class, you could save the original background color in .data():

  $('.forum').data('bgcolor', '#380606').hover(function(){
    var $this = $(this);
    var newBgc = $this.data('bgcolor');
    $this.data('bgcolor', $this.css('background-color')).css('background-color', newBgc);
  });

_x000D_
_x000D_
$(document).ready(function(){_x000D_
  $('.forum').data('bgcolor', '#380606').hover(function(){_x000D_
    var $this = $(this);_x000D_
    var newBgc = $this.data('bgcolor');_x000D_
    $this.data('bgcolor', $this.css('background-color')).css('background-color', newBgc);_x000D_
  });_x000D_
});
_x000D_
.forum { color: white; }_x000D_
#blue { background-color: blue; }
_x000D_
<meta charset=utf-8>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<p class="forum" style="background-color:red;">Red</p>_x000D_
<p class="forum" style="background:green;">Green</p>_x000D_
<p class="forum" id="blue">Blue</p>
_x000D_
_x000D_
_x000D_

or

  $('.forum').hover(
    function(){
      var $this = $(this);
      $this.data('bgcolor', $this.css('background-color')).css('background-color', '#380606');
    },
    function(){
      var $this = $(this);
      $this.css('background-color', $this.data('bgcolor'));
    }
  );   

_x000D_
_x000D_
$(document).ready(function(){_x000D_
  $('.forum').hover(_x000D_
    function(){_x000D_
      var $this = $(this);_x000D_
      $this.data('bgcolor', $this.css('background-color')).css('background-color', '#380606');_x000D_
    },_x000D_
    function(){_x000D_
      var $this = $(this);_x000D_
      $this.css('background-color', $this.data('bgcolor'));_x000D_
    }_x000D_
  );    _x000D_
});
_x000D_
.forum { color: white; }_x000D_
#blue { background-color: blue; }
_x000D_
<meta charset=utf-8>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<p class="forum" style="background-color:red;">Red</p>_x000D_
<p class="forum" style="background:green;">Green</p>_x000D_
<p class="forum" id="blue">Blue</p>
_x000D_
_x000D_
_x000D_

Access 2010 VBA query a table and iterate through results

Ahh. Because I missed the point of you initial post, here is an example which also ITERATES. The first example did not. In this case, I retreive an ADODB recordset, then load the data into a collection, which is returned by the function to client code:

EDIT: Not sure what I screwed up in pasting the code, but the formatting is a little screwball. Sorry!

Public Function StatesCollection() As Collection
Dim cn As ADODB.Connection
Dim cmd As ADODB.Command
Dim rs As ADODB.Recordset
Dim colReturn As New Collection

Set colReturn = New Collection

Dim SQL As String
SQL = _
    "SELECT tblState.State, tblState.StateName " & _
    "FROM tblState"

Set cn = New ADODB.Connection
Set cmd = New ADODB.Command

With cn
    .Provider = DataConnection.MyADOProvider
    .ConnectionString = DataConnection.MyADOConnectionString
    .Open
End With

With cmd
    .CommandText = SQL
    .ActiveConnection = cn
End With

Set rs = cmd.Execute

With rs
    If Not .EOF Then
    Do Until .EOF
        colReturn.Add Nz(!State, "")
        .MoveNext
    Loop
    End If
    .Close
End With
cn.Close

Set rs = Nothing
Set cn = Nothing

Set StatesCollection = colReturn

End Function

Getting error "The package appears to be corrupt" while installing apk file

In my case, the target phone had the app already installed, but in a "disabled" state. So the user thought it was already uninstalled, but it wasn't. I went to the main app list, clicked on the "disabled" app, uninstalled it, and then the APK would go on.

Mouseover or hover vue.js

There is a correct working JSFiddle: http://jsfiddle.net/1cekfnqw/176/

<p v-on:mouseover="mouseOver" v-bind:class="{on: active, 'off': !active}">Hover over me!</p>

Changing route doesn't scroll to top in the new page

Just put this code to run

$rootScope.$on("$routeChangeSuccess", function (event, currentRoute, previousRoute) {

    window.scrollTo(0, 0);

});

What is an MDF file?

Just to make this absolutely clear for all:

A .MDF file is “typically” a SQL Server data file however it is important to note that it does NOT have to be.

This is because .MDF is nothing more than a recommended/preferred notation but the extension itself does not actually dictate the file type.

To illustrate this, if someone wanted to create their primary data file with an extension of .gbn they could go ahead and do so without issue.

To qualify the preferred naming conventions:

  • .mdf - Primary database data file.
  • .ndf - Other database data files i.e. non Primary.
  • .ldf - Log data file.

Checking if a folder exists using a .bat file

I think the answer is here (possibly duplicate):

How to test if a file is a directory in a batch script?

IF EXIST %VAR%\NUL ECHO It's a directory

Replace %VAR% with your directory. Please read the original answer because includes details about handling white spaces in the folder name.

As foxidrive said, this might not be reliable on NT class windows. It works for me, but I know it has some limitations (which you can find in the referenced question)

if exist "c:\folder\" echo folder exists 

should be enough for modern windows.

How to format background color using twitter bootstrap?

Bootstrap default "contextual backgrounds" helper classes to change the background color:

.bg-primary
.bg-default
.bg-info
.bg-warning
.bg-danger

If you need set custom background color then, you can write your own custom classes in style.css( a custom css file) example below

.bg-pink
{
  background-color: #CE6F9E;
}

Difference between require, include, require_once and include_once?

There are require and include_once as well.

So your question should be...

  1. When should I use require vs. include?
  2. When should I use require_once vs. require

The answer to 1 is described here.

The require() function is identical to include(), except that it handles errors differently. If an error occurs, the include() function generates a warning, but the script will continue execution. The require() generates a fatal error, and the script will stop.

The answer to 2 can be found here.

The require_once() statement is identical to require() except PHP will check if the file has already been included, and if so, not include (require) it again.

What are the uses of "using" in C#?

public class ClassA:IDisposable

{
   #region IDisposable Members        
    public void Dispose()
    {            
        GC.SuppressFinalize(this);
    }
    #endregion
}

public void fn_Data()

    {
     using (ClassA ObjectName = new ClassA())
            {
                //use objectName 
            }
    }

Simple JavaScript problem: onClick confirm not preventing default action

try this:

OnClientClick='return (confirm("Are you sure you want to delete this comment?"));'

Saving a high resolution image in R

You can do the following. Add your ggplot code after the first line of code and end with dev.off().

tiff("test.tiff", units="in", width=5, height=5, res=300)
# insert ggplot code
dev.off()

res=300 specifies that you need a figure with a resolution of 300 dpi. The figure file named 'test.tiff' is saved in your working directory.

Change width and height in the code above depending on the desired output.

Note that this also works for other R plots including plot, image, and pheatmap.

Other file formats

In addition to TIFF, you can easily use other image file formats including JPEG, BMP, and PNG. Some of these formats require less memory for saving.

How to prevent favicon.ico requests?

A very simple solution is put the below code in your .htaccess. I had the same issue and it solve my problem.

<IfModule mod_alias.c>
    RedirectMatch 403 favicon.ico
</IfModule>

Reference: http://perishablepress.com/block-favicon-url-404-requests/

Hard reset of a single file

Since Git 2.23 (August 2019) you can use restore (more info):

git restore pathTo/MyFile

The above will restore MyFile on HEAD (the last commit) on the current branch.

If you want to get the changes from other commit you can go backwards on the commit history. The below command will get MyFile two commits previous to the last one. You need now the -s (--source) option since now you use master~2 and not master (the default) as you restore source:

git restore -s master~2 pathTo/MyFile

You can also get the file from other branch!

git restore -s my-feature-branch pathTo/MyFile

Count records for every month in a year

This will give you the count per month for 2012;

SELECT MONTH(ARR_DATE) MONTH, COUNT(*) COUNT
FROM table_emp
WHERE YEAR(arr_date)=2012
GROUP BY MONTH(ARR_DATE);

Demo here.

Check Whether a User Exists

Create system user some_user if it doesn't exist

if [[ $(getent passwd some_user) = "" ]]; then
    sudo adduser --no-create-home --force-badname --disabled-login --disabled-password --system some_user
fi

how to remove untracked files in Git?

Those are untracked files. This means git isn't tracking them. It's only listing them because they're not in the git ignore file. Since they're not being tracked by git, git reset won't touch them.

If you want to blow away all untracked files, the simplest way is git clean -f (use git clean -n instead if you want to see what it would destroy without actually deleting anything). Otherwise, you can just delete the files you don't want by hand.

angularjs getting previous route path

In your html :

<a href="javascript:void(0);" ng-click="go_back()">Go Back</a>

On your main controller :

$scope.go_back = function() { 
  $window.history.back();
};

When user click on Go Back link the controller function is called and it will go back to previous route.

SQL 'like' vs '=' performance

See https://web.archive.org/web/20150209022016/http://myitforum.com/cs2/blogs/jnelson/archive/2007/11/16/108354.aspx

Quote from there:

the rules for index usage with LIKE are loosely like this:

  • If your filter criteria uses equals = and the field is indexed, then most likely it will use an INDEX/CLUSTERED INDEX SEEK

  • If your filter criteria uses LIKE, with no wildcards (like if you had a parameter in a web report that COULD have a % but you instead use the full string), it is about as likely as #1 to use the index. The increased cost is almost nothing.

  • If your filter criteria uses LIKE, but with a wildcard at the beginning (as in Name0 LIKE '%UTER') it's much less likely to use the index, but it still may at least perform an INDEX SCAN on a full or partial range of the index.

  • HOWEVER, if your filter criteria uses LIKE, but starts with a STRING FIRST and has wildcards somewhere AFTER that (as in Name0 LIKE 'COMP%ER'), then SQL may just use an INDEX SEEK to quickly find rows that have the same first starting characters, and then look through those rows for an exact match.

(Also keep in mind, the SQL engine still might not use an index the way you're expecting, depending on what else is going on in your query and what tables you're joining to. The SQL engine reserves the right to rewrite your query a little to get the data in a way that it thinks is most efficient and that may include an INDEX SCAN instead of an INDEX SEEK)

Fastest way to convert an iterator to a list

@Robino was suggesting to add some tests which make sense, so here is a simple benchmark between 3 possible ways (maybe the most used ones) to convert an iterator to a list:

  1. by type constructor

list(my_iterator)

  1. by unpacking

[*my_iterator]

  1. using list comprehension

[e for e in my_iterator]

I have been using simple_bechmark library

from simple_benchmark import BenchmarkBuilder
from heapq import nsmallest

b = BenchmarkBuilder()

@b.add_function()
def convert_by_type_constructor(size):
    list(iter(range(size)))

@b.add_function()
def convert_by_list_comprehension(size):
    [e for e in iter(range(size))]

@b.add_function()
def convert_by_unpacking(size):
    [*iter(range(size))]


@b.add_arguments('Convert an iterator to a list')
def argument_provider():
    for exp in range(2, 22):
        size = 2**exp
        yield size, size

r = b.run()
r.plot()

enter image description here

As you can see there is very hard to make a difference between conversion by the constructor and conversion by unpacking, conversion by list comprehension is the “slowest” approach.


I have been testing also across different Python versions (3.6, 3.7, 3.8, 3.9) by using the following simple script:

import argparse
import timeit

parser = argparse.ArgumentParser(
    description='Test convert iterator to list')
parser.add_argument(
    '--size', help='The number of elements from iterator')

args = parser.parse_args()

size = int(args.size)
repeat_number = 10000

# do not wait too much if the size is too big
if size > 10000:
    repeat_number = 100


def test_convert_by_type_constructor():
    list(iter(range(size)))


def test_convert_by_list_comprehension():
    [e for e in iter(range(size))]


def test_convert_by_unpacking():
    [*iter(range(size))]


def get_avg_time_in_ms(func):
    avg_time = timeit.timeit(func, number=repeat_number) * 1000 / repeat_number
    return round(avg_time, 6)


funcs = [test_convert_by_type_constructor,
         test_convert_by_unpacking, test_convert_by_list_comprehension]

print(*map(get_avg_time_in_ms, funcs))

The script will be executed via a subprocess from a Jupyter Notebook (or a script), the size parameter will be passed through command-line arguments and the script results will be taken from standard output.

from subprocess import PIPE, run

import pandas

simple_data = {'constructor': [], 'unpacking': [], 'comprehension': [],
        'size': [], 'python version': []}


size_test = 100, 1000, 10_000, 100_000, 1_000_000
for version in ['3.6', '3.7', '3.8', '3.9']:
    print('test for python', version)
    for size in size_test:
        command = [f'python{version}', 'perf_test_convert_iterator.py', f'--size={size}']
        result = run(command, stdout=PIPE, stderr=PIPE, universal_newlines=True)
        constructor, unpacking,  comprehension = result.stdout.split()
        
        simple_data['constructor'].append(float(constructor))
        simple_data['unpacking'].append(float(unpacking))
        simple_data['comprehension'].append(float(comprehension))
        simple_data['python version'].append(version)
        simple_data['size'].append(size)

df_ = pandas.DataFrame(simple_data)
df_

enter image description here

You can get my full notebook from here.

In most of the cases, in my tests, unpacking shows to be faster, but the difference is so small that the results may change from a run to the other. Again, the comprehension approach is the slowest, in fact, the other 2 methods are up to ~ 60% faster.

Importing the private-key/public-certificate pair in the Java KeyStore

With your private key and public certificate, you need to create a PKCS12 keystore first, then convert it into a JKS.

# Create PKCS12 keystore from private key and public certificate.
openssl pkcs12 -export -name myservercert -in selfsigned.crt -inkey server.key -out keystore.p12

# Convert PKCS12 keystore into a JKS keystore
keytool -importkeystore -destkeystore mykeystore.jks -srckeystore keystore.p12 -srcstoretype pkcs12 -alias myservercert

To verify the contents of the JKS, you can use this command:

keytool -list -v -keystore mykeystore.jks

If this was not a self-signed certificate, you would probably want to follow this step with importing the certificate chain leading up to the trusted CA cert.

How to use color picker (eye dropper)?

Currently, the eyedropper tool is not working in my version of Chrome (as described above), though it worked for me in the past. I hear it is being updated in the latest version of Chrome.

However, I'm able to grab colors easily in Firefox.

  1. Open page in Firefox
  2. Hamburger Menu -> Web Developer -> Eyedropper
  3. Drag eyedropper tool over the image... Click.
    Color is copied to your clipboard, and eyedropper tool goes away.
  4. Paste color code

In case you cannot get the eyedropper tool to work in Chrome, this is a good work around.
I also find it easier to access :-)

How to list files in a directory in a C program?

One tiny addition to JB Jansen's answer - in the main readdir() loop I'd add this:

  if (dir->d_type == DT_REG)
  {
     printf("%s\n", dir->d_name);
  }

Just checking if it's really file, not (sym)link, directory, or whatever.

NOTE: more about struct dirent in libc documentation.

Java, looping through result set

Result Set are actually contains multiple rows of data, and use a cursor to point out current position. So in your case, rs4.getString(1) only get you the data in first column of first row. In order to change to next row, you need to call next()

a quick example

while (rs.next()) {
    String sid = rs.getString(1);
    String lid = rs.getString(2);
    // Do whatever you want to do with these 2 values
}

there are many useful method in ResultSet, you should take a look :)

What is an attribute in Java?

A class is an element in object oriented programming that aggregates attributes(fields) - which can be public accessible or not - and methods(functions) - which also can be public or private and usually writes/reads those attributes.

so you can have a class like Array with a public attribute lengthand a public method sort().

accessing a docker container from another container

Using docker-compose, services are exposed to each other by name by default. Docs.
You could also specify an alias like;

version: '2.1'
services:
  mongo:
    image: mongo:3.2.11
  redis:
    image: redis:3.2.10
  api:
    image: some-image
    depends_on:
      - mongo
      - solr
    links:
      - "mongo:mongo.openconceptlab.org"
      - "solr:solr.openconceptlab.org"
      - "some-service:some-alias"

And then access the service using the specified alias as a host name, e.g mongo.openconceptlab.org for mongo in this case.

Combining CSS Pseudo-elements, ":after" the ":last-child"

An old thread, nonetheless someone may benefit from this:

li:not(:last-child)::after { content: ","; }
li:last-child::after { content: "."; }

This should work in CSS3 and [untested] CSS2.

Fixed digits after decimal with f-strings

When it comes to float numbers, you can use format specifiers:

f'{value:{width}.{precision}}'

where:

  • value is any expression that evaluates to a number
  • width specifies the number of characters used in total to display, but if value needs more space than the width specifies then the additional space is used.
  • precision indicates the number of characters used after the decimal point

What you are missing is the type specifier for your decimal value. In this link, you an find the available presentation types for floating point and decimal.

Here you have some examples, using the f (Fixed point) presentation type:

# notice that it adds spaces to reach the number of characters specified by width
In [1]: f'{1 + 3 * 1.5:10.3f}'
Out[1]: '     5.500'

# notice that it uses more characters than the ones specified in width
In [2]: f'{3000 + 3 ** (1 / 2):2.1f}' 
Out[2]: '3001.7'

In [3]: f'{1.2345 + 4 ** (1 / 2):9.6f}'
Out[3]: ' 3.234500'

# omitting width but providing precision will use the required characters to display the number with the the specified decimal places
In [4]: f'{1.2345 + 3 * 2:.3f}' 
Out[4]: '7.234'

# not specifying the format will display the number with as many digits as Python calculates
In [5]: f'{1.2345 + 3 * 0.5}'
Out[5]: '2.7344999999999997'

Should I learn C before learning C++?

I learned C first, and I took a course in data structures which used C, before I learned C++. This has worked well for me. A data structures course in C gave me a solid understanding of pointers and memory management. It also made obvious the benefits of the object oriented paradigm, once I had learned what it was.

On the flip side, by learning C first, I have developed some habits that initially caused me to write bad C++ code, such as excessive use of pointers (when C++ references would do) and the preprocessor.

C++ is really a very complex language with lots of features. It is not really a superset of C, though. Rather there is a subset of C++ consisting of the basic procedural programming constructs (loops, ifs, and functions), which is very similar to C. In your case, I would start with that, and then work my way up to more advanced concepts like classes and templates.

The most important thing, IMHO, is to be exposed to different programming paradigms, like procedural, object-oriented, functional, and logical, early on, before your brain freezes into one way of looking at the world. Incidentally, I would also strongly recommend that you learn a functional programming language, like Scheme. It would really expand your horizons.

Where does the .gitignore file belong?

Put .gitignore in the working directory. It doesn't work if you put it in the .git (repository) directory.

$ ls -1d .git*
.git
.gitignore

Run local java applet in browser (chrome/firefox) "Your security settings have blocked a local application from running"

Go to java control tab>java control pannel>click security tab>down the security level to medium. Then applet progrramme after 2to 3 security promt it will run.

Cause of a process being a deadlock victim

The answers here are worth a try, but you should also review your code. Specifically have a read of Polyfun's answer here: How to get rid of deadlock in a SQL Server 2005 and C# application?

It explains the concurrency issue, and how the usage of "with (updlock)" in your queries might correct your deadlock situation - depending really on exactly what your code is doing. If your code does follow this pattern, this is likely a better fix to make, before resorting to dirty reads, etc.

WCF vs ASP.NET Web API

The new ASP.NET Web API is a continuation of the previous WCF Web API project (although some of the concepts have changed).

WCF was originally created to enable SOAP-based services. For simpler RESTful or RPCish services (think clients like jQuery) ASP.NET Web API should be good choice.


For us, WCF is used for SOAP and Web API for REST. I wish Web API supported SOAP too. We are not using advanced features of WCF. Here is comparison from MSDN:

enter image description here


ASP.net Web API is all about HTTP and REST based GET,POST,PUT,DELETE with well know ASP.net MVC style of programming and JSON returnable; web API is for all the light weight process and pure HTTP based components. For one to go ahead with WCF even for simple or simplest single web service it will bring all the extra baggage. For light weight simple service for ajax or dynamic calls always WebApi just solves the need. This neatly complements or helps in parallel to the ASP.net MVC.

Check out the podcast : Hanselminutes Podcast 264 - This is not your father's WCF - All about the WebAPI with Glenn Block by Scott Hanselman for more information.


In the scenarios listed below you should go for WCF:

  1. If you need to send data on protocols like TCP, MSMQ or MIME
  2. If the consuming client just knows how to consume SOAP messages

WEB API is a framework for developing RESTful/HTTP services.

There are so many clients that do not understand SOAP like Browsers, HTML5, in those cases WEB APIs are a good choice.

HTTP services header specifies how to secure service, how to cache the information, type of the message body and HTTP body can specify any type of content like HTML not just XML as SOAP services.

How to get a file directory path from file path?

dirname and basename are the tools you're looking for for extracting path components:

$ export VAR='/home/pax/file.c'
$ echo "$(dirname "${VAR}")" ; echo "$(basename "${VAR}")"
/home/pax
file.c

They're not internal Bash commands but they're part of the POSIX standard - see dirname and basename. Hence, they're probably available on, or can be obtained for, most platforms that are capable of running bash.

How to pass parameters to a Script tag?

If you are using jquery you might want to consider their data method.

I have used something similar to what you are trying in your response but like this:

<script src="http://path.to/widget.js" param_a = "2" param_b = "5" param_c = "4">
</script>

You could also create a function that lets you grab the GET params directly (this is what I frequently use):

function $_GET(q,s) {
    s = s || window.location.search;
    var re = new RegExp('&'+q+'=([^&]*)','i');
    return (s=s.replace(/^\?/,'&').match(re)) ? s=s[1] : s='';
}

// Grab the GET param
var param_a = $_GET('param_a');

Rails formatting date

Use

Model.created_at.strftime("%FT%T")

where,

%F - The ISO 8601 date format (%Y-%m-%d)
%T - 24-hour time (%H:%M:%S)

Following are some of the frequently used useful list of Date and Time formats that you could specify in strftime method:

Date (Year, Month, Day):
  %Y - Year with century (can be negative, 4 digits at least)
          -0001, 0000, 1995, 2009, 14292, etc.
  %C - year / 100 (round down.  20 in 2009)
  %y - year % 100 (00..99)

  %m - Month of the year, zero-padded (01..12)
          %_m  blank-padded ( 1..12)
          %-m  no-padded (1..12)
  %B - The full month name (``January'')
          %^B  uppercased (``JANUARY'')
  %b - The abbreviated month name (``Jan'')
          %^b  uppercased (``JAN'')
  %h - Equivalent to %b

  %d - Day of the month, zero-padded (01..31)
          %-d  no-padded (1..31)
  %e - Day of the month, blank-padded ( 1..31)

  %j - Day of the year (001..366)

Time (Hour, Minute, Second, Subsecond):
  %H - Hour of the day, 24-hour clock, zero-padded (00..23)
  %k - Hour of the day, 24-hour clock, blank-padded ( 0..23)
  %I - Hour of the day, 12-hour clock, zero-padded (01..12)
  %l - Hour of the day, 12-hour clock, blank-padded ( 1..12)
  %P - Meridian indicator, lowercase (``am'' or ``pm'')
  %p - Meridian indicator, uppercase (``AM'' or ``PM'')

  %M - Minute of the hour (00..59)

  %S - Second of the minute (00..59)

  %L - Millisecond of the second (000..999)
  %N - Fractional seconds digits, default is 9 digits (nanosecond)
          %3N  millisecond (3 digits)
          %6N  microsecond (6 digits)
          %9N  nanosecond (9 digits)
          %12N picosecond (12 digits)

For the complete list of formats for strftime method please visit APIDock

Difference between Big-O and Little-O Notation

f ? O(g) says, essentially

For at least one choice of a constant k > 0, you can find a constant a such that the inequality 0 <= f(x) <= k g(x) holds for all x > a.

Note that O(g) is the set of all functions for which this condition holds.

f ? o(g) says, essentially

For every choice of a constant k > 0, you can find a constant a such that the inequality 0 <= f(x) < k g(x) holds for all x > a.

Once again, note that o(g) is a set.

In Big-O, it is only necessary that you find a particular multiplier k for which the inequality holds beyond some minimum x.

In Little-o, it must be that there is a minimum x after which the inequality holds no matter how small you make k, as long as it is not negative or zero.

These both describe upper bounds, although somewhat counter-intuitively, Little-o is the stronger statement. There is a much larger gap between the growth rates of f and g if f ? o(g) than if f ? O(g).

One illustration of the disparity is this: f ? O(f) is true, but f ? o(f) is false. Therefore, Big-O can be read as "f ? O(g) means that f's asymptotic growth is no faster than g's", whereas "f ? o(g) means that f's asymptotic growth is strictly slower than g's". It's like <= versus <.

More specifically, if the value of g(x) is a constant multiple of the value of f(x), then f ? O(g) is true. This is why you can drop constants when working with big-O notation.

However, for f ? o(g) to be true, then g must include a higher power of x in its formula, and so the relative separation between f(x) and g(x) must actually get larger as x gets larger.

To use purely math examples (rather than referring to algorithms):

The following are true for Big-O, but would not be true if you used little-o:

  • x² ? O(x²)
  • x² ? O(x² + x)
  • x² ? O(200 * x²)

The following are true for little-o:

  • x² ? o(x³)
  • x² ? o(x!)
  • ln(x) ? o(x)

Note that if f ? o(g), this implies f ? O(g). e.g. x² ? o(x³) so it is also true that x² ? O(x³), (again, think of O as <= and o as <)

Intro to GPU programming

If you use MATLAB, it becomes pretty simple to use GPU's for technical computing (matrix computations and heavy math/number crunching). I find it useful for uses of GPU cards outside of gaming. Check out the link below:

http://www.mathworks.com/discovery/matlab-gpu.html

Change keystore password from no password to a non blank password

On my system the password is 'changeit'. On blank if I hit enter then it complains about short password. Hope this helps

enter image description here

How to check if an item is selected from an HTML drop down list?

Select select = new Select(_element);
List<WebElement> selectedOptions = select.getAllSelectedOptions();

if(selectedOptions.size() > 0){
    return true;
}else{
    return false;
}

Working with Enums in android

As commented by Chris, enums require much more memory on Android that adds up as they keep being used everywhere. You should try IntDef or StringDef instead, which use annotations so that the compiler validates passed values.

public abstract class ActionBar {
...
@IntDef({NAVIGATION_MODE_STANDARD, NAVIGATION_MODE_LIST, NAVIGATION_MODE_TABS})
@Retention(RetentionPolicy.SOURCE)
public @interface NavigationMode {}

public static final int NAVIGATION_MODE_STANDARD = 0;
public static final int NAVIGATION_MODE_LIST = 1;
public static final int NAVIGATION_MODE_TABS = 2;

@NavigationMode
public abstract int getNavigationMode();

public abstract void setNavigationMode(@NavigationMode int mode);

It can also be used as flags, allowing for binary composition (OR / AND operations).

EDIT: It seems that transforming enums into ints is one of the default optimizations in Proguard.

How to upgrade OpenSSL in CentOS 6.5 / Linux / Unix from source?

I agree that in 95% of cases, all you need is sudo yum update openssl

However, if you need a specific version of openssl or specific functionality, which is not in CentOS repository, you probably need to compile from source. The other answers here were incomplete. Below is what worked (CentOS 6.9), although this may introduce incompatibilities with installed software, and will not auto-update the openssl.


Choose openssl version from https://www.openssl.org/source/

Log-in as root:

cd /usr/local/src/

# OPTIONALLY CHANGE openssl-1.1.0f.tar.gz to the version which you want
wget https://www.openssl.org/source/openssl-1.1.0f.tar.gz

sha256sum openssl-1.1.0f.tar.gz  #confirm this matches the published hash

tar -zxf openssl-1.1.0f.tar.gz

cd /usr/local/src/openssl-1.1.0f

./config --prefix=/usr/local --openssldir=/usr/local/openssl
make
make test
make install

export LD_LIBRARY_PATH=/usr/local/lib64

#make export permanent
echo "export LD_LIBRARY_PATH=/usr/local/lib64" > /etc/profile.d/ld_library_path.sh
chmod ugo+x /etc/profile.d/ld_library_path.sh

openssl version  #confirm it works

#recommended reboot here

openssl version  #confirm it works after reboot

Retrieving values from nested JSON Object

You can see that JSONObject extends a HashMap, so you can simply use it as a HashMap:

JSONObject jsonChildObject = (JSONObject)jsonObject.get("LanguageLevels");
for (Map.Entry in jsonChildOBject.entrySet()) {
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}

PDOException SQLSTATE[HY000] [2002] No such file or directory

Mamp user enable option Allow network access to MYSQL

enter image description here

Android design support library for API 28 (P) not working

if you want to solve this problem without migrating to AndroidX (I don't recommend it)

this manifest merger issue is related to one of your dependency using androidX.

you need to decrease this dependency's release version. for my case :

I was using google or firebase

api 'com.google.android.gms:play-services-base:17.1.0'

I have to decrease it 15.0.1 to use in support library.

How to Replace Multiple Characters in SQL?

One option is to use a numbers/tally table to drive an iterative process via a pseudo-set based query.

The general idea of char replacement can be demonstrated with a simple character map table approach:

create table charMap (srcChar char(1), replaceChar char(1))
insert charMap values ('a', 'z')
insert charMap values ('b', 'y')


create table testChar(srcChar char(1))
insert testChar values ('1')
insert testChar values ('a')
insert testChar values ('2')
insert testChar values ('b')

select 
coalesce(charMap.replaceChar, testChar.srcChar) as charData
from testChar left join charMap on testChar.srcChar = charMap.srcChar

Then you can bring in the tally table approach to do the lookup on each character position in the string.

create table tally (i int)
declare @i int
set @i = 1
while @i <= 256 begin
    insert tally values (@i)
    set @i = @i + 1
end

create table testData (testString char(10))
insert testData values ('123a456')
insert testData values ('123ab456')
insert testData values ('123b456')

select
    i,
    SUBSTRING(testString, i, 1) as srcChar,
    coalesce(charMap.replaceChar, SUBSTRING(testString, i, 1)) as charData
from testData cross join tally
    left join charMap on SUBSTRING(testString, i, 1) = charMap.srcChar
where i <= LEN(testString)

CSS to prevent child element from inheriting parent styles

Unfortunately, you're out of luck here.

There is inherit to copy a certain value from a parent to its children, but there is no property the other way round (which would involve another selector to decide which style to revert).

You will have to revert style changes manually:

div { color: green; }

form div { color: red; }

form div div.content { color: green; }

If you have access to the markup, you can add several classes to style precisely what you need:

form div.sub { color: red; }

form div div.content { /* remains green */ }

Edit: The CSS Working Group is up to something:

div.content {
  all: revert;
}

No idea, when or if ever this will be implemented by browsers.

Edit 2: As of March 2015 all modern browsers but Safari and IE/Edge have implemented it: https://twitter.com/LeaVerou/status/577390241763467264 (thanks, @Lea Verou!)

Edit 3: default was renamed to revert.

Powershell Log Off Remote Session

Perhaps surprisingly you can logoff users with the logoff command.

C:\> logoff /?
Terminates a session.

LOGOFF [sessionname | sessionid] [/SERVER:servername] [/V] [/VM]

  sessionname         The name of the session.
  sessionid           The ID of the session.
  /SERVER:servername  Specifies the Remote Desktop server containing the user
                      session to log off (default is current).
  /V                  Displays information about the actions performed.
  /VM                 Logs off a session on server or within virtual machine.
                      The unique ID of the session needs to be specified.

The session ID can be determined with the qwinsta (query session) or quser (query user) commands (see here):

$server   = 'MyServer'
$username = $env:USERNAME

$session = ((quser /server:$server | ? { $_ -match $username }) -split ' +')[2]

logoff $session /server:$server

How do I write a "tab" in Python?

This is the code:

f = open(filename, 'w')
f.write("hello\talex")

The \t inside the string is the escape sequence for the horizontal tabulation.

Styling Google Maps InfoWindow

Use the InfoBox plugin from the Google Maps Utility Library. It makes styling/managing map pop-ups much easier.

Note that you'll need to make sure it loads after the google maps API:

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY&callback=initMap" async defer></script>
<script src="/js/infobox_packed.js" async defer></script>

Efficiently replace all accented characters in a string?

Answer os Crisalin is almost perfect. Just improved the performance to avoid create new RegExp on each run.

var normalizeConversions = [
    { regex: new RegExp('ä|æ|?', 'g'), clean: 'ae' },
    { regex: new RegExp('ö|œ', 'g'), clean: 'oe' },
    { regex: new RegExp('ü', 'g'), clean: 'ue' },
    { regex: new RegExp('Ä', 'g'), clean: 'Ae' },
    { regex: new RegExp('Ü', 'g'), clean: 'Ue' },
    { regex: new RegExp('Ö', 'g'), clean: 'Oe' },
    { regex: new RegExp('À|Á|Â|Ã|Ä|Å|?|A|A|A|A', 'g'), clean: 'A' },
    { regex: new RegExp('à|á|â|ã|å|?|a|a|a|a|ª', 'g'), clean: 'a' },
    { regex: new RegExp('Ç|C|C|C|C', 'g'), clean: 'C' },
    { regex: new RegExp('ç|c|c|c|c', 'g'), clean: 'c' },
    { regex: new RegExp('Ð|D|Ð', 'g'), clean: 'D' },
    { regex: new RegExp('ð|d|d', 'g'), clean: 'd' },
    { regex: new RegExp('È|É|Ê|Ë|E|E|E|E|E', 'g'), clean: 'E' },
    { regex: new RegExp('è|é|ê|ë|e|e|e|e|e', 'g'), clean: 'e' },
    { regex: new RegExp('G|G|G|G', 'g'), clean: 'G' },
    { regex: new RegExp('g|g|g|g', 'g'), clean: 'g' },
    { regex: new RegExp('H|H', 'g'), clean: 'H' },
    { regex: new RegExp('h|h', 'g'), clean: 'h' },
    { regex: new RegExp('Ì|Í|Î|Ï|I|I|I|I|I|I', 'g'), clean: 'I' },
    { regex: new RegExp('ì|í|î|ï|i|i|i|i|i|i', 'g'), clean: 'i' },
    { regex: new RegExp('J', 'g'), clean: 'J' },
    { regex: new RegExp('j', 'g'), clean: 'j' },
    { regex: new RegExp('K', 'g'), clean: 'K' },
    { regex: new RegExp('k', 'g'), clean: 'k' },
    { regex: new RegExp('L|L|L|?|L', 'g'), clean: 'L' },
    { regex: new RegExp('l|l|l|?|l', 'g'), clean: 'l' },
    { regex: new RegExp('Ñ|N|N|N', 'g'), clean: 'N' },
    { regex: new RegExp('ñ|n|n|n|?', 'g'), clean: 'n' },
    { regex: new RegExp('Ò|Ó|Ô|Õ|O|O|O|O|O|Ø|?', 'g'), clean: 'O' },
    { regex: new RegExp('ò|ó|ô|õ|o|o|o|o|o|ø|?|º', 'g'), clean: 'o' },
    { regex: new RegExp('R|R|R', 'g'), clean: 'R' },
    { regex: new RegExp('r|r|r', 'g'), clean: 'r' },
    { regex: new RegExp('S|S|S|Š', 'g'), clean: 'S' },
    { regex: new RegExp('s|s|s|š|?', 'g'), clean: 's' },
    { regex: new RegExp('T|T|T', 'g'), clean: 'T' },
    { regex: new RegExp('t|t|t', 'g'), clean: 't' },
    { regex: new RegExp('Ù|Ú|Û|U|U|U|U|U|U|U|U|U|U|U|U', 'g'), clean: 'U' },
    { regex: new RegExp('ù|ú|û|u|u|u|u|u|u|u|u|u|u|u|u', 'g'), clean: 'u' },
    { regex: new RegExp('Ý|Ÿ|Y', 'g'), clean: 'Y' },
    { regex: new RegExp('ý|ÿ|y', 'g'), clean: 'y' },
    { regex: new RegExp('W', 'g'), clean: 'W' },
    { regex: new RegExp('w', 'g'), clean: 'w' },
    { regex: new RegExp('Z|Z|Ž', 'g'), clean: 'Z' },
    { regex: new RegExp('z|z|ž', 'g'), clean: 'z' },
    { regex: new RegExp('Æ|?', 'g'), clean: 'AE' },
    { regex: new RegExp('ß', 'g'), clean: 'ss' },
    { regex: new RegExp('?', 'g'), clean: 'IJ' },
    { regex: new RegExp('?', 'g'), clean: 'ij' },
    { regex: new RegExp('Œ', 'g'), clean: 'OE' },
    { regex: new RegExp('ƒ', 'g'), clean: 'f' }
];

Usage:

function(str){
    normalizeConversions.forEach(function(normalizeEntry){
        str = str.replace(normalizeEntry.regex, normalizeEntry.clean);
    });
    return str;
};

Refresh DataGridView when updating data source

Well, it doesn't get much better than that. Officially, you should use

dataGridView1.DataSource = typeof(List); 
dataGridView1.DataSource = itemStates;

It's still a "clear/reset source" kind of solution, but I have yet to find anything else that would reliably refresh the DGV data source.

How to get element's width/height within directives and component?

For a bit more flexibility than with micronyks answer, you can do it like that:

1. In your template, add #myIdentifier to the element you want to obtain the width from. Example:

<p #myIdentifier>
  my-component works!
</p>

2. In your controller, you can use this with @ViewChild('myIdentifier') to get the width:

import {AfterViewInit, Component, ElementRef, OnInit, ViewChild} from '@angular/core';

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.scss']
})
export class MyComponentComponent implements AfterViewInit {

  constructor() { }

  ngAfterViewInit() {
    console.log(this.myIdentifier.nativeElement.offsetWidth);
  }

  @ViewChild('myIdentifier')
  myIdentifier: ElementRef;

}

Security

About the security risk with ElementRef, like this, there is none. There would be a risk, if you would modify the DOM using an ElementRef. But here you are only getting DOM Elements so there is no risk. A risky example of using ElementRef would be: this.myIdentifier.nativeElement.onclick = someFunctionDefinedBySomeUser;. Like this Angular doesn't get a chance to use its sanitisation mechanisms since someFunctionDefinedBySomeUser is inserted directly into the DOM, skipping the Angular sanitisation.

Javascript onclick hide div

If you want to close it you can either hide it or remove it from the page. To hide it you would do some javascript like:

this.parentNode.style.display = 'none';

To remove it you use removeChild

this.parentNode.parentNode.removeChild(this.parentNode);

If you had a library like jQuery included then hiding or removing the div would be slightly easier:

$(this).parent().hide();
$(this).parent().remove();

One other thing, as your img is in an anchor the onclick event on the anchor is going to fire as well. As the href is set to # then the page will scroll back to the top of the page. Generally it is good practice that if you want a link to do something other than go to its href you should set the onclick event to return false;

Binding Listbox to List<object> in WinForms

You're looking for the DataSource property:

List<SomeType> someList = ...;
myListBox.DataSource = someList;

You should also set the DisplayMember property to the name of a property in the object that you want the listbox to display. If you don't, it will call ToString().

Set form backcolor to custom color

With Winforms you can use Form.BackColor to do this.
From within the Form's code:

BackColor = Color.LightPink;

If you mean a WPF Window you can use the Background property.
From within the Window's code:

Background = Brushes.LightPink;

When to use async false and async true in ajax function in jquery

It is best practice to go asynchronous if you can do several things in parallel (no inter-dependencies). If you need it to complete to continue loading the next thing you could use synchronous, but note that this option is deprecated to avoid abuse of sync:

jQuery.ajax() method's async option deprecated, what now?

using OR and NOT in solr query

simple do id:("12345") OR id:("7890") .... and so on

How to create a self-signed certificate for a domain name for development?

I ran into this same problem when I wanted to enable SSL to a project hosted on IIS 8. Finally the tool I used was OpenSSL, after many days fighting with makecert commands.The certificate is generated in Debian, but I could import it seamlessly into IIS 7 and 8.

Download the OpenSSL compatible with your OS and this configuration file. Set the configuration file as default configuration of OpenSSL.

First we will generate the private key and certificate of Certification Authority (CA). This certificate is to sign the certificate request (CSR).

You must complete all fields that are required in this process.

  1. openssl req -new -x509 -days 3650 -extensions v3_ca -keyout root-cakey.pem -out root-cacert.pem -newkey rsa:4096

You can create a configuration file with default settings like this: Now we will generate the certificate request, which is the file that is sent to the Certification Authorities.

The Common Name must be set the domain of your site, for example: public.organization.com.

  1. openssl req -new -nodes -out server-csr.pem -keyout server-key.pem -newkey rsa:4096

Now the certificate request is signed with the generated CA certificate.

  1. openssl x509 -req -days 365 -CA root-cacert.pem -CAkey root-cakey.pem -CAcreateserial -in server-csr.pem -out server-cert.pem

The generated certificate must be exported to a .pfx file that can be imported into the IIS.

  1. openssl pkcs12 -export -out server-cert.pfx -inkey server-key.pem -in server-cert.pem -certfile root-cacert.pem -name "Self Signed Server Certificate"

In this step we will import the certificate CA.

  1. In your server must import the CA certificate to the Trusted Root Certification Authorities, for IIS can trust the certificate to be imported. Remember that the certificate to be imported into the IIS, has been signed with the certificate of the CA.

    • Open Command Prompt and type mmc.
    • Click on File.
    • Select Add/Remove Snap in....
    • Double click on Certificates.
    • Select Computer Account and Next ->.
    • Select Local Computer and Finish.
    • Ok.
    • Go to Certificates -> Trusted Root Certification Authorities -> Certificates, rigth click on Certificates and select All Tasks -> Import ...

enter image description here

  • Select Next -> Browse ...
  • You must select All Files to browse the location of root-cacert.pem file.
  • Click on Next and select Place all certificates in the following store: Trusted Root Certification Authorities.
  • Click on Next and Finish.

enter image description here

With this step, the IIS trust on the authenticity of our certificate.

  1. In our last step we will import the certificate to IIS and add the binding site.

    • Open Internet Information Services (IIS) Manager or type inetmgr on command prompt and go to Server Certificates.
    • Click on Import....
    • Set the path of .pfx file, the passphrase and Select certificate store on Web Hosting.

enter image description here

  • Click on OK.
  • Now go to your site on IIS Manager and select Bindings... and Add a new binding.

  • Select https as the type of binding and you should be able to see the imported certificate.

  • Click on OK and all is done.

enter image description here

Invert "if" statement to reduce nesting

Performance-wise, there will be no noticeable difference between the two approaches.

But coding is about more than performance. Clarity and maintainability are also very important. And, in cases like this where it doesn't affect performance, it is the only thing that matters.

There are competing schools of thought as to which approach is preferable.

One view is the one others have mentioned: the second approach reduces the nesting level, which improves code clarity. This is natural in an imperative style: when you have nothing left to do, you might as well return early.

Another view, from the perspective of a more functional style, is that a method should have only one exit point. Everything in a functional language is an expression. So if statements must always have an else clauses. Otherwise the if expression wouldn't always have a value. So in the functional style, the first approach is more natural.

Polymorphism vs Overriding vs Overloading

Here's an example of polymorphism in pseudo-C#/Java:

class Animal
{
    abstract string MakeNoise ();
}

class Cat : Animal {
    string MakeNoise () {
        return "Meow";
    }
}

class Dog : Animal {
    string MakeNoise () {
        return "Bark";
    }
}

Main () {
   Animal animal = Zoo.GetAnimal ();
   Console.WriteLine (animal.MakeNoise ());
}

The Main function doesn't know the type of the animal and depends on a particular implementation's behavior of the MakeNoise() method.

Edit: Looks like Brian beat me to the punch. Funny we used the same example. But the above code should help clarify the concepts.

How is Java platform-independent when it needs a JVM to run?

Edit: Not quite. See comments below.

Java doesn't directly run on anything. It needs to be converted to bytecode by a JVM.

Because JVMs exist for all major platforms, this makes Java platform-independent THROUGH the JVM.

How to clear input buffer in C?

The program will not work properly because at Line 1, when the user presses Enter, it will leave in the input buffer 2 character: Enter key (ASCII code 13) and \n (ASCII code 10). Therefore, at Line 2, it will read the \n and will not wait for the user to enter a character.

The behavior you see at line 2 is correct, but that's not quite the correct explanation. With text-mode streams, it doesn't matter what line-endings your platform uses (whether carriage return (0x0D) + linefeed (0x0A), a bare CR, or a bare LF). The C runtime library will take care of that for you: your program will see just '\n' for newlines.

If you typed a character and pressed enter, then that input character would be read by line 1, and then '\n' would be read by line 2. See I'm using scanf %c to read a Y/N response, but later input gets skipped. from the comp.lang.c FAQ.

As for the proposed solutions, see (again from the comp.lang.c FAQ):

which basically state that the only portable approach is to do:

int c;
while ((c = getchar()) != '\n' && c != EOF) { }

Your getchar() != '\n' loop works because once you call getchar(), the returned character already has been removed from the input stream.

Also, I feel obligated to discourage you from using scanf entirely: Why does everyone say not to use scanf? What should I use instead?

Making heatmap from pandas DataFrame

Please note that the authors of seaborn only want seaborn.heatmap to work with categorical dataframes. It's not general.

If your index and columns are numeric and/or datetime values, this code will serve you well.

Matplotlib heat-mapping function pcolormesh requires bins instead of indices, so there is some fancy code to build bins from your dataframe indices (even if your index isn't evenly spaced!).

The rest is simply np.meshgrid and plt.pcolormesh.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

def conv_index_to_bins(index):
    """Calculate bins to contain the index values.
    The start and end bin boundaries are linearly extrapolated from 
    the two first and last values. The middle bin boundaries are 
    midpoints.

    Example 1: [0, 1] -> [-0.5, 0.5, 1.5]
    Example 2: [0, 1, 4] -> [-0.5, 0.5, 2.5, 5.5]
    Example 3: [4, 1, 0] -> [5.5, 2.5, 0.5, -0.5]"""
    assert index.is_monotonic_increasing or index.is_monotonic_decreasing

    # the beginning and end values are guessed from first and last two
    start = index[0] - (index[1]-index[0])/2
    end = index[-1] + (index[-1]-index[-2])/2

    # the middle values are the midpoints
    middle = pd.DataFrame({'m1': index[:-1], 'p1': index[1:]})
    middle = middle['m1'] + (middle['p1']-middle['m1'])/2

    if isinstance(index, pd.DatetimeIndex):
        idx = pd.DatetimeIndex(middle).union([start,end])
    elif isinstance(index, (pd.Float64Index,pd.RangeIndex,pd.Int64Index)):
        idx = pd.Float64Index(middle).union([start,end])
    else:
        print('Warning: guessing what to do with index type %s' % 
              type(index))
        idx = pd.Float64Index(middle).union([start,end])

    return idx.sort_values(ascending=index.is_monotonic_increasing)

def calc_df_mesh(df):
    """Calculate the two-dimensional bins to hold the index and 
    column values."""
    return np.meshgrid(conv_index_to_bins(df.index),
                       conv_index_to_bins(df.columns))

def heatmap(df):
    """Plot a heatmap of the dataframe values using the index and 
    columns"""
    X,Y = calc_df_mesh(df)
    c = plt.pcolormesh(X, Y, df.values.T)
    plt.colorbar(c)

Call it using heatmap(df), and see it using plt.show().

enter image description here

Error: "an object reference is required for the non-static field, method or property..."

Change your signatures to private static bool siprimo(long a) and private static long volteado(long a) and see where that gets you.

Mockito verify order / sequence of method calls

With BDD it's

@Test
public void testOrderWithBDD() {


    // Given
    ServiceClassA firstMock = mock(ServiceClassA.class);
    ServiceClassB secondMock = mock(ServiceClassB.class);

    //create inOrder object passing any mocks that need to be verified in order
    InOrder inOrder = inOrder(firstMock, secondMock);

    willDoNothing().given(firstMock).methodOne();
    willDoNothing().given(secondMock).methodTwo();

    // When
    firstMock.methodOne();
    secondMock.methodTwo();

    // Then
    then(firstMock).should(inOrder).methodOne();
    then(secondMock).should(inOrder).methodTwo();


}

How can I backup a remote SQL Server database to a local drive?

I know this is an older post, but for what it's worth, I've found that the "simplest" solution is to just right-click on the database, and select "Tasks" -> "Export Data-tier Application". It's possible that this option is only available because the server is hosted on Azure (from what I remember working with Azure in the past, the .bacpac format was quite common there).

Once that's done, you can right-click on your local server "Databases" list, and use the "Import Data-tier Application" to get the data to your local machine using the .bacpac file.

Just bear in mind the export could take a long time. Took roughly two hours for mine to finish exporting. Import part is much faster, though.

Set cursor position on contentEditable <div>

After playing around I've modified eyelidlessness' answer above and made it a jQuery plugin so you can just do one of these:

var html = "The quick brown fox";
$div.html(html);

// Select at the text "quick":
$div.setContentEditableSelection(4, 5);

// Select at the beginning of the contenteditable div:
$div.setContentEditableSelection(0);

// Select at the end of the contenteditable div:
$div.setContentEditableSelection(html.length);

Excuse the long code post, but it may help someone:

$.fn.setContentEditableSelection = function(position, length) {
    if (typeof(length) == "undefined") {
        length = 0;
    }

    return this.each(function() {
        var $this = $(this);
        var editable = this;
        var selection;
        var range;

        var html = $this.html();
        html = html.substring(0, position) +
            '<a id="cursorStart"></a>' +
            html.substring(position, position + length) +
            '<a id="cursorEnd"></a>' +
            html.substring(position + length, html.length);
        console.log(html);
        $this.html(html);

        // Populates selection and range variables
        var captureSelection = function(e) {
            // Don't capture selection outside editable region
            var isOrContainsAnchor = false,
                isOrContainsFocus = false,
                sel = window.getSelection(),
                parentAnchor = sel.anchorNode,
                parentFocus = sel.focusNode;

            while (parentAnchor && parentAnchor != document.documentElement) {
                if (parentAnchor == editable) {
                    isOrContainsAnchor = true;
                }
                parentAnchor = parentAnchor.parentNode;
            }

            while (parentFocus && parentFocus != document.documentElement) {
                if (parentFocus == editable) {
                    isOrContainsFocus = true;
                }
                parentFocus = parentFocus.parentNode;
            }

            if (!isOrContainsAnchor || !isOrContainsFocus) {
                return;
            }

            selection = window.getSelection();

            // Get range (standards)
            if (selection.getRangeAt !== undefined) {
                range = selection.getRangeAt(0);

                // Get range (Safari 2)
            } else if (
                document.createRange &&
                selection.anchorNode &&
                selection.anchorOffset &&
                selection.focusNode &&
                selection.focusOffset
            ) {
                range = document.createRange();
                range.setStart(selection.anchorNode, selection.anchorOffset);
                range.setEnd(selection.focusNode, selection.focusOffset);
            } else {
                // Failure here, not handled by the rest of the script.
                // Probably IE or some older browser
            }
        };

        // Slight delay will avoid the initial selection
        // (at start or of contents depending on browser) being mistaken
        setTimeout(function() {
            var cursorStart = document.getElementById('cursorStart');
            var cursorEnd = document.getElementById('cursorEnd');

            // Don't do anything if user is creating a new selection
            if (editable.className.match(/\sselecting(\s|$)/)) {
                if (cursorStart) {
                    cursorStart.parentNode.removeChild(cursorStart);
                }
                if (cursorEnd) {
                    cursorEnd.parentNode.removeChild(cursorEnd);
                }
            } else if (cursorStart) {
                captureSelection();
                range = document.createRange();

                if (cursorEnd) {
                    range.setStartAfter(cursorStart);
                    range.setEndBefore(cursorEnd);

                    // Delete cursor markers
                    cursorStart.parentNode.removeChild(cursorStart);
                    cursorEnd.parentNode.removeChild(cursorEnd);

                    // Select range
                    selection.removeAllRanges();
                    selection.addRange(range);
                } else {
                    range.selectNode(cursorStart);

                    // Select range
                    selection.removeAllRanges();
                    selection.addRange(range);

                    // Delete cursor marker
                    document.execCommand('delete', false, null);
                }
            }

            // Register selection again
            captureSelection();
        }, 10);
    });
};

What are the lengths of Location Coordinates, latitude and longitude?

The ideal datatype for storing Lat Long values in SQL Server is decimal(9,6)

As others have said, this is at approximately 10cm precision, whilst only using 5 bytes of storage.

e.g. CAST(123.456789 as decimal(9,6)) as [LatOrLong]

Prevent redirect after form is submitted

Since it is bypassing CORS and CSP, this is to keep in the toolbox. Here is a variation.

This will POST a base64 encoded object at localhost:8080, and will clean up the DOM after usage.

_x000D_
_x000D_
const theOBJECT = {message: 'Hello world!', target: 'local'}_x000D_
_x000D_
document.body.innerHTML += '<iframe id="postframe" name="hiddenFrame" width="0" height="0" border="0" style="display: none;"></iframe><form id="dynForm" target="hiddenFrame" action="http://localhost:8080/" method="post"><input type="hidden" name="somedata" value="'+btoa(JSON.stringify(theOBJECT))+'"></form>';_x000D_
document.getElementById("dynForm").submit();_x000D_
dynForm.outerHTML = ""_x000D_
postframe.outerHTML = ""
_x000D_
_x000D_
_x000D_

From the network debugger tab, we can observe a successful POST to a http:// unencrypted server from a tls/https page.

enter image description here

Replace transparency in PNG images with white background

Welp it looks like my decision to install "graphics magick" over "image magick" has some rough edges - when I reinstall genuine crufty old "image magick", then the above command works perfectly well.

edit, a long time later — One of these days I'll check to see if "graphics magick" has fixed this issue.

urlencode vs rawurlencode?

echo rawurlencode('http://www.google.com/index.html?id=asd asd');

yields

http%3A%2F%2Fwww.google.com%2Findex.html%3Fid%3Dasd%20asd

while

echo urlencode('http://www.google.com/index.html?id=asd asd');

yields

http%3A%2F%2Fwww.google.com%2Findex.html%3Fid%3Dasd+asd

The difference being the asd%20asd vs asd+asd

urlencode differs from RFC 1738 by encoding spaces as + instead of %20

Renaming Columns in an SQL SELECT Statement

select column1 as xyz,
      column2 as pqr,
.....

from TableName;

How to zip a whole folder using PHP

Code updated 2015/04/22.

Zip a whole folder:

// Get real path for our folder
$rootPath = realpath('folder-to-zip');

// Initialize archive object
$zip = new ZipArchive();
$zip->open('file.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);

// Create recursive directory iterator
/** @var SplFileInfo[] $files */
$files = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($rootPath),
    RecursiveIteratorIterator::LEAVES_ONLY
);

foreach ($files as $name => $file)
{
    // Skip directories (they would be added automatically)
    if (!$file->isDir())
    {
        // Get real and relative path for current file
        $filePath = $file->getRealPath();
        $relativePath = substr($filePath, strlen($rootPath) + 1);

        // Add current file to archive
        $zip->addFile($filePath, $relativePath);
    }
}

// Zip archive will be created only after closing object
$zip->close();

Zip a whole folder + delete all files except "important.txt":

// Get real path for our folder
$rootPath = realpath('folder-to-zip');

// Initialize archive object
$zip = new ZipArchive();
$zip->open('file.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);

// Initialize empty "delete list"
$filesToDelete = array();

// Create recursive directory iterator
/** @var SplFileInfo[] $files */
$files = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($rootPath),
    RecursiveIteratorIterator::LEAVES_ONLY
);

foreach ($files as $name => $file)
{
    // Skip directories (they would be added automatically)
    if (!$file->isDir())
    {
        // Get real and relative path for current file
        $filePath = $file->getRealPath();
        $relativePath = substr($filePath, strlen($rootPath) + 1);

        // Add current file to archive
        $zip->addFile($filePath, $relativePath);

        // Add current file to "delete list"
        // delete it later cause ZipArchive create archive only after calling close function and ZipArchive lock files until archive created)
        if ($file->getFilename() != 'important.txt')
        {
            $filesToDelete[] = $filePath;
        }
    }
}

// Zip archive will be created only after closing object
$zip->close();

// Delete all files from "delete list"
foreach ($filesToDelete as $file)
{
    unlink($file);
}

How to create materialized views in SQL Server?

When indexed view is not an option, and quick updates are not necessary, you can create a hack cache table:

select * into cachetablename from myviewname
alter table cachetablename add primary key (columns)
-- OR alter table cachetablename add rid bigint identity primary key
create index...

then sp_rename view/table or change any queries or other views that reference it to point to the cache table.

schedule daily/nightly/weekly/whatnot refresh like

begin transaction
truncate table cachetablename
insert into cachetablename select * from viewname
commit transaction

NB: this will eat space, also in your tx logs. Best used for small datasets that are slow to compute. Maybe refactor to eliminate "easy but large" columns first into an outer view.

HTML "overlay" which allows clicks to fall through to elements behind it

A silly hack I did was to set the height of the element to zero but overflow:visible; combining this with pointer-events:none; seems to cover all the bases.

.overlay {
    height:0px;
    overflow:visible;
    pointer-events:none;
    background:none !important;
}

Limiting floats to two decimal points

from decimal import Decimal


def round_float(v, ndigits=2, rt_str=False):
    d = Decimal(v)
    v_str = ("{0:.%sf}" % ndigits).format(round(d, ndigits))
    if rt_str:
        return v_str
    return Decimal(v_str)

Results:

Python 3.6.1 (default, Dec 11 2018, 17:41:10)
>>> round_float(3.1415926)
Decimal('3.14')
>>> round_float(3.1445926)
Decimal('3.14')
>>> round_float(3.1455926)
Decimal('3.15')
>>> round_float(3.1455926, rt_str=True)
'3.15'
>>> str(round_float(3.1455926))
'3.15'

CSS rounded corners in IE8

As Internet Explorer doesn't natively support rounded corners. So a better cross-browser way to handle it would be to use rounded-corner images at the corners. Many famous websites use this approach.

You can also find rounded image generators around the web. One such link is http://www.generateit.net/rounded-corner/

Python get current time in right timezone

To get the current time in the local timezone as a naive datetime object:

from datetime import datetime
naive_dt = datetime.now()

If it doesn't return the expected time then it means that your computer is misconfigured. You should fix it first (it is unrelated to Python).

To get the current time in UTC as a naive datetime object:

naive_utc_dt = datetime.utcnow()

To get the current time as an aware datetime object in Python 3.3+:

from datetime import datetime, timezone

utc_dt = datetime.now(timezone.utc) # UTC time
dt = utc_dt.astimezone() # local time

To get the current time in the given time zone from the tz database:

import pytz

tz = pytz.timezone('Europe/Berlin')
berlin_now = datetime.now(tz)

It works during DST transitions. It works if the timezone had different UTC offset in the past i.e., it works even if the timezone corresponds to multiple tzinfo objects at different times.

segmentation fault : 11

Run your program with valgrind of linked to efence. That will tell you where the pointer is being dereferenced and most likely fix your problem if you fix all the errors they tell you about.

How to fix the session_register() deprecated issue?

before PHP 5.3

session_register("name");

since PHP 5.3

$_SESSION['name'] = $name;

Big-O summary for Java Collections Framework implementations?

The Javadocs from Sun for each collection class will generally tell you exactly what you want. HashMap, for example:

This implementation provides constant-time performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets. Iteration over collection views requires time proportional to the "capacity" of the HashMap instance (the number of buckets) plus its size (the number of key-value mappings).

TreeMap:

This implementation provides guaranteed log(n) time cost for the containsKey, get, put and remove operations.

TreeSet:

This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains).

(emphasis mine)

jQuery UI Alert Dialog as a replacement for alert()

Just throw an empty, hidden div onto your html page and give it an ID. Then you can use that for your jQuery UI dialog. You can populate the text just like you normally would with any jquery call.

"id cannot be resolved or is not a field" error?

In main.xml (or wherever your item is defined) make sure that the ID for the R item is defined with @+id/... Here is an example with a button:

<Button android:text="B1" android:id="@+id/button_one"
        android:layout_gravity="center_horizontal|center"
        android:layout_height="fill_parent" android:layout_width="wrap_content" />

Each of these is important because:

  • @ must precede the string
  • + indicates it will create if not existing (whatever your item is)

Why can't Python import Image from PIL?

Install Pillow from Command Line:

python -m pip install pillow

Get the second largest number in a list in linear time

You could always use sorted

>>> sorted(numbers)[-2]
74

Early exit from function?

if you are looking for a script to avoid submitting form when some errors found, this method should work

function verifyData(){
     if (document.MyForm.FormInput.value.length == "") {
          alert("Write something!");
     }
     else {
          document.MyForm.submit();
     }
}

change the Submit Button type to "button"

<input value="Save" type="button" onClick="verifyData()">

hope this help.

How to group subarrays by a column value?

function array_group_by($arr, array $keys) {

if (!is_array($arr)) {
    trigger_error('array_group_by(): The first argument should be an array', E_USER_ERROR);
}
if (count($keys)==0) {
    trigger_error('array_group_by(): The Second argument Array can not be empty', E_USER_ERROR);
}

// Load the new array, splitting by the target key
$grouped = [];
foreach ($arr as $value) {
    $grouped[$value[$keys[0]]][] = $value;
}

// Recursively build a nested grouping if more parameters are supplied
// Each grouped array value is grouped according to the next sequential key
if (count($keys) > 1) {
        foreach ($grouped as $key => $value) {
       $parms = array_merge([$value], [array_slice($keys, 1,count($keys))]);
       $grouped[$key] = call_user_func_array('array_group_by', $parms);

    }
}
return $grouped;

}

Unable to establish SSL connection upon wget on Ubuntu 14.04 LTS

Although this is almost certainly not the OPs issue, you can also get Unable to establish SSL connection from wget if you're behind a proxy and don't have HTTP_PROXY and HTTPS_PROXY environment variables set correctly. Make sure to set HTTP_PROXY and HTTPS_PROXY to point to your proxy.

This is a common situation if you work for a large corporation.

How to import CSV file data into a PostgreSQL table?

As Paul mentioned, import works in pgAdmin:

right click on table -> import

select local file, format and coding

here is a german pgAdmin GUI screenshot:

pgAdmin import GUI

similar thing you can do with DbVisualizer (I have a license, not sure about free version)

right click on a table -> Import Table Data...

DbVisualizer import GUI

Passing an array/list into a Python function

def sumlist(items=[]):
    sum = 0
    for i in items:
        sum += i

    return sum

t=sumlist([2,4,8,1])
print(t)

VBA Check if variable is empty

How you test depends on the Property's DataType:

| Type                                 | Test                            | Test2
| Numeric (Long, Integer, Double etc.) | If obj.Property = 0 Then        | 
| Boolen (True/False)                  | If Not obj.Property Then        | If obj.Property = False Then
| Object                               | If obj.Property Is Nothing Then |
| String                               | If obj.Property = "" Then       | If LenB(obj.Property) = 0 Then
| Variant                              | If obj.Property = Empty Then    |

You can tell the DataType by pressing F2 to launch the Object Browser and looking up the Object. Another way would be to just use the TypeName function:MsgBox TypeName(obj.Property)

How do you echo a 4-digit Unicode character in Bash?

In UTF-8 it's actually 6 digits (or 3 bytes).

$ printf '\xE2\x98\xA0'
?

To check how it's encoded by the console, use hexdump:

$ printf ? | hexdump
0000000 98e2 00a0                              
0000003

What is the difference between explicit and implicit cursors in Oracle?

Every SQL statement executed by the Oracle database has a cursor associated with it, which is a private work area to store processing information. Implicit cursors are implicitly created by the Oracle server for all DML and SELECT statements.

You can declare and use Explicit cursors to name the private work area, and access its stored information in your program block.

Form onSubmit determine which submit button was pressed

OP stated he didn't want to modify the code for the buttons. This is the least-intrusive answer I could come up with using the other answers as a guide. It doesn't require additional hidden fields, allows you to leave the button code intact (sometimes you don't have access to what generates it), and gives you the info you were looking for from anywhere in your code...which button was used to submit the form. I haven't evaluated what happens if the user uses the Enter key to submit the form, rather than clicking.

<script language="javascript" type="text/javascript">

    var initiator = '';
    $(document).ready(function() {
        $(":submit").click(function() { initiator = this.name });
    });

</script>

Then you have access to the 'initiator' variable anywhere that might need to do the checking. Hope this helps.

~Spanky

Store query result in a variable using in PL/pgSQL

As long as you are assigning a single variable, you can also use plain assignment in a plpgsql function:

name := (SELECT t.name from test_table t where t.id = x);

Or use SELECT INTO like @mu already provided.

This works, too:

name := t.name from test_table t where t.id = x;

But better use one of the first two, clearer methods, as @Pavel commented.

I shortened the syntax with a table alias additionally.
Update: I removed my code example and suggest to use IF EXISTS() instead like provided by @Pavel.

jQuery $.ajax(), $.post sending "OPTIONS" as REQUEST_METHOD in Firefox

I have posted a clear example of how to solve this if control the server code of the domain you are POSTing to. This answer is touched on in this thread, but this more clearly explains it IMO.

How do I send a cross-domain POST request via JavaScript?

Where does Chrome store cookies?

Since the expiration time is zero (the third argument, the first false) the cookie is a session cookie, which will expire when the current session ends. (See the setcookie reference).

Therefore it doesn't need to be saved.

Command line to remove an environment variable from the OS level configuration

To remove the variable from the current command session without removing it permanently, use the regular built-in set command - just put nothing after the equals sign:

set FOOBAR=

To confirm, run set with no arguments and check the current environment. The variable should be missing from the list entirely.

Note: this will only remove the variable from the current environment - it will not persist the change to the registry. When a new command process is started, the variable will be back.

How to pass arguments to addEventListener listener function?

someVar value should be accessible only in some_function() context, not from listener's. If you like to have it within listener, you must do something like:

someObj.addEventListener("click",
                         function(){
                             var newVar = someVar;
                             some_function(someVar);
                         },
                         false);

and use newVar instead.

The other way is to return someVar value from some_function() for using it further in listener (as a new local var):

var someVar = some_function(someVar);

Trying to use fetch and pass in mode: no-cors

So if you're like me and developing a website on localhost where you're trying to fetch data from Laravel API and use it in your Vue front-end, and you see this problem, here is how I solved it:

  1. In your Laravel project, run command php artisan make:middleware Cors. This will create app/Http/Middleware/Cors.php for you.
  2. Add the following code inside the handles function in Cors.php:

    return $next($request)
        ->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    
  3. In app/Http/kernel.php, add the following entry in $routeMiddleware array:

    ‘cors’ => \App\Http\Middleware\Cors::class
    

    (There would be other entries in the array like auth, guest etc. Also make sure you're doing this in app/Http/kernel.php because there is another kernel.php too in Laravel)

  4. Add this middleware on route registration for all the routes where you want to allow access, like this:

    Route::group(['middleware' => 'cors'], function () {
        Route::get('getData', 'v1\MyController@getData');
        Route::get('getData2', 'v1\MyController@getData2');
    });
    
  5. In Vue front-end, make sure you call this API in mounted() function and not in data(). Also make sure you use http:// or https:// with the URL in your fetch() call.

Full credits to Pete Houston's blog article.

Rails: How to list database tables/objects using the Rails console?

To get a list of all model classes, you can use ActiveRecord::Base.subclasses e.g.

ActiveRecord::Base.subclasses.map { |cl| cl.name }
ActiveRecord::Base.subclasses.find { |cl| cl.name == "Foo" }

How to check if a float value is a whole number

The above answers work for many cases but they miss some. Consider the following:

fl = sum([0.1]*10)  # this is 0.9999999999999999, but we want to say it IS an int

Using this as a benchmark, some of the other suggestions don't get the behavior we might want:

fl.is_integer() # False

fl % 1 == 0     # False

Instead try:

def isclose(a, b, rel_tol=1e-09, abs_tol=0.0):
    return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)

def is_integer(fl):
    return isclose(fl, round(fl))

now we get:

is_integer(fl)   # True

isclose comes with Python 3.5+, and for other Python's you can use this mostly equivalent definition (as mentioned in the corresponding PEP)