Programs & Examples On #Django uploads

Django-uploads refers to how django handles file uploads

How to force C# .net app to run only one instance in Windows?

I prefer a mutex solution similar to the following. As this way it re-focuses on the app if it is already loaded

using System.Threading;

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);

/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
   bool createdNew = true;
   using (Mutex mutex = new Mutex(true, "MyApplicationName", out createdNew))
   {
      if (createdNew)
      {
         Application.EnableVisualStyles();
         Application.SetCompatibleTextRenderingDefault(false);
         Application.Run(new MainForm());
      }
      else
      {
         Process current = Process.GetCurrentProcess();
         foreach (Process process in Process.GetProcessesByName(current.ProcessName))
         {
            if (process.Id != current.Id)
            {
               SetForegroundWindow(process.MainWindowHandle);
               break;
            }
         }
      }
   }
}

How to ignore ansible SSH authenticity checking?

If you don't want to modify ansible.cfg or the playbook.yml then you can just set an environment variable:

export ANSIBLE_HOST_KEY_CHECKING=False

How to apply slide animation between two activities in Android?

Slide animation can be applied to activity transitions by calling overridePendingTransition and passing animation resources for enter and exit activities.

Slide animations can be slid right, slide left, slide up and slide down.

Slide up

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/linear_interpolator">
    <scale
        android:duration="800"
        android:fromXScale="1.0"
        android:fromYScale="1.0"
        android:toXScale="1.0"
        android:toYScale="0.0" />
</set>

Slide down

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/linear_interpolator">
    <scale
        android:duration="800"
        android:fromXScale="1.0"
        android:fromYScale="0.0"
        android:toXScale="1.0"
        android:toYScale="1.0" />
</set>

overridePendingTransition(R.anim.slide_down, R.anim.slide_up);

See activity transition animation examples for more activity transition examples.

Merging two images in C#/.NET

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

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

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

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

How to get longitude and latitude of any address?

Use the following code for getting lat and long using php. Here are two methods:

Type-1:

    <?php
     // Get lat and long by address         
        $address = $dlocation; // Google HQ
        $prepAddr = str_replace(' ','+',$address);
        $geocode=file_get_contents('https://maps.google.com/maps/api/geocode/json?address='.$prepAddr.'&sensor=false');
        $output= json_decode($geocode);
        $latitude = $output->results[0]->geometry->location->lat;
        $longitude = $output->results[0]->geometry->location->lng;

?>

edit - Google Maps requests must be over https

Type-2:

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
     <script>
      var geocoder;
      var map;
      function initialize() {
        geocoder = new google.maps.Geocoder();
         var latlng = new google.maps.LatLng(50.804400, -1.147250);
        var mapOptions = {
         zoom: 6,
         center: latlng
        }
         map = new google.maps.Map(document.getElementById('map-canvas12'), mapOptions);
        }

       function codeAddress(address,tutorname,url,distance,prise,postcode) {
       var address = address;

        geocoder.geocode( { 'address': address}, function(results, status) {
         if (status == google.maps.GeocoderStatus.OK) {
          map.setCenter(results[0].geometry.location);
           var marker = new google.maps.Marker({
          map: map,
          position: results[0].geometry.location
      });

      var infowindow = new google.maps.InfoWindow({
         content: 'Tutor Name: '+tutorname+'<br>Price Guide: '+prise+'<br>Distance: '+distance+' Miles from you('+postcode+')<br> <a href="'+url+'" target="blank">View Tutor profile</a> '
       });
        infowindow.open(map,marker);

          } /*else {
          alert('Geocode was not successful for the following reason: ' + status);
        }*/
       });
     }


      google.maps.event.addDomListener(window, 'load', initialize);

     window.onload = function(){
      initialize();
      // your code here
      <?php foreach($addr as $add) { 

      ?>
      codeAddress('<?php echo $add['address']; ?>','<?php echo $add['tutorname']; ?>','<?php echo $add['url']; ?>','<?php echo $add['distance']; ?>','<?php echo $add['prise']; ?>','<?php echo substr( $postcode1,0,4); ?>');
      <?php } ?>
    };
      </script>

     <div id="map-canvas12"></div>

How to change color of ListView items on focus and on click

The child views in your list row should be considered selected whenever the parent row is selected, so you should be able to just set a normal state drawable/color-list on the views you want to change, no messy Java code necessary. See this SO post.

Specifically, you'd set the textColor of your textViews to an XML resource like this one:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true" android:drawable="@color/black" /> <!-- focused -->
    <item android:state_focused="true" android:state_pressed="true" android:drawable="@color/black" /> <!-- focused and pressed-->
    <item android:state_pressed="true" android:drawable="@color/green" /> <!-- pressed -->
    <item android:drawable="@color/black" /> <!-- default -->
</selector> 

jquery validate check at least one checkbox

Example from https://github.com/ffmike/jquery-validate

 <label for="spam_email">
     <input type="checkbox" class="checkbox" id="spam_email" value="email" name="spam[]" validate="required:true, minlength:2" /> Spam via E-Mail </label>
 <label for="spam_phone">
     <input type="checkbox" class="checkbox" id="spam_phone" value="phone" name="spam[]" /> Spam via Phone </label>
 <label for="spam_mail">
     <input type="checkbox" class="checkbox" id="spam_mail" value="mail" name="spam[]" /> Spam via Mail </label>
 <label for="spam[]" class="error">Please select at least two types of spam.</label>

The same without field "validate" in tags only using javascript:

$("#testform").validate({ 
    rules: { 
            "spam[]": { 
                    required: true, 
                    minlength: 1 
            } 
    }, 
    messages: { 
            "spam[]": "Please select at least two types of spam."
    } 
}); 

And if you need different names for inputs, you can use somethig like this:

<input type="hidden" name="spam" id="spam"/>
<label for="spam_phone">
    <input type="checkbox" class="checkbox" id="spam_phone" value="phone" name="spam_phone" /> Spam via Phone</label>
<label for="spam_mail">
    <input type="checkbox" class="checkbox" id="spam_mail" value="mail" name="spam_mail" /> Spam via Mail </label>

Javascript:

 $("#testform").validate({ 
    rules: { 
        spam: { 
            required: function (element) {
                var boxes = $('.checkbox');
                if (boxes.filter(':checked').length == 0) {
                    return true;
                }
                return false;
            },
            minlength: 1 
        } 
    }, 
    messages: { 
            spam: "Please select at least two types of spam."
    } 
}); 

I have added hidden input before inputs and setting it to "required" if there is no selected checkboxes

Create sequence of repeated values, in sequence?

You missed the each= argument to rep():

R> n <- 3
R> rep(1:5, each=n)
 [1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5
R> 

so your example can be done with a simple

R> rep(1:8, each=20)

Function to convert timestamp to human date in javascript

Moment.js can convert unix timestamps into any custom format

In this case : var time = moment(1382086394000).format("DD-MM-YYYY h:mm:ss");

will print 18-10-2013 11:53:14;

Here's a plunker that demonstrates this.

Check if a string is palindrome

bool IsPalindrome(const char* psz)
{
    int i = 0;
    int j;

    if ((psz == NULL) || (psz[0] == '\0'))
    {
        return false;
    }

    j = strlen(psz) - 1;
    while (i < j)
    {
        if (psz[i] != psz[j])
        {
            return false;
        }
        i++;
        j--;
    }
    return true;

}

// STL string version:

bool IsPalindrome(const string& str)
{
    if (str.empty())
        return false;

    int i = 0;                // first characters
    int j = str.length() - 1; // last character

    while (i < j)
    {
        if (str[i] != str[j])
        {
            return false;
        }
        i++;
        j--;
    }
    return true;
}

How to change an Eclipse default project into a Java project

  1. Right click on project
  2. Configure -> 'Convert to Faceted Form'
  3. You will get a popup, Select 'Java' in 'Project Facet' column.
  4. Press Apply and Ok.

Split a string by another string in C#

In order to split by a string you'll have to use the string array overload.

string data = "THExxQUICKxxBROWNxxFOX";

return data.Split(new string[] { "xx" }, StringSplitOptions.None);

Getting request URL in a servlet

The getRequestURL() omits the port when it is 80 while the scheme is http, or when it is 443 while the scheme is https.

So, just use getRequestURL() if all you want is obtaining the entire URL. This does however not include the GET query string. You may want to construct it as follows then:

StringBuffer requestURL = request.getRequestURL();
if (request.getQueryString() != null) {
    requestURL.append("?").append(request.getQueryString());
}
String completeURL = requestURL.toString();

When should I use Kruskal as opposed to Prim (and vice versa)?

The best time for Kruskal's is O(E logV). For Prim's using fib heaps we can get O(E+V lgV). Therefore on a dense graph, Prim's is much better.

Java default constructor

A default constructor does not take any arguments:

public class Student { 
    // default constructor
    public Student() {   

    }
}

System.BadImageFormatException An attempt was made to load a program with an incorrect format

I had the same issue when getting my software running on another machine. On my developer pc (Windows 7), I had Visual Studio 2015 installed, the target pc was a clean installation of Windows 10 (.Net installed). I also tested it on another clean Windows 7 pc including .Net Framework. However, on both target pc's I needed to install the Visual C++ Redistributable for Visual Studio 2015 package for x86 or x64 (depends on what your application is build for). That was already installed on my developer pc.

My application was using a C library, which has been compiled to a C++ application using /clr and /TP options in visual studio. Also the application was providing functions to C# by using dllexport method signatures. Not sure if the C# integration leaded to give me that error or if a C++ application would have given me the same.

Hope it helps anybody.

Most concise way to convert a Set<T> to a List<T>

Try this for Set:

Set<String> listOfTopicAuthors = .....
List<String> setList = new ArrayList<String>(listOfTopicAuthors); 

Try this for Map:

Map<String, String> listOfTopicAuthors = .....
// List of values:
List<String> mapValueList = new ArrayList<String>(listOfTopicAuthors.values());
// List of keys:
List<String> mapKeyList = new ArrayList<String>(listOfTopicAuthors.KeySet());

How should I use Outlook to send code snippets?

When I paste code into Outlook or have sentences containing code or technical syntax I get annoyed by all of the red squiggles that identify spelling errors. If you want Outlook to clear all of the red spellcheck squiggles you can add a button to the Quick Access Toolbar that calls a VBA macro and removes all squiggles from the current document.

I prefer to run this macro separate from my style choice because I often use it on a selection of text that has mixed content.

For syntax highlighting I use the Notepad++ technique already listed by @srujanreddy, though I discovered that the right-click context menu option a bit handier than navigating the Plugins menu.

Image showing you can right-click on selected text and choose to copy text with syntax highlighting

If you get annoyed by spell check while you are preparing your email you can add a button to your quick access toolbar that will remove the red squiggles from the message body.
See this article: https://stackoverflow.com/a/49865743/1898524

Remove Spell Check Squiggles

Algorithm for solving Sudoku

Here is a much faster solution based on hari's answer. The basic difference is that we keep a set of possible values for cells that don't have a value assigned. So when we try a new value, we only try valid values and we also propagate what this choice means for the rest of the sudoku. In the propagation step, we remove from the set of valid values for each cell the values that already appear in the row, column, or the same block. If only one number is left in the set, we know that the position (cell) has to have that value.

This method is known as forward checking and look ahead (http://ktiml.mff.cuni.cz/~bartak/constraints/propagation.html).

The implementation below needs one iteration (calls of solve) while hari's implementation needs 487. Of course my code is a bit longer. The propagate method is also not optimal.

import sys
from copy import deepcopy

def output(a):
    sys.stdout.write(str(a))

N = 9

field = [[5,1,7,6,0,0,0,3,4],
         [2,8,9,0,0,4,0,0,0],
         [3,4,6,2,0,5,0,9,0],
         [6,0,2,0,0,0,0,1,0],
         [0,3,8,0,0,6,0,4,7],
         [0,0,0,0,0,0,0,0,0],
         [0,9,0,0,0,0,0,7,8],
         [7,0,3,4,0,0,5,6,0],
         [0,0,0,0,0,0,0,0,0]]

def print_field(field):
    if not field:
        output("No solution")
        return
    for i in range(N):
        for j in range(N):
            cell = field[i][j]
            if cell == 0 or isinstance(cell, set):
                output('.')
            else:
                output(cell)
            if (j + 1) % 3 == 0 and j < 8:
                output(' |')

            if j != 8:
                output(' ')
        output('\n')
        if (i + 1) % 3 == 0 and i < 8:
            output("- - - + - - - + - - -\n")

def read(field):
    """ Read field into state (replace 0 with set of possible values) """

    state = deepcopy(field)
    for i in range(N):
        for j in range(N):
            cell = state[i][j]
            if cell == 0:
                state[i][j] = set(range(1,10))

    return state

state = read(field)


def done(state):
    """ Are we done? """

    for row in state:
        for cell in row:
            if isinstance(cell, set):
                return False
    return True


def propagate_step(state):
    """
    Propagate one step.

    @return:  A two-tuple that says whether the configuration
              is solvable and whether the propagation changed
              the state.
    """

            new_units = False

    # propagate row rule
    for i in range(N):
        row = state[i]
        values = set([x for x in row if not isinstance(x, set)])
        for j in range(N):
            if isinstance(state[i][j], set):
                state[i][j] -= values
                if len(state[i][j]) == 1:
                    val = state[i][j].pop()
                    state[i][j] = val
                    values.add(val)
                    new_units = True
                elif len(state[i][j]) == 0:
                    return False, None

    # propagate column rule
    for j in range(N):
        column = [state[x][j] for x in range(N)]
        values = set([x for x in column if not isinstance(x, set)])
        for i in range(N):
            if isinstance(state[i][j], set):
                state[i][j] -= values
                if len(state[i][j]) == 1:
                    val = state[i][j].pop()
                    state[i][j] = val
                    values.add(val)
                    new_units = True
                elif len(state[i][j]) == 0:
                    return False, None

    # propagate cell rule
    for x in range(3):
        for y in range(3):
            values = set()
            for i in range(3 * x, 3 * x + 3):
                for j in range(3 * y, 3 * y + 3):
                    cell = state[i][j]
                    if not isinstance(cell, set):
                        values.add(cell)
            for i in range(3 * x, 3 * x + 3):
                for j in range(3 * y, 3 * y + 3):
                    if isinstance(state[i][j], set):
                        state[i][j] -= values
                        if len(state[i][j]) == 1:
                            val = state[i][j].pop()
                            state[i][j] = val
                            values.add(val)
                            new_units = True
                        elif len(state[i][j]) == 0:
                            return False, None

    return True, new_units

def propagate(state):
    """ Propagate until we reach a fixpoint """
    while True:
        solvable, new_unit = propagate_step(state)
        if not solvable:
            return False
        if not new_unit:
            return True


def solve(state):
    """ Solve sudoku """

    solvable = propagate(state)

    if not solvable:
        return None

    if done(state):
        return state

    for i in range(N):
        for j in range(N):
            cell = state[i][j]
            if isinstance(cell, set):
                for value in cell:
                    new_state = deepcopy(state)
                    new_state[i][j] = value
                    solved = solve(new_state)
                    if solved is not None:
                        return solved
                return None

print_field(solve(state))

Apache default VirtualHost

The other answers here didn't work for me, but I found a pretty simple solution that did work.

I made the default one the last one listed, and I gave it ServerAlias *.

For example:

NameVirtualHost *:80

<VirtualHost *:80>
    ServerName www.secondwebsite.com
    ServerAlias secondwebsite.com *.secondwebsite.com
    DocumentRoot /home/secondwebsite/web
</VirtualHost>

<VirtualHost *:80>
    ServerName www.defaultwebsite.com
    ServerAlias *
    DocumentRoot /home/defaultwebsite/web
</VirtualHost>

If the visitor didn't explicitly choose to go to something ending in secondwebsite.com, they get the default website.

Convert Java object to XML string

Here is a util class for marshaling and unmarshaling objects. In my case it was a nested class, so I made it static JAXBUtils.

import javax.xml.bind.JAXB;
import java.io.StringReader;
import java.io.StringWriter;

public class JAXBUtils
{
    /**
     * Unmarshal an XML string
     * @param xml     The XML string
     * @param type    The JAXB class type.
     * @return The unmarshalled object.
     */
    public <T> T unmarshal(String xml, Class<T> type)
    {
        StringReader reader = new StringReader(xml);
        return javax.xml.bind.JAXB.unmarshal(reader, type);
    }

    /**
     * Marshal an Object to XML.
     * @param object    The object to marshal.
     * @return The XML string representation of the object.
     */
    public String marshal(Object object)
    {
        StringWriter stringWriter = new StringWriter();
        JAXB.marshal(object, stringWriter);
        return stringWriter.toString();
    }
}

Regex any ASCII character

Try using .+ instead of [(\w)(\W)(\s)]+.

Note that this actually includes more than you need - ASCII only defines the first 128 characters.

Calling another different view from the controller using ASP.NET MVC 4

To return a different view, you can specify the name of the view you want to return and model as follows:

return View("ViewName", yourModel);

if the view is in different folder under Views folder then use below absolute path:

return View("~/Views/FolderName/ViewName.aspx");

Print a file's last modified date in Bash

EDITED: turns out that I had forgotten the quotes needed for $entry in order to print correctly and not give the "no such file or directory" error. Thank you all so much for helping me!

Here is my final code:

    echo "Please type in the directory you want all the files to be listed with last modified dates" #bash can't find file creation dates

read directory

for entry in "$directory"/*

do
modDate=$(stat -c %y "$entry") #%y = last modified. Qoutes are needed otherwise spaces in file name with give error of "no such file"
modDate=${modDate%% *} #%% takes off everything off the string after the date to make it look pretty
echo $entry:$modDate

Prints out like this:

/home/joanne/Dropbox/cheat sheet.docx:2012-03-14
/home/joanne/Dropbox/Comp:2013-05-05
/home/joanne/Dropbox/Comp 150 java.zip:2013-02-11
/home/joanne/Dropbox/Comp 151 Java 2.zip:2013-02-11
/home/joanne/Dropbox/Comp 162 Assembly Language.zip:2013-02-11
/home/joanne/Dropbox/Comp 262 Comp Architecture.zip:2012-12-12
/home/joanne/Dropbox/Comp 345 Image Processing.zip:2013-02-11
/home/joanne/Dropbox/Comp 362 Operating Systems:2013-05-05
/home/joanne/Dropbox/Comp 447 Societal Issues.zip:2013-02-11

Unable to open project... cannot be opened because the project file cannot be parsed

Goto PhoneGapTest>>platform Then delete the folder ios after that go to terminal then type: sudo phonegap build ios after that you can run the project

String MinLength and MaxLength validation don't work (asp.net mvc)

This can replace the MaxLength and the MinLength

[StringLength(40, MinimumLength = 10 , ErrorMessage = "Password cannot be longer than 40 characters and less than 10 characters")]

AttributeError: 'str' object has no attribute 'strftime'

You should use datetime object, not str.

>>> from datetime import datetime
>>> cr_date = datetime(2013, 10, 31, 18, 23, 29, 227)
>>> cr_date.strftime('%m/%d/%Y')
'10/31/2013'

To get the datetime object from the string, use datetime.datetime.strptime:

>>> datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f')
datetime.datetime(2013, 10, 31, 18, 23, 29, 227)
>>> datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f').strftime('%m/%d/%Y')
'10/31/2013'

How to determine the encoding of text?

It is, in principle, impossible to determine the encoding of a text file, in the general case. So no, there is no standard Python library to do that for you.

If you have more specific knowledge about the text file (e.g. that it is XML), there might be library functions.

How can I get the image url in a Wordpress theme?

If your img folder is inside your theme folder, just follow the example below:

<img src="<?php echo  get_theme_file_uri(); ?>/img/yourimagename.jpg" class="story-img" alt="your alt text">

Kotlin Android start new Activity

Remember to add the activity you want to present, to your AndroidManifest.xml too :-) That was the issue for me.

Fast query runs slow in SSRS

I had the report html output trouble on report retrieving 32000 lines. The query ran fast but the output into web browser was very slow. In my case I had to activate “Interactive Paging” to allow user to see first page and be able to generate Excel file. The pros of this solution is that first page appears fast and user can generate export to Excel or PDF, the cons is that user can scroll only current page. If user wants to see more content he\she must use navigation buttons above the grid. In my case user accepted this behavior because the export to Excel was more important.

To activate “Interactive Paging” you must click on the free area in the report pane and change property “InteractiveSize”\ “Height” on the report level in Properties pane. Set this property to different from 0. I set to 8.5 inches in my case. Also ensure that you unchecked “Keep together on one page if possible” property on the Tablix level (right click on the Tablix, then “Tablix Properties”, then “General”\ “Page Break Options”).

enter image description here

Changing the action of a form with JavaScript/jQuery

jQuery (1.4.2) gets confused if you have any form elements named "action". You can get around this by using the DOM attribute methods or simply avoid having form elements named "action".

<form action="foo">
  <button name="action" value="bar">Go</button>
</form>

<script type="text/javascript">
  $('form').attr('action', 'baz'); //this fails silently
  $('form').get(0).setAttribute('action', 'baz'); //this works
</script>

How do I get the SelectedItem or SelectedIndex of ListView in vb.net?

Please Try This for Getting column Index

Private Sub lvDetail_MouseMove(sender As Object, e As MouseEventArgs) Handles lvDetail.MouseClick

    Dim info As ListViewHitTestInfo = lvDetail.HitTest(e.X, e.Y)
    Dim rowIndex As Integer = lvDetail.FocusedItem.Index
    lvDetail.Items(rowIndex).Selected = True
    Dim xTxt = info.SubItem.Text
    For i = 0 To lvDetail.Columns.Count - 1
        If lvDetail.SelectedItems(0).SubItems(i).Text = xTxt Then
            MsgBox(i)
        End If
    Next
End Sub

How to convert DateTime to a number with a precision greater than days in T-SQL?

CAST to a float or decimal instead of an int/bigint.

The integer portion (before the decimal point) represents the number of whole days. After the decimal are the fractional days (i.e., time).

Switch to selected tab by name in Jquery-UI Tabs

It seems that using the id works as well as the index, e.g. simply doing this will work out of the box...

$("#tabs").tabs("select", "#sample-tab-1");

This is well documented in the official docs:

"Select a tab, as if it were clicked. The second argument is the zero-based index of the tab to be selected or the id selector of the panel the tab is associated with (the tab's href fragment identifier, e.g. hash, points to the panel's id)."

I assume this was added after this question was asked and probably after most of the answers

Import pfx file into particular certificate store from command line

To anyone else looking for this, I wasn't able to use certutil -importpfx into a specific store, and I didn't want to download the importpfx tool supplied by jaspernygaard's answer in order to avoid the requirement of copying the file to a large number of servers. I ended up finding my answer in a powershell script shown here.

The code uses System.Security.Cryptography.X509Certificates to import the certificate and then moves it into the desired store:

function Import-PfxCertificate { 

    param([String]$certPath,[String]$certRootStore = “localmachine”,[String]$certStore = “My”,$pfxPass = $null) 
    $pfx = new-object System.Security.Cryptography.X509Certificates.X509Certificate2 

    if ($pfxPass -eq $null) 
    {
        $pfxPass = read-host "Password" -assecurestring
    } 

    $pfx.import($certPath,$pfxPass,"Exportable,PersistKeySet") 

    $store = new-object System.Security.Cryptography.X509Certificates.X509Store($certStore,$certRootStore) 
    $store.open("MaxAllowed") 
    $store.add($pfx) 
    $store.close() 
}

How to get Bitmap from an Uri?

(KOTLIN) So, as of April 7th, 2020 none of the above mentioned options worked, but here's what worked for me:

  1. If you want to store the bitmap in a val and set an imageView with it, use this:

    val bitmap = BitmapFactory.decodeFile(currentPhotoPath).also { bitmap -> imageView.setImageBitmap(bitmap) }

  2. If you just want to set the bitmap to and imageView, use this:

    BitmapFactory.decodeFile(currentPhotoPath).also { bitmap -> imageView.setImageBitmap(bitmap) }

String formatting in Python 3

Python 3.6 now supports shorthand literal string interpolation with PEP 498. For your use case, the new syntax is simply:

f"({self.goals} goals, ${self.penalties})"

This is similar to the previous .format standard, but lets one easily do things like:

>>> width = 10
>>> precision = 4
>>> value = decimal.Decimal('12.34567')
>>> f'result: {value:{width}.{precision}}'
'result:      12.35'

How to change language of app when user selects language?

Good solutions explained pretty well here. But Here is one more.

Create your own CustomContextWrapper class extending ContextWrapper and use it to change Locale setting for the complete application. Here is a GIST with usage.

And then call the CustomContextWrapper with saved locale identifier e.g. 'hi' for Hindi language in activity lifecycle method attachBaseContext. Usage here:

@Override
protected void attachBaseContext(Context newBase) {
    // fetch from shared preference also save the same when applying. Default here is en = English
    String language = MyPreferenceUtil.getInstance().getString("saved_locale", "en");
    super.attachBaseContext(MyContextWrapper.wrap(newBase, language));
}

Recover from git reset --hard?

If you're developing on Netbeans, look between the file tabs and the file edit area. There is a "Source" and "History". On "History" you'll see changes made using version control (git/other), but also changes made locally. In this case, local changes could save you.

Invalid length parameter passed to the LEFT or SUBSTRING function

This is because the CHARINDEX-1 is returning a -ive value if the look-up for " " (space) is 0. The simplest solution would be to avoid '-ve' by adding

ABS(CHARINDEX(' ', PostCode ) -1))

which will return only +ive values for your length even if CHARINDEX(' ', PostCode ) -1) is a -ve value. Correct me if I'm wrong!

Calculate distance in meters when you know longitude and latitude in java

Based on another question on stackoverflow, I got this code.. This calculates the result in meters, not in miles :)

 public static float distFrom(float lat1, float lng1, float lat2, float lng2) {
    double earthRadius = 6371000; //meters
    double dLat = Math.toRadians(lat2-lat1);
    double dLng = Math.toRadians(lng2-lng1);
    double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
               Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
               Math.sin(dLng/2) * Math.sin(dLng/2);
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    float dist = (float) (earthRadius * c);

    return dist;
    }

Creating random numbers with no duplicates

This would be a lot simpler in java-8:

Stream.generate(new Random()::ints)
            .distinct()
            .limit(16) // whatever limit you might need
            .toArray(Integer[]::new);

Regex for Mobile Number Validation

This regex is very short and sweet for working.

/^([+]\d{2})?\d{10}$/

Ex: +910123456789 or 0123456789

-> /^ and $/ is for starting and ending
-> The ? mark is used for conditional formatting where before question mark is available or not it will work
-> ([+]\d{2}) this indicates that the + sign with two digits '\d{2}' here you can place digit as per country
-> after the ? mark '\d{10}' this says that the digits must be 10 of length change as per your country mobile number length

This is how this regex for mobile number is working.
+ sign is used for world wide matching of number.

if you want to add the space between than you can use the

[ ]

here the square bracket represents the character sequence and a space is character for searching in regex.
for the space separated digit you can use this regex

/^([+]\d{2}[ ])?\d{10}$/

Ex: +91 0123456789

Thanks ask any question if you have.

How to set custom JsonSerializerSettings for Json.NET in ASP.NET Web API?

Answer is adding this 2 lines of code to Global.asax.cs Application_Start method

var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = 
    Newtonsoft.Json.PreserveReferencesHandling.All;

Reference: Handling Circular Object References

How to generate a random number between 0 and 1?

Set the seed using srand(). Also, you're not specifying the max value in rand(), so it's using RAND_MAX. I'm not sure if it's actually 10000... why not just specify it. Although, we don't know what your "expected results" are. It's a random number generator. What are you expecting, and what are you seeing?

As noted in another comment, SA() isn't returning anything explicitly.

http://pubs.opengroup.org/onlinepubs/009695399/functions/rand.html http://www.thinkage.ca/english/gcos/expl/c/lib/rand.html

Edit: From Generating random number between [-1, 1] in C? ((float)rand())/RAND_MAX returns a floating-point number in [0,1]

Automatic vertical scroll bar in WPF TextBlock?

<ScrollViewer MaxHeight="50"  
              Width="Auto" 
              HorizontalScrollBarVisibility="Disabled"
              VerticalScrollBarVisibility="Auto">
     <TextBlock Text="{Binding Path=}" 
                Style="{StaticResource TextStyle_Data}" 
                TextWrapping="Wrap" />
</ScrollViewer>

I am doing this in another way by putting MaxHeight in ScrollViewer.

Just Adjust the MaxHeight to show more or fewer lines of text. Easy.

Is there a function to split a string in PL/SQL?

Please find next an example you may find useful

--1st substring

select substr('alfa#bravo#charlie#delta', 1,  
  instr('alfa#bravo#charlie#delta', '#', 1, 1)-1) from dual;

--2nd substring

select substr('alfa#bravo#charlie#delta', instr('alfa#bravo#charlie#delta', '#', 1, 1)+1,  
  instr('alfa#bravo#charlie#delta', '#', 1, 2) - instr('alfa#bravo#charlie#delta', '#', 1, 1) -1) from dual;

--3rd substring

select substr('alfa#bravo#charlie#delta', instr('alfa#bravo#charlie#delta', '#', 1, 2)+1,  
  instr('alfa#bravo#charlie#delta', '#', 1, 3) - instr('alfa#bravo#charlie#delta', '#', 1, 2) -1) from dual;

--4th substring

select substr('alfa#bravo#charlie#delta', instr('alfa#bravo#charlie#delta', '#', 1, 3)+1) from dual;

Best regards

Emanuele

How to add icon inside EditText view in Android ?

Use :

<EditText
    ..     
    android:drawableStart="@drawable/icon" />

Bootstrap 3: Scroll bars

You need to use overflow option like below:

.nav{
    max-height: 300px;
    overflow-y: scroll; 
}

Change the height according to amount of items you need to show

Referencing system.management.automation.dll in Visual Studio

The assembly coming with Powershell SDK (C:\Program Files\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0) does not come with Powershell 2 specific types.

Manually editing the csproj file solved my problem.

Java: Reading integers from a file into an array

File file = new File("E:/Responsibility.txt");  
    Scanner scanner = new Scanner(file);
    List<Integer> integers = new ArrayList<>();
    while (scanner.hasNext()) {
        if (scanner.hasNextInt()) {
            integers.add(scanner.nextInt());
        } else {
            scanner.next();
        }
    }
    System.out.println(integers);

How do I rename a local Git branch?

Advanced Git users can rename manually using:

Rename the old branch under .git/refs/heads to the new name

Rename the old branch under .git/logs/refs/heads to the new name

Update the .git/HEAD to point to yout new branch name

python paramiko ssh

There is something wrong with the accepted answer, it sometimes (randomly) brings a clipped response from server. I do not know why, I did not investigate the faulty cause of the accepted answer because this code worked perfectly for me:

import paramiko

ip='server ip'
port=22
username='username'
password='password'

cmd='some useful command' 

ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip,port,username,password)

stdin,stdout,stderr=ssh.exec_command(cmd)
outlines=stdout.readlines()
resp=''.join(outlines)
print(resp)

stdin,stdout,stderr=ssh.exec_command('some really useful command')
outlines=stdout.readlines()
resp=''.join(outlines)
print(resp)

how to generate web service out of wsdl

How about using the wsdl /server or wsdl /serverinterface switches? As far as I understand the wsdl.exe command line properties, that's what you're looking for.

- ADVANCED -

/server

Server switch has been deprecated. Please use /serverInterface instead.
Generate an abstract class for an xml web service implementation using
ASP.NET based on the contracts. The default is to generate client proxy
classes.

On the other hand: why do you want to create obsolete technology solutions? Why not create this web service as a WCF service. That's the current and more modern, much more flexible way to do this!

Marc


UPDATE:

When I use wsdl /server on a WSDL file, I get this file created:

[WebService(Namespace="http://.......")]
public abstract partial class OneCrmServiceType : System.Web.Services.WebService 
{
    /// <remarks/>
    [WebMethod]
    public abstract void OrderCreated(......);
}

This is basically almost exactly the same code that gets generated when you add an ASMX file to your solution (in the code behind file - "yourservice.asmx.cs"). I don't think you can get any closer to creating an ASMX file from a WSDL file.

You can always add the "yourservice.asmx" manually - it doesn't really contain much:

<%@ WebService Language="C#" CodeBehind="YourService.asmx.cs" 
      Class="YourServiceNamespace.YourServiceClass" %>

Rotate and translate

There is no need for that, as you can use css 'writing-mode' with values 'vertical-lr' or 'vertical-rl' as desired.

.item {
  writing-mode: vertical-rl;
}

CSS:writing-mode

What is the difference between null and System.DBNull.Value?

Well, null is not an instance of any type. Rather, it is an invalid reference.

However, System.DbNull.Value, is a valid reference to an instance of System.DbNull (System.DbNull is a singleton and System.DbNull.Value gives you a reference to the single instance of that class) that represents nonexistent* values in the database.

*We would normally say null, but I don't want to confound the issue.

So, there's a big conceptual difference between the two. The keyword null represents an invalid reference. The class System.DbNull represents a nonexistent value in a database field. In general, we should try avoid using the same thing (in this case null) to represent two very different concepts (in this case an invalid reference versus a nonexistent value in a database field).

Keep in mind, this is why a lot of people advocate using the null object pattern in general, which is exactly what System.DbNull is an example of.

Resize Cross Domain Iframe Height

You need to have access as well on the site that you will be iframing. i found the best solution here: https://gist.github.com/MateuszFlisikowski/91ff99551dcd90971377

yourotherdomain.html

<script type='text/javascript' src="js/jquery.min.js"></script>
<script type='text/javascript'>
  // Size the parent iFrame
  function iframeResize() {
    var height = $('body').outerHeight(); // IMPORTANT: If body's height is set to 100% with CSS this will not work.
    parent.postMessage("resize::"+height,"*");
  }

  $(document).ready(function() {
    // Resize iframe
    setInterval(iframeResize, 1000);
  });
</script>

your website with iframe

<iframe src='example.html' id='edh-iframe'></iframe>
<script type='text/javascript'>
  // Listen for messages sent from the iFrame
  var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
  var eventer = window[eventMethod];
  var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";

  eventer(messageEvent,function(e) {
    // If the message is a resize frame request
    if (e.data.indexOf('resize::') != -1) {
      var height = e.data.replace('resize::', '');
      document.getElementById('edh-iframe').style.height = height+'px';
    }
  } ,false);
</script>

How do I export an Android Studio project?

In the Android Studio go to File then Close Project. Then take the folder (in the workspace folder) of the project and copy it to a flash memory or whatever. Then when you get comfortable at home, copy this folder in the workspace folder you've already created, open the Android Studio and go to File then Open and import this project into your workspace.

The problem you have with this is that you're searching for the wrong term here, because in Android, exporting a project means compiling it to .apk file (not exporting the project). Import/Export is used for the .apk management, what you need is Open/Close project, the other thing is just copy/paste.

How to access static resources when mapping a global front controller servlet on /*

Serving static content with appropriate suffix in multiple servlet-mapping definitions solved the security issue which is mentioned in one of the comments in one of the answers posted. Quoted below:

This was a security hole in Tomcat (WEB-INF and META-INF contents are accessible this way) and it has been fixed in 7.0.4 (and will be ported to 5.x and 6.x as well). – BalusC Nov 2 '10 at 22:44

which helped me a lot. And here is how I solved it:

<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.js</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.css</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.jpg</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.htm</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.html</url-pattern>
</servlet-mapping>

Check that an email address is valid on iOS

to validate the email string you will need to write a regular expression to check it is in the correct form. there are plenty out on the web but be carefull as some can exclude what are actually legal addresses.

essentially it will look something like this

^((?>[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+\x20*|"((?=[\x01-\x7f])[^"\\]|\\[\x01-\x7f])*"\x20*)*(?<angle><))?((?!\.)(?>\.?[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+)+|"((?=[\x01-\x7f])[^"\\]|\\[\x01-\x7f])*")@(((?!-)[a-zA-Z\d\-]+(?<!-)\.)+[a-zA-Z]{2,}|\[(((?(?<!\[)\.)(25[0-5]|2[0-4]\d|[01]?\d?\d)){4}|[a-zA-Z\d\-]*[a-zA-Z\d]:((?=[\x01-\x7f])[^\\\[\]]|\\[\x01-\x7f])+)\])(?(angle)>)$

Actually checking if the email exists and doesn't bounce would mean sending an email and seeing what the result was. i.e. it bounced or it didn't. However it might not bounce for several hours or not at all and still not be a "real" email address. There are a number of services out there which purport to do this for you and would probably be paid for by you and quite frankly why bother to see if it is real?

It is good to check the user has not misspelt their email else they could enter it incorrectly, not realise it and then get hacked of with you for not replying. However if someone wants to add a bum email address there would be nothing to stop them creating it on hotmail or yahoo (or many other places) to gain the same end.

So do the regular expression and validate the structure but forget about validating against a service.

String to Dictionary in Python

This data is JSON! You can deserialize it using the built-in json module if you're on Python 2.6+, otherwise you can use the excellent third-party simplejson module.

import json    # or `import simplejson as json` if on Python < 2.6

json_string = u'{ "id":"123456789", ... }'
obj = json.loads(json_string)    # obj now contains a dict of the data

Convert time span value to format "hh:mm Am/Pm" using C#

At first, you need to convert time span to DateTime structure:

var dt = new DateTime(2000, 12, 1, timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds)

Then you need to convert the value to string with Short Time format

var result = dt.ToString("t"); // Convert to string using Short Time format

jquery function setInterval

This is because you are executing the function not referencing it. You should do:

  setInterval(swapImages,1000);

how to convert image to byte array in java?

java.io.FileInputStream is what you're looking for :-)

Number of visitors on a specific page

Go to Behavior > Site Content > All Pages and put your URI into the search box.enter image description here

Format datetime in asp.net mvc 4

Thanks Darin, For me, to be able to post to the create method, It only worked after I modified the BindModel code to :

public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
    var displayFormat = bindingContext.ModelMetadata.DisplayFormatString;
    var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

    if (!string.IsNullOrEmpty(displayFormat) && value != null)
    {
        DateTime date;
        displayFormat = displayFormat.Replace("{0:", string.Empty).Replace("}", string.Empty);
        // use the format specified in the DisplayFormat attribute to parse the date
         if (DateTime.TryParse(value.AttemptedValue, CultureInfo.GetCultureInfo("en-GB"), DateTimeStyles.None, out date))
        {
            return date;
        }
        else
        {
            bindingContext.ModelState.AddModelError(
                bindingContext.ModelName,
                string.Format("{0} is an invalid date format", value.AttemptedValue)
            );
        }
    }

    return base.BindModel(controllerContext, bindingContext);
}

Hope this could help someone else...

How to display a JSON representation and not [Object Object] on the screen

if you have array of object and you would like to deserialize them in compoent

get example() { this.arrayOfObject.map(i => JSON.stringify (i) ) };

then in template

<ul>
   <li *ngFor="obj of example">{{obj}}</li>
</ul>

foreach loop in angularjs

The angular.forEach() will iterate through your json object.

First iteration,

key = 0, value = { "name" : "Thomas", "password" : "thomasTheKing"}

Second iteration,

key = 1, value = { "name" : "Linda", "password" : "lindatheQueen" }

To get the value of your name, you can use value.name or value["name"]. Same with your password, you use value.password or value["password"].

The code below will give you what you want:

   angular.forEach(json, function (value, key)
         {
                //console.log(key);
                //console.log(value);
                if (value.password == "thomasTheKing") {
                    console.log("username is thomas");
                }
         });

How to push to History in React Router v4?

Now with react-router v5 you can use the useHistory hook like this:

import { useHistory } from "react-router-dom";

function HomeButton() {
  let history = useHistory();

  function handleClick() {
    history.push("/home");
  }

  return (
    <button type="button" onClick={handleClick}>
      Go home
    </button>
  );
}

read more at: https://reacttraining.com/react-router/web/api/Hooks/usehistory

Log all requests from the python-requests module

The underlying urllib3 library logs all new connections and URLs with the logging module, but not POST bodies. For GET requests this should be enough:

import logging

logging.basicConfig(level=logging.DEBUG)

which gives you the most verbose logging option; see the logging HOWTO for more details on how to configure logging levels and destinations.

Short demo:

>>> import requests
>>> import logging
>>> logging.basicConfig(level=logging.DEBUG)
>>> r = requests.get('http://httpbin.org/get?foo=bar&baz=python')
DEBUG:urllib3.connectionpool:Starting new HTTP connection (1): httpbin.org:80
DEBUG:urllib3.connectionpool:http://httpbin.org:80 "GET /get?foo=bar&baz=python HTTP/1.1" 200 366

Depending on the exact version of urllib3, the following messages are logged:

  • INFO: Redirects
  • WARN: Connection pool full (if this happens often increase the connection pool size)
  • WARN: Failed to parse headers (response headers with invalid format)
  • WARN: Retrying the connection
  • WARN: Certificate did not match expected hostname
  • WARN: Received response with both Content-Length and Transfer-Encoding, when processing a chunked response
  • DEBUG: New connections (HTTP or HTTPS)
  • DEBUG: Dropped connections
  • DEBUG: Connection details: method, path, HTTP version, status code and response length
  • DEBUG: Retry count increments

This doesn't include headers or bodies. urllib3 uses the http.client.HTTPConnection class to do the grunt-work, but that class doesn't support logging, it can normally only be configured to print to stdout. However, you can rig it to send all debug information to logging instead by introducing an alternative print name into that module:

import logging
import http.client

httpclient_logger = logging.getLogger("http.client")

def httpclient_logging_patch(level=logging.DEBUG):
    """Enable HTTPConnection debug logging to the logging framework"""

    def httpclient_log(*args):
        httpclient_logger.log(level, " ".join(args))

    # mask the print() built-in in the http.client module to use
    # logging instead
    http.client.print = httpclient_log
    # enable debugging
    http.client.HTTPConnection.debuglevel = 1

Calling httpclient_logging_patch() causes http.client connections to output all debug information to a standard logger, and so are picked up by logging.basicConfig():

>>> httpclient_logging_patch()
>>> r = requests.get('http://httpbin.org/get?foo=bar&baz=python')
DEBUG:urllib3.connectionpool:Starting new HTTP connection (1): httpbin.org:80
DEBUG:http.client:send: b'GET /get?foo=bar&baz=python HTTP/1.1\r\nHost: httpbin.org\r\nUser-Agent: python-requests/2.22.0\r\nAccept-Encoding: gzip, deflate\r\nAccept: */*\r\nConnection: keep-alive\r\n\r\n'
DEBUG:http.client:reply: 'HTTP/1.1 200 OK\r\n'
DEBUG:http.client:header: Date: Tue, 04 Feb 2020 13:36:53 GMT
DEBUG:http.client:header: Content-Type: application/json
DEBUG:http.client:header: Content-Length: 366
DEBUG:http.client:header: Connection: keep-alive
DEBUG:http.client:header: Server: gunicorn/19.9.0
DEBUG:http.client:header: Access-Control-Allow-Origin: *
DEBUG:http.client:header: Access-Control-Allow-Credentials: true
DEBUG:urllib3.connectionpool:http://httpbin.org:80 "GET /get?foo=bar&baz=python HTTP/1.1" 200 366

How to present a simple alert message in java?

I'll be the first to admit Java can be very verbose, but I don't think this is unreasonable:

JOptionPane.showMessageDialog(null, "My Goodness, this is so concise");

If you statically import javax.swing.JOptionPane.showMessageDialog using:

import static javax.swing.JOptionPane.showMessageDialog;

This further reduces to

showMessageDialog(null, "This is even shorter");

Android layout replacing a view with another view on run time

private void replaceView(View oldV,View newV){
        ViewGroup par = (ViewGroup)oldV.getParent();
        if(par == null){return;}
        int i1 = par.indexOfChild(oldV);
        par.removeViewAt(i1);
        par.addView(newV,i1);
    }

Javascript reduce on array of objects

After the first iteration your're returning a number and then trying to get property x of it to add to the next object which is undefined and maths involving undefined results in NaN.

try returning an object contain an x property with the sum of the x properties of the parameters:

var arr = [{x:1},{x:2},{x:4}];

arr.reduce(function (a, b) {
  return {x: a.x + b.x}; // returns object with property x
})

// ES6
arr.reduce((a, b) => ({x: a.x + b.x}));

// -> {x: 7}

Explanation added from comments:

The return value of each iteration of [].reduce used as the a variable in the next iteration.

Iteration 1: a = {x:1}, b = {x:2}, {x: 3} assigned to a in Iteration 2

Iteration 2: a = {x:3}, b = {x:4}.

The problem with your example is that you're returning a number literal.

function (a, b) {
  return a.x + b.x; // returns number literal
}

Iteration 1: a = {x:1}, b = {x:2}, // returns 3 as a in next iteration

Iteration 2: a = 3, b = {x:2} returns NaN

A number literal 3 does not (typically) have a property called x so it's undefined and undefined + b.x returns NaN and NaN + <anything> is always NaN

Clarification: I prefer my method over the other top answer in this thread as I disagree with the idea that passing an optional parameter to reduce with a magic number to get out a number primitive is cleaner. It may result in fewer lines written but imo it is less readable.

What is the reason and how to avoid the [FIN, ACK] , [RST] and [RST, ACK]

Here is a rough explanation of the concepts.

[ACK] is the acknowledgement that the previously sent data packet was received.

[FIN] is sent by a host when it wants to terminate the connection; the TCP protocol requires both endpoints to send the termination request (i.e. FIN).

So, suppose

  • host A sends a data packet to host B
  • and then host B wants to close the connection.
  • Host B (depending on timing) can respond with [FIN,ACK] indicating that it received the sent packet and wants to close the session.
  • Host A should then respond with a [FIN,ACK] indicating that it received the termination request (the ACK part) and that it too will close the connection (the FIN part).

However, if host A wants to close the session after sending the packet, it would only send a [FIN] packet (nothing to acknowledge) but host B would respond with [FIN,ACK] (acknowledges the request and responds with FIN).

Finally, some TCP stacks perform half-duplex termination, meaning that they can send [RST] instead of the usual [FIN,ACK]. This happens when the host actively closes the session without processing all the data that was sent to it. Linux is one operating system which does just this.

You can find a more detailed and comprehensive explanation here.

node.js, socket.io with SSL

check this.configuration..

app = module.exports = express();
var httpsOptions = { key: fs.readFileSync('certificates/server.key'), cert: fs.readFileSync('certificates/final.crt') };        
var secureServer = require('https').createServer(httpsOptions, app);
io = module.exports = require('socket.io').listen(secureServer,{pingTimeout: 7000, pingInterval: 10000});
io.set("transports", ["xhr-polling","websocket","polling", "htmlfile"]);
secureServer.listen(3000);

Make div stay at bottom of page's content all the time even when there are scrollbars

Just worked out for another solution as above example have bug( somewhere error ) for me. Variation from the selected answer.

html,body {
    height: 100%
}

#nonFooter {
    min-height: 100%;
    position:relative;
    /* Firefox */
    min-height: -moz-calc(100% - 30px);
    /* WebKit */
    min-height: -webkit-calc(100% - 30px);
    /* Opera */
    min-height: -o-calc(100% - 30px);
    /* Standard */
    min-height: calc(100% - 30px);
}

#footer {
    height:30px;
    margin: 0;
    clear: both;
    width:100%;
    position: relative;
}

for html layout

<body>
    <div id="nonFooter">header,middle,left,right,etc</div>
    <div id="footer"></div>
</body>

Well this way don't support old browser however its acceptable for old browser to scrolldown 30px to view the footer

How to insert an item into an array at a specific index (JavaScript)?

You can implement the Array.insert method by doing this:

Array.prototype.insert = function ( index, item ) {
    this.splice( index, 0, item );
};

Then you can use it like:

var arr = [ 'A', 'B', 'D', 'E' ];
arr.insert(2, 'C');

// => arr == [ 'A', 'B', 'C', 'D', 'E' ]

.htaccess rewrite to redirect root URL to subdirectory

This will try the subdir if the file doesn't exist in the root. Needed this as I moved a basic .html website that expects to be ran at the root level and pushed it to a subdir. Only works if all files are flat (no .htaccess trickery in the subdir possible). Useful for linked things like css and js files.

# Internal Redirect to subdir if file is found there.
RewriteEngine on
RewriteCond %{DOCUMENT_ROOT}/%{REQUEST_URI} !-s
RewriteCond %{DOCUMENT_ROOT}/subdir/%{REQUEST_URI} -s
RewriteRule ^(.*)$ /subdir/$1 [L]

Image convert to Base64

It's useful to work with Deferred Object in this case, and return promise:

function readImage(inputElement) {
    var deferred = $.Deferred();

    var files = inputElement.get(0).files;
    if (files && files[0]) {
        var fr= new FileReader();
        fr.onload = function(e) {
            deferred.resolve(e.target.result);
        };
        fr.readAsDataURL( files[0] );
    } else {
        deferred.resolve(undefined);
    }

    return deferred.promise();
}

And above function could be used in this way:

var inputElement = $("input[name=file]");
readImage(inputElement).done(function(base64Data){
    alert(base64Data);
});

Or in your case:

$(input).on('change',function(){
  readImage($(this)).done(function(base64Data){ alert(base64Data); });
});

Limiting the number of characters in a string, and chopping off the rest

The solution may be java.lang.String.format("%" + maxlength + "s", string).trim(), like this:

int maxlength = 20;
String longString = "Any string you want which length is greather than 'maxlength'";
String shortString = "Anything short";
String resultForLong = java.lang.String.format("%" + maxlength + "s", longString).trim();
String resultForShort = java.lang.String.format("%" + maxlength + "s", shortString).trim();
System.out.println(resultForLong);
System.out.println(resultForShort);

ouput:

Any string you want w

Anything short

Array definition in XML?

The second way isn't valid XML; did you mean <numbers>[3,2,1]</numbers>?

If so, then the first one is preferred because all you need to get the array elements is some XML manipulation. On the second one you first need to get the value of the <numbers> element via XML manipulation, then somehow parse the [3,2,1] text using something else.

Or if you really want some compact format, you can consider using JSON (which "natively" supports arrays). But that depends on your application requirements.

Using <style> tags in the <body> with other HTML

As others have already mentioned, HTML 4 requires the <style> tag to be placed in the <head> section (even though most browsers allow <style> tags within the body).

However, HTML 5 includes the scoped attribute (see update below), which allows you to create style sheets that are scoped within the parent element of the <style> tag. This also enables you to place <style> tags within the <body> element:

<!DOCTYPE html>
<html>
<head></head>
<body>

<div id="scoped-content">
    <style type="text/css" scoped>
        h1 { color: red; } 
    </style>

    <h1>Hello</h1>
</div>

    <h1>
      World
    </h1>

</body>
</html>

If you render the above code in an HTML-5 enabled browser that supports scoped, you will see the limited scope of the style sheet.

There's just one major caveat...

At the time I'm writing this answer (May, 2013) almost no mainstream browser currently supports the scoped attribute. (Although apparently developer builds of Chromium support it.)

HOWEVER, there is an interesting implication of the scoped attribute that pertains to this question. It means that future browsers are mandated via the standard to allow <style> elements within the <body> (as long as the <style> elements are scoped.)

So, given that:

  • Almost every existing browser currently ignores the scoped attribute
  • Almost every existing browser currently allows <style> tags within the <body>
  • Future implementations will be required to allow (scoped) <style> tags within the <body>

...then there is literally no harm * in placing <style> tags within the body, as long as you future proof them with a scoped attribute. The only problem is that current browsers won't actually limit the scope of the stylesheet - they'll apply it to the whole document. But the point is that, for all practical purposes, you can include <style> tags within the <body> provided that you:

  • Future-proof your HTML by including the scoped attribute
  • Understand that as of now, the stylesheet within the <body> will not actually be scoped (because no mainstream browser support exists yet)


* except of course, for pissing off HTML validators...


Finally, regarding the common (but subjective) claim that embedding CSS within HTML is poor practice, it should be noted that the whole point of the scoped attribute is to accommodate typical modern development frameworks that allow developers to import chunks of HTML as modules or syndicated content. It is very convenient to have embedded CSS that only applies to a particular chunk of HTML, in order to develop encapsulated, modular components with specific stylings.


Update as of Feb 2019, according to the Mozilla documentation, the scoped attribute is deprecated. Chrome stopped supporting it in version 36 (2014) and Firefox in version 62 (2018). In both cases, the feature had to be explicitly enabled by the user in the browsers' settings. No other major browser ever supported it.

What is the difference between i++ & ++i in a for loop?

JLS§14.14.1, The basic for Statement, makes it clear that the ForUpdate expression(s) are evaluated and the value(s) are discarded. The effect is to make the two forms identical in the context of a for statement.

Using strtok with a std::string

EDIT: usage of const cast is only used to demonstrate the effect of strtok() when applied to a pointer returned by string::c_str().

You should not use strtok() since it modifies the tokenized string which may lead to undesired, if not undefined, behaviour as the C string "belongs" to the string instance.

#include <string>
#include <iostream>

int main(int ac, char **av)
{
    std::string theString("hello world");
    std::cout << theString << " - " << theString.size() << std::endl;

    //--- this cast *only* to illustrate the effect of strtok() on std::string 
    char *token = strtok(const_cast<char  *>(theString.c_str()), " ");

    std::cout << theString << " - " << theString.size() << std::endl;

    return 0;
}

After the call to strtok(), the space was "removed" from the string, or turned down to a non-printable character, but the length remains unchanged.

>./a.out
hello world - 11
helloworld - 11

Therefore you have to resort to native mechanism, duplication of the string or an third party library as previously mentioned.

How do I check if an object has a specific property in JavaScript?

Do not do this object.hasOwnProperty(key)). It's really bad because these methods may be shadowed by properties on the object in question - consider { hasOwnProperty: false } - or, the object may be a null object (Object.create(null)).

The best way is to do Object.prototype.hasOwnProperty.call(object, key) or:

const has = Object.prototype.hasOwnProperty; // Cache the lookup once, in module scope.
/* Or */
import has from 'has'; // https://www.npmjs.com/package/has
// ...
console.log(has.call(object, key));

What is the meaning of # in URL and how can I use that?

Originally it was used as an anchor to jump to an element with the same name/id.

However, nowadays it's usually used with AJAX-based pages since changing the hash can be detected using JavaScript and allows you to use the back/forward button without actually triggering a full page reload.

Return content with IHttpActionResult for non-OK response

Anyone who is interested in returning anything with any statuscode with returning ResponseMessage:

//CreateResponse(HttpStatusCode, T value)
return ResponseMessage(Request.CreateResponse(HttpStatusCode.XX, object));

JSON to TypeScript class instance?

You can now use Object.assign(target, ...sources). Following your example, you could use it like this:

class Foo {
  name: string;
  getName(): string { return this.name };
}

let fooJson: string = '{"name": "John Doe"}';
let foo: Foo = Object.assign(new Foo(), JSON.parse(fooJson));

console.log(foo.getName()); //returns John Doe

Object.assign is part of ECMAScript 2015 and is currently available in most modern browsers.

Make element fixed on scroll

You can do that with some easy jQuery:

http://jsfiddle.net/jpXjH/6/

var elementPosition = $('#navigation').offset();

$(window).scroll(function(){
        if($(window).scrollTop() > elementPosition.top){
              $('#navigation').css('position','fixed').css('top','0');
        } else {
            $('#navigation').css('position','static');
        }    
});

How do I extract specific 'n' bits of a 32-bit unsigned integer in C?

There is a single BEXTR (Bit field extract (with register)) x86 instruction on Intel and AMD CPUs and UBFX on ARM. There are intrinsic functions such as _bextr_u32() (link requires sign-in) that allow to invoke this instruction explicitly.

They implement (source >> offset) & ((1 << n) - 1) C code: get n continuous bits from source starting at the offset bit. Here's a complete function definition that handles edge cases:

#include <limits.h>

unsigned getbits(unsigned value, unsigned offset, unsigned n)
{
  const unsigned max_n = CHAR_BIT * sizeof(unsigned);
  if (offset >= max_n)
    return 0; /* value is padded with infinite zeros on the left */
  value >>= offset; /* drop offset bits */
  if (n >= max_n)
    return value; /* all  bits requested */
  const unsigned mask = (1u << n) - 1; /* n '1's */
  return value & mask;
}

For example, to get 3 bits from 2273 (0b100011100001) starting at 5-th bit, call getbits(2273, 5, 3)—it extracts 7 (0b111).

For example, say I want the first 17 bits of the 32-bit value; what is it that I should do?

unsigned first_bits = value & ((1u << 17) - 1); // & 0x1ffff

Assuming CHAR_BIT * sizeof(unsigned) is 32 on your system.

I presume I am supposed to use the modulus operator and I tried it and was able to get the last 8 bits and last 16 bits

unsigned last8bitsvalue  = value & ((1u <<  8) - 1); // & 0xff
unsigned last16bitsvalue = value & ((1u << 16) - 1); // & 0xffff

If the offset is always zero as in all your examples in the question then you don't need the more general getbits(). There is a special cpu instruction BLSMSK that helps to compute the mask ((1 << n) - 1).

Converting newline formatting from Mac to Windows

Just do tr delete:

tr -d "\r" <infile.txt >outfile.txt

GUI Tool for PostgreSQL

There is a comprehensive list of tools on the PostgreSQL Wiki:

https://wiki.postgresql.org/wiki/PostgreSQL_Clients

And of course PostgreSQL itself comes with pgAdmin, a GUI tool for accessing Postgres databases.

How to override !important?

Disclaimer: Avoid !important at all cost.

This is a dirty, dirty hack, but you can override an !important, without an !important, by using an (infinitely looping or very long lasting) animation on the property you're trying to override the importants on.

_x000D_
_x000D_
@keyframes forceYellow {_x000D_
  from {_x000D_
    background-color: yellow;_x000D_
  }_x000D_
  to {_x000D_
    background-color: yellow;_x000D_
  }_x000D_
}_x000D_
_x000D_
div {_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  margin: 0 auto;_x000D_
  background: red !important;_x000D_
  animation: 1s linear infinite forceYellow;_x000D_
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

creating Hashmap from a JSON String

This worked for me:

JSONObject jsonObj = new JSONObject();
jsonObj.put("phonetype","N95");
jsonObj.put("cat","WP");

jsonObj to Hashmap as following using gson

HashMap<String, Object> hashmap = new Gson().fromJson(jsonObj.toString(), HashMap.class);

package used

<dependencies>
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20180813</version>
    </dependency>
    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.8.6</version>
    </dependency>
</dependencies>

C++ wait for user input

There is no "standard" library function to do this. The standard (perhaps surprisingly) does not actually recognise the concept of a "keyboard", albeit it does have a standard for "console input".

There are various ways to achieve it on different operating systems (see herohuyongtao's solution) but it is not portable across all platforms that support keyboard input.

Remember that C++ (and C) are devised to be languages that can run on embedded systems that do not have keyboards. (Having said that, an embedded system might not have various other devices that the standard library supports).

This matter has been debated for a long time.

What is the best regular expression to check if a string is a valid URL?

What platform? If using .NET, use System.Uri.TryCreate, not a regex.

For example:

static bool IsValidUrl(string urlString)
{
    Uri uri;
    return Uri.TryCreate(urlString, UriKind.Absolute, out uri)
        && (uri.Scheme == Uri.UriSchemeHttp
         || uri.Scheme == Uri.UriSchemeHttps
         || uri.Scheme == Uri.UriSchemeFtp
         || uri.Scheme == Uri.UriSchemeMailto
            /*...*/);
}

// In test fixture...

[Test]
void IsValidUrl_Test()
{
    Assert.True(IsValidUrl("http://www.example.com"));
    Assert.False(IsValidUrl("javascript:alert('xss')"));
    Assert.False(IsValidUrl(""));
    Assert.False(IsValidUrl(null));
}

(Thanks to @Yoshi for the tip about javascript:)

Failed to build gem native extension — Rails install

mkmf is part of the ruby1.9.1-dev package. This package contains the header files needed for extension libraries for Ruby 1.9.1. You need to install the ruby1.9.1-dev package by doing:

sudo apt-get install ruby1.9.1-dev

Then you can install Rails as per normal.

Generally it's easier to just do:

sudo apt-get install ruby-dev

PHP: maximum execution time when importing .SQL data file

You're trying to import a huge dataset via a web interface.

By default PHP scripts run in the context of a web server have a maximum execution time limit because you don't want a single errant PHP script tying up the entire server and causing a denial of service.

For that reason your import is failing. PHPMyAdmin is a web application and is hitting the limit imposed by PHP.

You could try raising the limit but that limit exists for a good reason so that's not advisable. Running a script that is going to take a very long time to execute in a web server is a very bad idea.

PHPMyAdmin isn't really intended for heavy duty jobs like this, it's meant for day to day housekeeping tasks and troubleshooting.

Your best option is to use the proper tools for the job, such as the mysql commandline tools. Assuming your file is an SQL dump then you can try running the following from the commandline:

mysql -u(your user name here) -p(your password here) -h(your sql server name here) (db name here) < /path/to/your/sql/dump.sql

Or if you aren't comfortable with commandline tools then something like SQLYog (for Windows), Sequel Pro (for Mac), etc may be more suitable for running an import job

Excel VBA Open a Folder

If you want to open a windows file explorer, you should call explorer.exe

Call Shell("explorer.exe" & " " & "P:\Engineering", vbNormalFocus)

Equivalent syxntax

Shell "explorer.exe" & " " & "P:\Engineering", vbNormalFocus

Testing if a checkbox is checked with jQuery

<input type="checkbox" id="ans" value="1" />

Jquery : var test= $("#ans").is(':checked') and it return true or false.

In your function:

$test =($request->get ( 'test' )== "true")? '1' : '0';

Why std::cout instead of simply cout?

If you are working in ROOT, you do not even have to write #include<iostream> and using namespace std; simply start from int filename().

This will solve the issue.

Why is there no tuple comprehension in Python?

You can use a generator expression:

tuple(i for i in (1, 2, 3))

but parentheses were already taken for … generator expressions.

Install apk without downloading

you can use this code .may be solve the problem

Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("http://192.168.43.1:6789/mobile_base/test.apk"));
startActivity(intent);

BootStrap : Uncaught TypeError: $(...).datetimepicker is not a function

I had the same problem, you have to load first the Moment.js file!

_x000D_
_x000D_
<script src="path/moment.js"></script>_x000D_
<script src="path/bootstrap-datetimepicker.js"></script>
_x000D_
_x000D_
_x000D_

How to update/upgrade a package using pip?

The way is

pip install [package_name] --upgrade

or in short

pip install [package_name] -U

Using sudo will ask to enter your root password to confirm the action, but although common, is considered unsafe.

If you do not have a root password (if you are not the admin) you should probably work with virtualenv.

You can also use the user flag to install it on this user only.

pip install [package_name] --upgrade --user

Leave only two decimal places after the dot

You can use this

"String.Format("{0:F2}", String Value);"

Gives you only the two digits after Dot, exactly two digits.

Insert array into MySQL database with PHP

I think the simple method would be using

ob_start(); //Start output buffer
print_r($var);
$var = ob_get_contents(); //Grab output
ob_end_clean(); //Discard output buffer

and your array output will be recorded as a simple variable

Fastest way to check a string is alphanumeric in Java

Use String.matches(), like:

String myString = "qwerty123456";
System.out.println(myString.matches("[A-Za-z0-9]+"));

That may not be the absolute "fastest" possible approach. But in general there's not much point in trying to compete with the people who write the language's "standard library" in terms of performance.

How to calculate 1st and 3rd quartiles?

If you want to use raw python rather than numpy or panda, you can use the python stats module to find the median of the upper and lower half of the list:

    >>> import statistics as stat
    >>> def quartile(data):
            data.sort()               
            half_list = int(len(data)//2)
            upper_quartile = stat.median(data[-half_list]
            lower_quartile = stat.median(data[:half_list])
            print("Lower Quartile: "+str(lower_quartile))
            print("Upper Quartile: "+str(upper_quartile))
            print("Interquartile Range: "+str(upper_quartile-lower_quartile)

    >>> quartile(df.time_diff)

Line 1: import the statistics module under the alias "stat"

Line 2: define the quartile function

Line 3: sort the data into ascending order

Line 4: get the length of half of the list

Line 5: get the median of the lower half of the list

Line 6: get the median of the upper half of the list

Line 7: print the lower quartile

Line 8: print the upper quartile

Line 9: print the interquartile range

Line 10: run the quartile function for the time_diff column of the DataFrame

How to check if an integer is within a range of numbers in PHP?

Might help:

if ( in_array(2, range(1,7)) ) {
    echo 'Number 2 is in range 1-7';
}

http://php.net/manual/en/function.range.php

Best Regular Expression for Email Validation in C#

First option (bad because of throw-catch, but MS will do work for you):

bool IsValidEmail(string email)
{
    try {
        var mail = new System.Net.Mail.MailAddress(email);
        return true;
    }
    catch {
        return false;
    }
}

Second option is read I Knew How To Validate An Email Address Until I Read The RFC and RFC specification

How to display a json array in table format?

using jquery $.each you can access all data and also set in table like this

<table style="width: 100%">
     <thead>
          <tr>
               <th>Id</th>
               <th>Name</th>
               <th>Category</th>
               <th>Color</th>
           </tr>
     </thead>
     <tbody id="tbody">
     </tbody>
</table>

$.each(data, function (index, item) {
     var eachrow = "<tr>"
                 + "<td>" + item[1] + "</td>"
                 + "<td>" + item[2] + "</td>"
                 + "<td>" + item[3] + "</td>"
                 + "<td>" + item[4] + "</td>"
                 + "</tr>";
     $('#tbody').append(eachrow);
});

how to make twitter bootstrap submenu to open on the left side?

I have created a javascript function that looks if he has enough space on the right side. If it has he will show it on the right side, else he will display it on the left side

Tested in:

  • Firefox (mac)
  • Chorme (mac)
  • Safari (mac)

Javascript:

$(document).ready(function(){
    //little fix for the poisition.
    var newPos     = $(".fixed-menuprofile .dropdown-submenu").offset().left - $(this).width();
    $(".fixed-menuprofile .dropdown-submenu").find('ul').offset({ "left": newPos });

    $(".fixed-menu .dropdown-submenu").mouseover(function() {
        var submenuPos = $(this).offset().left + 325;
        var windowPos  = $(window).width();
        var oldPos     = $(this).offset().left + $(this).width();
        var newPos     = $(this).offset().left - $(this).width();

        if( submenuPos > windowPos ){
            $(this).find('ul').offset({ "left": newPos });
        } else {
            $(this).find('ul').offset({ "left": oldPos });
        }
    });
});

because I don't want to add this fix on every menu items I created a new class on it. place the fixed-menu on the ul:

<ul class="dropdown-menu fixed-menu">

I hope this works out for you.

ps. little bug in safari and chrome, first hover will place it to mutch to the left will update this post if I fixed it.

How to specify the port an ASP.NET Core application is hosted on?

In ASP.NET Core 3.1, there are 4 main ways to specify a custom port:

  • Using command line arguments, by starting your .NET application with --urls=[url]:
dotnet run --urls=http://localhost:5001/
  • Using appsettings.json, by adding a Urls node:
{
  "Urls": "http://localhost:5001"
}
  • Using environment variables, with ASPNETCORE_URLS=http://localhost:5001/.
  • Using UseUrls(), if you prefer doing it programmatically:
public static class Program
{
    public static void Main(string[] args) =>
        CreateHostBuilder(args).Build().Run();

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(builder =>
            {
                builder.UseStartup<Startup>();
                builder.UseUrls("http://localhost:5001/");
            });
}

Or, if you're still using the web host builder instead of the generic host builder:

public class Program
{
    public static void Main(string[] args) =>
        new WebHostBuilder()
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup<Startup>()
            .UseUrls("http://localhost:5001/")
            .Build()
            .Run();
}

Resource blocked due to MIME type mismatch (X-Content-Type-Options: nosniff)

https://cdn.rawgit.com is shutting down. Thus, one of the alternate options can be used. JSDeliver is a free cdn that can be used.

// load any GitHub release, commit, or branch

// note: we recommend using npm for projects that support it

https://cdn.jsdelivr.net/gh/user/repo@version/file

// load jQuery v3.2.1

https://cdn.jsdelivr.net/gh/jquery/[email protected]/dist/jquery.min.js

// use a version range instead of a specific version

https://cdn.jsdelivr.net/gh/jquery/[email protected]/dist/jquery.min.js

https://cdn.jsdelivr.net/gh/jquery/jquery@3/dist/jquery.min.js

// omit the version completely to get the latest one

// you should NOT use this in production

https://cdn.jsdelivr.net/gh/jquery/jquery/dist/jquery.min.js

// add ".min" to any JS/CSS file to get a minified version

// if one doesn't exist, we'll generate it for you

https://cdn.jsdelivr.net/gh/jquery/[email protected]/src/core.min.js

// add / at the end to get a directory listing

https://cdn.jsdelivr.net/gh/jquery/jquery/

ref - https://www.jsdelivr.com/?docs=gh

How to get the current time in YYYY-MM-DD HH:MI:Sec.Millisecond format in Java?

You can simply get it in the format you want.

String date = String.valueOf(android.text.format.DateFormat.format("dd-MM-yyyy", new java.util.Date()));

Get all dates between two dates in SQL Server

This can be considered as bit tricky way as in my situation, I can't use a CTE table, so decided to join with sys.all_objects and then created row numbers and added that to start date till it reached the end date.

See the code below where I generated all dates in Jul 2018. Replace hard coded dates with your own variables (tested in SQL Server 2016):

select top (datediff(dd, '2018-06-30', '2018-07-31')) ROW_NUMBER() 
over(order by a.name) as SiNo, 
Dateadd(dd, ROW_NUMBER() over(order by a.name) , '2018-06-30') as Dt from sys.all_objects a

Store output of subprocess.Popen call in a string

The following captures stdout and stderr of the process in a single variable. It is Python 2 and 3 compatible:

from subprocess import check_output, CalledProcessError, STDOUT

command = ["ls", "-l"]
try:
    output = check_output(command, stderr=STDOUT).decode()
    success = True 
except CalledProcessError as e:
    output = e.output.decode()
    success = False

If your command is a string rather than an array, prefix this with:

import shlex
command = shlex.split(command)

What is the best way to paginate results in SQL Server

Use case wise the following seem to be easy to use and fast. Just set the page number.

use AdventureWorks
DECLARE @RowsPerPage INT = 10, @PageNumber INT = 6;
with result as(
SELECT SalesOrderDetailID, SalesOrderID, ProductID,
ROW_NUMBER() OVER (ORDER BY SalesOrderDetailID) AS RowNum
FROM Sales.SalesOrderDetail
where 1=1
)
select SalesOrderDetailID, SalesOrderID, ProductID from result
WHERE result.RowNum BETWEEN ((@PageNumber-1)*@RowsPerPage)+1
AND @RowsPerPage*(@PageNumber)

also without CTE

use AdventureWorks
DECLARE @RowsPerPage INT = 10, @PageNumber INT = 6
SELECT SalesOrderDetailID, SalesOrderID, ProductID
FROM (
SELECT SalesOrderDetailID, SalesOrderID, ProductID,
ROW_NUMBER() OVER (ORDER BY SalesOrderDetailID) AS RowNum
FROM Sales.SalesOrderDetail
where 1=1
 ) AS SOD
WHERE SOD.RowNum BETWEEN ((@PageNumber-1)*@RowsPerPage)+1
AND @RowsPerPage*(@PageNumber)

Default value for field in Django model

You can set the default like this:

b = models.CharField(max_length=7,default="foobar")

and then you can hide the field with your model's Admin class like this:

class SomeModelAdmin(admin.ModelAdmin):
    exclude = ("b")

Counting the number of files in a directory using Java

Using sigar should help. Sigar has native hooks to get the stats

new Sigar().getDirStat(dir).getTotal()

jQuery bind to Paste Event, how to get the content of the paste

You could compare the original value of the field and the changed value of the field and deduct the difference as the pasted value. This catches the pasted text correctly even if there is existing text in the field.

http://jsfiddle.net/6b7sK/

function text_diff(first, second) {
    var start = 0;
    while (start < first.length && first[start] == second[start]) {
        ++start;
    }
    var end = 0;
    while (first.length - end > start && first[first.length - end - 1] == second[second.length - end - 1]) {
        ++end;
    }
    end = second.length - end;
    return second.substr(start, end - start);
}
$('textarea').bind('paste', function () {
    var self = $(this);
    var orig = self.val();
    setTimeout(function () {
        var pasted = text_diff(orig, $(self).val());
        console.log(pasted);
    });
});

POST unchecked HTML checkboxes

The easiest solution is a "dummy" checkbox plus hidden input if you are using jquery:

 <input id="id" type="hidden" name="name" value="1/0">
 <input onchange="$('#id').val(this.checked?1:0)" type="checkbox" id="dummy-id" 
 name="dummy-name" value="1/0" checked="checked/blank">

Set the value to the current 1/0 value to start with for BOTH inputs, and checked=checked if 1. The input field (active) will now always be posted as 1 or 0. Also the checkbox can be clicked more than once before submission and still work correctly.

Limit Get-ChildItem recursion depth

I tried to limit Get-ChildItem recursion depth using Resolve-Path

$PATH = "."
$folder = get-item $PATH 
$FolderFullName = $Folder.FullName
$PATHs = Resolve-Path $FolderFullName\*\*\*\
$Folders = $PATHs | get-item | where {$_.PsIsContainer}

But this works fine :

gci "$PATH\*\*\*\*"

How do I start/stop IIS Express Server?

You can stop any IIS Express application or you can stop all application. Right click on IIS express icon , which is located at right bottom corner of task bar. Then Select Show All Application

enter image description here

Pandas groupby: How to get a union of strings

In [4]: df = read_csv(StringIO(data),sep='\s+')

In [5]: df
Out[5]: 
   A         B       C
0  1  0.749065    This
1  2  0.301084      is
2  3  0.463468       a
3  4  0.643961  random
4  1  0.866521  string
5  2  0.120737       !

In [6]: df.dtypes
Out[6]: 
A      int64
B    float64
C     object
dtype: object

When you apply your own function, there is not automatic exclusions of non-numeric columns. This is slower, though, than the application of .sum() to the groupby

In [8]: df.groupby('A').apply(lambda x: x.sum())
Out[8]: 
   A         B           C
A                         
1  2  1.615586  Thisstring
2  4  0.421821         is!
3  3  0.463468           a
4  4  0.643961      random

sum by default concatenates

In [9]: df.groupby('A')['C'].apply(lambda x: x.sum())
Out[9]: 
A
1    Thisstring
2           is!
3             a
4        random
dtype: object

You can do pretty much what you want

In [11]: df.groupby('A')['C'].apply(lambda x: "{%s}" % ', '.join(x))
Out[11]: 
A
1    {This, string}
2           {is, !}
3               {a}
4          {random}
dtype: object

Doing this on a whole frame, one group at a time. Key is to return a Series

def f(x):
     return Series(dict(A = x['A'].sum(), 
                        B = x['B'].sum(), 
                        C = "{%s}" % ', '.join(x['C'])))

In [14]: df.groupby('A').apply(f)
Out[14]: 
   A         B               C
A                             
1  2  1.615586  {This, string}
2  4  0.421821         {is, !}
3  3  0.463468             {a}
4  4  0.643961        {random}

Set the intervals of x-axis using r

You can use axis:

> axis(side=1, at=c(0:23))

That is, something like this:

plot(0:23, d, type='b', axes=FALSE)
axis(side=1, at=c(0:23))
axis(side=2, at=seq(0, 600, by=100))
box()

MySQL delete multiple rows in one query conditions unique to each row

You were very close, you can use this:

DELETE FROM table WHERE (col1,col2) IN ((1,2),(3,4),(5,6))

Please see this fiddle.

What is the difference between MySQL, MySQLi and PDO?

Those are different APIs to access a MySQL backend

  • The mysql is the historical API
  • The mysqli is a new version of the historical API. It should perform better and have a better set of function. Also, the API is object-oriented.
  • PDO_MySQL, is the MySQL for PDO. PDO has been introduced in PHP, and the project aims to make a common API for all the databases access, so in theory you should be able to migrate between RDMS without changing any code (if you don't use specific RDBM function in your queries), also object-oriented.

So it depends on what kind of code you want to produce. If you prefer object-oriented layers or plain functions...

My advice would be

  1. PDO
  2. MySQLi
  3. mysql

Also my feeling, the mysql API would probably being deleted in future releases of PHP.

How to run travis-ci locally

I'm not sure what was your original reason for running Travis locally, if you just wanted to play with it, then stop reading here as it's irrelevant for you.

If you already have experience with hosted Travis and you want to get the same experience in your own datacenter, read on.

Since Dec 2014 Travis CI offers an Enterprise on-premises version.

http://blog.travis-ci.com/2014-12-19-introducing-travis-ci-enterprise/

The pricing is part of the article as well:

The licensing is done per seats, where every license includes 20 users. Pricing starts at $6,000 per license, which includes 20 users and 5 concurrent builds. There's a premium option with unlimited builds for $8,500.

Vue is not defined

I got this error but as undefined due to the way I included js files

Initailly i had

<script src="~/vue/blade-account-update-credit-card-vue.js" asp-append-version="true"></script>
<script src="~/lib/vue/vue_v2.5.16.js"></script>

in the end of my .cshtml page GOT Error Vue not Defined but later I changed it to

<script src="~/lib/vue/vue_v2.5.16.js"></script> 
<script src="~/vue/blade-account-update-credit-card-vue.js" asp-append-version="true"></script>

and magically it worked. So i assume that vue js needs to be loaded on top of the .vue

Struct with template variables in C++

From the other answers, the problem is that you're templating a typedef. The only "way" to do this is to use a templated class; ie, basic template metaprogramming.

template<class T> class vector_Typedefs {
    /*typedef*/ struct array { //The typedef isn't necessary
        size_t x; 
        T *ary; 
    }; 

    //Any other templated typedefs you need. Think of the templated class like something
    // between a function and namespace.
}

//An advantage is:
template<> class vector_Typedefs<bool>
{
    struct array {
        //Special behavior for the binary array
    }
}

How to debug when Kubernetes nodes are in 'Not Ready' state

First, describe nodes and see if it reports anything:

$ kubectl describe nodes

Look for conditions, capacity and allocatable:

Conditions:
  Type              Status
  ----              ------
  OutOfDisk         False
  MemoryPressure    False
  DiskPressure      False
  Ready             True
Capacity:
 cpu:       2
 memory:    2052588Ki
 pods:      110
Allocatable:
 cpu:       2
 memory:    1950188Ki
 pods:      110

If everything is alright here, SSH into the node and observe kubelet logs to see if it reports anything. Like certificate erros, authentication errors etc.

If kubelet is running as a systemd service, you can use

$ journalctl -u kubelet

How do I declare an array with a custom class?

You have to provide a default constructor. While you're at it, fix your other constructor, too:

class Name
{
public:
  Name() { }
  Name(string const & f, string const & l) : first(f), last(l) { }
  //...
};

Alternatively, you have to provide the initializers:

Name arr[3] { { "John", "Doe" }, { "Jane", "Smith" }, { "", "" } };

The latter is conceptually preferable, because there's no reason that your class should have a notion of a "default" state. In that case, you simply have to provide an appropriate initializer for every element of the array.

Objects in C++ can never be in an ill-defined state; if you think about this, everything should become very clear.


An alternative is to use a dynamic container, though this is different from what you asked for:

std::vector<Name> arr;
arr.reserve(3);  // morally "an uninitialized array", though it really isn't

arr.emplace_back("John", "Doe");
arr.emplace_back("Jane", "Smith");
arr.emplace_back("", "");

std::vector<Name> brr { { "ab", "cd" }, { "de", "fg" } }; // yet another way

getting the last item in a javascript object

You can try this. This will store last item. Here need to convert obj into array. Then use array pop() function that will return last item from converted array.

_x000D_
_x000D_
var obj = { 'a' : 'apple', 'b' : 'banana', 'c' : 'carrot' };_x000D_
var last = Object.keys(obj).pop();_x000D_
console.log(last);_x000D_
console.log(obj[last]);
_x000D_
_x000D_
_x000D_

replace String with another in java

Replacing one string with another can be done in the below methods

Method 1: Using String replaceAll

 String myInput = "HelloBrother";
 String myOutput = myInput.replaceAll("HelloBrother", "Brother"); // Replace hellobrother with brother
 ---OR---
 String myOutput = myInput.replaceAll("Hello", ""); // Replace hello with empty
 System.out.println("My Output is : " +myOutput);       

Method 2: Using Pattern.compile

 import java.util.regex.Pattern;
 String myInput = "JAVAISBEST";
 String myOutputWithRegEX = Pattern.compile("JAVAISBEST").matcher(myInput).replaceAll("BEST");
 ---OR -----
 String myOutputWithRegEX = Pattern.compile("JAVAIS").matcher(myInput).replaceAll("");
 System.out.println("My Output is : " +myOutputWithRegEX);           

Method 3: Using Apache Commons as defined in the link below:

http://commons.apache.org/proper/commons-lang/javadocs/api-z.1/org/apache/commons/lang3/StringUtils.html#replace(java.lang.String, java.lang.String, java.lang.String)

REFERENCE

EXCEL VBA Check if entry is empty or not 'space'

A common trick is to check like this:

trim(TextBox1.Value & vbnullstring) = vbnullstring

this will work for spaces, empty strings, and genuine null values

How to use Git Revert

The reason reset and revert tend to come up a lot in the same conversations is because different version control systems use them to mean different things.

In particular, people who are used to SVN or P4 who want to throw away uncommitted changes to a file will often reach for revert before being told that they actually want reset.

Similarly, the revert equivalent in other VCSes is often called rollback or something similar - but "rollback" can also mean "I want to completely discard the last few commits", which is appropriate for reset but not revert. So, there's a lot of confusion where people know what they want to do, but aren't clear on which command they should be using for it.

As for your actual questions about revert...

Okay, you're going to use git revert but how?

git revert first-bad-commit..last-bad-commit

And after running git revert do you have to do something else after? Do you have to commit the changes revert made or does revert directly commit to the repo or what??

By default, git revert prompts you for a commit message and then commits the results. This can be overridden. I quote the man page:

--edit

With this option, git revert will let you edit the commit message prior to committing the revert. This is the default if you run the command from a terminal.

--no-commit

Usually the command automatically creates some commits with commit log messages stating which commits were reverted. This flag applies the changes necessary to revert the named commits to your working tree and the index, but does not make the commits. In addition, when this option is used, your index does not have to match the HEAD commit. The revert is done against the beginning state of your index.

This is useful when reverting more than one commits' effect to your index in a row.

In particular, by default it creates a new commit for each commit you're reverting. You can use revert --no-commit to create changes reverting all of them without committing those changes as individual commits, then commit at your leisure.

Angular 2 Unit Tests: Cannot find name 'describe'

In my case, the solution was to remove the typeRoots in my tsconfig.json.

As you can read in the TypeScript doc

If typeRoots is specified, only packages under typeRoots will be included.

Uncaught TypeError: Cannot set property 'value' of null

The problem is that you haven't got any element with the id u so that you are calling something that doesn't exist.
To fix that you have to add an id to the element.

<input id="u" type="text" class="searchbox1" name="search" placeholder="Search for Brand, Store or an Item..." value="text" />


And I've seen too you have added a value for the input, so it means the input is not empty and it will contain text. As result placeholder won't be displayed.

Finally there is a warning that W3Validator will say because of the "/" in the end. :

For the current document, the validator interprets strings like according to legacy rules that break the expectations of most authors and thus cause confusing warnings and error messages from the validator. This interpretation is triggered by HTML 4 documents or other SGML-based HTML documents. To avoid the messages, simply remove the "/" character in such contexts. NB: If you expect <FOO /> to be interpreted as an XML-compatible "self-closing" tag, then you need to use XHTML or HTML5.

In conclusion it says you have to remove the slash. Simply write this:

<input id="u" type="text" class="searchbox1" name="search" placeholder="Search for Brand, Store or an Item...">

How to accept Date params in a GET request to Spring MVC Controller?

Below solution perfectly works for spring boot application.

Controller:

@GetMapping("user/getAllInactiveUsers")
List<User> getAllInactiveUsers(@RequestParam("date") @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") Date dateTime) {
    return userRepository.getAllInactiveUsers(dateTime);
}

So in the caller (in my case its a web flux), we need to pass date time in this("yyyy-MM-dd HH:mm:ss") format.

Caller Side:

public Flux<UserDto> getAllInactiveUsers(String dateTime) {
    Flux<UserDto> userDto = RegistryDBService.getDbWebClient(dbServiceUrl).get()
            .uri("/user/getAllInactiveUsers?date={dateTime}", dateTime).retrieve()
            .bodyToFlux(User.class).map(UserDto::of);
    return userDto;
}

Repository:

@Query("SELECT u from User u  where u.validLoginDate < ?1 AND u.invalidLoginDate < ?1 and u.status!='LOCKED'")
List<User> getAllInactiveUsers(Date dateTime);

Cheers!!

Read/Write String from/to a File in Android

Hope this might be useful to you.

Write File:

private void writeToFile(String data,Context context) {
    try {
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("config.txt", Context.MODE_PRIVATE));
        outputStreamWriter.write(data);
        outputStreamWriter.close();
    }
    catch (IOException e) {
        Log.e("Exception", "File write failed: " + e.toString());
    } 
}

Read File:

private String readFromFile(Context context) {

    String ret = "";

    try {
        InputStream inputStream = context.openFileInput("config.txt");

        if ( inputStream != null ) {
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String receiveString = "";
            StringBuilder stringBuilder = new StringBuilder();

            while ( (receiveString = bufferedReader.readLine()) != null ) {
                stringBuilder.append("\n").append(receiveString);
            }

            inputStream.close();
            ret = stringBuilder.toString();
        }
    }
    catch (FileNotFoundException e) {
        Log.e("login activity", "File not found: " + e.toString());
    } catch (IOException e) {
        Log.e("login activity", "Can not read file: " + e.toString());
    }

    return ret;
}

How to remove elements from a generic list while iterating over it?

Using .ToList() will make a copy of your list, as explained in this question: ToList()-- Does it Create a New List?

By using ToList(), you can remove from your original list, because you're actually iterating over a copy.

foreach (var item in listTracked.ToList()) {    

        if (DetermineIfRequiresRemoval(item)) {
            listTracked.Remove(item)
        }

     }

All com.android.support libraries must use the exact same version specification

After searching and combining answers, 2018 version of this question and it worked for me:

1) On navigation tab change it to project view

2) Navigate to [YourProjectName]/.idea/libraries/

3) Delete all files starting with Gradle__com_android_support_[libraryName]

E.g: Gradle__com_android_support_animated_vector_drawable_26_0_0.xml

4) In your gradle file define a variable and use it to replace version number like ${variableName}

Def variable:

ext {
    support_library_version = '28.0.0' //use the version of choice
}

Use variable:

implementation "com.android.support:cardview-v7:${support_library_version}"

example gradle:

dependencies {
    ext {
        support_library_version = '28.0.0' //use the version of choice
    }

    implementation fileTree(include: ['*.jar'], dir: 'libs')

    implementation "com.android.support:animated-vector-drawable:${support_library_version}"
    implementation "com.android.support:appcompat-v7:${support_library_version}"
    implementation "com.android.support:customtabs:${support_library_version}"
    implementation "com.android.support:cardview-v7:${support_library_version}"
    implementation "com.android.support:support-compat:${support_library_version}"
    implementation "com.android.support:support-v4:${support_library_version}"
    implementation "com.android.support:support-core-utils:${support_library_version}"
    implementation "com.android.support:support-core-ui:${support_library_version}"
    implementation "com.android.support:support-fragment:${support_library_version}"
    implementation "com.android.support:support-media-compat:${support_library_version}"
    implementation "com.android.support:appcompat-v7:${support_library_version}"
    implementation "com.android.support:recyclerview-v7:${support_library_version}"
    implementation "com.android.support:design:${support_library_version}"

}

How should I unit test multithreaded code?

Assuming under "multi-threaded" code was meant something that is

  • stateful and mutable
  • AND accessed/modified by multiple threads concurrently

In other words we are talking about testing custom stateful thread-safe class/method/unit - which should be a very rare beast nowadays.

Because this beast is rare, first of all we need to make sure that there are all valid excuses to write it.

Step 1. Consider modifying state in same synchronization context.

Today it is easy to write compose-able concurrent and asynchronous code where IO or other slow operations offloaded to background but shared state is updated and queried in one synchronization context. e.g. async/await tasks and Rx in .NET etc. - they are all testable by design, "real" Tasks and schedulers can be substituted to make testing deterministic (however this is out of scope of the question).

It may sound very constrained but this approach works surprisingly well. It is possible to write whole apps in this style without need to make any state thread-safe (I do).

Step 2. If manipulating of shared state on single synchronization context is absolutely not possible.

Make sure the wheel is not being reinvented / there's definitely no standard alternative that can be adapted for the job. It should be likely that code is very cohesive and contained within one unit e.g. with a good chance it is a special case of some standard thread-safe data structure like hash map or collection or whatever.

Note: if code is large / spans across multiple classes AND needs multi-thread state manipulation then there's a very high chance that design is not good, reconsider Step 1

Step 3. If this step is reached then we need to test our own custom stateful thread-safe class/method/unit.

I'll be dead honest : I never had to write proper tests for such code. Most of the time I get away at Step 1, sometimes at Step 2. Last time I had to write custom thread-safe code was so many years ago that it was before I adopted unit testing / probably I wouldn't have to write it with the current knowledge anyway.

If I really had to test such code (finally, actual answer) then I would try couple of things below

  1. Non-deterministic stress testing. e.g. run 100 threads simultaneously and check that end result is consistent. This is more typical for higher level / integration testing of multiple users scenarios but also can be used at the unit level.

  2. Expose some test 'hooks' where test can inject some code to help make deterministic scenarios where one thread must perform operation before the other. As ugly as it is, I can't think of anything better.

  3. Delay-driven testing to make threads run and perform operations in particular order. Strictly speaking such tests are non-deterministic too (there's a chance of system freeze / stop-the-world GC collection which can distort otherwise orchestrated delays), also it is ugly but allows to avoid hooks.

What is an API key?

It looks like that many people use API keys as a security solution. The bottom line is: Never treat API keys as secret it is not. On https or not, whoever can read the request can see the API key and can make whatever call they want. An API Key should be just as a 'user' identifier as its not a complete security solution even when used with ssl.

The better description is in Eugene Osovetsky link to: When working with most APIs, why do they require two types of authentication, namely a key and a secret? Or check http://nordicapis.com/why-api-keys-are-not-enough/

how to merge 200 csv files in Python

Here is a script:

  • Concatenating csv files named SH1.csv to SH200.csv
  • Keeping the headers
import glob
import re

# Looking for filenames like 'SH1.csv' ... 'SH200.csv'
pattern = re.compile("^SH([1-9]|[1-9][0-9]|1[0-9][0-9]|200).csv$")
file_parts = [name for name in glob.glob('*.csv') if pattern.match(name)]

with open("file_merged.csv","wb") as file_merged:
    for (i, name) in enumerate(file_parts):
        with open(name, "rb") as file_part:
            if i != 0:
                next(file_part) # skip headers if not first file
            file_merged.write(file_part.read())

mysqldump with create database line

By default mysqldump always creates the CREATE DATABASE IF NOT EXISTS db_name; statement at the beginning of the dump file.

[EDIT] Few things about the mysqldump file and it's options:

--all-databases, -A

Dump all tables in all databases. This is the same as using the --databases option and naming all the databases on the command line.

--add-drop-database

Add a DROP DATABASE statement before each CREATE DATABASE statement. This option is typically used in conjunction with the --all-databases or --databases option because no CREATE DATABASE statements are written unless one of those options is specified.

--databases, -B

Dump several databases. Normally, mysqldump treats the first name argument on the command line as a database name and following names as table names. With this option, it treats all name arguments as database names. CREATE DATABASE and USE statements are included in the output before each new database.

--no-create-db, -n

This option suppresses the CREATE DATABASE statements that are otherwise included in the output if the --databases or --all-databases option is given.

Some time ago, there was similar question actually asking about not having such statement on the beginning of the file (for XML file). Link to that question is here.

So to answer your question:

  • if you have one database to dump, you should have the --add-drop-database option in your mysqldump statement.
  • if you have multiple databases to dump, you should use the option --databases or --all-databases and the CREATE DATABASE syntax will be added automatically

More information at MySQL Reference Manual

How to remove error about glyphicons-halflings-regular.woff2 not found

This problem happens because IIS does not find the actual location of woff2 file mime types. Set URL of font-face properly, also keep font-family as glyphicons-halflings-regular in your CSS file as shown below.

@font-face {
font-family: 'glyphicons-halflings-regular'; 
src: url('../../../fonts/glyphicons-halflings-regular.woff2') format('woff2');}

DateTimePicker: pick both date and time

Set the Format to Custom and then specify the format:

dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = "MM/dd/yyyy hh:mm:ss";  

or however you want to lay it out. You could then type in directly the date/time. If you use MMM, you'll need to use the numeric value for the month for entry, unless you write some code yourself for that (e.g., 5 results in May)

Don't know about the picker for date and time together. Sounds like a custom control to me.

Method has the same erasure as another method in type

Define a single Method without type like void add(Set ii){}

You can mention the type while calling the method based on your choice. It will work for any type of set.

How to play a local video with Swift?

Swift 3

if let filePath = Bundle.main.path(forResource: "small", ofType: ".mp4") {
    let filePathURL = NSURL.fileURL(withPath: filePath)

    let player = AVPlayer(url: filePathURL)
    let playerController = AVPlayerViewController()
    playerController.player = player
    self.present(playerController, animated: true) {
        player.play()
    }
}

Convert Python dictionary to JSON array

If you use Python 2, don't forget to add the UTF-8 file encoding comment on the first line of your script.

# -*- coding: UTF-8 -*-

This will fix some Unicode problems and make your life easier.

Disable Button in Angular 2

I tried use [disabled]="!editmode" but it not work in my case.

This is my solution [disabled]="!editmode ? 'disabled': null" , I share for whom concern.

<button [disabled]="!editmode ? 'disabled': null" 
    (click)='loadChart()'>
            <div class="btn-primary">Load Chart</div>
    </button>

Stackbliz https://stackblitz.com/edit/angular-af55ep

ping response "Request timed out." vs "Destination Host unreachable"

As I understand it, "request timeout" means the ICMP packet reached from one host to the other host but the reply could not reach the requesting host. There may be more packet loss or some physical issue. "destination host unreachable" means there is no proper route defined between two hosts.

How to Decrease Image Brightness in CSS

try this if you need to convert black image into white:

.classname{
    filter: brightness(0) invert(1);
}

How to compare two files in Notepad++ v6.6.8

There is the "Compare" plugin. You can install it via Plugins > Plugin Manager.

Alternatively you can install a specialized file compare software like WinMerge.

Setting the JVM via the command line on Windows

Yes - just explicitly provide the path to java.exe. For instance:

c:\Users\Jon\Test>"c:\Program Files\java\jdk1.6.0_03\bin\java.exe" -version
java version "1.6.0_03"
Java(TM) SE Runtime Environment (build 1.6.0_03-b05)
Java HotSpot(TM) Client VM (build 1.6.0_03-b05, mixed mode, sharing)

c:\Users\Jon\Test>"c:\Program Files\java\jdk1.6.0_12\bin\java.exe" -version
java version "1.6.0_12"
Java(TM) SE Runtime Environment (build 1.6.0_12-b04)
Java HotSpot(TM) Client VM (build 11.2-b01, mixed mode, sharing)

The easiest way to do this for a running command shell is something like:

set PATH=c:\Program Files\Java\jdk1.6.0_03\bin;%PATH%

For example, here's a complete session showing my default JVM, then the change to the path, then the new one:

c:\Users\Jon\Test>java -version
java version "1.6.0_12"
Java(TM) SE Runtime Environment (build 1.6.0_12-b04)
Java HotSpot(TM) Client VM (build 11.2-b01, mixed mode, sharing)

c:\Users\Jon\Test>set PATH=c:\Program Files\Java\jdk1.6.0_03\bin;%PATH%

c:\Users\Jon\Test>java -version
java version "1.6.0_03"
Java(TM) SE Runtime Environment (build 1.6.0_03-b05)
Java HotSpot(TM) Client VM (build 1.6.0_03-b05, mixed mode, sharing)

This won't change programs which explicitly use JAVA_HOME though.

Note that if you get the wrong directory in the path - including one that doesn't exist - you won't get any errors, it will effectively just be ignored.

space between divs - display table-cell

<div style="display:table;width:100%"  >
<div style="display:table-cell;width:49%" id="div1">
content
</div>

<!-- space between divs - display table-cell -->
<div style="display:table-cell;width:1%" id="separated"></div>
<!-- //space between divs - display table-cell -->

<div style="display:table-cell;width:50%" id="div2">
content
</div>
</div>

Convert Variable Name to String?

I think this is a cool solution and I suppose the best you can get. But do you see any way to handle the ambigious results, your function may return? As "is" operator behaves unexpectedly with integers shows, low integers and strings of the same value get cached by python so that your variablename-function might priovide ambigous results with a high probability. In my case, I would like to create a decorator, that adds a new variable to a class by the varialbename i pass it:

def inject(klass, dependency):
klass.__dict__["__"+variablename(dependency)]=dependency

But if your method returns ambigous results, how can I know the name of the variable I added?

var any_var="myvarcontent"
var myvar="myvarcontent"
@inject(myvar)
class myclasss():
    def myclass_method(self):
        print self.__myvar    #I can not be sure, that this variable will be set...

Maybe if I will also check the local list I could at least remove the "dependency"-Variable from the list, but this will not be a reliable result.

When should we use mutex and when should we use semaphore

Here is how I remember when to use what -

Semaphore: Use a semaphore when you (thread) want to sleep till some other thread tells you to wake up. Semaphore 'down' happens in one thread (producer) and semaphore 'up' (for same semaphore) happens in another thread (consumer) e.g.: In producer-consumer problem, producer wants to sleep till at least one buffer slot is empty - only the consumer thread can tell when a buffer slot is empty.

Mutex: Use a mutex when you (thread) want to execute code that should not be executed by any other thread at the same time. Mutex 'down' happens in one thread and mutex 'up' must happen in the same thread later on. e.g.: If you are deleting a node from a global linked list, you do not want another thread to muck around with pointers while you are deleting the node. When you acquire a mutex and are busy deleting a node, if another thread tries to acquire the same mutex, it will be put to sleep till you release the mutex.

Spinlock: Use a spinlock when you really want to use a mutex but your thread is not allowed to sleep. e.g.: An interrupt handler within OS kernel must never sleep. If it does the system will freeze / crash. If you need to insert a node to globally shared linked list from the interrupt handler, acquire a spinlock - insert node - release spinlock.

Compiling/Executing a C# Source File in Command Prompt

You can compile a C# program :

c: > csc Hello.cs

You can run the program

c: > Hello

Getting HTML elements by their attribute names

You can get attribute using javascript,

element.getAttribute(attributeName);

Ex:

var wrap = document.getElementById("wrap");
var myattr = wrap.getAttribute("title");

Refer:

https://developer.mozilla.org/en/DOM/element.getAttribute

Downloading Java JDK on Linux via wget is shown license page instead

download jdk 8u221

$ wget -c --content-disposition "https://javadl.oracle.com/webapps/download/AutoDL?BundleId=239835_230deb18db3e4014bb8e3e8324f81b43"
$ old=$(ls -hat | grep jre | head -n1)
$ mv $old $(echo $old | awk -F"?" '{print $1}')

my blog 044-wget??jdk8u221

Go build: "Cannot find package" (even though GOPATH is set)

In the recent go versions from 1.14 onwards, we have to do go mod vendor before building or running, since by default go appends -mod=vendor to the go commands. So after doing go mod vendor, if we try to build, we won't face this issue.

Hot deploy on JBoss - how do I make JBoss "see" the change?

Hot deployment is stable only for changes on static parts of the application (jsf, xhtml, etc.).

Here is a working solution, according to JBoss AS 7.1.1.Final:

  • Build your project.
  • Navigate to [JBOSS_HOME]/standalone/tmp/vfs.
  • Open the most recently modified folder named "deployment[some_alphanumeric_values]", i.e. "deployment344b1c870c8edbd".
  • Navigate to the specific view that you want to edit (usually, this is included into the packaged .war folder) and open it with a text editor (i.e. Notepad++).
  • Make the changes you want and save the file.
  • Refresh the respective page on your browser. The changes should be visible now.
  • When finished, don't forget to copy these changes to your actual development environment, rebuild and redeploy.

    C++ JSON Serialization

    This is my attempt using Qt: https://github.com/carlonluca/lqobjectserializer. A JSON like this:

    {"menu": {
        "header": "SVG Viewer",
        "items": [
            {"id": "Open"},
            {"id": "OpenNew", "label": "Open New"},
            null,
            {"id": "ZoomIn", "label": "Zoom In"},
            {"id": "ZoomOut", "label": "Zoom Out"},
            {"id": "OriginalView", "label": "Original View"},
            null,
            {"id": "Quality"},
            {"id": "Pause"},
            {"id": "Mute"},
            null,
            {"id": "Find", "label": "Find..."},
            {"id": "FindAgain", "label": "Find Again"},
            {"id": "Copy"},
            {"id": "CopyAgain", "label": "Copy Again"},
            {"id": "CopySVG", "label": "Copy SVG"},
            {"id": "ViewSVG", "label": "View SVG"},
            {"id": "ViewSource", "label": "View Source"},
            {"id": "SaveAs", "label": "Save As"},
            null,
            {"id": "Help"},
            {"id": "About", "label": "About Adobe CVG Viewer..."}
        ]
    }}
    

    can be deserialized by declaring classes like these:

    L_BEGIN_CLASS(Item)
    L_RW_PROP(QString, id, setId, QString())
    L_RW_PROP(QString, label, setLabel, QString())
    L_END_CLASS
    
    L_BEGIN_CLASS(Menu)
    L_RW_PROP(QString, header, setHeader)
    L_RW_PROP_ARRAY_WITH_ADDER(Item*, items, setItems)
    L_END_CLASS
    
    L_BEGIN_CLASS(MenuRoot)
    L_RW_PROP(Menu*, menu, setMenu, nullptr)
    L_END_CLASS
    

    and writing writing:

    LDeserializer<MenuRoot> deserializer;
    QScopedPointer<MenuRoot> g(deserializer.deserialize(jsonString));
    

    You also need to inject mappings for meta objects once:

    QHash<QString, QMetaObject> factory {
        { QSL("Item*"), Item::staticMetaObject },
        { QSL("Menu*"), Menu::staticMetaObject }
    };
    

    I'm looking for a way to avoid this.

    how to create a cookie and add to http response from inside my service layer?

    To add a new cookie, use HttpServletResponse.addCookie(Cookie). The Cookie is pretty much a key value pair taking a name and value as strings on construction.

    Why is "except: pass" a bad programming practice?

    >>> import this
    

    The Zen of Python, by Tim Peters

    Beautiful is better than ugly.
    Explicit is better than implicit.
    Simple is better than complex.
    Complex is better than complicated.
    Flat is better than nested.
    Sparse is better than dense.
    Readability counts.
    Special cases aren't special enough to break the rules.
    Although practicality beats purity.
    Errors should never pass silently.
    Unless explicitly silenced.
    In the face of ambiguity, refuse the temptation to guess.
    There should be one-- and preferably only one --obvious way to do it.
    Although that way may not be obvious at first unless you're Dutch.
    Now is better than never.
    Although never is often better than right now.
    If the implementation is hard to explain, it's a bad idea.
    If the implementation is easy to explain, it may be a good idea.
    Namespaces are one honking great idea -- let's do more of those!

    So, here is my opinion. Whenever you find an error, you should do something to handle it, i.e. write it in logfile or something else. At least, it informs you that there used to be a error.

    What is the difference between absolute and relative xpaths? Which is preferred in Selenium automation testing?

    Absolute Xpath: It uses Complete path from the Root Element to the desire element.

    Relative Xpath: You can simply start by referencing the element you want and go from there.

    Relative Xpaths are always preferred as they are not the complete paths from the root element. (//html//body). Because in future, if any webelement is added/removed, then the absolute Xpath changes. So Always use Relative Xpaths in your Automation.

    Below are Some Links which you can Refer for more Information on them.

    Splitting strings using a delimiter in python

    So, your input is 'dan|warrior|54' and you want "warrior". You do this like so:

    >>> dan = 'dan|warrior|54'
    >>> dan.split('|')[1]
    "warrior"
    

    How to read xml file contents in jQuery and display in html elements?

    _x000D_
    _x000D_
     $.get("/folder_name/filename.xml", function (xml) {_x000D_
     var xmlInnerhtml = xml.documentElement.innerHTML;_x000D_
     });
    _x000D_
    _x000D_
    _x000D_

    Python for and if on one line

    You are producing a filtered list by using a list comprehension. i is still being bound to each and every element of that list, and the last element is still 'three', even if it was subsequently filtered out from the list being produced.

    You should not use a list comprehension to pick out one element. Just use a for loop, and break to end it:

    for elem in my_list:
        if elem == 'two':
            break
    

    If you must have a one-liner (which would be counter to Python's philosophy, where readability matters), use the next() function and a generator expression:

    i = next((elem for elem in my_list if elem == 'two'), None)
    

    which will set i to None if there is no such matching element.

    The above is not that useful a filter; your are essentially testing if the value 'two' is in the list. You can use in for that:

    elem = 'two' if 'two' in my_list else None
    

    asp.net mvc3 return raw html to view

    There's no much point in doing that, because View should be generating html, not the controller. But anyways, you could use Controller.Content method, which gives you ability to specify result html, also content-type and encoding

    public ActionResult Index()
    {
        return Content("<html></html>");
    }
    

    Or you could use the trick built in asp.net-mvc framework - make the action return string directly. It will deliver string contents into users's browser.

    public string Index()
    {
        return "<html></html>";
    }
    

    In fact, for any action result other than ActionResult, framework tries to serialize it into string and write to response.

    In Java, how do I get the difference in seconds between 2 dates?

    It is not recommended to use java.util.Date or System.currentTimeMillis() to measure elapsed times. These dates are not guaranteed to be monotonic and will changes occur when the system clock is modified (eg when corrected from server). In probability this will happen rarely, but why not code a better solution rather than worrying about possibly negative or very large changes?

    Instead I would recommend using System.nanoTime().

    long t1 = System.nanoTime();
    long t2 = System.nanoTime();
    
    long elapsedTimeInSeconds = (t2 - t1) / 1000000000;
    

    EDIT

    For more information about monoticity see the answer to a related question I asked, where possible nanoTime uses a monotonic clock. I have tested but only using Windows XP, Java 1.6 and modifying the clock whereby nanoTime was monotonic and currentTimeMillis wasn't.

    Also from Java's Real time doc's:

    Q: 50. Is the time returned via the real-time clock of better resolution than that returned by System.nanoTime()?

    The real-time clock and System.nanoTime() are both based on the same system call and thus the same clock.

    With Java RTS, all time-based APIs (for example, Timers, Periodic Threads, Deadline Monitoring, and so forth) are based on the high-resolution timer. And, together with real-time priorities, they can ensure that the appropriate code will be executed at the right time for real-time constraints. In contrast, ordinary Java SE APIs offer just a few methods capable of handling high-resolution times, with no guarantee of execution at a given time. Using System.nanoTime() between various points in the code to perform elapsed time measurements should always be accurate.

    Iterator Loop vs index loop

    its a matter of speed. using the iterator accesses the elements faster. a similar question was answered here:

    What's faster, iterating an STL vector with vector::iterator or with at()?

    Edit: speed of access varies with each cpu and compiler

    Delaying function in swift

    You can use GCD (in the example with a 10 second delay):

    Swift 2

    let triggerTime = (Int64(NSEC_PER_SEC) * 10)
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, triggerTime), dispatch_get_main_queue(), { () -> Void in
        self.functionToCall()
    })
    

    Swift 3 and Swift 4

    DispatchQueue.main.asyncAfter(deadline: .now() + 10.0, execute: {
        self.functionToCall()
    })
    

    Swift 5 or Later

     DispatchQueue.main.asyncAfter(deadline: .now() + 10.0) {
            //call any function
        }
    

    how to set default culture info for entire c# application

    Not for entire application or particular class.

    CurrentUICulture and CurrentCulture are settable per thread as discussed here Is there a way of setting culture for a whole application? All current threads and new threads?. You can't change InvariantCulture at all.

    Sample code to change cultures for current thread:

    CultureInfo ci = new CultureInfo(theCultureString);
    Thread.CurrentThread.CurrentCulture = ci;
    Thread.CurrentThread.CurrentUICulture = ci;
    

    For class you can set/restore culture inside critical methods, but it would be significantly safe to use appropriate overrides for most formatting related methods that take culture as one of arguments:

    (3.3).ToString(new CultureInfo("fr-FR"))
    

    How to execute a bash command stored as a string with quotes and asterisk

    Use an array, not a string, as given as guidance in BashFAQ #50.

    Using a string is extremely bad security practice: Consider the case where password (or a where clause in the query, or any other component) is user-provided; you don't want to eval a password containing $(rm -rf .)!


    Just Running A Local Command

    cmd=( mysql AMORE -u username -ppassword -h localhost -e "SELECT  host  FROM amoreconfig" )
    "${cmd[@]}"
    

    Printing Your Command Unambiguously

    cmd=( mysql AMORE -u username -ppassword -h localhost -e "SELECT  host  FROM amoreconfig" )
    printf 'Proposing to run: '
    printf '%q ' "${cmd[@]}"
    printf '\n'
    

    Running Your Command Over SSH (Method 1: Using Stdin)

    cmd=( mysql AMORE -u username -ppassword -h localhost -e "SELECT  host  FROM amoreconfig" )
    printf -v cmd_str '%q ' "${cmd[@]}"
    ssh other_host 'bash -s' <<<"$cmd_str"
    

    Running Your Command Over SSH (Method 2: Command Line)

    cmd=( mysql AMORE -u username -ppassword -h localhost -e "SELECT  host  FROM amoreconfig" )
    printf -v cmd_str '%q ' "${cmd[@]}"
    ssh other_host "bash -c $cmd_str"
    

    How do you create a toggle button?

    You can use the "active" pseudoclass (it won't work on IE6, though, for elements other than links)

    a:active
    {
        ...desired style here...
    }
    

    Executing <script> elements inserted with .innerHTML

    @phidah... Here is a very interesting solution to your problem: http://24ways.org/2005/have-your-dom-and-script-it-too

    So it would look like this instead:

    <img src="empty.gif" onload="alert('test');this.parentNode.removeChild(this);" />

    How to use Lambda in LINQ select statement

    Lambda Expression result

    var storesList = context.Stores.Select(x => new { Value= x.name,Text= x.ID }).ToList();
    

    Serializing an object as UTF-8 XML in .NET

    Very good answer using inheritance, just remember to override the initializer

    public class Utf8StringWriter : StringWriter
    {
        public Utf8StringWriter(StringBuilder sb) : base (sb)
        {
        }
        public override Encoding Encoding { get { return Encoding.UTF8; } }
    }
    

    Eclipse/Maven error: "No compiler is provided in this environment"

    1. Uninstall older Java(JDK/JRE) from the system( Keep one (latest) java version), Also remove if any old java jre/jdk entries in environment variables PATH/CLASSPATH
    2. Eclipse->Window->Preferences->Installed JREs->Add/Edit JDK from the latest installation
    3. Eclipse->Window->Preferences->Installed JREs->Execution Environment->Select the desired java version on left and click the check box on right
    4. If you are using maven include the following tag in pom.xml (update versions as needed) inside plugins tag.

      <plugin>  
              <groupId>org.apache.maven.plugins</groupId>
              <artifactId>maven-compiler-plugin</artifactId>
              <version>3.1</version>
              <configuration>
                  <source>1.8</source>
                  <target>1.8</target>
              </configuration>
          </plugin>
      
    5. Right click on eclipse project Maven - > Update Project

    How to put/get multiple JSONObjects to JSONArray?

    Once you have put the values into the JSONObject then put the JSONObject into the JSONArray staright after.

    Something like this maybe:

    jsonObj.put("value1", 1);
    jsonObj.put("value2", 900);
    jsonObj.put("value3", 1368349);
    jsonArray.put(jsonObj);
    

    Then create new JSONObject, put the other values into it and add it to the JSONArray:

    jsonObj.put("value1", 2);
    jsonObj.put("value2", 1900);
    jsonObj.put("value3", 136856);
    jsonArray.put(jsonObj);
    

    Huge performance difference when using group by vs distinct

    The two queries express the same question. Apparently the query optimizer chooses two different execution plans. My guess would be that the distinct approach is executed like:

    • Copy all business_key values to a temporary table
    • Sort the temporary table
    • Scan the temporary table, returning each item that is different from the one before it

    The group by could be executed like:

    • Scan the full table, storing each value of business key in a hashtable
    • Return the keys of the hashtable

    The first method optimizes for memory usage: it would still perform reasonably well when part of the temporary table has to be swapped out. The second method optimizes for speed, but potentially requires a large amount of memory if there are a lot of different keys.

    Since you either have enough memory or few different keys, the second method outperforms the first. It's not unusual to see performance differences of 10x or even 100x between two execution plans.

    In Java, how do I check if a string contains a substring (ignoring case)?

    You can use the toLowerCase() method:

    public boolean contains( String haystack, String needle ) {
      haystack = haystack == null ? "" : haystack;
      needle = needle == null ? "" : needle;
    
      // Works, but is not the best.
      //return haystack.toLowerCase().indexOf( needle.toLowerCase() ) > -1
    
      return haystack.toLowerCase().contains( needle.toLowerCase() )
    }
    

    Then call it using:

    if( contains( str1, str2 ) ) {
      System.out.println( "Found " + str2 + " within " + str1 + "." );
    }
    

    Notice that by creating your own method, you can reuse it. Then, when someone points out that you should use contains instead of indexOf, you have only a single line of code to change.

    How to plot data from multiple two column text files with legends in Matplotlib?

    Assume your file looks like this and is named test.txt (space delimited):

    1 2
    3 4
    5 6
    7 8
    

    Then:

    #!/usr/bin/python
    
    import numpy as np
    import matplotlib.pyplot as plt
    
    with open("test.txt") as f:
        data = f.read()
    
    data = data.split('\n')
    
    x = [row.split(' ')[0] for row in data]
    y = [row.split(' ')[1] for row in data]
    
    fig = plt.figure()
    
    ax1 = fig.add_subplot(111)
    
    ax1.set_title("Plot title...")    
    ax1.set_xlabel('your x label..')
    ax1.set_ylabel('your y label...')
    
    ax1.plot(x,y, c='r', label='the data')
    
    leg = ax1.legend()
    
    plt.show()
    

    Example plot:

    I find that browsing the gallery of plots on the matplotlib site helpful for figuring out legends and axes labels.

    Create an array of integers property in Objective-C

    This works

    @interface RGBComponents : NSObject {
    
        float components[8];
    
    }
    
    @property(readonly) float * components;
    

    - (float *) components {
        return components;
    }
    

    Recursion in Python? RuntimeError: maximum recursion depth exceeded while calling a Python object

    The error is a stack overflow. That should ring a bell on this site, right? It occurs because a call to poruszanie results in another call to poruszanie, incrementing the recursion depth by 1. The second call results in another call to the same function. That happens over and over again, each time incrementing the recursion depth.

    Now, the usable resources of a program are limited. Each function call takes a certain amount of space on top of what is called the stack. If the maximum stack height is reached, you get a stack overflow error.

    Convert Pandas Column to DateTime

    Use the to_datetime function, specifying a format to match your data.

    raw_data['Mycol'] =  pd.to_datetime(raw_data['Mycol'], format='%d%b%Y:%H:%M:%S.%f')
    

    How to read GET data from a URL using JavaScript?

    I also made a fairly simple function. You call on it by: get("yourgetname");

    and get whatever there was. (now that i wrote it i noticed it will give you %26 if you had a & in your value..)

    function get(name){
      var url = window.location.search;
      var num = url.search(name);
      var namel = name.length;
      var frontlength = namel+num+1; //length of everything before the value 
      var front = url.substring(0, frontlength);  
      url = url.replace(front, "");  
      num = url.search("&");
    
     if(num>=0) return url.substr(0,num); 
     if(num<0)  return url;             
    }
    

    How to delete last character from a string using jQuery?

    @skajfes and @GolezTrol provided the best methods to use. Personally, I prefer using "slice()". It's less code, and you don't have to know how long a string is. Just use:

    //-----------------------------------------
    // @param begin  Required. The index where 
    //               to begin the extraction. 
    //               1st character is at index 0
    //
    // @param end    Optional. Where to end the
    //               extraction. If omitted, 
    //               slice() selects all 
    //               characters from the begin 
    //               position to the end of 
    //               the string.
    var str = '123-4';
    alert(str.slice(0, -1));
    

    load Js file in HTML

    If this is your detail.html I don't see where do you load detail.js? Maybe this

    <script src="js/index.js"></script>
    

    should be this

    <script src="js/detail.js"></script>
    

    ?

    How can I get key's value from dictionary in Swift?

    Use subscripting to access the value for a dictionary key. This will return an Optional:

    let apple: String? = companies["AAPL"]
    

    or

    if let apple = companies["AAPL"] {
        // ...
    }
    

    You can also enumerate over all of the keys and values:

    var companies = ["AAPL" : "Apple Inc", "GOOG" : "Google Inc", "AMZN" : "Amazon.com, Inc", "FB" : "Facebook Inc"]
    
    for (key, value) in companies {
        print("\(key) -> \(value)")
    }
    

    Or enumerate over all of the values:

    for value in Array(companies.values) {
        print("\(value)")
    }
    

    How to make JavaScript execute after page load?

    Comparison

    In below snippet I collect choosen methods and show their sequence. Remarks

    • the document.onload (X) is not supported by any modern browser (event is never fired)
    • if you use <body onload="bodyOnLoad()"> (F) and at the same time window.onload (E) then only first one will be executed (because it override second one)
    • event handler given in <body onload="..."> (F) is wrapped by additional onload function
    • document.onreadystatechange (D) not override document .addEventListener('readystatechange'...) (C) probably cecasue onXYZevent-like methods are independent than addEventListener queues (which allows add multiple listeners). Probably nothing happens between execution this two handlers.
    • all scripts write their timestamp in console - but scripts which also have access to div write their timestamps also in body (click "Full Page" link after script execution to see it).
    • solutions readystatechange (C,D) are executed multiple times by browser but for different document states:
      • loading - the document is loading (no fired in snippet)
      • interactive - the document is parsed, fired before DOMContentLoaded
      • complete - the document and resources are loaded, fired before body/window onload

    _x000D_
    _x000D_
    <html>_x000D_
    _x000D_
    <head>_x000D_
      <script>_x000D_
        // solution A_x000D_
        console.log(`[timestamp: ${Date.now()}] A: Head script`);_x000D_
        _x000D_
        // solution B_x000D_
        document.addEventListener("DOMContentLoaded", () => {_x000D_
          print(`[timestamp: ${Date.now()}] B: DOMContentLoaded`);_x000D_
        });_x000D_
    _x000D_
        // solution C_x000D_
        document.addEventListener('readystatechange', () => {_x000D_
          print(`[timestamp: ${Date.now()}] C: ReadyState: ${document.readyState}`);_x000D_
        });_x000D_
       _x000D_
        // solution D_x000D_
        document.onreadystatechange = s=> {print(`[timestamp: ${Date.now()}] D: document.onreadystatechange ReadyState: ${document.readyState}`)};_x000D_
        _x000D_
        // solution E (never executed)_x000D_
        window.onload = () => {_x000D_
          print(`E: <body onload="..."> override this handler`);_x000D_
        };_x000D_
    _x000D_
        // solution F_x000D_
        function bodyOnLoad() {_x000D_
          print(`[timestamp: ${Date.now()}] F: <body onload='...'>`);      _x000D_
          infoAboutOnLoad(); // additional info_x000D_
        }_x000D_
        _x000D_
        // solution X_x000D_
        document.onload = () => {print(`document.onload is never fired`)};_x000D_
    _x000D_
    _x000D_
    _x000D_
        // HELPERS_x000D_
    _x000D_
        function print(txt) { _x000D_
          console.log(txt);_x000D_
          if(mydiv) mydiv.innerHTML += txt.replace('<','&lt;').replace('>','&gt;') + '<br>';_x000D_
        }_x000D_
        _x000D_
        function infoAboutOnLoad() {_x000D_
          console.log("window.onload (after  override):", (''+document.body.onload).replace(/\s+/g,' '));_x000D_
          console.log(`body.onload==window.onload --> ${document.body.onload==window.onload}`);_x000D_
        }_x000D_
                _x000D_
        console.log("window.onload (before override):", (''+document.body.onload).replace(/\s+/g,' '));_x000D_
    _x000D_
      </script>_x000D_
    </head>_x000D_
    _x000D_
    <body onload="bodyOnLoad()">_x000D_
      <div id="mydiv"></div>_x000D_
    _x000D_
      <!-- this script must te at the bottom of <body> -->_x000D_
      <script>_x000D_
        // solution G_x000D_
        print(`[timestamp: ${Date.now()}] G: <body> bottom script`);_x000D_
      </script>_x000D_
    </body>_x000D_
    _x000D_
    </html>
    _x000D_
    _x000D_
    _x000D_

    Calculate time difference in minutes in SQL Server

    The following works as expected:

    SELECT  Diff = CASE DATEDIFF(HOUR, StartTime, EndTime)
                        WHEN 0 THEN CAST(DATEDIFF(MINUTE, StartTime, EndTime) AS VARCHAR(10))
                        ELSE CAST(60 - DATEPART(MINUTE, StartTime) AS VARCHAR(10)) +
                            REPLICATE(',60', DATEDIFF(HOUR, StartTime, EndTime) - 1) + 
                            + ',' + CAST(DATEPART(MINUTE, EndTime) AS VARCHAR(10))
                    END
    FROM    (VALUES 
                (CAST('11:15' AS TIME), CAST('13:15' AS TIME)),
                (CAST('10:45' AS TIME), CAST('18:59' AS TIME)),
                (CAST('10:45' AS TIME), CAST('11:59' AS TIME))
            ) t (StartTime, EndTime);
    

    To get 24 columns, you could use 24 case expressions, something like:

    SELECT  [0] = CASE WHEN DATEDIFF(HOUR, StartTime, EndTime) = 0
                            THEN DATEDIFF(MINUTE, StartTime, EndTime)
                        ELSE 60 - DATEPART(MINUTE, StartTime)
                    END,
            [1] = CASE WHEN DATEDIFF(HOUR, StartTime, EndTime) = 1 
                            THEN DATEPART(MINUTE, EndTime)
                        WHEN DATEDIFF(HOUR, StartTime, EndTime) > 1 THEN 60
                    END,
            [2] = CASE WHEN DATEDIFF(HOUR, StartTime, EndTime) = 2
                            THEN DATEPART(MINUTE, EndTime)
                        WHEN DATEDIFF(HOUR, StartTime, EndTime) > 2 THEN 60
                    END -- ETC
    FROM    (VALUES 
                (CAST('11:15' AS TIME), CAST('13:15' AS TIME)),
                (CAST('10:45' AS TIME), CAST('18:59' AS TIME)),
                (CAST('10:45' AS TIME), CAST('11:59' AS TIME))
            ) t (StartTime, EndTime);
    

    The following also works, and may end up shorter than repeating the same case expression over and over:

    WITH Numbers (Number) AS
    (   SELECT  ROW_NUMBER() OVER(ORDER BY t1.N) - 1
        FROM    (VALUES (1), (1), (1), (1), (1), (1)) AS t1 (N)
                CROSS JOIN (VALUES (1), (1), (1), (1)) AS t2 (N)
    ), YourData AS
    (   SELECT  StartTime, EndTime
        FROM    (VALUES 
                    (CAST('11:15' AS TIME), CAST('13:15' AS TIME)),
                    (CAST('09:45' AS TIME), CAST('18:59' AS TIME)),
                    (CAST('10:45' AS TIME), CAST('11:59' AS TIME))
                ) AS t (StartTime, EndTime)
    ), PivotData AS
    (   SELECT  t.StartTime,
                t.EndTime,
                n.Number,
                MinuteDiff = CASE WHEN n.Number = 0 AND DATEDIFF(HOUR, StartTime, EndTime) = 0 THEN DATEDIFF(MINUTE, StartTime, EndTime)
                                    WHEN n.Number = 0 THEN 60 - DATEPART(MINUTE, StartTime)
                                    WHEN DATEDIFF(HOUR, t.StartTime, t.EndTime) <= n.Number THEN DATEPART(MINUTE, EndTime)
                                    ELSE 60
                                END
        FROM    YourData AS t
                INNER JOIN Numbers AS n
                    ON n.Number <= DATEDIFF(HOUR, StartTime, EndTime)
    )
    SELECT  *
    FROM    PivotData AS d
            PIVOT 
            (   MAX(MinuteDiff)
                FOR Number IN 
                (   [0], [1], [2], [3], [4], [5], 
                    [6], [7], [8], [9], [10], [11],
                    [12], [13], [14], [15], [16], [17], 
                    [18], [19], [20], [21], [22], [23]
                ) 
            ) AS pvt;
    

    It works by joining to a table of 24 numbers, so the case expression doesn't need to be repeated, then rolling these 24 numbers back up into columns using PIVOT