Programs & Examples On #Live streaming

Live Streaming is the action of streaming a media (voice, video) over the network in real time.

Live-stream video from one android phone to another over WiFi

I did work on something like this once, but sending a video and playing it in real time is a really complex thing. I suggest you work with PNG's only. In my implementation What i did was capture PNGs using the host camera and then sending them over the network to the client, Which will display the image as soon as received and request the next image from the host. Since you are on wifi that communication will be fast enough to get around 8-10 images per-second(approximation only, i worked on Bluetooth). So this will look like a continuous video but with much less effort. For communication you may use UDP sockets(Faster and less complex) or DLNA (Not sure how that works).

What is the difference between RTP or RTSP in a streaming server?

AFAIK, RTSP does not transmit streams at all, it is just an out-of-band control protocol with functions like PLAY and STOP.

Raw UDP or RTP over UDP are transmission protocols for streams just like raw TCP or HTTP over TCP.

To be able to stream a certain program over the given transmission protocol, an encapsulation method has to be defined for your container format. For example TS container can be transmitted over UDP but Matroska can not.

Pretty much everything can be transported through TCP though.

(The fact that which codec do you use also matters indirectly as it restricts the container formats you can use.)

java.lang.NoClassDefFoundError: com/fasterxml/jackson/core/JsonFactory

Because of old version I got this error. Then I changed to this version n error gone Using maven my pom.xml



my old version was '2.2.3'

EC2 instance types's exact network performance?

FWIW CloudFront supports streaming as well. Might be better than plain streaming from instances.

How to embed new Youtube's live video permanent URL?

Here's how to do it in Squarespace using the embed block classes to create responsiveness.

Put this into a code block:

<div class="sqs-block embed-block sqs-block-embed" data-block-type="22" >
    <div class="sqs-block-content"><div class="intrinsic" style="max-width:100%">
        <div class="embed-block-wrapper embed-block-provider-YouTube" style="padding-bottom:56.20609%;">
            <iframe allow="autoplay; fullscreen" scrolling="no" data-image-dimensions="854x480" allowfullscreen="true" src="" width="854" data-embed="true" frameborder="0" title="YouTube embed" class="embedly-embed" height="480">

Tweak however you'd like!

What is the Angular equivalent to an AngularJS $watch?

This behaviour is now part of the component lifecycle.

A component can implement the ngOnChanges method in the OnChanges interface to get access to input changes.


import {Component, Input, OnChanges} from 'angular2/core';

  selector: 'hero-comp',
  templateUrl: 'app/components/hero-comp/hero-comp.html',
  styleUrls: ['app/components/hero-comp/hero-comp.css'],
  providers: [],
  directives: [],

  pipes: [],
  inputs:['hero', 'real']
export class HeroComp implements OnChanges{
  @Input() hero:Hero;
  @Input() real:string;
  constructor() {
  ngOnChanges(changes) {

Stop on first error

Maybe you want set -e:

This tells bash that it should exit the script if any statement returns a non-true return value. The benefit of using -e is that it prevents errors snowballing into serious issues when they could have been caught earlier. Again, for readability you may want to use set -o errexit.

Business logic in MVC

A1: Business Logic goes to Model part in MVC. Role of Model is to contain data and business logic. Controller on the other hand is responsible to receive user input and decide what to do.

A2: A Business Rule is part of Business Logic. They have a has a relationship. Business Logic has Business Rules.

Take a look at Wikipedia entry for MVC. Go to Overview where it mentions the flow of MVC pattern.

Also look at Wikipedia entry for Business Logic. It is mentioned that Business Logic is comprised of Business Rules and Workflow.

JPA or JDBC, how are they different?

In layman's terms:

  • JDBC is a standard for Database Access
  • JPA is a standard for ORM

JDBC is a standard for connecting to a DB directly and running SQL against it - e.g SELECT * FROM USERS, etc. Data sets can be returned which you can handle in your app, and you can do all the usual things like INSERT, DELETE, run stored procedures, etc. It is one of the underlying technologies behind most Java database access (including JPA providers).

One of the issues with traditional JDBC apps is that you can often have some crappy code where lots of mapping between data sets and objects occur, logic is mixed in with SQL, etc.

JPA is a standard for Object Relational Mapping. This is a technology which allows you to map between objects in code and database tables. This can "hide" the SQL from the developer so that all they deal with are Java classes, and the provider allows you to save them and load them magically. Mostly, XML mapping files or annotations on getters and setters can be used to tell the JPA provider which fields on your object map to which fields in the DB. The most famous JPA provider is Hibernate, so it's a good place to start for concrete examples.

Other examples include OpenJPA, toplink, etc.

Under the hood, Hibernate and most other providers for JPA write SQL and use JDBC to read and write from and to the DB.

How to merge multiple lists into one list in python?

import itertools
ab = itertools.chain(['it'], ['was'], ['annoying'])

Just another method....

how to make a countdown timer in java

You can create a countdown timer using applet, below is the code,

   import java.applet.*;
   import java.awt.*;
   import java.awt.event.*;
   import javax.swing.*;
   import javax.swing.Timer; // not java.util.Timer
   import java.text.NumberFormat;

    * An applet that counts down from a specified time. When it reaches 00:00,
    * it optionally plays a sound and optionally moves the browser to a new page.
    * Place the mouse over the applet to pause the count; move it off to resume.
    * This class demonstrates most applet methods and features.

public class Countdown extends JApplet implements ActionListener, MouseListener
long remaining; // How many milliseconds remain in the countdown.
long lastUpdate; // When count was last updated
JLabel label; // Displays the count
Timer timer; // Updates the count every second
NumberFormat format; // Format minutes:seconds with leading zeros
Image image; // Image to display along with the time
AudioClip sound; // Sound to play when we reach 00:00

// Called when the applet is first loaded
public void init() {
    // Figure out how long to count for by reading the "minutes" parameter
    // defined in a <param> tag inside the <applet> tag. Convert to ms.
    String minutes = getParameter("minutes");
    if (minutes != null) remaining = Integer.parseInt(minutes) * 60000;
    else remaining = 600000; // 10 minutes by default

    // Create a JLabel to display remaining time, and set some properties.
    label = new JLabel();
    label.setHorizontalAlignment(SwingConstants.CENTER );
    label.setOpaque(true); // So label draws the background color

    // Read some parameters for this JLabel object
    String font = getParameter("font");
    String foreground = getParameter("foreground");
    String background = getParameter("background");
    String imageURL = getParameter("image");

    // Set label properties based on those parameters
    if (font != null) label.setFont(Font.decode(font));
    if (foreground != null) label.setForeground(Color.decode(foreground));
    if (background != null) label.setBackground(Color.decode(background));
    if (imageURL != null) {
        // Load the image, and save it so we can release it later
        image = getImage(getDocumentBase(), imageURL);
        // Now display the image in the JLabel.
        label.setIcon(new ImageIcon(image));

    // Now add the label to the applet. Like JFrame and JDialog, JApplet
    // has a content pane that you add children to
    getContentPane().add(label, BorderLayout.CENTER);

    // Get an optional AudioClip to play when the count expires
    String soundURL = getParameter("sound");
    if (soundURL != null) sound=getAudioClip(getDocumentBase(), soundURL);

    // Obtain a NumberFormat object to convert number of minutes and
    // seconds to strings. Set it up to produce a leading 0 if necessary
    format = NumberFormat.getNumberInstance();
    format.setMinimumIntegerDigits(2); // pad with 0 if necessary

    // Specify a MouseListener to handle mouse events in the applet.
    // Note that the applet implements this interface itself

    // Create a timer to call the actionPerformed() method immediately,
    // and then every 1000 milliseconds. Note we don't start the timer yet.
    timer = new Timer(1000, this);
    timer.setInitialDelay(0); // First timer is immediate.

// Free up any resources we hold; called when the applet is done
public void destroy() { if (image != null) image.flush(); }

// The browser calls this to start the applet running
// The resume() method is defined below.
public void start() { resume(); } // Start displaying updates

// The browser calls this to stop the applet. It may be restarted later.
// The pause() method is defined below
public void stop() { pause(); } // Stop displaying updates

// Return information about the applet
public String getAppletInfo() {
    return "Countdown applet Copyright (c) 2003 by David Flanagan";

// Return information about the applet parameters
public String[][] getParameterInfo() { return parameterInfo; }

// This is the parameter information. One array of strings for each
// parameter. The elements are parameter name, type, and description.
static String[][] parameterInfo = {
    {"minutes", "number", "time, in minutes, to countdown from"},
    {"font", "font", "optional font for the time display"},
    {"foreground", "color", "optional foreground color for the time"},
    {"background", "color", "optional background color"},
    {"image", "image URL", "optional image to display next to countdown"},
    {"sound", "sound URL", "optional sound to play when we reach 00:00"},
    {"newpage", "document URL", "URL to load when timer expires"},

// Start or resume the countdown
void resume() {
    // Restore the time we're counting down from and restart the timer.
    lastUpdate = System.currentTimeMillis();
    timer.start(); // Start the timer

// Pause the countdown
void pause() {
    // Subtract elapsed time from the remaining time and stop timing
    long now = System.currentTimeMillis();
    remaining -= (now - lastUpdate);
    timer.stop(); // Stop the timer

// Update the displayed time. This method is called from actionPerformed()
// which is itself invoked by the timer.
void updateDisplay() {
    long now = System.currentTimeMillis(); // current time in ms
    long elapsed = now - lastUpdate; // ms elapsed since last update
    remaining -= elapsed; // adjust remaining time
    lastUpdate = now; // remember this update time

    // Convert remaining milliseconds to mm:ss format and display
    if (remaining < 0) remaining = 0;
    int minutes = (int)(remaining/60000);
    int seconds = (int)((remaining)/1000);
    label.setText(format.format(minutes) + ":" + format.format(seconds));

    // If we've completed the countdown beep and display new page
    if (remaining == 0) {
        // Stop updating now.
        // If we have an alarm sound clip, play it now.
        if (sound != null);
        // If there is a newpage URL specified, make the browser
        // load that page now.
        String newpage = getParameter("newpage");
        if (newpage != null) {
            try {
                URL url = new URL(getDocumentBase(), newpage);
            catch(MalformedURLException ex) {      showStatus(ex.toString()); }

// This method implements the ActionListener interface.
// It is invoked once a second by the Timer object
// and updates the JLabel to display minutes and seconds remaining.
public void actionPerformed(ActionEvent e) { updateDisplay(); }

// The methods below implement the MouseListener interface. We use
// two of them to pause the countdown when the mouse hovers over the timer.
// Note that we also display a message in the statusline
public void mouseEntered(MouseEvent e) {
    pause(); // pause countdown
    showStatus("Paused"); // display statusline message
public void mouseExited(MouseEvent e) {
    resume(); // resume countdown
    showStatus(""); // clear statusline
// These MouseListener methods are unused.
public void mouseClicked(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}

How do I filter an array with AngularJS and use a property of the filtered object as the ng-model attribute?

Here is a modified JSBin with a working sample:

Here is what I did with filters in the input:

<input ng-model="(results.subjects | filter:{grade:'C'})[0].title">

How do I combine two lists into a dictionary in Python?

I don't know about best (simplest? fastest? most readable?), but one way would be:

dict(zip([1, 2, 3, 4], [a, b, c, d]))

How to get previous page url using jquery

    $(document).ready(function() {
               var referrer =  document.referrer;

                   function goBack() {  
                        function noBack() {

using this you can avoid load previous page load

Need a query that returns every field that contains a specified letter

try this

Select * From Table
Where field like '%' + ltrValue1 + '%'
  And field like '%' + ltrValue2 + '%'
... etc.

and be prepared for a table scan as this functionality cannot use any existing indices

How to make a radio button look like a toggle button

Here is the solution that works for all browsers (also IE7 and IE8; didn't check for IE6):


<div class="toggle">
    <label><input type="radio" name="toggle"><span>On</span></label>    
<div class="toggle">
    <label><input type="radio" name="toggle"><span>Off</span></label>




body {

.toggle {
    border:1px solid #D0D0D0;

.toggle label {

.toggle label span {
    padding:3px 0px;
    cursor: pointer;

.toggle label input {

.toggle .input-checked /*, .bounds input:checked + span works for firefox and ie9 but breaks js for ie8(ONLY) */ {

Makes use of minimal JS (jQuery, two lines).

Refresh certain row of UITableView based on Int in Swift

I realize this question is for Swift, but here is the Xamarin equivalent code of the accepted answer if someone is interested.

var indexPath = NSIndexPath.FromRowSection(rowIndex, 0);
tableView.ReloadRows(new NSIndexPath[] { indexPath }, UITableViewRowAnimation.Top);

Easy way to concatenate two byte arrays

Another way is to use a utility function (you could make this a static method of a generic utility class if you like):

byte[] concat(byte[]...arrays)
    // Determine the length of the result array
    int totalLength = 0;
    for (int i = 0; i < arrays.length; i++)
        totalLength += arrays[i].length;

    // create the result array
    byte[] result = new byte[totalLength];

    // copy the source arrays into the result array
    int currentIndex = 0;
    for (int i = 0; i < arrays.length; i++)
        System.arraycopy(arrays[i], 0, result, currentIndex, arrays[i].length);
        currentIndex += arrays[i].length;

    return result;

Invoke like so:

byte[] a;
byte[] b;
byte[] result = concat(a, b);

It will also work for concatenating 3, 4, 5 arrays, etc.

Doing it this way gives you the advantage of fast arraycopy code which is also very easy to read and maintain.

iptables block access to port 8000 except from IP address

You can always use iptables to delete the rules. If you have a lot of rules, just output them using the following command.

iptables-save > myfile

vi to edit them from the commend line. Just use the "dd" to delete the lines you no longer want.

iptables-restore < myfile and you're good to go.  


NLS_NUMERIC_CHARACTERS setting for decimal

Best way is,

SELECT to_number(replace(:Str,',','')/100) --into num2 
FROM dual;

Does MS SQL Server's "between" include the range boundaries?

BETWEEN (Transact-SQL)

Specifies a(n) (inclusive) range to test.

test_expression [ NOT ] BETWEEN begin_expression AND end_expression



Is the expression to test for in the range defined by begin_expression and end_expression. test_expression must be the same data type as both begin_expression and end_expression.


Specifies that the result of the predicate be negated.


Is any valid expression. begin_expression must be the same data type as both test_expression and end_expression.


Is any valid expression. end_expression must be the same data type as both test_expression and begin_expression.


Acts as a placeholder that indicates test_expression should be within the range indicated by begin_expression and end_expression.


To specify an exclusive range, use the greater than (>) and less than operators (<). If any input to the BETWEEN or NOT BETWEEN predicate is NULL, the result is UNKNOWN.

Result Value

BETWEEN returns TRUE if the value of test_expression is greater than or equal to the value of begin_expression and less than or equal to the value of end_expression.

NOT BETWEEN returns TRUE if the value of test_expression is less than the value of begin_expression or greater than the value of end_expression.

How to change menu item text dynamically in Android

I needed to change the menu icon for the fragment. I altered Charles’s answer to this question a bit for the fragment:

    private Menu top_menu;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

       rootview = inflater.inflate(R.layout.first_content,null);

    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(, menu);
        this.top_menu = menu;

    // my procedure
    private void updateIconMenu() {
         if(top_menu!= null) {
             MenuItem nav_undo = top_menu.findItem(;
             nav_undo.setIcon( R.drawable.back);

Can't pickle <type 'instancemethod'> when using multiprocessing

I ran into this same issue but found out that there is a JSON encoder that can be used to move these objects between processes.

from pyVmomi.VmomiSupport import VmomiJSONEncoder

Use this to create your list:

jsonSerialized = json.dumps(pfVmomiObj, cls=VmomiJSONEncoder)

Then in the mapped function, use this to recover the object:

pfVmomiObj = json.loads(jsonSerialized)

How to get overall CPU usage (e.g. 57%) on Linux

Try mpstat from the sysstat package

> sudo apt-get install sysstat
Linux 3.0.0-13-generic (ws025)  02/10/2012  _x86_64_    (2 CPU)  

03:33:26 PM  CPU    %usr   %nice    %sys %iowait    %irq   %soft  %steal  %guest   %idle
03:33:26 PM  all    2.39    0.04    0.19    0.34    0.00    0.01    0.00    0.00   97.03

Then some cutor grepto parse the info you need:

mpstat | grep -A 5 "%idle" | tail -n 1 | awk -F " " '{print 100 -  $ 12}'a

How to add http:// if it doesn't exist in the URL

Try this. It is not watertight1, but it might be good enough:

function addhttp($url) {
    if (!preg_match("@^[hf]tt?ps?://@", $url)) {
        $url = "http://" . $url;
    return $url;

1. That is, prefixes like "fttps://" are treated as valid.

How to Specify "Vary: Accept-Encoding" header in .htaccess

I'm afraid Aularon didn't provide enough steps to complete the process. With a little trial and error, I was able to successfully enable Gzipping on my dedicated WHM server.

Below are the steps:

  • Run EasyApache within WHM, select Deflate within the Exhaustive Options list, and rebuild the server.

  • Once done, goto Services Configuration >> Apache Configuration >> Include Editor >> Post VirtualHost Include, select All Versions, and then paste the mod_headers.c and mod_headers.c code (listed above in Aularon's post) on top of on another within the input field.

  • Once saved, I was seeing a 75.36% data savings on average! You can run a before and after test by using this HTTP Compression tool to see your own results:

Hope this works for you all!

  • Matt

How to add to an NSDictionary

By setting you'd use setValue:(id)value forKey:(id)key method of NSMutableDictionary object:

NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setValue:[NSNumber numberWithInt:5] forKey:@"age"];

Or in modern Objective-C:

NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
dict[@"age"] = @5;

The difference between mutable and "normal" is, well, mutability. I.e. you can alter the contents of NSMutableDictionary (and NSMutableArray) while you can't do that with "normal" NSDictionary and NSArray

Tensorflow r1.0 : could not a find a version that satisfies the requirement tensorflow

I was getting the same error

  1. Get Python 3.5
  2. Upgrade pip version to 9
  3. Install tensorflow

It worked for me

Java BigDecimal: Round to the nearest whole value

You want

round(new MathContext(0));  // or perhaps another math context with rounding mode HALF_UP

XmlSerializer: remove unnecessary xsi and xsd namespaces

I'm using:

public class Person
    public string FirstName { get; set; }
    public string LastName { get; set; }

class Program
    static void Main(string[] args)
        const string DEFAULT_NAMESPACE = "";
        var serializer = new XmlSerializer(typeof(Person), DEFAULT_NAMESPACE);
        var namespaces = new XmlSerializerNamespaces();
        namespaces.Add("", DEFAULT_NAMESPACE);

        using (var stream = new MemoryStream())
            var someone = new Person
                FirstName = "Donald",
                LastName = "Duck"
            serializer.Serialize(stream, someone, namespaces);
            stream.Position = 0;
            using (var reader = new StreamReader(stream))

To get the following XML:

<?xml version="1.0"?>
<Person xmlns="">

If you don't want the namespace, just set DEFAULT_NAMESPACE to "".

smtp configuration for php mail

php's email() function hands the email over to a underlying mail transfer agent which is usually postfix on linux systems

so the preferred method on linux is to configure your postfix to use a relayhost, which is done by a line of

relayhost =

in /etc/postfix/

however in the OP's scenario I somehow suspect that it's a job that his hosting team should have done

Get the value of checked checkbox?

This does not directly answer the question, but may help future visitors.

If you want to have a variable always be the current state of the checkbox (rather than having to keep checking its state), you can modify the onchange event to set that variable.

This can be done in the HTML:

<input class='messageCheckbox' type='checkbox' onchange='some_var=this.checked;'>

or with JavaScript:

cb = document.getElementsByClassName('messageCheckbox')[0]
cb.addEventListener('change', function(){some_var = this.checked})

Is there a way to comment out markup in an .ASPX page?

Another way assuming it's not server side code you want to comment out is...

<asp:panel runat="server" visible="false">
    html here

How do I get a value of in Python that is "timezone aware"?

It should be emphasized that since Python 3.6, you only need the standard lib to get a timezone aware datetime object that represents local time (the setting of your OS). Using astimezone()

import datetime

datetime.datetime(2010, 12, 25, 10, 59).astimezone()
# e.g.
# datetime.datetime(2010, 12, 25, 10, 59, tzinfo=datetime.timezone(datetime.timedelta(seconds=3600), 'Mitteleuropäische Zeit'))

datetime.datetime(2010, 12, 25, 12, 59).astimezone().isoformat()
# e.g.
# '2010-12-25T12:59:00+01:00'

# I'm on CET/CEST

(see @johnchen902's comment). Note there's a small caveat though, astimezone(None) gives aware datetime, unaware of DST.

Linq code to select one item

I'll tell you what worked for me:

int id = int.Parse(insertItem.OwnerTableView.DataKeyValues[insertItem.ItemIndex]["id_usuario"].ToString());

var query = user.First(x => x.id_usuario == id);
tbUsername.Text = query.username;
tbEmail.Text =;
tbPassword.Text = query.password;

My id is the row I want to query, in this case I got it from a radGrid, then I used it to query, but this query returns a row, then you can assign the values you got from the query to textbox, or anything, I had to assign those to textbox.

Warning: Use the 'defaultValue' or 'value' props on <select> instead of setting 'selected' on <option>

With Hooks and useState

Use defaultValue to select the default value.

    const statusOptions = [
        { value: 1, label: 'Publish' },
        { value: 0, label: 'Unpublish' }
    const [statusValue, setStatusValue] = useState('');
    const handleStatusChange = e => {

<Select options={statusOptions} 
    defaultValue={[{ value: published, label: published == 1 ? 'Publish' : 'Unpublish' }]} 
    value={statusOptions.find(obj => obj.value === statusValue)} required />

How can I get the current stack trace in Java?

Maybe you could try this:

catch(Exception e)
    StringWriter writer = new StringWriter();
    PrintWriter pw = new PrintWriter(writer);
    String errorDetail = writer.toString();

The string 'errorDetail' contains the stacktrace.

Differences between git pull origin master & git pull origin/master

git pull origin master will pull changes from the origin remote, master branch and merge them to the local checked-out branch.

git pull origin/master will pull changes from the locally stored branch origin/master and merge that to the local checked-out branch. The origin/master branch is essentially a "cached copy" of what was last pulled from origin, which is why it's called a remote branch in git parlance. This might be somewhat confusing.

You can see what branches are available with git branch and git branch -r to see the "remote branches".

How do I show a "Loading . . . please wait" message in Winforms for a long loading form?

or if you don't want anything fancy like animation etc. you can create a label and dock it to form then change it's z-index from document outline window to 0 and give it a background color so other controls wont be visible than run Application.DoEvents() once in form load event and do all your coding in form shown event and at the and of shown event set your label visible property to false then run Application.DoEvents() again.

Visual Studio 2012 Web Publish doesn't copy files

For what it's worth, I eventually gave up on fighting with Web Deploy to get it to do what I wanted (copy deployable files and nothing else), so I scripted it in PowerShell and am really happy with the result. It's much faster than anything I tried through MSBuild/Web Publish, presumably because those methods were still doing things I didn't need.

Here's the gist (literally):

function copy-deployable-web-files($proj_path, $deploy_dir) {
  # copy files where Build Action = "Content" 
  $proj_dir = split-path -parent $proj_path
  [xml]$xml = get-content $proj_path
  $xml.Project.ItemGroup | % { $_.Content } | % { $_.Include } | ? { $_ } | % {
    $from = "$proj_dir\$_"
    $to = split-path -parent "$deploy_dir\$_"
    if (!(test-path $to)) { md $to }
    cp $from $to

  # copy everything in bin
  cp "$proj_dir\bin" $deploy_dir -recurse

In my case I'm calling this in a CI environment (TeamCity), but it could easily be hooked into a post-build event as well.

Possible to view PHP code of a website?

Noone cand read the file except for those who have access to the file. You must make the code readable (but not writable) by the web server. If the php code handler is running properly you can't read it by requesting by name from the web server.

If someone compromises your server you are at risk. Ensure that the web server can only write to locations it absolutely needs to. There are a few locations under /var which should be properly configured by your distribution. They should not be accessible over the web. /var/www should not be writable, but may contain subdirectories written to by the web server for dynamic content. Code handlers should be disabled for these.

Ensure you don't do anything in your php code which can lead to code injection. The other risk is directory traversal using paths containing .. or begining with /. Apache should already be patched to prevent this when it is handling paths. However, when it runs code, including php, it does not control the paths. Avoid anything that allows the web client to pass a file path.

How to URL encode a string in Ruby

If you want to "encode" a full URL without having to think about manually splitting it into its different parts, I found the following worked in the same way that I used to use URI.encode:


Copy files to network computers on windows command line

Why for? What do you want to iterate? Try this.

call :cpy pc-name-1
call :cpy pc-name-2

net use \\%1\{destfolder} {password} /user:{username}
copy {file} \\%1\{destfolder}
goto :EOF

Python pandas insert list into a cell

As mentionned in this post pandas: how to store a list in a dataframe?; the dtypes in the dataframe may influence the results, as well as calling a dataframe or not to be assigned to.

Why emulator is very slow in Android Studio?

In my case, the problem was coming from the execution of WinSAT.exe (located in System32 folder). I disabled it and issue solved.

To turn it off:

  1. Start > Task Scheduler (taskschd.msc)
  2. Find Task Scheduler (Local)
  3. Task Scheduler Library
  4. Microsoft > Windows > Maintenance
  5. Right click WinSAT
  6. Select disable.

The Reference

Also, suppress it from Task Manager or simply reboot your machine.

Point: In this situation (when the problem comes from WinSAT) emulator works (with poor performance) when you use Software - GLES 2.0 and works with very very poor performance when you use Hardware - GLES 2.0.

Is it possible to run selenium (Firefox) web driver without a GUI?

What you're looking for is a .

Yes, it's possible to run Selenium on Firefox headlessly. Here is a post you can follow.

Here is the summary steps to set up Xvfb

#install Xvfb
sudo apt-get install xvfb

#set display number to :99
Xvfb :99 -ac &
export DISPLAY=:99    

#you are now having an X display by Xvfb

Open Windows Explorer and select a file

Check out this snippet:

Private Sub openDialog()
    Dim fd As Office.FileDialog

    Set fd = Application.FileDialog(msoFileDialogFilePicker)

   With fd

      .AllowMultiSelect = False

      ' Set the title of the dialog box.
      .Title = "Please select the file."

      ' Clear out the current filters, and add our own.
      .Filters.Add "Excel 2003", "*.xls"
      .Filters.Add "All Files", "*.*"

      ' Show the dialog box. If the .Show method returns True, the
      ' user picked at least one file. If the .Show method returns
      ' False, the user clicked Cancel.
      If .Show = True Then
        txtFileName = .SelectedItems(1) 'replace txtFileName with your textbox

      End If
   End With
End Sub

I think this is what you are asking for.

How to simulate a mouse click using JavaScript?

Here's a pure JavaScript function which will simulate a click (or any mouse event) on a target element:

function simulatedClick(target, options) {

  var event = target.ownerDocument.createEvent('MouseEvents'),
      options = options || {},
      opts = { // These are the default values, set up for un-modified left clicks
        type: 'click',
        canBubble: true,
        cancelable: true,
        view: target.ownerDocument.defaultView,
        detail: 1,
        screenX: 0, //The coordinates within the entire page
        screenY: 0,
        clientX: 0, //The coordinates within the viewport
        clientY: 0,
        ctrlKey: false,
        altKey: false,
        shiftKey: false,
        metaKey: false, //I *think* 'meta' is 'Cmd/Apple' on Mac, and 'Windows key' on Win. Not sure, though!
        button: 0, //0 = left, 1 = middle, 2 = right
        relatedTarget: null,

  //Merge the options with the defaults
  for (var key in options) {
    if (options.hasOwnProperty(key)) {
      opts[key] = options[key];

  //Pass in the options

  //Fire the event

Here's a working example:

You can simulate a click on any element in the DOM. Something like simulatedClick(document.getElementById('yourButtonId')) would work.

You can pass in an object into options to override the defaults (to simulate which mouse button you want, whether Shift/Alt/Ctrl are held, etc. The options it accepts are based on the MouseEvents API.

I've tested in Firefox, Safari and Chrome. Internet Explorer might need special treatment, I'm not sure.

Creating a procedure in mySql with parameters

Its very easy to create procedure in Mysql. Here, in my example I am going to create a procedure which is responsible to fetch all data from student table according to supplied name.

CREATE PROCEDURE getStudentInfo(IN s_name VARCHAR(64))
SELECT * FROM student_database.student s where s.sname = s_name;

In the above example ,database and table names are student_database and student respectively. Note: Instead of s_name, you can also pass @s_name as global variable.

How to call procedure? Well! its very easy, simply you can call procedure by hitting this command

$mysql> CAll getStudentInfo('pass_required_name');

enter image description here

Adding Apostrophe in every field in particular column for excel

i use concantenate. works for me.

  1. fill j2-j14 with '(appostrophe)
  2. enter L2 with formula =concantenate(j2,k2)
  3. copy L2 to L3-L14

Git: How to check if a local repo is up to date?

If you use

git fetch --dry-run -v <link/to/remote/git/repo>

you'll get feedback about whether it is up-to-date. So basically, you just need to add the "verbose" option to the answer given before.

Setting PATH environment variable in OSX permanently

For setting up path in Mac two methods can be followed.

  1. Creating a file for variable name and paste the path there under /etc/paths.d and source the file to profile_bashrc.
  2. Export path variable in ~/.profile_bashrc as


AND source the the path. Its simple and stable.

You can set any path variable by Mac terminal or in linux also.

How to iterate a table rows with JQuery and access some cell values?

$("tr.item").each(function() {
  $this = $(this);
  var value = $this.find("span.value").html();
  var quantity = $this.find("input.quantity").val();

sed one-liner to convert all uppercase to lowercase?

echo  "Hello  MY name is SUJIT "  | sed 's/./\L&/g'


hello  my name is sujit

How to JUnit test that two List<E> contain the same elements in the same order?

assertTrue()/assertFalse() : to use only to assert boolean result returned

assertTrue(Iterables.elementsEqual(argumentComponents, returnedComponents));

You want to use Assert.assertTrue() or Assert.assertFalse() as the method under test returns a boolean value.
As the method returns a specific thing such as a List that should contain some expected elements, asserting with assertTrue() in this way : Assert.assertTrue(myActualList.containsAll(myExpectedList) is an anti pattern.
It makes the assertion easy to write but as the test fails, it also makes it hard to debug because the test runner will only say to you something like :

expected true but actual is false

Assert.assertEquals(Object, Object) in JUnit4 or Assertions.assertIterableEquals(Iterable, Iterable) in JUnit 5 : to use only as both equals() and toString() are overrided for the classes (and deeply) of the compared objects

It matters because the equality test in the assertion relies on equals() and the test failure message relies on toString() of the compared objects.
As String overrides both equals() and toString(), it is perfectly valid to assert the List<String> with assertEquals(Object,Object). And about this matter : you have to override equals() in a class because it makes sense in terms of object equality, not only to make assertions easier in a test with JUnit.
To make assertions easier you have other ways (that you can see in the next points of the answer).

Is Guava a way to perform/build unit test assertions ?

Is Google Guava Iterables.elementsEqual() the best way, provided I have the library in my build path, to compare those two lists?

No it is not. Guava is not an library to write unit test assertions.
You don't need it to write most (all I think) of unit tests.

What's the canonical way to compare lists for unit tests?

As a good practice I favor assertion/matcher libraries.

I cannot encourage JUnit to perform specific assertions because this provides really too few and limited features : it performs only an assertion with a deep equals.
Sometimes you want to allow any order in the elements, sometimes you want to allow that any elements of the expected match with the actual, and so for...

So using a unit test assertion/matcher library such as Hamcrest or AssertJ is the correct way.
The actual answer provides a Hamcrest solution. Here is a AssertJ solution.

org.assertj.core.api.ListAssert.containsExactly() is what you need : it verifies that the actual group contains exactly the given values and nothing else, in order as stated :

Verifies that the actual group contains exactly the given values and nothing else, in order.

Your test could look like :

import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;

void ofComponent_AssertJ() throws Exception {
   MyObject myObject = MyObject.ofComponents("One", "Two", "Three");
             .containsExactly("One", "Two", "Three");

A AssertJ good point is that declaring a List as expected is needless : it makes the assertion straighter and the code more readable :

         .containsExactly("One", "Two", "Three");

And if the test fails :

// Fail : Three was not expected 
          .containsExactly("One", "Two");

you get a very clear message such as :



<["One", "Two", "Three"]>

to contain exactly (and in same order):

<["One", "Two"]>

but some elements were not expected:


Assertion/matcher libraries are a must because these will really further

Suppose that MyObject doesn't store Strings but Foos instances such as :

public class MyFooObject {

    private List<Foo> values;
    public static MyFooObject ofComponents(Foo... values) {
        // ...

    public List<Foo> getComponents(){
        return new ArrayList<>(values);

That is a very common need. With AssertJ the assertion is still simple to write. Better you can assert that the list content are equal even if the class of the elements doesn't override equals()/hashCode() while JUnit ways require that :

import org.assertj.core.api.Assertions;
import static org.assertj.core.groups.Tuple.tuple;
import org.junit.jupiter.api.Test;

void ofComponent() throws Exception {
    MyFooObject myObject = MyFooObject.ofComponents(new Foo(1, "One"), new Foo(2, "Two"), new Foo(3, "Three"));

              .extracting(Foo::getId, Foo::getName)
              .containsExactly(tuple(1, "One"),
                               tuple(2, "Two"),
                               tuple(3, "Three"));

"Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset" using PHP

I asked a question about this and I was referred to this post with the message:

This question already has an answer here:

“Notice: Undefined variable”, “Notice: Undefined index”, and “Notice: Undefined offset” using PHP

I am sharing my question and solution here:

This is the error:

enter image description here

Line 154 is the problem. This is what I have in line 154:

153    foreach($cities as $key => $city){
154        if(($city != 'London') && ($city != 'Madrid') && ($citiesCounterArray[$key] >= 1)){

I think the problem is that I am writing if conditions for the variable $city, which is not the key but the value in $key => $city. First, could you confirm if that is the cause of the warning? Second, if that is the problem, why is it that I cannot write a condition based on the value? Does it have to be with the key that I need to write the condition?

UPDATE 1: The problem is that when executing $citiesCounterArray[$key], sometimes the $key corresponds to a key that does not exist in the $citiesCounterArray array, but that is not always the case based on the data of my loop. What I need is to set a condition so that if $key exists in the array, then run the code, otherwise, skip it.

UPDATE 2: This is how I fixed it by using array_key_exists():

foreach($cities as $key => $city){
    if(array_key_exists($key, $citiesCounterArray)){
        if(($city != 'London') && ($city != 'Madrid') && ($citiesCounterArray[$key] >= 1)){

Programmatically add new column to DataGridView

Here's a sample method that adds two extra columns programmatically to the grid view:

    private void AddColumnsProgrammatically()
        // I created these columns at function scope but if you want to access 
        // easily from other parts of your class, just move them to class scope.
        // E.g. Declare them outside of the function...
        var col3 = new DataGridViewTextBoxColumn();
        var col4 = new DataGridViewCheckBoxColumn();

        col3.HeaderText = "Column3";
        col3.Name = "Column3";

        col4.HeaderText = "Column4";
        col4.Name = "Column4";

        dataGridView1.Columns.AddRange(new DataGridViewColumn[] {col3,col4});

A great way to figure out how to do this kind of process is to create a form, add a grid view control and add some columns. (This process will actually work for ANY kind of form control. All instantiation and initialization happens in the Designer.) Then examine the form's Designer.cs file to see how the construction takes place. (Visual Studio does everything programmatically but hides it in the Form Designer.)

For this example I created two columns for the view named Column1 and Column2 and then searched Form1.Designer.cs for Column1 to see everywhere it was referenced. The following information is what I gleaned and, copied and modified to create two more columns dynamically:

// Note that this info scattered throughout the designer but can easily collected.

        System.Windows.Forms.DataGridViewTextBoxColumn Column1;
        System.Windows.Forms.DataGridViewCheckBoxColumn Column2;

        this.Column1 = new System.Windows.Forms.DataGridViewTextBoxColumn();
        this.Column2 = new System.Windows.Forms.DataGridViewCheckBoxColumn();

        this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {

        this.Column1.HeaderText = "Column1";
        this.Column1.Name = "Column1";

        this.Column2.HeaderText = "Column2";
        this.Column2.Name = "Column2";

How to change the URL from "localhost" to something else, on a local system using wampserver?

They are probably using a virtual host (

You can go into your Apache configuration file (httpd.conf) or your virtual host configuration file (recommended) and add something like:

<VirtualHost *:80>
    DocumentRoot /www/ap-mispro
    ServerName ap-mispro

    # Other directives here

And when you call up http://ap-mispro/ you would see whatever is in C:/wamp/www/ap-mispro (assuming default directory structure). The ServerName and DocumentRoot do no have to have the same name at all. Other factors needed to make this work:

  1. You have to make sure httpd-vhosts.conf is included by httpd.conf for your changes in that file to take effect.
  2. When you make changes to either file, you have to restart Apache to see your changes.
  3. You have to change your hosts file for your computer to know where to go when you type http://ap-mispro into your browser. This change to your hosts file will only apply to your computer - not that it sounds like you are trying from anyone else's.

There are plenty more things to know about virtual hosts but this should get you started.

Detecting scroll direction

Simple code

// Events
$(document).on('mousewheel DOMMouseScroll', "element", function(e) {
    let delta = e.originalEvent.wheelDelta;
    if (delta > 0 || e.originalEvent.detail < 0) upScrollFunction();
    if (delta < 0 || e.originalEvent.detail > 0) donwScrollFunction();

How do I test if a recordSet is empty? isNull?

If Not temp_rst1 Is Nothing Then ...

Getting around the Max String size in a vba function?

I may have missed something here, but why can't you just declare your string with the desired size? For example, in my VBA code I often use something like:

Dim AString As String * 1024

which provides for a 1k string. Obviously, you can use whatever declaration you like within the larger limits of Excel and available memory etc.

This may be a little inefficient in some cases, and you will probably wish to use Trim(AString) like constructs to obviate any superfluous trailing blanks. Still, it easily exceeds 256 chars.

Create a day-of-week column in a Pandas dataframe using Python

df =df['Date'].dt.dayofweek

dayofweek is in numeric format

How to print without newline or space?

Or have a function like:

def Print(s):
   return sys.stdout.write(str(s))

Then now:

for i in range(10): # or `xrange` for python 2 version



Splitting a dataframe string column into multiple different columns

The way via unlist and matrix seems a bit convoluted, and requires you to hard-code the number of elements (this is actually a pretty big no-go. Of course you could circumvent hard-coding that number and determine it at run-time)

I would go a different route, and construct a data frame directly from the list that strsplit returns. For me, this is conceptually simpler. There are essentially two ways of doing this:

  1. – but since the list is exactly the wrong way round (we have a list of rows rather than a list of columns) we have to transpose the result. We also clear the rownames since they are ugly by default (but that’s strictly unnecessary!):

    `rownames<-`(t(, '\\.'))), NULL)
  2. Alternatively, use rbind to construct a data frame from the list of rows. We use to call rbind with all the rows as separate arguments:, strsplit(text, '\\.'))

Both ways yield the same result:

     [,1] [,2] [,3]  [,4]
[1,] "F"  "US" "CLE" "V13"
[2,] "F"  "US" "CA6" "U13"
[3,] "F"  "US" "CA6" "U13"
[4,] "F"  "US" "CA6" "U13"
[5,] "F"  "US" "CA6" "U13"
[6,] "F"  "US" "CA6" "U13"

Clearly, the second way is much simpler than the first.

Get SSID when WIFI is connected

Starting with Android 8.1 (API 27), apps must be granted the ACCESS_COARSE_LOCATION (or ACCESS_FINE_LOCATION) permission in order to obtain results from WifiInfo.getSSID() or WifiInfo.getBSSID(). Apps that target API 29 or higher (Android 10) must be granted ACCESS_FINE_LOCATION.

This permission is also needed to obtain results from WifiManager.getConnectionInfo() and WifiManager.getScanResults() although it is not clear if this is new in 8.1 or was required previously.

Source: "BSSID/SSID can be used to deduce location, so require the same location permissions for access to these WifiInfo fields requested using WifiManager.getConnectionInfo() as for WifiManager.getScanResults()."

Adding <script> to WordPress in <head> element

I believe that is your best reference to handle this task very well depends on your needs

check out these two pages on WordPress Codex:



How to get a unix script to run every 15 seconds?

If you insist of running your script from cron:

* * * * * /foo/bar/your_script
* * * * * sleep 15; /foo/bar/your_script
* * * * * sleep 30; /foo/bar/your_script
* * * * * sleep 45; /foo/bar/your_script

and replace your script name&path to /foo/bar/your_script

What is the difference between venv, pyvenv, pyenv, virtualenv, virtualenvwrapper, pipenv, etc?

I would just avoid the use of virtualenv after Python3.3+ and instead use the standard shipped library venv. To create a new virtual environment you would type:

$ python3 -m venv <MYVENV>  

virtualenv tries to copy the Python binary into the virtual environment's bin directory. However it does not update library file links embedded into that binary, so if you build Python from source into a non-system directory with relative path names, the Python binary breaks. Since this is how you make a copy distributable Python, it is a big flaw. BTW to inspect embedded library file links on OS X, use otool. For example from within your virtual environment, type:

$ otool -L bin/python
    @executable_path/../Python (compatibility version 3.4.0, current version 3.4.0)
    /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1238.0.0)

Consequently I would avoid virtualenvwrapper and pipenv. pyvenv is deprecated. pyenv seems to be used often where virtualenv is used but I would stay away from it also since I think venv also does what pyenv is built for.

venv creates virtual environments in the shell that are fresh and sandboxed, with user-installable libraries, and it's multi-python safe. Fresh because virtual environments only start with the standard libraries that ship with python, you have to install any other libraries all over again with pip install while the virtual environment is active. Sandboxed because none of these new library installs are visible outside the virtual environment, so you can delete the whole environment and start again without worrying about impacting your base python install. User-installable libraries because the virtual environment's target folder is created without sudo in some directory you already own, so you won't need sudo permissions to install libraries into it. Finally it is multi-python safe, since when virtual environments activate, the shell only sees the python version (3.4, 3.5 etc.) that was used to build that virtual environment.

pyenv is similar to venv in that it lets you manage multiple python environments. However with pyenv you can't conveniently rollback library installs to some start state and you will likely need admin privileges at some point to update libraries. So I think it is also best to use venv.

In the last couple of years I have found many problems in build systems (emacs packages, python standalone application builders, installers...) that ultimately come down to issues with virtualenv. I think python will be a better platform when we eliminate this additional option and only use venv.

EDIT: Tweet of the BDFL,

I use venv (in the stdlib) and a bunch of shell aliases to quickly switch.

— Guido van Rossum (@gvanrossum) October 22, 2020

Making the Android emulator run faster

Official web page

~50% faster


  • Install "Intel x86 Emulator Accelerator (HAXM)" => SDK-Manager/Extras
  • Install "Intel x86 Atom System Images" => SDK-Manager/Android 2.3.3
  • Go to the Android SDK root folder and navigate to extras\intel\Hardware_Accelerated_Execution_Manager. Execute file IntelHaxm.exe to install. (in Android Studio you can navigate to: Settings -> Android SDK -> SDK Tools -> Intel x86 Emulator Accelerator (HAXM installer))

  • Create AVD with "Intel atom x86" CPU/ABI

  • Run emulator and check in console that HAXM running (open a Command Prompt window and execute the command: sc query intelhaxm)

enter image description here

Also don't forget install this one

enter image description here

P.S. during AVD creation add emulation memory: Hardware/New/Device ram size/set up value 512 or more


  • Install KVM: open GOOGLE, write "kvm installation "
  • Create AVD with "Intel atom x86" CPU/ABI
  • Run from command line: emulator -avd avd_name -qemu -m 512 -enable-kvm
  • Or run from Eclipse: Run/Run Configurations/Tab "Target" - > check Intel x86 AVD and in "Additional Emulator Command Line Options" window add: -qemu -m 512 -enable-kvm (click Run)

enter image description here

P.S. For Fedora, for Ubuntu


  • In Android SDK Manager, install Intel x86 Atom System Image
  • In Android SDK Manager, install Intel x86 Emulator Accelerator (HAXM)
  • In finder, go to the install location of the Intel Emulator Accelerator and install IntelHAXM (open the dmg and run the installation). You can find the location by placing your mouse over the Emulator Accelerator entry in the SDK Manager.
  • Create or update an AVD and specify Intel Atom x86 as the CPU. Intel x86 Emulator Accelerator (HAXM) showing Location

P.S: Check this tool, very convenient even trial

Archive the artifacts in Jenkins

Also, does Jenkins delete the artifacts after each build ? (not the archived artifacts, I know I can tell it to delete those)

No, Hudson/Jenkins does not, by itself, clear the workspace after a build. You might have actions in your build process that erase, overwrite, or move build artifacts from where you left them. There is an option in the job configuration, in Advanced Project Options (which must be expanded), called "Clean workspace before build" that will wipe the workspace at the beginning of a new build.

spring data jpa @query and pageable

A similar question was asked on the Spring forums, where it was pointed out that to apply pagination, a second subquery must be derived. Because the subquery is referring to the same fields, you need to ensure that your query uses aliases for the entities/tables it refers to. This means that where you wrote:

select * from internal_uddi where urn like

You should instead have:

select * from internal_uddi iu where iu.urn like ...

unexpected T_VARIABLE, expecting T_FUNCTION

check that you entered a variable as argument with the '$' symbol

Difference between object and class in Scala

The object keyword creates a new singleton type, which is like a class that only has a single named instance. If you’re familiar with Java, declaring an object in Scala is a lot like creating a new instance of an anonymous class.

Scala has no equivalent to Java’s static keyword, and an object is often used in Scala where you might use a class with static members in Java.

You have to be inside an angular-cli project in order to use the build command after reinstall of angular-cli

This error comes when there's incompatibility between node version and angular/cli version. therefore use below command to update the cli version to latest

npm install -g @angular/cli@latest

How to prevent errno 32 broken pipe?

It depends on how you tested it, and possibly on differences in the TCP stack implementation of the personal computer and the server.

For example, if your sendall always completes immediately (or very quickly) on the personal computer, the connection may simply never have broken during sending. This is very likely if your browser is running on the same machine (since there is no real network latency).

In general, you just need to handle the case where a client disconnects before you're finished, by handling the exception.

Remember that TCP communications are asynchronous, but this is much more obvious on physically remote connections than on local ones, so conditions like this can be hard to reproduce on a local workstation. Specifically, loopback connections on a single machine are often almost synchronous.

How to replace all strings to numbers contained in each string in Notepad++?

psxls gave a great answer but I think my Notepad++ version is slightly different so the $ (dollar sign) capturing did not work.

I have Notepad++ v.5.9.3 and here's how you can accomplish your task:

Search for the pattern: value=\"([0-9]*)\" And replace with: \1 (whatever you want to do around that capturing group)

Ex. Surround with square brackets

[\1] --> will produce value="[4]"

python error: no module named pylab

You'll need to install numpy, scipy and matplotlib to get pylab. In ubuntu you can install them with this command:

sudo apt-get install python-numpy python-scipy python-matplotlib

If you installed python from source you will need to install these packages through pip. Note that you may have to install other dependencies to do this, as well as install numpy before the other two.

That said, I would recommend using the version of python in the repositories as I think it is up to date with the current version of python (2.7.3).

How to connect to SQL Server database from JavaScript in the browser?

As stated before it shouldn't be done using client side Javascript but there's a framework for implementing what you want more securely.

Nodejs is a framework that allows you to code server connections in javascript so have a look into Nodejs and you'll probably learn a bit more about communicating with databases and grabbing data you need.

A better way to check if a path exists or not in PowerShell

if (Test-Path C:\DockerVol\SelfCertSSL) {
    write-host "Folder already exists."
} else {
   New-Item -Path "C:\DockerVol\" -Name "SelfCertSSL" -ItemType "directory"

Converting HTML to plain text in PHP for e-mail

Markdownify converts HTML to Markdown, a plain-text formatting system used on this very site.

Looking for a short & simple example of getters/setters in C#

Getters and Setters in C# are something that simplifies the code.

private string name = "spots";

public string Name
    get { return name; }
    set { name = value; }

And calling it (assume we have a person obj with a name property):

Console.WriteLine(Person.Name); //prints "spots"
Person.Name = "stops";
Console.Writeline(Person.Name); //prints "stops"

This simplifies your code. Where in Java you might have to have two methods, one to Get() and one to Set() the property, in C# it is all done in one spot. I usually do this at the start of my classes:

public string foobar {get; set;}

This creates a getter and setter for my foobar property. Calling it is the same way as shown before. Somethings to note are that you don't have to include both get and set. If you don't want the property being modified, don't include set!

How do I view the list of functions a Linux shared library is exporting?

Among other already mentioned tools you can use also readelf (manual). It is similar to objdump but goes more into detail. See this for the difference explanation.

$ readelf -sW /lib/ |head -n10

Symbol table '.dynsym' contains 128 entries:
   Num:    Value  Size Type    Bind   Vis      Ndx Name
     0: 00000000     0 NOTYPE  LOCAL  DEFAULT  UND
     1: 00000000     0 FUNC    GLOBAL DEFAULT  UND pthread_mutex_unlock@GLIBC_2.0 (4)
     2: 00000000     0 FUNC    GLOBAL DEFAULT  UND pthread_mutex_destroy@GLIBC_2.0 (4)
     3: 00000000     0 NOTYPE  WEAK   DEFAULT  UND _ITM_deregisterTMCloneTable
     4: 00000000     0 FUNC    GLOBAL DEFAULT  UND memmove@GLIBC_2.0 (5)
     5: 00000000     0 FUNC    GLOBAL DEFAULT  UND free@GLIBC_2.0 (5)
     6: 00000000     0 FUNC    GLOBAL DEFAULT  UND memcpy@GLIBC_2.0 (5)

Chart.js v2 - hiding grid lines

If you want to hide gridlines but want to show yAxes, you can set:

yAxes: [{...
         gridLines: {
                        drawBorder: true,
                        display: false

How to get name of calling function/method in PHP?

You can also use the info provided by a php exception, it's an elegant solution:

function GetCallingMethodName(){
    $e = new Exception();
    $trace = $e->getTrace();
    //position 0 would be the line that called this function so we ignore it
    $last_call = $trace[1];

function firstCall($a, $b){
    theCall($a, $b);

function theCall($a, $b){

firstCall('lucia', 'php');

And you get this... (voilà!)

    [file] => /home/lufigueroa/Desktop/test.php
    [line] => 12
    [function] => theCall
    [args] => Array
            [0] => lucia
            [1] => php


Call one constructor from another

Error handling and making your code reusable is key. I added string to int validation and it is possible to add other types if needed. Solving this problem with a more reusable solution could be this:

public class Sample
    public Sample(object inputToInt)
        _intField = objectToInt(inputToInt);

    public int IntProperty => _intField;

    private readonly int _intField;

public static int objectToInt(object inputToInt)
    switch (inputToInt)
            case int inputInt:
                return inputInt;
            case string inputString:
            if (!int.TryParse(inputString, out int parsedInt))
                throw new InvalidParameterException($"The input {inputString} could not be parsed to int");
            return parsedInt;

                throw new InvalidParameterException($"Constructor do not support {inputToInt.GetType().Name}");

How can I switch views programmatically in a view controller? (Xcode, iPhone)

To dismiss the Viewcontroller called with the previous answers code by CmdSft

ViewController *viewController = [[ViewController alloc] init];    
[self presentViewController:viewController animated:YES completion:nil];

you can use

[self dismissViewControllerAnimated:YES completion: nil];

Nth max salary in Oracle

This will show the 3rd max salary from table employee. If you want to find out the 5th or 6th (whatever you want) value then just change the where condition like this where rownum<=5" or "where rownum<=6 and so on...

select min(sal) from(select distinct(sal) from emp  where rownum<=3 order by sal desc);

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

That true,Mustafa....its working..its point to two layout

  1. setContentView(R.layout.your_layout)
  2. v23(your_layout).

You should take Button both activity layout...
solve this problem successfully

svn list of files that are modified in local copy

Right click folder -> Click Tortoise SVN -> Check for modification

Sorting arraylist in alphabetical order (case insensitive)

try this code

Collections.sort(yourarraylist, new SortBasedOnName());

import java.util.Comparator;
import com.RealHelp.objects.FBFriends_Obj;
import com.RealHelp.ui.importFBContacts;

public class SortBasedOnName implements Comparator
public int compare(Object o1, Object o2) 

    FBFriends_Obj dd1 = (FBFriends_Obj)o1;// where FBFriends_Obj is your object class
    FBFriends_Obj dd2 = (FBFriends_Obj)o2;
    return dd1.uname.compareToIgnoreCase(dd2.uname);//where uname is field name


List(of String) or Array or ArrayList

You can do something like this,

  Dim lstOfStrings As New List(Of String) From {"Value1", "Value2", "Value3"}

Collection Initializers

Is there Unicode glyph Symbol to represent "Search"

Displayed correct at Chrome OS - screenshots from this system.

tibetan astrological sign sgra gcan -char rtags U+0F17 ? U+0F17

telephone recorder (U+2315) ? U+2315

lepcha letter gla (U+1C04) ? U+1C04

What are passive event listeners?

Passive event listeners are an emerging web standard, new feature shipped in Chrome 51 that provide a major potential boost to scroll performance. Chrome Release Notes.

It enables developers to opt-in to better scroll performance by eliminating the need for scrolling to block on touch and wheel event listeners.

Problem: All modern browsers have a threaded scrolling feature to permit scrolling to run smoothly even when expensive JavaScript is running, but this optimization is partially defeated by the need to wait for the results of any touchstart and touchmove handlers, which may prevent the scroll entirely by calling preventDefault() on the event.

Solution: {passive: true}

By marking a touch or wheel listener as passive, the developer is promising the handler won't call preventDefault to disable scrolling. This frees the browser up to respond to scrolling immediately without waiting for JavaScript, thus ensuring a reliably smooth scrolling experience for the user.

document.addEventListener("touchstart", function(e) {
    console.log(e.defaultPrevented);  // will be false
    e.preventDefault();   // does nothing since the listener is passive
    console.log(e.defaultPrevented);  // still false
}, Modernizr.passiveeventlisteners ? {passive: true} : false);

DOM Spec , Demo Video , Explainer Doc

Difference between "this" and"super" keywords in Java

From your question, I take it that you are really asking about the use of this and super in constructor chaining; e.g.

public class A extends B {
    public A(...) {


public class A extends B {
    public A(...) {

The difference is simple:

  • The this form chains to a constructor in the current class; i.e. in the A class.

  • The super form chains to a constructor in the immediate superclass; i.e. in the B class.

Make A List Item Clickable (HTML/CSS)

Here is a working solution -

I used simple jQuery:

$(function() {
    $('li').css('cursor', 'pointer')

    .click(function() {
        window.location = $('a', this).attr('href');
        return false;

How can I stop Chrome from going into debug mode?

If you were unfamiliar with the tools, it was likely that at some point while in the debugger you toggled a setting that was causing the debugger to stop the application.

I suggest you "Disable all break points":

Enter image description here


ASP.NET Web API - PUT & DELETE Verbs Not Allowed - IIS 8

After endless searching and trying the already supplied answers (adding the PUT,DELETE verbs and remove WEBdav) it just didn't work.

I went to IIS logging settings: > View Log Files. In my case W3SVC4 was the folder with the latest date, opened the folder, looked up the latest log file and saw this entry: GET /Rejected-By-UrlScan ~/MYDOMAIN/API/ApiName/UpdateMETHOD

The Update method was listed with verb GET, weird right? So I Googled for Rejected-By-UrlScan and found this link: UrlScan Broke My Blog.

I went to here: %windir%\system32\inetsrv\urlscan\UrlScan.ini

Basically, the UrlScan blocked PUT and DELETE verbs. I opened this INI file, added the PUT and DELETE to the AllowVerbs and removed them from the DenyVerbs listings. I saved the INI file and it worked! So for me these steps were necessary next to the ExtensionlessUrlHandler hints.

Windows Webserver 2008 R2 (64 bit), IIS 7.5. I'm using this in combination with DotNetNuke (DNN) WebAPI. ASP.Net 4.0 My update method:

[DnnAuthorize(StaticRoles = "MyRoleNames")]
public HttpResponseMessage UpdateMETHOD(DTO.MyObject myData)

How to send HTTP request in java?

I know others will recommend Apache's http-client, but it adds complexity (i.e., more things that can go wrong) that is rarely warranted. For a simple task, will do.

URL url = new URL("");
InputStream is = url.openStream();
try {
  /* Now read the retrieved document from the stream. */
} finally {

How to get a responsive button in bootstrap 3

In Bootstrap, the .btn class has a white-space: nowrap; property, making it so that the button text won't wrap. So, after setting that to normal, and giving the button a width, the text should wrap to the next line if the text would exceed the set width.

#new-board-btn {
    white-space: normal;

How to remove a directory from git repository?

To remove folder/directory only from git repository and not from the local try 3 simple commands.

Steps to remove directory

git rm -r --cached FolderName
git commit -m "Removed folder from repository"
git push origin master

Steps to ignore that folder in next commits

To ignore that folder from next commits make one file in root folder (main project directory where the git is initialized) named .gitignore and put that folder name into it. You can ignore as many files/folders as you want

.gitignore file will look like this


remove directory

Multipart forms from C# client

Building on dnolans example, this is the version I could actually get to work (there were some errors with the boundary, encoding wasn't set) :-)

To send the data:

HttpWebRequest oRequest = null;
oRequest = (HttpWebRequest)HttpWebRequest.Create("");
oRequest.ContentType = "multipart/form-data; boundary=" + PostData.boundary;
oRequest.Method = "POST";
PostData pData = new PostData();
Encoding encoding = Encoding.UTF8;
Stream oStream = null;

/* ... set the parameters, read files, etc. IE:
   pData.Params.Add(new PostDataParam("email", "[email protected]", PostDataParamType.Field));
   pData.Params.Add(new PostDataParam("fileupload", "filename.txt", "filecontents" PostDataParamType.File));

byte[] buffer = encoding.GetBytes(pData.GetPostData());

oRequest.ContentLength = buffer.Length;

oStream = oRequest.GetRequestStream();
oStream.Write(buffer, 0, buffer.Length);

HttpWebResponse oResponse = (HttpWebResponse)oRequest.GetResponse();

The PostData class should look like:

public class PostData
    // Change this if you need to, not necessary
    public static string boundary = "AaB03x";

    private List<PostDataParam> m_Params;

    public List<PostDataParam> Params
        get { return m_Params; }
        set { m_Params = value; }

    public PostData()
        m_Params = new List<PostDataParam>();

    /// <summary>
    /// Returns the parameters array formatted for multi-part/form data
    /// </summary>
    /// <returns></returns>
    public string GetPostData()
        StringBuilder sb = new StringBuilder();
        foreach (PostDataParam p in m_Params)
            sb.AppendLine("--" + boundary);

            if (p.Type == PostDataParamType.File)
                sb.AppendLine(string.Format("Content-Disposition: file; name=\"{0}\"; filename=\"{1}\"", p.Name, p.FileName));
                sb.AppendLine("Content-Type: application/octet-stream");
                sb.AppendLine(string.Format("Content-Disposition: form-data; name=\"{0}\"", p.Name));

        sb.AppendLine("--" + boundary + "--");

        return sb.ToString();

public enum PostDataParamType

public class PostDataParam
    public PostDataParam(string name, string value, PostDataParamType type)
        Name = name;
        Value = value;
        Type = type;

    public PostDataParam(string name, string filename, string value, PostDataParamType type)
        Name = name;
        Value = value;
        FileName = filename;
        Type = type;

    public string Name;
    public string FileName;
    public string Value;
    public PostDataParamType Type;

ImportError: No module named pythoncom

You should be using pip to install packages, since it gives you uninstall capabilities.

Also, look into virtualenv. It works well with pip and gives you a sandbox so you can explore new stuff without accidentally hosing your system-wide install.

Is quitting an application frowned upon?

The Android application life cycle is designed for mobile phone users, not computer users.

The app life-cycle is the brutally simplistic paradigm required to turn a Linux server into a consumer appliance.

Android is Java over Linux, a real cross-platform server OS. That is how it spread so quickly. The app life-cycle encapsulates the underlying reality of the OS.

To mobile users, apps are just installed or not installed. There is no concept of running or exiting. In fact, app processes are meant to run until the OS releases them for their held resources.

Since this is Stack Overflow, anyone reading this is a computer user and must turn off 90% of their knowledge to understand the mobile app lifecycle.

How to fix an UnsatisfiedLinkError (Can't find dependent libraries) in a JNI project

  • Short answer: for "can't find dependent library" error, check your $PATH (corresponds to bullet point #3 below)
  • Long answer:
    1. Pure java world: jvm uses "Classpath" to find class files
    2. JNI world (java/native boundary): jvm uses "java.library.path" (which defaults to $PATH) to find dlls
    3. pure native world: native code uses $PATH to load other dlls

Access restriction: The type 'Application' is not API (restriction on required library rt.jar)

Even if its old question, for me in Eclipse I just right click on Src folder and properties (Alt+Enter) and the check for the Ignore optional compile problems removed the error.

enter image description here

Mongoose: Get full list of users

you can also do it by async function to get all the users

await User.find({},(err,users)=>{

    if (err){
    return  res.status(422).send(err)

    if (!users){
        return res.status(422).send({error:"No data in the collection"})



Force "git push" to overwrite remote files

Simple steps by using tortoisegit

GIT giving local files commit and pushing into git repository.

Steps :

1) stash changes stash name

2) pull

3) stash pop

4) commit 1 or more files and give commit changes description set author and Date

5) push

Enter key pressed event handler

Either KeyDown or KeyUp.

TextBox tb = new TextBox();
tb.KeyDown += new KeyEventHandler(tb_KeyDown);

static void tb_KeyDown(object sender, KeyEventArgs e)
    if (e.KeyCode == Keys.Enter)
        //enter key is down

How to randomize two ArrayLists in the same fashion?

Wrap them in another class so that you can end up with a single array or List of those objects.

public class Data {
    private String txtFileName;
    private String imgFileName;

    // Add/generate c'tor, getter/setter, equals, hashCode and other boilerplate.

Usage example:

List<Data> list = new ArrayList<Data>();
list.add(new Data("H1.txt", "e1.jpg"));
list.add(new Data("H2.txt", "e2.jpg"));
// ...


How to merge lists into a list of tuples?

I am not sure if this a pythonic way or not but this seems simple if both lists have the same number of elements :

list_a = [1, 2, 3, 4]

list_b = [5, 6, 7, 8]

list_c=[(list_a[i],list_b[i]) for i in range(0,len(list_a))]

"message failed to fetch from registry" while trying to install any module

One thing that has worked for me with random npm install errors (where the package that errors out is different under different times (but same environment) is to use this:

npm cache clean

And then repeat the process. Then the process seems to go smoother and the real problem and error message will emerge, where you can fix it and then proceed.

This is based on experience of running npm install of a whole bunch of packages under a pretty bare Ubuntu installation inside a Docker instance. Sometimes there are build/make tools missing from the Ubuntu and the npm errors will not show the real problem until you clean the cache for some reason.

How to set environment variables in PyCharm?

None of the above methods worked for me. If you are on Windows, try this on PyCharm terminal:


You can access it in your scripts using os.environ['YOUR_VAR'].

How can strip whitespaces in PHP's variable?

Sometimes you would need to delete consecutive white spaces. You can do it like this:

$str = "My   name    is";
$str = preg_replace('/\s\s+/', ' ', $str);


My name is

Scala how can I count the number of occurrences in a list

scala collections do have count: list.count(_ == 2)

Django DoesNotExist

I have found the solution to this issue using ObjectDoesNotExist on this way

from django.core.exceptions import ObjectDoesNotExist

  # try something
except ObjectDoesNotExist:
  # do something

After this, my code works as I need

Thanks any way, your post help me to solve my issue

How can I list ALL grants a user received?

Sorry guys, but selecting from all_tab_privs_recd where grantee = 'your user' will not give any output except public grants and current user grants if you run the select from a different (let us say, SYS) user. As documentation says,

ALL_TAB_PRIVS_RECD describes the following types of grants:

Object grants for which the current user is the grantee
Object grants for which an enabled role or PUBLIC is the grantee

So, if you're a DBA and want to list all object grants for a particular (not SYS itself) user, you can't use that system view.

In this case, you must perform a more complex query. Here is one taken (traced) from TOAD to select all object grants for a particular user:

select privilege,
       decode(mod(oa.option$,2), 1, 'YES', 'NO') grantable, grantee, grantor, owner,
       decode(o.TYPE#, 0, 'NEXT OBJECT', 1, 'INDEX', 2, 'TABLE', 3, 'CLUSTER',
                       4, 'VIEW', 5, 'SYNONYM', 6, 'SEQUENCE',
                       7, 'PROCEDURE', 8, 'FUNCTION', 9, 'PACKAGE',
                       11, 'PACKAGE BODY', 12, 'TRIGGER',
                       13, 'TYPE', 14, 'TYPE BODY',
                       19, 'TABLE PARTITION', 20, 'INDEX PARTITION', 21, 'LOB',
                       22, 'LIBRARY', 23, 'DIRECTORY', 24, 'QUEUE',
                       28, 'JAVA SOURCE', 29, 'JAVA CLASS', 30, 'JAVA RESOURCE',
                       32, 'INDEXTYPE', 33, 'OPERATOR',
                       34, 'TABLE SUBPARTITION', 35, 'INDEX SUBPARTITION',
                       40, 'LOB PARTITION', 41, 'LOB SUBPARTITION',
                       42, 'MATERIALIZED VIEW',
                       43, 'DIMENSION',
                       44, 'CONTEXT', 46, 'RULE SET', 47, 'RESOURCE PLAN',
                       66, 'JOB', 67, 'PROGRAM', 74, 'SCHEDULE',
                       48, 'CONSUMER GROUP',
                       51, 'SUBSCRIPTION', 52, 'LOCATION',
                       55, 'XML SCHEMA', 56, 'JAVA DATA',
                       57, 'EDITION', 59, 'RULE',
                       62, 'EVALUATION CONTEXT',
                       'UNDEFINED') object_type, object_name,
       '' column_name
        from sys.objauth$ oa, sys.obj$ o, sys.user$ u, sys.user$ ur, sys.user$ ue,
             table_privilege_map tpm
        where oa.obj# = o.obj#
          and oa.grantor# = ur.user#
          and oa.grantee# = ue.user#
          and oa.col# is null
          and oa.privilege# = tpm.privilege
          and u.user# = o.owner#
          and o.TYPE# in (2, 4, 6, 9, 7, 8, 42, 23, 22, 13, 33, 32, 66, 67, 74, 57)
  and = 'your user'
  and bitand (o.flags, 128) = 0
union all -- column level grants
select privilege,
       decode(mod(oa.option$,2), 1, 'YES', 'NO') grantable, grantee, grantor, owner,
       decode(o.TYPE#, 2, 'TABLE', 4, 'VIEW', 42, 'MATERIALIZED VIEW') object_type, object_name, column_name
from sys.objauth$ oa, sys.obj$ o, sys.user$ u, sys.user$ ur, sys.user$ ue,
     sys.col$ c, table_privilege_map tpm
where oa.obj# = o.obj#
  and oa.grantor# = ur.user#
  and oa.grantee# = ue.user#
  and oa.obj# = c.obj#
  and oa.col# = c.col#
  and bitand(, 32) = 0 /* not hidden column */
  and oa.col# is not null
  and oa.privilege# = tpm.privilege
  and u.user# = o.owner#
  and o.TYPE# in (2, 4, 42)
  and = 'your user'
  and bitand (o.flags, 128) = 0;

This will list all object grants (including column grants) for your (specified) user. If you don't want column level grants then delete all part of the select beginning with 'union' clause.

UPD: Studying the documentation I found another view that lists all grants in much simpler way:

select * from DBA_TAB_PRIVS where grantee = 'your user';

Bear in mind that there's no DBA_TAB_PRIVS_RECD view in Oracle.

postgresql COUNT(DISTINCT ...) very slow

If your count(distinct(x)) is significantly slower than count(x) then you can speed up this query by maintaining x value counts in different table, for example table_name_x_counts (x integer not null, x_count int not null), using triggers. But your write performance will suffer and if you update multiple x values in single transaction then you'd need to do this in some explicit order to avoid possible deadlock.

How to make fixed header table inside scrollable div?

Using position: sticky on th will do the trick.

Note: if you use position: sticky on thead or tr, it won't work.

Declaring multiple variables in JavaScript

It's common to use one var statement per scope for organization. The way all "scopes" follow a similar pattern making the code more readable. Additionally, the engine "hoists" them all to the top anyway. So keeping your declarations together mimics what will actually happen more closely.

Simple way to sort strings in the (case sensitive) alphabetical order

Simply use


without String.CASE_INSENSITIVE_ORDER comparator parameter.

what is the differences between sql server authentication and windows authentication..?

SQL Authentication

SQL Authentication is the typical authentication used for various database systems, composed of a username and a password. Obviously, an instance of SQL Server can have multiple such user accounts (using SQL authentication) with different usernames and passwords. In shared servers where different users should have access to different databases, SQL authentication should be used. Also, when a client (remote computer) connects to an instance of SQL Server on other computer than the one on which the client is running, SQL Server authentication is needed. Even if you don't define any SQL Server user accounts, at the time of installation a root account - sa - is added with the password you provided. Just like any SQL Server account, this can be used to log-in localy or remotely, however if an application is the one that does the log in, and it should have access to only one database, it's strongly recommended that you don't use the sa account, but create a new one with limited access. Overall, SQL authentication is the main authentication method to be used while the one we review below - Windows Authentication - is more of a convenience.

Windows Authentication

When you are accessing SQL Server from the same computer it is installed on, you shouldn't be prompted to type in an username and password. And you are not, if you're using Windows Authentication. With Windows Authentication, the SQL Server service already knows that someone is logged in into the operating system with the correct credentials, and it uses these credentials to allow the user into its databases. Of course, this works as long as the client resides on the same computer as the SQL Server, or as long as the connecting client matches the Windows credentials of the server. Windows Authentication is often used as a more convenient way to log-in into a SQL Server instance without typing a username and a password, however when more users are envolved, or remote connections are being established with the SQL Server, SQL authentication should be used.

Why doesn't calling a Python string method do anything unless you assign its output?

All string functions as lower, upper, strip are returning a string without modifying the original. If you try to modify a string, as you might think well it is an iterable, it will fail.

x = 'hello'
x[0] = 'i' #'str' object does not support item assignment

There is a good reading about the importance of strings being immutable: Why are Python strings immutable? Best practices for using them

Java executors: how to be notified, without blocking, when a task completes?

Use a CountDownLatch.

It's from java.util.concurrent and it's exactly the way to wait for several threads to complete execution before continuing.

In order to achieve the callback effect you're looking after, that does require a little additional extra work. Namely, handling this by yourself in a separate thread which uses the CountDownLatch and does wait on it, then goes on about notifying whatever it is you need to notify. There is no native support for callback, or anything similar to that effect.

EDIT: now that I further understand your question, I think you are reaching too far, unnecessarily. If you take a regular SingleThreadExecutor, give it all the tasks, and it will do the queueing natively.

404 Not Found The requested URL was not found on this server

change this

Include conf/extra/httpd-vhosts.conf


#Include conf/extra/httpd-vhosts.conf

and restart all services

Change the Theme in Jupyter Notebook?

Follow these steps

Install jupyterthemes with pip:

pip install jupyterthemes

Then Choose the themes from the following and set them using the following command, Once you have installed successfully, Many of us thought we need to start the jupyter server again, just refresh the page.

Set the theme with the following command:

jt -t <theme-name>

Available themes:

  • onedork
  • grade3
  • oceans16
  • chesterish
  • monokai
  • solarizedl
  • solarizedd

Screens of the available themes are also available in the Github repository.

What is the difference between mocking and spying when using Mockito?

If there is an object with 8 methods and you have a test where you want to call 7 real methods and stub one method you have two options:

  1. Using a mock you would have to set it up by invoking 7 callRealMethod and stub one method
  2. Using a spy you have to set it up by stubbing one method

The official documentation on doCallRealMethod recommends using a spy for partial mocks.

See also javadoc spy(Object) to find out more about partial mocks. Mockito.spy() is a recommended way of creating partial mocks. The reason is it guarantees real methods are called against correctly constructed object because you're responsible for constructing the object passed to spy() method.

How do I run a program from command prompt as a different user and as an admin

Runas doesn't magically run commands as an administrator, it runs them as whatever account you provide credentials for. If it's not an administrator account, runas doesn't care.

Converting Varchar Value to Integer/Decimal Value in SQL Server

You can use it without casting such as:

select sum(`stuff`) as mySum from test;

Or cast it to decimal:

select sum(cast(`stuff` as decimal(4,2))) as mySum from test;



For SQL Server, you can use:

select sum(cast(stuff as decimal(5,2))) as mySum from test;


In php, is 0 treated as empty?

Not sure if there are still people looking for an explanation and a solution. The comments above say it all on the differences between TRUE / FALSE / 1 / 0.
I would just like to bring my 2 cents for the way to display the actual value.


If you're working with a Boolean datatype, you're looking for a TRUE vs. FALSE result; if you store it in MySQL, it will be stored as 1 resp. 0 (if I'm not mistaking, this is the same in your server's memory).

So to display the the value in PHP, you need to check if it is true (1) or false (0) and display whatever you want: "TRUE" or "FALSE" or possibly "1" or "0".
Attention, everything bigger (or different) than 0 will also be considered as TRUE in PHP. E.g.: 2, "abc", etc. will all return TRUE.


If you're working with a number datatype, the way it is stored is the same.
To display the value, you need to tell PHP to handle it as a number. The easiest way I found is to multiply it by 1.

How to update json file with python

def updateJsonFile():
    jsonFile = open("replayScript.json", "r") # Open the JSON file for reading
    data = json.load(jsonFile) # Read the JSON into the buffer
    jsonFile.close() # Close the JSON file

    ## Working with buffered content
    tmp = data["location"] 
    data["location"] = path
    data["mode"] = "replay"

    ## Save our changes to JSON file
    jsonFile = open("replayScript.json", "w+")

What's NSLocalizedString equivalent in Swift?

When you are developing an SDK. You need some extra operation.

1) create Localizable.strings as usual in YourLocalizeDemoSDK.

2) create the same Localizable.strings in YourLocalizeDemo.

3) find your Bundle Path of YourLocalizeDemoSDK.


// if you use NSLocalizeString in NSObject, you can use it like this
let value = NSLocalizedString("key", tableName: nil, bundle: Bundle(for: type(of: self)), value: "", comment: "")

Bundle(for: type(of: self)) helps you to find the bundle in YourLocalizeDemoSDK. If you use Bundle.main instead, you will get a wrong value(in fact it will be the same string with the key).

But if you want to use the String extension mentioned by dr OX. You need to do some more. The origin extension looks like this.

extension String {
    var localized: String {
        return NSLocalizedString(self, tableName: nil, bundle: Bundle.main, value: "", comment: "")

As we know, we are developing an SDK, Bundle.main will get the bundle of YourLocalizeDemo's bundle. That's not what we want. We need the bundle in YourLocalizeDemoSDK. This is a trick to find it quickly.

Run the code below in a NSObject instance in YourLocalizeDemoSDK. And you will get the URL of YourLocalizeDemoSDK.

let bundleURLOfSDK = Bundle(for: type(of: self)).bundleURL
let mainBundleURL = Bundle.main.bundleURL

Print both of the two url, you will find that we can build bundleURLofSDK base on mainBundleURL. In this case, it will be:

let bundle = Bundle(url: Bundle.main.bundleURL.appendingPathComponent("Frameworks").appendingPathComponent("YourLocalizeDemoSDK.framework")) ?? Bundle.main

And the String extension will be:

extension String {
    var localized: String {
        let bundle = Bundle(url: Bundle.main.bundleURL.appendingPathComponent("Frameworks").appendingPathComponent("YourLocalizeDemoSDK.framework")) ?? Bundle.main
        return NSLocalizedString(self, tableName: nil, bundle: bundle, value: "", comment: "")

Hope it helps.

How to use function srand() with time.h?


void main()
  time_t t;
  int i;


Can (domain name) subdomains have an underscore "_" in it?

A note on terminology, in furtherance to Bortzmeyer's answer

One should be clear about definitions. As used here:

  • domain name is the identifier of a resource in a DNS database
  • label is the part of a domain name in between dots
  • hostname is a special type of domain name which identifies Internet hosts

The hostname is subject to the restrictions of RFC 952 and the slight relaxation of RFC 1123

RFC 2181 makes clear that there is a difference between a domain name and a hostname:

...[the fact that] any binary label can have an MX record does not imply that any binary name can be used as the host part of an e-mail address...

So underscores in hostnames are a no-no, underscores in domain names are a-ok.

In practice, one may well see hostnames with underscores. As the Robustness Principle says: "Be conservative in what you send, liberal in what you accept".

A note on encoding

In the 21st century, it turns out that hostnames as well as domain names may be internationalized! This means resorting to encodings in case of labels that contain characters that are outside the allowed set.

In particular, it allows one to encode the _ in hostnames (Update 2017-07: This is doubtful, see comments. The _ still cannot be used in hostnames. Indeed, it cannot even be used in internationalized labels.)

The first RFC for internationalization was RFC 3490 of March 2003, "Internationalizing Domain Names in Applications (IDNA)". Today, we have:

  • RFC 5890 "IDNA: Definitions and Document Framework"
  • RFC 5891 "IDNA: Protocol"
  • RFC 5892 "The Unicode Code Points and IDNA"
  • RFC 5893 "Right-to-Left Scripts for IDNA"
  • RFC 5894 "IDNA: Background, Explanation, and Rationale"
  • RFC 5895 "Mapping Characters for IDNA 2008"

You may also want to check the Wikipedia Entry

RFC 5890 introduces the term LDH (Letter-Digit-Hypen) label for labels used in hostnames and says:

This is the classical label form used, albeit with some additional restrictions, in hostnames (RFC 952). Its syntax is identical to that described as the "preferred name syntax" in Section 3.5 of RFC 1034 as modified by RFC 1123. Briefly, it is a string consisting of ASCII letters, digits, and the hyphen with the further restriction that the hyphen cannot appear at the beginning or end of the string. Like all DNS labels, its total length must not exceed 63 octets.

Going back to simpler times, this Internet draft is an early proposal for hostname internationalization. Hostnames with international characters may be encoded using, for example, 'RACE' encoding.

The author of the 'RACE encoding' proposal notes:

According to RFC 1035, host parts must be case-insensitive, start and end with a letter or digit, and contain only letters, digits, and the hyphen character ("-"). This, of course, excludes any internationalized characters, as well as many other characters in the ASCII character repertoire. Further, domain name parts must be 63 octets or shorter in length.... All post-converted name parts that contain internationalized characters begin with the string "bq--". (...) The string "bq--" was chosen because it is extremely unlikely to exist in host parts before this specification was produced.

What is a Sticky Broadcast?

The value of a sticky broadcast is the value that was last broadcast and is currently held in the sticky cache. This is not the value of a broadcast that was received right now. I suppose you can say it is like a browser cookie that you can access at any time. The sticky broadcast is now deprecated, per the docs for sticky broadcast methods (e.g.):

This method was deprecated in API level 21. Sticky broadcasts should not be used. They provide no security (anyone can access them), no protection (anyone can modify them), and many other problems. The recommended pattern is to use a non-sticky broadcast to report that something has changed, with another mechanism for apps to retrieve the current value whenever desired.

How do I uniquely identify computers visiting my web site?

Because i want the solution to work on all machines and all browsers (within reason) I am trying to create a solution using javascript.

Isn't that a really good reason not to use javascript?

As others have said - cookies are probably your best option - just be aware of the limitations.

How to declare a structure in a header that is to be used by multiple files in c?

For a structure definition that is to be used across more than one source file, you should definitely put it in a header file. Then include that header file in any source file that needs the structure.

The extern declaration is not used for structure definitions, but is instead used for variable declarations (that is, some data value with a structure type that you have defined). If you want to use the same variable across more than one source file, declare it as extern in a header file like:

extern struct a myAValue;

Then, in one source file, define the actual variable:

struct a myAValue;

If you forget to do this or accidentally define it in two source files, the linker will let you know about this.

How to $http Synchronous call with AngularJS

var EmployeeController = ["$scope", "EmployeeService",
        function ($scope, EmployeeService) {
            $scope.Employee = {};
            $scope.Save = function (Employee) {                
                if ($scope.EmployeeForm.$valid) {
                        .then(function (response) {
                            if (response.HasError) {
                                $scope.HasError = response.HasError;
                                $scope.ErrorMessage = response.ResponseMessage;
                            } else {

                        .catch(function (response) {


var EmployeeService = ["$http", "$q",
            function ($http, $q) {
                var self = this;

                self.Save = function (employee) {
                    var deferred = $q.defer();                
                        .post("/api/EmployeeApi/Create", angular.toJson(employee))
                        .success(function (response, status, headers, config) {
                            deferred.resolve(response, status, headers, config);
                        .error(function (response, status, headers, config) {
                            deferred.reject(response, status, headers, config);

                    return deferred.promise;

Where can I find free WPF controls and control templates?

I strongly recommend the MahApps it's simply awesome!

Create PDF with Java

I prefer outputting my data into XML (using Castor, XStream or JAXB), then transforming it using a XSLT stylesheet into XSL-FO and render that with Apache FOP into PDF. Worked so far for 10-page reports and 400-page manuals. I found this more flexible and stylable than generating PDFs in code using iText.

ImageView - have height match width?

i did like this -


Node.js Generate html

You can use jsdom

const jsdom = require("jsdom");
const { JSDOM } = jsdom;
const { document } = (new JSDOM(`...`)).window;

or, take a look at cheerio, it may more suitable in your case.

How to resolve "Input string was not in a correct format." error?

The problem is with line

imageWidth = 1 * Convert.ToInt32(Label1.Text);

Label1.Text may or may not be int. Check.

Use Int32.TryParse(value, out number) instead. That will solve your problem.

int imageWidth;
if(Int32.TryParse(Label1.Text, out imageWidth))
    Image1.Width= imageWidth;

How do I exit from a function?

return; // Prematurely return from the method (same keword works in VB, by the way)

How do I find the mime-type of a file with php?

mime_content_type() is deprecated, so you won't be able to count on it working in the future. There is a "fileinfo" PECL extension, but I haven't heard good things about it.

If you are running on a *nix server, you can do the following, which has worked fine for me:

$file = escapeshellarg( $filename );
$mime = shell_exec("file -bi " . $file);
$filename should probably include the absolute path.

MySQL: determine which database is selected?

@mysql_result(mysql_query("SELECT DATABASE();"),0)

If no database selected, or there is no connection it returns NULL otherwise the name of the selected database.

How to run an awk commands in Windows?

If you want to avoid including the full path to awk, you need to update your PATH variable to include the path to the directory where awk is located, then you can just type


to run your programs.

Go to Control Panel->System->Advanced and set your PATH environment variable to include "C:\Program Files (x86)\GnuWin32\bin" at the end (separated by a semi-colon) from previous entry. enter image description here

'' is not recognized as an internal or external command, operable program or batch file

When you want to run an executable file from the Command prompt, (cmd.exe), or a batch file, it will:

  • Search the current working directory for the executable file.
  • Search all locations specified in the %PATH% environment variable for the executable file.

If the file isn't found in either of those options you will need to either:

  1. Specify the location of your executable.
  2. Change the working directory to that which holds the executable.
  3. Add the location to %PATH% by apending it, (recommended only with extreme caution).

You can see which locations are specified in %PATH% from the Command prompt, Echo %Path%.

Because of your reported error we can assume that Mobile.exe is not in the current directory or in a location specified within the %Path% variable, so you need to use 1., 2. or 3..

Examples for 1.



"C:\directory path with spaces\My-App\Mobile.exe"

Alternatively you may try:

Start C:\directory_path_without_spaces\My-App\Mobile.exe


Start "" "C:\directory path with spaces\My-App\Mobile.exe"

Where "" is an empty title, (you can optionally add a string between those doublequotes).

Examples for 2.

CD /D C:\directory_path_without_spaces\My-App


CD /D "C:\directory path with spaces\My-App"

You could also use the /D option with Start to change the working directory for the executable to be run by the start command

Start /D C:\directory_path_without_spaces\My-App Mobile.exe


Start "" /D "C:\directory path with spaces\My-App" Mobile.exe

What is Python used for?

Why should you learn Python Programming Language?

Python offers a stepping stone into the world of programming. Even though Python Programming Language has been around for 25 years, it is still rising in popularity. Some of the biggest advantage of Python are it's

  • Easy to Read & Easy to Learn
  • Very productive or small as well as big projects
  • Big libraries for many things

enter image description here

What is Python Programming Language used for?

As a general purpose programming language, Python can be used for multiple things. Python can be easily used for small, large, online and offline projects. The best options for utilizing Python are web development, simple scripting and data analysis. Below are a few examples of what Python will let you do:

Web Development:

You can use Python to create web applications on many levels of complexity. There are many excellent Python web frameworks including, Pyramid, Django and Flask, to name a few.

Data Analysis:

Python is the leading language of choice for many data scientists. Python has grown in popularity, within this field, due to its excellent libraries including; NumPy and Pandas and its superb libraries for data visualisation like Matplotlib and Seaborn.

Machine Learning:

What if you could predict customer satisfaction or analyse what factors will affect household pricing or to predict stocks over the next few days, based on previous years data? There are many wonderful libraries implementing machine learning algorithms such as Scikit-Learn, NLTK and TensorFlow.

Computer Vision:

You can do many interesting things such as Face detection, Color detection while using Opencv and Python.

Internet Of Things With Raspberry Pi:

Raspberry Pi is a very tiny and affordable computer which was developed for education and has gained enormous popularity among hobbyists with do-it-yourself hardware and automation. You can even build a robot and automate your entire home. Raspberry Pi can be used as the brain for your robot in order to perform various actions and/or react to the environment. The coding on a Raspberry Pi can be performed using Python. The Possibilities are endless!

Game Development:

Create a video game using module Pygame. Basically, you use Python to write the logic of the game. PyGame applications can run on Android devices.

Web Scraping:

If you need to grab data from a website but the site does not have an API to expose data, use Python to scraping data.

Writing Scripts:

If you're doing something manually and want to automate repetitive stuff, such as emails, it's not difficult to automate once you know the basics of this language.

Browser Automation:

Perform some neat things such as opening a browser and posting a Facebook status, you can do it with Selenium with Python.

GUI Development:

Build a GUI application (desktop app) using Python modules Tkinter, PyQt to support it.

Rapid Prototyping:

Python has libraries for just about everything. Use it to quickly built a (lower-performance, often less powerful) prototype. Python is also great for validating ideas or products for established companies and start-ups alike.

Python can be used in so many different projects. If you're a programmer looking for a new language, you want one that is growing in popularity. As a newcomer to programming, Python is the perfect choice for learning quickly and easily.

Call static method with reflection

Class that will call the methods:

namespace myNamespace
    public class myClass
        public static void voidMethodWithoutParameters()
            // code here
        public static string stringReturnMethodWithParameters(string param1, string param2)
            // code here
            return "output";

Calling myClass static methods using Reflection:

var myClassType = Assembly.GetExecutingAssembly().GetType(GetType().Namespace + ".myClass");
// calling my void Method that has no parameters.
myClassType.GetMethod("voidMethodWithoutParameters", BindingFlags.Public | BindingFlags.Static).Invoke(null, null);

// calling my string returning Method & passing to it two string parameters.
Object methodOutput = myClassType.GetMethod("stringReturnMethodWithParameters", BindingFlags.Public | BindingFlags.Static).Invoke(null, new object[] { "value1", "value1" });

Note: I don't need to instantiate an object of myClass to use it's methods, as the methods I'm using are static.

Great resources:

How can I specify a branch/tag when adding a Git submodule?

We use Quack to pull a specific module from another Git repository. We need to pull code without the whole code base of the provided repository - we need a very specific module / file from that huge repository and should be updated every time we run update.

So we achieved it in this way:

Create configuration

name: Project Name

    path: repo/path
    branch: dev
    hexsha: 9e3e9642cfea36f4ae216d27df100134920143b9
    path: repo/path/filename.txt

    tasks: ['modules']

With the above configuration, it creates one directory from the provided GitHub repository as specified in first module configuration, and the other one is to pull and create a file from the given repository.

Other developers just need to run

$ quack

And it pulls the code from the above configurations.

Is it possible to reference one CSS rule within another?

Just add the classes to your html

<div class="someDiv radius opacity"></div>

How to call javascript function from button click event

You're already prepending the hash sign in your showDialog() function, and you're missing single quotes in your second code snippet. You should also return false from the handler to prevent a postback from occurring. Try:

<asp:Button ID="ButtonAdd" runat="server" Text="Add"
    OnClientClick="showDialog('<%=addPerson.ClientID %>'); return false;" />

Can't connect to Postgresql on port 5432

You probably need to either open up the port to access it in your LAN (or outside of it) or bind the network address to the port (make PostgreSQL listen on your LAN instead of just on localhost)

Extract matrix column values by matrix column name

> myMatrix <- matrix(1:10, nrow=2)
> rownames(myMatrix) <- c("A", "B")
> colnames(myMatrix) <- c("A", "B", "C", "D", "E")

> myMatrix
  A B C D  E
A 1 3 5 7  9
B 2 4 6 8 10

> myMatrix["A", "A"]
[1] 1

> myMatrix["A", ]
A B C D E 
1 3 5 7 9 

> myMatrix[, "A"]
A B 
1 2 

How to add data to DataGridView

LINQ is a "query" language (thats the Q), so modifying data is outside its scope.

That said, your DataGridView is presumably bound to an ItemsSource, perhaps of type ObservableCollection<T> or similar. In that case, just do something like X.ToList().ForEach(yourGridSource.Add) (this might have to be adapted based on the type of source in your grid).

How to set the allowed url length for a nginx request (error code: 414, uri too large)


Syntax: large_client_header_buffers number size ;
Default: large_client_header_buffers 4 8k;
Context: http, server

Sets the maximum number and size of buffers used for reading large client request header. A request line cannot exceed the size of one buffer, or the 414 (Request-URI Too Large) error is returned to the client. A request header field cannot exceed the size of one buffer as well, or the 400 (Bad Request) error is returned to the client. Buffers are allocated only on demand. By default, the buffer size is equal to 8K bytes. If after the end of request processing a connection is transitioned into the keep-alive state, these buffers are released.

so you need to change the size parameter at the end of that line to something bigger for your needs.

Disabling the button after once click

protected void Page_Load(object sender, EventArgs e)
        // prevent user from making operation twice
                               "this.disabled=true;" + GetPostBackEventReference(btnSave).ToString() + ";");

        // ... etc. 

jQuery find events handlers registered with an object

I've combined both solutions from @jps to one function:

jQuery.fn.getEvents = function() {
    if (typeof(jQuery._data) === 'function') {
        return jQuery._data(this.get(0), 'events') || {};

    // jQuery version < 1.7.?
    if (typeof( === 'function') {
        return'events') || {};

    return {};

But beware, this function can only return events that were set using jQuery itself.

In Tensorflow, get the names of all the Tensors in a graph

There is a way to do it slightly faster than in Yaroslav's answer by using get_operations. Here is a quick example:

import tensorflow as tf

a = tf.constant(1.3, name='const_a')
b = tf.Variable(3.1, name='variable_b')
c = tf.add(a, b, name='addition')
d = tf.multiply(c, a, name='multiply')

for op in tf.get_default_graph().get_operations():

Extract substring using regexp in plain bash

    echo "US/Central - 10:26 PM (CST)" | sed -n "s/^.*-\s*\(\S*\).*$/\1/p"

-n      suppress printing
s       substitute
^.*     anything at the beginning
-       up until the dash
\s*     any space characters (any whitespace character)
\(      start capture group
\S*     any non-space characters
\)      end capture group
.*$     anything at the end
\1      substitute 1st capture group for everything on line
p       print it

Use RSA private key to generate public key?

People looking for SSH public key...

If you're looking to extract the public key for use with OpenSSH, you will need to get the public key a bit differently

$ ssh-keygen -y -f mykey.pem >

This public key format is compatible with OpenSSH. Append the public key to remote:~/.ssh/authorized_keys and you'll be good to go

docs from SSH-KEYGEN(1)

ssh-keygen -y [-f input_keyfile]  

-y This option will read a private OpenSSH format file and print an OpenSSH public key to stdout.

Counting null and non-null values in a single query

for counting not null values

select count(*) from us where a is not null;

for counting null values

 select count(*) from us where a is null;

Regexp Java for password validation

Use Passay library which is powerful api.

How to "flatten" a multi-dimensional array to simple one in PHP?

This is a one line, SUPER easy to use:

$result = array();
array_walk_recursive($original_array,function($v) use (&$result){ $result[] = $v; });

It is very easy to understand, inside the anonymous function/closure. $v is the value of your $original_array.

How do you use youtube-dl to download live streams (that are live)?

There is no need to pass anything to ffmpeg you can just grab the desired format, in this example, it was the "95" format.

So once you know that it is the 95, you just type:

youtube-dl -f 95\?v\=6aXR-SL5L2o

that is to say:

youtube-dl -f <format number> <url>

It will begin generating on the working directory a <somename>.<probably mp4>.part which is the partially downloaded file, let it go and just press <Ctrl-C> to stop the capture.

The file will still be named <something>.part, rename it to <whatever>.mp4 and there it is...

The ffmpeg code:

ffmpeg -i $(youtube-dl -f <format number> -g <url>) -copy <file_name>.ts

also worked for me, but sound and video got out of sync, using just youtube-dl seemed to yield a better result although it too uses ffmpeg.

The downside of this approach is that you cannot watch the video while downloading, well you can open yet another FF or Chrome, but it seems that mplayer cannot process the video output till youtube-dl/ffmpeg are running.

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

The VCS files can have its information coded in Quoted printable which is a nightmare. The above solution recommending "VCS to ICS Calendar Converter" is the way to go.

How to convert CSV file to multiline JSON?

How about using Pandas to read the csv file into a DataFrame (pd.read_csv), then manipulating the columns if you want (dropping them or updating values) and finally converting the DataFrame back to JSON (pd.DataFrame.to_json).

Note: I haven't checked how efficient this will be but this is definitely one of the easiest ways to manipulate and convert a large csv to json.

How to set an environment variable in a running docker container

Here's how you can modify a running container to update its environment variables. This assumes you're running on Linux. I tested it with Docker 19.03.8

Live Restore

First, ensure that your Docker daemon is set to leave containers running when it's shut down. Edit your /etc/docker/daemon.json, and add "live-restore": true as a top-level key.

sudo vim /etc/docker/daemon.json

My file looks like this:

    "default-runtime": "nvidia",
    "runtimes": {
        "nvidia": {
            "path": "nvidia-container-runtime",
            "runtimeArgs": []
    "live-restore": true

Taken from here.

Get the Container ID

Save the ID of the container you want to edit for easier access to the files.

export CONTAINER_ID=`docker inspect --format="{{.Id}}" <YOUR CONTAINER NAME>`

Edit Container Configuration

Edit the configuration file, go to the "Env" section, and add your key.

sudo vim /var/lib/docker/containers/$CONTAINER_ID/config.v2.json

My file looks like this:


Stop and Start Docker

I found that restarting Docker didn't work, I had to stop and then start Docker with two separate commands.

sudo systemctl stop docker
sudo systemctl start docker

Because of live-restore, your containers should stay up.

Verify That It Worked

docker exec <YOUR CONTAINER NAME> bash -c 'echo $TEST'

Single quotes are important here.

You can also verify that the uptime of your container hasn't changed:

docker ps

How to insert current_timestamp into Postgres via python

Sure, just pass a string value for that timestamp column in the format: '2011-05-16 15:36:38' (you can also append a timezone there, like 'PST'). PostgreSQL will automatically convert the string to a timestamp. See

SQL Query to find the last day of the month


This works great in T-sql ..

Replace the GETDATE() of the query with your column name .

How can I change my Cygwin home folder after installation?

Starting with Cygwin 1.7.34, the recommended way to do this is to add a custom db_home setting to /etc/nsswitch.conf. A common wish when doing this is to make your Cygwin home directory equal to your Windows user profile directory. This setting will do that:

db_home: windows

Or, equivalently:

db_home: /%H

You need to use the latter form if you want some variation on this scheme, such as to segregate your Cygwin home files into a subdirectory of your Windows user profile directory:

db_home: /%H/cygwin

There are several other alternative schemes for the windows option plus several other % tokens you can use instead of %H or in addition to it. See the nsswitch.conf syntax description in the Cygwin User Guide for details.

If you installed Cygwin prior to 1.7.34 or have run its mkpasswd utility so that you have an /etc/passwd file, you can change your Cygwin home directory by editing your user's entry in that file. Your home directory is the second-to-last element on your user's line in /etc/passwd

Whichever way you do it, this causes the HOME environment variable to be set during shell startup.²

See this FAQ item for more on the topic.


  1. Consider moving /etc/passwd and /etc/group out of the way in order to use the new SAM/AD-based mechanism instead.

  2. While it is possible to simply set %HOME% via the Control Panel, it is officially discouraged. Not only does it unceremoniously override the above mechanisms, it doesn't always work, such as when running shell scripts via cron.

Retrieving parameters from a URL

import cgitb

import cgi
print "Content-Type: text/plain;charset=utf-8"
form = cgi.FieldStorage()
i = int(form.getvalue('a'))+int(form.getvalue('b'))
print i

Which is the correct C# infinite loop, for (;;) or while (true)?



Is always what I've used and what I've seen others use for a loop that has to be broken manually.

How to sort an array in descending order in Ruby

Regarding the benchmark suite mentioned, these results also hold for sorted arrays.

sort_by/reverse it is:

# foo.rb
require 'benchmark'

NUM_RUNS = 1000

# arr = []
arr1 = { { num: rand(1000) } }
arr2 = { |n| { num: n } }.reverse do |x|
  { 'randomized'     => arr1,
    'sorted'         => arr2 }.each do |label, arr|
    puts '---------------------------------------------------'
    puts label'sort_by / reverse') {
      NUM_RUNS.times { arr.sort_by { |h| h[:num] }.reverse }
    }'sort_by -') {
      NUM_RUNS.times { arr.sort_by { |h| -h[:num] } }

And the results:

$: ruby foo.rb
                           user     system      total        real
sort_by / reverse      1.680000   0.010000   1.690000 (  1.682051)
sort_by -              1.830000   0.000000   1.830000 (  1.830359)
sort_by / reverse      0.400000   0.000000   0.400000 (  0.402990)
sort_by -              0.500000   0.000000   0.500000 (  0.499350)

How to run function in AngularJS controller on document ready?

$scope.$on('$ViewData', function(event) {
//Your code.

git: can't push (unpacker error) related to permission issues

For what it worth, I had the same problem over my own VPS and it was caused by my low hard disk space on VPS. Confirmed by df -h command and after i cleaned up my VPS' hard disk; the problem was gone.


Shortcut to comment out a block of code with sublime text

You're looking for the toggle_comment command. (Edit > Comment > Toggle Comment)

By default, this command is mapped to:

  • Ctrl+/ (On Windows and Linux)
  • Command ?+/ (On Mac)

This command also takes a block argument, which allows you to use block comments instead of single lines (e.g. /* ... */ as opposed to // ... in JavaScript). By default, the following key combinations are mapped to toggle block comments:

  • Ctrl+Shift+/ (On Windows and Linux)
  • Command ?+Alt+/ (On Mac)

How to execute an .SQL script file using c#

There are two points to considerate.

1) This source code worked for me:

private static string Execute(string credentials, string scriptDir, string scriptFilename)
  Process process = new Process();
  process.StartInfo.UseShellExecute = false;
  process.StartInfo.WorkingDirectory = scriptDir;
  process.StartInfo.RedirectStandardOutput = true;
  process.StartInfo.FileName = "sqlplus";
  process.StartInfo.Arguments = string.Format("{0} @{1}", credentials, scriptFilename);
  process.StartInfo.CreateNoWindow = true;

  string output = process.StandardOutput.ReadToEnd();

  return output;

I set the working directory to the script directory, so that sub scripts within the script also work.

Call it e.g. as Execute("usr/pwd@service", "c:\myscripts", "script.sql")

2) You have to finalize your SQL script with the statement EXIT;

Preloading @font-face fonts?

A simple technique is to put this somewhere in your index:

<div class="font_preload" style="opacity: 0">
    <span style="font-family: 'myfontface#1font-family', Arial, sans-serif;"></span>
    <span style="font-family: 'myfontface#2font-family', Arial, sans-serif;"></span>

Tested on Chrome 34, Safari 7 and FF 29 and IE 11

How do I enable EF migrations for multiple contexts to separate databases?

In case you already have a "Configuration" with many migrations and want to keep this as is, you can always create a new "Configuration" class, give it another name, like

class MyNewContextConfiguration : DbMigrationsConfiguration<MyNewDbContext>

then just issue the command

Add-Migration -ConfigurationTypeName MyNewContextConfiguration InitialMigrationName

and EF will scaffold the migration without problems. Finally update your database, from now on, EF will complain if you don't tell him which configuration you want to update:

Update-Database -ConfigurationTypeName MyNewContextConfiguration 


You don't need to deal with Enable-Migrations as it will complain "Configuration" already exists, and renaming your existing Configuration class will bring issues to the migration history.

You can target different databases, or the same one, all configurations will share the __MigrationHistory table nicely.

List of Timezone IDs for use with FindTimeZoneById() in C#?

I suspect this is what most people are looking for:

Microsoft Time Zone Index Values

Hopefully MS keeps it up to date even after XP.

JavaScript: function returning an object

The latest way to do this with ES2016 JavaScript

let makeGamePlayer = (name, totalScore, gamesPlayed) => ({

Styling HTML email for Gmail

As others have said, some email programs will not read the css styles. If you already have a web email written up you can use the following tool from zurb to inline all of your styles:

This comes in extremely handy when using templates like those mentioned above from mailchimp, campaign monitor, etc. as they, as you have found, will not work in some email programs. This tool leaves your style section for the mail programs that will read it and puts all the styles inline to get more universal readability in the format that you wanted.

No connection could be made because the target machine actively refused it (PHP / WAMP)

In my case i did the following and worked for me

  1. I clicked on the wamp icon.
  2. i went to MySQL > Service administration 'wampmysqld64' > install service
  3. Then click on wamp icon > Restart all service.

Label points in geom_point

The ggrepel package works great for repelling overlapping text labels away from each other. You can use either geom_label_repel() (draws rectangles around the text) or geom_text_repel() functions.


nba <- read.csv("", sep = ",")

nbaplot <- ggplot(nba, aes(x= MIN, y = PTS)) + 
  geom_point(color = "blue", size = 3)

### geom_label_repel
nbaplot + 
  geom_label_repel(aes(label = Name),
                  box.padding   = 0.35, 
                  point.padding = 0.5,
                  segment.color = 'grey50') +

enter image description here

### geom_text_repel
# only label players with PTS > 25 or < 18
# align text vertically with nudge_y and allow the labels to 
# move horizontally with direction = "x"
ggplot(nba, aes(x= MIN, y = PTS, label = Name)) + 
  geom_point(color = dplyr::case_when(nba$PTS > 25 ~ "#1b9e77", 
                                      nba$PTS < 18 ~ "#d95f02",
                                      TRUE ~ "#7570b3"), 
             size = 3, alpha = 0.8) +
  geom_text_repel(data          = subset(nba, PTS > 25),
                  nudge_y       = 32 - subset(nba, PTS > 25)$PTS,
                  size          = 4,
                  box.padding   = 1.5,
                  point.padding = 0.5,
                  force         = 100,
                  segment.size  = 0.2,
                  segment.color = "grey50",
                  direction     = "x") +
  geom_label_repel(data         = subset(nba, PTS < 18),
                  nudge_y       = 16 - subset(nba, PTS < 18)$PTS,
                  size          = 4,
                  box.padding   = 0.5,
                  point.padding = 0.5,
                  force         = 100,
                  segment.size  = 0.2,
                  segment.color = "grey50",
                  direction     = "x") +
  scale_x_continuous(expand = expand_scale(mult = c(0.2, .2))) +
  scale_y_continuous(expand = expand_scale(mult = c(0.1, .1))) +
  theme_classic(base_size = 16)

Edit: To use ggrepel with lines, see this and this.

Created on 2019-05-01 by the reprex package (v0.2.0).

What is a NullReferenceException, and how do I fix it?

Literally the easiest way to fix a NullReferenceExeption has two ways. If you have a GameObject for example with a script attached and a variable named rb (rigidbody) this variable will start null when you start your game.
This is why you get a NullReferenceExeption because the computer does not have data stored in that variable.

I'll be using a RigidBody variable as an example.
We can add data really easily actually in a few ways:

  1. Add a RigidBody to your object with AddComponent > Physics > Rigidbody
    Then go into your script and type rb = GetComponent<Rigidbody>();
    This line of code works best under your Start() or Awake() functions.
  2. You can add a component programmatically and assign the variable at the same time with one line of code: rb = AddComponent<RigidBody>();

Further Notes: If you want unity to add a component to your object and you might have forgotten to add one, you can type [RequireComponent(typeof(RigidBody))] above your class declaration (the space below all of your usings).
Enjoy and have fun making games!

What should be the package name of android app?

As you stated, package names are usually in the form of 'com.organizationName.appName' - all lowercase and no spaces. It sounds like the package name that you entered when uploading the app was different from the one declared in the AndroidManifest.

Difference between Running and Starting a Docker container

This is a very important question and the answer is very simple, but fundamental:

  1. Run: create a new container of an image, and execute the container. You can create N clones of the same image. The command is: docker run IMAGE_ID and not docker run CONTAINER_ID

enter image description here

  1. Start: Launch a container previously stopped. For example, if you had stopped a database with the command docker stop CONTAINER_ID, you can relaunch the same container with the command docker start CONTAINER_ID, and the data and settings will be the same.

enter image description here

ssh-copy-id no identities found error

The ssh-copy-id is not able to locate the file that is generated by ssh-keygen in your system, Use the following command to complete:

  1. find the path of the .pub file: locate *.pub
  2. copy the path (ex: /home/user_name/.ssh/ and run the following command: ssh-copy-id -i /home/user_name/.ssh/ hostname

How can I determine if a date is between two dates in Java?

Here's a couple ways to do this using the Joda-Time 2.3 library.

One way is to use the simple isBefore and isAfter methods on DateTime instances. By the way, DateTime in Joda-Time is similar in concept to a java.util.Date (a moment in time on the timeline of the Universe) but includes a time zone.

Another way is to build an Interval in Joda-Time. The contains method tests if a given DateTime occurs within the span of time covered by the Interval. The beginning of the Interval is inclusive, but the endpoint is exclusive. This approach is known as "Half-Open", symbolically [).

See both ways in the following code example.

Convert the java.util.Date instances to Joda-Time DateTime instances. Simply pass the Date instance to constructor of DateTime. In practice you should also pass a specific DateTimeZone object rather than rely on JVM’s default time zone.

DateTime dateTime1 = new DateTime( new java.util.Date() ).minusWeeks( 1 );
DateTime dateTime2 = new DateTime( new java.util.Date() );
DateTime dateTime3 = new DateTime( new java.util.Date() ).plusWeeks( 1 );

Compare by testing for before/after…

boolean is1After2 = dateTime1.isAfter( dateTime2 );
boolean is2Before3 = dateTime2.isBefore( dateTime3 );

boolean is2Between1And3 = ( ( dateTime2.isAfter( dateTime1 ) ) && ( dateTime2.isBefore( dateTime3 ) ) );

Using the Interval approach instead of isAfter/isBefore…

Interval interval = new Interval( dateTime1, dateTime3 );
boolean intervalContainsDateTime2 = interval.contains( dateTime2 );

Dump to console…

System.out.println( "DateTimes: " + dateTime1 + " " + dateTime1 + " " + dateTime1 );
System.out.println( "is1After2 " + is1After2 );
System.out.println( "is2Before3 " + is2Before3 );
System.out.println( "is2Between1And3 " + is2Between1And3 );
System.out.println( "intervalContainsDateTime2 " + intervalContainsDateTime2 );

When run…

DateTimes: 2014-01-22T20:26:14.955-08:00 2014-01-22T20:26:14.955-08:00 2014-01-22T20:26:14.955-08:00
is1After2 false
is2Before3 true
is2Between1And3 true
intervalContainsDateTime2 true

How to call a JavaScript function, declared in <head>, in the body when I want to call it

Just drop


in the body where you want it to be called, understanding that when the page loads and the browser reaches that point, that's when the call will occur.

No Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator

I had this issue and i fixed with the code below.

open class JacksonMapper {

    open fun mapper(): ObjectMapper {
        val mapper = ObjectMapper()

        return mapper

SQLAlchemy: how to filter date field?

if you want to get the whole period:

    from sqlalchemy import and_, func

    query = DBSession.query(User).filter(and_( >= '1985-01-17'),\
                                     <= '1988-01-17'))

That means range: 1985-01-17 00:00 - 1988-01-17 23:59


For complete the accepted answer, Had the same issue. First specified the remote

git remote add origin

git fetch 

Then get the code

git pull origin master

SSH to Vagrant box in Windows?

There is an OpenSSH package for Windows which is basically a stripped down Cygwin. It has an msi-Installer and (after setting your path accordingly) works with "vsagrant ssh":

CGRectMake, CGPointMake, CGSizeMake, CGRectZero, CGPointZero is unavailable in Swift

In Swift 4 it works like below

collectionView.setContentOffset(, animated: true)

Rounding float in Ruby

you can use this for rounding to a precison..

//to_f is for float

salary= 2921.9121
puts salary.to_f.round(2) // to 2 decimal place                   

puts salary.to_f.round() // to 3 decimal place          

Convert datetime to Unix timestamp and convert it back in python

def dt2ts(dt, utc=False):
    if utc:
        return calendar.timegm(dt.timetuple())
    if dt.tzinfo is None:
        return int(time.mktime(dt.timetuple()))
    utc_dt = dt.astimezone(tz.tzutc()).timetuple()
    return calendar.timegm(utc_dt)

If you want UTC timestamp :time.mktime just for local dt .Use calendar.timegm is safe but dt must the utc zone so change the zone to utc. If dt in UTC just use calendar.timegm.

Difference between map and collect in Ruby?

#collect is actually an alias for #map. That means the two methods can be used interchangeably, and effect the same behavior.

matplotlib.pyplot will not forget previous plots - how can I flush/refresh?

I discovered that this behaviour only occurs after running a particular script, similar to the one in the question. I have no idea why it occurs.

It works (refreshes the graphs) if I put


after every

How can I inspect the file system of a failed `docker build`?

Debugging build step failures is indeed very annoying.

The best solution I have found is to make sure that each step that does real work succeeds, and adding a check after those that fails. That way you get a committed layer that contains the outputs of the failed step that you can inspect.

A Dockerfile, with an example after the # Run DB2 silent installer line:

# DB2 10.5 Client Dockerfile (Part 1)
# Requires
#   - DB2 10.5 Client for 64bit Linux ibm_data_server_runtime_client_linuxx64_v10.5.tar.gz
#   - Response file for DB2 10.5 Client for 64bit Linux db2rtcl_nr.rsp 
# Using Ubuntu 14.04 base image as the starting point.
FROM ubuntu:14.04

MAINTAINER David Carew <[email protected]>

# DB2 prereqs (also installing sharutils package as we use the utility uuencode to generate password - all others are required for the DB2 Client) 
RUN dpkg --add-architecture i386 && apt-get update && apt-get install -y sharutils binutils libstdc++6:i386 libpam0g:i386 && ln -s /lib/i386-linux-gnu/ /lib/
RUN apt-get install -y libxml2

# Create user db2clnt
# Generate strong random password and allow sudo to root w/o password
RUN  \
   adduser --quiet --disabled-password -shell /bin/bash -home /home/db2clnt --gecos "DB2 Client" db2clnt && \
   echo db2clnt:`dd if=/dev/urandom bs=16 count=1 2>/dev/null | uuencode -| head -n 2 | grep -v begin | cut -b 2-10` | chgpasswd && \
   adduser db2clnt sudo && \
   echo '%sudo ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers

# Install DB2
RUN mkdir /install
# Copy DB2 tarball - ADD command will expand it automatically
ADD v10.5fp9_linuxx64_rtcl.tar.gz /install/
# Copy response file
COPY  db2rtcl_nr.rsp /install/
# Run  DB2 silent installer
RUN mkdir /logs
RUN (/install/rtcl/db2setup -t /logs/trace -l /logs/log -u /install/db2rtcl_nr.rsp && touch /install/done) || /bin/true
RUN test -f /install/done || (echo ERROR-------; echo install failed, see files in container /logs directory of the last container layer; echo run docker run '<last image id>' /bin/cat /logs/trace; echo ----------)
RUN test -f /install/done

# Clean up unwanted files
RUN rm -fr /install/rtcl

# Login as db2clnt user
CMD su - db2clnt