Programs & Examples On #Handle leak

Null or empty check for a string variable

Yes, that code does exactly that.

You can also use:

if (@value is null or @value = '')

Edit:

With the added information that @value is an int value, you need instead:

if (@value is null)

An int value can never contain the value ''.

How do I restore a dump file from mysqldump?

You cannot use the Restore menu in MySQL Admin if the backup / dump wasn't created from there. It's worth a shot though. If you choose to "ignore errors" with the checkbox for that, it will say it completed successfully, although it clearly exits with only a fraction of rows imported...this is with a dump, mind you.

matplotlib: colorbars and its text labels

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import ListedColormap

#discrete color scheme
cMap = ListedColormap(['white', 'green', 'blue','red'])

#data
np.random.seed(42)
data = np.random.rand(4, 4)
fig, ax = plt.subplots()
heatmap = ax.pcolor(data, cmap=cMap)

#legend
cbar = plt.colorbar(heatmap)

cbar.ax.get_yaxis().set_ticks([])
for j, lab in enumerate(['$0$','$1$','$2$','$>3$']):
    cbar.ax.text(.5, (2 * j + 1) / 8.0, lab, ha='center', va='center')
cbar.ax.get_yaxis().labelpad = 15
cbar.ax.set_ylabel('# of contacts', rotation=270)


# put the major ticks at the middle of each cell
ax.set_xticks(np.arange(data.shape[1]) + 0.5, minor=False)
ax.set_yticks(np.arange(data.shape[0]) + 0.5, minor=False)
ax.invert_yaxis()

#labels
column_labels = list('ABCD')
row_labels = list('WXYZ')
ax.set_xticklabels(column_labels, minor=False)
ax.set_yticklabels(row_labels, minor=False)

plt.show()

You were very close. Once you have a reference to the color bar axis, you can do what ever you want to it, including putting text labels in the middle. You might want to play with the formatting to make it more visible.

demo

How do you change the character encoding of a postgres database?

To change the encoding of your database:

  1. Dump your database
  2. Drop your database,
  3. Create new database with the different encoding
  4. Reload your data.

Make sure the client encoding is set correctly during all this.

Source: http://archives.postgresql.org/pgsql-novice/2006-03/msg00210.php

How to hide only the Close (x) button?

If you really want to hide it, as in "not visible", then you will probably have to create a borderless form and draw the caption components yourself. VisualStyles library has the Windows Elements available. You would also have to add back in the functionality of re-sizing the form or moving the form by grabbing the caption bar. Not to mention the system menu in the corner.

In most cases, it's hard to justify having the "close" button not available, especially when you want a modal form with minimizing capabilities. Minimizing a modal form really makes no sense.

Plot a horizontal line using matplotlib

Use matplotlib.pyplot.hlines:

  • Plot multiple horizontal lines by passing a list to the y parameter.
  • y can be passed as a single location: y=40
  • y can be passed as multiple locations: y=[39, 40, 41]
  • If you're a plotting a figure with something like fig, ax = plt.subplots(), then replace plt.hlines or plt.axhline with ax.hlines or ax.axhline, respectively.
  • matplotlib.pyplot.axhline can only plot a single location (e.g. y=40)

plt.plot

import numpy as np
import matplotlib.pyplot as plt

xs = np.linspace(1, 21, 200)

plt.figure(figsize=(6, 3))
plt.hlines(y=39.5, xmin=100, xmax=175, colors='aqua', linestyles='-', lw=2, label='Single Short Line')
plt.hlines(y=[39, 40, 41], xmin=[0, 25, 50], xmax=[len(xs)], colors='purple', linestyles='--', lw=2, label='Multiple Lines')
plt.legend(bbox_to_anchor=(1.04,0.5), loc="center left", borderaxespad=0)

enter image description here

ax.plot

import numpy as np
import matplotlib.pyplot as plt

xs = np.linspace(1, 21, 200)
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(6, 6))

ax1.hlines(y=40, xmin=0, xmax=len(xs), colors='r', linestyles='--', lw=2)
ax1.set_title('One Line')

ax2.hlines(y=[39, 40, 41], xmin=0, xmax=len(xs), colors='purple', linestyles='--', lw=2)
ax2.set_title('Multiple Lines')

plt.tight_layout()
plt.show()

enter image description here

Time Series Axis

  • xmin and xmax will accept a date like '2020-09-10' or datetime(2020, 9, 10)
    • xmin=datetime(2020, 9, 10), xmax=datetime(2020, 9, 10) + timedelta(days=3)
    • Given date = df.index[9], xmin=date, xmax=date + pd.Timedelta(days=3), where the index is a DatetimeIndex.
import pandas_datareader as web  # conda or pip install this; not part of pandas
import pandas as pd
import matplotlib.pyplot as plt

# get test data
df = web.DataReader('^gspc', data_source='yahoo', start='2020-09-01', end='2020-09-28').iloc[:, :2]

# plot dataframe
ax = df.plot(figsize=(9, 6), title='S&P 500', ylabel='Price')

# add horizontal line
ax.hlines(y=3450, xmin='2020-09-10', xmax='2020-09-17', color='purple', label='test')

ax.legend()
plt.show()

enter image description here

  • Sample time series data if web.DataReader doesn't work.
data = {pd.Timestamp('2020-09-01 00:00:00'): {'High': 3528.03, 'Low': 3494.6}, pd.Timestamp('2020-09-02 00:00:00'): {'High': 3588.11, 'Low': 3535.23}, pd.Timestamp('2020-09-03 00:00:00'): {'High': 3564.85, 'Low': 3427.41}, pd.Timestamp('2020-09-04 00:00:00'): {'High': 3479.15, 'Low': 3349.63}, pd.Timestamp('2020-09-08 00:00:00'): {'High': 3379.97, 'Low': 3329.27}, pd.Timestamp('2020-09-09 00:00:00'): {'High': 3424.77, 'Low': 3366.84}, pd.Timestamp('2020-09-10 00:00:00'): {'High': 3425.55, 'Low': 3329.25}, pd.Timestamp('2020-09-11 00:00:00'): {'High': 3368.95, 'Low': 3310.47}, pd.Timestamp('2020-09-14 00:00:00'): {'High': 3402.93, 'Low': 3363.56}, pd.Timestamp('2020-09-15 00:00:00'): {'High': 3419.48, 'Low': 3389.25}, pd.Timestamp('2020-09-16 00:00:00'): {'High': 3428.92, 'Low': 3384.45}, pd.Timestamp('2020-09-17 00:00:00'): {'High': 3375.17, 'Low': 3328.82}, pd.Timestamp('2020-09-18 00:00:00'): {'High': 3362.27, 'Low': 3292.4}, pd.Timestamp('2020-09-21 00:00:00'): {'High': 3285.57, 'Low': 3229.1}, pd.Timestamp('2020-09-22 00:00:00'): {'High': 3320.31, 'Low': 3270.95}, pd.Timestamp('2020-09-23 00:00:00'): {'High': 3323.35, 'Low': 3232.57}, pd.Timestamp('2020-09-24 00:00:00'): {'High': 3278.7, 'Low': 3209.45}, pd.Timestamp('2020-09-25 00:00:00'): {'High': 3306.88, 'Low': 3228.44}, pd.Timestamp('2020-09-28 00:00:00'): {'High': 3360.74, 'Low': 3332.91}}

df = pd.DataFrame.from_dict(data, 'index')

error: expected declaration or statement at end of input in c

Try to place a

return 0;

on the end of your code or just erase the

void

from your main function I hope that I helped

Ignore 'Security Warning' running script from command line

Assume that you need to launch ps script from shared folder

copy \\\server\script.ps1 c:\tmp.ps1 /y && PowerShell.exe -ExecutionPolicy Bypass -File c:\tmp.ps1 && del /f c:\tmp.ps1

P.S. Reduce googling)

Javascript Iframe innerHTML

document.getElementById('iframe01').outerHTML

is it possible to evenly distribute buttons across the width of an android linearlayout

You may use it with like the following.

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_marginTop="15dp">
    <Space
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Save"/>
    <Space
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Reset"/>
    <Space
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="cancel"/>
    <Space
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"/>
</LinearLayout>

VueJs get url query

In my case I console.log(this.$route) and returned the fullPath:

console.js:
fullPath: "/solicitud/MX/666",
params: {market: "MX", id: "666"},
path: "/solicitud/MX/666"

console.js: /solicitud/MX/666

How to install VS2015 Community Edition offline

If you are a MSDN subscriber follow the steps below:

  1. Go to msdn.microsoft.com and sign in.

  2. Go to Programs->Subscriptions->Overview

  3. Click on Subscriber Access

  4. Click on Product Keys ( Claim key as needed)

  5. Select your Visual Studio Preference.

  6. click the EXE drop down list, and select DVD. This will change it to an .ISO image.By default the web installer is selected,

  7. Click green download button(approximately 7.12Gb)

note: I used a Virtual-CloneDrive-5.5 to mount this ISO and install

How to update a record using sequelize for node?

I have used sequelize.js, node.js and transaction in below code and added proper error handling if it doesn't find data it will throw error that no data found with that id

editLocale: async (req, res) => {

    sequelize.sequelize.transaction(async (t1) => {

        if (!req.body.id) {
            logger.warn(error.MANDATORY_FIELDS);
            return res.status(500).send(error.MANDATORY_FIELDS);
        }

        let id = req.body.id;

        let checkLocale= await sequelize.Locale.findOne({
            where: {
                id : req.body.id
            }
        });

        checkLocale = checkLocale.get();
        if (checkLocale ) {
            let Locale= await sequelize.Locale.update(req.body, {
                where: {
                    id: id
                }
            });

            let result = error.OK;
            result.data = Locale;

            logger.info(result);
            return res.status(200).send(result);
        }
        else {
            logger.warn(error.DATA_NOT_FOUND);
            return res.status(404).send(error.DATA_NOT_FOUND);
        }
    }).catch(function (err) {
        logger.error(err);
        return res.status(500).send(error.SERVER_ERROR);
    });
},

How to install PIP on Python 3.6?

I just successfully installed a package for excel. After installing the python 3.6, you have to download the desired package, then install. For eg,

  1. python.exe -m pip download openpyxl==2.1.4

  2. python.exe -m pip install openpyxl==2.1.4

Duplicate Symbols for Architecture arm64

From the errors, it would appear any Classes appear multiple time.Find and removed that Classes it will working.

Am creating AppDelegate.h and .m file creating multiple time. So this error will occur.Finally find and removed that classes it's working fine for me.

SoapFault exception: Could not connect to host

Version check helped me OpenSSL. OpenSSL_1_0_1f not supported TSLv.1_2 ! Check version and compatibility with TSLv.1_2 on github openssl/openssl . And regenerate your certificate with new openssl

openssl pkcs12 -in path.p12 -out newfile.pem

P.S I don’t know what they were minus, but this solution will really help.

Why does calling sumr on a stream with 50 tuples not complete

sumr is implemented in terms of foldRight:

 final def sumr(implicit A: Monoid[A]): A = F.foldRight(self, A.zero)(A.append) 

foldRight is not always tail recursive, so you can overflow the stack if the collection is too long. See Why foldRight and reduceRight are NOT tail recursive? for some more discussion of when this is or isn't true.

Share application "link" in Android

Call this method:

public static void shareApp(Context context)
{
    final String appPackageName = context.getPackageName();
    Intent sendIntent = new Intent();
    sendIntent.setAction(Intent.ACTION_SEND);
    sendIntent.putExtra(Intent.EXTRA_TEXT, "Check out the App at: https://play.google.com/store/apps/details?id=" + appPackageName);
    sendIntent.setType("text/plain");
    context.startActivity(sendIntent);
}

Why is it bad style to `rescue Exception => e` in Ruby?

TL;DR: Use StandardError instead for general exception catching. When the original exception is re-raised (e.g. when rescuing to log the exception only), rescuing Exception is probably okay.


Exception is the root of Ruby's exception hierarchy, so when you rescue Exception you rescue from everything, including subclasses such as SyntaxError, LoadError, and Interrupt.

Rescuing Interrupt prevents the user from using CTRLC to exit the program.

Rescuing SignalException prevents the program from responding correctly to signals. It will be unkillable except by kill -9.

Rescuing SyntaxError means that evals that fail will do so silently.

All of these can be shown by running this program, and trying to CTRLC or kill it:

loop do
  begin
    sleep 1
    eval "djsakru3924r9eiuorwju3498 += 5u84fior8u8t4ruyf8ihiure"
  rescue Exception
    puts "I refuse to fail or be stopped!"
  end
end

Rescuing from Exception isn't even the default. Doing

begin
  # iceberg!
rescue
  # lifeboats
end

does not rescue from Exception, it rescues from StandardError. You should generally specify something more specific than the default StandardError, but rescuing from Exception broadens the scope rather than narrowing it, and can have catastrophic results and make bug-hunting extremely difficult.


If you have a situation where you do want to rescue from StandardError and you need a variable with the exception, you can use this form:

begin
  # iceberg!
rescue => e
  # lifeboats
end

which is equivalent to:

begin
  # iceberg!
rescue StandardError => e
  # lifeboats
end

One of the few common cases where it’s sane to rescue from Exception is for logging/reporting purposes, in which case you should immediately re-raise the exception:

begin
  # iceberg?
rescue Exception => e
  # do some logging
  raise # not enough lifeboats ;)
end

How to change default text file encoding in Eclipse?

I was having the same problem when I received a html to put inside my project and rename it to .jsp. To solve the problem, I needed to what people above already said, that is, to change text encoding in Eclipse Preferences. However, before renaming the files to .jsp, it was necessary to include the following line in the beginning of each .html file:

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>

I believe this forced Eclipse to understand that it was necessary to change file encoding when I tried to rename .html to .jsp.

WPF button click in C# code

Button btn = new Button();
btn.Name = "btn1";
btn.Click += btn1_Click;

private void btn1_Click(object sender, RoutedEventArgs e)
{
    // do something
}

Creating a new directory in C

You can use mkdir:

$ man 2 mkdir

#include <sys/stat.h>
#include <sys/types.h>

int result = mkdir("/home/me/test.txt", 0777);

Create Log File in Powershell

function WriteLog
{
    Param ([string]$LogString)
    $LogFile = "C:\$(gc env:computername).log"
    $DateTime = "[{0:MM/dd/yy} {0:HH:mm:ss}]" -f (Get-Date)
    $LogMessage = "$Datetime $LogString"
    Add-content $LogFile -value $LogMessage
}

WriteLog "This is my log message"

Is it possible to use argsort in descending order?

With your example:

avgDists = np.array([1, 8, 6, 9, 4])

Obtain indexes of n maximal values:

ids = np.argpartition(avgDists, -n)[-n:]

Sort them in descending order:

ids = ids[np.argsort(avgDists[ids])[::-1]]

Obtain results (for n=4):

>>> avgDists[ids]
array([9, 8, 6, 4])

How to convert CharSequence to String?

You can directly use String.valueOf()

String.valueOf(charSequence)

Though this is same as toString() it does a null check on the charSequence before actually calling toString.

This is useful when a method can return either a charSequence or null value.

SQL Developer is returning only the date, not the time. How do I fix this?

From Tools > Preferences > Database > NLS Parameter and set Date Format as

DD-MON-RR HH:MI:SS

Observable.of is not a function

For Angular 5+ :

import { Observable } from 'rxjs/Observable';should work. The observer package should match the import as well import { Observer } from 'rxjs/Observer'; if you're using observers that is

import {<something>} from 'rxjs'; does a huge import so it's better to avoid it.

How to quit android application programmatically

@Sivi 's answer closes the app. But on return, if you have some child activities, another unfinished activity might be opened. I added noHistory:true to my activities so the app on return starts from MainActivity.

<activity 
      android:name=".MainActivity"
      android:noHistory="true">
</activity>

CSS border less than 1px

The minimum width that your screen can display is 1 pixel. So its impossible to display less then 1px. 1 pixels can only have 1 color and cannot be split up.

What is the exact meaning of Git Bash?

At its core, Git is a set of command line utility programs that are designed to execute on a Unix style command-line environment. Modern operating systems like Linux and macOS both include built-in Unix command line terminals. This makes Linux and macOS complementary operating systems when working with Git. Microsoft Windows instead uses Windows command prompt, a non-Unix terminal environment.

What is Git Bash?

Git Bash is an application for Microsoft Windows environments which provides an emulation layer for a Git command line experience. Bash is an acronym for Bourne Again Shell. A shell is a terminal application used to interface with an operating system through written commands. Bash is a popular default shell on Linux and macOS. Git Bash is a package that installs Bash, some common bash utilities, and Git on a Windows operating system.

source : https://www.atlassian.com/git/tutorials/git-bash

Add space between cells (td) using css

Mine is:

border-spacing: 10px;
border-collapse: separate;

read.csv warning 'EOF within quoted string' prevents complete reading of file

Actually, using read.csv() to read a file with text content is not a good idea, disable the quote as set quote="" is only a temporary solution, it only worked with Separate quotation marks. There are other reasons would cause the warning, such as some special characters.

The permanent solution(using read.csv()), finding out what those special characters are and use a regular expression to eliminate them is an idea.

Have you ever think of installing the package {data.table} and use fread() to read the file. it is much faster and would not bother you with this EOF warning. Note that the file it loads it will be stored as a data.table object but not a data.frame object. The class data.table has many good features, but anyway, you can transform it using as.data.frame() if needed.

How to find index of STRING array in Java from a given value?

An easy way would be to iterate over the items in the array in a loop.

for (var i = 0; i < arrayLength; i++) {
 // (string) Compare the given string with myArray[i]
 // if it matches store/save i and exit the loop.
}

There would definitely be better ways but for small number of items this should be blazing fast. Btw this is javascript but same method should work in almost every programming language.

Hibernate problem - "Use of @OneToMany or @ManyToMany targeting an unmapped class"

In my case a has to add my classes, when building the SessionFactory, with addAnnotationClass

Configuration configuration.configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
SessionFactory sessionFactory = configuration
            .addAnnotatedClass(MyEntity1.class)
            .addAnnotatedClass(MyEntity2.class)
            .buildSessionFactory(builder.build());

How to solve a pair of nonlinear equations using Python?

An alternative to fsolve is root:

import numpy as np
from scipy.optimize import root    

def your_funcs(X):

    x, y = X
    # all RHS have to be 0
    f = [x + y**2 - 4,
         np.exp(x) + x * y - 3]

    return f

sol = root(your_funcs, [1.0, 1.0])
print(sol.x)

This will print

[0.62034452 1.83838393]

If you then check

print(your_funcs(sol.x))

you obtain

[4.4508396968012676e-11, -1.0512035686360832e-11]

confirming that the solution is correct.

How can I convert my Java program to an .exe file?

The latest Java Web Start has been enhanced to allow good offline operation as well as allowing "local installation". It is worth looking into.

EDIT 2018: Java Web Start is no longer bundled with the newest JDK's. Oracle is pushing towards a "deploy your app locally with an enclosed JRE" model instead.

Java: Identifier expected

Try it like this instead, move your myclass items inside a main method:

    class UserInput {
      public void name() {
        System.out.println("This is a test.");
      }
    }

    public class MyClass {

        public static void main( String args[] )
        {
            UserInput input = new UserInput();
            input.name();
        }

    }

load csv into 2D matrix with numpy for plotting

I think using dtype where there is a name row is confusing the routine. Try

>>> r = np.genfromtxt(fname, delimiter=',', names=True)
>>> r
array([[  6.11882430e+02,   9.08956010e+03,   5.13300000e+03,
          8.64075140e+02,   1.71537476e+03,   7.65227770e+02,
          1.29111196e+12],
       [  6.11882430e+02,   9.08956010e+03,   5.13300000e+03,
          8.64075140e+02,   1.71537476e+03,   7.65227770e+02,
          1.29111311e+12],
       [  6.11882430e+02,   9.08956010e+03,   5.13300000e+03,
          8.64075140e+02,   1.71537476e+03,   7.65227770e+02,
          1.29112065e+12]])
>>> r[:,0]    # Slice 0'th column
array([ 611.88243,  611.88243,  611.88243])

Fragments within Fragments

Nested fragments are supported in android 4.2 and later

The Android Support Library also now supports nested fragments, so you can implement nested fragment designs on Android 1.6 and higher.

To nest a fragment, simply call getChildFragmentManager() on the Fragment in which you want to add a fragment. This returns a FragmentManager that you can use like you normally do from the top-level activity to create fragment transactions. For example, here’s some code that adds a fragment from within an existing Fragment class:

Fragment videoFragment = new VideoPlayerFragment();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.add(R.id.video_fragment, videoFragment).commit();

To get more idea about nested fragments, please go through these tutorials
Part 1
Part 2
Part 3

and here is a SO post which discuss about best practices for nested fragments.

how to delete installed library form react native project

I will post my answer here since it's the first result in google's search

1) react-native unlink <Module Name>

2) npm unlink <Module Name>

3) npm uninstall --save <Module name

How to generate range of numbers from 0 to n in ES2015 only?

Here's another variation that doesn't use Array.

let range = (n, l=[], delta=1) => {
  if (n < 0) { 
    return l 
  }
  else {
    l.unshift(n)
    return range(n - delta, l) 
  }
}

Tensorflow image reading & display

You can use tf.keras API.

import tensorflow as tf
import numpy as np
from tensorflow.keras.preprocessing.image import load_img, array_to_img

tf.enable_eager_execution()

img = load_img("example.png")
img = tf.convert_to_tensor(np.asarray(img))
image = tf.image.resize_images(img, (800, 800))
to_img = array_to_img(image)
to_img.show()

How to position one element relative to another with jQuery?

tl;dr: (try it here)

If you have the following HTML:

<div id="menu" style="display: none;">
   <!-- menu stuff in here -->
   <ul><li>Menu item</li></ul>
</div>

<div class="parent">Hover over me to show the menu here</div>

then you can use the following JavaScript code:

$(".parent").mouseover(function() {
    // .position() uses position relative to the offset parent, 
    var pos = $(this).position();

    // .outerWidth() takes into account border and padding.
    var width = $(this).outerWidth();

    //show the menu directly over the placeholder
    $("#menu").css({
        position: "absolute",
        top: pos.top + "px",
        left: (pos.left + width) + "px"
    }).show();
});

But it doesn't work!

This will work as long as the menu and the placeholder have the same offset parent. If they don't, and you don't have nested CSS rules that care where in the DOM the #menu element is, use:

$(this).append($("#menu"));

just before the line that positions the #menu element.

But it still doesn't work!

You might have some weird layout that doesn't work with this approach. In that case, just use jQuery.ui's position plugin (as mentioned in an answer below), which handles every conceivable eventuality. Note that you'll have to show() the menu element before calling position({...}); the plugin can't position hidden elements.

Update notes 3 years later in 2012:

(The original solution is archived here for posterity)

So, it turns out that the original method I had here was far from ideal. In particular, it would fail if:

  • the menu's offset parent is not the placeholder's offset parent
  • the placeholder has a border/padding

Luckily, jQuery introduced methods (position() and outerWidth()) way back in 1.2.6 that make finding the right values in the latter case here a lot easier. For the former case, appending the menu element to the placeholder works (but will break CSS rules based on nesting).

How do I tokenize a string in C++?

I thought that was what the >> operator on string streams was for:

string word; sin >> word;

Odd behavior when Java converts int to byte?

often in books you will find the explanation of casting from int to byte as being performed by modulus division. this is not strictly correct as shown below what actually happens is the 24 most significant bits from the binary value of the int number are discarded leaving confusion if the remaining leftmost bit is set which designates the number as negative

public class castingsample{

public static void main(String args[]){

    int i;
    byte y;
    i = 1024;
    for(i = 1024; i > 0; i-- ){

      y = (byte)i;
      System.out.print(i + " mod 128 = " + i%128 + " also ");
      System.out.println(i + " cast to byte " + " = " + y);

    }

}

}

Best practice to look up Java Enum

The error message in IllegalArgumentException is already descriptive enough.

Your method makes a generic exception out of a specific one with the same message simply reworded. A developer would prefer the specific exception type and can handle the case appropriately instead of trying to handle RuntimeException.

If the intent is to make the message more user friendly, then references to values of enums is irrelevant to them anyway. Let the UI code determine what should be displayed to the user, and the UI developer would be better off with the IllegalArgumentException.

Difference between 'struct' and 'typedef struct' in C++?

One more important difference: typedefs cannot be forward declared. So for the typedef option you must #include the file containing the typedef, meaning everything that #includes your .h also includes that file whether it directly needs it or not, and so on. It can definitely impact your build times on larger projects.

Without the typedef, in some cases you can just add a forward declaration of struct Foo; at the top of your .h file, and only #include the struct definition in your .cpp file.

How to uncompress a tar.gz in another directory

You can use the option -C (or --directory if you prefer long options) to give the target directory of your choice in case you are using the Gnu version of tar. The directory should exist:

mkdir foo
tar -xzf bar.tar.gz -C foo

If you are not using a tar capable of extracting to a specific directory, you can simply cd into your target directory prior to calling tar; then you will have to give a complete path to your archive, of course. You can do this in a scoping subshell to avoid influencing the surrounding script:

mkdir foo
(cd foo; tar -xzf ../bar.tar.gz)  # instead of ../ you can use an absolute path as well

Or, if neither an absolute path nor a relative path to the archive file is suitable, you also can use this to name the archive outside of the scoping subshell:

TARGET_PATH=a/very/complex/path/which/might/even/be/absolute
mkdir -p "$TARGET_PATH"
(cd "$TARGET_PATH"; tar -xzf -) < bar.tar.gz

How do I use a file grep comparison inside a bash if/else statement?

just use bash

while read -r line
do
  case "$line" in
    *MYSQL_ROLE=master*)
       echo "do your stuff";;
    *) echo "doesn't exist";;      
  esac
done <"/etc/aws/hosts.conf"

How to obtain the last index of a list?

Did you mean len(list1)-1?

If you're searching for other method, you can try list1.index(list1[-1]), but I don't recommend this one. You will have to be sure, that the list contains NO duplicates.

Windows batch: formatted date into variable

If you wish to achieve this using standard MS-DOS commands in a batch file then you could use:

FOR /F "TOKENS=1 eol=/ DELIMS=/ " %%A IN ('DATE/T') DO SET dd=%%A
FOR /F "TOKENS=1,2 eol=/ DELIMS=/ " %%A IN ('DATE/T') DO SET mm=%%B
FOR /F "TOKENS=1,2,3 eol=/ DELIMS=/ " %%A IN ('DATE/T') DO SET yyyy=%%C

I'm sure this can be improved upon further but this gives the date into 3 variables for Day (dd), Month (mm) and Year (yyyy). You can then use these later in your batch script as required.

SET todaysdate=%yyyy%%mm%%dd%
echo %dd%
echo %mm%
echo %yyyy%
echo %todaysdate%

While I understand an answer has been accepted for this question this alternative method may be appreciated by many looking to achieve this without using the WMI console, so I hope it adds some value to this question.

How to convert a Scikit-learn dataset to a Pandas dataset?

Update: 2020

You can use the parameter as_frame=True to get pandas dataframes.

If as_frame parameter available (eg. load_iris)

from sklearn import datasets
X,y = datasets.load_iris(return_X_y=True) # numpy arrays

dic_data = datasets.load_iris(as_frame=True)
print(dic_data.keys())

df = dic_data['frame'] # pandas dataframe data + target
df_X = dic_data['data'] # pandas dataframe data only
ser_y = dic_data['target'] # pandas series target only
dic_data['target_names'] # numpy array

If as_frame parameter NOT available (eg. load_boston)

from sklearn import datasets

fnames = [ i for i in dir(datasets) if 'load_' in i]
print(fnames)

fname = 'load_boston'
loader = getattr(datasets,fname)()
df = pd.DataFrame(loader['data'],columns= loader['feature_names'])
df['target'] = loader['target']
df.head(2)

"webxml attribute is required" error in Maven

mvn-war-plugin 2.3 fixes this:

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <version>2.3</version>
        </plugin>
        ...

python .replace() regex

In order to replace text using regular expression use the re.sub function:

sub(pattern, repl, string[, count, flags])

It will replace non-everlaping instances of pattern by the text passed as string. If you need to analyze the match to extract information about specific group captures, for instance, you can pass a function to the string argument. more info here.

Examples

>>> import re
>>> re.sub(r'a', 'b', 'banana')
'bbnbnb'

>>> re.sub(r'/\d+', '/{id}', '/andre/23/abobora/43435')
'/andre/{id}/abobora/{id}'

Remove spaces from a string in VB.NET

2015: Newer LINQ & lambda.

  1. As this is an old Q (and Answer), just thought to update it with newer 2015 methods.
  2. The original "space" can refer to non-space whitespace (ie, tab, newline, paragraph separator, line feed, carriage return, etc, etc).
  3. Also, Trim() only remove the spaces from the front/back of the string, it does not remove spaces inside the string; eg: " Leading and Trailing Spaces " will become "Leading and Trailing Spaces", but the spaces inside are still present.

Function RemoveWhitespace(fullString As String) As String
    Return New String(fullString.Where(Function(x) Not Char.IsWhiteSpace(x)).ToArray())
End Function

This will remove ALL (white)-space, leading, trailing and within the string.

Angular 4 Pipe Filter

Pipes in Angular 2+ are a great way to transform and format data right from your templates.

Pipes allow us to change data inside of a template; i.e. filtering, ordering, formatting dates, numbers, currencies, etc. A quick example is you can transfer a string to lowercase by applying a simple filter in the template code.

List of Built-in Pipes from API List Examples

{{ user.name | uppercase }}

Example of Angular version 4.4.7. ng version


Custom Pipes which accepts multiple arguments.

HTML « *ngFor="let student of students | jsonFilterBy:[searchText, 'name'] "
TS   « transform(json: any[], args: any[]) : any[] { ... }

Filtering the content using a Pipe « json-filter-by.pipe.ts

import { Pipe, PipeTransform, Injectable } from '@angular/core';

@Pipe({ name: 'jsonFilterBy' })
@Injectable()
export class JsonFilterByPipe implements PipeTransform {

  transform(json: any[], args: any[]) : any[] {
    var searchText = args[0];
    var jsonKey = args[1];

    // json = undefined, args = (2) [undefined, "name"]
    if(searchText == null || searchText == 'undefined') return json;
    if(jsonKey    == null || jsonKey    == 'undefined') return json;

    // Copy all objects of original array into new Array.
    var returnObjects = json;
    json.forEach( function ( filterObjectEntery ) {

      if( filterObjectEntery.hasOwnProperty( jsonKey ) ) {
        console.log('Search key is available in JSON object.');

        if ( typeof filterObjectEntery[jsonKey] != "undefined" && 
        filterObjectEntery[jsonKey].toLowerCase().indexOf(searchText.toLowerCase()) > -1 ) {
            // object value contains the user provided text.
        } else {
            // object didn't match a filter value so remove it from array via filter
            returnObjects = returnObjects.filter(obj => obj !== filterObjectEntery);
        }
      } else {
        console.log('Search key is not available in JSON object.');
      }

    })
    return returnObjects;
  }
}

Add to @NgModule « Add JsonFilterByPipe to your declarations list in your module; if you forget to do this you'll get an error no provider for jsonFilterBy. If you add to module then it is available to all the component's of that module.

@NgModule({
  imports: [
    CommonModule,
    RouterModule,
    FormsModule, ReactiveFormsModule,
  ],
  providers: [ StudentDetailsService ],
  declarations: [
    UsersComponent, UserComponent,

    JsonFilterByPipe,
  ],
  exports : [UsersComponent, UserComponent]
})
export class UsersModule {
    // ...
}

File Name: users.component.ts and StudentDetailsService is created from this link.

import { MyStudents } from './../../services/student/my-students';
import { Component, OnInit, OnDestroy } from '@angular/core';
import { StudentDetailsService } from '../../services/student/student-details.service';

@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrls: [ './users.component.css' ],

  providers:[StudentDetailsService]
})
export class UsersComponent implements OnInit, OnDestroy  {

  students: MyStudents[];
  selectedStudent: MyStudents;

  constructor(private studentService: StudentDetailsService) { }

  ngOnInit(): void {
    this.loadAllUsers();
  }
  ngOnDestroy(): void {
    // ONDestroy to prevent memory leaks
  }

  loadAllUsers(): void {
    this.studentService.getStudentsList().then(students => this.students = students);
  }

  onSelect(student: MyStudents): void {
    this.selectedStudent = student;
  }

}

File Name: users.component.html

<div>
    <br />
    <div class="form-group">
        <div class="col-md-6" >
            Filter by Name: 
            <input type="text" [(ngModel)]="searchText" 
                   class="form-control" placeholder="Search By Category" />
        </div>
    </div>

    <h2>Present are Students</h2>
    <ul class="students">
    <li *ngFor="let student of students | jsonFilterBy:[searchText, 'name'] " >
        <a *ngIf="student" routerLink="/users/update/{{student.id}}">
            <span class="badge">{{student.id}}</span> {{student.name | uppercase}}
        </a>
    </li>
    </ul>
</div>

Take a screenshot via a Python script on Linux

Try it:

#!/usr/bin/python

import gtk.gdk
import time
import random
import socket
import fcntl
import struct
import getpass
import os
import paramiko     

while 1:
    # generate a random time between 120 and 300 sec
    random_time = random.randrange(20,25)
    # wait between 120 and 300 seconds (or between 2 and 5 minutes) 

    print "Next picture in: %.2f minutes" % (float(random_time) / 60)

    time.sleep(random_time)
    w = gtk.gdk.get_default_root_window()   
    sz = w.get_size()
    print "The size of the window is %d x %d" % sz
    pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB,False,8,sz[0],sz[1])
    pb = pb.get_from_drawable(w,w.get_colormap(),0,0,0,0,sz[0],sz[1])
    ts = time.asctime( time.localtime(time.time()) )
    date = time.strftime("%d-%m-%Y")
    timer = time.strftime("%I:%M:%S%p")
    filename = timer
    filename += ".png"

    if (pb != None):
        username = getpass.getuser() #Get username
        newpath = r'screenshots/'+username+'/'+date #screenshot save path
        if not os.path.exists(newpath): os.makedirs(newpath)
        saveas = os.path.join(newpath,filename)
        print saveas
        pb.save(saveas,"png")
    else:
        print "Unable to get the screenshot."

Import error No module named skimage

For python 3.5 in case you have multiple python versions and want to install with python3.5:

pip3 install scikit-image --user

How to have an automatic timestamp in SQLite?

To complement answers above...

If you are using EF, adorn the property with Data Annotation [Timestamp], then go to the overrided OnModelCreating, inside your context class, and add this Fluent API code:

modelBuilder.Entity<YourEntity>()
                .Property(b => b.Timestamp)
                .ValueGeneratedOnAddOrUpdate()
                .IsConcurrencyToken()
                .ForSqliteHasDefaultValueSql("CURRENT_TIMESTAMP");

It will make a default value to every data that will be insert into this table.

Hide all warnings in ipython

The accepted answer does not work in Jupyter (at least when using some libraries).

The Javascript solutions here only hide warnings that are already showing but not warnings that would be shown in the future.

To hide/unhide warnings in Jupyter and JupyterLab I wrote the following script that essentially toggles css to hide/unhide warnings.

%%javascript
(function(on) {
const e=$( "<a>Setup failed</a>" );
const ns="js_jupyter_suppress_warnings";
var cssrules=$("#"+ns);
if(!cssrules.length) cssrules = $("<style id='"+ns+"' type='text/css'>div.output_stderr { } </style>").appendTo("head");
e.click(function() {
    var s='Showing';  
    cssrules.empty()
    if(on) {
        s='Hiding';
        cssrules.append("div.output_stderr, div[data-mime-type*='.stderr'] { display:none; }");
    }
    e.text(s+' warnings (click to toggle)');
    on=!on;
}).click();
$(element).append(e);
})(true);

htmlentities() vs. htmlspecialchars()

Because:

  • Sometimes you're writing XML data, and you can't use HTML entities in a XML file.
  • Because htmlentities substitutes more characters than htmlspecialchars. This is unnecessary, makes the PHP script less efficient and the resulting HTML code less readable.

htmlentities is only necessary if your pages use encodings such as ASCII or LATIN-1 instead of UTF-8 and you're handling data with an encoding different from the page's.

Call and receive output from Python script in Java?

Not sure if I understand your question correctly, but provided that you can call the Python executable from the console and just want to capture its output in Java, you can use the exec() method in the Java Runtime class.

Process p = Runtime.getRuntime().exec("python yourapp.py");

You can read up on how to actually read the output here:

http://www.devdaily.com/java/edu/pj/pj010016

There is also an Apache library (the Apache exec project) that can help you with this. You can read more about it here:

http://www.devdaily.com/java/java-exec-processbuilder-process-1

http://commons.apache.org/exec/

append new row to old csv file python

If you use pandas, you can append your dataframes to an existing CSV file this way:

df.to_csv('log.csv', mode='a', index=False, header=False)

With mode='a' we ensure that we append, rather than overwrite, and with header=False we ensure that we append only the values of df rows, rather than header + values.

NoSuchMethodError in javax.persistence.Table.indexes()[Ljavax/persistence/Index

i have experienced same issue in my spring boot application. after removing manually javax.persistance.jar file from lib folder. issue was fixed. in pom.xml file i have remained following dependency only

  <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
  </dependency>

How to detect if a browser is Chrome using jQuery?

User Endless is right,

$.browser.chrome = (typeof window.chrome === "object"); 

code is best to detect Chrome browser using jQuery.

If you using IE and added GoogleFrame as plugin then

var is_chrome = /chrome/.test( navigator.userAgent.toLowerCase() );

code will treat as Chrome browser because GoogleFrame plugin modifying the navigator property and adding chromeframe inside it.

H2 in-memory database. Table not found

I came to this post because I had the same error.

In my case the database evolutions weren't been executed, so the table wasn't there at all.

My problem was that the folder structure for the evolution scripts was wrong.

from: https://www.playframework.com/documentation/2.0/Evolutions

Play tracks your database evolutions using several evolutions script. These scripts are written in plain old SQL and should be located in the conf/evolutions/{database name} directory of your application. If the evolutions apply to your default database, this path is conf/evolutions/default.

I had a folder called conf/evolutions.default created by eclipse. The issue disappeared after I corrected the folder structure to conf/evolutions/default

Resize iframe height according to content height in it

Below is my onload event handler.

I use an IFRAME within a jQuery UI dialog. Different usages will need some adjustments. This seems to do the trick for me (for now) in Internet Explorer 8 and Firefox 3.5. It might need some extra tweaking, but the general idea should be clear.

    function onLoadDialog(frame) {
    try {
        var body = frame.contentDocument.body;
        var $body = $(body);
        var $frame = $(frame);
        var contentDiv = frame.parentNode;
        var $contentDiv = $(contentDiv);

        var savedShow = $contentDiv.dialog('option', 'show');
        var position = $contentDiv.dialog('option', 'position');
        // disable show effect to enable re-positioning (UI bug?)
        $contentDiv.dialog('option', 'show', null);
        // show dialog, otherwise sizing won't work
        $contentDiv.dialog('open');

        // Maximize frame width in order to determine minimal scrollHeight
        $frame.css('width', $contentDiv.dialog('option', 'maxWidth') -
                contentDiv.offsetWidth + frame.offsetWidth);

        var minScrollHeight = body.scrollHeight;
        var maxWidth = body.offsetWidth;
        var minWidth = 0;
        // decrease frame width until scrollHeight starts to grow (wrapping)
        while (Math.abs(maxWidth - minWidth) > 10) {
            var width = minWidth + Math.ceil((maxWidth - minWidth) / 2);
            $body.css('width', width);
            if (body.scrollHeight > minScrollHeight) {
                minWidth = width;
            } else {
                maxWidth = width;
            }
        }
        $frame.css('width', maxWidth);
        // use maximum height to avoid vertical scrollbar (if possible)
        var maxHeight = $contentDiv.dialog('option', 'maxHeight')
        $frame.css('height', maxHeight);
        $body.css('width', '');
        // correct for vertical scrollbar (if necessary)
        while (body.clientWidth < maxWidth) {
            $frame.css('width', maxWidth + (maxWidth - body.clientWidth));
        }

        var minScrollWidth = body.scrollWidth;
        var minHeight = Math.min(minScrollHeight, maxHeight);
        // descrease frame height until scrollWidth decreases (wrapping)
        while (Math.abs(maxHeight - minHeight) > 10) {
            var height = minHeight + Math.ceil((maxHeight - minHeight) / 2);
            $body.css('height', height);
            if (body.scrollWidth < minScrollWidth) {
                minHeight = height;
            } else {
                maxHeight = height;
            }
        }
        $frame.css('height', maxHeight);
        $body.css('height', '');

        // reset widths to 'auto' where possible
        $contentDiv.css('width', 'auto');
        $contentDiv.css('height', 'auto');
        $contentDiv.dialog('option', 'width', 'auto');

        // re-position the dialog
        $contentDiv.dialog('option', 'position', position);

        // hide dialog
        $contentDiv.dialog('close');
        // restore show effect
        $contentDiv.dialog('option', 'show', savedShow);
        // open using show effect
        $contentDiv.dialog('open');
        // remove show effect for consecutive requests
        $contentDiv.dialog('option', 'show', null);

        return;
    }

    //An error is raised if the IFrame domain != its container's domain
    catch (e) {
        window.status = 'Error: ' + e.number + '; ' + e.description;
        alert('Error: ' + e.number + '; ' + e.description);
    }
};

How to check if a file exists in Documents folder?

If you set up your file system differently or looking for a different way of setting up a file system and then checking if a file exists in the documents folder heres an another example. also show dynamic checking

for (int i = 0; i < numberHere; ++i){
    NSFileManager* fileMgr = [NSFileManager defaultManager];
    NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    NSString* imageName = [NSString stringWithFormat:@"image-%@.png", i];
    NSString* currentFile = [documentsDirectory stringByAppendingPathComponent:imageName];
    BOOL fileExists = [fileMgr fileExistsAtPath:currentFile];
    if (fileExists == NO){
        cout << "DOESNT Exist!" << endl;
    } else {
        cout << "DOES Exist!" << endl;
    }
}

How to define a variable in a Dockerfile?

You can use ARG - see https://docs.docker.com/engine/reference/builder/#arg

The ARG instruction defines a variable that users can pass at build-time to the builder with the docker build command using the --build-arg <varname>=<value> flag. If a user specifies a build argument that was not defined in the Dockerfile, the build outputs an error.

Calculate the mean by group

There are many ways to do this in R. Specifically, by, aggregate, split, and plyr, cast, tapply, data.table, dplyr, and so forth.

Broadly speaking, these problems are of the form split-apply-combine. Hadley Wickham has written a beautiful article that will give you deeper insight into the whole category of problems, and it is well worth reading. His plyr package implements the strategy for general data structures, and dplyr is a newer implementation performance tuned for data frames. They allow for solving problems of the same form but of even greater complexity than this one. They are well worth learning as a general tool for solving data manipulation problems.

Performance is an issue on very large datasets, and for that it is hard to beat solutions based on data.table. If you only deal with medium-sized datasets or smaller, however, taking the time to learn data.table is likely not worth the effort. dplyr can also be fast, so it is a good choice if you want to speed things up, but don't quite need the scalability of data.table.

Many of the other solutions below do not require any additional packages. Some of them are even fairly fast on medium-large datasets. Their primary disadvantage is either one of metaphor or of flexibility. By metaphor I mean that it is a tool designed for something else being coerced to solve this particular type of problem in a 'clever' way. By flexibility I mean they lack the ability to solve as wide a range of similar problems or to easily produce tidy output.


Examples

base functions

tapply:

tapply(df$speed, df$dive, mean)
#     dive1     dive2 
# 0.5419921 0.5103974

aggregate:

aggregate takes in data.frames, outputs data.frames, and uses a formula interface.

aggregate( speed ~ dive, df, mean )
#    dive     speed
# 1 dive1 0.5790946
# 2 dive2 0.4864489

by:

In its most user-friendly form, it takes in vectors and applies a function to them. However, its output is not in a very manipulable form.:

res.by <- by(df$speed, df$dive, mean)
res.by
# df$dive: dive1
# [1] 0.5790946
# ---------------------------------------
# df$dive: dive2
# [1] 0.4864489

To get around this, for simple uses of by the as.data.frame method in the taRifx library works:

library(taRifx)
as.data.frame(res.by)
#    IDX1     value
# 1 dive1 0.6736807
# 2 dive2 0.4051447

split:

As the name suggests, it performs only the "split" part of the split-apply-combine strategy. To make the rest work, I'll write a small function that uses sapply for apply-combine. sapply automatically simplifies the result as much as possible. In our case, that means a vector rather than a data.frame, since we've got only 1 dimension of results.

splitmean <- function(df) {
  s <- split( df, df$dive)
  sapply( s, function(x) mean(x$speed) )
}
splitmean(df)
#     dive1     dive2 
# 0.5790946 0.4864489 

External packages

data.table:

library(data.table)
setDT(df)[ , .(mean_speed = mean(speed)), by = dive]
#    dive mean_speed
# 1: dive1  0.5419921
# 2: dive2  0.5103974

dplyr:

library(dplyr)
group_by(df, dive) %>% summarize(m = mean(speed))

plyr (the pre-cursor of dplyr)

Here's what the official page has to say about plyr:

It’s already possible to do this with base R functions (like split and the apply family of functions), but plyr makes it all a bit easier with:

  • totally consistent names, arguments and outputs
  • convenient parallelisation through the foreach package
  • input from and output to data.frames, matrices and lists
  • progress bars to keep track of long running operations
  • built-in error recovery, and informative error messages
  • labels that are maintained across all transformations

In other words, if you learn one tool for split-apply-combine manipulation it should be plyr.

library(plyr)
res.plyr <- ddply( df, .(dive), function(x) mean(x$speed) )
res.plyr
#    dive        V1
# 1 dive1 0.5790946
# 2 dive2 0.4864489

reshape2:

The reshape2 library is not designed with split-apply-combine as its primary focus. Instead, it uses a two-part melt/cast strategy to perform a wide variety of data reshaping tasks. However, since it allows an aggregation function it can be used for this problem. It would not be my first choice for split-apply-combine operations, but its reshaping capabilities are powerful and thus you should learn this package as well.

library(reshape2)
dcast( melt(df), variable ~ dive, mean)
# Using dive as id variables
#   variable     dive1     dive2
# 1    speed 0.5790946 0.4864489

Benchmarks

10 rows, 2 groups

library(microbenchmark)
m1 <- microbenchmark(
  by( df$speed, df$dive, mean),
  aggregate( speed ~ dive, df, mean ),
  splitmean(df),
  ddply( df, .(dive), function(x) mean(x$speed) ),
  dcast( melt(df), variable ~ dive, mean),
  dt[, mean(speed), by = dive],
  summarize( group_by(df, dive), m = mean(speed) ),
  summarize( group_by(dt, dive), m = mean(speed) )
)

> print(m1, signif = 3)
Unit: microseconds
                                           expr  min   lq   mean median   uq  max neval      cld
                    by(df$speed, df$dive, mean)  302  325  343.9    342  362  396   100  b      
              aggregate(speed ~ dive, df, mean)  904  966 1012.1   1020 1060 1130   100     e   
                                  splitmean(df)  191  206  249.9    220  232 1670   100 a       
  ddply(df, .(dive), function(x) mean(x$speed)) 1220 1310 1358.1   1340 1380 2740   100      f  
         dcast(melt(df), variable ~ dive, mean) 2150 2330 2440.7   2430 2490 4010   100        h
                   dt[, mean(speed), by = dive]  599  629  667.1    659  704  771   100   c     
 summarize(group_by(df, dive), m = mean(speed))  663  710  774.6    744  782 2140   100    d    
 summarize(group_by(dt, dive), m = mean(speed)) 1860 1960 2051.0   2020 2090 3430   100       g 

autoplot(m1)

benchmark 10 rows

As usual, data.table has a little more overhead so comes in about average for small datasets. These are microseconds, though, so the differences are trivial. Any of the approaches works fine here, and you should choose based on:

  • What you're already familiar with or want to be familiar with (plyr is always worth learning for its flexibility; data.table is worth learning if you plan to analyze huge datasets; by and aggregate and split are all base R functions and thus universally available)
  • What output it returns (numeric, data.frame, or data.table -- the latter of which inherits from data.frame)

10 million rows, 10 groups

But what if we have a big dataset? Let's try 10^7 rows split over ten groups.

df <- data.frame(dive=factor(sample(letters[1:10],10^7,replace=TRUE)),speed=runif(10^7))
dt <- data.table(df)
setkey(dt,dive)

m2 <- microbenchmark(
  by( df$speed, df$dive, mean),
  aggregate( speed ~ dive, df, mean ),
  splitmean(df),
  ddply( df, .(dive), function(x) mean(x$speed) ),
  dcast( melt(df), variable ~ dive, mean),
  dt[,mean(speed),by=dive],
  times=2
)

> print(m2, signif = 3)
Unit: milliseconds
                                           expr   min    lq    mean median    uq   max neval      cld
                    by(df$speed, df$dive, mean)   720   770   799.1    791   816   958   100    d    
              aggregate(speed ~ dive, df, mean) 10900 11000 11027.0  11000 11100 11300   100        h
                                  splitmean(df)   974  1040  1074.1   1060  1100  1280   100     e   
  ddply(df, .(dive), function(x) mean(x$speed))  1050  1080  1110.4   1100  1130  1260   100      f  
         dcast(melt(df), variable ~ dive, mean)  2360  2450  2492.8   2490  2520  2620   100       g 
                   dt[, mean(speed), by = dive]   119   120   126.2    120   122   212   100 a       
 summarize(group_by(df, dive), m = mean(speed))   517   521   531.0    522   532   620   100   c     
 summarize(group_by(dt, dive), m = mean(speed))   154   155   174.0    156   189   321   100  b      

autoplot(m2)

benchmark 1e7 rows, 10 groups

Then data.table or dplyr using operating on data.tables is clearly the way to go. Certain approaches (aggregate and dcast) are beginning to look very slow.

10 million rows, 1,000 groups

If you have more groups, the difference becomes more pronounced. With 1,000 groups and the same 10^7 rows:

df <- data.frame(dive=factor(sample(seq(1000),10^7,replace=TRUE)),speed=runif(10^7))
dt <- data.table(df)
setkey(dt,dive)

# then run the same microbenchmark as above
print(m3, signif = 3)
Unit: milliseconds
                                           expr   min    lq    mean median    uq   max neval    cld
                    by(df$speed, df$dive, mean)   776   791   816.2    810   828   925   100  b    
              aggregate(speed ~ dive, df, mean) 11200 11400 11460.2  11400 11500 12000   100      f
                                  splitmean(df)  5940  6450  7562.4   7470  8370 11200   100     e 
  ddply(df, .(dive), function(x) mean(x$speed))  1220  1250  1279.1   1280  1300  1440   100   c   
         dcast(melt(df), variable ~ dive, mean)  2110  2190  2267.8   2250  2290  2750   100    d  
                   dt[, mean(speed), by = dive]   110   111   113.5    111   113   143   100 a     
 summarize(group_by(df, dive), m = mean(speed))   625   630   637.1    633   644   701   100  b    
 summarize(group_by(dt, dive), m = mean(speed))   129   130   137.3    131   142   213   100 a     

autoplot(m3)

enter image description here

So data.table continues scaling well, and dplyr operating on a data.table also works well, with dplyr on data.frame close to an order of magnitude slower. The split/sapply strategy seems to scale poorly in the number of groups (meaning the split() is likely slow and the sapply is fast). by continues to be relatively efficient--at 5 seconds, it's definitely noticeable to the user but for a dataset this large still not unreasonable. Still, if you're routinely working with datasets of this size, data.table is clearly the way to go - 100% data.table for the best performance or dplyr with dplyr using data.table as a viable alternative.

how to return a char array from a function in C

Lazy notes in comments.

#include <stdio.h>
// for malloc
#include <stdlib.h>

// you need the prototype
char *substring(int i,int j,char *ch);


int main(void /* std compliance */)
{
  int i=0,j=2;
  char s[]="String";
  char *test;
  // s points to the first char, S
  // *s "is" the first char, S
  test=substring(i,j,s); // so s only is ok
  // if test == NULL, failed, give up
  printf("%s",test);
  free(test); // you should free it
  return 0;
}


char *substring(int i,int j,char *ch)
{
  int k=0;
  // avoid calc same things several time
  int n = j-i+1; 
  char *ch1;
  // you can omit casting - and sizeof(char) := 1
  ch1=malloc(n*sizeof(char));
  // if (!ch1) error...; return NULL;

  // any kind of check missing:
  // are i, j ok? 
  // is n > 0... ch[i] is "inside" the string?...
  while(k<n)
    {   
      ch1[k]=ch[i];
      i++;k++;
    }   

  return ch1;
}

How do I get a list of files in a directory in C++?

Here's an example in C on Linux. That's if, you're on Linux and don't mind doing this small bit in ANSI C.

#include <dirent.h>

DIR *dpdf;
struct dirent *epdf;

dpdf = opendir("./");
if (dpdf != NULL){
   while (epdf = readdir(dpdf)){
      printf("Filename: %s",epdf->d_name);
      // std::cout << epdf->d_name << std::endl;
   }
}
closedir(dpdf);

Text not wrapping in p tag

Adding width: 100%; to the offending p element solved the problem for me. I don't know why it works.

Multiple conditions in if statement shell script

You are trying to compare strings inside an arithmetic command (((...))). Use [[ instead.

if [[ $username == "$username1" && $password == "$password1" ]] ||
   [[ $username == "$username2" && $password == "$password2" ]]; then

Note that I've reduced this to two separate tests joined by ||, with the && moved inside the tests. This is because the shell operators && and || have equal precedence and are simply evaluated from left to right. As a result, it's not generally true that a && b || c && d is equivalent to the intended ( a && b ) || ( c && d ).

What does character set and collation mean exactly?

A character set is a subset of all written glyphs. A character encoding specifies how those characters are mapped to numeric values. Some character encodings, like UTF-8 and UTF-16, can encode any character in the Universal Character Set. Others, like US-ASCII or ISO-8859-1 can only encode a small subset, since they use 7 and 8 bits per character, respectively. Because many standards specify both a character set and a character encoding, the term "character set" is often substituted freely for "character encoding".

A collation comprises rules that specify how characters can be compared for sorting. Collations rules can be locale-specific: the proper order of two characters varies from language to language.

Choosing a character set and collation comes down to whether your application is internationalized or not. If not, what locale are you targeting?

In order to choose what character set you want to support, you have to consider your application. If you are storing user-supplied input, it might be hard to foresee all the locales in which your software will eventually be used. To support them all, it might be best to support the UCS (Unicode) from the start. However, there is a cost to this; many western European characters will now require two bytes of storage per character instead of one.

Choosing the right collation can help performance if your database uses the collation to create an index, and later uses that index to provide sorted results. However, since collation rules are often locale-specific, that index will be worthless if you need to sort results according to the rules of another locale.

AttributeError: module 'cv2.cv2' has no attribute 'createLBPHFaceRecognizer'

I got openCV installed smoothly in my mac by:

$ brew install opencv
$ brew link --overwrite --dry-run opencv // to force linking
$ pip3 install opencv-contrib-python

I got it at windows 10 using:

c:\> pip3 install opencv-python
c:\> pip3 install opencv-contrib-python

Then I got it tested by

$ python3
Python 3.7.3 (default, Mar 27 2019, 09:23:15) 
[Clang 10.0.1 (clang-1001.0.46.3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv2
>>> cv2.__version__
'4.1.0'
>>> exit()

Proper way to use AJAX Post in jquery to pass model from strongly typed MVC3 view

This is the way it worked for me:

$.post("/Controller/Action", $("#form").serialize(), function(json) {       
        // handle response
}, "json");

[HttpPost]
public ActionResult TV(MyModel id)
{
    return Json(new { success = true });
}

Use RSA private key to generate public key?

In most software that generates RSA private keys, including openssl's, the private key is represented as a PKCS#1 RSAPrivatekey object or some variant thereof:

A.1.2 RSA private key syntax

An RSA private key should be represented with the ASN.1 type
RSAPrivateKey:

  RSAPrivateKey ::= SEQUENCE {
      version           Version,
      modulus           INTEGER,  -- n
      publicExponent    INTEGER,  -- e
      privateExponent   INTEGER,  -- d
      prime1            INTEGER,  -- p
      prime2            INTEGER,  -- q
      exponent1         INTEGER,  -- d mod (p-1)
      exponent2         INTEGER,  -- d mod (q-1)
      coefficient       INTEGER,  -- (inverse of q) mod p
      otherPrimeInfos   OtherPrimeInfos OPTIONAL
  }

As you can see, this format has a number of fields including the modulus and public exponent and thus is a strict superset of the information in an RSA public key.

How to delete large data of table in SQL without log?

  1. If you are Deleting All the rows in that table the simplest option is to Truncate table, something like

    TRUNCATE TABLE LargeTable
    GO
    

    Truncate table will simply empty the table, you cannot use WHERE clause to limit the rows being deleted and no triggers will be fired.

  2. On the other hand if you are deleting more than 80-90 Percent of the data, say if you have total of 11 Million rows and you want to delete 10 million another way would be to Insert these 1 million rows (records you want to keep) to another staging table. Truncate this Large table and Insert back these 1 Million rows.

  3. Or if permissions/views or other objects which has this large table as their underlying table doesnt get affected by dropping this table you can get these relatively small amount of the rows into another table drop this table and create another table with same schema and import these rows back into this ex-Large table.

  4. One last option I can think of is to change your database's Recovery Mode to SIMPLE and then delete rows in smaller batches using a while loop something like this..

    DECLARE @Deleted_Rows INT;
    SET @Deleted_Rows = 1;
    
    
    WHILE (@Deleted_Rows > 0)
      BEGIN
       -- Delete some small number of rows at a time
         DELETE TOP (10000)  LargeTable 
         WHERE readTime < dateadd(MONTH,-7,GETDATE())
    
      SET @Deleted_Rows = @@ROWCOUNT;
    END
    

and dont forget to change the Recovery mode back to full and I think you have to take a backup to make it fully affective (the change or recovery modes).

Excel: replace part of cell's string value

I know this is old but I had a similar need for this and I did not want to do the find and replace version. It turns out that you can nest the substitute method like so:

=SUBSTITUTE(SUBSTITUTE(F149, "a", " AM"), "p", " PM")

In my case, I am using excel to view a DBF file and however it was populated has times like this:

9:16a
2:22p

So I just made a new column and put that formula in it to convert it to the excel time format.

Set selected radio from radio group with a value

There is a better way of checking radios and checkbox; you have to pass an array of values to the val method instead of a raw value

Note: If you simply pass the value by itself (without being inside an array), that will result in all values of "mygroup" being set to the value.

$("input[name=mygroup]").val([5]);

Here is the jQuery doc that explains how it works: http://api.jquery.com/val/#val-value

And .val([...]) also works with form elements like <input type="checkbox">, <input type="radio">, and <option>s inside of a <select>.

The inputs and the options having a value that matches one of the elements of the array will be checked or selected, while those having a value that don't match one of the elements of the array will be unchecked or unselected

Fiddle demonstrating this working: https://jsfiddle.net/92nekvp3/

Flutter : Vertically center column

You control how a row or column aligns its children using the mainAxisAlignment and crossAxisAlignment properties. For a row, the main axis runs horizontally and the cross axis runs vertically. For a column, the main axis runs vertically and the cross axis runs horizontally.

 mainAxisAlignment: MainAxisAlignment.center,
 crossAxisAlignment: CrossAxisAlignment.center,

Convert a string to datetime in PowerShell

You need to specify the format it already has, in order to parse it:

$InvoiceDate = [datetime]::ParseExact($invoice, "dd-MMM-yy", $null)

Now you can output it in the format you need:

$InvoiceDate.ToString('yyyy-MM-dd')

or

'{0:yyyy-MM-dd}' -f $InvoiceDate

Using print statements only to debug

A simple way to do this is to call a logging function:

DEBUG = True

def log(s):
    if DEBUG:
        print s

log("hello world")

Then you can change the value of DEBUG and run your code with or without logging.

The standard logging module has a more elaborate mechanism for this.

java.lang.NoClassDefFoundError: com/sun/mail/util/MailLogger for JUnit test case for Java mail

The javax.mail-api artifact is only good for compiling against.

You actually need to run code, so you need a complete implementation of JavaMail API. Use this:

<dependency>
    <groupId>com.sun.mail</groupId>
    <artifactId>javax.mail</artifactId>
    <version>1.6.2</version>
</dependency>

NOTE: The version number will probably differ. Check the latest version here.

Boto3 Error: botocore.exceptions.NoCredentialsError: Unable to locate credentials

Create an S3 client object with your credentials

AWS_S3_CREDS = {
    "aws_access_key_id":"your access key", # os.getenv("AWS_ACCESS_KEY")
    "aws_secret_access_key":"your aws secret key" # os.getenv("AWS_SECRET_KEY")
}
s3_client = boto3.client('s3',**AWS_S3_CREDS)

It is always good to get credentials from os environment

To set Environment variables run the following commands in terminal

if linux or mac

$ export AWS_ACCESS_KEY="aws_access_key"
$ export AWS_SECRET_KEY="aws_secret_key"

if windows

c:System\> set AWS_ACCESS_KEY="aws_access_key"
c:System\> set AWS_SECRET_KEY="aws_secret_key"

Why doesn't height: 100% work to expand divs to the screen height?

Alternatively, if you use position: absolute then height: 100% will work just fine.

Filter Pyspark dataframe column with None value

None/Null is a data type of the class NoneType in pyspark/python so, Below will not work as you are trying to compare NoneType object with string object

Wrong way of filreting

df[df.dt_mvmt == None].count() 0 df[df.dt_mvmt != None].count() 0

correct

df=df.where(col("dt_mvmt").isNotNull()) returns all records with dt_mvmt as None/Null

Identifying Exception Type in a handler Catch Block

Alternatively:

var exception = err as Web2PDFException; 

if ( excecption != null ) 
{ 
     Web2PDFException wex = exception; 
     .... 
}

Difference between static memory allocation and dynamic memory allocation

Static memory allocation is allocated memory before execution pf program during compile time. Dynamic memory alocation is alocated memory during execution of program at run time.

displayname attribute vs display attribute

Perhaps this is specific to .net core, I found DisplayName would not work but Display(Name=...) does. This may save someone else the troubleshooting involved :)

//using statements
using System;
using System.ComponentModel.DataAnnotations;  //needed for Display annotation
using System.ComponentModel;  //needed for DisplayName annotation

public class Whatever
{
    //Property
    [Display(Name ="Release Date")]
    public DateTime ReleaseDate { get; set; }
}


//cshtml file
@Html.DisplayNameFor(model => model.ReleaseDate)

Copy table without copying data

Try

CREATE TABLE foo LIKE bar;

so the keys and indexes are copied over as, well.

Documentation

Regular expression to match balanced parentheses

The answer depends on whether you need to match matching sets of brackets, or merely the first open to the last close in the input text.

If you need to match matching nested brackets, then you need something more than regular expressions. - see @dehmann

If it's just first open to last close see @Zach

Decide what you want to happen with:

abc ( 123 ( foobar ) def ) xyz ) ghij

You need to decide what your code needs to match in this case.

Launch a shell command with in a python script, wait for the termination and return to the script

The os.exec*() functions replace the current programm with the new one. When this programm ends so does your process. You probably want os.system().

JavaScript: Global variables after Ajax requests

AJAX stands for Asynchronous JavaScript and XML. Thus, the post to the server happens out-of-sync with the rest of the function. Try some code like this instead (it just breaks the shorthand $.post out into the longer $.ajax call and adds the async option).

var it_works = false;

$.ajax({
  type: 'POST',
  async: false,
  url: "some_file.php",
  data: "",
  success: function() {it_works = true;}
});

alert(it_works);

Hope this helps!

Connect to sqlplus in a shell script and run SQL scripts

Wouldn't something akin to this be better, security-wise?:

sqlplus -s /nolog << EOF
CONNECT admin/password;

whenever sqlerror exit sql.sqlcode;
set echo off 
set heading off

@pl_script_1.sql
@pl_script_2.sql

exit;
EOF 

How correctly produce JSON by RESTful web service?

You can annotate your bean with jaxb annotations.

  @XmlRootElement
  public class MyJaxbBean {
    public String name;
    public int age;

    public MyJaxbBean() {} // JAXB needs this

    public MyJaxbBean(String name, int age) {
      this.name = name;
      this.age = age;
    }
  }

and then your method would look like this:

   @GET @Produces("application/json")
   public MyJaxbBean getMyBean() {
      return new MyJaxbBean("Agamemnon", 32);
   }

There is a chapter in the latest documentation that deals with this:

https://jersey.java.net/documentation/latest/user-guide.html#json

Remove array element based on object property

We can remove the element based on the property using the below 2 approaches.

  1. Using filter method
testArray.filter(prop => prop.key !== 'Test Value')
  1. Using splice method. For this method we need to find the index of the propery.
const index = testArray.findIndex(prop => prop.key === 'Test Value')
testArray.splice(index,1)

Bootstrap 3: Keep selected tab on page refresh

There is a solution after reloading the page and keeping the expected tab as selected.

Suppose after saving data the redirected url is : my_url#tab_2

Now through the following script your expected tab will remain selected.

$(document).ready(function(){
    var url = document.location.toString();
    if (url.match('#')) {
        $('.nav-tabs a[href="#' + url.split('#')[1] + '"]').tab('show');
        $('.nav-tabs a').removeClass('active');
    }
});

Nested classes' scope?

class Outer(object):
    outer_var = 1

    class Inner(object):
        @property
        def inner_var(self):
            return Outer.outer_var

This isn't quite the same as similar things work in other languages, and uses global lookup instead of scoping the access to outer_var. (If you change what object the name Outer is bound to, then this code will use that object the next time it is executed.)

If you instead want all Inner objects to have a reference to an Outer because outer_var is really an instance attribute:

class Outer(object):
    def __init__(self):
        self.outer_var = 1

    def get_inner(self):
        return self.Inner(self)
        # "self.Inner" is because Inner is a class attribute of this class
        # "Outer.Inner" would also work, or move Inner to global scope
        # and then just use "Inner"

    class Inner(object):
        def __init__(self, outer):
            self.outer = outer

        @property
        def inner_var(self):
            return self.outer.outer_var

Note that nesting classes is somewhat uncommon in Python, and doesn't automatically imply any sort of special relationship between the classes. You're better off not nesting. (You can still set a class attribute on Outer to Inner, if you want.)

Retain precision with double in Java

As others have noted, not all decimal values can be represented as binary since decimal is based on powers of 10 and binary is based on powers of two.

If precision matters, use BigDecimal, but if you just want friendly output:

System.out.printf("%.2f\n", total);

Will give you:

11.40

How to add an extra language input to Android?

I don't know about sliding the space bar. I have a small box on the left of my keyboard that indicates which language is selected ( when english is selected it shows the words EN with a small microphone on top. Being that I also have spanish as one of my languages, I just tap that button and it swithces back and forth from spanish to english.

Logical operators ("and", "or") in DOS batch

It's just as easy as the following:

AND> if+if

if "%VAR1%"=="VALUE" if "%VAR2%"=="VALUE" *do something*

OR> if // if

set BOTH=0
if "%VAR1%"=="VALUE" if "%VAR2%"=="VALUE" set BOTH=1
if "%BOTH%"=="0" if "%VAR1%"=="VALUE" *do something*
if "%BOTH%"=="0" if "%VAR2%"=="VALUE" *do something*

I know that there are other answers, but I think that the mine is more simple, so more easy to understand. Hope this helps you! ;)

Send email using java

Will this code work to send email?

Well, no, not without changing some parts since you're getting an error. You are currently trying to send mail via a SMTP server running on localhost but you aren't running any hence the ConnectException.

Assuming the code is OK (I didn't really check), you'll have to either run a local SMTP server, or to use a (remote) one (from your ISP).

Regarding the code, you can find samples in the JavaMail download package as mentioned in the FAQ:

Where can I find some example programs that show how to use JavaMail?

Q: Where can I find some example programs that show how to use JavaMail?
A: There are many example programs included in the JavaMail download package, including simple command line programs illustrating various aspects of the JavaMail API, a Swing-based GUI application, a simple servlet-based application, and a complete web application using JSP pages and a tag library.

Form Submission without page refresh

<script type="text/javascript">
    var frm = $('#myform');
    frm.submit(function (ev) {
        $.ajax({
            type: frm.attr('method'),
            url: frm.attr('action'),
            data: frm.serialize(),
            success: function (data) {
                alert('ok');
            }
        });

        ev.preventDefault();
    });
</script>

<form id="myform" action="/your_url" method="post">
    ...
</form>

In C#, why is String a reference type that behaves like a value type?

Not only strings are immutable reference types. Multi-cast delegates too. That is why it is safe to write

protected void OnMyEventHandler()
{
     delegate handler = this.MyEventHandler;
     if (null != handler)
     {
        handler(this, new EventArgs());
     }
}

I suppose that strings are immutable because this is the most safe method to work with them and allocate memory. Why they are not Value types? Previous authors are right about stack size etc. I would also add that making strings a reference types allow to save on assembly size when you use the same constant string in the program. If you define

string s1 = "my string";
//some code here
string s2 = "my string";

Chances are that both instances of "my string" constant will be allocated in your assembly only once.

If you would like to manage strings like usual reference type, put the string inside a new StringBuilder(string s). Or use MemoryStreams.

If you are to create a library, where you expect a huge strings to be passed in your functions, either define a parameter as a StringBuilder or as a Stream.

Align an element to bottom with flexbox

1. Style parent element: style="display:flex; flex-direction:column; flex:1;"

2. Style the element you want to stay at bottom: style="margin-top: auto;"

3. Done! Wow. That was easy.

Example:

enter image description here

<section style="display:flex; flex-wrap:wrap;"> // For demo, not necessary
    <div style="display:flex; flex-direction:column; flex:1;"> // Parent element
        <button style="margin-top: auto;"> I </button> // Target element
    </div>

    ... 5 more identical divs, for demo ...

</section>

Demo: https://codepen.io/ferittuncer/pen/YzygpWX

Drawing Isometric game worlds

Coobird's answer is the correct, complete one. However, I combined his hints with those from another site to create code that works in my app (iOS/Objective-C), which I wanted to share with anyone who comes here looking for such a thing. Please, if you like/up-vote this answer, do the same for the originals; all I did was "stand on the shoulders of giants."

As for sort-order, my technique is a modified painter's algorithm: each object has (a) an altitude of the base (I call "level") and (b) an X/Y for the "base" or "foot" of the image (examples: avatar's base is at his feet; tree's base is at it's roots; airplane's base is center-image, etc.) Then I just sort lowest to highest level, then lowest (highest on-screen) to highest base-Y, then lowest (left-most) to highest base-X. This renders the tiles the way one would expect.

Code to convert screen (point) to tile (cell) and back:

typedef struct ASIntCell {  // like CGPoint, but with int-s vice float-s
    int x;
    int y;
} ASIntCell;

// Cell-math helper here:
//      http://gamedevelopment.tutsplus.com/tutorials/creating-isometric-worlds-a-primer-for-game-developers--gamedev-6511
// Although we had to rotate the coordinates because...
// X increases NE (not SE)
// Y increases SE (not SW)
+ (ASIntCell) cellForPoint: (CGPoint) point
{
    const float halfHeight = rfcRowHeight / 2.;

    ASIntCell cell;
    cell.x = ((point.x / rfcColWidth) - ((point.y - halfHeight) / rfcRowHeight));
    cell.y = ((point.x / rfcColWidth) + ((point.y + halfHeight) / rfcRowHeight));

    return cell;
}


// Cell-math helper here:
//      http://stackoverflow.com/questions/892811/drawing-isometric-game-worlds/893063
// X increases NE,
// Y increases SE
+ (CGPoint) centerForCell: (ASIntCell) cell
{
    CGPoint result;

    result.x = (cell.x * rfcColWidth  / 2) + (cell.y * rfcColWidth  / 2);
    result.y = (cell.y * rfcRowHeight / 2) - (cell.x * rfcRowHeight / 2);

    return result;
}

Convert UTF-8 to base64 string

It's a little difficult to tell what you're trying to achieve, but assuming you're trying to get a Base64 string that when decoded is abcdef==, the following should work:

byte[] bytes = Encoding.UTF8.GetBytes("abcdef==");
string base64 = Convert.ToBase64String(bytes);
Console.WriteLine(base64);

This will output: YWJjZGVmPT0= which is abcdef== encoded in Base64.

Edit:

To decode a Base64 string, simply use Convert.FromBase64String(). E.g.

string base64 = "YWJjZGVmPT0=";
byte[] bytes = Convert.FromBase64String(base64);

At this point, bytes will be a byte[] (not a string). If we know that the byte array represents a string in UTF8, then it can be converted back to the string form using:

string str = Encoding.UTF8.GetString(bytes);
Console.WriteLine(str);

This will output the original input string, abcdef== in this case.

How to change string into QString?

Alternative way:

std::string s = "This is an STL string";
QString qs = QString::fromAscii(s.data(), s.size());

This has the advantage of not using .c_str() which might cause the std::string to copy itself in case there is no place to add the '\0' at the end.

Spark: subtract two DataFrames

For me , df1.subtract(df2) was inconsistent. Worked correctly on one dataframe but not on the other . That was because of duplicates . df1.exceptAll(df2) returns a new dataframe with the records from df1 that do not exist in df2 , including any duplicates.

Safari 3rd party cookie iframe trick no longer working?

This solution applies in some cases - if possible:

If the iframe content page uses a subdomain of the page containing the iframe, the cookie is no longer blocked.

How can I dismiss the on screen keyboard?

To dismiss the keyboard (1.7.8+hotfix.2 and above) just call the method below:

FocusScope.of(context).unfocus();

Once the FocusScope.of(context).unfocus() method already check if there is focus before dismiss the keyboard it's not needed to check it. But in case you need it just call another context method: FocusScope.of(context).hasPrimaryFocus

jquery $(window).height() is returning the document height

With no doctype tag, Chrome reports the same value for both calls.

Adding a strict doctype like <!DOCTYPE html> causes the values to work as advertised.

The doctype tag must be the very first thing in your document. E.g., you can't have any text before it, even if it doesn't render anything.

Converting map to struct

You can do it ... it may get a bit ugly and you'll be faced with some trial and error in terms of mapping types .. but heres the basic gist of it:

func FillStruct(data map[string]interface{}, result interface{}) {
    t := reflect.ValueOf(result).Elem()
    for k, v := range data {
        val := t.FieldByName(k)
        val.Set(reflect.ValueOf(v))
    }
}

Working sample: http://play.golang.org/p/PYHz63sbvL

What Does 'zoom' do in CSS?

This property controls the magnification level for the current element. The rendering effect for the element is that of a “zoom” function on a camera. Even though this property is not inherited, it still affects the rendering of child elements.

Example

 div { zoom: 200% }
 <div style=”zoom: 200%”>This is x2 text </div>

Pass variables to Ruby script via command line

Unless it is the most trivial case, there is only one sane way to use command line options in Ruby. It is called docopt and documented here.

What is amazing with it, is it's simplicity. All you have to do, is specify the "help" text for your command. What you write there will then be auto-parsed by the standalone (!) ruby library.

From the example:

#!/usr/bin/env ruby
require 'docopt.rb'

doc = <<DOCOPT
Usage: #{__FILE__} --help
       #{__FILE__} -v...
       #{__FILE__} go [go]
       #{__FILE__} (--path=<path>)...
       #{__FILE__} <file> <file>

Try: #{__FILE__} -vvvvvvvvvv
     #{__FILE__} go go
     #{__FILE__} --path ./here --path ./there
     #{__FILE__} this.txt that.txt

DOCOPT

begin
  require "pp"
  pp Docopt::docopt(doc)
rescue Docopt::Exit => e
  puts e.message
end

The output:

$ ./counted_example.rb -h
Usage: ./counted_example.rb --help
       ./counted_example.rb -v...
       ./counted_example.rb go [go]
       ./counted_example.rb (--path=<path>)...
       ./counted_example.rb <file> <file>

Try: ./counted_example.rb -vvvvvvvvvv
     ./counted_example.rb go go
     ./counted_example.rb --path ./here --path ./there
     ./counted_example.rb this.txt that.txt

$ ./counted_example.rb something else
{"--help"=>false,
 "-v"=>0,
 "go"=>0,
 "--path"=>[],
 "<file>"=>["something", "else"]}

$ ./counted_example.rb -v
{"--help"=>false, "-v"=>1, "go"=>0, "--path"=>[], "<file>"=>[]}

$ ./counted_example.rb go go
{"--help"=>false, "-v"=>0, "go"=>2, "--path"=>[], "<file>"=>[]}

Enjoy!

postgres, ubuntu how to restart service on startup? get stuck on clustering after instance reboot

ENABLE is what you are looking for

USAGE: type this command once and then you are good to go. Your service will start automaticaly at boot up

 sudo systemctl enable postgresql

DISABLE exists as well ofc

Some DOC: freedesktop man systemctl

How to parse a JSON string into JsonNode in Jackson?

Richard's answer is correct. Alternatively you can also create a MappingJsonFactory (in org.codehaus.jackson.map) which knows where to find ObjectMapper. The error you got was because the regular JsonFactory (from core package) has no dependency to ObjectMapper (which is in the mapper package).

But usually you just use ObjectMapper and do not worry about JsonParser or other low level components -- they will just be needed if you want to data-bind parts of stream, or do low-level handling.

How to insert tab character when expandtab option is on in Vim

You can disable expandtab option from within Vim as below:

:set expandtab!

or

:set noet

PS: And set it back when you are done with inserting tab, with "set expandtab" or "set et"

PS: If you have tab set equivalent to 4 spaces in .vimrc (softtabstop), you may also like to set it to 8 spaces in order to be able to insert a tab by pressing tab key once instead of twice (set softtabstop=8).

Bash script processing limited number of commands in parallel

In fact, xargs can run commands in parallel for you. There is a special -P max_procs command-line option for that. See man xargs.

ETag vs Header Expires

Etag and Last-modified headers are validators.

They help the browser and/or the cache (reverse proxy) to understand if a file/page, has changed, even if it preserves the same name.

Expires and Cache-control are giving refresh information.

This means that they inform, the browser and the reverse in-between proxies, up to what time or for how long, they may keep the page/file at their cache.

So the question usually is which one validator to use, etag or last-modified, and which refresh infomation header to use, expires or cache-control.

Android error while retrieving information from server 'RPC:s-5:AEC-0' in Google Play?

  1. Enter into SETTING
  2. Choose"Apps" & All
  3. Select Google Services Framework
  4. Clear data
  5. Force stop
  6. Go to Apps and download without error

Module 'tensorflow' has no attribute 'contrib'

tf.contrib has moved out of TF starting TF 2.0 alpha.
Take a look at these tf 2.0 release notes https://github.com/tensorflow/tensorflow/releases/tag/v2.0.0-alpha0
You can upgrade your TF 1.x code to TF 2.x using the tf_upgrade_v2 script https://www.tensorflow.org/alpha/guide/upgrade

Can't pickle <type 'instancemethod'> when using multiprocessing Pool.map()

A potentially trivial solution to this is to switch to using multiprocessing.dummy. This is a thread based implementation of the multiprocessing interface that doesn't seem to have this problem in Python 2.7. I don't have a lot of experience here, but this quick import change allowed me to call apply_async on a class method.

A few good resources on multiprocessing.dummy:

https://docs.python.org/2/library/multiprocessing.html#module-multiprocessing.dummy

http://chriskiehl.com/article/parallelism-in-one-line/

NPM doesn't install module dependencies

Just in case anyone is suffering from this predicament and happens to make the same asanine mistake that I did, here is what it was in my case. After banging my head against the wall for an hour, I realized that I had my json incorrectly nested, and the key "dependencies" was inside of the key "repository".
Needless to say, no errors were evident, and no modules were installed.

Validate select box

For starters, you can "disable" the option from being selected accidentally by users:

<option value="" disabled="disabled">Choose an option</option>

Then, inside your JavaScript event (doesn't matter whether it is jQuery or JavaScript), for your form to validate whether it is set, do:

select = document.getElementById('select'); // or in jQuery use: select = this;
if (select.value) {
  // value is set to a valid option, so submit form
  return true;
}
return false;

Or something to that effect.

Keystore change passwords

If the keystore contains other key-entries with different password you have to change them also or you can isolate your key to different keystore using below command,

keytool -importkeystore  -srckeystore mystore.jck -destkeystore myotherstore.jks -srcstoretype jceks
-deststoretype jks -srcstorepass mystorepass -deststorepass myotherstorepass -srcalias myserverkey
-destalias myotherserverkey -srckeypass mykeypass -destkeypass myotherkeypass

How to print a date in a regular format?

You can do:

mylist.append(str(today))

How do files get into the External Dependencies in Visual Studio C++?

To resolve external dependencies within project. below things are important..
1. The compiler should know that where are header '.h' files located in workspace.
2. The linker able to find all specified  all '.lib' files & there names for current project.

So, Developer has to specify external dependencies for Project as below..

1. Select Project in Solution explorer.

2 . Project Properties -> Configuration Properties -> C/C++ -> General
specify all header files in "Additional Include Directories".

3.  Project Properties -> Configuration Properties -> Linker -> General
specify relative path for all lib files in "Additional Library Directories".

enter image description here enter image description here

Making macOS Installer Packages which are Developer ID ready

FYI for those that are trying to create a package installer for a bundle or plugin, it's easy:

pkgbuild --component "Color Lists.colorPicker" --install-location ~/Library/ColorPickers ColorLists.pkg

Access Controller method from another controller in Laravel 5

  1. Well, of course, you can instantiate the other controller and call the method you want. Probably it's not a good practice but I don't know why:
$otherController = new OtherController();
$otherController->methodFromOtherController($param1, $param2 ...);
  1. But, doing this, you will have a problem: the other method returns something like response()->json($result), and is not it what you want.

  2. To resolve this problem, define the first parameter of the other controller's method as:

public function methodFromOtherController(Request $request = null, ...
  1. When you call methodFromOtherController from the main controller, you will pass null as first parameter value:
$otherController = new OtherController();
$otherController->methodFromOtherController(null, $param1, $param2 ...);
  1. Finally, create a condition at the end of the methodFromOtherController method:
public function methodFromOtherController(Request $request = null, ...) 
{
  ...
  if (is_null($request)) {
    return $result;
  } else {
    return response()->json($result);
  }
}
  1. Once Laravel you ever set $request when it is called by direct route, you can differentiate each situation and return a correspondent value.

Build tree array from flat array in javascript

Here is a modified version of Steven Harris' that is plain ES5 and returns an object keyed on the id rather than returning an array of nodes at both the top level and for the children.

unflattenToObject = function(array, parent) {
  var tree = {};
  parent = typeof parent !== 'undefined' ? parent : {id: 0};

  var childrenArray = array.filter(function(child) {
    return child.parentid == parent.id;
  });

  if (childrenArray.length > 0) {
    var childrenObject = {};
    // Transform children into a hash/object keyed on token
    childrenArray.forEach(function(child) {
      childrenObject[child.id] = child;
    });
    if (parent.id == 0) {
      tree = childrenObject;
    } else {
      parent['children'] = childrenObject;
    }
    childrenArray.forEach(function(child) {
      unflattenToObject(array, child);
    })
  }

  return tree;
};

var arr = [
    {'id':1 ,'parentid': 0},
    {'id':2 ,'parentid': 1},
    {'id':3 ,'parentid': 1},
    {'id':4 ,'parentid': 2},
    {'id':5 ,'parentid': 0},
    {'id':6 ,'parentid': 0},
    {'id':7 ,'parentid': 4}
];
tree = unflattenToObject(arr);

$(window).height() vs $(document).height

$(document).height:if your device height was bigger. Your page has Not any scroll;

$(document).height: assume you have not scroll and return this height;

$(window).height: return your page height on your device.

Only allow specific characters in textbox

For your validation event IMO the easiest method would be to use a character array to validate textbox characters against. True - iterating and validating isn't particularly efficient, but it is straightforward.

Alternately, use a regular expression of your whitelist characters against the input string. Your events are availalbe at MSDN here: http://msdn.microsoft.com/en-us/library/system.windows.forms.control.lostfocus.aspx

How to hide scrollbar in Firefox?

For webkit use following:

::-webkit-scrollbar {
    width: 0px;  /* remove scrollbar space */
    background: transparent;  /* optional: just make scrollbar invisible */
}

For Mozilla Firefox use following code:

@-moz-document url-prefix() {
    html,body{overflow: hidden !important;}
}

and if scrolling does not work then add

element {overflow-y: scroll;}

to specific element

How can I remove all objects but one from the workspace in R?

Using the keep function from the gdata package is quite convenient.

> ls()
[1] "a" "b" "c"

library(gdata)
> keep(a) #shows you which variables will be removed
[1] "b" "c"
> keep(a, sure = TRUE) # setting sure to TRUE removes variables b and c
> ls()
[1] "a"

Java time-based map/cache with expiring keys

This is a sample implementation that i did for the same requirement and concurrency works well. Might be useful for someone.

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 
 * @author Vivekananthan M
 *
 * @param <K>
 * @param <V>
 */
public class WeakConcurrentHashMap<K, V> extends ConcurrentHashMap<K, V> {

    private static final long serialVersionUID = 1L;

    private Map<K, Long> timeMap = new ConcurrentHashMap<K, Long>();
    private long expiryInMillis = 1000;
    private static final SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss:SSS");

    public WeakConcurrentHashMap() {
        initialize();
    }

    public WeakConcurrentHashMap(long expiryInMillis) {
        this.expiryInMillis = expiryInMillis;
        initialize();
    }

    void initialize() {
        new CleanerThread().start();
    }

    @Override
    public V put(K key, V value) {
        Date date = new Date();
        timeMap.put(key, date.getTime());
        System.out.println("Inserting : " + sdf.format(date) + " : " + key + " : " + value);
        V returnVal = super.put(key, value);
        return returnVal;
    }

    @Override
    public void putAll(Map<? extends K, ? extends V> m) {
        for (K key : m.keySet()) {
            put(key, m.get(key));
        }
    }

    @Override
    public V putIfAbsent(K key, V value) {
        if (!containsKey(key))
            return put(key, value);
        else
            return get(key);
    }

    class CleanerThread extends Thread {
        @Override
        public void run() {
            System.out.println("Initiating Cleaner Thread..");
            while (true) {
                cleanMap();
                try {
                    Thread.sleep(expiryInMillis / 2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        private void cleanMap() {
            long currentTime = new Date().getTime();
            for (K key : timeMap.keySet()) {
                if (currentTime > (timeMap.get(key) + expiryInMillis)) {
                    V value = remove(key);
                    timeMap.remove(key);
                    System.out.println("Removing : " + sdf.format(new Date()) + " : " + key + " : " + value);
                }
            }
        }
    }
}


Git Repo Link (With Listener Implementation)

https://github.com/vivekjustthink/WeakConcurrentHashMap

Cheers!!

How to create a link for all mobile devices that opens google maps with a route starting at the current location, destinating a given place?

if (navigator.geolocation) { //Checks if browser supports geolocation
navigator.geolocation.getCurrentPosition(function (position) {                                                                                            
 var latitude = position.coords.latitude;                    //users current
 var longitude = position.coords.longitude;                 //location
 var coords = new google.maps.LatLng(latitude, longitude); //Creates variable for map coordinates
 var directionsService = new google.maps.DirectionsService();
 var directionsDisplay = new google.maps.DirectionsRenderer();
 var mapOptions = //Sets map options
 {
   zoom: 15,  //Sets zoom level (0-21)
   center: coords, //zoom in on users location
   mapTypeControl: true, //allows you to select map type eg. map or satellite
   navigationControlOptions:
   {
     style: google.maps.NavigationControlStyle.SMALL //sets map controls size eg. zoom
   },
   mapTypeId: google.maps.MapTypeId.ROADMAP //sets type of map Options:ROADMAP, SATELLITE, HYBRID, TERRIAN
 };
 map = new google.maps.Map( /*creates Map variable*/ document.getElementById("map"),    mapOptions /*Creates a new map using the passed optional parameters in the mapOptions parameter.*/);
 directionsDisplay.setMap(map);
 directionsDisplay.setPanel(document.getElementById('panel'));
 var request = {
   origin: coords,
   destination: 'BT42 1FL',
   travelMode: google.maps.DirectionsTravelMode.DRIVING
 };

 directionsService.route(request, function (response, status) {
   if (status == google.maps.DirectionsStatus.OK) {
     directionsDisplay.setDirections(response);
   }
 });
 });
 }

How to identify object types in java

You can compare class tokens to each other, so you could use value.getClass() == Integer.class. However, the simpler and more canonical way is to use instanceof :

    if (value instanceof Integer) {
        System.out.println("This is an Integer");
    } else if(value instanceof String) {
        System.out.println("This is a String");
    } else if(value instanceof Float) {
        System.out.println("This is a Float");
    }

Notes:

  • the only difference between the two is that comparing class tokens detects exact matches only, while instanceof C matches for subclasses of C too. However, in this case all the classes listed are final, so they have no subclasses. Thus instanceof is probably fine here.
  • as JB Nizet stated, such checks are not OO design. You may be able to solve this problem in a more OO way, e.g.

    System.out.println("This is a(n) " + value.getClass().getSimpleName());
    

SSRS expression to format two decimal places does not show zeros

Format(Fields!CUL1.Value, "0.00") would work better since @abe suggests they want to show 0.00 , and if the value was 0, "#0.##" would show "0".

Run bash script as daemon

A Daemon is just program that runs as a background process, rather than being under the direct control of an interactive user...

[The below bash code is for Debian systems - Ubuntu, Linux Mint distros and so on]

The simple way:

The simple way would be to edit your /etc/rc.local file and then just have your script run from there (i.e. everytime you boot up the system):

sudo nano /etc/rc.local

Add the following and save:

#For a BASH script
/bin/sh TheNameOfYourScript.sh > /dev/null &

The better way to do this would be to create a Daemon via Upstart:

sudo nano /etc/init/TheNameOfYourDaemon.conf

add the following:

description "My Daemon Job"
author "Your Name"
start on runlevel [2345]    

pre-start script
  echo "[`date`] My Daemon Starting" >> /var/log/TheNameOfYourDaemonJobLog.log
end script

exec /bin/sh TheNameOfYourScript.sh > /dev/null &

Save this.

Confirm that it looks ok:

init-checkconf /etc/init/TheNameOfYourDaemon.conf

Now reboot the machine:

sudo reboot

Now when you boot up your system, you can see the log file stating that your Daemon is running:

cat  /var/log/TheNameOfYourDaemonJobLog.log

• Now you may start/stop/restart/get the status of your Daemon via:

restart: this will stop, then start a service

sudo service TheNameOfYourDaemonrestart restart

start: this will start a service, if it's not running

sudo service TheNameOfYourDaemonstart start

stop: this will stop a service, if it's running

sudo service TheNameOfYourDaemonstop stop

status: this will display the status of a service

sudo service TheNameOfYourDaemonstatus status

How to load CSS Asynchronously

If you have a strict content security policy that doesn't allow @vladimir-salguero's answer, you can use this (please make note of the script nonce):

<script nonce="(your nonce)" async>
$(document).ready(function() {
    $('link[media="none"]').each(function(a, t) {
        var n = $(this).attr("data-async"),
            i = $(this);
        void 0 !== n && !1 !== n && ("true" == n || n) && i.attr("media", "all")
    })
});
</script>

Just add the following to your stylesheet reference: media="none" data-async="true". Here's an example:

<link rel="stylesheet" href="../path/script.js" media="none" data-async="true" />

Example for jQuery:

<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css" type="text/css" media="none" data-async="true" crossorigin="anonymous" /><noscript><link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css" type="text/css" /></noscript>

Extract MSI from EXE

The only way to do that is running the exe and collect the MSI. The thing you must take care of is that if you are tranforming the MSI using MST they might get lost.

I use this batch commandline:

SET TMP=c:\msipath

MD "%TMP%"

SET TEMP=%TMP%

start /d "c:\install" install.exe /L1033

PING 1.1.1.1 -n 1 -w 10000 >NUL

for /R "%TMP%" %%f in (*.msi) do copy "%%f" "%TMP%"

taskkill /F /IM msiexec.exe /T

php error: Class 'Imagick' not found

Debian 9

I just did the following and everything else needed got automatically installed as well.

sudo apt-get -y -f install php-imagick
sudo /etc/init.d/apache2 restart

Map implementation with duplicate keys

You could simply pass an array of values for the value in a regular HashMap, thus simulating duplicate keys, and it would be up to you to decide what data to use.

You may also just use a MultiMap, although I do not like the idea of duplicate keys myself.

How to un-commit last un-pushed git commit without losing the changes

For the case: "This has not been pushed, only committed." - if you use IntelliJ (or another JetBrains IDE) and you haven't pushed changes yet you can do next.

  1. Go to Version control window (Alt + 9/Command + 9) - "Log" tab.
  2. Right-click on a commit before your last one.
  3. Reset current branch to here
  4. pick Soft (!!!)
  5. push the Reset button in the bottom of the dialog window.

Done.

This will "uncommit" your changes and return your git status to the point before your last local commit. You will not lose any changes you made.

Why is my toFixed() function not working?

I tried function toFixed(2) many times. Every time console shows "toFixed() is not a function".

but how I resolved is By using Math.round()

eg:

if ($(this).attr('name') == 'time') {
    var value = parseFloat($(this).val());
    value = Math.round(value*100)/100; // 10 defines 1 decimals, 100 for 2, 1000 for 3
    alert(value);
}

this thing surely works for me and it might help you guys too...

How to use the switch statement in R functions?

Well, switch probably wasn't really meant to work like this, but you can:

AA = 'foo'
switch(AA, 
foo={
  # case 'foo' here...
  print('foo')
},
bar={
  # case 'bar' here...
  print('bar')    
},
{
   print('default')
}
)

...each case is an expression - usually just a simple thing, but here I use a curly-block so that you can stuff whatever code you want in there...

How to make a hyperlink in telegram without using bots?

In telegram desktop, use this hotkey: ctrl+K

In android:

  1. type your text
  2. select it
  3. and click on Create Link from its options

You can see these steps in this image: link creation in telegram android

How to have the formatter wrap code with IntelliJ?

Do you mean that the formatter does not break long lines? Check Settings / Project Settings / Code Style / Wrapping.

Update: in later versions of IntelliJ, the option is under Settings / Editor / Code Style. And select Wrap when typing reaches right margin.

How to remove undefined and null values from an object using lodash?

To complete the other answers, in lodash 4 to ignore only undefined and null (And not properties like false) you can use a predicate in _.pickBy:

_.pickBy(obj, v !== null && v !== undefined)

Example below :

_x000D_
_x000D_
const obj = { a: undefined, b: 123, c: true, d: false, e: null};_x000D_
_x000D_
const filteredObject = _.pickBy(obj, v => v !== null && v !== undefined);_x000D_
_x000D_
console.log = (obj) => document.write(JSON.stringify(filteredObject, null, 2));_x000D_
console.log(filteredObject);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.js"></script>
_x000D_
_x000D_
_x000D_

Arrays vs Vectors: Introductory Similarities and Differences

I'll add that arrays are very low-level constructs in C++ and you should try to stay away from them as much as possible when "learning the ropes" -- even Bjarne Stroustrup recommends this (he's the designer of C++).

Vectors come very close to the same performance as arrays, but with a great many conveniences and safety features. You'll probably start using arrays when interfacing with API's that deal with raw arrays, or when building your own collections.

"The transaction log for database is full due to 'LOG_BACKUP'" in a shared host

Call your hosting company and either have them set up regular log backups or set the recovery model to simple. I'm sure you know what informs the choice, but I'll be explicit anyway. Set the recovery model to full if you need the ability to restore to an arbitrary point in time. Either way the database is misconfigured as is.

Load image from resources

    this.toolStrip1 = new System.Windows.Forms.ToolStrip();
    this.toolStrip1.Location = new System.Drawing.Point(0, 0);
    this.toolStrip1.Name = "toolStrip1";
    this.toolStrip1.Size = new System.Drawing.Size(444, 25);
    this.toolStrip1.TabIndex = 0;
    this.toolStrip1.Text = "toolStrip1";
    object O = global::WindowsFormsApplication1.Properties.Resources.ResourceManager.GetObject("best_robust_ghost");

    ToolStripButton btn = new ToolStripButton("m1");
    btn.DisplayStyle = ToolStripItemDisplayStyle.Image;
    btn.Image = (Image)O;
    this.toolStrip1.Items.Add(btn);

    this.Controls.Add(this.toolStrip1);

VS 2012: Scroll Solution Explorer to current file

If you need one-off sync with the solution pane, then there is new command "Sync with Active Document" (default shortcut: Ctrl+[, S). Explained here: Visual Studio 2012 New Features: Solution Explorer

why windows 7 task scheduler task fails with error 2147942667

I had the same problem, on Windows7.

I was getting error 2147942667 and a report of being unable to run c:\windows\system32\CMD.EXE. I tried with and without double quotes in the Script and Start-in and it made no difference. Then I tried replacing all path references to mapped network drives and with UNC references (\Server1\Sharexx\my_scripts\run_this.cmd) and that fixed it for me. Pat.

Regex to replace multiple spaces with a single space

Also a possibility:

str.replace( /\s+/g, ' ' )

How to remove gem from Ruby on Rails application?

If you're using Rails 3+, remove the gem from the Gemfile and run bundle install.

If you're using Rails 2, hopefully you've put the declaration in config/environment.rb. If so, removing it from there and running rake gems:install should do the trick.

JAX-RS — How to return JSON and HTTP status code together?

In case you want to change the status code because of an exception, with JAX-RS 2.0 you can implement an ExceptionMapper like this. This handles this kind of exception for the whole app.

@Provider
public class UnauthorizedExceptionMapper implements ExceptionMapper<EJBAccessException> {

    @Override
    public Response toResponse(EJBAccessException exception) {
        return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
    }

}

How can I check if a MySQL table exists with PHP?

Or you could use

show tables where Tables_in_{insert_db_name}='tablename';

How to check if a string in Python is in ASCII?

Your question is incorrect; the error you see is not a result of how you built python, but of a confusion between byte strings and unicode strings.

Byte strings (e.g. "foo", or 'bar', in python syntax) are sequences of octets; numbers from 0-255. Unicode strings (e.g. u"foo" or u'bar') are sequences of unicode code points; numbers from 0-1112064. But you appear to be interested in the character é, which (in your terminal) is a multi-byte sequence that represents a single character.

Instead of ord(u'é'), try this:

>>> [ord(x) for x in u'é']

That tells you which sequence of code points "é" represents. It may give you [233], or it may give you [101, 770].

Instead of chr() to reverse this, there is unichr():

>>> unichr(233)
u'\xe9'

This character may actually be represented either a single or multiple unicode "code points", which themselves represent either graphemes or characters. It's either "e with an acute accent (i.e., code point 233)", or "e" (code point 101), followed by "an acute accent on the previous character" (code point 770). So this exact same character may be presented as the Python data structure u'e\u0301' or u'\u00e9'.

Most of the time you shouldn't have to care about this, but it can become an issue if you are iterating over a unicode string, as iteration works by code point, not by decomposable character. In other words, len(u'e\u0301') == 2 and len(u'\u00e9') == 1. If this matters to you, you can convert between composed and decomposed forms by using unicodedata.normalize.

The Unicode Glossary can be a helpful guide to understanding some of these issues, by pointing how how each specific term refers to a different part of the representation of text, which is far more complicated than many programmers realize.

update query with join on two tables

this is Postgres UPDATE JOIN format:

UPDATE address 
SET cid = customers.id
FROM customers 
WHERE customers.id = address.id

Here's the other variations: http://mssql-to-postgresql.blogspot.com/2007/12/updates-in-postgresql-ms-sql-mysql.html

VBScript -- Using error handling

VBScript has no notion of throwing or catching exceptions, but the runtime provides a global Err object that contains the results of the last operation performed. You have to explicitly check whether the Err.Number property is non-zero after each operation.

On Error Resume Next

DoStep1

If Err.Number <> 0 Then
  WScript.Echo "Error in DoStep1: " & Err.Description
  Err.Clear
End If

DoStep2

If Err.Number <> 0 Then
  WScript.Echo "Error in DoStop2:" & Err.Description
  Err.Clear
End If

'If you no longer want to continue following an error after that block's completed,
'call this.
On Error Goto 0

The "On Error Goto [label]" syntax is supported by Visual Basic and Visual Basic for Applications (VBA), but VBScript doesn't support this language feature so you have to use On Error Resume Next as described above.

How to count down in for loop?

The range function in python has the syntax:

range(start, end, step)

It has the same syntax as python lists where the start is inclusive but the end is exclusive.

So if you want to count from 5 to 1, you would use range(5,0,-1) and if you wanted to count from last to posn you would use range(last, posn - 1, -1).

How do I find a list of Homebrew's installable packages?

brew help will show you the list of commands that are available.

brew list will show you the list of installed packages. You can also append formulae, for example brew list postgres will tell you of files installed by postgres (providing it is indeed installed).

brew search <search term> will list the possible packages that you can install. brew search post will return multiple packages that are available to install that have post in their name.

brew info <package name> will display some basic information about the package in question.

You can also search http://searchbrew.com or https://brewformulas.org (both sites do basically the same thing)

What is the difference between static func and class func in Swift?

From Swift2.0, Apple says:

"Always prefix type property requirements with the static keyword when you define them in a protocol. This rule pertains even though type property requirements can be prefixed with the class or static keyword when implemented by a class:"

Hibernate Criteria Query to get specific columns

You can map another entity based on this class (you should use entity-name in order to distinct the two) and the second one will be kind of dto (dont forget that dto has design issues ). you should define the second one as readonly and give it a good name in order to be clear that this is not a regular entity. by the way select only few columns is called projection , so google with it will be easier.

alternative - you can create named query with the list of fields that you need (you put them in the select ) or use criteria with projection

Python 2.7 getting user input and manipulating as string without quotations

If you want to use input instead of raw_input in python 2.x,then this trick will come handy

    if hasattr(__builtins__, 'raw_input'):
      input=raw_input

After which,

testVar = input("Ask user for something.")

will work just fine.

Switch statement: must default be the last case?

Chiming in with another example: This can be useful if "default" is an unexpected case, and you want to log the error but also do something sensible. Example from some of my own code:

  switch (style)
  {
  default:
    MSPUB_DEBUG_MSG(("Couldn't match dash style, using solid line.\n"));
  case SOLID:
    return Dash(0, RECT_DOT);
  case DASH_SYS:
  {
    Dash ret(shapeLineWidth, dotStyle);
    ret.m_dots.push_back(Dot(1, 3 * shapeLineWidth));
    return ret;
  }
  // more cases follow
  }

How do you update a DateTime field in T-SQL?

Using a DateTime parameter is the best way. However, if you still want to pass a DateTime as a string, then the CAST should not be necessary provided that a language agnostic format is used.

e.g.

Given a table created like :

create table t1 (id int, EndDate DATETIME)
insert t1 (id, EndDate) values (1, GETDATE())

The following should always work :

update t1 set EndDate = '20100525' where id = 1 -- YYYYMMDD is language agnostic

The following will work :

SET LANGUAGE us_english
update t1 set EndDate = '2010-05-25' where id = 1

However, this won't :

SET LANGUAGE british
update t1 set EndDate = '2010-05-25' where id = 1  

This is because 'YYYY-MM-DD' is not a language agnostic format (from SQL server's point of view) .

The ISO 'YYYY-MM-DDThh:mm:ss' format is also language agnostic, and useful when you need to pass a non-zero time.

More info : http://karaszi.com/the-ultimate-guide-to-the-datetime-datatypes

How Best to Compare Two Collections in Java and Act on Them?

For a set that small is generally not worth it to convert from an Array to a HashMap/set. In fact, you're probably best off keeping them in an array and then sorting them by key and iterating over both lists simultaneously to do the comparison.

jQuery event to trigger action when a div is made visible

my solution:

; (function ($) {
$.each([ "toggle", "show", "hide" ], function( i, name ) {
    var cssFn = $.fn[ name ];
    $.fn[ name ] = function( speed, easing, callback ) {
        if(speed == null || typeof speed === "boolean"){
            var ret=cssFn.apply( this, arguments )
            $.fn.triggerVisibleEvent.apply(this,arguments)
            return ret
        }else{
            var that=this
            var new_callback=function(){
                callback.call(this)
                $.fn.triggerVisibleEvent.apply(that,arguments)
            }
            var ret=this.animate( genFx( name, true ), speed, easing, new_callback )
            return ret
        }
    };
});

$.fn.triggerVisibleEvent=function(){
    this.each(function(){
        if($(this).is(':visible')){
            $(this).trigger('visible')
            $(this).find('[data-trigger-visible-event]').triggerVisibleEvent()
        }
    })
}
})(jQuery);

example usage:

if(!$info_center.is(':visible')){
    $info_center.attr('data-trigger-visible-event','true').one('visible',processMoreLessButton)
}else{
    processMoreLessButton()
}

function processMoreLessButton(){
//some logic
}

How to get URL parameters with Javascript?

function getURLParameter(name) {
  return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [null, ''])[1].replace(/\+/g, '%20')) || null;
}

So you can use:

myvar = getURLParameter('myvar');

How to pause javascript code execution for 2 seconds

This Link might be helpful for you.

Every time I've wanted a sleep in the middle of my function, I refactored to use a setTimeout().

C# Call a method in a new thread

Asynchronous version:

private async Task DoAsync()
{
    await Task.Run(async () =>
    {
        //Do something awaitable here
    });
}

Difference between == and === in JavaScript

=== and !== are strict comparison operators:

JavaScript has both strict and type-converting equality comparison. For strict equality the objects being compared must have the same type and:

  • Two strings are strictly equal when they have the same sequence of characters, same length, and same characters in corresponding positions.
  • Two numbers are strictly equal when they are numerically equal (have the same number value). NaN is not equal to anything, including NaN. Positive and negative zeros are equal to one another.
  • Two Boolean operands are strictly equal if both are true or both are false.
  • Two objects are strictly equal if they refer to the same Object.
  • Null and Undefined types are == (but not ===). [I.e. (Null==Undefined) is true but (Null===Undefined) is false]

Comparison Operators - MDC

API vs. Webservice

An API (Application Programming Interface) is the means by which third parties can write code that interfaces with other code. A Web Service is a type of API, one that almost always operates over HTTP (though some, like SOAP, can use alternate transports, like SMTP). The official W3C definition mentions that Web Services don't necessarily use HTTP, but this is almost always the case and is usually assumed unless mentioned otherwise.

For examples of web services specifically, see SOAP, REST, and XML-RPC. For an example of another type of API, one written in C for use on a local machine, see the Linux Kernel API.

As far as the protocol goes, a Web service API almost always uses HTTP (hence the Web part), and definitely involves communication over a network. APIs in general can use any means of communication they wish. The Linux kernel API, for example, uses Interrupts to invoke the system calls that comprise its API for calls from user space.

"code ." Not working in Command Line for Visual Studio Code on OSX/Mac

For code . to work in OSX terminal append code as described here https://code.visualstudio.com/Docs/setup but instead of to .bashrc, in OSX try .profile which is loaded at terminal session start.

How to sort alphabetically while ignoring case sensitive?

Here is an example to sort an array : Case-insensitive

import java.text.Collator;
import java.util.Arrays;

public class Main {
  public static void main(String args[]) {

    String[] myArray = new String[] { "A", "B", "b" };
    Arrays.sort(myArray, Collator.getInstance());

  System.out.println(Arrays.toString(myArray));

 }

}

/* Output:[A, b, B] */

Simple way to query connected USB devices info in Python?

If you just need the name of the device here is a little hack which i wrote in bash. To run it in python you need the following snippet. Just replace $1 and $2 with Bus number and Device number eg 001 or 002.

import os
os.system("lsusb | grep \"Bus $1 Device $2\" | sed 's/\// /' | awk '{for(i=7;i<=NF;++i)print $i}'")

Alternately you can save it as a bash script and run it from there too. Just save it as a bash script like foo.sh make it executable.

#!/bin/bash
myvar=$(lsusb | grep "Bus $1 Device $2" | sed 's/\// /' | awk '{for(i=7;i<=NF;++i)print $i}')
echo $myvar

Then call it in python script as

import os
os.system('foo.sh')

Automatically capture output of last command into a variable using Bash?

I think you might be able to hack out a solution that involves setting your shell to a script containing:

#!/bin/sh
bash | tee /var/log/bash.out.log

Then if you set $PROMPT_COMMAND to output a delimiter, you can write a helper function (maybe called _) that gets you the last chunk of that log, so you can use it like:

% find lots*of*files
...
% echo "$(_)"
... # same output, but doesn't run the command again

Maven version with a property

The version of the pom.xml should be valid

<groupId>com.amazonaws.lambda</groupId>
<artifactId>lambda</artifactId>
<version>2.2.4 SNAPSHOT</version>
<packaging>jar</packaging>

This version should not be like 2.2.4. etc

When should one use a spinlock instead of mutex?

Please also note that on certain environments and conditions (such as running on windows on dispatch level >= DISPATCH LEVEL), you cannot use mutex but rather spinlock. On unix - same thing.

Here is equivalent question on competitor stackexchange unix site: https://unix.stackexchange.com/questions/5107/why-are-spin-locks-good-choices-in-linux-kernel-design-instead-of-something-more

Info on dispatching on windows systems: http://download.microsoft.com/download/e/b/a/eba1050f-a31d-436b-9281-92cdfeae4b45/IRQL_thread.doc

Python: How would you save a simple settings/config file?

ConfigParser Basic example

The file can be loaded and used like this:

#!/usr/bin/env python

import ConfigParser
import io

# Load the configuration file
with open("config.yml") as f:
    sample_config = f.read()
config = ConfigParser.RawConfigParser(allow_no_value=True)
config.readfp(io.BytesIO(sample_config))

# List all contents
print("List all contents")
for section in config.sections():
    print("Section: %s" % section)
    for options in config.options(section):
        print("x %s:::%s:::%s" % (options,
                                  config.get(section, options),
                                  str(type(options))))

# Print some contents
print("\nPrint some contents")
print(config.get('other', 'use_anonymous'))  # Just get the value
print(config.getboolean('other', 'use_anonymous'))  # You know the datatype?

which outputs

List all contents
Section: mysql
x host:::localhost:::<type 'str'>
x user:::root:::<type 'str'>
x passwd:::my secret password:::<type 'str'>
x db:::write-math:::<type 'str'>
Section: other
x preprocessing_queue:::["preprocessing.scale_and_center",
"preprocessing.dot_reduction",
"preprocessing.connect_lines"]:::<type 'str'>
x use_anonymous:::yes:::<type 'str'>

Print some contents
yes
True

As you can see, you can use a standard data format that is easy to read and write. Methods like getboolean and getint allow you to get the datatype instead of a simple string.

Writing configuration

import os
configfile_name = "config.yaml"

# Check if there is already a configurtion file
if not os.path.isfile(configfile_name):
    # Create the configuration file as it doesn't exist yet
    cfgfile = open(configfile_name, 'w')

    # Add content to the file
    Config = ConfigParser.ConfigParser()
    Config.add_section('mysql')
    Config.set('mysql', 'host', 'localhost')
    Config.set('mysql', 'user', 'root')
    Config.set('mysql', 'passwd', 'my secret password')
    Config.set('mysql', 'db', 'write-math')
    Config.add_section('other')
    Config.set('other',
               'preprocessing_queue',
               ['preprocessing.scale_and_center',
                'preprocessing.dot_reduction',
                'preprocessing.connect_lines'])
    Config.set('other', 'use_anonymous', True)
    Config.write(cfgfile)
    cfgfile.close()

results in

[mysql]
host = localhost
user = root
passwd = my secret password
db = write-math

[other]
preprocessing_queue = ['preprocessing.scale_and_center', 'preprocessing.dot_reduction', 'preprocessing.connect_lines']
use_anonymous = True

XML Basic example

Seems not to be used at all for configuration files by the Python community. However, parsing / writing XML is easy and there are plenty of possibilities to do so with Python. One is BeautifulSoup:

from BeautifulSoup import BeautifulSoup

with open("config.xml") as f:
    content = f.read()

y = BeautifulSoup(content)
print(y.mysql.host.contents[0])
for tag in y.other.preprocessing_queue:
    print(tag)

where the config.xml might look like this

<config>
    <mysql>
        <host>localhost</host>
        <user>root</user>
        <passwd>my secret password</passwd>
        <db>write-math</db>
    </mysql>
    <other>
        <preprocessing_queue>
            <li>preprocessing.scale_and_center</li>
            <li>preprocessing.dot_reduction</li>
            <li>preprocessing.connect_lines</li>
        </preprocessing_queue>
        <use_anonymous value="true" />
    </other>
</config>

Set min-width either by content or 200px (whichever is greater) together with max-width

The problem is that flex: 1 sets flex-basis: 0. Instead, you need

.container .box {
  min-width: 200px;
  max-width: 400px;
  flex-basis: auto; /* default value */
  flex-grow: 1;
}

_x000D_
_x000D_
.container {_x000D_
  display: -webkit-flex;_x000D_
  display: flex;_x000D_
  -webkit-flex-wrap: wrap;_x000D_
  flex-wrap: wrap;_x000D_
}_x000D_
_x000D_
.container .box {_x000D_
  -webkit-flex-grow: 1;_x000D_
  flex-grow: 1;_x000D_
  min-width: 100px;_x000D_
  max-width: 400px;_x000D_
  height: 200px;_x000D_
  background-color: #fafa00;_x000D_
  overflow: hidden;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

powershell mouse move does not prevent idle mode

<# Stay Awake by Frank Poth 2019-04-16 #>

(Get-Host).UI.RawUI.WindowTitle = "Stay Awake"

[System.Console]::BufferWidth  = [System.Console]::WindowWidth  = 40
[System.Console]::BufferHeight = [System.Console]::WindowHeight = 10

$shell = New-Object -ComObject WScript.Shell

$start_time = Get-Date -UFormat %s <# Get the date in MS #>
$current_time = $start_time
$elapsed_time = 0

Write-Host "I am awake!"

Start-Sleep -Seconds 5

$count = 0

while($true) {

  $shell.sendkeys("{NUMLOCK}{NUMLOCK}") <# Fake some input! #>

  if ($count -eq 8) {

    $count = 0
    Clear-Host

  }

  if ($count -eq 0) {

    $current_time = Get-Date -UFormat %s
    $elapsed_time = $current_time - $start_time

    Write-Host "I've been awake for "([System.Math]::Round(($elapsed_time / 60), 2))" minutes!"

  } else { Write-Host "Must stay awake..." }

  $count ++

  Start-Sleep -Seconds 2.5

}

The part that matters is $shell.sendkeys("{NUMLOCK}{NUMLOCK}") This registers two presses on the numlock key and fools the shell into thinking input was entered. I wrote this today after searching through various scripts that didn't work for me. Hope it helps someone!

Set CSS property in Javascript?

<h1>Silence and Smile</h1>
<input  type="button"  value="Show Red"   onclick="document.getElementById('h1').style.color='Red'"/>
<input  type="button"  value="Show Green" onclick="document.getElementById('h1').style.color='Green'"/>

Writing a pandas DataFrame to CSV file

To delimit by a tab you can use the sep argument of to_csv:

df.to_csv(file_name, sep='\t')

To use a specific encoding (e.g. 'utf-8') use the encoding argument:

df.to_csv(file_name, sep='\t', encoding='utf-8')

get list of packages installed in Anaconda

To check if a specific package is installed:

conda list html5lib

which outputs something like this if installed:

# packages in environment at C:\ProgramData\Anaconda3:
#
# Name                    Version                   Build  Channel
html5lib                  1.0.1                    py37_0

or something like this if not installed:

# packages in environment at C:\ProgramData\Anaconda3:
#
# Name                    Version                   Build  Channel

you don't need to type the exact package name. Partial matches are supported:

conda list html

This outputs all installed packages containing 'html':

# packages in environment at C:\ProgramData\Anaconda3:
#
# Name                    Version                   Build  Channel
html5lib                  1.0.1                    py37_0
sphinxcontrib-htmlhelp    1.0.2                      py_0
sphinxcontrib-serializinghtml 1.1.3                      py_0

jQuery Datepicker onchange event issue

On jQueryUi 1.9 I've managed to get it to work through an additional data value and a combination of beforeShow and onSelect functions:

$( ".datepicker" ).datepicker({
    beforeShow: function( el ){
        // set the current value before showing the widget
        $(this).data('previous', $(el).val() );
    },

    onSelect: function( newText ){
        // compare the new value to the previous one
        if( $(this).data('previous') != newText ){
            // do whatever has to be done, e.g. log it to console
            console.log( 'changed to: ' + newText );
        }
    }
});

Works for me :)

How to make a button redirect to another page using jQuery or just Javascript

Use a link and style it like a button:

<a href="#page2" class="ui-btn ui-shadow ui-corner-all">Click this button</a>

Min/Max of dates in an array?

Same as apply, now with spread :

const maxDate = new Date(Math.max(...dates));

(could be a comment on best answer)

Random number generator only generating one random number

There are a lot of solutions, here one: if you want only number erase the letters and the method receives a random and the result length.

public String GenerateRandom(Random oRandom, int iLongitudPin)
{
    String sCharacters = "123456789ABCDEFGHIJKLMNPQRSTUVWXYZ123456789";
    int iLength = sCharacters.Length;
    char cCharacter;
    int iLongitudNuevaCadena = iLongitudPin; 
    String sRandomResult = "";
    for (int i = 0; i < iLongitudNuevaCadena; i++)
    {
        cCharacter = sCharacters[oRandom.Next(iLength)];
        sRandomResult += cCharacter.ToString();
    }
    return (sRandomResult);
}

Equation for testing if a point is inside a circle

In general, x and y must satisfy (x - center_x)^2 + (y - center_y)^2 < radius^2.

Please note that points that satisfy the above equation with < replaced by == are considered the points on the circle, and the points that satisfy the above equation with < replaced by > are considered the outside the circle.

How to merge multiple dicts with same key or different key?

If keys are nested:

d1 = { 'key1': { 'nkey1': 'x1' }, 'key2': { 'nkey2': 'y1' } } 
d2 = { 'key1': { 'nkey1': 'x2' }, 'key2': { 'nkey2': 'y2' } }
ds = [d1, d2]
d = {}
for k in d1.keys():
    for k2 in d1[k].keys():
        d.setdefault(k, {})
        d[k].setdefault(k2, [])
        d[k][k2] = tuple(d[k][k2] for d in ds)

yields:

{'key1': {'nkey1': ('x1', 'x2')}, 'key2': {'nkey2': ('y1', 'y2')}}

Format LocalDateTime with Timezone in Java8

The prefix "Local" in JSR-310 (aka java.time-package in Java-8) does not indicate that there is a timezone information in internal state of that class (here: LocalDateTime). Despite the often misleading name such classes like LocalDateTime or LocalTime have NO timezone information or offset.

You tried to format such a temporal type (which does not contain any offset) with offset information (indicated by pattern symbol Z). So the formatter tries to access an unavailable information and has to throw the exception you observed.

Solution:

Use a type which has such an offset or timezone information. In JSR-310 this is either OffsetDateTime (which contains an offset but not a timezone including DST-rules) or ZonedDateTime. You can watch out all supported fields of such a type by look-up on the method isSupported(TemporalField).. The field OffsetSeconds is supported in OffsetDateTime and ZonedDateTime, but not in LocalDateTime.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss.SSSSSS Z");
String s = ZonedDateTime.now().format(formatter);

How would I stop a while loop after n amount of time?

Petr Krampl's answer is the best in my opinion, but more needs to be said about the nature of loops and how to optimize the use of the system. Beginners who happen upon this thread may be further confused by the logical and algorithmic errors in the question and existing answers.

First, let's look at what your code does as you originally wrote it:

while True:
    test = 0
    if test == 5:
        break
    test = test - 1

If you say while True in a loop context, normally your intention is to stay in the loop forever. If that's not your intention, you should consider other options for the structure of the loop. Petr Krampl showed you a perfectly reasonable way to handle this that's much more clear to someone else who may read your code. In addition, it will be more clear to you several months later should you need to revisit your code to add or fix something. Well-written code is part of your documentation. There are usually multiple ways to do things, but that doesn't make all of the ways equally valid in all contexts. while true is a good example of this especially in this context.

Next, we will look at the algorithmic error in your original code. The very first thing you do in the loop is assign 0 to test. The very next thing you do is to check if the value of test is 5, which will never be the case unless you have multiple threads modifying the same memory location. Threading is not in scope for this discussion, but it's worth noting that the code could technically work, but even with multiple threads a lot would be missing, e.g. semaphores. Anyway, you will sit in this loop forever regardless of the fact that the sentinel is forcing an infinite loop.

The statement test = test - 1 is useless regardless of what it does because the variable is reset at the beginning of the next iteration of the loop. Even if you changed it to be test = 5, the loop would still be infinite because the value is reset each time. If you move the initialization statement outside the loop, then it will at least have a chance to exit. What you may have intended was something like this:

test = 0
while True:
    test = test - 1
    if test == 5:
        break

The order of the statements in the loop depends on the logic of your program. It will work in either order, though, which is the main point.

The next issue is the potential and probable logical error of starting at 0, continually subtracting 1, and then comparing with a positive number. Yes, there are occasions where this may actually be what you intend to do as long as you understand the implications, but this is most likely not what you intended. Newer versions of python will not wrap around when you reach the 'bottom' of the range of an integer like C and various other languages. It will let you continue to subtract 1 until you've filled the available memory on your system or at least what's allocated to your process. Look at the following script and the results:

test = 0

while True:
    test  -= 1

    if test % 100 == 0:
        print "Test = %d" % test

    if test == 5:
        print "Test = 5"
        break

which produces this:

Test = -100
Test = -200
Test = -300
Test = -400
...
Test = -21559000
Test = -21559100
Test = -21559200
Test = -21559300
...

The value of test will never be 5, so this loop will never exit.

To add to Petr Krampl's answer, here's a version that's probably closer to what you actually intended in addition to exiting the loop after a certain period of time:

import time

test = 0
timeout = 300   # [seconds]

timeout_start = time.time()

while time.time() < timeout_start + timeout:
    if test == 5:
        break
    test -= 1

It still won't break based on the value of test, but this is a perfectly valid loop with a reasonable initial condition. Further boundary checking could help you to avoid execution of a very long loop for no reason, e.g. check if the value of test is less than 5 upon loop entry, which would immediately break the loop.


One other thing should be mentioned that no other answer has addressed. Sometimes when you loop like this, you may not want to consume the CPU for the entire allotted time. For example, say you are checking the value of something that changes every second. If you don't introduce some kind of delay, you would use every available CPU cycle allotted to your process. That's fine if it's necessary, but good design will allow a lot of programs to run in parallel on your system without overburdening the available resources. A simple sleep statement will free up the vast majority of the CPU cycles allotted to your process so other programs can do work.

The following example isn't very useful, but it does demonstrate the concept. Let's say you want to print something every second. One way to do it would be like this:

import time

tCurrent = time.time()

while True:
    if time.time() >= tCurrent + 1:
        print "Time = %d" % time.time()
        tCurrent = time.time()

The output would be this:

Time = 1498226796
Time = 1498226797
Time = 1498226798
Time = 1498226799

And the process CPU usage would look like this:

enter image description here

That's a huge amount of CPU usage for doing basically no work. This code is much nicer to the rest of the system:

import time

tCurrent = time.time()

while True:
    time.sleep(0.25) # sleep for 250 milliseconds
    if time.time() >= tCurrent + 1:
        print "Time = %d" % time.time()
        tCurrent = time.time()

The output is the same:

Time = 1498226796
Time = 1498226797
Time = 1498226798
Time = 1498226799

and the CPU usage is way, way lower:

enter image description here